text stringlengths 14 6.51M |
|---|
unit IconTooltipUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, WComponent, WNineSlicesPanel, Logger;
type
TIconTooltipForm = class(TForm)
procedure FormCreate(Sender: TObject);
private
pLabel: TLabel;
pGap: Integer;
pBackgroundPanel: TWNineSlicesPanel;
procedure LazyInitialization();
public
procedure ShowAbove(const component:TWComponent; const text:String);
property Gap: Integer read pGap write pGap;
end;
var
IconTooltipForm: TIconTooltipForm;
implementation
{$R *.dfm}
uses Main;
procedure TIconTooltipForm.FormCreate(Sender: TObject);
begin
pGap := 4;
end;
procedure TIconTooltipForm.LazyInitialization;
var labelFont: TFont;
begin
if pBackgroundPanel = nil then begin
pBackgroundPanel := TWNineSlicesPanel.Create(Self);
pBackgroundPanel.ImagePathPrefix := TMain.Instance.FilePaths.SkinDirectory + '\TooltipBackground';
pBackgroundPanel.Visible := true;
pBackgroundPanel.Parent := Self;
end;
if pLabel = nil then begin
pLabel := TLabel.Create(Self);
pLabel.Parent := Self;
pLabel.AutoSize := true;
pLabel.Visible := true;
labelFont := TFont.Create();
labelFont.Style := TMain.Instance.Style.IconTooltip.FontStyles;
labelFont.Color := TMain.Instance.Style.IconTooltip.FontColor;
pLabel.Font := labelFont;
end;
end;
procedure TIconTooltipForm.ShowAbove(const component: TWComponent; const text: String);
var point: TPoint;
begin
if component.Parent = nil then Exit;
LazyInitialization();
pLabel.Caption := text;
Width := pLabel.Width + TMain.Instance.Style.IconTooltip.paddingH;
Height := pLabel.Height + TMain.Instance.Style.IconTooltip.paddingV;
pBackgroundPanel.Width := Width;
pBackgroundPanel.Height := Height;
pLabel.Left := TMain.Instance.Style.IconTooltip.paddingLeft;
pLabel.Top := TMain.Instance.Style.IconTooltip.paddingTop;
Left := Round(component.ScreenLeft + component.Width / 2 - Width / 2);
Top := component.ScreenTop - Height - pGap;
Repaint();
Show();
end;
end.
|
{
Report records that have internal FormID index greater than the number of plugin's masters.
}
unit ReportUnclampedFormIDs;
function Process(e: IInterface): Integer;
var
idx: integer;
begin
idx := GetElementNativeValues(e, 'Record Header\FormID') shr 24;
if idx > MasterCount(GetFile(e)) then
AddMessage(Format('[%s] Unclamped FormID index of %s for %s', [GetFileName(e), IntToHex(idx, 2), Name(e)]));
end;
end. |
{**
Remote Procedure Call (RPC) helper unit.
}
unit BinkyBoinkRPCUnit;
{$mode objfpc}{$H+}
{$I blinkyboink.inc}
interface
uses
Classes, SysUtils, BlckSock;
type
TBinkyBoinkGUIRequest = class;
TBinkyBoinkGUIResult = class;
{**
Object.TBinkyBoinkRPC
RPC Helper object
}
TBinkyBoinkRPC = class
private
FHost,
FPort: String;
FSockect: TTCPBlockSocket;
FRequest: TBinkyBoinkGUIRequest;
FResult: TBinkyBoinkGUIResult;
protected
public
constructor Create;
destructor Destroy; override;
function Get(aContent: String): String;
published
{** Host/IP of the target machine }
property Host: String read FHost write FHost;
{** Port of the target machine; defaulted to 31416 }
property Port: String read FPort write FPort;
{** Request object }
property Request: TBinkyBoinkGUIRequest read FRequest;
{** Result object }
property Result: TBinkyBoinkGUIResult read FResult;
end;
{**
Object.TBinkyBoinkGUIRequest
RPC Request Object
}
TBinkyBoinkGUIRequest = class
private
FContent: String;
protected
public
constructor Create;
published
{** Holds the XML content that will be sent to BOINC }
property Content: String read FContent write FContent;
end;
{**
Object.TBinkyBoinkGUIResult
RPC Result Object
}
TBinkyBoinkGUIResult = class
private
FContent: String;
protected
public
constructor Create;
published
{** Holds the XML content returned from BOINC }
property Content: String read FContent write FContent;
end;
implementation
const
RPCWrapper = '<boinc_gui_rpc_request>'#13'%s</boinc_gui_rpc_request>'#13#13;
{**
Object.TBinkyBoinkRPC.Create
RPC helper object creator
}
constructor TBinkyBoinkRPC.Create;
begin
inherited Create;
FHost:= 'localhost';
FPort:= '31416';
FRequest:= TBinkyBoinkGUIRequest.Create;
FResult:= TBinkyBoinkGUIResult.Create;
FSockect:= TTCPBlockSocket.Create;
end;
{**
Object.TBinkyBoinkRPC.Destroy
RPC helper object destructor
}
destructor TBinkyBoinkRPC.Destroy;
begin
FreeAndNil(FRequest);
FreeAndNil(FResult);
FreeAndNil(FSockect);
inherited Destroy;
end;
{**
Object.TBinkyBoinkRPC.Get
RPC Call with content
}
function TBinkyBoinkRPC.Get(aContent: String): String;
var
OneByte: Byte;
begin
FRequest.Content:= Format(RPCWrapper, [aContent]);
try
FSockect.Connect(FSockect.ResolveIPToName(FHost), FPort);
FSockect.SendString(FRequest.Content);
if FSockect.CanRead(100) then
begin
OneByte:= FSockect.RecvByte(100);
repeat
FResult.Content := FResult.Content + chr(OneByte);
OneByte:= FSockect.RecvByte(100);
until OneByte=3;
end;
finally
Result:= FResult.Content;
end;
end;
{**
Object.TBinkyBoinkGUIRequest.Create
RPC Request helper object constructor
}
constructor TBinkyBoinkGUIRequest.Create;
begin
FContent:= '';
end;
{**
Object.TBinkyBoinkGUIResult.Create
RPC Result helper object constructor
}
constructor TBinkyBoinkGUIResult.Create;
begin
FContent:= '';
end;
initialization
finalization
end.
|
unit roGraph;
interface
uses
Windows, Graphics, Classes, Types, Math, Forms, Controls;
procedure FillDC(DC: HDC; const aRect: TRect; const Color: TColor);
procedure FillDCBorder(const DC: HDC; const aRect: TRect; const wl, wt, wr, wb
: integer; const Color: TColor);
procedure BitBltBorder(const DestDC: HDC; const X, Y, Width, Height: Integer;
const SrcDC: HDC; const XSrc, YSrc: Integer; const BorderWidth : integer);
function HeightOf(const r: TRect; CheckNegative : boolean = False): integer;
function OffsetPoint(p: TPoint; x,y : integer): TPoint;
function RectInRect(BigRect, SmallRect : TRect): boolean;
function RectIsVisible(const ParentRect, Rect : TRect): boolean;
function RectsAnd(const R1, R2 : TRect): TRect;
function RotateRect(R : TRect): TRect;
function WidthOf(const r: TRect; CheckNegative : boolean = False): integer;
{function HLStoRGB(hlsc: integer): integer;
function RGBtoHLS(rgbc: integer): integer;}
var
User32Lib: Cardinal = 0;
UpdateLayeredWindow: function (Handle: THandle; hdcDest: HDC; pptDst: PPoint; _psize: PSize;
hdcSrc: HDC; pptSrc: PPoint; crKey: COLORREF; pblend: PBLENDFUNCTION; dwFlags: DWORD): Boolean; stdcall;
SetLayeredWindowAttributes: function (Hwnd: THandle; crKey: COLORREF; bAlpha: Byte; dwFlags: DWORD): Boolean; stdcall;
implementation
var
FCheckWidth, FCheckHeight: Integer;
procedure BitBltBorder(const DestDC: HDC; const X, Y, Width, Height: Integer;
const SrcDC: HDC; const XSrc, YSrc: Integer; const BorderWidth : integer);
begin
BitBlt(DestDC, X, Y, BorderWidth, Height, SrcDC, XSrc, YSrc, SRCCOPY);
BitBlt(DestDC, X + BorderWidth, Y, Width, BorderWidth, SrcDC, XSrc + BorderWidth, YSrc, SRCCOPY);
BitBlt(DestDC, Width - BorderWidth, Y + BorderWidth, Width, Height, SrcDC, XSrc + Width - BorderWidth, YSrc + BorderWidth, SRCCOPY);
BitBlt(DestDC, X + BorderWidth, Height - BorderWidth, Width - BorderWidth, Height, SrcDC, XSrc + BorderWidth, YSrc + Height - BorderWidth, SRCCOPY);
end;
function RectIsVisible(const ParentRect, Rect : TRect): boolean;
begin
Result := (Rect.Bottom > ParentRect.Top) and
(Rect.Right > ParentRect.Left) and
(Rect.Left < ParentRect.Right) and
(Rect.Top < ParentRect.Bottom) and not IsRectEmpty(Rect);
end;
function RectInRect(BigRect, SmallRect : TRect): boolean;
begin
inc(BigRect.Bottom); inc(BigRect.Right);
Result := PtInRect(BigRect, SmallRect.TopLeft) and PtInRect(BigRect, SmallRect.BottomRight);
end;
function RotateRect(R : TRect): TRect;
var
i : integer;
begin
i := R.left;
R.left := R.top;
R.top := i;
i := R.right;
R.right := R.bottom;
R.bottom := i;
Result := R;
end;
function RectsAnd(const R1, R2 : TRect): TRect;
begin
Result.Left := max(R1.Left, R2.Left);
Result.Top := max(R1.Top, R2.Top);
Result.Right := min(R1.Right, R2.Right);
Result.Bottom := min(R1.Bottom, R2.Bottom);
end;
function OffsetPoint(p: TPoint; x,y : integer): TPoint;
begin
Result := p;
inc(Result.x, x);
inc(Result.y, y);
end;
function WidthOf(const r: TRect; CheckNegative : boolean = False): integer;
begin
Result := integer(r.Right - r.Left);
if CheckNegative and (Result < 0) then Result := 0;
end;
function HeightOf(const r: TRect; CheckNegative : boolean = False): integer;
begin
Result := integer(r.Bottom - r.Top);
if CheckNegative and (Result < 0) then Result := 0;
end;
procedure DrawColorArrow(Canvas : TCanvas; Color : TColor; R : TRect; Direction : integer);
const
aWidth = 6;
aHeight = 3;
var
x, y, Left, Top, i : integer;
begin
i := 0;
case Direction of
BF_BOTTOM : begin
Left := R.Left + (WidthOf(R) - aWidth) div 2 - 1;
Top := R.Top + (HeightOf(R) - aHeight) div 2 - 1;
for y := Top to Top + aHeight do begin
for x := i to aHeight do begin
Canvas.Pixels[Left + x, y] := Color;
Canvas.Pixels[Left + aWidth - x + 1, y] := Color;
end;
inc(i);
end;
end;
BF_RIGHT : begin
Left := R.Left + (WidthOf(R) - aHeight) div 2;
Top := R.Top + (HeightOf(R) - aWidth) div 2;
for x := Left to Left + aHeight do begin
for y := Top + i to Top + aHeight do begin
Canvas.Pixels[x, y] := Color;
Canvas.Pixels[x, y + aHeight - i] := Color;
end;
inc(i);
end;
end;
end;
end;
{$IFNDEF ACHINTS}
{$ENDIF}
procedure FillDC(DC: HDC; const aRect: TRect; const Color: TColor);
var
OldBrush, NewBrush : hBrush;
SavedDC : hdc;
begin
SavedDC := SaveDC(DC);
NewBrush := CreateSolidBrush(Cardinal(ColorToRGB(Color)));
OldBrush := SelectObject(dc, NewBrush);
try
FillRect(DC, aRect, NewBrush);
finally
SelectObject(dc, OldBrush);
DeleteObject(NewBrush);
RestoreDC(DC, SavedDC);
end;
end;
procedure FillDCBorder(const DC: HDC; const aRect: TRect; const wl, wt, wr, wb : integer; const Color: TColor);
var
OldBrush, NewBrush : hBrush;
SavedDC : hWnd;
begin
SavedDC := SaveDC(DC);
NewBrush := CreateSolidBrush(Cardinal(ColorToRGB(Color)));
OldBrush := SelectObject(dc, NewBrush);
try
FillRect(DC, Rect(aRect.Left, aRect.Top, aRect.Right, aRect.Top + wt), NewBrush);
FillRect(DC, Rect(aRect.Left, aRect.Top + wt, aRect.Left + wl, aRect.Bottom), NewBrush);
FillRect(DC, Rect(aRect.Left + wl, aRect.Bottom - wb, aRect.Right, aRect.Bottom), NewBrush);
FillRect(DC, Rect(aRect.Right - wr, aRect.Top + wt, aRect.Right, aRect.Bottom - wb), NewBrush);
finally
SelectObject(dc, OldBrush);
DeleteObject(NewBrush);
RestoreDC(DC, SavedDC);
end;
end;
function CreateBmpLike(const Bmp: TBitmap): TBitmap;
begin
Result := TBitmap.Create;
Result.Width := Bmp.Width;
Result.Height := Bmp.Height;
Result.PixelFormat := Bmp.PixelFormat
end;
end.
|
unit NewServerForm;
{
Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au)
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 HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, ValueSetEditorCore;
type
TfrmNewServer = class(TForm)
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
edtName: TEdit;
edtAddress: TEdit;
Label3: TLabel;
edtUsername: TEdit;
Label4: TLabel;
edtPassword: TEdit;
CheckBox1: TCheckBox;
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
private
FContext : TValueSetEditorContext;
FDoesSearch : boolean;
procedure SetContext(const Value: TValueSetEditorContext);
public
property Context : TValueSetEditorContext read FContext write SetContext;
Property DoesSearch : boolean read FDoesSearch write FDoesSearch;
end;
var
frmNewServer: TfrmNewServer;
implementation
{$R *.dfm}
procedure TfrmNewServer.Button1Click(Sender: TObject);
var
msg : String;
begin
screen.Cursor := crHourGlass;
Panel1.Caption := ' Checking Server';
try
Panel1.Update;
if Context.CheckServer(frmNewServer.edtAddress.Text, msg, FDoesSearch) then
ModalResult := mrOk
finally
screen.Cursor := crDefault;
Panel1.Caption := '';
end;
if ModalResult <> mrOk then
ShowMessage(msg);
end;
procedure TfrmNewServer.CheckBox1Click(Sender: TObject);
begin
if CheckBox1.Checked then
edtPassword.PasswordChar := #0
else
edtPassword.PasswordChar := '*';
end;
procedure TfrmNewServer.FormDestroy(Sender: TObject);
begin
FContext.Free;
end;
procedure TfrmNewServer.SetContext(const Value: TValueSetEditorContext);
begin
FContext.Free;
FContext := value;
end;
end.
|
{
ID: a_zaky01
PROG: fc
LANG: PASCAL
}
uses
math;
type
point=record
x,y:extended;
end;
label
closefile;
var
pi,ans:extended;
n,i,pos,start:longint;
mid,temp:point;
flag:boolean;
p,hull:array[0..10001] of point;
angle:array[1..10000] of extended;
fin,fout:text;
function distance(point1,point2:point):extended;
begin
distance:=sqrt((point1.x-point2.x)*(point1.x-point2.x)+(point1.y-point2.y)*(point1.y-point2.y));
end;
function zcross(point1,point2:point):extended;
begin
zcross:=point1.x*point2.y-point1.y*point2.x;
end;
function sub(point1,point2:point):point;
begin
sub.x:=point1.x-point2.x;
sub.y:=point1.y-point2.y;
end;
function right(p1,p2,p3:point):boolean;
var
v1,v2:point;
begin
v1:=sub(p1,p2);
v2:=sub(p2,p3);
exit(zcross(v1,v2)<0);
end;
function atan(y,x:extended):extended;
begin
if x=0 then
if y=0 then exit(0.0)
else if y>0 then exit(pi/2)
else exit(3*pi/2);
atan:=arctan(y/x);
if atan<0 then atan:=atan+pi;
if y<0 then atan:=atan+pi;
end;
procedure sort(l,r:longint);
var
i,j:longint;
mid,temp:extended;
tempp:point;
begin
i:=l;
j:=r;
mid:=angle[(l+r) div 2];
repeat
while angle[i]<mid do inc(i);
while angle[j]>mid do dec(j);
if i<=j then
begin
temp:=angle[i];
angle[i]:=angle[j];
angle[j]:=temp;
tempp:=p[i];
p[i]:=p[j];
p[j]:=tempp;
inc(i);
dec(j);
end;
until i>j;
if l<j then sort(l,j);
if i<r then sort(i,r);
end;
begin
pi:=arccos(-1); //I wonder why I cannot put it as a constant value
assign(fin,'fc.in');
assign(fout,'fc.out');
reset(fin);
rewrite(fout);
readln(fin,n);
for i:=1 to n do
with p[i] do readln(fin,x,y);
if n=1 then
begin
writeln(fout,'0.00');
goto closefile;
end;
with mid do
begin
x:=0;
y:=0;
end;
for i:=1 to n do
begin
mid.x:=mid.x+(p[i].x/n);
mid.y:=mid.y+(p[i].y/n);
end;
for i:=1 to n do angle[i]:=atan(p[i].y-mid.y,p[i].x-mid.x);
sort(1,n);
hull[1]:=p[1];
hull[2]:=p[2];
pos:=3;
for i:=3 to n-1 do
begin
while (pos>2) and right(hull[pos-2],hull[pos-1],p[i]) do dec(pos);
hull[pos]:=p[i];
inc(pos);
end;
temp:=p[n];
while (pos>2) and right(hull[pos-2],hull[pos-1],temp) do dec(pos);
start:=1;
repeat
flag:=false;
if (pos-start>=2) and right(hull[pos-1],temp,hull[start]) then
begin
temp:=hull[pos-1];
dec(pos);
flag:=true;
end;
if (pos-start>=2) and right(temp,hull[start],hull[start+1]) then
begin
inc(start);
flag:=true;
end;
until not flag;
hull[pos]:=temp;
ans:=distance(hull[start],hull[pos]);
for i:=start to pos-1 do ans:=ans+distance(hull[i],hull[i+1]);
writeln(fout,ans:0:2);
closefile:
close(fin);
close(fout);
end.
|
unit ResourceEditingSupport;
interface
uses
SysUtils,
DateSupport,
FHIRTypes, FHIRResources,
FMX.DateTimeCtrls;
function displayLang(lang : String) : string;
function displayUse(coding : TFHIRCoding) : string;
function CodeForUse(s : String) : String;
procedure presentDateTime(date : TFHIRDateTime; ded: TDateEdit; tdt: TTimeEdit);
function storeDateTime(ded: TDateEdit; tdt: TTimeEdit): TFHIRDateTime;
function getJurisdictionSearch(i: integer): string;
function readJurisdiction(res : TFhirMetadataResource): String;
function FMXescape(s : String) : String;
implementation
function displayLang(lang : String) : string;
begin
if lang = '' then
result := ''
else if lang.StartsWith('bn') then result := 'bn (Bengali)'
else if lang.startsWith('cs') then result := 'cs (Czech)'
else if lang.startsWith('da') then result := 'da (Danish)'
else if lang.startsWith('de') then result := 'de (German)'
else if lang.startsWith('el') then result := 'el (Greek)'
else if lang.startsWith('en') then result := 'en (English)'
else if lang.startsWith('es') then result := 'es (Spanish)'
else if lang.startsWith('fi') then result := 'fi (Finnish)'
else if lang.startsWith('fr') then result := 'fr (French)'
else if lang.startsWith('fy') then result := 'fy (Frysian)'
else if lang.startsWith('hi') then result := 'hi (Hindi)'
else if lang.startsWith('hr') then result := 'hr (Croatian)'
else if lang.startsWith('it') then result := 'it (Italian)'
else if lang.startsWith('ja') then result := 'ja (Japanese)'
else if lang.startsWith('ko') then result := 'ko (Korean)'
else if lang.startsWith('nl') then result := 'nl (Dutch)'
else if lang.startsWith('no') then result := 'no (Norwegian)'
else if lang.startsWith('pa') then result := 'pa (Punjabi)'
else if lang.startsWith('pt') then result := 'pt (Portuguese)'
else if lang.startsWith('ru') then result := 'ru (Russian)'
else if lang.startsWith('sr') then result := 'sr (Serbian)'
else if lang.startsWith('sv') then result := 'sv (Swedish)'
else if lang.startsWith('te') then result := 'te (Telegu)'
else if lang.startsWith('zh') then result := 'zh (Chinese))'
else
result := lang;
end;
function displayUse(coding : TFHIRCoding) : string;
begin
if (coding = nil) then
exit('');
if (coding.system = 'http://snomed.info/sct') then
begin
if coding.code = '900000000000003001' then
exit('Fully specified name');
if coding.code = '900000000000013009' then
exit('Synonym');
if coding.code = '900000000000550004' then
exit('Definition');
end;
if coding.display <> '' then
result := coding.display
else
result := '';
end;
function CodeForUse(s : String) : String;
begin
if (s = 'Fully specified name') then
result := '900000000000003001'
else if (s = 'Synonym') then
result := '900000000000013009'
else
result := '900000000000550004';
end;
procedure presentDateTime(date : TFHIRDateTime; ded: TDateEdit; tdt: TTimeEdit);
begin
if date = nil then
begin
ded.Text := '';
tdt.Text := '';
end
else
begin
ded.DateTime := trunc(date.value.DateTime);
if ded.DateTime = date.value.DateTime then
tdt.Text := ''
else
tdt.DateTime := date.value.DateTime - ded.DateTime;
end;
end;
function storeDateTime(ded: TDateEdit; tdt: TTimeEdit): TFHIRDateTime;
begin
if ded.Text = '' then
result := nil
else
result := TFhirDateTime.Create(TDateTimeEx.make(trunc(ded.DateTime) + tdt.Time, dttzLocal));
end;
function getJurisdictionSearch(i: integer): string;
begin
case i of
1:result := 'urn:iso:std:iso:3166|AT';
2:result := 'urn:iso:std:iso:3166|AU';
3:result := 'urn:iso:std:iso:3166|BR';
4:result := 'urn:iso:std:iso:3166|CA';
5:result := 'urn:iso:std:iso:3166|CH';
6:result := 'urn:iso:std:iso:3166|CL';
7:result := 'urn:iso:std:iso:3166|CN';
8:result := 'urn:iso:std:iso:3166|DE';
9:result := 'urn:iso:std:iso:3166|DK';
10:result := 'urn:iso:std:iso:3166|EE';
11:result := 'urn:iso:std:iso:3166|ES';
12:result := 'urn:iso:std:iso:3166|FI';
13:result := 'urn:iso:std:iso:3166|FR';
14:result := 'urn:iso:std:iso:3166|GB';
15:result := 'urn:iso:std:iso:3166|NL';
16:result := 'urn:iso:std:iso:3166|NO';
17:result := 'urn:iso:std:iso:3166|NZ';
18:result := 'urn:iso:std:iso:3166|RU';
19:result := 'urn:iso:std:iso:3166|US';
21:result := 'urn:iso:std:iso:3166|VN';
22:result := 'http://unstats.un.org/unsd/methods/m49/m49.htm|001';
23:result := 'http://unstats.un.org/unsd/methods/m49/m49.htm|002';
24:result := 'http://unstats.un.org/unsd/methods/m49/m49.htm|019';
25:result := 'http://unstats.un.org/unsd/methods/m49/m49.htm|142';
26:result := 'http://unstats.un.org/unsd/methods/m49/m49.htm|150';
27:result := 'http://unstats.un.org/unsd/methods/m49/m49.htm|053';
else
result := '';
end;
end;
function readJurisdiction(res : TFhirMetadataResource): String;
var
cc : TFhirCodeableConcept;
c : TFhirCoding;
begin
result := '';
for cc in res.jurisdictionList do
for c in cc.codingList do
begin
if c.system = 'urn:iso:std:iso:3166' then
begin
if c.code = 'AT' then exit('Austraia');
if c.code = 'AU' then exit('Australia');
if c.code = 'BR' then exit('Brazil');
if c.code = 'CA' then exit('Canada');
if c.code = 'CH' then exit('Switzerland');
if c.code = 'CL' then exit('Chile');
if c.code = 'CN' then exit('China');
if c.code = 'DE' then exit('Germany');
if c.code = 'DK' then exit('Denmark');
if c.code = 'EE' then exit('Estonia');
if c.code = 'ES' then exit('Spain');
if c.code = 'FI' then exit('Finland');
if c.code = 'FR' then exit('France');
if c.code = 'GB' then exit('UK');
if c.code = 'NL' then exit('Netherlands');
if c.code = 'NO' then exit('Norway');
if c.code = 'NZ' then exit('NZ');
if c.code = 'RU' then exit('Russia');
if c.code = 'US' then exit('USA');
if c.code = 'VN' then exit('Vietnam');
end
else if c.system = 'http://unstats.un.org/unsd/methods/m49/m49.htm' then
begin
if c.code = '001' { World } then exit('World');
if c.code = '002' { Africa } then exit('Africa');
if c.code = '019' { Americas } then exit('Americas');
if c.code = '142' { Asia } then exit('Asia');
if c.code = '150' { Europe } then exit('Europe');
if c.code = '053' { Australia and New Zealand } then exit('Australasia');
end
end;
end;
function FMXescape(s : String) : String;
begin
result := s.replace('&', '&&');
end;
end.
|
unit MongoAPI;
interface
{$I MongoC_defines.inc}
uses
Windows, SysUtils;
const
MongoC_DllVersion = '1-0-1'; (* PLEASE!!! maintain this constant in sync with the dll driver version this code operates with *)
CPUType = {$IFDEF WIN64} '64' {$ELSE} '32' {$ENDIF};
ConfigType = {$IFDEF DEBUG} 'd' {$ELSE} 'r' {$ENDIF};
Default_MongoCDLL = 'mongoc_' + ConfigType + CPUType + '_v' + MongoC_DllVersion + '.dll';
type
{$IFNDEF DELPHI2007}
UTF8String = AnsiString;
UInt64 = Int64;
{$ENDIF}
{$IFNDEF DELPHIXE}
NativeUInt = Cardinal;
{$ENDIF}
PBsonOIDValue = ^TBsonOIDValue;
TBsonOIDValue = array[0..11] of Byte;
EMongoFatalError = class(Exception);
{$IFDEF VER130}
PPAnsiChar = ^PAnsiChar;
{$ENDIF}
{ A value of TBsonType indicates the type of the data associated
with a field within a BSON document. }
TBsonType = (bsonEOO, // 0
bsonDOUBLE, // 1
bsonSTRING, // 2
bsonOBJECT, // 3
bsonARRAY, // 4
bsonBINDATA, // 5
bsonUNDEFINED, // 6
bsonOID, // 7
bsonBOOL, // 8
bsonDATE, // 9
bsonNULL, // 10
bsonREGEX, // 11
bsonDBREF, (* Deprecated. 12 *)
bsonCODE, // 13
bsonSYMBOL, // 14
bsonCODEWSCOPE, // 15
bsonINT, // 16
bsonTIMESTAMP, // 17
bsonLONG); // 18
type
TMongoInterfacedObject = class(TInterfacedObject)
public
constructor Create;
destructor Destroy; override;
end;
type
TMongoObject = class(TObject)
public
constructor Create;
destructor Destroy; override;
end;
{$IFDEF OnDemandMongoCLoad}
type
// MongoDB declarations
Tset_mem_alloc_functions = procedure (custom_bson_malloc_func,
custom_bson_realloc_func,
custom_bson_free_func : Pointer); cdecl;
Tmongo_env_sock_init = function : integer; cdecl;
Tmongo_alloc = function : Pointer; cdecl;
Tmongo_dealloc = procedure (c: Pointer); cdecl;
Tmongo_client = function (c: Pointer; host: PAnsiChar; port: Integer): Integer; cdecl;
Tmongo_destroy = procedure(c: Pointer); cdecl;
Tmongo_replica_set_init = procedure (c: Pointer; Name: PAnsiChar); cdecl;
Tmongo_replica_set_add_seed = procedure (c: Pointer; host: PAnsiChar; port: Integer); cdecl;
Tmongo_replica_set_client = function(c: Pointer): Integer; cdecl;
Tmongo_is_connected = function (c: Pointer): LongBool; cdecl;
Tmongo_get_err = function(c: Pointer): Integer; cdecl;
Tmongo_set_op_timeout = function (c: Pointer; millis: Integer): Integer; cdecl;
Tmongo_get_op_timeout = function (c: Pointer): Integer; cdecl;
Tmongo_get_primary = function (c: Pointer): PAnsiChar; cdecl;
Tmongo_check_connection = function (c: Pointer): Integer; cdecl;
Tmongo_disconnect = procedure (c: Pointer); cdecl;
Tmongo_reconnect = function (c: Pointer): Integer; cdecl;
Tmongo_cmd_ismaster = function (c: Pointer; b: Pointer): Longbool; cdecl;
Tmongo_get_socket = function (c: Pointer): Pointer; cdecl;
Tmongo_get_host_count = function (c: Pointer): Integer; cdecl;
Tmongo_get_host = function (c: Pointer; i: Integer): PAnsiChar; cdecl;
Tmongo_insert = function (c: Pointer; ns: PAnsiChar; b: Pointer; wc: Pointer): Integer; cdecl;
Tmongo_insert_batch = function (c: Pointer; ns: PAnsiChar; bsons: Pointer; Count: Integer; wc: Pointer; flags: Integer): Integer; cdecl;
Tmongo_update = function (c: Pointer; ns: PAnsiChar; cond: Pointer; op: Pointer; flags: Integer; wc: Pointer): Integer; cdecl;
Tmongo_remove = function (c: Pointer; ns: PAnsiChar; criteria: Pointer; wc: Pointer): Integer; cdecl;
Tmongo_find_one = function (c: Pointer; ns: PAnsiChar; query: Pointer; fields: Pointer; Result: Pointer): Integer; cdecl;
Tbson_alloc = function : Pointer; cdecl;
Tbson_dealloc = procedure (b: Pointer); cdecl;
Tbson_copy = procedure (dest: Pointer; src: Pointer); cdecl;
Tmongo_cursor_alloc = function : Pointer; cdecl;
Tmongo_cursor_dealloc = procedure (Cursor: Pointer); cdecl;
Tmongo_cursor_destroy = procedure (Cursor: Pointer); cdecl;
Tmongo_find = function (c: Pointer; ns: PAnsiChar; query: Pointer; fields: Pointer; limit, skip, options: Integer): Pointer; cdecl;
Tmongo_cursor_next = function (Cursor: Pointer): Integer; cdecl;
Tmongo_cursor_bson = function (Cursor: Pointer): Pointer; cdecl;
Tmongo_cmd_drop_collection = function (c: Pointer; db: PAnsiChar; collection: PAnsiChar; Result: Pointer): Integer; cdecl;
Tmongo_cmd_drop_db = function (c: Pointer; db: PAnsiChar): Integer; cdecl;
Tmongo_count = function (c: Pointer; db: PAnsiChar; collection: PAnsiChar; query: Pointer): Double; cdecl;
Tmongo_create_index = function (c: Pointer; ns: PAnsiChar; key: Pointer; name : PAnsiChar; options: Integer; ttl : integer; res: Pointer): Integer; cdecl;
Tmongo_cmd_add_user = function (c: Pointer; db: PAnsiChar; Name: PAnsiChar; password: PAnsiChar): Integer; cdecl;
Tmongo_cmd_create_user = function (c: Pointer; db: PAnsiChar; Name: PAnsiChar; password: PAnsiChar; roles : PPAnsiChar): Integer; cdecl;
Tmongo_cmd_authenticate = function (c: Pointer; db: PAnsiChar; Name: PAnsiChar; password: PAnsiChar): Integer; cdecl;
Tmongo_run_command = function (c: Pointer; db: PAnsiChar; command: Pointer; res: Pointer): Integer; cdecl;
Tmongo_cmd_get_last_error = function (c: Pointer; db: PAnsiChar; res: Pointer): Integer; cdecl;
Tmongo_cmd_get_prev_error = function (c: Pointer; db: PAnsiChar; res: Pointer): Integer; cdecl;
Tmongo_cmd_reset_error = procedure(c : Pointer; db : PAnsiChar); cdecl;
Tmongo_get_server_err = function (c: Pointer): Integer; cdecl;
Tmongo_get_server_err_string = function (c: Pointer): PAnsiChar; cdecl;
// WriteConcern API
Tmongo_write_concern_alloc = function : Pointer; cdecl;
Tmongo_write_concern_dealloc = procedure (write_concern : Pointer); cdecl;
Tmongo_write_concern_init = procedure(write_concern : pointer); cdecl;
Tmongo_write_concern_finish = function(write_concern : pointer) : integer; cdecl;
Tmongo_write_concern_destroy = procedure(write_concern : pointer); cdecl;
Tmongo_set_write_concern = procedure(conn : pointer; write_concern : pointer); cdecl;
Tmongo_write_concern_get_w = function (write_concern : Pointer) : integer; cdecl;
Tmongo_write_concern_get_wtimeout = function(write_concern : Pointer) : integer; cdecl;
Tmongo_write_concern_get_j = function(write_concern : Pointer) : integer; cdecl;
Tmongo_write_concern_get_fsync = function(write_concern : Pointer) : integer; cdecl;
Tmongo_write_concern_get_mode = function(write_concern : Pointer) : PAnsiChar; cdecl;
Tmongo_write_concern_get_cmd = function(write_concern : Pointer) : Pointer; cdecl;
Tmongo_write_concern_set_w = procedure(write_concern : Pointer; w : integer); cdecl;
Tmongo_write_concern_set_wtimeout = procedure(write_concern : Pointer; wtimeout : integer); cdecl;
Tmongo_write_concern_set_j = procedure(write_concern : Pointer; j : integer); cdecl;
Tmongo_write_concern_set_fsync = procedure(write_concern : Pointer; fsync : integer); cdecl;
Tmongo_write_concern_set_mode = procedure(write_concern : Pointer; mode : PAnsiChar); cdecl;
// MongoBSON declarations
Tbson_free = procedure (b : pointer); cdecl;
Tbson_init = function (b: Pointer) : integer; cdecl;
Tbson_init_finished_data = function (b : Pointer; data : PAnsiChar; ownsData : LongBool) : integer; cdecl;
Tbson_init_empty = function (b : Pointer) : integer; cdecl;
Tbson_destroy = procedure (b: Pointer); cdecl;
Tbson_finish = function (b: Pointer): Integer; cdecl;
Tbson_data = function( b : Pointer ) : Pointer; cdecl;
Tbson_print = procedure (b: Pointer); cdecl;
Tbson_oid_gen = procedure (oid: Pointer); cdecl;
Tbson_set_oid_inc = procedure (proc : pointer); cdecl;
Tbson_set_oid_fuzz = procedure (proc : pointer); cdecl;
Tbson_oid_to_string = procedure (oid: Pointer; s: PAnsiChar); cdecl;
Tbson_oid_from_string = procedure (oid: Pointer; s: PAnsiChar); cdecl;
Tbson_append_string = function (b: Pointer; Name: PAnsiChar; Value: PAnsiChar): Integer; cdecl;
Tbson_append_string_n = function (b: Pointer; Name: PAnsiChar; Value: PAnsiChar; Len : NativeUInt): Integer; cdecl;
Tbson_append_code = function (b: Pointer; Name: PAnsiChar; Value: PAnsiChar): Integer; cdecl;
Tbson_append_code_n = function (b: Pointer; Name: PAnsiChar; Value: PAnsiChar; Len : NativeUInt): Integer; cdecl;
Tbson_append_symbol = function (b: Pointer; Name: PAnsiChar; Value: PAnsiChar): Integer; cdecl;
Tbson_append_symbol_n = function (b: Pointer; Name: PAnsiChar; Value: PAnsiChar; Len : NativeUInt): Integer; cdecl;
Tbson_append_int = function (b: Pointer; Name: PAnsiChar; Value: Integer): Integer; cdecl;
Tbson_append_long = function (b: Pointer; Name: PAnsiChar; Value: Int64): Integer; cdecl;
Tbson_append_double = function (b: Pointer; Name: PAnsiChar; Value: Double): Integer; cdecl;
Tbson_append_date = function (b: Pointer; Name: PAnsiChar; Value: Int64): Integer; cdecl;
Tbson_append_bool = function (b: Pointer; Name: PAnsiChar; Value: LongBool): Integer; cdecl;
Tbson_append_null = function (b: Pointer; Name: PAnsiChar): Integer; cdecl;
Tbson_append_undefined = function (b: Pointer; Name: PAnsiChar): Integer; cdecl;
Tbson_append_start_object = function (b: Pointer; Name: PAnsiChar): Integer; cdecl;
Tbson_append_start_array = function (b: Pointer; Name: PAnsiChar): Integer; cdecl;
Tbson_append_finish_object = function (b: Pointer): Integer; cdecl;
Tbson_append_oid = function (b: Pointer; Name: PAnsiChar; oid: Pointer): Integer; cdecl;
Tbson_append_code_w_scope = function (b: Pointer; Name: PAnsiChar; code: PAnsiChar; scope: Pointer): Integer; cdecl;
Tbson_append_regex = function (b: Pointer; Name: PAnsiChar; pattern: PAnsiChar; options: PAnsiChar): Integer; cdecl;
Tbson_append_timestamp2 = function (b: Pointer; Name: PAnsiChar; Time: Integer; increment: Integer): Integer; cdecl;
Tbson_append_binary = function (b: Pointer; Name: PAnsiChar; Kind: Byte; Data: Pointer; Len: NativeUInt): Integer; cdecl;
Tbson_append_bson = function (b: Pointer; Name: PAnsiChar; Value: Pointer): Integer; cdecl;
Tbson_buffer_size = function (b: Pointer): NativeUInt; cdecl;
Tbson_size = function (b: Pointer): Integer; cdecl;
Tbson_iterator_alloc = function (): Pointer; cdecl;
Tbson_iterator_dealloc = procedure (i: Pointer); cdecl;
Tbson_iterator_init = procedure (i: Pointer; b: Pointer); cdecl;
Tbson_find = function (i: Pointer; b: Pointer; Name: PAnsiChar): TBsonType; cdecl;
Tbson_iterator_type = function (i: Pointer): TBsonType; cdecl;
Tbson_iterator_next = function (i: Pointer): TBsonType; cdecl;
Tbson_iterator_key = function (i: Pointer): PAnsiChar; cdecl;
Tbson_iterator_double = function (i: Pointer): Double; cdecl;
Tbson_iterator_long = function (i: Pointer): Int64; cdecl;
Tbson_iterator_int = function (i: Pointer): Integer; cdecl;
Tbson_iterator_bool = function (i: Pointer): LongBool; cdecl;
Tbson_iterator_string = function (i: Pointer): PAnsiChar; cdecl;
Tbson_iterator_date = function (i: Pointer): Int64; cdecl;
Tbson_iterator_subiterator = procedure (i: Pointer; sub: Pointer); cdecl;
Tbson_iterator_oid = function (i: Pointer): Pointer; cdecl;
Tbson_iterator_code = function (i: Pointer): PAnsiChar; cdecl;
Tbson_iterator_code_scope_init = procedure (i: Pointer; b: Pointer); cdecl;
Tbson_iterator_regex = function (i: Pointer): PAnsiChar; cdecl;
Tbson_iterator_regex_opts = function (i: Pointer): PAnsiChar; cdecl;
Tbson_iterator_timestamp_time = function (i: Pointer): Integer; cdecl;
Tbson_iterator_timestamp_increment = function (i: Pointer): Integer; cdecl;
Tbson_iterator_bin_len = function (i: Pointer): Integer; cdecl;
Tbson_iterator_bin_type = function (i: Pointer): Byte; cdecl;
Tbson_iterator_bin_data = function (i: Pointer): Pointer; cdecl;
TInt64toDouble = function (i64: Int64): Double; cdecl;
Tset_bson_err_handler = function(newErrorHandler : Pointer) : Pointer; cdecl;
// GridFS declarations
Tgridfs_alloc = function : Pointer; cdecl;
Tgridfs_dealloc = procedure (g: Pointer); cdecl;
Tgridfs_init = function (c: Pointer; db: PAnsiChar; prefix: PAnsiChar; g: Pointer): Integer; cdecl;
Tgridfs_destroy = procedure (g: Pointer); cdecl;
Tgridfs_store_file = function (g: Pointer; FileName: PAnsiChar; remoteName: PAnsiChar; contentType: PAnsiChar; Flags : Integer): Integer; cdecl;
Tgridfs_remove_filename = procedure (g: Pointer; remoteName: PAnsiChar); cdecl;
Tgridfs_store_buffer = function (g: Pointer; p: Pointer; size: UInt64; remoteName: PAnsiChar; contentType: PAnsiChar; Flags : Integer): Integer; cdecl;
Tgridfile_create = function : Pointer; cdecl;
Tgridfile_dealloc = procedure (gf: Pointer); cdecl;
Tgridfile_writer_init = procedure (gf: Pointer; gfs: Pointer; remoteName: PAnsiChar; contentType: PAnsiChar; Flags : Integer); cdecl;
Tgridfile_write_buffer = function (gf: Pointer; Data: Pointer; Length: UInt64) : UInt64; cdecl;
Tgridfile_writer_done = function (gf: Pointer): Integer; cdecl;
Tgridfs_find_query = function (g: Pointer; query: Pointer; gf: Pointer): Integer; cdecl;
Tgridfile_set_filter_context = procedure( gfile, context : Pointer); cdecl;
Tgridfile_destroy = procedure (gf: Pointer); cdecl;
Tgridfile_get_filename = function (gf: Pointer): PAnsiChar; cdecl;
Tgridfile_get_chunksize = function (gf: Pointer): Integer; cdecl;
Tgridfile_get_contentlength = function (gf: Pointer): UInt64; cdecl;
Tgridfile_get_contenttype = function (gf: Pointer): PAnsiChar; cdecl;
Tgridfile_get_uploaddate = function (gf: Pointer): Int64; cdecl;
Tgridfile_get_md5 = function (gf: Pointer): PAnsiChar; cdecl;
Tgridfile_get_metadata = procedure (gf: Pointer; b: Pointer; copyData : LongBool); cdecl;
Tgridfile_get_numchunks = function (gf: Pointer): Integer; cdecl;
Tgridfile_get_descriptor = procedure (gf: Pointer; b: Pointer); cdecl;
Tgridfile_get_chunk = procedure (gf: Pointer; i: Integer; b: Pointer); cdecl;
Tgridfile_get_chunks = function (gf: Pointer; i: NativeUInt; Count: NativeUInt): Pointer; cdecl;
Tgridfile_read_buffer = function (gf: Pointer; buf: Pointer; size: UInt64): UInt64; cdecl;
Tgridfile_seek = function (gf: Pointer; offset: UInt64): UInt64; cdecl;
Tgridfile_init = function (gfs, meta, gfile : pointer) : integer; cdecl;
Tgridfile_get_id = function (gfile : pointer) : TBsonOIDValue; cdecl;
Tgridfile_truncate = function (gfile : Pointer; newSize : UInt64) : UInt64; cdecl;
Tgridfile_expand = function (gfile : Pointer; bytesToExpand : UInt64) : UInt64; cdecl;
Tgridfile_set_size = function(gfile : Pointer; newSize : UInt64) : UInt64; cdecl;
Tgridfs_get_caseInsensitive = function (gf : Pointer) : LongBool; cdecl;
Tgridfs_set_caseInsensitive = procedure (gf : Pointer; newValue : LongBool); cdecl;
Tgridfile_set_flags = procedure(gf : Pointer; Flags : Integer); cdecl;
Tgridfile_get_flags = function(gf : Pointer) : Integer; cdecl;
// ZLib and AES encryption extensions
Tinit_ZLib_AES_filtering = function (flags : integer) : integer; cdecl;
Tcreate_ZLib_AES_filter_context = function (flags : integer) : Pointer; cdecl;
Tdestroy_ZLib_AES_filter_context = procedure (context : Pointer; flags : integer); cdecl;
TZLib_AES_filter_context_set_encryption_key = function( context : Pointer; Passphrase : PAnsiChar; bits : integer ) : integer; cdecl;
var
HMongoDBDll : HMODULE;
// MongoDB declarations
set_mem_alloc_functions : Tset_mem_alloc_functions;
mongo_env_sock_init : Tmongo_env_sock_init;
mongo_alloc : Tmongo_alloc;
mongo_dealloc : Tmongo_dealloc;
mongo_client : Tmongo_client;
mongo_destroy : Tmongo_destroy;
mongo_replica_set_init : Tmongo_replica_set_init;
mongo_replica_set_add_seed : Tmongo_replica_set_add_seed;
mongo_replica_set_client : Tmongo_replica_set_client;
mongo_is_connected : Tmongo_is_connected;
mongo_get_err : Tmongo_get_err;
mongo_set_op_timeout : Tmongo_set_op_timeout;
mongo_get_op_timeout : Tmongo_get_op_timeout;
mongo_get_primary : Tmongo_get_primary;
mongo_check_connection : Tmongo_check_connection;
mongo_disconnect : Tmongo_disconnect;
mongo_reconnect : Tmongo_reconnect;
mongo_cmd_ismaster : Tmongo_cmd_ismaster;
mongo_get_socket : Tmongo_get_socket;
mongo_get_host_count : Tmongo_get_host_count;
mongo_get_host : Tmongo_get_host;
mongo_insert : Tmongo_insert;
mongo_insert_batch : Tmongo_insert_batch;
mongo_update : Tmongo_update;
mongo_remove : Tmongo_remove;
mongo_find_one : Tmongo_find_one;
bson_alloc : Tbson_alloc;
bson_dealloc : Tbson_dealloc;
bson_copy : Tbson_copy;
mongo_cursor_alloc : Tmongo_cursor_alloc;
mongo_cursor_dealloc : Tmongo_cursor_dealloc;
mongo_cursor_destroy : Tmongo_cursor_destroy;
mongo_find : Tmongo_find;
mongo_cursor_next : Tmongo_cursor_next;
mongo_cursor_bson : Tmongo_cursor_bson;
mongo_cmd_drop_collection : Tmongo_cmd_drop_collection;
mongo_cmd_drop_db : Tmongo_cmd_drop_db;
mongo_count : Tmongo_count;
mongo_create_index : Tmongo_create_index;
mongo_cmd_add_user : Tmongo_cmd_add_user;
mongo_cmd_create_user : Tmongo_cmd_create_user;
mongo_cmd_authenticate : Tmongo_cmd_authenticate;
mongo_run_command : Tmongo_run_command;
mongo_cmd_get_last_error : Tmongo_cmd_get_last_error;
mongo_cmd_get_prev_error : Tmongo_cmd_get_prev_error;
mongo_cmd_reset_error : Tmongo_cmd_reset_error;
mongo_get_server_err : Tmongo_get_server_err;
mongo_get_server_err_string : Tmongo_get_server_err_string;
// WriteConcern API
mongo_write_concern_alloc : Tmongo_write_concern_alloc;
mongo_write_concern_dealloc : Tmongo_write_concern_dealloc;
mongo_write_concern_init : Tmongo_write_concern_init;
mongo_write_concern_finish : Tmongo_write_concern_finish;
mongo_write_concern_destroy : Tmongo_write_concern_destroy;
mongo_set_write_concern : Tmongo_set_write_concern;
mongo_write_concern_get_w : Tmongo_write_concern_get_w;
mongo_write_concern_get_wtimeout : Tmongo_write_concern_get_wtimeout;
mongo_write_concern_get_j : Tmongo_write_concern_get_j;
mongo_write_concern_get_fsync : Tmongo_write_concern_get_fsync;
mongo_write_concern_get_mode : Tmongo_write_concern_get_mode;
mongo_write_concern_get_cmd : Tmongo_write_concern_get_cmd;
mongo_write_concern_set_w : Tmongo_write_concern_set_w;
mongo_write_concern_set_wtimeout : Tmongo_write_concern_set_wtimeout;
mongo_write_concern_set_j : Tmongo_write_concern_set_j;
mongo_write_concern_set_fsync : Tmongo_write_concern_set_fsync;
mongo_write_concern_set_mode : Tmongo_write_concern_set_mode;
// MongoBson declarations
bson_free : Tbson_free;
bson_init : Tbson_init;
bson_init_finished_data : Tbson_init_finished_data;
bson_init_empty : Tbson_init_empty;
bson_destroy : Tbson_destroy;
bson_finish : Tbson_finish;
bson_print : Tbson_print;
bson_data : Tbson_data;
bson_oid_gen : Tbson_oid_gen;
bson_set_oid_inc : Tbson_set_oid_inc;
bson_set_oid_fuzz : Tbson_set_oid_fuzz;
bson_oid_to_string : Tbson_oid_to_string;
bson_oid_from_string : Tbson_oid_from_string;
bson_append_string : Tbson_append_string;
bson_append_string_n : Tbson_append_string_n;
bson_append_code : Tbson_append_code;
bson_append_code_n : Tbson_append_code_n;
bson_append_symbol : Tbson_append_symbol;
bson_append_symbol_n : Tbson_append_symbol_n;
bson_append_int : Tbson_append_int;
bson_append_long : Tbson_append_long;
bson_append_double : Tbson_append_double;
bson_append_date : Tbson_append_date;
bson_append_bool : Tbson_append_bool;
bson_append_null : Tbson_append_null;
bson_append_undefined : Tbson_append_undefined;
bson_append_start_object : Tbson_append_start_object;
bson_append_start_array : Tbson_append_start_array;
bson_append_finish_object : Tbson_append_finish_object;
bson_append_oid : Tbson_append_oid;
bson_append_code_w_scope : Tbson_append_code_w_scope;
bson_append_regex : Tbson_append_regex;
bson_append_timestamp2 : Tbson_append_timestamp2;
bson_append_binary : Tbson_append_binary;
bson_append_bson : Tbson_append_bson;
bson_buffer_size : Tbson_buffer_size;
bson_size : Tbson_size;
bson_iterator_alloc : Tbson_iterator_alloc;
bson_iterator_dealloc : Tbson_iterator_dealloc;
bson_iterator_init : Tbson_iterator_init;
bson_find : Tbson_find;
bson_iterator_type : Tbson_iterator_type;
bson_iterator_next : Tbson_iterator_next;
bson_iterator_key : Tbson_iterator_key;
bson_iterator_double : Tbson_iterator_double;
bson_iterator_long : Tbson_iterator_long;
bson_iterator_int : Tbson_iterator_int;
bson_iterator_bool : Tbson_iterator_bool;
bson_iterator_string : Tbson_iterator_string;
bson_iterator_date: Tbson_iterator_date;
bson_iterator_subiterator : Tbson_iterator_subiterator;
bson_iterator_oid : Tbson_iterator_oid;
bson_iterator_code : Tbson_iterator_code;
bson_iterator_code_scope_init : Tbson_iterator_code_scope_init;
bson_iterator_regex : Tbson_iterator_regex;
bson_iterator_regex_opts : Tbson_iterator_regex_opts;
bson_iterator_timestamp_time : Tbson_iterator_timestamp_time;
bson_iterator_timestamp_increment : Tbson_iterator_timestamp_increment;
bson_iterator_bin_len : Tbson_iterator_bin_len;
bson_iterator_bin_type : Tbson_iterator_bin_type;
bson_iterator_bin_data : Tbson_iterator_bin_data;
set_bson_err_handler : Tset_bson_err_handler;
// GridFS declarations
gridfs_alloc : Tgridfs_alloc;
gridfs_dealloc : Tgridfs_dealloc;
gridfs_init : Tgridfs_init;
gridfs_destroy : Tgridfs_destroy;
gridfs_store_file : Tgridfs_store_file;
gridfs_remove_filename : Tgridfs_remove_filename;
gridfs_store_buffer : Tgridfs_store_buffer;
gridfile_create : Tgridfile_create;
gridfile_dealloc : Tgridfile_dealloc;
gridfile_writer_init : Tgridfile_writer_init;
gridfile_write_buffer : Tgridfile_write_buffer;
gridfile_writer_done : Tgridfile_writer_done;
gridfs_find_query : Tgridfs_find_query;
gridfile_set_filter_context : Tgridfile_set_filter_context;
gridfile_destroy : Tgridfile_destroy;
gridfile_get_filename : Tgridfile_get_filename;
gridfile_get_chunksize : Tgridfile_get_chunksize;
gridfile_get_contentlength : Tgridfile_get_contentlength;
gridfile_get_contenttype: Tgridfile_get_contenttype;
gridfile_get_uploaddate : Tgridfile_get_uploaddate;
gridfile_get_md5 : Tgridfile_get_md5;
gridfile_get_metadata : Tgridfile_get_metadata;
gridfile_get_numchunks : Tgridfile_get_numchunks;
gridfile_get_descriptor : Tgridfile_get_descriptor;
gridfile_get_chunk: Tgridfile_get_chunk;
gridfile_get_chunks : Tgridfile_get_chunks;
gridfile_read_buffer : Tgridfile_read_buffer;
gridfile_seek : Tgridfile_seek;
gridfile_init : Tgridfile_init;
gridfile_get_id : Tgridfile_get_id;
gridfile_truncate : Tgridfile_truncate;
gridfile_expand : Tgridfile_expand;
gridfile_set_size : Tgridfile_set_size;
gridfs_get_caseInsensitive : Tgridfs_get_caseInsensitive;
gridfs_set_caseInsensitive : Tgridfs_set_caseInsensitive;
gridfile_set_flags : Tgridfile_set_flags;
gridfile_get_flags : Tgridfile_get_flags;
// ZLib and AES extensions
init_ZLib_AES_filtering : Tinit_ZLib_AES_filtering;
create_ZLib_AES_filter_context : Tcreate_ZLib_AES_filter_context;
destroy_ZLib_AES_filter_context : Tdestroy_ZLib_AES_filter_context;
ZLib_AES_filter_context_set_encryption_key : TZLib_AES_filter_context_set_encryption_key;
Int64toDouble : TInt64toDouble;
procedure InitMongoDBLibrary(const MongoCDLL : UTF8String = Default_MongoCDLL);
procedure DoneMongoDBLibrary;
{$Else}
// MongoDB declarations
procedure set_mem_alloc_functions (custom_bson_malloc_func,
custom_bson_realloc_func,
custom_bson_free_func : Pointer); cdecl; external Default_MongoCDLL;
function mongo_env_sock_init : integer; cdecl; external Default_MongoCDLL;
function mongo_alloc: Pointer; cdecl; external Default_MongoCDLL;
procedure mongo_dealloc(c: Pointer); cdecl; external Default_MongoCDLL;
function mongo_client(c: Pointer; host: PAnsiChar; port: Integer): Integer; cdecl; external Default_MongoCDLL;
procedure mongo_destroy(c: Pointer); cdecl; external Default_MongoCDLL;
procedure mongo_replica_set_init(c: Pointer; Name: PAnsiChar); cdecl; external Default_MongoCDLL;
procedure mongo_replica_set_add_seed(c: Pointer; host: PAnsiChar; port: Integer); cdecl; external Default_MongoCDLL;
function mongo_replica_set_client(c: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_is_connected(c: Pointer): Longbool; cdecl; external Default_MongoCDLL;
function mongo_get_err(c: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_set_op_timeout(c: Pointer; millis: Integer): Integer; cdecl; external Default_MongoCDLL;
function mongo_get_op_timeout(c: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_get_primary(c: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
function mongo_check_connection(c: Pointer): Integer; cdecl; external Default_MongoCDLL;
procedure mongo_disconnect(c: Pointer); cdecl; external Default_MongoCDLL;
function mongo_reconnect(c: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_cmd_ismaster(c: Pointer; b: Pointer): Longbool; cdecl; external Default_MongoCDLL;
function mongo_get_socket(c: Pointer): Pointer; cdecl; external Default_MongoCDLL;
function mongo_get_host_count(c: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_get_host(c: Pointer; i: Integer): PAnsiChar; cdecl; external Default_MongoCDLL;
function mongo_insert(c: Pointer; ns: PAnsiChar; b: Pointer; wc: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_insert_batch(c: Pointer; ns: PAnsiChar; bsons: Pointer; Count: Integer; wc: Pointer; flags: Integer): Integer; cdecl; external Default_MongoCDLL;
function mongo_update(c: Pointer; ns: PAnsiChar; cond: Pointer; op: Pointer; flags: Integer; wc: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_remove(c: Pointer; ns: PAnsiChar; criteria: Pointer; wc: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_find_one(c: Pointer; ns: PAnsiChar; query: Pointer; fields: Pointer; Result: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_alloc: Pointer; cdecl; external Default_MongoCDLL;
procedure bson_dealloc(b: Pointer); cdecl; external Default_MongoCDLL;
procedure bson_copy(dest: Pointer; src: Pointer); cdecl; external Default_MongoCDLL;
function mongo_cursor_alloc: Pointer; cdecl; external Default_MongoCDLL;
procedure mongo_cursor_dealloc(Cursor: Pointer); cdecl; external Default_MongoCDLL;
procedure mongo_cursor_destroy(Cursor: Pointer); cdecl; external Default_MongoCDLL;
function mongo_find(c: Pointer; ns: PAnsiChar; query: Pointer; fields: Pointer; limit, skip, options: Integer): Pointer; cdecl; external Default_MongoCDLL;
function mongo_cursor_next(Cursor: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_cursor_bson(Cursor: Pointer): Pointer; cdecl; external Default_MongoCDLL;
function mongo_cmd_drop_collection(c: Pointer; db: PAnsiChar; collection: PAnsiChar; Result: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_cmd_drop_db(c: Pointer; db: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function mongo_count(c: Pointer; db: PAnsiChar; collection: PAnsiChar; query: Pointer): Double; cdecl; external Default_MongoCDLL;
function mongo_create_index(c: Pointer; ns: PAnsiChar; key: Pointer; name : PAnsiChar; options: Integer; ttl : integer; res: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_cmd_add_user(c: Pointer; db: PAnsiChar; Name: PAnsiChar; password: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function mongo_cmd_create_user(c: Pointer; db: PAnsiChar; Name: PAnsiChar; password: PAnsiChar; roles : PPAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function mongo_cmd_authenticate(c: Pointer; db: PAnsiChar; Name: PAnsiChar; password: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function mongo_run_command(c: Pointer; db: PAnsiChar; command: Pointer; res: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_cmd_get_last_error(c: Pointer; db: PAnsiChar; res: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_cmd_get_prev_error(c: Pointer; db: PAnsiChar; res: Pointer): Integer; cdecl; external Default_MongoCDLL;
procedure mongo_cmd_reset_error(c : Pointer; db : PAnsiChar); cdecl; external Default_MongoCDLL;
function mongo_get_server_err(c: Pointer): Integer; cdecl; external Default_MongoCDLL;
function mongo_get_server_err_string(c: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
// WriteConcern API functions
function mongo_write_concern_alloc : Pointer; cdecl; external Default_MongoCDLL;
procedure mongo_write_concern_dealloc(write_concern : Pointer); cdecl; external Default_MongoCDLL;
procedure mongo_write_concern_init(write_concern : pointer); cdecl; external Default_MongoCDLL;
function mongo_write_concern_finish(write_concern : pointer) : integer; cdecl; external Default_MongoCDLL;
procedure mongo_write_concern_destroy(write_concern : pointer); cdecl; external Default_MongoCDLL;
procedure mongo_set_write_concern(conn : pointer; write_concern : pointer); cdecl; external Default_MongoCDLL;
function mongo_write_concern_get_w(write_concern : Pointer) : integer; cdecl; external Default_MongoCDLL;
function mongo_write_concern_get_wtimeout(write_concern : Pointer) : integer; cdecl; external Default_MongoCDLL;
function mongo_write_concern_get_j(write_concern : Pointer) : integer; cdecl; external Default_MongoCDLL;
function mongo_write_concern_get_fsync(write_concern : Pointer) : integer; cdecl; external Default_MongoCDLL;
function mongo_write_concern_get_mode(write_concern : Pointer) : PAnsiChar; cdecl; external Default_MongoCDLL;
function mongo_write_concern_get_cmd(write_concern : Pointer) : Pointer; cdecl; external Default_MongoCDLL;
procedure mongo_write_concern_set_w(write_concern : Pointer; w : integer); cdecl; external Default_MongoCDLL;
procedure mongo_write_concern_set_wtimeout(write_concern : Pointer; wtimeout : integer); cdecl; external Default_MongoCDLL;
procedure mongo_write_concern_set_j(write_concern : Pointer; j : integer); cdecl; external Default_MongoCDLL;
procedure mongo_write_concern_set_fsync(write_concern : Pointer; fsync : integer); cdecl; external Default_MongoCDLL;
procedure mongo_write_concern_set_mode(write_concern : Pointer; mode : PAnsiChar); cdecl; external Default_MongoCDLL;
// MongoBson declarations
procedure bson_free(b : pointer); cdecl; external Default_MongoCDLL;
function bson_init(b: Pointer) : integer; cdecl; external Default_MongoCDLL;
function bson_init_finished_data(b : Pointer; data : PAnsiChar; ownsData : LongBool) : integer; cdecl; external Default_MongoCDLL;
function bson_init_empty(b : Pointer) : integer; cdecl; external Default_MongoCDLL;
procedure bson_destroy(b: Pointer); cdecl; external Default_MongoCDLL;
function bson_finish(b: Pointer): Integer; cdecl; external Default_MongoCDLL;
procedure bson_print(b: Pointer); cdecl; external Default_MongoCDLL;
function bson_data( b : Pointer ) : Pointer; cdecl; external Default_MongoCDLL;
procedure bson_oid_gen(oid: Pointer); cdecl; external Default_MongoCDLL;
procedure bson_set_oid_inc (proc : pointer); cdecl; external Default_MongoCDLL;
procedure bson_set_oid_fuzz (proc : pointer); cdecl; external Default_MongoCDLL;
procedure bson_oid_to_string(oid: Pointer; s: PAnsiChar); cdecl; external Default_MongoCDLL;
procedure bson_oid_from_string(oid: Pointer; s: PAnsiChar); cdecl; external Default_MongoCDLL;
function bson_append_string(b: Pointer; Name: PAnsiChar; Value: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function bson_append_string_n(b: Pointer; Name: PAnsiChar; Value: PAnsiChar; Len : NativeUInt): Integer; cdecl; external Default_MongoCDLL;
function bson_append_code(b: Pointer; Name: PAnsiChar; Value: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function bson_append_code_n(b: Pointer; Name: PAnsiChar; Value: PAnsiChar; Len : NativeUInt): Integer; cdecl; external Default_MongoCDLL;
function bson_append_symbol(b: Pointer; Name: PAnsiChar; Value: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function bson_append_symbol_n (b: Pointer; Name: PAnsiChar; Value: PAnsiChar; Len : NativeUInt): Integer; cdecl; external Default_MongoCDLL;
function bson_append_int(b: Pointer; Name: PAnsiChar; Value: Integer): Integer; cdecl; external Default_MongoCDLL;
function bson_append_long(b: Pointer; Name: PAnsiChar; Value: Int64): Integer; cdecl; external Default_MongoCDLL;
function bson_append_double(b: Pointer; Name: PAnsiChar; Value: Double): Integer; cdecl; external Default_MongoCDLL;
function bson_append_date(b: Pointer; Name: PAnsiChar; Value: Int64): Integer; cdecl; external Default_MongoCDLL;
function bson_append_bool(b: Pointer; Name: PAnsiChar; Value: LongBool): Integer; cdecl; external Default_MongoCDLL;
function bson_append_null(b: Pointer; Name: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function bson_append_undefined(b: Pointer; Name: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function bson_append_start_object(b: Pointer; Name: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function bson_append_start_array(b: Pointer; Name: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function bson_append_finish_object(b: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_append_oid(b: Pointer; Name: PAnsiChar; oid: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_append_code_w_scope(b: Pointer; Name: PAnsiChar; code: PAnsiChar; scope: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_append_regex(b: Pointer; Name: PAnsiChar; pattern: PAnsiChar; options: PAnsiChar): Integer; cdecl; external Default_MongoCDLL;
function bson_append_timestamp2(b: Pointer; Name: PAnsiChar; Time: Integer; increment: Integer): Integer; cdecl; external Default_MongoCDLL;
function bson_append_binary(b: Pointer; Name: PAnsiChar; Kind: Byte; Data: Pointer; Len: NativeUInt): Integer; cdecl; external Default_MongoCDLL;
function bson_append_bson(b: Pointer; Name: PAnsiChar; Value: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_buffer_size(b: Pointer): NativeUInt; cdecl; external Default_MongoCDLL;
function bson_size(b: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_iterator_alloc(): Pointer; cdecl; external Default_MongoCDLL;
procedure bson_iterator_dealloc(i: Pointer); cdecl; external Default_MongoCDLL;
procedure bson_iterator_init(i: Pointer; b: Pointer); cdecl; external Default_MongoCDLL;
function bson_find(i: Pointer; b: Pointer; Name: PAnsiChar): TBsonType; cdecl; external Default_MongoCDLL;
function bson_iterator_type(i: Pointer): TBsonType; cdecl; external Default_MongoCDLL;
function bson_iterator_next(i: Pointer): TBsonType; cdecl; external Default_MongoCDLL;
function bson_iterator_key(i: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
function bson_iterator_double(i: Pointer): Double; cdecl; external Default_MongoCDLL;
function bson_iterator_long(i: Pointer): Int64; cdecl; external Default_MongoCDLL;
function bson_iterator_int(i: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_iterator_bool(i: Pointer): LongBool; cdecl; external Default_MongoCDLL;
function bson_iterator_string(i: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
function bson_iterator_date(i: Pointer): Int64; cdecl; external Default_MongoCDLL;
procedure bson_iterator_subiterator(i: Pointer; sub: Pointer); cdecl; external Default_MongoCDLL;
function bson_iterator_oid(i: Pointer): Pointer; cdecl; external Default_MongoCDLL;
function bson_iterator_code(i: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
procedure bson_iterator_code_scope_init(i: Pointer; b: Pointer); cdecl; external Default_MongoCDLL;
function bson_iterator_regex(i: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
function bson_iterator_regex_opts(i: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
function bson_iterator_timestamp_time(i: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_iterator_timestamp_increment(i: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_iterator_bin_len(i: Pointer): Integer; cdecl; external Default_MongoCDLL;
function bson_iterator_bin_type(i: Pointer): Byte; cdecl; external Default_MongoCDLL;
function bson_iterator_bin_data(i: Pointer): Pointer; cdecl; external Default_MongoCDLL;
function Int64toDouble(i64: Int64): Double; cdecl; external Default_MongoCDLL Name 'bson_int64_to_double';
function set_bson_err_handler(newErrorHandler : Pointer) : Pointer; cdecl; external Default_MongoCDLL;
// GridFS declarations
function gridfs_alloc: Pointer; cdecl; external Default_MongoCDLL;
procedure gridfs_dealloc(g: Pointer); cdecl; external Default_MongoCDLL;
function gridfs_init(c: Pointer; db: PAnsiChar; prefix: PAnsiChar; g: Pointer): Integer; cdecl; external Default_MongoCDLL;
procedure gridfs_destroy(g: Pointer); cdecl; external Default_MongoCDLL;
function gridfs_store_file(g: Pointer; FileName: PAnsiChar; remoteName: PAnsiChar; contentType: PAnsiChar; Flags : Integer): Integer; cdecl; external Default_MongoCDLL;
procedure gridfs_remove_filename(g: Pointer; remoteName: PAnsiChar); cdecl; external Default_MongoCDLL;
function gridfs_store_buffer(g: Pointer; p: Pointer; size: UInt64; remoteName: PAnsiChar; contentType: PAnsiChar; Flags : Integer): Integer; cdecl; external Default_MongoCDLL;
function gridfile_create: Pointer; cdecl; external Default_MongoCDLL;
procedure gridfile_dealloc(gf: Pointer); cdecl; external Default_MongoCDLL;
procedure gridfile_writer_init(gf: Pointer; gfs: Pointer; remoteName: PAnsiChar; contentType: PAnsiChar; Flags : Integer); cdecl; external Default_MongoCDLL;
function gridfile_write_buffer(gf: Pointer; Data: Pointer; Length: UInt64) : UInt64; cdecl; external Default_MongoCDLL;
function gridfile_writer_done(gf: Pointer): Integer; cdecl; external Default_MongoCDLL;
function gridfs_find_query(g: Pointer; query: Pointer; gf: Pointer): Integer; cdecl; external Default_MongoCDLL;
procedure gridfile_set_filter_context( gfile, context : Pointer); cdecl; external Default_MongoCDLL;
procedure gridfile_destroy(gf: Pointer); cdecl; external Default_MongoCDLL;
function gridfile_get_filename(gf: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
function gridfile_get_chunksize(gf: Pointer): Integer; cdecl; external Default_MongoCDLL;
function gridfile_get_contentlength(gf: Pointer): UInt64; cdecl; external Default_MongoCDLL;
function gridfile_get_contenttype(gf: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
function gridfile_get_uploaddate(gf: Pointer): Int64; cdecl; external Default_MongoCDLL;
function gridfile_get_md5(gf: Pointer): PAnsiChar; cdecl; external Default_MongoCDLL;
procedure gridfile_get_metadata(gf: Pointer; b: Pointer; copyData : LongBool); cdecl; external Default_MongoCDLL;
function gridfile_get_numchunks(gf: Pointer): Integer; cdecl; external Default_MongoCDLL;
procedure gridfile_get_descriptor(gf: Pointer; b: Pointer); cdecl; external Default_MongoCDLL;
procedure gridfile_get_chunk(gf: Pointer; i: Integer; b: Pointer); cdecl; external Default_MongoCDLL;
function gridfile_get_chunks(gf: Pointer; i: NativeUInt; Count: NativeUInt): Pointer; cdecl; external Default_MongoCDLL;
function gridfile_read_buffer(gf: Pointer; buf: Pointer; size: UInt64): UInt64; cdecl; external Default_MongoCDLL;
function gridfile_seek(gf: Pointer; offset: UInt64): UInt64; cdecl; external Default_MongoCDLL;
function gridfile_init(gfs, meta, gfile : pointer) : integer; cdecl; external Default_MongoCDLL;
function gridfile_get_id(gfile : pointer) : TBsonOIDValue; cdecl; external Default_MongoCDLL;
function gridfile_truncate(gfile : Pointer; newSize : UInt64) : UInt64; cdecl; external Default_MongoCDLL;
function gridfile_expand(gfile : Pointer; bytesToExpand : UInt64) : UInt64; cdecl; external Default_MongoCDLL;
function gridfile_set_size(gfile : Pointer; newSize : UInt64) : UInt64; cdecl; external Default_MongoCDLL;
function gridfs_get_caseInsensitive (gf : Pointer) : LongBool; cdecl; external Default_MongoCDLL;
procedure gridfs_set_caseInsensitive(gf : Pointer; newValue : LongBool); cdecl; external Default_MongoCDLL;
procedure gridfile_set_flags(gf : Pointer; Flags : Integer); cdecl; external Default_MongoCDLL;
function gridfile_get_flags(gf : Pointer) : Integer; cdecl; external Default_MongoCDLL;
// ZLib and AES extensions
function init_ZLib_AES_filtering(flags : integer) : integer; cdecl; external Default_MongoCDLL;
function create_ZLib_AES_filter_context(flags : integer) : Pointer; cdecl; external Default_MongoCDLL;
procedure destroy_ZLib_AES_filter_context(context : Pointer; flags : integer); cdecl; external Default_MongoCDLL;
function ZLib_AES_filter_context_set_encryption_key( context : Pointer; Passphrase : PAnsiChar; bits : integer ) : integer; cdecl; external Default_MongoCDLL;
{$EndIf}
function mongo_write_concern_create: Pointer;
procedure bson_dealloc_and_destroy(bson : Pointer);
function bson_create: pointer;
implementation
{$IFDEF OnDemandMongoCLoad}
resourcestring
SFailedLoadingMongocDll = 'Failed loading mongoc.dll';
SFunctionNotFoundOnMongoCLibrary = 'Function "%s" not found on MongoC library';
{$ENDIF}
procedure DefaultMongoErrorHandler(const Msg : PAnsiChar); cdecl;
begin
raise EMongoFatalError.Create(string(Msg));
end;
function delphi_malloc(size : NativeUInt) : Pointer; cdecl;
begin
GetMem(Result, Size);
end;
function delphi_realloc(p : Pointer; size : NativeUInt) : Pointer; cdecl;
begin
Result := p;
ReallocMem(Result, size);
end;
procedure delphi_free(p : pointer); cdecl;
begin
FreeMem(p);
end;
procedure MongoAPIInit;
begin
set_mem_alloc_functions(@delphi_malloc, @delphi_realloc, @delphi_free);
mongo_env_sock_init;
init_ZLib_AES_filtering(0);
set_bson_err_handler(@DefaultMongoErrorHandler);
end;
{$IFDEF OnDemandMongoCLoad}
var
UsedDLLName : UTF8String = '';
procedure InitMongoDBLibrary(const MongoCDLL : UTF8String = Default_MongoCDLL);
function GetProcAddress(h : HMODULE; const FnName : UTF8String) : Pointer;
begin
Result := Windows.GetProcAddress(h, PAnsiChar(FnName));
if Result = nil then
raise Exception.CreateFmt(SFunctionNotFoundOnMongoCLibrary, [FnName]);
end;
begin
if HMongoDBDll <> 0 then
exit;
if UsedDLLName = '' then
UsedDLLName := MongoCDLL;
HMongoDBDll := LoadLibraryA(PAnsiChar(UsedDLLName));
if HMongoDBDll = 0 then
raise Exception.Create(SFailedLoadingMongocDll);
// MongoDB initializations
set_mem_alloc_functions := GetProcAddress(HMongoDBDll, 'set_mem_alloc_functions');
mongo_env_sock_init := GetProcAddress(HMongoDBDll, 'mongo_env_sock_init');
mongo_alloc := GetProcAddress(HMongoDBDll, 'mongo_alloc');
mongo_dealloc := GetProcAddress(HMongoDBDll, 'mongo_dealloc');
mongo_client := GetProcAddress(HMongoDBDll, 'mongo_client');
mongo_destroy := GetProcAddress(HMongoDBDll, 'mongo_destroy');
mongo_replica_set_init := GetProcAddress(HMongoDBDll, 'mongo_replica_set_init');
mongo_replica_set_add_seed := GetProcAddress(HMongoDBDll, 'mongo_replica_set_add_seed');
mongo_replica_set_client := GetProcAddress(HMongoDBDll, 'mongo_replica_set_client');
mongo_is_connected := GetProcAddress(HMongoDBDll, 'mongo_is_connected');
mongo_get_err := GetProcAddress(HMongoDBDll, 'mongo_get_err');
mongo_set_op_timeout := GetProcAddress(HMongoDBDll, 'mongo_set_op_timeout');
mongo_get_op_timeout := GetProcAddress(HMongoDBDll, 'mongo_get_op_timeout');
mongo_get_primary := GetProcAddress(HMongoDBDll, 'mongo_get_primary');
mongo_check_connection := GetProcAddress(HMongoDBDll, 'mongo_check_connection');
mongo_disconnect := GetProcAddress(HMongoDBDll, 'mongo_disconnect');
mongo_reconnect := GetProcAddress(HMongoDBDll, 'mongo_reconnect');
mongo_cmd_ismaster := GetProcAddress(HMongoDBDll, 'mongo_cmd_ismaster');
mongo_get_socket := GetProcAddress(HMongoDBDll, 'mongo_get_socket');
mongo_get_host_count := GetProcAddress(HMongoDBDll, 'mongo_get_host_count');
mongo_get_host := GetProcAddress(HMongoDBDll, 'mongo_get_host');
mongo_insert := GetProcAddress(HMongoDBDll, 'mongo_insert');
mongo_insert_batch := GetProcAddress(HMongoDBDll, 'mongo_insert_batch');
mongo_update := GetProcAddress(HMongoDBDll, 'mongo_update');
mongo_remove := GetProcAddress(HMongoDBDll, 'mongo_remove');
mongo_find_one := GetProcAddress(HMongoDBDll, 'mongo_find_one');
bson_alloc := GetProcAddress(HMongoDBDll, 'bson_alloc');
bson_dealloc := GetProcAddress(HMongoDBDll, 'bson_dealloc');
bson_copy := GetProcAddress(HMongoDBDll, 'bson_copy');
mongo_cursor_alloc := GetProcAddress(HMongoDBDll, 'mongo_cursor_alloc');
mongo_cursor_dealloc := GetProcAddress(HMongoDBDll, 'mongo_cursor_dealloc');
mongo_cursor_destroy := GetProcAddress(HMongoDBDll, 'mongo_cursor_destroy');
mongo_find := GetProcAddress(HMongoDBDll, 'mongo_find');
mongo_cursor_next := GetProcAddress(HMongoDBDll, 'mongo_cursor_next');
mongo_cursor_bson := GetProcAddress(HMongoDBDll, 'mongo_cursor_bson');
mongo_cmd_drop_collection := GetProcAddress(HMongoDBDll, 'mongo_cmd_drop_collection');
mongo_cmd_drop_db := GetProcAddress(HMongoDBDll, 'mongo_cmd_drop_db');
mongo_count := GetProcAddress(HMongoDBDll, 'mongo_count');
mongo_create_index := GetProcAddress(HMongoDBDll, 'mongo_create_index');
mongo_cmd_add_user := GetProcAddress(HMongoDBDll, 'mongo_cmd_add_user');
mongo_cmd_create_user := GetProcAddress(HMongoDBDll, 'mongo_cmd_create_user');
mongo_cmd_authenticate := GetProcAddress(HMongoDBDll, 'mongo_cmd_authenticate');
mongo_run_command := GetProcAddress(HMongoDBDll, 'mongo_run_command');
mongo_cmd_get_last_error := GetProcAddress(HMongoDBDll, 'mongo_cmd_get_last_error');
mongo_cmd_get_prev_error := GetProcAddress(HMongoDBDll, 'mongo_cmd_get_prev_error');
mongo_cmd_reset_error := GetProcAddress(HMongoDBDll, 'mongo_cmd_reset_error');
mongo_get_server_err := GetProcAddress(HMongoDBDll, 'mongo_get_server_err');
mongo_get_server_err_string := GetProcAddress(HMongoDBDll, 'mongo_get_server_err_string');
// WriteConcern API
mongo_write_concern_alloc := GetProcAddress(HMongoDBDll, 'mongo_write_concern_alloc');
mongo_write_concern_dealloc := GetProcAddress(HMongoDBDll, 'mongo_write_concern_dealloc');
mongo_write_concern_init := GetProcAddress(HMongoDBDll, 'mongo_write_concern_init');
mongo_write_concern_finish := GetProcAddress(HMongoDBDll, 'mongo_write_concern_finish');
mongo_write_concern_destroy := GetProcAddress(HMongoDBDll, 'mongo_write_concern_destroy');
mongo_set_write_concern := GetProcAddress(HMongoDBDll, 'mongo_set_write_concern');
mongo_write_concern_get_w := GetProcAddress(HMongoDBDll, 'mongo_write_concern_get_w');
mongo_write_concern_get_wtimeout := GetProcAddress(HMongoDBDll, 'mongo_write_concern_get_wtimeout');
mongo_write_concern_get_j := GetProcAddress(HMongoDBDll, 'mongo_write_concern_get_j');
mongo_write_concern_get_fsync := GetProcAddress(HMongoDBDll, 'mongo_write_concern_get_fsync');
mongo_write_concern_get_mode := GetProcAddress(HMongoDBDll, 'mongo_write_concern_get_mode');
mongo_write_concern_get_cmd := GetProcAddress(HMongoDBDll, 'mongo_write_concern_get_cmd');
mongo_write_concern_set_w := GetProcAddress(HMongoDBDll, 'mongo_write_concern_set_w');
mongo_write_concern_set_wtimeout := GetProcAddress(HMongoDBDll, 'mongo_write_concern_set_wtimeout');
mongo_write_concern_set_j := GetProcAddress(HMongoDBDll, 'mongo_write_concern_set_j');
mongo_write_concern_set_fsync := GetProcAddress(HMongoDBDll, 'mongo_write_concern_set_fsync');
mongo_write_concern_set_mode := GetProcAddress(HMongoDBDll, 'mongo_write_concern_set_mode');
// MongoBson initializations
bson_free := GetProcAddress(HMongoDBDll, 'bson_free');
bson_alloc := GetProcAddress(HMongoDBDll, 'bson_alloc');
bson_init := GetProcAddress(HMongoDBDll, 'bson_init');
bson_init_empty := GetProcAddress(HMongoDBDll, 'bson_init_empty');
bson_init_finished_data := GetProcAddress(HMongoDBDll, 'bson_init_finished_data');
bson_destroy := GetProcAddress(HMongoDBDll, 'bson_destroy');
bson_dealloc := GetProcAddress(HMongoDBDll, 'bson_dealloc');
bson_copy := GetProcAddress(HMongoDBDll, 'bson_copy');
bson_finish := GetProcAddress(HMongoDBDll, 'bson_finish');
bson_print := GetProcAddress(HMongoDBDll, 'bson_print');
bson_data := GetProcAddress(HMongoDBDll, 'bson_data');
bson_oid_gen := GetProcAddress(HMongoDBDll, 'bson_oid_gen');
bson_set_oid_inc := GetProcAddress(HMongoDBDll, 'bson_set_oid_inc');
bson_set_oid_fuzz := GetProcAddress(HMongoDBDll, 'bson_set_oid_fuzz');
bson_oid_to_string := GetProcAddress(HMongoDBDll, 'bson_oid_to_string');
bson_oid_from_string := GetProcAddress(HMongoDBDll, 'bson_oid_from_string');
bson_append_string := GetProcAddress(HMongoDBDll, 'bson_append_string');
bson_append_string_n := GetProcAddress(HMongoDBDll, 'bson_append_string_n');
bson_append_code := GetProcAddress(HMongoDBDll, 'bson_append_code');
bson_append_code_n := GetProcAddress(HMongoDBDll, 'bson_append_code_n');
bson_append_symbol := GetProcAddress(HMongoDBDll, 'bson_append_symbol');
bson_append_symbol_n := GetProcAddress(HMongoDBDll, 'bson_append_symbol_n');
bson_append_int := GetProcAddress(HMongoDBDll, 'bson_append_int');
bson_append_long := GetProcAddress(HMongoDBDll, 'bson_append_long');
bson_append_double := GetProcAddress(HMongoDBDll, 'bson_append_double');
bson_append_date := GetProcAddress(HMongoDBDll, 'bson_append_date');
bson_append_bool := GetProcAddress(HMongoDBDll, 'bson_append_bool');
bson_append_null := GetProcAddress(HMongoDBDll, 'bson_append_null');
bson_append_undefined := GetProcAddress(HMongoDBDll, 'bson_append_undefined');
bson_append_start_object := GetProcAddress(HMongoDBDll, 'bson_append_start_object');
bson_append_start_array := GetProcAddress(HMongoDBDll, 'bson_append_start_array');
bson_append_finish_object := GetProcAddress(HMongoDBDll, 'bson_append_finish_object');
bson_append_oid := GetProcAddress(HMongoDBDll, 'bson_append_oid');
bson_append_code_w_scope := GetProcAddress(HMongoDBDll, 'bson_append_code_w_scope');
bson_append_regex := GetProcAddress(HMongoDBDll, 'bson_append_regex');
bson_append_timestamp2 := GetProcAddress(HMongoDBDll, 'bson_append_timestamp2');
bson_append_binary := GetProcAddress(HMongoDBDll, 'bson_append_binary');
bson_append_bson := GetProcAddress(HMongoDBDll, 'bson_append_bson');
bson_buffer_size := GetProcAddress(HMongoDBDll, 'bson_buffer_size');
bson_size := GetProcAddress(HMongoDBDll, 'bson_size');
bson_iterator_alloc := GetProcAddress(HMongoDBDll, 'bson_iterator_alloc');
bson_iterator_dealloc := GetProcAddress(HMongoDBDll, 'bson_iterator_dealloc');
bson_iterator_init := GetProcAddress(HMongoDBDll, 'bson_iterator_init');
bson_find := GetProcAddress(HMongoDBDll, 'bson_find');
bson_iterator_type := GetProcAddress(HMongoDBDll, 'bson_iterator_type');
bson_iterator_next := GetProcAddress(HMongoDBDll, 'bson_iterator_next');
bson_iterator_key := GetProcAddress(HMongoDBDll, 'bson_iterator_key');
bson_iterator_double := GetProcAddress(HMongoDBDll, 'bson_iterator_double');
bson_iterator_long := GetProcAddress(HMongoDBDll, 'bson_iterator_long');
bson_iterator_int := GetProcAddress(HMongoDBDll, 'bson_iterator_int');
bson_iterator_bool := GetProcAddress(HMongoDBDll, 'bson_iterator_bool');
bson_iterator_string := GetProcAddress(HMongoDBDll, 'bson_iterator_string');
bson_iterator_date:= GetProcAddress(HMongoDBDll, 'bson_iterator_date');
bson_iterator_subiterator := GetProcAddress(HMongoDBDll, 'bson_iterator_subiterator');
bson_iterator_oid := GetProcAddress(HMongoDBDll, 'bson_iterator_oid');
bson_iterator_code := GetProcAddress(HMongoDBDll, 'bson_iterator_code');
bson_iterator_code_scope_init := GetProcAddress(HMongoDBDll, 'bson_iterator_code_scope_init');
bson_iterator_regex := GetProcAddress(HMongoDBDll, 'bson_iterator_regex');
bson_iterator_regex_opts := GetProcAddress(HMongoDBDll, 'bson_iterator_regex_opts');
bson_iterator_timestamp_time := GetProcAddress(HMongoDBDll, 'bson_iterator_timestamp_time');
bson_iterator_timestamp_increment := GetProcAddress(HMongoDBDll, 'bson_iterator_timestamp_increment');
bson_iterator_bin_len := GetProcAddress(HMongoDBDll, 'bson_iterator_bin_len');
bson_iterator_bin_type := GetProcAddress(HMongoDBDll, 'bson_iterator_bin_type');
bson_iterator_bin_data := GetProcAddress(HMongoDBDll, 'bson_iterator_bin_data');
set_bson_err_handler := GetProcAddress(HMongoDBDll, 'set_bson_err_handler');
// GridFS functions
gridfs_alloc := GetProcAddress(HMongoDBDll, 'gridfs_alloc');
gridfs_dealloc := GetProcAddress(HMongoDBDll, 'gridfs_dealloc');
gridfs_init := GetProcAddress(HMongoDBDll, 'gridfs_init');
gridfile_set_filter_context := GetProcAddress(HMongoDBDll, 'gridfile_set_filter_context');
gridfs_destroy := GetProcAddress(HMongoDBDll, 'gridfs_destroy');
gridfs_store_file := GetProcAddress(HMongoDBDll, 'gridfs_store_file');
gridfs_remove_filename := GetProcAddress(HMongoDBDll, 'gridfs_remove_filename');
gridfs_store_buffer := GetProcAddress(HMongoDBDll, 'gridfs_store_buffer');
gridfile_create := GetProcAddress(HMongoDBDll, 'gridfile_create');
gridfile_dealloc := GetProcAddress(HMongoDBDll, 'gridfile_dealloc');
gridfile_writer_init := GetProcAddress(HMongoDBDll, 'gridfile_writer_init');
gridfile_write_buffer := GetProcAddress(HMongoDBDll, 'gridfile_write_buffer');
gridfile_writer_done := GetProcAddress(HMongoDBDll, 'gridfile_writer_done');
gridfs_find_query := GetProcAddress(HMongoDBDll, 'gridfs_find_query');
gridfile_destroy := GetProcAddress(HMongoDBDll, 'gridfile_destroy');
gridfile_get_filename := GetProcAddress(HMongoDBDll, 'gridfile_get_filename');
gridfile_get_chunksize := GetProcAddress(HMongoDBDll, 'gridfile_get_chunksize');
gridfile_get_contentlength := GetProcAddress(HMongoDBDll, 'gridfile_get_contentlength');
gridfile_get_contenttype:= GetProcAddress(HMongoDBDll, 'gridfile_get_contenttype');
gridfile_get_uploaddate := GetProcAddress(HMongoDBDll, 'gridfile_get_uploaddate');
gridfile_get_md5 := GetProcAddress(HMongoDBDll, 'gridfile_get_md5');
gridfile_get_metadata := GetProcAddress(HMongoDBDll, 'gridfile_get_metadata');
gridfile_get_numchunks := GetProcAddress(HMongoDBDll, 'gridfile_get_numchunks');
gridfile_get_descriptor := GetProcAddress(HMongoDBDll, 'gridfile_get_descriptor');
gridfile_get_chunk:= GetProcAddress(HMongoDBDll, 'gridfile_get_chunk');
gridfile_get_chunks := GetProcAddress(HMongoDBDll, 'gridfile_get_chunks');
gridfile_read_buffer := GetProcAddress(HMongoDBDll, 'gridfile_read_buffer');
gridfile_seek := GetProcAddress(HMongoDBDll, 'gridfile_seek');
gridfile_init := GetProcAddress(HMongoDBDll, 'gridfile_init');
gridfile_get_id := GetProcAddress(HMongoDBDll, 'gridfile_get_id');
gridfile_truncate := GetProcAddress(HMongoDBDll, 'gridfile_truncate');
gridfile_expand := GetProcAddress(HMongoDBDll, 'gridfile_expand');
gridfile_set_size := GetProcAddress(HMongoDBDll, 'gridfile_set_size');
gridfs_get_caseInsensitive := GetProcAddress(HMongoDBDll, 'gridfs_get_caseInsensitive');
gridfs_set_caseInsensitive := GetProcAddress(HMongoDBDll, 'gridfs_set_caseInsensitive');
gridfile_set_flags := GetProcAddress(HMongoDBDll, 'gridfile_set_flags');
gridfile_get_flags := GetProcAddress(HMongoDBDll, 'gridfile_get_flags');
// ZLib and AES extensions
init_ZLib_AES_filtering := GetProcAddress(HMongoDBDll, 'init_ZLib_AES_filtering');
create_ZLib_AES_filter_context := GetProcAddress(HMongoDBDll, 'create_ZLib_AES_filter_context');
destroy_ZLib_AES_filter_context := GetProcAddress(HMongoDBDll, 'destroy_ZLib_AES_filter_context');
ZLib_AES_filter_context_set_encryption_key := GetProcAddress(HMongoDBDll, 'ZLib_AES_filter_context_set_encryption_key');
Int64toDouble := GetProcAddress(HMongoDBDll, 'bson_int64_to_double');
MongoAPIInit;
end;
procedure DoneMongoDBLibrary;
begin
if HMongoDBDll <> 0 then
begin
FreeLibrary(HMongoDBDll);
HMongoDBDll := 0;
end;
end;
{$ENDIF}
{ TMongoInterfacedObject }
constructor TMongoInterfacedObject.Create;
begin
inherited;
end;
destructor TMongoInterfacedObject.Destroy;
begin
inherited;
end;
{ TMongoObject }
constructor TMongoObject.Create;
begin
inherited;
end;
destructor TMongoObject.Destroy;
begin
inherited;
end;
procedure bson_dealloc_and_destroy(bson : Pointer);
begin
bson_destroy(bson);
bson_dealloc(bson);
end;
function mongo_write_concern_create: Pointer;
begin
Result := mongo_write_concern_alloc;
mongo_write_concern_init(Result);
end;
function bson_create: pointer;
begin
Result := bson_alloc;
if bson_init_empty(Result) <> 0 then
raise EMongoFatalError.Create('Call to bson_init_empty failed');
end;
initialization
{$IFNDEF OnDemandMongoCLoad}
MongoAPIInit;
{$ENDIF}
finalization
{$IFDEF OnDemandMongoCLoad}
DoneMongoDBLibrary;
{$ENDIF}
end.
|
// shallow way to recognize item as Staff
function isStaff(item: IInterface): boolean;
var
tmp: IInterface;
begin
Result := false;
if (Signature(item) = 'WEAP') then begin
// WeapTypeStaff [KYWD:0001E716] VendorItemStaff [KYWD:000937A4]
if ( hasKeyword(item, 'WeapTypeStaff') or hasKeyword(item, 'VendorItemStaff') ) then begin
Result := true;
end else begin
tmp := GetElementEditValues(item, 'DNAM\Animation Type');
if Assigned(tmp) then begin
if (tmp = 'Staff') then begin
Result := true;
end;
end;
end;
end;
end;
|
๏ปฟunit WinningPrize;
interface
uses
System.SysUtils;
type
TWinningPrize = class(TObject)
private
_chance: double;
_playTime: integer;
_n: integer;
function __play: boolean;
public
constructor Create(chance: double; playTime: integer; n: integer);
destructor Destroy; override;
procedure Run;
end;
implementation
{ TWinningPrize }
constructor TWinningPrize.Create(chance: double; playTime: integer; n: integer);
begin
if (chance < 0.0) or (chance > 1.0) then
raise Exception.Create('chance must be between 0 and 1!');
if (playTime <= 0) or (n <= 0) then
raise Exception.Create('playTime or N must be larger than 0!');
_chance := chance;
_playTime := playTime;
_n := n;
end;
destructor TWinningPrize.Destroy;
begin
inherited Destroy;
end;
procedure TWinningPrize.Run;
var
wins, i: integer;
begin
wins := 0;
for i := 0 to _n - 1 do
begin
if __play then
Inc(wins);
end;
WriteLn('winning rate: ' + (wins / _n).ToString);
end;
function TWinningPrize.__play: boolean;
var
i: integer;
begin
Randomize;
for i := 0 to _playTime - 1 do
begin
if Random < _chance then
Exit(True);
end;
Result := False;
end;
end.
|
(**************************************************************)
(* Programmname : MAINMENU.PAS V1.8 *)
(* Programmautor : Michael Rippl *)
(* Compiler : Quick Pascal V1.0 *)
(* Inhalt : Hauptmenย des Kopierprogramms Venus V2.1 *)
(* Bemerkung : - *)
(* Letzte ยnderung : 08-Mar-1991 *)
(**************************************************************)
UNIT MainMenu;
INTERFACE
TYPE MenuSelections = (SingleDrive, CylinderCopy, DualDrive, MultipleCopy,
ImageToHd, RestoreImage, QuitVenus, MemoryUsage,
ErrorTrials, AdjustDisk, SystemInfo, MemorySizes,
DiskInfo, VenusInfo, DosShell, ChangeColor, SaveConfig);
(* Diese Funktion ist verantwortlich fยr das Hauptmenย von Venus *)
FUNCTION DoMainMenu : MenuSelections;
IMPLEMENTATION
USES KeyMouse, Primitiv, Windows, VenColor; (* Units einbinden *)
(* Diese Funktion ist verantwortlich fยr das Hauptmenย von Venus *)
FUNCTION DoMainMenu : MenuSelections;
CONST NoMenu = 0; (* Kein Menย ist aktiv *)
NoMenuPoint = 1; (* Kein Menยpunkt aktiv *)
MenuDiskCopy = 8; (* Menย DiskCopy *)
MenuParameter = 9; (* Menย Parameter *)
MenuInformation = 10; (* Menย Information *)
MenuTools = 11; (* Menย Tools *)
CopySingleDrive = 20; (* Menยpunkte DiskCopy *)
CopyMultiple = 21;
CopyDualDrive = 22;
CopyExitVenus = 23;
CopyImageToHd = 24;
CopyRestoreImage = 25;
CopyCylinder = 26;
ParamMemory = 30; (* Menยpunkte Parameter *)
ParamErrTrials = 31;
ParamTarget = 32;
InfoSystem = 40; (* Menยpunkte Information *)
InfoMemorySizes = 41;
InfoVenusCopy = 42;
InfoDiskette = 43;
ToolsDosShell = 50; (* Menยpunkte Tools *)
ToolsChangeColor = 51;
ToolsSaveConfig = 52;
VAR QuitMenu, (* Menยauswahl ist zu Ende *)
AltKeyDown, (* Alt Taste ist gedrยckt *)
ClickLeftDown : BOOLEAN; (* Linke Maustaste unten *)
KindOfChoice : MenuSelections; (* Punkt der Menยauswahl *)
NewEvent : Event; (* Ereignis eingetroffen *)
ActualMenuId, (* Aktuelles Auswahlfeld *)
ActualMenuPoint : BYTE; (* Aktueller Menยpunkt *)
HotKeyRed : Colors; (* Rote HotKey Tasten *)
(* Diese Prozedur zeichnet das Menย DiskCopy *)
PROCEDURE DrawDiskCopy;
VAR DiskCopyMenu : Window;
WindowHandle : pWindow;
BEGIN
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
PutString(16, 0, ' DISKCOPY ', cCyan, cBlack);
PutChar(17, 0, 'D', HotKeyRed, cBlack);
WITH DiskCopyMenu DO (* Fensterdaten eintragen *)
BEGIN
LeftEdge := 15;
TopEdge := 1;
Width := 27;
Height := 10;
DetailPen := cBlack;
BlockPen := cCyan;
Flags := [Single, Shadow, Simple];
END;
WindowHandle := OpenWindow(DiskCopyMenu); (* Menยfenster ยffnen *)
PutString(17, 2, 'Single Drive Copy F2', cBlack, cCyan);
PutString(17, 3, 'Multiple Copy F3', cBlack, cCyan);
PutString(17, 4, 'Cylinder Copy F4', cBlack, cCyan);
PutString(17, 5, 'Image To Harddisk F5', cBlack, cCyan);
PutString(17, 6, 'Restore Disk Image F6', cBlack, cCyan);
PutString(17, 7, 'Dual Drive Copy F7', cBlack, cCyan);
PutString(17, 9, 'Exit Venus Program ESC', cBlack, cCyan);
PutChar(17, 2, 'S', cYellow, cCyan);
PutChar(17, 3, 'M', cYellow, cCyan);
PutChar(17, 4, 'C', cYellow, cCyan);
PutChar(17, 5, 'I', cYellow, cCyan);
PutChar(17, 6, 'R', cYellow, cCyan);
PutChar(17, 7, 'D', cYellow, cCyan);
PutString(15, 8, 'รรรรรรรรรรรรรรรรรรรรรรรรรรยด', cBlack, cCyan);
PutChar(17, 9, 'E', cYellow, cCyan);
CreateArea(16, 2, 25, 1, CopySingleDrive); (* Menยpunktfelder anlegen *)
CreateArea(16, 3, 25, 1, CopyMultiple);
CreateArea(16, 4, 25, 1, CopyCylinder);
CreateArea(16, 5, 25, 1, CopyImageToHd);
CreateArea(16, 6, 25, 1, CopyRestoreImage);
CreateArea(16, 7, 25, 1, CopyDualDrive);
CreateArea(16, 9, 25, 1, CopyExitVenus);
ActualMenuId := MenuDiskCopy; (* Auswahlfeld DiskCopy *)
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
END; (* DrawDiskCopy *)
(* Diese Prozedur zeichnet das Menย Parameter *)
PROCEDURE DrawParameter;
VAR ParameterMenu : Window;
WindowHandle : pWindow;
BEGIN
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
PutString(28, 0, ' PARAMETER ', cCyan, cBlack);
PutChar(29, 0, 'P', HotKeyRed, cBlack);
WITH ParameterMenu DO (* Fensterdaten eintragen *)
BEGIN
LeftEdge := 27;
TopEdge := 1;
Width := 27;
Height := 5;
DetailPen := cBlack;
BlockPen := cCyan;
Flags := [Single, Shadow, Simple];
END;
WindowHandle := OpenWindow(ParameterMenu); (* Menยfenster ยffnen *)
PutString(29, 2, 'Define Memory Usage F9', cBlack, cCyan);
PutString(29, 3, 'Set Error Trials', cBlack, cCyan);
PutString(29, 4, 'Adjust Target Disk F8', cBlack, cCyan);
PutChar(29, 2, 'D', cYellow, cCyan);
PutChar(29, 3, 'S', cYellow, cCyan);
PutChar(29, 4, 'A', cYellow, cCyan);
CreateArea(28, 2, 25, 1, ParamMemory); (* Menยpunktfelder anlegen *)
CreateArea(28, 3, 25, 1, ParamErrTrials);
CreateArea(28, 4, 25, 1, ParamTarget);
ActualMenuId := MenuParameter; (* Auswahlfeld Parameter *)
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
END; (* DrawParameter *)
(* Diese Prozedur zeichnet das Menย Information *)
PROCEDURE DrawInformation;
VAR InformationMenu : Window;
WindowHandle : pWindow;
BEGIN
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
PutString(41, 0, ' INFORMATION ', cCyan, cBlack);
PutChar(42, 0, 'I', HotKeyRed, cBlack);
WITH InformationMenu DO (* Fensterdaten eintragen *)
BEGIN
LeftEdge := 40;
TopEdge := 1;
Width := 27;
Height := 7;
DetailPen := cBlack;
BlockPen := cCyan;
Flags := [Single, Shadow, Simple];
END;
WindowHandle := OpenWindow(InformationMenu); (* Menยfenster ยffnen *)
PutString(42, 2, 'System Information', cBlack, cCyan);
PutString(42, 3, 'Memory Sizes F11', cBlack, cCyan);
PutString(42, 4, 'Disk Information F12', cBlack, cCyan);
PutString(42, 6, 'Venus DiskCopy V2.1', cBlack, cCyan);
PutChar(42, 2, 'S', cYellow, cCyan);
PutChar(42, 3, 'M', cYellow, cCyan);
PutChar(42, 4, 'D', cYellow, cCyan);
PutString(40, 5, 'รรรรรรรรรรรรรรรรรรรรรรรรรรยด', cBlack, cCyan);
PutChar(42, 6, 'V', cYellow, cCyan);
CreateArea(41, 2, 25, 1, InfoSystem); (* Menยpunktfelder anlegen *)
CreateArea(41, 3, 25, 1, InfoMemorySizes);
CreateArea(41, 4, 25, 1, InfoDiskette);
CreateArea(41, 6, 25, 1, InfoVenusCopy);
ActualMenuId := MenuInformation; (* Auswahlfeld Information *)
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
END; (* DrawInformation *)
(* Diese Prozedur zeichnet das Menย Tools *)
PROCEDURE DrawTools;
VAR ToolMenu : Window;
WindowHandle : pWindow;
BEGIN
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
PutString(56, 0, ' TOOLS ', cCyan, cBlack);
PutChar(57, 0, 'T', HotKeyRed, cBlack);
WITH ToolMenu DO (* Fensterdaten eintragen *)
BEGIN
LeftEdge := 52;
TopEdge := 1;
Width := 25;
Height := 6;
DetailPen := cBlack;
BlockPen := cCyan;
Flags := [Single, Shadow, Simple];
END;
WindowHandle := OpenWindow(ToolMenu); (* Menยfenster ยffnen *)
PutString(54, 2, 'Virtual Dos Shell F1', cBlack, cCyan);
PutString(54, 3, 'Change Colors', cBlack, cCyan);
PutString(54, 5, 'Save Configuration', cBlack, cCyan);
PutChar(54, 2, 'V', cYellow, cCyan);
PutChar(54, 3, 'C', cYellow, cCyan);
PutString(52, 4, 'รรรรรรรรรรรรรรรรรรรรรรรรยด', cBlack, cCyan);
PutChar(54, 5, 'S', cYellow, cCyan);
CreateArea(53, 2, 23, 1, ToolsDosShell); (* Menยpunktfelder anlegen *)
CreateArea(53, 3, 23, 1, ToolsChangeColor);
CreateArea(53, 5, 23, 1, ToolsSaveConfig);
ActualMenuId := MenuTools; (* Auswahlfeld Tools *)
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
END; (* DrawTools *)
(* Diese Prozedur schlieรกt ein bestimmtes Menยfenster *)
PROCEDURE CloseMenu;
VAR WindowStatus : BOOLEAN;
BEGIN
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
WindowStatus := CloseWindow; (* Menยfenster schlieรกen *)
CASE ActualMenuId OF
MenuDiskCopy : (* Auswahlfeld DiskCopy *)
BEGIN
PutString(16, 0, ' DISKCOPY ', cBlack, cCyan);
DeleteArea(CopySingleDrive); (* Menยpunktfelder lยschen *)
DeleteArea(CopyMultiple);
DeleteArea(CopyCylinder);
DeleteArea(CopyImageToHd);
DeleteArea(CopyRestoreImage);
DeleteArea(CopyDualDrive);
DeleteArea(CopyExitVenus);
END;
MenuParameter : (* Auswahlfeld Parameter *)
BEGIN
PutString(28, 0, ' PARAMETER ', cBlack, cCyan);
DeleteArea(ParamMemory); (* Menยpunktfelder lยschen *)
DeleteArea(ParamErrTrials);
DeleteArea(ParamTarget);
END;
MenuInformation : (* Auswahlfeld Information *)
BEGIN
PutString(41, 0, ' INFORMATION ', cBlack, cCyan);
DeleteArea(InfoSystem); (* Menยpunktfelder lยschen *)
DeleteArea(InfoMemorySizes);
DeleteArea(InfoDiskette);
DeleteArea(InfoVenusCopy);
END;
MenuTools : (* Auswahlfeld Tools *)
BEGIN
PutString(56, 0, ' TOOLS ', cBlack, cCyan);
DeleteArea(ToolsDosShell); (* Menยpunktfelder lยschen *)
DeleteArea(ToolsChangeColor);
DeleteArea(ToolsSaveConfig);
END;
END;
ActualMenuId := NoMenu; (* Kein Menย ist aktiv *)
ActualMenuPoint := NoMenuPoint; (* Kein Menยpunkt aktiv *)
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
END; (* CloseMenu *)
(* Diese Prozedur markiert einen Menยpunkt als aktiv *)
PROCEDURE ActiveMenuPoint(MenuPointId : BYTE);
VAR ActiveColor, (* Buchstabe hervorgehoben *)
NormalColor : BYTE; (* Normale Buchstabenfarbe *)
BEGIN
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
ActiveColor := Ord(cBlack) SHL 4 OR Ord(HotKeyRed);
NormalColor := Ord(cBlack) SHL 4 OR Ord(cCyan);
CASE MenuPointId OF
CopySingleDrive :
BEGIN
PutAttributes(16, 2, 25, 1, NormalColor);
PutAttributes(17, 2, 1, 1, ActiveColor);
END;
CopyMultiple :
BEGIN
PutAttributes(16, 3, 25, 1, NormalColor);
PutAttributes(17, 3, 1, 1, ActiveColor);
END;
CopyCylinder :
BEGIN
PutAttributes(16, 4, 25, 1, NormalColor);
PutAttributes(17, 4, 1, 1, ActiveColor);
END;
CopyImageToHd :
BEGIN
PutAttributes(16, 5, 25, 1, NormalColor);
PutAttributes(17, 5, 1, 1, ActiveColor);
END;
CopyRestoreImage :
BEGIN
PutAttributes(16, 6, 25, 1, NormalColor);
PutAttributes(17, 6, 1, 1, ActiveColor);
END;
CopyDualDrive :
BEGIN
PutAttributes(16, 7, 25, 1, NormalColor);
PutAttributes(17, 7, 1, 1, ActiveColor);
END;
CopyExitVenus :
BEGIN
PutAttributes(16, 9, 25, 1, NormalColor);
PutAttributes(17, 9, 1, 1, ActiveColor);
END;
ParamMemory :
BEGIN
PutAttributes(28, 2, 25, 1, NormalColor);
PutAttributes(29, 2, 1, 1, ActiveColor);
END;
ParamErrTrials :
BEGIN
PutAttributes(28, 3, 25, 1, NormalColor);
PutAttributes(29, 3, 1, 1, ActiveColor);
END;
ParamTarget :
BEGIN
PutAttributes(28, 4, 25, 1, NormalColor);
PutAttributes(29, 4, 1, 1, ActiveColor);
END;
InfoSystem :
BEGIN
PutAttributes(41, 2, 25, 1, NormalColor);
PutAttributes(42, 2, 1, 1, ActiveColor);
END;
InfoMemorySizes :
BEGIN
PutAttributes(41, 3, 25, 1, NormalColor);
PutAttributes(42, 3, 1, 1, ActiveColor);
END;
InfoDiskette :
BEGIN
PutAttributes(41, 4, 25, 1, NormalColor);
PutAttributes(42, 4, 1, 1, ActiveColor);
END;
InfoVenusCopy :
BEGIN
PutAttributes(41, 6, 25, 1, NormalColor);
PutAttributes(42, 6, 1, 1, ActiveColor);
END;
ToolsDosShell :
BEGIN
PutAttributes(53, 2, 23, 1, NormalColor);
PutAttributes(54, 2, 1, 1, ActiveColor);
END;
ToolsChangeColor :
BEGIN
PutAttributes(53, 3, 23, 1, NormalColor);
PutAttributes(54, 3, 1, 1, ActiveColor);
END;
ToolsSaveConfig :
BEGIN
PutAttributes(53, 5, 23, 1, NormalColor);
PutAttributes(54, 5, 1, 1, ActiveColor);
END;
END;
ActualMenuPoint := MenuPointId; (* Aktueller Menยpunkt *)
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
END; (* ActiveMenuPoint *)
(* Diese Prozedur markiert einen Menยpunkt als nicht aktiv *)
PROCEDURE ReActiveMenuPoint;
VAR ActiveColor, (* Buchstabe hervorgehoben *)
NormalColor : BYTE; (* Normale Buchstabenfarbe *)
BEGIN
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
ActiveColor := Ord(cCyan) SHL 4 OR Ord(cYellow);
NormalColor := Ord(cCyan) SHL 4 OR Ord(cBlack);
CASE ActualMenuPoint OF
CopySingleDrive :
BEGIN
PutAttributes(16, 2, 25, 1, NormalColor);
PutAttributes(17, 2, 1, 1, ActiveColor);
END;
CopyMultiple :
BEGIN
PutAttributes(16, 3, 25, 1, NormalColor);
PutAttributes(17, 3, 1, 1, ActiveColor);
END;
CopyCylinder :
BEGIN
PutAttributes(16, 4, 25, 1, NormalColor);
PutAttributes(17, 4, 1, 1, ActiveColor);
END;
CopyImageToHd :
BEGIN
PutAttributes(16, 5, 25, 1, NormalColor);
PutAttributes(17, 5, 1, 1, ActiveColor);
END;
CopyRestoreImage :
BEGIN
PutAttributes(16, 6, 25, 1, NormalColor);
PutAttributes(17, 6, 1, 1, ActiveColor);
END;
CopyDualDrive :
BEGIN
PutAttributes(16, 7, 25, 1, NormalColor);
PutAttributes(17, 7, 1, 1, ActiveColor);
END;
CopyExitVenus :
BEGIN
PutAttributes(16, 9, 25, 1, NormalColor);
PutAttributes(17, 9, 1, 1, ActiveColor);
END;
ParamMemory :
BEGIN
PutAttributes(28, 2, 25, 1, NormalColor);
PutAttributes(29, 2, 1, 1, ActiveColor);
END;
ParamErrTrials :
BEGIN
PutAttributes(28, 3, 25, 1, NormalColor);
PutAttributes(29, 3, 1, 1, ActiveColor);
END;
ParamTarget :
BEGIN
PutAttributes(28, 4, 25, 1, NormalColor);
PutAttributes(29, 4, 1, 1, ActiveColor);
END;
InfoSystem :
BEGIN
PutAttributes(41, 2, 25, 1, NormalColor);
PutAttributes(42, 2, 1, 1, ActiveColor);
END;
InfoMemorySizes :
BEGIN
PutAttributes(41, 3, 25, 1, NormalColor);
PutAttributes(42, 3, 1, 1, ActiveColor);
END;
InfoDiskette :
BEGIN
PutAttributes(41, 4, 25, 1, NormalColor);
PutAttributes(42, 4, 1, 1, ActiveColor);
END;
InfoVenusCopy :
BEGIN
PutAttributes(41, 6, 25, 1, NormalColor);
PutAttributes(42, 6, 1, 1, ActiveColor);
END;
ToolsDosShell :
BEGIN
PutAttributes(53, 2, 23, 1, NormalColor);
PutAttributes(54, 2, 1, 1, ActiveColor);
END;
ToolsChangeColor :
BEGIN
PutAttributes(53, 3, 23, 1, NormalColor);
PutAttributes(54, 3, 1, 1, ActiveColor);
END;
ToolsSaveConfig :
BEGIN
PutAttributes(53, 5, 23, 1, NormalColor);
PutAttributes(54, 5, 1, 1, ActiveColor);
END;
END;
ActualMenuPoint := NoMenuPoint; (* Kein Menยpunkt aktiv *)
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
END; (* ReActiveMenuPoint *)
(* Diese Prozedur wird aufgerufen, falls die linke Maustaste gedrยckt wird *)
PROCEDURE MouseLeftDown(NewEvent : Event);
BEGIN
IF NOT AltKeyDown THEN (* Kein Alt gedrยckt *)
BEGIN
ClickLeftDown := TRUE; (* Linke Taste gedrยckt *)
CASE NewEvent.AreaId OF
MenuDiskCopy : (* Auswahlfeld DiskCopy *)
BEGIN
IF (ActualMenuId <> NoMenu) AND
(ActualMenuId <> MenuDiskCopy) THEN
CloseMenu; (* Aktuelles Menufenster *)
IF ActualMenuId = NoMenu THEN
DrawDiskCopy; (* Neues Menu zeichnen *)
END;
MenuParameter : (* Auswahlfeld Parameter *)
BEGIN
IF (ActualMenuId <> NoMenu) AND
(ActualMenuId <> MenuParameter) THEN
CloseMenu; (* Aktuelles Menยfenster *)
IF ActualMenuId = NoMenu THEN
DrawParameter; (* Neues Menu zeichnen *)
END;
MenuInformation : (* Auswahlfeld Information *)
BEGIN
IF (ActualMenuId <> NoMenu) AND
(ActualMenuId <> MenuInformation) THEN
CloseMenu; (* Aktuelles Menยfenster *)
IF ActualMenuId = NoMenu THEN
DrawInformation; (* Neues Menu zeichnen *)
END;
MenuTools : (* Auswahlfeld Tools *)
BEGIN
IF (ActualMenuId <> NoMenu) AND
(ActualMenuId <> MenuTools) THEN
CloseMenu; (* Aktuelles Menยfenster *)
IF ActualMenuId = NoMenu THEN
DrawTools; (* Neues Menu zeichnen *)
END;
CopySingleDrive, CopyMultiple, CopyCylinder, CopyImageToHd,
CopyRestoreImage, CopyDualDrive, CopyExitVenus, ParamMemory,
ParamErrTrials, ParamTarget, InfoSystem, InfoMemorySizes,
InfoDiskette, InfoVenusCopy, ToolsDosShell, ToolsChangeColor,
ToolsSaveConfig :
BEGIN
ReActiveMenuPoint; (* Menยpunkt reaktivieren *)
ActiveMenuPoint(NewEvent.AreaId); (* Neuer aktiver Menยpunkt *)
END;
ELSE (* Kein sinnvoller Click *)
ClickLeftDown := FALSE;
IF ActualMenuId <> NoMenu THEN
CloseMenu; (* Aktuelles Menยfenster *)
END;
END;
END; (* MouseLeftDown *)
(* Diese Prozedur wird aufgerufen, falls die linke Maustaste losgelassen wird *)
PROCEDURE MouseLeftUp(NewEvent : Event);
BEGIN
IF ClickLeftDown THEN (* Sinnvoller Maus-Click *)
BEGIN
ClickLeftDown := FALSE; (* Linke Maustaste oben *)
CASE NewEvent.AreaId OF
MenuDiskCopy : (* Auswahlfeld DiskCopy *)
BEGIN
IF ActualMenuPoint = NoMenuPoint THEN (* Kein Menยpunkt aktiv *)
ActiveMenuPoint(CopySingleDrive); (* Menยpunkt aktivieren *)
END;
MenuParameter : (* Auswahlfeld Parameter *)
BEGIN
IF ActualMenuPoint = NoMenuPoint THEN (* Kein Menยpunkt aktiv *)
ActiveMenuPoint(ParamMemory); (* Menยpunkt aktivieren *)
END;
MenuInformation : (* Auswahlfeld Information *)
BEGIN
IF ActualMenuPoint = NoMenuPoint THEN (* Kein Menยpunkt aktiv *)
ActiveMenuPoint(InfoSystem); (* Menยpunkt aktivieren *)
END;
MenuTools : (* Auswahlfeld Tools *)
BEGIN
IF ActualMenuPoint = NoMenuPoint THEN (* Kein Menยpunkt aktiv *)
ActiveMenuPoint(ToolsDosShell); (* Menยpunkt aktivieren *)
END;
CopySingleDrive :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := SingleDrive;
QuitMenu := TRUE;
END;
CopyMultiple :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := MultipleCopy;
QuitMenu := TRUE;
END;
CopyCylinder :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := CylinderCopy;
QuitMenu := TRUE;
END;
CopyImageToHd :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := ImageToHd;
QuitMenu := TRUE;
END;
CopyRestoreImage :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := RestoreImage;
QuitMenu := TRUE;
END;
CopyDualDrive :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := DualDrive;
QuitMenu := TRUE;
END;
CopyExitVenus :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := QuitVenus;
QuitMenu := TRUE;
END;
ParamMemory :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := MemoryUsage;
QuitMenu := TRUE;
END;
ParamErrTrials :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := ErrorTrials;
QuitMenu := TRUE;
END;
ParamTarget :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := AdjustDisk;
QuitMenu := TRUE;
END;
InfoSystem :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := SystemInfo;
QuitMenu := TRUE;
END;
InfoMemorySizes :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := MemorySizes;
QuitMenu := TRUE;
END;
InfoDiskette :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := DiskInfo;
QuitMenu := TRUE;
END;
InfoVenusCopy :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := VenusInfo;
QuitMenu := TRUE;
END;
ToolsDosShell :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := DosShell;
QuitMenu := TRUE;
END;
ToolsChangeColor :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := ChangeColor;
QuitMenu := TRUE;
END;
ToolsSaveConfig :
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := SaveConfig;
QuitMenu := TRUE;
END;
ELSE (* Kein sinnvoller Click *)
IF ActualMenuId <> NoMenu THEN
CloseMenu; (* Aktuelles Menยfenster *)
END;
END;
END; (* MouseLeftUp *)
(* Diese Prozedur wird aufgerufen, falls die Maus bewegt wird *)
PROCEDURE MouseMove(NewEvent : Event);
BEGIN
IF ClickLeftDown THEN (* Linke Taste gedrยckt *)
BEGIN
CASE NewEvent.AreaId OF
MenuDiskCopy :
BEGIN
IF ActualMenuId <> MenuDiskCopy THEN (* Neuer Menยpunkt ist da *)
BEGIN
CloseMenu; (* Altes Menยfenster zu *)
DrawDiskCopy; (* Neues Menยfenster offen *)
END;
END;
MenuParameter :
BEGIN
IF ActualMenuId <> MenuParameter THEN (* Neuer Menยpunkt ist da *)
BEGIN
CloseMenu; (* Altes Menยfenster zu *)
DrawParameter; (* Neues Menยfenster offen *)
END;
END;
MenuInformation :
BEGIN
IF ActualMenuId <> MenuInformation THEN(* Neuer Menยpunkt ist da *)
BEGIN
CloseMenu; (* Altes Menยfenster zu *)
DrawInformation; (* Neues Menยfenster offen *)
END;
END;
MenuTools :
BEGIN
IF ActualMenuId <> MenuTools THEN (* Neuer Menยpunkt ist da *)
BEGIN
CloseMenu; (* Altes Menยfenster zu *)
DrawTools; (* Neues Menยfenster offen *)
END;
END;
CopySingleDrive, CopyMultiple, CopyCylinder, CopyImageToHd,
CopyRestoreImage, CopyDualDrive, CopyExitVenus, ParamMemory,
ParamErrTrials, ParamTarget, InfoSystem, InfoMemorySizes,
InfoDiskette, InfoVenusCopy, ToolsDosShell, ToolsChangeColor,
ToolsSaveConfig :
BEGIN
IF ActualMenuPoint <> NoMenuPoint THEN
ReActiveMenuPoint; (* Aktueller Menยpunkt *)
ActiveMenuPoint(NewEvent.AreaId);
END;
ELSE (* Kein sinnvoller Move *)
IF ActualMenuPoint <> NoMenuPoint THEN
ReActiveMenuPoint; (* Aktueller Menยpunkt *)
END;
END;
END; (* MouseMove *)
(* Diese Prozedur wird aufgerufen, wenn die ALT Taste betยtigt wird *)
PROCEDURE DoAltKey(NewEvent : Event);
BEGIN
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
IF NewEvent.ScanCode = 56 THEN (* Alt niedergedrยckt *)
BEGIN
IF ActualMenuId = NoMenu THEN (* Es ist kein Menย aktiv *)
BEGIN
AltKeyDown := TRUE; (* Alt Taste ist gedrยckt *)
PutChar(17, 0, 'D', HotKeyRed, cCyan);
PutChar(29, 0, 'P', HotKeyRed, cCyan);
PutChar(42, 0, 'I', HotKeyRed, cCyan);
PutChar(57, 0, 'T', HotKeyRed, cCyan);
END;
END
ELSE (* Alt losgelassen *)
BEGIN
IF AltKeyDown THEN (* Alt Taste war gedrยckt *)
BEGIN
AltKeyDown := FALSE; (* Alt nicht gedrยckt *)
IF ActualMenuId <> MenuDiskCopy THEN
PutChar(17, 0, 'D', cBlack, cCyan);
IF ActualMenuId <> MenuParameter THEN
PutChar(29, 0, 'P', cBlack, cCyan);
IF ActualMenuId <> MenuInformation THEN
PutChar(42, 0, 'I', cBlack, cCyan);
IF ActualMenuId <> MenuTools THEN
PutChar(57, 0, 'T', cBlack, cCyan);
END;
END;
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
END; (* DoAltKey *)
(* Diese Prozedur wird aufgerufen, wenn ALT + D, P, I oder T gedrยckt wurde *)
PROCEDURE DoAltDPITKey(NewEvent : Event);
BEGIN
CASE NewEvent.ScanCode OF (* Eingabe unterscheiden *)
32 : (* ScanCode der Taste D *)
BEGIN
DrawDiskCopy; (* Auswahlfeld DiskCopy *)
ActiveMenuPoint(CopySingleDrive); (* Menยpunkt aktivieren *)
END;
25 : (* ScanCode der Taste P *)
BEGIN
DrawParameter; (* Auswahlfeld Parameter *)
ActiveMenuPoint(ParamMemory); (* Menยpunkt aktivieren *)
END;
23 : (* ScanCode der Taste I *)
BEGIN
DrawInformation; (* Auswahlfeld Information *)
ActiveMenuPoint(InfoSystem); (* Menยpunkt aktivieren *)
END;
20 : (* ScanCode der Taste T *)
BEGIN
DrawTools; (* Auswahlfeld Tools *)
ActiveMenuPoint(ToolsDosShell); (* Menยpunkt aktivieren *)
END;
END;
END; (* DoAltDPITKey *)
(* Diese Prozedur wird aufgerufen, wenn per Taste ein Menยpunkt gewยhlt wird *)
PROCEDURE DoMenuKey(NewEvent : Event);
BEGIN
CASE ActualMenuId OF (* Menย unterscheiden *)
MenuDiskCopy : (* Auswahlfeld DiskCopy *)
BEGIN
CASE NewEvent.ScanCode OF (* Taste unterscheiden *)
31 : (* ScanCode der Taste S *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := SingleDrive;
QuitMenu := TRUE;
END;
50 : (* ScanCode der Taste M *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := MultipleCopy;
QuitMenu := TRUE;
END;
23 : (* ScanCode der Taste I *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := ImageToHd;
QuitMenu := TRUE;
END;
46 : (* ScanCode der Taste C *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := CylinderCopy;
QuitMenu := TRUE;
END;
19 : (* ScanCode der Taste R *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := RestoreImage;
QuitMenu := TRUE;
END;
32 : (* ScanCode der Taste D *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := DualDrive;
QuitMenu := TRUE;
END;
18 : (* ScanCode der Taste E *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := QuitVenus;
QuitMenu := TRUE;
END;
ELSE ; (* Eingabe ignorieren *)
END;
END;
MenuParameter : (* Auswahlfeld Parameter *)
BEGIN
CASE NewEvent.ScanCode OF (* Taste unterscheiden *)
32 : (* ScanCode der Taste D *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := MemoryUsage;
QuitMenu := TRUE;
END;
31 : (* ScanCode der Taste S *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := ErrorTrials;
QuitMenu := TRUE;
END;
30 : (* ScanCode der Taste A *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := AdjustDisk;
QuitMenu := TRUE;
END;
ELSE ; (* Eingabe ignorieren *)
END;
END;
MenuInformation : (* Auswahlfeld Information *)
BEGIN
CASE NewEvent.ScanCode OF (* Taste unterscheiden *)
31 : (* ScanCode der Taste S *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := SystemInfo;
QuitMenu := TRUE;
END;
50 : (* ScanCode der Taste M *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := MemorySizes;
QuitMenu := TRUE;
END;
32 : (* ScanCode der Taste D *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := DiskInfo;
QuitMenu := TRUE;
END;
47 : (* ScanCode der Taste V *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := VenusInfo;
QuitMenu := TRUE;
END;
ELSE ; (* Eingabe ignorieren *)
END;
END;
MenuTools : (* Auswahlfeld Tools *)
BEGIN
CASE NewEvent.ScanCode OF (* Taste unterscheiden *)
47 : (* ScanCode der Taste V *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := DosShell;
QuitMenu := TRUE;
END;
46 : (* ScanCode der Taste C *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := ChangeColor;
QuitMenu := TRUE;
END;
31 : (* ScanCode der Taste S *)
BEGIN
CloseMenu; (* Aktuelles Menยfenster *)
KindOfChoice := SaveConfig;
QuitMenu := TRUE;
END;
ELSE ; (* Eingabe ignorieren *)
END;
END;
END;
END; (* DoMenuKey *)
(* Diese Prozedur wird aufgerufen, wenn Cursor Left oder Right gedrยckt wird *)
PROCEDURE DoLeftRightKey(NewEvent : Event);
VAR RememberMenuId : BYTE; (* Aktives Menย merken *)
BEGIN
RememberMenuId := ActualMenuId;
CloseMenu; (* Aktuelles Menยfenster *)
IF NewEvent.ScanCode = 75 THEN (* ScanCode Cursor Left *)
BEGIN
CASE RememberMenuId OF (* Menย unterscheiden *)
MenuDiskCopy : (* Auswahlfeld DiskCopy *)
BEGIN
DrawTools; (* Auswahlfeld Tools *)
ActiveMenuPoint(ToolsDosShell); (* Menยpunkt aktivieren *)
END;
MenuParameter : (* Auswahlfeld Parameter *)
BEGIN
DrawDiskCopy; (* Auswahlfeld DiskCopy *)
ActiveMenuPoint(CopySingleDrive); (* Menยpunkt aktivieren *)
END;
MenuInformation : (* Auswahlfeld Information *)
BEGIN
DrawParameter; (* Auswahlfeld Parameter *)
ActiveMenuPoint(ParamMemory); (* Menยpunkt aktivieren *)
END;
MenuTools : (* Auswahlfeld Tools *)
BEGIN
DrawInformation; (* Auswahlfeld Information *)
ActiveMenuPoint(InfoSystem); (* Menยpunkt aktivieren *)
END;
END;
END
ELSE (* ScanCode Cursor Right *)
BEGIN
CASE RememberMenuId OF (* Menย unterscheiden *)
MenuDiskCopy : (* Auswahlfeld DiskCopy *)
BEGIN
DrawParameter; (* Auswahlfeld Parameter *)
ActiveMenuPoint(ParamMemory); (* Menยpunkt aktivieren *)
END;
MenuParameter : (* Auswahlfeld Parameter *)
BEGIN
DrawInformation; (* Auswahlfeld Information *)
ActiveMenuPoint(InfoSystem); (* Menยpunkt aktivieren *)
END;
MenuInformation : (* Auswahlfeld Information *)
BEGIN
DrawTools; (* Auswahlfeld Tools *)
ActiveMenuPoint(ToolsDosShell); (* Menยpunkt aktivieren *)
END;
MenuTools : (* Auswahlfeld Tools *)
BEGIN
DrawDiskCopy; (* Auswahlfeld DiskCopy *)
ActiveMenuPoint(CopySingleDrive); (* Menยpunkt aktivieren *)
END;
END;
END;
END; (* DoLeftRightKey *)
(* Diese Prozedur wird aufgerufen, wenn Cursor Up oder Down gedrยckt wird *)
PROCEDURE DoUpDownKey(NewEvent : Event);
VAR RememberMenuPoint : BYTE; (* Menยpunkt merken *)
BEGIN
RememberMenuPoint := ActualMenuPoint; (* Aktiver Menยpunkt *)
ReActiveMenuPoint; (* Alter Menยpunkt weg *)
IF NewEvent.ScanCode = 72 THEN (* ScanCode Cursor Up *)
BEGIN
CASE RememberMenuPoint OF (* Menยpunkt unterscheiden *)
CopySingleDrive : ActiveMenuPoint(CopyExitVenus);
CopyMultiple : ActiveMenuPoint(CopySingleDrive);
CopyCylinder : ActiveMenuPoint(CopyMultiple);
CopyImageToHd : ActiveMenuPoint(CopyCylinder);
CopyRestoreImage : ActiveMenuPoint(CopyImageToHd);
CopyDualDrive : ActiveMenuPoint(CopyRestoreImage);
CopyExitVenus : ActiveMenuPoint(CopyDualDrive);
ParamMemory : ActiveMenuPoint(ParamTarget);
ParamErrTrials : ActiveMenuPoint(ParamMemory);
ParamTarget : ActiveMenuPoint(ParamErrTrials);
InfoSystem : ActiveMenuPoint(InfoVenusCopy);
InfoMemorySizes : ActiveMenuPoint(InfoSystem);
InfoDiskette : ActiveMenuPoint(InfoMemorySizes);
InfoVenusCopy : ActiveMenuPoint(InfoDiskette);
ToolsDosShell : ActiveMenuPoint(ToolsSaveConfig);
ToolsChangeColor : ActiveMenuPoint(ToolsDosShell);
ToolsSaveConfig : ActiveMenuPoint(ToolsChangeColor);
END;
END
ELSE (* ScanCode Cursor Down *)
BEGIN
CASE RememberMenuPoint OF (* Menยpunkt unterscheiden *)
CopySingleDrive : ActiveMenuPoint(CopyMultiple);
CopyMultiple : ActiveMenuPoint(CopyCylinder);
CopyCylinder : ActiveMenuPoint(CopyImageToHd);
CopyImageToHd : ActiveMenuPoint(CopyRestoreImage);
CopyRestoreImage : ActiveMenuPoint(CopyDualDrive);
CopyDualDrive : ActiveMenuPoint(CopyExitVenus);
CopyExitVenus : ActiveMenuPoint(CopySingleDrive);
ParamMemory : ActiveMenuPoint(ParamErrTrials);
ParamErrTrials : ActiveMenuPoint(ParamTarget);
ParamTarget : ActiveMenuPoint(ParamMemory);
InfoSystem : ActiveMenuPoint(InfoMemorySizes);
InfoMemorySizes : ActiveMenuPoint(InfoDiskette);
InfoDiskette : ActiveMenuPoint(InfoVenusCopy);
InfoVenusCopy : ActiveMenuPoint(InfoSystem);
ToolsDosShell : ActiveMenuPoint(ToolsChangeColor);
ToolsChangeColor : ActiveMenuPoint(ToolsSaveConfig);
ToolsSaveConfig : ActiveMenuPoint(ToolsDosShell);
END;
END;
END; (* DoUpDownKey *)
(* Diese Prozedur wird aufgerufen, wenn die RETURN Taste betยtigt wird *)
PROCEDURE DoReturnKey;
VAR RememberMenuPoint : BYTE; (* Menยpunkt merken *)
BEGIN
RememberMenuPoint := ActualMenuPoint; (* Aktiver Menยpunkt *)
CloseMenu; (* Aktuelles Menยfenster *)
QuitMenu := TRUE;
CASE RememberMenuPoint OF (* Menยpunkt unterscheiden *)
CopySingleDrive : KindOfChoice := SingleDrive;
CopyMultiple : KindOfChoice := MultipleCopy;
CopyCylinder : KindOfChoice := CylinderCopy;
CopyImageToHd : KindOfChoice := ImageToHd;
CopyRestoreImage : KindOfChoice := RestoreImage;
CopyDualDrive : KindOfChoice := DualDrive;
CopyExitVenus : KindOfChoice := QuitVenus;
ParamMemory : KindOfChoice := MemoryUsage;
ParamErrTrials : KindOfChoice := ErrorTrials;
ParamTarget : KindOfChoice := AdjustDisk;
InfoSystem : KindOfChoice := SystemInfo;
InfoMemorySizes : KindOfChoice := MemorySizes;
InfoDiskette : KindOfChoice := DiskInfo;
InfoVenusCopy : KindOfChoice := VenusInfo;
ToolsDosShell : KindOfChoice := DosShell;
ToolsChangeColor : KindOfChoice := ChangeColor;
ToolsSaveConfig : KindOfChoice := SaveConfig;
END;
END; (* DoReturnKey *)
BEGIN (* DoMainMenu *)
QuitMenu := FALSE; (* Kein Menยpunkt gewยhlt *)
AltKeyDown := FALSE; (* Alt nicht gedrยckt *)
ClickLeftDown := FALSE; (* Linke Maustaste oben *)
ActualMenuId := NoMenu; (* Kein Menย ist aktiv *)
ActualMenuPoint := NoMenuPoint; (* Kein Menยpunkt aktiv *)
IF ColorGraphic THEN HotKeyRed := cLightRed (* Farbgrafikkarte *)
ELSE HotKeyRed := cYellow; (* Monochromgrafikkarte *)
IF MouseAvail THEN MouseOff; (* Maus ausschalten *)
VideoFill(0, 0, 80, 1, ' ', cBlack, cCyan);
PutString(0, 0, ' SINGLE DRIVE ', cYellow, cRed);
PutString(17, 0, 'DISKCOPY PARAMETER INFORMATION TOOLS',
cBlack, cCyan);
IF MouseAvail THEN MouseOn; (* Maus anschalten *)
CreateArea(16, 0, 10, 1, MenuDiskCopy); (* Auswahlfeld DiskCopy *)
CreateArea(28, 0, 11, 1, MenuParameter); (* Auswahlfeld Parameter *)
CreateArea(41, 0, 13, 1, MenuInformation); (* Auswahlfeld Information *)
CreateArea(56, 0, 7, 1, MenuTools); (* Auswahlfeld Tools *)
REPEAT
GetEvent(NewEvent); (* Auf ein Ereignis warten *)
IF NewEvent.Mouse THEN (* Die Maus wurde benutzt *)
BEGIN
CASE NewEvent.mEvent OF (* Ereignis unterscheiden *)
EventMouseMove : MouseMove(NewEvent);
EventLeftDown : MouseLeftDown(NewEvent);
EventLeftUp : MouseLeftUp(NewEvent);
ELSE ; (* Ereignis ignorieren *)
END;
END
ELSE (* Taste wurde gedrยckt *)
BEGIN
CASE NewEvent.ScanCode OF (* ScanCode unterscheiden *)
56, 184 : DoAltKey(NewEvent); (* Alt Taste betยtigt *)
32, 25, 23, 31, 50, 18, 30, 47, 19, 46, 20 :
BEGIN (* D P I S M E A V R C T *)
IF AltKeyDown AND (ActualMenuId = NoMenu) THEN
DoAltDPITKey(NewEvent)
ELSE IF NOT AltKeyDown AND NOT ClickLeftDown AND
(ActualMenuId <> NoMenu) THEN
DoMenuKey(NewEvent);
END;
1 : (* ScanCode der Taste ESC *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown AND
(ActualMenuId <> NoMenu) THEN CloseMenu
ELSE IF ActualMenuId = NoMenu THEN (* Menย abbrechen *)
BEGIN
KindOfChoice := QuitVenus;
QuitMenu := TRUE;
END;
END;
59 : (* ScanCode der Taste F1 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := DosShell;
QuitMenu := TRUE;
END;
END;
60 : (* ScanCode der Taste F2 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := SingleDrive;
QuitMenu := TRUE;
END;
END;
61 : (* ScanCode der Taste F3 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := MultipleCopy;
QuitMenu := TRUE;
END;
END;
62 : (* ScanCode der Taste F4 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := CylinderCopy;
QuitMenu := TRUE;
END;
END;
63 : (* ScanCode der Taste F5 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := ImageToHd;
QuitMenu := TRUE;
END;
END;
64 : (* ScanCode der Taste F6 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := RestoreImage;
QuitMenu := TRUE;
END;
END;
65 : (* ScanCode der Taste F7 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := DualDrive;
QuitMenu := TRUE;
END;
END;
66 : (* ScanCode der Taste F8 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := AdjustDisk;
QuitMenu := TRUE;
END;
END;
67 : (* ScanCode der Taste F9 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := MemoryUsage;
QuitMenu := TRUE;
END;
END;
68 : (* ScanCode der Taste F10 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown AND
(ActualMenuId = NoMenu) THEN (* Kein Menย ist aktiv *)
BEGIN
DrawDiskCopy;
ActiveMenuPoint(CopySingleDrive);
END;
END;
215 : (* ScanCode der Taste F11 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := MemorySizes;
QuitMenu := TRUE;
END;
END;
216 : (* ScanCode der Taste F12 *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown THEN
BEGIN
IF ActualMenuId <> NoMenu THEN
CloseMenu;
KindOfChoice := DiskInfo;
QuitMenu := TRUE;
END;
END;
75, 77 : (* Curs Left, Curs Right *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown AND
(ActualMenuId <> NoMenu) THEN
DoLeftRightKey(NewEvent);
END;
72, 80 : (* Curs Up, Curs Down *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown AND
(ActualMenuId <> NoMenu) THEN
DoUpDownKey(NewEvent);
END;
28 : (* ScanCode der Taste RET *)
BEGIN
IF NOT AltKeyDown AND NOT ClickLeftDown AND
(ActualMenuPoint <> NoMenuPoint) THEN
DoReturnKey;
END;
ELSE ; (* Eingabe ignorieren *)
END;
END;
UNTIL QuitMenu; (* Benutzer hat gewยhlt *)
DeleteArea(MenuDiskCopy); (* Gadgets entfernen *)
DeleteArea(MenuParameter);
DeleteArea(MenuInformation);
DeleteArea(MenuTools);
DoMainMenu := KindOfChoice; (* Art der Menยauswahl *)
END; (* DoMainMenu *)
END. (* MainMenu *)
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit hashfunctions;
interface
type
THashTableSizeInt = 0..MaxInt;
function Integer32Hash32(const Key: DWord): DWord; inline;
function Integer64Hash32(const Key: QWord): DWord; inline;
function PtrUIntHash32(const Key: PtrUInt): DWord; inline;
function PointerHash32(const Key: Pointer): DWord; inline;
function TMethodHash32(const Key: TMethod): DWord; inline;
function RawByteStringHash32(const Key: RawByteString): DWord; inline;
function AnsiStringHash32(const Key: AnsiString): DWord; inline;
function UTF8StringHash32(const Key: UTF8String): DWord; inline;
implementation
{$IF SIZEOF(DWord) <> 4} {$ERROR DWord must be 32 bits wide.} {$ENDIF}
{$IF SIZEOF(QWord) <> 8} {$ERROR QWord must be 64 bits wide.} {$ENDIF}
uses
sysutils;
function Integer32Hash32(const Key: DWord): DWord;
begin
Assert(SizeOf(DWord) * 8 = 32);
Result := Key;
{ Robert Jenkins 32bit Integer Hash - http://burtleburtle.net/bob/hash/integer.html }
{$PUSH}
{$OVERFLOWCHECKS OFF}
{$RANGECHECKS OFF}
{$HINTS OFF} // because all this intentionally overflows
Result := (Result + $7ed55d16) + (Result shl 12);
Result := (Result xor $c761c23c) xor (Result shr 19);
Result := (Result + $165667b1) + (Result shl 5);
Result := (Result + $d3a2646c) xor (Result shl 9);
Result := (Result + $fd7046c5) + (Result shl 3);
Result := (Result xor $b55a4f09) xor (Result shr 16);
{$POP}
end;
function Integer64Hash32(const Key: QWord): DWord;
var
Scratch: QWord;
begin
Assert(SizeOf(QWord) * 8 = 64);
{$PUSH}
{$OVERFLOWCHECKS OFF}
Scratch := Key;
{ Thomas Wang's hash6432shift - http://www.concentric.net/~Ttwang/tech/inthash.htm }
Scratch := (not Scratch) + (Scratch shl 18);
Scratch := Scratch xor (Scratch shr 31);
Scratch := Scratch * 21;
Scratch := Scratch xor (Scratch shr 11);
Scratch := Scratch + (Scratch shl 6);
Scratch := Scratch xor (Scratch shr 22);
Result := DWord(Scratch);
{$POP}
end;
function PtrUIntHash32(const Key: PtrUInt): DWord;
begin
{$PUSH}
{$OVERFLOWCHECKS OFF}
{$IF SizeOf(PtrUInt) = SizeOf(DWord) }
Result := Integer32Hash32(Key);
{$ELSEIF SizeOf(PtrUInt) = SizeOf(QWord) }
Result := Integer64Hash32(Key);
{$ELSE}
{$FATAL No hash function for pointer size on this platform. }
{$ENDIF}
{$POP}
end;
function PointerHash32(const Key: Pointer): DWord;
begin
{$HINTS OFF} // Otherwise it complains that casting Pointer to PtrUInt is not portable, but it is portable, by definition
Result := PtrUIntHash32(PtrUInt(Key));
{$HINTS ON}
end;
function TMethodHash32(const Key: TMethod): DWord;
begin
{$IF SizeOf(PtrUInt) = SizeOf(DWord) }
Assert(SizeOf(Key) = SizeOf(QWord));
Result := Integer64Hash32(QWord(Key));
{$ELSEIF SizeOf(Pointer) = SizeOf(QWord) }
// XXX no idea if this is an acceptable hash function
// XXX should print out the hashtable histogram once there's a number of watchers
{$HINTS OFF} // Otherwise it complains that casting Pointer to QWord is not portable, but we only go down this path if it is ok for this platform
Result := Integer64Hash32(QWord(TMethod(Key).Code)) xor Integer64Hash32(QWord(TMethod(Key).Data));
{$HINTS ON}
{$ELSE}
Result := PointerHash32(TMethod.Code) xor PointerHash32(TMethod.Data);
{$ENDIF}
end;
function RawByteStringHash32(const Key: RawByteString): DWord;
var
Index: Cardinal;
begin
{$PUSH}
{$RANGECHECKS OFF}
{$HINTS OFF} // not sure if the four hints for the next few lines are valid or not, but I'm guessing not.
// djb2 from http://www.cse.yorku.ca/~oz/hash.html:
Result := 5381;
if (Length(Key) > 0) then
for Index := 1 to Length(Key) do
Result := Result shl 5 + Result + Ord(Key[Index]);
{$HINTS ON}
// djb2 bis from http://www.cse.yorku.ca/~oz/hash.html:
//Result := 5381;
//if (Length(Key) > 0) then
// for Index := 1 to Length(Key) do
// Result := Result * 33 xor Ord(Key[Index]);
// sdbm from http://www.cse.yorku.ca/~oz/hash.html:
//Result := 0;
//if (Length(Key) > 0) then
// for Index := 1 to Length(Key) do
// Result := Ord(Key[Index]) + (Result shl 6) + (Result shl 16) - Result;
{$POP}
end;
function AnsiStringHash32(const Key: AnsiString): DWord;
begin
Result := RawByteStringHash32(Key);
end;
function UTF8StringHash32(const Key: UTF8String): DWord;
begin
Result := RawByteStringHash32(Key);
end;
end. |
{ Este exemplo foi baixado no site www.andrecelestino.com
Passe por lรก a qualquer momento para conferir os novos artigos! :)
contato@andrecelestino.com }
unit untArquivosINI;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ExtCtrls, Buttons, IniFiles;
type
TFrmArquivosINI = class(TForm)
lblTitulo: TLabel;
StatusBar: TStatusBar;
pnlCampos: TPanel;
lblMensagem: TLabel;
edtMensagem: TEdit;
btnGravarArquivo: TBitBtn;
Bevel: TBevel;
btnLerArquivo: TBitBtn;
procedure btnGravarArquivoClick(Sender: TObject);
procedure btnLerArquivoClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmArquivosINI: TFrmArquivosINI;
implementation
{$R *.dfm}
procedure TFrmArquivosINI.btnGravarArquivoClick(Sender: TObject);
var
ArquivoINI: TIniFile;
begin
ArquivoINI := TIniFile.Create('C:\Configuracao.ini');
ArquivoINI.WriteString('Exemplo', 'Mensagem', edtMensagem.Text);
ArquivoINI.Free;
ShowMessage('Mensagem armazenada com sucesso!');
end;
procedure TFrmArquivosINI.btnLerArquivoClick(Sender: TObject);
var
ArquivoINI: TIniFile;
Mensagem : string;
begin
ArquivoINI := TIniFile.Create('C:\Configuracao.ini');
Mensagem := ArquivoINI.ReadString('Exemplo', 'Mensagem', '');
ArquivoINI.WriteFloat('2', '2', 12.5);
ArquivoINI.Free;
ShowMessage('Mensagem armazenada no arquivo INI: ' + #13 + Mensagem);
end;
end.
|
unit cmpThemedScrollBox;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics, Forms, UxTheme,Themes;
type
TThemedScrollBox = class(TScrollBox)
private
fUseTheme: boolean;
fTheme : HTHEME;
procedure DoWMNCPaint (DC : HDC);
procedure SetUseTheme(const Value: boolean);
procedure WMNCPaint (var msg : TwmNCPaint); message WM_NCPAINT;
procedure WMThemeChanged(var Message: TMessage); message WM_THEMECHANGED;
protected
procedure CreateWnd; override;
public
constructor Create (AOwner : TComponent); override;
{ Public declarations }
published
property UseTheme : boolean read fUseTheme write SetUseTheme default True;
end;
implementation
var
IsWinNT: Boolean; // necessary to fix a bug in Win95/WinME regarding non-client area region intersection
// and to allow for check of system dependent hint animation
IsWin2K: Boolean; // nessary to provide correct string shortage
IsWinXP: Boolean; // necessary to paint the correct frame for the string edit
{ TThemedScrollBox }
constructor TThemedScrollBox.Create(AOwner: TComponent);
begin
inherited;
fUseTheme := True;
end;
procedure TThemedScrollBox.CreateWnd;
begin
inherited;
if IsWinXP then
Perform (WM_THEMECHANGED, 0, 0);
end;
procedure TThemedScrollBox.DoWMNCPaint(DC: HDC);
// Unfortunately, the VCL does a bad job regarding non-client area painting in TWinControl to paint a window's bevel
// which results often in heavy flickering. This method is a copy of TWinControl.WMNCPaintHandler adjusted to take
// the passed update region into account (actually, this happens already in the WMNCPaint).
// Since the advent of themes this method also draws the theme border.
const
InnerStyles: array[TBevelCut] of Integer = (0, BDR_SUNKENINNER, BDR_RAISEDINNER, 0);
OuterStyles: array[TBevelCut] of Integer = (0, BDR_SUNKENOUTER, BDR_RAISEDOUTER, 0);
EdgeStyles: array[TBevelKind] of Integer = (0, 0, BF_SOFT, BF_FLAT);
Ctl3DStyles: array[Boolean] of Integer = (BF_MONO, 0);
var
RC, RW: TRect;
EdgeSize: Integer;
Styles: Integer;
HasClientEdge: Boolean;
begin
// Determine outer rectangle to draw.
RC := Rect(0, 0, Width, Height);
Styles := GetWindowLong(Handle, GWL_EXSTYLE);
HasClientEdge := (Styles and WS_EX_CLIENTEDGE) <> 0;
// Draw control frame first
if HasClientEdge then
begin
if fUseTheme and (FTheme <> 0) then
begin
ExcludeClipRect(DC, RC.Left + 2, RC.Top + 2, RC.Right - 2, RC.Bottom - 2);
DrawThemeBackground(FTheme, DC, 0, 0, RC, nil);
end;
InflateRect(RC, -2, -2);
end;
if (BevelKind <> bkNone) or (BorderWidth > 0) then
begin
Styles := GetWindowLong(Handle, GWL_STYLE);
if (Styles and WS_BORDER) <> 0 then
InflateRect(RC, -1, -1);
if (Styles and WS_THICKFRAME) <> 0 then
InflateRect(RC, -3, -3);
RW := RC;
if BevelKind <> bkNone then
begin
DrawEdge(DC, RC, InnerStyles[BevelInner] or OuterStyles[BevelOuter], Byte(BevelEdges) or EdgeStyles[BevelKind] or
Ctl3DStyles[Ctl3D]);
EdgeSize := 0;
if BevelInner <> bvNone then
Inc(EdgeSize, BevelWidth);
if BevelOuter <> bvNone then
Inc(EdgeSize, BevelWidth);
with RC do
begin
if beLeft in BevelEdges then
Inc(Left, EdgeSize);
if beTop in BevelEdges then
Inc(Top, EdgeSize);
if beRight in BevelEdges then
Dec(Right, EdgeSize);
if beBottom in BevelEdges then
Dec(Bottom, EdgeSize);
end;
end;
// Repaint only the part in the original clipping region and not yet drawn parts.
IntersectClipRect(DC, RC.Left, RC.Top, RC.Right, RC.Bottom);
// Determine inner rectangle to exclude (RC corresponds then to the client area).
InflateRect(RC, -BorderWidth, -BorderWidth);
// Remove the inner rectangle.
ExcludeClipRect(DC, RC.Left, RC.Top, RC.Right, RC.Bottom);
// Erase parts not drawn.
Brush.Color := clBtnFace; // FColors.BorderColor;
Windows.FillRect(DC, RW, Brush.Handle);
end
end;
procedure TThemedScrollBox.SetUseTheme(const Value: boolean);
begin
if value <> fUseTheme then
begin
fUseTheme := Value;
if IsWinXP then
Perform (WM_THEMECHANGED, 0, 0);
end
end;
procedure TThemedScrollBox.WMNCPaint(var msg: TwmNCPaint);
var
DC: HDC;
begin
// Don't use the inherited NC paint handler as it doesn't consider the current clipping region
// leading so to annoying flicker.
// If the tree is themed then the border which is drawn by the inherited handler will be overpainted.
// This will, at time, cause a bit flicker, but since I found nowhwere documentation about how to do it right
// I have to live with that for the time being.
DefaultHandler(Msg);
dc := GetWindowDC (Handle);
if DC <> 0 then
begin
DoWMNCPaint (DC);
ReleaseDC(Handle, DC);
end;
Msg.Result := 0;
end;
procedure TThemedScrollBox.WMThemeChanged(var Message: TMessage);
begin
if FTheme <> 0 then
begin
CloseThemeData(FTheme);
FTheme := 0;
end;
if fUseTheme then
FTheme := OpenThemeData(Handle, 'listbox');
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_NOERASE or RDW_NOCHILDREN);
end;
procedure InitializeGlobalStructures;
begin
IsWinNT := (Win32Platform and VER_PLATFORM_WIN32_NT) <> 0;
IsWin2K := IsWinNT and (Win32MajorVersion > 4);
isWinXP := IsWin2K and (Win32MinorVersion > 0);
end;
begin
InitializeGlobalStructures
end.
|
unit uDMApuracaoICMSST;
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,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TDmApuracaoICMSST = class(TDataModule)
QryAnalise: TFDQuery;
DsAnalise: TDataSource;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
FQry : TFDQuery;
FQryTemp : TFDMemTable;
vSefSQL : String;
public
{ Public declarations }
function GetAnalise(pCodPart , pMes , pAno : String ; pXML , pSPED : Boolean):Boolean;
function GetContribuinte(pCNPJ : String):Boolean;
function GetSQL88STES(pDatIni, pDatFin, pCNPJ: String): String;
function GetSQL88STITNF(pDatIni, pDatFin, pCNPJ: String): String;
function GetQry : TFDQuery;
function GetQryTemp : TFDMemTable;
function GetSEF(pDatIni, pDatFin, pCNPJ : String) : String;
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
Uses uDMBase,BiblKhronos, uApuracaoICMSST;
{ TDmApuracaoICMSST }
procedure TDmApuracaoICMSST.DataModuleCreate(Sender: TObject);
begin
FQry := TFDQuery.Create(nil);
FQry.Connection := dmPrincipal.BancoExec;
FQryTemp := TFDMemTable.Create(nil);
FQryTemp.CachedUpdates := true;
end;
procedure TDmApuracaoICMSST.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(FQry);
FreeAndNil(FQryTemp);
end;
function TDmApuracaoICMSST.GetAnalise(pCodPart , pMes , pAno : String ;
pXML , pSPED : Boolean):Boolean;
function GetSQL : String;
begin
result := 'SELECT * FROM (';
if pSPED then
begin
result := result + #13 + 'SELECT * FROM ( '+
'SELECT '+
'P."COD_ITEM",P."CODBARRA",P."DESCR_ITEM", '+
'NF."DT_E_ES" AS "DATA_ENTRADA", '+
'SUM(COALESCE(NP."QTDE",0)) AS "QTDE_ENTRADA", '+
'SUM(NP."VL_BC_ICMS_ST") AS "BC_ICMS_ST_ENT", '+
'SUM(NP."VL_ICMS_ST") AS "VL_ICMS_ST_ENT", '+
'SUM((NP."VL_BC_ICMS_ST" / NP."QTDE")) VL_ICMS_ST_UNI_ENT, '+
'V."DATA" AS "DATA_SAIDA", '+
'SUM(VI."QTD") AS "QTDE_SAIDA", '+
'SUM((VI."QTD" * VI."VL_ITEM")) AS "BC_ICMS_ST_SAI", '+
'SUM((P."ALIQ_ICMS" * VI."VL_ITEM")) AS TOTAL_ICMS_SAIDA, '+
'SUM( ( (NP."VL_BC_ICMS_ST" / NP."QTDE") * (VI."QTD") * (P."ALIQ_ICMS"))) TOTAL_ICMS_ENTRADA, '+
'SUM(( (P."ALIQ_ICMS" * VI."VL_ITEM") - '+
'( (NP."VL_BC_ICMS_ST" / NP."QTDE") * (VI."QTD") * (P."ALIQ_ICMS")) '+
'))DIFERENCA, '+
'(SUM(COALESCE(NP."QTDE",0)) - SUM(COALESCE(VI."QTD",0))) ESTOQUE_FINAL, '+
'SUM( ( '+
' CASE '+
' WHEN '+
' ( (P."ALIQ_ICMS" * VI."VL_ITEM") - '+
'( (NP."VL_BC_ICMS_ST" / NP."QTDE") * (VI."QTD") * (P."ALIQ_ICMS")) '+
' ) < 0 THEN '+
' ( (P."ALIQ_ICMS" * VI."VL_ITEM") - '+
'( (NP."VL_BC_ICMS_ST" / NP."QTDE") * (VI."QTD") * (P."ALIQ_ICMS")) '+
' ) '+
' ELSE '+
' 0 '+
' END '+
' ))SALDO_RESTITUIR, '+
' '+
' SUM( ( '+
' CASE '+
' WHEN '+
' ( (P."ALIQ_ICMS" * VI."VL_ITEM") - '+
' ( (NP."VL_BC_ICMS_ST" / NP."QTDE") * (VI."QTD") * (P."ALIQ_ICMS")) '+
' ) > 0 THEN '+
' ( (P."ALIQ_ICMS" * VI."VL_ITEM") - '+
' ( (NP."VL_BC_ICMS_ST" / NP."QTDE") * (VI."QTD") * (P."ALIQ_ICMS")) '+
' ) '+
' ELSE '+
' 0 '+
' END '+
' )) SALDO_ACOMPLEMENTAR '+
' '+
' FROM "REGISTRO0200" P '+
' LEFT JOIN "REGISTRO0000" C ON C."ID" = P."ID_SPED" '+
' LEFT JOIN "REGISTROC170" NP ON NP."COD_ITEM" = P."COD_ITEM" '+
' LEFT JOIN "REGISTROC100" NF ON NF."ID" = NP."IDNF" '+
' LEFT JOIN "REGISTROC425" VI ON VI."COD_ITEM" = P."COD_ITEM" '+
' LEFT JOIN "REGISTROC400" V ON V."ID" = VI."ID_REDZ" '+
' LEFT JOIN "NCM" NC ON P."COD_NCM" = NC."NCM" '+
' WHERE C."MES" =:MES AND C."ANO" =:ANO AND C."CNPJ" = :CNPJ '+
' GROUP BY P."COD_ITEM", P."CODBARRA",P."DESCR_ITEM",NF."DT_E_ES",V."DATA" '+
' ORDER BY P."COD_ITEM", P."CODBARRA",P."DESCR_ITEM",NF."DT_E_ES",V."DATA" )A ';
end;
if pXML then
begin
if pSPED then
result := Result + ' UNION ALL ';
result := result + 'SELECT * FROM ( SELECT '+
' NP."COD_ITEM",NP."COD_EAN",NP."DESCR_ITEM", '+
' NF."DT_E_ES" AS "DATA_ENTRADA", '+
' SUM(COALESCE(NP."QTDE",0)) AS "QTDE_ENTRADA", '+
' SUM(NP."VL_BC_ICMS_ST") AS "BC_ICMS_ST_ENT", '+
' SUM(NP."VL_ICMS_ST") AS "VL_ICMS_ST_ENT", '+
' SUM( ( '+
' CASE '+
' WHEN '+
' ( (NP."VL_BC_ICMS_ST") '+
' ) > 0 AND (NP."QTDE") > 0 THEN '+
' ((NP."VL_BC_ICMS_ST" / NP."QTDE") '+
' ) '+
' ELSE '+
' 0 '+
' END '+
' ))VL_ICMS_ST_UNI_ENT, '+
' NF."DT_E_ES" AS "DATA_SAIDA", '+
' SUM(NP."QTDE" * 0) AS "QTDE_SAIDA", '+
' SUM(0) AS "BC_ICMS_ST_SAI", '+
' SUM(0) AS "TOTAL_ICMS_SAIDA", '+
' SUM(NP."VL_ICMS_ST") "TOTAL_ICMS_ENTRADA", '+
' SUM((CASE '+
' WHEN ((NP."VL_BC_ICMS_ST")) > 0 '+
' AND (NP."QTDE") > 0 THEN (NP."VL_BC_ICMS_ST" / NP."QTDE") - NP."VL_ITEM"'+
' ELSE 0 '+
' END))AS DIFERENCA, '+
' SUM(COALESCE(NP."QTDE",0)) "ESTOQUE_FINAL", '+
' SUM((CASE '+
' WHEN ((NP."VL_BC_ICMS_ST")) > 0 '+
' AND (NP."QTDE") > 0 '+
' THEN CASE '+
' WHEN (NP."VL_BC_ICMS_ST" / NP."QTDE") - NP."VL_ITEM" < 0 THEN ((NP."VL_BC_ICMS_ST" / NP."QTDE") - NP."VL_ITEM") * NP."ALIQ_ICMS" '+
' ELSE 0 '+
' END '+
' ELSE 0 '+
' END)) SALDO_ACOMPLEMENTAR, '+
' SUM((CASE '+
' WHEN ((NP."VL_BC_ICMS_ST")) > 0 '+
' AND (NP."QTDE") > 0 '+
' THEN CASE '+
' WHEN (NP."VL_BC_ICMS_ST" / NP."QTDE") - NP."VL_ITEM" > 0 THEN ((NP."VL_BC_ICMS_ST" / NP."QTDE") - NP."VL_ITEM") * NP."ALIQ_ICMS" '+
' ELSE 0 '+
' END '+
' ELSE 0 '+
' END)) SALDO_RESTITUIR '+
' FROM "NF_ITENS" NP '+
' LEFT JOIN "NF" NF ON NF."ID" = NP."IDNF" '+
' LEFT JOIN "NCM" NC ON NP."NCM" = NC."NCM" '+
' WHERE NF."MES" =:MES AND NF."ANO" = :ANO AND NF."COD_EMP" =:CNPJ '+
' GROUP BY NP."COD_ITEM", NP."COD_EAN",NP."DESCR_ITEM",NF."DT_E_ES",NP."VL_ITEM" '+
' ORDER BY NP."COD_ITEM", NP."COD_EAN",NP."DESCR_ITEM",NF."DT_E_ES")B ';
end;
result := result + #13 +
') X ----- where X."VL_ICMS_ST_ENT" > 0';
CopyQuery(Result);
end;
begin
with QryAnalise do
begin
Close;
SQL.Text := GetSQL;
ParamByName('CNPJ').AsString := pCodPart;
ParamByName('MES').AsInteger := pMes.ToInteger;
ParamByName('ANO').AsInteger := pAno.ToInteger;
Open;
result := not (IsEmpty);
end;
vSefSQL := GetSQL;
end;
function TDmApuracaoICMSST.GetContribuinte(pCNPJ: String): Boolean;
function GetSQL : String;
begin
result := 'SELECT * FROM "GET_CONTRIBUINTE" WHERE "CNPJ" = ' + pCNPJ.QuotedString;
end;
begin
with FQry do
begin
close;
SQL.Text := GetSQL;
CopyQuery(SQL.Text);
Open;
end;
result := not (FQry.IsEmpty);
end;
function TDmApuracaoICMSST.GetQry: TFDQuery;
begin
Result := FQry;
end;
function TDmApuracaoICMSST.GetQryTemp: TFDMemTable;
begin
result := FQryTemp;
end;
function TDmApuracaoICMSST.GetSEF(pDatIni, pDatFin, pCNPJ: String): String;
begin
Result := ' SELECT *, ' +
' I."NCM", ' +
' I."COD_EAN", '+
' I."UNID", ' +
' I."P_MVA_ST", ' +
' I."P_RED_BC_ST" FROM "REGISTROC170" R ' +
' LEFT JOIN "NF" N ON R."IDNF" = N."ID" ' +
' LEFT JOIN "NF_ITENS" I ON R."IDNF" = I."ID" ' +
// ' LEFT JOIN "NCM" NC ON NC."NCM" = I."NCM" ' +
' WHERE N."DT_E_ES" BETWEEN ' + pDatIni.QuotedString +
' AND ' + pDatFin.QuotedString +
' AND N."COD_EMP" = ' + pCNPJ.QuotedString;
end;
function TDmApuracaoICMSST.GetSQL88STES(pDatIni, pDatFin, pCNPJ: String): String;
begin
result := ' SELECT I."COD_ITEM",'+
' CAST( '+
' ( (CASE WHEN N."IND_OPER" = ''E'' THEN SUM("QTDE") '+
' ELSE 0 END) - (CASE WHEN N."IND_OPER" = ''S'' '+
' THEN SUM("QTDE") ELSE 0 END)) AS NUMERIC(15,2) '+
' ) "QTDE", '+
' (CASE WHEN N."IND_OPER" = ''E'' THEN SUM(I."VL_ICMS_ST") '+
' ELSE 0 END) - (CASE WHEN N."IND_OPER" = ''S'' THEN '+
' SUM(I."VL_ICMS_ST") ELSE 0 END) "VL_ICMSST", '+
' (CASE WHEN N."IND_OPER" = ''E'' THEN SUM(I."VL_ICMS") '+
' ELSE 0 END) - (CASE WHEN N."IND_OPER" = ''S'' THEN '+
' SUM(I."VL_ICMS") ELSE 0 END) "VL_ICMS" '+
' FROM "NF_ITENS" I '+
' LEFT JOIN "NF" N ON N."ID" = I."IDNF" '+
' WHERE N."DT_E_ES" BETWEEN ' + pDatIni.QuotedString +
' AND ' + pDatFin.QuotedString +
' AND N."COD_EMP" = ' + pCNPJ.QuotedString +
' GROUP BY I."COD_ITEM",N."IND_OPER" '+
' ORDER BY CAST("COD_ITEM" AS NUMERIC)';
end;
function TDmApuracaoICMSST.GetSQL88STITNF(pDatIni, pDatFin,
pCNPJ: String): String;
begin
result := ' SELECT '+
' N."COD_PART", '+
' N."COD_MOD", '+
' N."SER", '+
' N."NUM_DOC", '+
' I."CFOP", '+
' COALESCE(I."CST",I."CSOSN")"CST", '+
' I."NUM_ITEM", '+
' N."DT_E_ES", '+
' I."COD_ITEM", '+
' I."QTDE", '+
' I."VL_ITEM", '+
' I."VL_DESC", '+
' I."VL_BC_ICMS", '+
' I."VL_BC_ICMS_ST", '+
' I."ALIQ_ST", '+
' I."ALIQ_ICMS", '+
' I."VL_IPI", '+
' N."CHV_NFE" '+
' FROM "NF_ITENS" I '+
' LEFT JOIN "NF" N ON N."ID" = I."IDNF" '+
' WHERE I."VL_BC_ICMS_ST" > 0 '+
' AND N."DT_E_ES" BETWEEN ' + pDatIni.QuotedString +
' AND ' + pDatFin.QuotedString +
' AND N."COD_EMP" = ' + pCNPJ.QuotedString +
' ORDER BY N."CHV_NFE",I."NUM_ITEM" ';
end;
end.
|
(************************************* Ext2D Engine *************************************)
(* ะะพะดัะปั : E2DSound.pas *)
(* ะะฒัะพั : ะัะธะฝ ะะปะฐะดะธะผะธั *)
(* ะกะพะทะดะฐะฝ : 03.11.06 *)
(* ะะฝัะพัะผะฐัะธั : ะะพะดัะปั ัะพะดะตะถะธั ััะฝะบัะธะธ ะดะปั ัะฐะฑะพัั ัะพ ะทะฒัะบะพะผ. *)
(* ะะทะผะตะฝะตะฝะธั : ะฝะตั ะธะทะผะตะฝะตะฝะธะน. *)
(****************************************************************************************)
unit E2DSound;
interface
uses
E2DTypes;
{ ะคัะฝะบัะธั ะดะปั ัะพะทะดะฐะฝะธั ะพะฑัะตะบัะพะฒ DirectSound.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะตัะปะธ ััะฝะบัะธั ะฒัะฟะพะปะฝะธะปะฐัั ััะฟะตัะฝะพ - E2DERR_OK, ะตัะปะธ ะฝะตัะดะฐัะฝะพ -
ะบะพะด ะพัะธะฑะบะธ. }
function E2D_CreateSound : E2D_Result; stdcall; export;
{ ะคัะฝะบัะธั ะดะปั ะฒะพัะฟัะพะธะทะฒะตะดะตะฝะธั ะทะฒัะบะฐ. ะะฐัะฐะผะตััั :
SoundID : ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ, ะบะพัะพััะน ะฝะตะพะฑั
ะพะดะธะผะพ ะฒะพัะฟัะพะธะทะฒะตััะธ;
Loop : ัะปะฐะณ, ัะธะณะฝะฐะปะธะทะธััััะธะน ะฝะฐะดะพ ะปะธ ะทะฐัะธะบะปะธัั ะฒะพัะฟัะพะธะทะฒะตะดะตะฝะธะต.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะตัะปะธ ััะฝะบัะธั ะฒัะฟะพะปะฝะธะปะฐัั ััะฟะตัะฝะพ - E2DERR_OK, ะตัะปะธ ะฝะตัะดะฐัะฝะพ -
ะบะพะด ะพัะธะฑะบะธ. }
function E2D_PlaySound(SoundID : E2D_TSoundID;
Loop : Boolean) : E2D_Result; stdcall; export;
{ ะคัะฝะบัะธั ะดะปั ะพััะฐะฝะพะฒะบะธ ะฒะพัะฟัะพะธะทะฒะตะดะตะฝะธั ะทะฒัะบะฐ. ะะฐัะฐะผะตััั :
SoundID : ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ, ะบะพัะพััะน ะฝะตะพะฑั
ะพะดะธะผะพ ะพััะฐะฝะพะฒะธัั.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะตัะปะธ ััะฝะบัะธั ะฒัะฟะพะปะฝะธะปะฐัั ััะฟะตัะฝะพ - E2DERR_OK, ะตัะปะธ ะฝะตัะดะฐัะฝะพ -
ะบะพะด ะพัะธะฑะบะธ. }
function E2D_StopSound(SoundID : E2D_TSoundID) : E2D_Result; stdcall; export;
{ ะคัะฝะบัะธั ะดะปั ะฟะพะปััะตะฝะธั ะณัะพะผะบะพััะธ ะทะฒัะบะฐ. ะะฐัะฐะผะตััั :
SoundID : ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ, ะณัะพะผะบะพััั ะบะพัะพัะณะพ ะฝะตะพะฑั
ะพะดะธะผะพ ะฟะพะปััะธัั;
Volume : ะฟะตัะตะผะตะฝะฝะฐั ะดะปั ัะพั
ัะฐะฝะตะฝะธั ะณัะพะผะบะพััะธ.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะตัะปะธ ััะฝะบัะธั ะฒัะฟะพะปะฝะธะปะฐัั ััะฟะตัะฝะพ - E2DERR_OK, ะตัะปะธ ะฝะตัะดะฐัะฝะพ -
ะบะพะด ะพัะธะฑะบะธ. }
function E2D_GetSoundVolume(SoundID : E2D_TSoundID; var
Volume : E2D_TSoundVolume) : E2D_Result; stdcall; export;
{ ะคัะฝะบัะธั ะดะปั ัััะฐะฝะพะฒะปะตะฝะธั ะณัะพะผะบะพััะธ ะทะฒัะบะฐ. ะะฐัะฐะผะตััั :
SoundID : ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ, ะณัะพะผะบะพััั ะบะพัะพัะณะพ ะฝะตะพะฑั
ะพะดะธะผะพ ัััะฐะฝะพะฒะธัั;
Volume : ะณัะพะผะบะพััั.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะตัะปะธ ััะฝะบัะธั ะฒัะฟะพะปะฝะธะปะฐัั ััะฟะตัะฝะพ - E2DERR_OK, ะตัะปะธ ะฝะตัะดะฐัะฝะพ -
ะบะพะด ะพัะธะฑะบะธ. }
function E2D_SetSoundVolume(SoundID : E2D_TSoundID;
Volume : E2D_TSoundVolume) : E2D_Result; stdcall; export;
{ ะคัะฝะบัะธั ะดะปั ะฟะพะปััะตะฝะธั ะณะปะพะฑะฐะปัะฝะพะน ะณัะพะผะบะพััะธ.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะณัะพะผะบะพััั. }
function E2D_GetGlobalVolume : E2D_TSoundVolume; stdcall; export;
{ ะคัะฝะบัะธั ะดะปั ัััะฐะฝะพะฒะปะตะฝะธั ะณะปะพะฑะฐะปัะฝะพะน ะณัะพะผะบะพััะธ. ะะฐัะฐะผะตััั :
Volume : ะณัะพะผะบะพััั.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะตัะปะธ ััะฝะบัะธั ะฒัะฟะพะปะฝะธะปะฐัั ััะฟะตัะฝะพ - E2DERR_OK, ะตัะปะธ ะฝะตัะดะฐัะฝะพ -
ะบะพะด ะพัะธะฑะบะธ. }
function E2D_SetGlobalVolume(Volume : E2D_TSoundVolume) : E2D_Result; stdcall; export;
{ ะคัะฝะบัะธั ะดะปั ะฟะพะปััะตะฝะธั ะฟะฐะฝะพัะฐะผั ะทะฒัะบะฐ. ะะฐัะฐะผะตััั :
SoundID : ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ, ะฟะฐะฝะพัะฐะผั ะบะพัะพัะณะพ ะฝะตะพะฑั
ะพะดะธะผะพ ะฟะพะปััะธัั;
Pan : ะฟะตัะตะผะตะฝะฝะฐั ะดะปั ัะพั
ัะฐะฝะตะฝะธั ะฟะฐะฝะพัะฐะผั.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะตัะปะธ ััะฝะบัะธั ะฒัะฟะพะปะฝะธะปะฐัั ััะฟะตัะฝะพ - E2DERR_OK, ะตัะปะธ ะฝะตัะดะฐัะฝะพ -
ะบะพะด ะพัะธะฑะบะธ. }
function E2D_GetSoundPan(SoundID : E2D_TSoundID;
var Pan : E2D_TSoundPan) : E2D_Result; stdcall; export;
{ ะคัะฝะบัะธั ะดะปั ัััะฐะฝะพะฒะปะตะฝะธั ะฟะฐะฝะพัะฐะผั ะทะฒัะบะฐ. ะะฐัะฐะผะตััั :
SoundID : ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ, ะฟะฐะฝะพัะฐะผั ะบะพัะพัะณะพ ะฝะตะพะฑั
ะพะดะธะผะพ ัััะฐะฝะพะฒะธัั;
Pan : ะฟะฐะฝะพัะฐะผะฐ.
ะะพะทะฒัะฐัะฐะตะผะพะต ะทะฝะฐัะตะฝะธะต : ะตัะปะธ ััะฝะบัะธั ะฒัะฟะพะปะฝะธะปะฐัั ััะฟะตัะฝะพ - E2DERR_OK, ะตัะปะธ ะฝะตัะดะฐัะฝะพ -
ะบะพะด ะพัะธะฑะบะธ. }
function E2D_SetSoundPan(SoundID : E2D_TSoundID;
Pan : E2D_TSoundPan) : E2D_Result; stdcall; export;
implementation
uses
E2DVars, { ะะปั ะฟะตัะตะผะตะฝะฝัั
ะทะฒัะบะฐ }
E2DConsts, { ะะปั ะบะพะฝััะฐะฝั ะพัะธะฑะพะบ }
DirectSound; { ะะปั ััะฝะบัะธะน DirectSound }
function E2D_CreateSound;
begin { E2D_CreateSound }
// ะกะพะทะดะฐะตะผ ะณะปะฐะฒะฝัะน ะพะฑัะตะบั DirectSound.
if DirectSoundCreate8(nil, DS_Main, nil) <> DS_OK then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SOUND_CREATEDS;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะฐะดะฐะตะผ ััะพะฒะตะฝั ะบะพะพะฟะตัะฐัะธะธ.
if DS_Main.SetCooperativeLevel(Window_Handle,
DSSCL_EXCLUSIVE) <> DS_OK then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั,
Result := E2DERR_SYSTEM_SETCOOPLVL;
// ัะดะฐะปัะตะผ ะณะปะฐะฒะฝัะน ะพะฑัะตะบั DirectSound
DS_Main := nil;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะตะปะฐะตะผ ัะตะทัะปััะฐั ััะฟะตัะฝัะผ.
Result := E2DERR_OK;
end; { E2D_CreateSound }
function E2D_PlaySound;
begin { E2D_PlaySound }
// ะัะพะฒะตััะตะผ ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ.
if SoundID >= NumSounds then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SYSTEM_INVALIDID;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะพัะฟัะพะธะทะฒะพะดะธะผ ะทะฒัะบ.
if Sounds[SoundID].Buffer.Play(0, 0,
Byte(Loop) * DSBPLAY_LOOPING) <> DS_OK then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SOUND_CANTPLAY;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะตะปะฐะตะผ ัะตะทัะปััะฐั ััะฟะตัะฝัะผ.
Result := E2DERR_OK;
end; { E2D_PlaySound }
function E2D_StopSound;
begin { E2D_StopSound }
// ะัะพะฒะตััะตะผ ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ.
if SoundID >= NumSounds then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SYSTEM_INVALIDID;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะััะฐะฝะฐะฒะปะธะฒะฐะตะผ ะทะฒัะบ.
if Sounds[SoundID].Buffer.Stop <> DS_OK then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SOUND_CANTSTOP;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะตะปะฐะตะผ ัะตะทัะปััะฐั ััะฟะตัะฝัะผ.
Result := E2DERR_OK;
end; { E2D_StopSound }
function E2D_GetSoundVolume;
begin { E2D_GetSoundVolume }
// ะัะพะฒะตััะตะผ ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ.
if SoundID >= NumSounds then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SYSTEM_INVALIDID;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะพะปััะฐะตะผ ะณัะพะผะบะพััั.
if Sounds[SoundID].Buffer.GetVolume(PInteger(@Volume)^) <> DS_OK then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SOUND_CANTGETVOL;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะตะปะฐะตะผ ัะตะทัะปััะฐั ััะฟะตัะฝัะผ.
Result := E2DERR_OK;
end; { E2D_GetSoundVolume }
function E2D_SetSoundVolume;
begin { E2D_SetSoundVolume }
// ะัะพะฒะตััะตะผ ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ.
if SoundID >= NumSounds then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SYSTEM_INVALIDID;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะฃััะฐะฝะฐะฒะปะธะฒะฐะตะผ ะณัะพะผะบะพััั.
if Sounds[SoundID].Buffer.SetVolume(Volume) <> DS_OK then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SOUND_CANTSETVOL;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะตะปะฐะตะผ ัะตะทัะปััะฐั ััะฟะตัะฝัะผ.
Result := E2DERR_OK;
end; { E2D_SetSoundVolume }
function E2D_GetGlobalVolume;
begin { E2D_GetGlobalVolume }
// ะะพะผะตัะฐะตะผ ะฒ ัะตะทัะปััะฐั ะณัะพะผะบะพััั.
Result := Volume_Global;
end; { E2D_GetGlobalVolume }
function E2D_SetGlobalVolume;
var
i : Longword; { ะกัะตััะธะบ ัะธะบะปะฐ }
begin { E2D_SetGlobalVolume }
// ะะตะปะฐะตะผ ัะตะทัะปััะฐั ััะฟะตัะฝัะผ.
Result := E2DERR_OK;
// ะัะพะฒะตััะตะผ ะบะพะปะธัะตััะฒะพ ะทะฐะณััะถะตะฝะฝัั
ะทะฒัะบะพะฒ.
if NumSounds > 0 then
// ะัะปะธ ะฝะตะพะฑั
ะพะดะธะผะพ ัััะฐะฝะฐะฒะปะธะฒะฐะตะผ ะณัะพะผะบะพััั ะฒัะตั
ะทะฒัะบะพะฒ.
for i := 0 to NumSounds - 1 do begin
// ะฃััะฐะฝะฐะฒะปะธะฒะฐะตะผ ะณัะพะผะบะพััั.
Result := E2D_SetSoundVolume(i, Volume);
// ะัะพะฒะตััะตะผ ัะตะทัะปััะฐั ะฒัะฟะพะปะฝะตะฝะธั.
if Result <> E2DERR_OK then
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end;
// ะกะพั
ัะฐะฝัะตะผ ะฝะพะฒัั ะณัะพะผะบะพััั.
Volume_Global := Volume;
end; { E2D_SetGlobalVolume }
function E2D_GetSoundPan;
begin { GetSoundPan }
// ะัะพะฒะตััะตะผ ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ.
if SoundID >= NumSounds then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SYSTEM_INVALIDID;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะพะปััะฐะตะผ ะฟะฐะฝะพัะฐะผั.
if Sounds[SoundID].Buffer.GetPan(PInteger(@Pan)^) <> DS_OK then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SOUND_CANTGETPAN;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะตะปะฐะตะผ ัะตะทัะปััะฐั ััะฟะตัะฝัะผ.
Result := E2DERR_OK;
end; { GetSoundPan }
function E2D_SetSoundPan;
begin { SetSoundPan }
// ะัะพะฒะตััะตะผ ะธะดะตะฝัะธัะธะบะฐัะพั ะทะฒัะบะฐ.
if SoundID >= NumSounds then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SYSTEM_INVALIDID;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะฃััะฐะฝะฐะฒะปะธะฒะฐะตะผ ะฟะฐะฝะพัะฐะผั.
if Sounds[SoundID].Buffer.SetPan(Pan) <> DS_OK then begin { if }
// ะัะปะธ ะฝะต ะฟะพะปััะธะปะพัั ะฟะพะผะตัะฐะตะผ ะบะพะด ะพัะธะฑะบะธ ะฒ ัะตะทัะปััะฐั
Result := E2DERR_SOUND_CANTSETPAN;
// ะธ ะฒัั
ะพะดะธะผ ะธะท ััะฝะบัะธะธ.
Exit;
end; { if }
// ะะตะปะฐะตะผ ัะตะทัะปััะฐั ััะฟะตัะฝัะผ.
Result := E2DERR_OK;
end; { SetSoundPan }
end.
|
unit TBGFiredacDriver.Model.Query;
interface
uses
TBGConnection.Model.Interfaces, Data.DB, System.Classes, FireDAC.Comp.Client,
System.SysUtils, TBGConnection.Model.DataSet.Proxy, TBGConnection.Model.Helper,
TBGConnection.Model.DataSet.Interfaces, TBGConnection.Model.DataSet.Factory,
TBGConnection.Model.DataSet.Observer, System.Generics.Collections;
Type
TFiredacModelQuery = class(TInterfacedObject, iQuery)
private
FSQL : String;
FKey : Integer;
FConexao : TFDConnection;
FDriver : iDriver;
FQuery : TList<TFDQuery>;
FDataSource : TDataSource;
FDataSet : TDictionary<integer, iDataSet>;
FChangeDataSet : TChangeDataSet;
FParams : TParams;
procedure InstanciaQuery;
function GetDataSet : iDataSet;
function GetQuery : TFDQuery;
procedure SetQuery(Value : TFDQuery);
public
constructor Create(Conexao : TFDConnection; Driver : iDriver);
destructor Destroy; override;
class function New(Conexao : TFDConnection; Driver : iDriver) : iQuery;
//iObserver
procedure ApplyUpdates(DataSet : TDataSet);
//iQuery
function Open(aSQL: String): iQuery;
function ExecSQL(aSQL : String) : iQuery; overload;
function DataSet : TDataSet; overload;
function DataSet(Value : TDataSet) : iQuery; overload;
function DataSource(Value : TDataSource) : iQuery;
function Fields : TFields;
function ChangeDataSet(Value : TChangeDataSet) : iQuery;
function &End: TComponent;
function Tag(Value : Integer) : iQuery;
function LocalSQL(Value : TComponent) : iQuery;
function Close : iQuery;
function SQL : TStrings;
function Params : TParams;
function ParamByName(Value : String) : TParam;
function ExecSQL : iQuery; overload;
function UpdateTableName(Tabela : String) : iQuery;
end;
implementation
uses
FireDAC.Stan.Param;
{ TFiredacModelQuery }
function TFiredacModelQuery.&End: TComponent;
begin
Result := GetQuery;
end;
function TFiredacModelQuery.ExecSQL: iQuery;
begin
Result := Self;
if Assigned(FParams) then
GetQuery.Params.Assign(FParams);
GetQuery.ExecSQL;
ApplyUpdates(nil);
end;
procedure TFiredacModelQuery.InstanciaQuery;
var
Query : TFDQuery;
begin
Query := TFDQuery.Create(nil);
Query.Connection := FConexao;
Query.AfterPost := ApplyUpdates;
Query.AfterDelete := ApplyUpdates;
FQuery.Add(Query);
end;
function TFiredacModelQuery.ExecSQL(aSQL: String): iQuery;
begin
FSQL := aSQL;
GetQuery.SQL.Text := FSQL;
GetQuery.ExecSQL;
ApplyUpdates(nil);
end;
function TFiredacModelQuery.Fields: TFields;
begin
Result := GetQuery.Fields;
end;
function TFiredacModelQuery.GetDataSet: iDataSet;
begin
Result := FDataSet.Items[FKey];
end;
function TFiredacModelQuery.GetQuery: TFDQuery;
begin
Result := FQuery.Items[Pred(FQuery.Count)];
end;
function TFiredacModelQuery.LocalSQL(Value: TComponent): iQuery;
begin
Result := Self;
GetQuery.LocalSQL := TFDCustomLocalSQL(Value);
end;
procedure TFiredacModelQuery.ApplyUpdates(DataSet: TDataSet);
begin
FDriver.Cache.ReloadCache('');
end;
function TFiredacModelQuery.ChangeDataSet(Value: TChangeDataSet): iQuery;
begin
Result := Self;
FChangeDataSet := Value;
end;
function TFiredacModelQuery.Close: iQuery;
begin
Result := Self;
GetQuery.Close;
end;
constructor TFiredacModelQuery.Create(Conexao : TFDConnection; Driver : iDriver);
begin
FDriver := Driver;
FConexao := Conexao;
FKey := 0;
FQuery := TList<TFDQuery>.Create;
FDataSet := TDictionary<integer, iDataSet>.Create;
InstanciaQuery;
end;
function TFiredacModelQuery.DataSet: TDataSet;
begin
Result := TDataSet(GetQuery);
end;
function TFiredacModelQuery.DataSet(Value: TDataSet): iQuery;
begin
Result := Self;
GetDataSet.DataSet(Value);
end;
function TFiredacModelQuery.DataSource(Value : TDataSource) : iQuery;
begin
Result := Self;
FDataSource := Value;
end;
destructor TFiredacModelQuery.Destroy;
begin
FreeAndNil(FQuery);
FreeAndNil(FDataSet);
inherited;
end;
class function TFiredacModelQuery.New(Conexao : TFDConnection; Driver : iDriver) : iQuery;
begin
Result := Self.Create(Conexao, Driver);
end;
function TFiredacModelQuery.Open(aSQL: String): iQuery;
var
Query : TFDQuery;
DataSet : iDataSet;
begin
Result := Self;
FSQL := aSQL;
if not FDriver.Cache.CacheDataSet(FSQL, DataSet) then
begin
InstanciaQuery;
DataSet.DataSet(GetQuery);
DataSet.SQL(FSQL);
GetQuery.Close;
GetQuery.Open(aSQL);
FDriver.Cache.AddCacheDataSet(DataSet.GUUID, DataSet);
end
else
SetQuery(TFDQuery(DataSet.DataSet));
FDataSource.DataSet := DataSet.DataSet;
Inc(FKey);
FDataSet.Add(FKey, DataSet);
end;
function TFiredacModelQuery.ParamByName(Value: String): TParam;
begin
Result := TParam(GetQuery.ParamByName(Value));
end;
function TFiredacModelQuery.Params: TParams;
begin
if not Assigned(FParams) then
FParams := TParams.Create(nil);
FParams.Assign(GetQuery.Params);
Result := FParams;
end;
procedure TFiredacModelQuery.SetQuery(Value: TFDQuery);
begin
FQuery.Items[Pred(FQuery.Count)] := Value;
end;
function TFiredacModelQuery.SQL: TStrings;
begin
Result := GetQuery.SQL;
end;
function TFiredacModelQuery.Tag(Value: Integer): iQuery;
begin
Result := Self;
GetQuery.Tag := Value;
end;
function TFiredacModelQuery.UpdateTableName(Tabela: String): iQuery;
begin
Result := Self;
end;
end.
|
(******************************************************************************
* 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.CSG.BSP;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$ifdef Delphi2009AndUp}
{$warn DUPLICATE_CTOR_DTOR off}
{$endif}
{$undef UseDouble}
{$ifdef UseDouble}
{$define NonSIMD}
{$endif}
{-$define NonSIMD}
{$ifdef NonSIMD}
{$undef SIMD}
{$else}
{$ifdef cpu386}
{$if not (defined(Darwin) or defined(CompileForWithPIC))}
{$define SIMD}
{$ifend}
{$endif}
{$ifdef cpux64}
{$define SIMD}
{$endif}
{$endif}
{$define NonRecursive}
{$ifndef fpc}
{$scopedenums on}
{$endif}
{$warnings off}
interface
uses SysUtils,Classes,Math,
PasVulkan.Types,
PasVulkan.Math;
type TpvCSGBSP=class
public
const Epsilon=1e-5;
SquaredEpsilon=Epsilon*Epsilon;
OneMinusEpsilon=1.0-Epsilon;
OnePlusEpsilon=1.0+Epsilon;
TJunctionEpsilon=1e-4;
TJunctionOneMinusEpsilon=1.0-TJunctionEpsilon;
TJunctionOnePlusEpsilon=1.0+TJunctionEpsilon;
NearPositionEpsilon=1e-5;
SquaredNearPositionEpsilon=NearPositionEpsilon*NearPositionEpsilon;
CSGOptimizationBoundEpsilon=1e-1;
daabbtNULLNODE=-1;
AABBMULTIPLIER=2.0;
type TFloat=TpvDouble;
PFloat=^TFloat;
TDynamicArray<T>=record
public
Items:array of T;
Count:TpvSizeInt;
procedure Initialize;
procedure Finalize;
procedure Clear;
procedure Finish;
procedure Assign(const aFrom:{$ifdef fpc}TpvCSGBSP.{$endif}TDynamicArray<T>); overload;
procedure Assign(const aItems:array of T); overload;
function AddNew:TpvSizeInt; overload;
function Insert(const aIndex:TpvSizeInt;const aItem:T):TpvSizeInt; overload;
function Add(const aItem:T):TpvSizeInt; overload;
function Add(const aItems:array of T):TpvSizeInt; overload;
function Add(const aFrom:{$ifdef fpc}TpvCSGBSP.{$endif}TDynamicArray<T>):TpvSizeInt; overload;
function AddRangeFrom(const aFrom:{$ifdef fpc}TpvCSGBSP.{$endif}TDynamicArray<T>;const aStartIndex,aCount:TpvSizeInt):TpvSizeInt; overload;
function AssignRangeFrom(const aFrom:{$ifdef fpc}TpvCSGBSP.{$endif}TDynamicArray<T>;const aStartIndex,aCount:TpvSizeInt):TpvSizeInt; overload;
procedure Exchange(const aIndexA,aIndexB:TpvSizeInt); inline;
procedure Delete(const aIndex:TpvSizeInt);
end;
TDynamicStack<T>=record
public
Items:array of T;
Count:TpvSizeInt;
procedure Initialize;
procedure Finalize;
procedure Push(const aItem:T);
function Pop(out aItem:T):boolean;
end;
TDynamicQueue<T>=record
public
type TQueueItems=array of T;
public
Items:TQueueItems;
Head:TpvSizeInt;
Tail:TpvSizeInt;
Count:TpvSizeInt;
Size:TpvSizeInt;
procedure Initialize;
procedure Finalize;
procedure GrowResize(const aSize:TpvSizeInt);
procedure Clear;
function IsEmpty:boolean;
procedure EnqueueAtFront(const aItem:T);
procedure Enqueue(const aItem:T);
function Dequeue(out aItem:T):boolean; overload;
function Dequeue:boolean; overload;
function Peek(out aItem:T):boolean;
end;
THashMap<THashMapKey,THashMapValue>=class
public
const CELL_EMPTY=-1;
CELL_DELETED=-2;
ENT_EMPTY=-1;
ENT_DELETED=-2;
type PHashMapEntity=^THashMapEntity;
THashMapEntity=record
Key:THashMapKey;
Value:THashMapValue;
end;
THashMapEntities=array of THashMapEntity;
THashMapEntityIndices=array of TpvSizeInt;
private
{$ifndef fpc}
type THashMapEntityEnumerator=record
private
fHashMap:THashMap<THashMapKey,THashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:THashMapEntity; inline;
public
constructor Create(const aHashMap:THashMap<THashMapKey,THashMapValue>);
function MoveNext:boolean; inline;
property Current:THashMapEntity read GetCurrent;
end;
THashMapKeyEnumerator=record
private
fHashMap:THashMap<THashMapKey,THashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:THashMapKey; inline;
public
constructor Create(const aHashMap:THashMap<THashMapKey,THashMapValue>);
function MoveNext:boolean; inline;
property Current:THashMapKey read GetCurrent;
end;
THashMapValueEnumerator=record
private
fHashMap:THashMap<THashMapKey,THashMapValue>;
fIndex:TpvSizeInt;
function GetCurrent:THashMapValue; inline;
public
constructor Create(const aHashMap:THashMap<THashMapKey,THashMapValue>);
function MoveNext:boolean; inline;
property Current:THashMapValue read GetCurrent;
end;
THashMapEntitiesObject=class
private
fOwner:THashMap<THashMapKey,THashMapValue>;
public
constructor Create(const aOwner:THashMap<THashMapKey,THashMapValue>);
function GetEnumerator:THashMapEntityEnumerator;
end;
THashMapKeysObject=class
private
fOwner:THashMap<THashMapKey,THashMapValue>;
public
constructor Create(const aOwner:THashMap<THashMapKey,THashMapValue>);
function GetEnumerator:THashMapKeyEnumerator;
end;
THashMapValuesObject=class
private
fOwner:THashMap<THashMapKey,THashMapValue>;
function GetValue(const aKey:THashMapKey):THashMapValue; inline;
procedure SetValue(const aKey:THashMapKey;const aValue:THashMapValue); inline;
public
constructor Create(const aOwner:THashMap<THashMapKey,THashMapValue>);
function GetEnumerator:THashMapValueEnumerator;
property Values[const Key:THashMapKey]:THashMapValue read GetValue write SetValue; default;
end;
{$endif}
private
fRealSize:TpvSizeInt;
fLogSize:TpvSizeInt;
fSize:TpvSizeInt;
fEntities:THashMapEntities;
fEntityToCellIndex:THashMapEntityIndices;
fCellToEntityIndex:THashMapEntityIndices;
fDefaultValue:THashMapValue;
fCanShrink:boolean;
{$ifndef fpc}
fEntitiesObject:THashMapEntitiesObject;
fKeysObject:THashMapKeysObject;
fValuesObject:THashMapValuesObject;
{$endif}
function HashData(const aData:TpvPointer;const aDataLength:TpvUInt32):TpvUInt32;
function FindCell(const aKey:THashMapKey):TpvUInt32;
procedure Resize;
protected
function HashKey(const aKey:THashMapKey):TpvUInt32; virtual;
function CompareKey(const aKeyA,aKeyB:THashMapKey):boolean; virtual;
function GetValue(const aKey:THashMapKey):THashMapValue;
procedure SetValue(const aKey:THashMapKey;const aValue:THashMapValue);
public
constructor Create(const aDefaultValue:THashMapValue);
destructor Destroy; override;
procedure Clear;
function Add(const aKey:THashMapKey;const aValue:THashMapValue):PHashMapEntity;
function Get(const aKey:THashMapKey;const aCreateIfNotExist:boolean=false):PHashMapEntity;
function TryGet(const aKey:THashMapKey;out aValue:THashMapValue):boolean;
function ExistKey(const aKey:THashMapKey):boolean;
function Delete(const aKey:THashMapKey):boolean;
property EntityValues[const Key:THashMapKey]:THashMapValue read GetValue write SetValue; default;
{$ifndef fpc}
property Entities:THashMapEntitiesObject read fEntitiesObject;
property Keys:THashMapKeysObject read fKeysObject;
property Values:THashMapValuesObject read fValuesObject;
{$endif}
property CanShrink:boolean read fCanShrink write fCanShrink;
end;
TFloatHashMap<TFloatHashMapValue>=class(THashMap<TFloat,TFloatHashMapValue>)
protected
function HashKey(const aKey:TFloat):TpvUInt32; override;
function CompareKey(const aKeyA,aKeyB:TFloat):boolean; override;
end;
TSizeIntSparseSet=class
public
type TSizeIntArray=array of TpvSizeInt;
private
fSize:TpvSizeInt;
fMaximumSize:TpvSizeInt;
fSparseToDense:TSizeIntArray;
fDense:TSizeIntArray;
function GetValue(const aIndex:TpvSizeInt):TpvSizeInt; inline;
procedure SetValue(const aIndex:TpvSizeInt;const aValue:TpvSizeInt); inline;
public
constructor Create(const aMaximumSize:TpvSizeInt=0);
destructor Destroy; override;
procedure Clear;
procedure Resize(const aNewMaximumSize:TpvSizeInt);
function Contains(const aValue:TpvSizeInt):boolean;
procedure Add(const aValue:TpvSizeInt);
procedure AddNew(const aValue:TpvSizeInt);
procedure Remove(const aValue:TpvSizeInt);
property Size:TpvSizeInt read fSize;
property SparseToDense:TSizeIntArray read fSparseToDense;
property Dense:TSizeIntArray read fDense;
end;
TVector2=record
public
x,y:TFloat;
constructor Create(const aFrom:TpvVector2); overload;
constructor Create(const aX,aY:TFloat); overload;
class operator Equal(const aLeft,aRight:TVector2):boolean;
class operator NotEqual(const aLeft,aRight:TVector2):boolean;
class operator Add(const aLeft,aRight:TVector2):TVector2;
class operator Subtract(const aLeft,aRight:TVector2):TVector2;
class operator Multiply(const aLeft:TVector2;const aRight:TFloat):TVector2;
class operator Divide(const aLeft:TVector2;const aRight:TFloat):TVector2;
class operator Negative(const aVector:TVector2):TVector2;
function Length:TFloat;
function SquaredLength:TFloat;
function Lerp(const aWith:TVector2;const aTime:TFloat):TVector2;
function ToVector:TpvVector2;
end;
PVector2=^TVector2;
TVector3=record
public
x,y,z:TFloat;
constructor Create(const aFrom:TpvVector3); overload;
constructor Create(const aX,aY,aZ:TFloat); overload;
class operator Equal(const aLeft,aRight:TVector3):boolean;
class operator NotEqual(const aLeft,aRight:TVector3):boolean;
class operator Add(const aLeft,aRight:TVector3):TVector3;
class operator Subtract(const aLeft,aRight:TVector3):TVector3;
class operator Multiply(const aLeft:TVector3;const aRight:TFloat):TVector3;
class operator Divide(const aLeft:TVector3;const aRight:TFloat):TVector3;
class operator Negative(const aVector:TVector3):TVector3;
function Cross(const aWith:TVector3):TVector3;
function Spacing(const aWith:TVector3):TFloat;
function Dot(const aWith:TVector3):TFloat;
function Length:TFloat;
function SquaredLength:TFloat;
function Lerp(const aWith:TVector3;const aTime:TFloat):TVector3;
function Normalize:TVector3;
function Perpendicular:TVector3;
function ToVector:TpvVector3;
end;
PVector3=^TVector3;
TVector4=record
public
x,y,z,w:TFloat;
constructor Create(const aFrom:TpvVector4); overload;
constructor Create(const aX,aY,aZ,aW:TFloat); overload;
class operator Equal(const aLeft,aRight:TVector4):boolean;
class operator NotEqual(const aLeft,aRight:TVector4):boolean;
class operator Add(const aLeft,aRight:TVector4):TVector4;
class operator Subtract(const aLeft,aRight:TVector4):TVector4;
class operator Multiply(const aLeft:TVector4;const aRight:TFloat):TVector4;
class operator Divide(const aLeft:TVector4;const aRight:TFloat):TVector4;
class operator Negative(const aVector:TVector4):TVector4;
function Length:TFloat;
function SquaredLength:TFloat;
function Lerp(const aWith:TVector4;const aTime:TFloat):TVector4;
function ToVector:TpvVector4;
end;
PVector4=^TVector4;
TVertex=record
public
Position:TVector3;
Normal:TVector3;
TexCoord:TVector4;
Color:TVector4;
class operator Equal(const aLeft,aRight:TVertex):boolean;
class operator NotEqual(const aLeft,aRight:TVertex):boolean;
class operator Add(const aLeft,aRight:TVertex):TVertex;
class operator Subtract(const aLeft,aRight:TVertex):TVertex;
class operator Multiply(const aLeft:TVertex;const aRight:TFloat):TVertex;
class operator Divide(const aLeft:TVertex;const aRight:TFloat):TVertex;
class operator Negative(const aLeft:TVertex):TVertex;
function Lerp(const aWith:TVertex;const aTime:TFloat):TVertex;
procedure Flip;
function CloneFlip:TVertex;
function Normalize:TVertex;
end;
TAABB=packed record
public
function Cost:TFloat;
function Combine(const aAABB:TAABB):TAABB; overload;
function Combine(const aVector:TVector3):TAABB; overload;
function Contains(const aAABB:TAABB;const aThreshold:TFloat=0.0):boolean;
function Intersects(const aAABB:TAABB;const aThreshold:TFloat=Epsilon):boolean;
function Intersection(const aAABB:TAABB;const aThreshold:TFloat=0.0):TAABB;
public
case boolean of
false:(
Min:TVector3;
Max:TVector3;
);
true:(
MinMax:array[0..1] of TVector3;
);
end;
PAABB=^TAABB;
PVertex=^TVertex;
TVertexList=TDynamicArray<TVertex>;
PVertexList=^TVertexList;
TIndex=TpvSizeInt;
PIndex=^TIndex;
TIndexList=TDynamicArray<TIndex>;
PIndexList=^TIndexList;
TPlane=record
public
Normal:TVector3;
Distance:TFloat;
constructor Create(const aV0,aV1,aV2:TVector3); overload;
constructor Create(const aNormal:TVector3;const aDistance:TFloat); overload;
class function CreateEmpty:TPlane; static;
function DistanceTo(const aWith:TVector3):TFloat;
function IntersectWithPointToPoint(const aPointA,aPointB:TVector3;const aIntersectionPoint:PVector3=nil):boolean; overload;
function IntersectWithPointToPoint(const aPointA,aPointB:TVertex;const aIntersectionPoint:PVertex=nil):boolean; overload;
function OK:boolean;
function Flip:TPlane;
procedure SplitTriangles(var aVertices:TVertexList;
const aIndices:TIndexList;
const aCoplanarBackList:PIndexList;
const aCoplanarFrontList:PIndexList;
const aBackList:PIndexList;
const aFrontList:PIndexList);
procedure SplitPolygons(var aVertices:TVertexList;
const aIndices:TIndexList;
const aCoplanarBackList:PIndexList;
const aCoplanarFrontList:PIndexList;
const aBackList:PIndexList;
const aFrontList:PIndexList);
end;
PPlane=^TPlane;
PDynamicAABBTreeNode=^TDynamicAABBTreeNode;
TDynamicAABBTreeNode=record
AABB:TAABB;
UserData:TpvPtrInt;
Children:array[0..1] of TpvSizeInt;
Height:TpvSizeInt;
case boolean of
false:(
Parent:TpvSizeInt;
);
true:(
Next:TpvSizeInt;
);
end;
PDynamicAABBTreeNodes=^TDynamicAABBTreeNodes;
TDynamicAABBTreeNodes=array[0..0] of TDynamicAABBTreeNode;
PDynamicAABBTreeSizeIntArray=^TDynamicAABBTreeSizeIntArray;
TDynamicAABBTreeSizeIntArray=array[0..65535] of TpvSizeInt;
TDynamicAABBFrozenTreeNode=record
Left:TpvSizeInt;
Right:TpvSizeInt;
AABB:TAABB;
UserData:pointer;
end;
TDynamicAABBTree=class
public
Root:TpvSizeInt;
Nodes:PDynamicAABBTreeNodes;
NodeCount:TpvSizeInt;
NodeCapacity:TpvSizeInt;
FreeList:TpvSizeInt;
Path:TpvSizeUInt;
InsertionCount:TpvSizeInt;
Stack:PDynamicAABBTreeSizeIntArray;
StackCapacity:TpvSizeInt;
constructor Create;
destructor Destroy; override;
function AllocateNode:TpvSizeInt;
procedure FreeNode(const aNodeID:TpvSizeInt);
function Balance(const aNodeID:TpvSizeInt):TpvSizeInt;
procedure InsertLeaf(const aLeaf:TpvSizeInt);
procedure RemoveLeaf(const aLeaf:TpvSizeInt);
function CreateProxy(const aAABB:TAABB;const aUserData:TpvPtrInt):TpvSizeInt;
procedure DestroyProxy(const aNodeID:TpvSizeInt);
function MoveProxy(const aNodeID:TpvSizeInt;const aAABB:TAABB;const aDisplacement:TVector3):boolean;
procedure Rebalance(const aIterations:TpvSizeInt);
end;
TSplitSettings=record
SearchBestFactor:TFloat;
PolygonSplitCost:TFloat;
PolygonImbalanceCost:TFloat;
end;
PSplitSettings=^TSplitSettings;
TVector3HashMap<TVector3HashMapValue>=class(TpvCSGBSP.THashMap<TpvCSGBSP.TVector3,TVector3HashMapValue>)
protected
function HashKey(const aKey:TpvCSGBSP.TVector3):TpvUInt32; override;
function CompareKey(const aKeyA,aKeyB:TpvCSGBSP.TVector3):boolean; override;
end;
TSingleTreeNode=class;
TDualTree=class;
TMesh=class
public
type TCSGOperation=
(
Union,
Subtraction,
Intersection
);
PCSGOperation=^TCSGOperation;
TCSGMode=(
SingleTree,
DualTree,
Triangles
);
PCSGMode=^TCSGMode;
TCSGOptimization=(
None,
CSG,
Polygons
);
PCSGOptimization=^TCSGOptimization;
TMode=
(
Triangles,
Polygons
);
PMode=^TMode;
private
fMode:TMode;
fVertices:TVertexList;
fIndices:TIndexList;
fPointerToVertices:PVertexList;
fPointerToIndices:PIndexList;
procedure SetMode(const aMode:TMode);
procedure SetVertices(const aVertices:TVertexList);
procedure SetIndices(const aIndices:TIndexList);
procedure TriangleCSGOperation(const aLeftNode:TSingleTreeNode;
const aRightNode:TSingleTreeNode;
const aVertices:TVertexList;
const aInside:boolean;
const aKeepEdge:boolean;
const aInvert:boolean);
procedure FastSplitPolygonsIntoOuterAndInnerMeshsByInsideRangeAABB(const aOuterLeftMesh:TMesh;
const aInnerLeftMesh:TMesh;
const aInsideRangeAABB:TAABB);
procedure DoUnion(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode;
const aSplitSettings:PSplitSettings=nil);
procedure DoSubtraction(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode;
const aSplitSettings:PSplitSettings=nil);
procedure DoIntersection(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode;
const aSplitSettings:PSplitSettings=nil);
public
constructor Create(const aMode:TMode=TMode.Polygons); reintroduce; overload;
constructor Create(const aFrom:TMesh); reintroduce; overload;
constructor Create(const aFrom:TSingleTreeNode); reintroduce; overload;
constructor Create(const aFrom:TDualTree); reintroduce; overload;
constructor Create(const aFrom:TAABB;const aMode:TMode=TMode.Polygons;const aAdditionalBounds:TFloat=0.0); reintroduce; overload;
constructor CreateCube(const aCX,aCY,aCZ,aRX,aRY,aRZ:TFloat;const aMode:TMode=TMode.Polygons);
constructor CreateSphere(const aCX,aCY,aCZ,aRadius:TFloat;const aSlices:TpvSizeInt=16;const aStacks:TpvSizeInt=8;const aMode:TMode=TMode.Polygons);
constructor CreateFromCSGOperation(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGOperation:TCSGOperation;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
constructor CreateUnion(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
constructor CreateSubtraction(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
constructor CreateIntersection(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
constructor CreateSymmetricDifference(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
destructor Destroy; override;
procedure SaveOBJToStream(const aStream:TStream);
procedure SaveOBJToFile(const aFileName:string);
procedure Clear;
procedure Assign(const aFrom:TMesh); overload;
procedure Assign(const aFrom:TSingleTreeNode); overload;
procedure Assign(const aFrom:TDualTree); overload;
procedure Append(const aFrom:TMesh); overload;
procedure Append(const aFrom:TSingleTreeNode); overload;
procedure Append(const aFrom:TDualTree); overload;
function AddVertex(const aVertex:TVertex):TIndex;
function AddVertices(const aVertices:array of TVertex):TIndex; overload;
function AddVertices(const aVertices:TVertexList):TIndex; overload;
function AddIndex(const aIndex:TIndex):TpvSizeInt;
function AddIndices(const aIndices:array of TIndex):TpvSizeInt; overload;
function AddIndices(const aIndices:TIndexList):TpvSizeInt; overload;
function GetAxisAlignedBoundingBox:TAABB;
procedure Invert;
procedure ConvertToPolygons;
procedure ConvertToTriangles;
procedure RemoveNearDuplicateIndices(var aIndices:TIndexList);
procedure Union(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil); overload;
procedure Union(const aWithMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil); overload;
procedure UnionOf(const aMeshs:array of TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
procedure Subtraction(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil); overload;
procedure Subtraction(const aWithMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil); overload;
procedure SubtractionOf(const aMeshs:array of TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
procedure Intersection(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil); overload;
procedure Intersection(const aWithMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil); overload;
procedure IntersectionOf(const aMeshs:array of TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
procedure SymmetricDifference(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil); overload;
procedure SymmetricDifference(const aWithMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil); overload;
procedure SymmetricDifferenceOf(const aMeshs:array of TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
procedure Canonicalize;
procedure CalculateNormals(const aCreasedNormalAngleThreshold:TFloat=90.0;
const aSoftNormals:boolean=true;
const aAreaWeighting:boolean=true;
const aAngleWeighting:boolean=true;
const aCreasedNormalAngleWeighting:boolean=true;
const aCheckForCreasedNormals:boolean=true);
procedure RemoveDuplicateAndUnusedVertices;
procedure FixTJunctions(const aConsistentInputVertices:boolean=false);
procedure MergeCoplanarConvexPolygons;
procedure Optimize;
function ToSingleTreeNode(const aSplitSettings:PSplitSettings=nil):TSingleTreeNode;
function ToDualTree(const aSplitSettings:PSplitSettings=nil):TDualTree;
public
property Vertices:TVertexList read fVertices write SetVertices;
property Indices:TIndexList read fIndices write SetIndices;
property PointerToVertices:PVertexList read fPointerToVertices;
property PointerToIndices:PIndexList read fPointerToIndices;
published
property Mode:TMode read fMode write SetMode;
end;
TSingleTreeNode=class
private
fIndices:TIndexList;
fPointerToIndices:PIndexList;
fMesh:TMesh;
fBack:TSingleTreeNode;
fFront:TSingleTreeNode;
fPlane:TPlane;
procedure SetIndices(const aIndices:TIndexList);
public
constructor Create(const aMesh:TMesh); reintroduce;
destructor Destroy; override;
procedure Invert;
procedure EvaluateSplitPlane(const aPlane:TPlane;
out aCountPolygonsSplits:TpvSizeInt;
out aCountBackPolygons:TpvSizeInt;
out aCountFrontPolygons:TpvSizeInt);
function FindSplitPlane(const aIndices:TIndexList;
const aSplitSettings:PSplitSettings):TPlane;
function ClipPolygons(var aVertices:TVertexList;const aIndices:TIndexList):TIndexList;
procedure ClipTo(const aNode:TSingleTreeNode);
procedure Merge(const aNode:TSingleTreeNode;
const aSplitSettings:PSplitSettings=nil);
procedure Build(const aIndices:TIndexList;
const aSplitSettings:PSplitSettings=nil);
function ToMesh:TMesh;
public
property Plane:TPlane read fPlane write fPlane;
property Indices:TIndexList read fIndices write SetIndices;
property PointerToIndices:PIndexList read fPointerToIndices;
published
property Mesh:TMesh read fMesh write fMesh;
property Back:TSingleTreeNode read fBack write fBack;
property Front:TSingleTreeNode read fFront write fFront;
end;
TDualTree=class
public
type TPolygon=record
public
Indices:TIndexList;
procedure Invert;
end;
PPolygon=^TPolygon;
TPolygonList=TDynamicArray<TPolygon>;
PPolygonList=^TPolygonList;
TPolygonNode=class;
TPolygonNodeList=TDynamicArray<TPolygonNode>;
PPolygonNodeList=^TPolygonNodeList;
TPolygonNode=class
private
fTree:TDualTree;
fParent:TDualTree.TPolygonNode;
fParentPrevious:TDualTree.TPolygonNode;
fParentNext:TDualTree.TPolygonNode;
fAllPrevious:TDualTree.TPolygonNode;
fAllNext:TDualTree.TPolygonNode;
fFirstChild:TDualTree.TPolygonNode;
fLastChild:TDualTree.TPolygonNode;
fRemoved:boolean;
fPolygon:TPolygon;
public
constructor Create(const aTree:TDualTree;const aParent:TDualTree.TPolygonNode); reintroduce;
destructor Destroy; override;
procedure RemoveFromParent;
function AddPolygon(const aPolygon:TPolygon):TDualTree.TPolygonNode;
function AddPolygonIndices(const aIndices:TIndexList):TDualTree.TPolygonNode;
procedure Remove;
procedure Invert;
procedure DrySplitByPlane(const aPlane:TPlane;var aCountSplits,aCoplanarBackList,aCoplanarFrontList,aBackList,aFrontList:TpvSizeInt);
procedure SplitByPlane(const aPlane:TPlane;var aCoplanarBackList,aCoplanarFrontList,aBackList,aFrontList:TPolygonNodeList);
published
property Tree:TDualTree read fTree write fTree;
property Parent:TDualTree.TPolygonNode read fParent;
property Removed:boolean read fRemoved;
end;
TNode=class
private
fTree:TDualTree;
fBack:TDualTree.TNode;
fFront:TDualTree.TNode;
fPlane:TPlane;
fPolygonNodes:TPolygonNodeList;
fIndices:TIndexList;
public
constructor Create(const aTree:TDualTree); reintroduce;
destructor Destroy; override;
procedure Invert;
procedure ClipPolygons(const aPolygonNodes:TPolygonNodeList;const aAlsoRemoveCoplanarFront:boolean=false);
procedure ClipTo(const aTree:TDualTree;const aAlsoRemoveCoplanarFront:boolean=false);
function FindSplitPlane(const aPolygonNodes:TPolygonNodeList):TPlane;
procedure AddPolygonNodes(const aPolygonNodes:TPolygonNodeList);
procedure AddIndices(const aIndices:TIndexList);
public
property Plane:TPlane read fPlane write fPlane;
published
property Tree:TDualTree read fTree write fTree;
property Back:TDualTree.TNode read fBack write fBack;
property Front:TDualTree.TNode read fFront write fFront;
end;
private
fMesh:TMesh;
fSplitSettings:TSplitSettings;
fFirstPolygonNode:TDualTree.TPolygonNode;
fLastPolygonNode:TDualTree.TPolygonNode;
fPolygonRootNode:TDualTree.TPolygonNode;
fRootNode:TDualTree.TNode;
public
constructor Create(const aMesh:TMesh;const aSplitSettings:PSplitSettings=nil); reintroduce;
destructor Destroy; override;
procedure Invert;
procedure ClipTo(const aWithTree:TDualTree;const aAlsoRemoveCoplanarFront:boolean=false);
procedure AddPolygons(const aPolygons:TPolygonList);
procedure AddIndices(const aIndices:TIndexList);
procedure GetPolygons(var aPolygons:TPolygonList);
procedure GetIndices(var aIndices:TIndexList);
procedure Merge(const aTree:TDualTree);
function ToMesh:TMesh;
end;
public
const DefaultSplitSettings:TSplitSettings=
(
SearchBestFactor:0.0;
PolygonSplitCost:1.0;
PolygonImbalanceCost:0.25;
);
ThresholdAABBVector:TVector3=(x:AABBEPSILON;y:AABBEPSILON;z:AABBEPSILON);
public
class function EpsilonSign(const aValue:TFloat):TpvSizeInt; static;
end;
implementation
{ TpvCSGBSP }
class function TpvCSGBSP.EpsilonSign(const aValue:TFloat):TpvSizeInt;
begin
if aValue<-Epsilon then begin
result:=-1;
end else if aValue>Epsilon then begin
result:=1;
end else begin
result:=0;
end;
end;
{ TpvCSGBSP.TDynamicArray<T> }
procedure TpvCSGBSP.TDynamicArray<T>.Initialize;
begin
Items:=nil;
Count:=0;
end;
procedure TpvCSGBSP.TDynamicArray<T>.Finalize;
begin
Items:=nil;
Count:=0;
end;
procedure TpvCSGBSP.TDynamicArray<T>.Clear;
begin
Items:=nil;
Count:=0;
end;
procedure TpvCSGBSP.TDynamicArray<T>.Finish;
begin
SetLength(Items,Count);
end;
procedure TpvCSGBSP.TDynamicArray<T>.Assign(const aFrom:TpvCSGBSP.TDynamicArray<T>);
begin
Items:=copy(aFrom.Items);
Count:=aFrom.Count;
end;
procedure TpvCSGBSP.TDynamicArray<T>.Assign(const aItems:array of T);
var Index:TpvSizeInt;
begin
Count:=length(aItems);
SetLength(Items,Count);
for Index:=0 to Count-1 do begin
Items[Index]:=aItems[Index];
end;
end;
function TpvCSGBSP.TDynamicArray<T>.Insert(const aIndex:TpvSizeInt;const aItem:T):TpvSizeInt;
begin
result:=aIndex;
if aIndex>=0 then begin
if aIndex<Count then begin
inc(Count);
if length(Items)<Count then begin
SetLength(Items,Count*2);
end;
Move(Items[aIndex],Items[aIndex+1],(Count-(aIndex+1))*SizeOf(T));
FillChar(Items[aIndex],SizeOf(T),#0);
end else begin
Count:=aIndex+1;
if length(Items)<Count then begin
SetLength(Items,Count*2);
end;
end;
Items[aIndex]:=aItem;
end;
end;
function TpvCSGBSP.TDynamicArray<T>.AddNew:TpvSizeInt;
begin
result:=Count;
if length(Items)<(Count+1) then begin
SetLength(Items,(Count+1)+((Count+1) shr 1));
end;
System.Initialize(Items[Count]);
inc(Count);
end;
function TpvCSGBSP.TDynamicArray<T>.Add(const aItem:T):TpvSizeInt;
begin
result:=Count;
if length(Items)<(Count+1) then begin
SetLength(Items,(Count+1)+((Count+1) shr 1));
end;
Items[Count]:=aItem;
inc(Count);
end;
function TpvCSGBSP.TDynamicArray<T>.Add(const aItems:array of T):TpvSizeInt;
var Index,FromCount:TpvSizeInt;
begin
result:=Count;
FromCount:=length(aItems);
if FromCount>0 then begin
if length(Items)<(Count+FromCount) then begin
SetLength(Items,(Count+FromCount)+((Count+FromCount) shr 1));
end;
for Index:=0 to FromCount-1 do begin
Items[Count]:=aItems[Index];
inc(Count);
end;
end;
end;
function TpvCSGBSP.TDynamicArray<T>.Add(const aFrom:TpvCSGBSP.TDynamicArray<T>):TpvSizeInt;
var Index:TpvSizeInt;
begin
result:=Count;
if aFrom.Count>0 then begin
if length(Items)<(Count+aFrom.Count) then begin
SetLength(Items,(Count+aFrom.Count)+((Count+aFrom.Count) shr 1));
end;
for Index:=0 to aFrom.Count-1 do begin
Items[Count]:=aFrom.Items[Index];
inc(Count);
end;
end;
end;
function TpvCSGBSP.TDynamicArray<T>.AddRangeFrom(const aFrom:{$ifdef fpc}TpvCSGBSP.{$endif}TDynamicArray<T>;const aStartIndex,aCount:TpvSizeInt):TpvSizeInt;
var Index:TpvSizeInt;
begin
result:=Count;
if aCount>0 then begin
if length(Items)<(Count+aCount) then begin
SetLength(Items,(Count+aCount)+((Count+aCount) shr 1));
end;
for Index:=0 to aCount-1 do begin
Items[Count]:=aFrom.Items[aStartIndex+Index];
inc(Count);
end;
end;
end;
function TpvCSGBSP.TDynamicArray<T>.AssignRangeFrom(const aFrom:{$ifdef fpc}TpvCSGBSP.{$endif}TDynamicArray<T>;const aStartIndex,aCount:TpvSizeInt):TpvSizeInt;
begin
Clear;
result:=AddRangeFrom(aFrom,aStartIndex,aCount);
end;
procedure TpvCSGBSP.TDynamicArray<T>.Exchange(const aIndexA,aIndexB:TpvSizeInt);
var Temp:T;
begin
Temp:=Items[aIndexA];
Items[aIndexA]:=Items[aIndexB];
Items[aIndexB]:=Temp;
end;
procedure TpvCSGBSP.TDynamicArray<T>.Delete(const aIndex:TpvSizeInt);
begin
if (Count>0) and (aIndex<Count) then begin
dec(Count);
System.Finalize(Items[aIndex]);
Move(Items[aIndex+1],Items[aIndex],SizeOf(T)*(Count-aIndex));
FillChar(Items[Count],SizeOf(T),#0);
end;
end;
{ TpvCSGBSP.TDynamicStack<T> }
procedure TpvCSGBSP.TDynamicStack<T>.Initialize;
begin
Items:=nil;
Count:=0;
end;
procedure TpvCSGBSP.TDynamicStack<T>.Finalize;
begin
Items:=nil;
Count:=0;
end;
procedure TpvCSGBSP.TDynamicStack<T>.Push(const aItem:T);
begin
if length(Items)<(Count+1) then begin
SetLength(Items,(Count+1)+((Count+1) shr 1));
end;
Items[Count]:=aItem;
inc(Count);
end;
function TpvCSGBSP.TDynamicStack<T>.Pop(out aItem:T):boolean;
begin
result:=Count>0;
if result then begin
dec(Count);
aItem:=Items[Count];
end;
end;
{ TpvCSGBSP.TDynamicQueue<T> }
procedure TpvCSGBSP.TDynamicQueue<T>.Initialize;
begin
Items:=nil;
Head:=0;
Tail:=0;
Count:=0;
Size:=0;
end;
procedure TpvCSGBSP.TDynamicQueue<T>.Finalize;
begin
Clear;
end;
procedure TpvCSGBSP.TDynamicQueue<T>.GrowResize(const aSize:TpvSizeInt);
var Index,OtherIndex:TpvSizeInt;
NewItems:TQueueItems;
begin
SetLength(NewItems,aSize);
OtherIndex:=Head;
for Index:=0 to Count-1 do begin
NewItems[Index]:=Items[OtherIndex];
inc(OtherIndex);
if OtherIndex>=Size then begin
OtherIndex:=0;
end;
end;
Items:=NewItems;
Head:=0;
Tail:=Count;
Size:=aSize;
end;
procedure TpvCSGBSP.TDynamicQueue<T>.Clear;
begin
while Count>0 do begin
dec(Count);
System.Finalize(Items[Head]);
inc(Head);
if Head>=Size then begin
Head:=0;
end;
end;
Items:=nil;
Head:=0;
Tail:=0;
Count:=0;
Size:=0;
end;
function TpvCSGBSP.TDynamicQueue<T>.IsEmpty:boolean;
begin
result:=Count=0;
end;
procedure TpvCSGBSP.TDynamicQueue<T>.EnqueueAtFront(const aItem:T);
var Index:TpvSizeInt;
begin
if Size<=Count then begin
GrowResize(Count+1);
end;
dec(Head);
if Head<0 then begin
inc(Head,Size);
end;
Index:=Head;
Items[Index]:=aItem;
inc(Count);
end;
procedure TpvCSGBSP.TDynamicQueue<T>.Enqueue(const aItem:T);
var Index:TpvSizeInt;
begin
if Size<=Count then begin
GrowResize(Count+1);
end;
Index:=Tail;
inc(Tail);
if Tail>=Size then begin
Tail:=0;
end;
Items[Index]:=aItem;
inc(Count);
end;
function TpvCSGBSP.TDynamicQueue<T>.Dequeue(out aItem:T):boolean;
begin
result:=Count>0;
if result then begin
dec(Count);
aItem:=Items[Head];
System.Finalize(Items[Head]);
FillChar(Items[Head],SizeOf(T),#0);
if Count=0 then begin
Head:=0;
Tail:=0;
end else begin
inc(Head);
if Head>=Size then begin
Head:=0;
end;
end;
end;
end;
function TpvCSGBSP.TDynamicQueue<T>.Dequeue:boolean;
begin
result:=Count>0;
if result then begin
dec(Count);
System.Finalize(Items[Head]);
FillChar(Items[Head],SizeOf(T),#0);
if Count=0 then begin
Head:=0;
Tail:=0;
end else begin
inc(Head);
if Head>=Size then begin
Head:=0;
end;
end;
end;
end;
function TpvCSGBSP.TDynamicQueue<T>.Peek(out aItem:T):boolean;
begin
result:=Count>0;
if result then begin
aItem:=Items[Head];
end;
end;
{ TpvCSGBSP.THashMap }
{$warnings off}
{$hints off}
{$ifndef fpc}
constructor TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapEntityEnumerator.Create(const aHashMap:THashMap<THashMapKey,THashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapEntityEnumerator.GetCurrent:THashMapEntity;
begin
result:=fHashMap.fEntities[fIndex];
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapEntityEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if fHashMap.fEntityToCellIndex[fIndex]<>CELL_EMPTY then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapKeyEnumerator.Create(const aHashMap:THashMap<THashMapKey,THashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapKeyEnumerator.GetCurrent:THashMapKey;
begin
result:=fHashMap.fEntities[fIndex].Key;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapKeyEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if fHashMap.fEntityToCellIndex[fIndex]<>CELL_EMPTY then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapValueEnumerator.Create(const aHashMap:THashMap<THashMapKey,THashMapValue>);
begin
fHashMap:=aHashMap;
fIndex:=-1;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapValueEnumerator.GetCurrent:THashMapValue;
begin
result:=fHashMap.fEntities[fIndex].Value;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapValueEnumerator.MoveNext:boolean;
begin
repeat
inc(fIndex);
if fIndex<fHashMap.fSize then begin
if fHashMap.fEntityToCellIndex[fIndex]<>CELL_EMPTY then begin
result:=true;
exit;
end;
end else begin
break;
end;
until false;
result:=false;
end;
constructor TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapEntitiesObject.Create(const aOwner:THashMap<THashMapKey,THashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapEntitiesObject.GetEnumerator:THashMapEntityEnumerator;
begin
result:=THashMapEntityEnumerator.Create(fOwner);
end;
constructor TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapKeysObject.Create(const aOwner:THashMap<THashMapKey,THashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapKeysObject.GetEnumerator:THashMapKeyEnumerator;
begin
result:=THashMapKeyEnumerator.Create(fOwner);
end;
constructor TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapValuesObject.Create(const aOwner:THashMap<THashMapKey,THashMapValue>);
begin
inherited Create;
fOwner:=aOwner;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapValuesObject.GetEnumerator:THashMapValueEnumerator;
begin
result:=THashMapValueEnumerator.Create(fOwner);
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapValuesObject.GetValue(const aKey:THashMapKey):THashMapValue;
begin
result:=fOwner.GetValue(aKey);
end;
procedure TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.THashMapValuesObject.SetValue(const aKey:THashMapKey;const aValue:THashMapValue);
begin
fOwner.SetValue(aKey,aValue);
end;
{$endif}
constructor TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.Create(const aDefaultValue:THashMapValue);
begin
inherited Create;
fRealSize:=0;
fLogSize:=0;
fSize:=0;
fEntities:=nil;
fEntityToCellIndex:=nil;
fCellToEntityIndex:=nil;
fDefaultValue:=aDefaultValue;
fCanShrink:=true;
{$ifndef fpc}
fEntitiesObject:=THashMapEntitiesObject.Create(self);
fKeysObject:=THashMapKeysObject.Create(self);
fValuesObject:=THashMapValuesObject.Create(self);
{$endif}
Resize;
end;
destructor TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.Destroy;
var Counter:TpvInt32;
begin
Clear;
for Counter:=0 to length(fEntities)-1 do begin
Finalize(fEntities[Counter].Key);
Finalize(fEntities[Counter].Value);
end;
SetLength(fEntities,0);
SetLength(fEntityToCellIndex,0);
SetLength(fCellToEntityIndex,0);
{$ifndef fpc}
FreeAndNil(fEntitiesObject);
FreeAndNil(fKeysObject);
FreeAndNil(fValuesObject);
{$endif}
inherited Destroy;
end;
procedure TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.Clear;
var Counter:TpvInt32;
begin
for Counter:=0 to length(fEntities)-1 do begin
Finalize(fEntities[Counter].Key);
Finalize(fEntities[Counter].Value);
end;
if fCanShrink then begin
fRealSize:=0;
fLogSize:=0;
fSize:=0;
SetLength(fEntities,0);
SetLength(fEntityToCellIndex,0);
SetLength(fCellToEntityIndex,0);
Resize;
end else begin
for Counter:=0 to length(fCellToEntityIndex)-1 do begin
fCellToEntityIndex[Counter]:=ENT_EMPTY;
end;
for Counter:=0 to length(fEntityToCellIndex)-1 do begin
fEntityToCellIndex[Counter]:=CELL_EMPTY;
end;
end;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.HashData(const aData:TpvPointer;const aDataLength:TpvUInt32):TpvUInt32;
// xxHash32
const PRIME32_1=TpvUInt32(2654435761);
PRIME32_2=TpvUInt32(2246822519);
PRIME32_3=TpvUInt32(3266489917);
PRIME32_4=TpvUInt32(668265263);
PRIME32_5=TpvUInt32(374761393);
Seed=TpvUInt32($1337c0d3);
v1Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_1)+TpvUInt64(PRIME32_2)));
v2Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_2)));
v3Initialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(0)));
v4Initialization=TpvUInt32(TpvUInt64(TpvInt64(TpvInt64(Seed)-TpvInt64(PRIME32_1))));
HashInitialization=TpvUInt32(TpvUInt64(TpvUInt64(Seed)+TpvUInt64(PRIME32_5)));
var v1,v2,v3,v4:TpvUInt32;
p,e,Limit:PpvUInt8;
begin
p:=aData;
if aDataLength>=16 then begin
v1:=v1Initialization;
v2:=v2Initialization;
v3:=v3Initialization;
v4:=v4Initialization;
e:=@PpvUInt8Array(aData)^[aDataLength-16];
repeat
{$if defined(fpc) or declared(ROLDWord)}
v1:=ROLDWord(v1+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v1,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v1:=((v1 shl 13) or (v1 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v2:=ROLDWord(v2+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v2,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v2:=((v2 shl 13) or (v2 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v3:=ROLDWord(v3+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v3,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v3:=((v3 shl 13) or (v3 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
{$if defined(fpc) or declared(ROLDWord)}
v4:=ROLDWord(v4+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2)),13)*TpvUInt32(PRIME32_1);
{$else}
inc(v4,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_2));
v4:=((v4 shl 13) or (v4 shr 19))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt32));
until {%H-}TpvPtrUInt(p)>{%H-}TpvPtrUInt(e);
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(v1,1)+ROLDWord(v2,7)+ROLDWord(v3,12)+ROLDWord(v4,18);
{$else}
result:=((v1 shl 1) or (v1 shr 31))+
((v2 shl 7) or (v2 shr 25))+
((v3 shl 12) or (v3 shr 20))+
((v4 shl 18) or (v4 shr 14));
{$ifend}
end else begin
result:=HashInitialization;
end;
inc(result,aDataLength);
e:=@PpvUInt8Array(aData)^[aDataLength];
while ({%H-}TpvPtrUInt(p)+SizeOf(TpvUInt32))<={%H-}TpvPtrUInt(e) do begin
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(result+(TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_3)),17)*TpvUInt32(PRIME32_4);
{$else}
inc(result,TpvUInt32(TpvPointer(p)^)*TpvUInt32(PRIME32_3));
result:=((result shl 17) or (result shr 15))*TpvUInt32(PRIME32_4);
{$ifend}
inc(p,SizeOf(TpvUInt32));
end;
while {%H-}TpvPtrUInt(p)<{%H-}TpvPtrUInt(e) do begin
{$if defined(fpc) or declared(ROLDWord)}
result:=ROLDWord(result+(TpvUInt8(TpvPointer(p)^)*TpvUInt32(PRIME32_5)),11)*TpvUInt32(PRIME32_1);
{$else}
inc(result,TpvUInt8(TpvPointer(p)^)*TpvUInt32(PRIME32_5));
result:=((result shl 11) or (result shr 21))*TpvUInt32(PRIME32_1);
{$ifend}
inc(p,SizeOf(TpvUInt8));
end;
result:=(result xor (result shr 15))*TpvUInt32(PRIME32_2);
result:=(result xor (result shr 13))*TpvUInt32(PRIME32_3);
result:=result xor (result shr 16);
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.HashKey(const aKey:THashMapKey):TpvUInt32;
var p:TpvUInt64;
begin
// We're hoping here that the compiler is here so smart, so that the compiler optimizes the
// unused if-branches away
case SizeOf(THashMapKey) of
SizeOf(UInt16):begin
// 16-bit big => use 16-bit integer-rehashing
result:=TpvUInt16(TpvPointer(@aKey)^);
result:=(result or (((not result) and $ffff) shl 16));
dec(result,result shl 6);
result:=result xor (result shr 17);
dec(result,result shl 9);
result:=result xor (result shl 4);
dec(result,result shl 3);
result:=result xor (result shl 10);
result:=result xor (result shr 15);
end;
SizeOf(TpvUInt32):begin
// 32-bit big => use 32-bit integer-rehashing
result:=TpvUInt32(TpvPointer(@aKey)^);
dec(result,result shl 6);
result:=result xor (result shr 17);
dec(result,result shl 9);
result:=result xor (result shl 4);
dec(result,result shl 3);
result:=result xor (result shl 10);
result:=result xor (result shr 15);
end;
SizeOf(TpvUInt64):begin
// 64-bit big => use 64-bit to 32-bit integer-rehashing
p:=TpvUInt64(TpvPointer(@aKey)^);
p:=(not p)+(p shl 18); // p:=((p shl 18)-p-)1;
p:=p xor (p shr 31);
p:=p*21; // p:=(p+(p shl 2))+(p shl 4);
p:=p xor (p shr 11);
p:=p+(p shl 6);
result:=TpvUInt32(TpvPtrUInt(p xor (p shr 22)));
end;
else begin
result:=HashData(PpvUInt8(TpvPointer(@aKey)),SizeOf(THashMapKey));
end;
end;
{$if defined(CPU386) or defined(CPUAMD64)}
// Special case: The hash value may be never zero
result:=result or (-TpvUInt32(ord(result=0) and 1));
{$else}
if result=0 then begin
// Special case: The hash value may be never zero
result:=$ffffffff;
end;
{$ifend}
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.CompareKey(const aKeyA,aKeyB:THashMapKey):boolean;
var Index:TpvInt32;
pA,pB:PpvUInt8Array;
begin
// We're hoping also here that the compiler is here so smart, so that the compiler optimizes the
// unused if-branches away
case SizeOf(THashMapKey) of
SizeOf(TpvUInt8):begin
result:=UInt8(TpvPointer(@aKeyA)^)=UInt8(TpvPointer(@aKeyB)^);
end;
SizeOf(TpvUInt16):begin
result:=UInt16(TpvPointer(@aKeyA)^)=UInt16(TpvPointer(@aKeyB)^);
end;
SizeOf(TpvUInt32):begin
result:=TpvUInt32(TpvPointer(@aKeyA)^)=TpvUInt32(TpvPointer(@aKeyB)^);
end;
SizeOf(TpvUInt64):begin
result:=TpvUInt64(TpvPointer(@aKeyA)^)=TpvUInt64(TpvPointer(@aKeyB)^);
end;
else begin
Index:=0;
pA:=@aKeyA;
pB:=@aKeyB;
while (Index+SizeOf(TpvUInt32))<SizeOf(THashMapKey) do begin
if TpvUInt32(TpvPointer(@pA^[Index])^)<>TpvUInt32(TpvPointer(@pB^[Index])^) then begin
result:=false;
exit;
end;
inc(Index,SizeOf(TpvUInt32));
end;
while (Index+SizeOf(UInt8))<SizeOf(THashMapKey) do begin
if UInt8(TpvPointer(@pA^[Index])^)<>UInt8(TpvPointer(@pB^[Index])^) then begin
result:=false;
exit;
end;
inc(Index,SizeOf(UInt8));
end;
result:=true;
end;
end;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.FindCell(const aKey:THashMapKey):TpvUInt32;
var HashCode,Mask,Step:TpvUInt32;
Entity:TpvInt32;
begin
HashCode:=HashKey(aKey);
Mask:=(2 shl fLogSize)-1;
Step:=((HashCode shl 1)+1) and Mask;
if fLogSize<>0 then begin
result:=HashCode shr (32-fLogSize);
end else begin
result:=0;
end;
repeat
Entity:=fCellToEntityIndex[result];
if (Entity=ENT_EMPTY) or ((Entity<>ENT_DELETED) and CompareKey(fEntities[Entity].Key,aKey)) then begin
exit;
end;
result:=(result+Step) and Mask;
until false;
end;
procedure TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.Resize;
var NewLogSize,NewSize,Cell,Entity,Counter:TpvInt32;
OldEntities:THashMapEntities;
OldCellToEntityIndex:THashMapEntityIndices;
OldEntityToCellIndex:THashMapEntityIndices;
begin
NewLogSize:=0;
NewSize:=fRealSize;
while NewSize<>0 do begin
NewSize:=NewSize shr 1;
inc(NewLogSize);
end;
if NewLogSize<1 then begin
NewLogSize:=1;
end;
fSize:=0;
fRealSize:=0;
fLogSize:=NewLogSize;
OldEntities:=fEntities;
OldCellToEntityIndex:=fCellToEntityIndex;
OldEntityToCellIndex:=fEntityToCellIndex;
fEntities:=nil;
fCellToEntityIndex:=nil;
fEntityToCellIndex:=nil;
SetLength(fEntities,2 shl fLogSize);
SetLength(fCellToEntityIndex,2 shl fLogSize);
SetLength(fEntityToCellIndex,2 shl fLogSize);
for Counter:=0 to length(fCellToEntityIndex)-1 do begin
fCellToEntityIndex[Counter]:=ENT_EMPTY;
end;
for Counter:=0 to length(fEntityToCellIndex)-1 do begin
fEntityToCellIndex[Counter]:=CELL_EMPTY;
end;
for Counter:=0 to length(OldEntityToCellIndex)-1 do begin
Cell:=OldEntityToCellIndex[Counter];
if Cell>=0 then begin
Entity:=OldCellToEntityIndex[Cell];
if Entity>=0 then begin
Add(OldEntities[Counter].Key,OldEntities[Counter].Value);
end;
end;
end;
for Counter:=0 to length(OldEntities)-1 do begin
Finalize(OldEntities[Counter].Key);
Finalize(OldEntities[Counter].Value);
end;
SetLength(OldEntities,0);
SetLength(OldCellToEntityIndex,0);
SetLength(OldEntityToCellIndex,0);
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.Add(const aKey:THashMapKey;const aValue:THashMapValue):PHashMapEntity;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
result:=nil;
while fRealSize>=(1 shl fLogSize) do begin
Resize;
end;
Cell:=FindCell(aKey);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=@fEntities[Entity];
result^.Key:=aKey;
result^.Value:=aValue;
exit;
end;
Entity:=fSize;
inc(fSize);
if Entity<(2 shl fLogSize) then begin
fCellToEntityIndex[Cell]:=Entity;
fEntityToCellIndex[Entity]:=Cell;
inc(fRealSize);
result:=@fEntities[Entity];
result^.Key:=aKey;
result^.Value:=aValue;
end;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.Get(const aKey:THashMapKey;const aCreateIfNotExist:boolean=false):PHashMapEntity;
var Entity:TpvInt32;
Cell:TpvUInt32;
Value:THashMapValue;
begin
result:=nil;
Cell:=FindCell(aKey);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=@fEntities[Entity];
end else if aCreateIfNotExist then begin
Initialize(Value);
result:=Add(aKey,Value);
end;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.TryGet(const aKey:THashMapKey;out aValue:THashMapValue):boolean;
var Entity:TpvInt32;
begin
Entity:=fCellToEntityIndex[FindCell(aKey)];
result:=Entity>=0;
if result then begin
aValue:=fEntities[Entity].Value;
end else begin
Initialize(aValue);
end;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.ExistKey(const aKey:THashMapKey):boolean;
begin
result:=fCellToEntityIndex[FindCell(aKey)]>=0;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.Delete(const aKey:THashMapKey):boolean;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
result:=false;
Cell:=FindCell(aKey);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
Finalize(fEntities[Entity].Key);
Finalize(fEntities[Entity].Value);
fEntityToCellIndex[Entity]:=CELL_DELETED;
fCellToEntityIndex[Cell]:=ENT_DELETED;
result:=true;
end;
end;
function TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.GetValue(const aKey:THashMapKey):THashMapValue;
var Entity:TpvInt32;
Cell:TpvUInt32;
begin
Cell:=FindCell(aKey);
Entity:=fCellToEntityIndex[Cell];
if Entity>=0 then begin
result:=fEntities[Entity].Value;
end else begin
result:=fDefaultValue;
end;
end;
procedure TpvCSGBSP.THashMap<THashMapKey,THashMapValue>.SetValue(const aKey:THashMapKey;const aValue:THashMapValue);
begin
Add(aKey,aValue);
end;
{ TpvCSGBSP.TFloatHashMap }
function TpvCSGBSP.TFloatHashMap<TFloatHashMapValue>.HashKey(const aKey:TFloat):TpvUInt32;
begin
result:=trunc(aKey*4096)*73856093;
if result=0 then begin
result:=$ffffffff;
end;
end;
function TpvCSGBSP.TFloatHashMap<TFloatHashMapValue>.CompareKey(const aKeyA,aKeyB:TFloat):boolean;
begin
result:=SameValue(aKeyA,aKeyB);
end;
{ TpvCSGBSP.TVector3HashMap }
function TpvCSGBSP.TVector3HashMap<TVector3HashMapValue>.HashKey(const aKey:TVector3):TpvUInt32;
begin
result:=(trunc(aKey.x*4096)*73856093) xor
(trunc(aKey.y*4096)*19349653) xor
(trunc(aKey.z*4096)*83492791);
if result=0 then begin
result:=$ffffffff;
end;
end;
function TpvCSGBSP.TVector3HashMap<TVector3HashMapValue>.CompareKey(const aKeyA,aKeyB:TVector3):boolean;
begin
result:=SameValue(aKeyA.x,aKeyB.x) and
SameValue(aKeyA.y,aKeyB.y) and
SameValue(aKeyA.z,aKeyB.z);
end;
{$warnings on}
{$hints on}
{ TpvCSGBSP.TSizeIntSparseSet }
constructor TpvCSGBSP.TSizeIntSparseSet.Create(const aMaximumSize:TpvSizeInt=0);
begin
inherited Create;
fSize:=0;
fMaximumSize:=aMaximumSize;
fSparseToDense:=nil;
fDense:=nil;
SetLength(fSparseToDense,fMaximumSize);
SetLength(fDense,fMaximumSize);
FillChar(fSparseToDense[0],fMaximumSize*SizeOf(longint),#$ff);
FillChar(fDense[0],fMaximumSize*SizeOf(TpvSizeInt),#$00);
end;
destructor TpvCSGBSP.TSizeIntSparseSet.Destroy;
begin
SetLength(fSparseToDense,0);
SetLength(fDense,0);
inherited Destroy;
end;
procedure TpvCSGBSP.TSizeIntSparseSet.Clear;
begin
fSize:=0;
end;
procedure TpvCSGBSP.TSizeIntSparseSet.Resize(const aNewMaximumSize:TpvSizeInt);
begin
SetLength(fSparseToDense,aNewMaximumSize);
SetLength(fDense,aNewMaximumSize);
if fMaximumSize<aNewMaximumSize then begin
FillChar(fSparseToDense[fMaximumSize],(fMaximumSize-aNewMaximumSize)*SizeOf(longint),#$ff);
FillChar(fDense[fMaximumSize],(fMaximumSize-aNewMaximumSize)*SizeOf(TpvSizeInt),#$00);
end;
fMaximumSize:=aNewMaximumSize;
end;
function TpvCSGBSP.TSizeIntSparseSet.Contains(const aValue:TpvSizeInt):boolean;
begin
result:=((aValue>=0) and (aValue<fMaximumSize) and
(fSparseToDense[aValue]<fSize)) and
(fDense[fSparseToDense[aValue]]=aValue);
end;
function TpvCSGBSP.TSizeIntSparseSet.GetValue(const aIndex:TpvSizeInt):TpvSizeInt;
begin
if (aIndex>=0) and (aIndex<fSize) then begin
result:=fDense[aIndex];
end;
end;
procedure TpvCSGBSP.TSizeIntSparseSet.SetValue(const aIndex:TpvSizeInt;const aValue:TpvSizeInt);
begin
if (aIndex>=0) and (aIndex<fSize) then begin
fDense[aIndex]:=aValue;
end;
end;
procedure TpvCSGBSP.TSizeIntSparseSet.Add(const aValue:TpvSizeInt);
begin
if (aValue>=0) and (aValue<fMaximumSize) then begin
fSparseToDense[aValue]:=fSize;
fDense[fSize]:=aValue;
inc(fSize);
end;
end;
procedure TpvCSGBSP.TSizeIntSparseSet.AddNew(const aValue:TpvSizeInt);
begin
if not Contains(aValue) then begin
Add(aValue);
end;
end;
procedure TpvCSGBSP.TSizeIntSparseSet.Remove(const aValue:TpvSizeInt);
var OldIndex:TpvSizeInt;
NewValue:TpvSizeInt;
begin
if Contains(aValue) then begin
OldIndex:=fSparseToDense[aValue];
fSparseToDense[aValue]:=-1;
dec(fSize);
if fSize>=0 then begin
NewValue:=fDense[fSize];
fSparseToDense[NewValue]:=OldIndex;
fDense[OldIndex]:=NewValue;
end else begin
fDense[OldIndex]:=0;
end;
end;
end;
{ TpvCSGBSP.TVector2 }
constructor TpvCSGBSP.TVector2.Create(const aFrom:TpvVector2);
begin
x:=aFrom.x;
y:=aFrom.y;
end;
constructor TpvCSGBSP.TVector2.Create(const aX,aY:TFloat);
begin
x:=aX;
y:=aY;
end;
class operator TpvCSGBSP.TVector2.Equal(const aLeft,aRight:TVector2):boolean;
begin
result:=SameValue(aLeft.x,aRight.x) and
SameValue(aLeft.y,aRight.y);
end;
class operator TpvCSGBSP.TVector2.NotEqual(const aLeft,aRight:TVector2):boolean;
begin
result:=not (SameValue(aLeft.x,aRight.x) and
SameValue(aLeft.y,aRight.y));
end;
class operator TpvCSGBSP.TVector2.Add(const aLeft,aRight:TVector2):TVector2;
begin
result.x:=aLeft.x+aRight.x;
result.y:=aLeft.y+aRight.y;
end;
class operator TpvCSGBSP.TVector2.Subtract(const aLeft,aRight:TVector2):TVector2;
begin
result.x:=aLeft.x-aRight.x;
result.y:=aLeft.y-aRight.y;
end;
class operator TpvCSGBSP.TVector2.Multiply(const aLeft:TVector2;const aRight:TFloat):TVector2;
begin
result.x:=aLeft.x*aRight;
result.y:=aLeft.y*aRight;
end;
class operator TpvCSGBSP.TVector2.Divide(const aLeft:TVector2;const aRight:TFloat):TVector2;
begin
result.x:=aLeft.x/aRight;
result.y:=aLeft.y/aRight;
end;
class operator TpvCSGBSP.TVector2.Negative(const aVector:TVector2):TVector2;
begin
result.x:=-aVector.x;
result.y:=-aVector.y;
end;
function TpvCSGBSP.TVector2.Length:TFloat;
begin
result:=sqrt(sqr(x)+sqr(y));
end;
function TpvCSGBSP.TVector2.SquaredLength:TFloat;
begin
result:=sqr(x)+sqr(y);
end;
function TpvCSGBSP.TVector2.Lerp(const aWith:TVector2;const aTime:TFloat):TVector2;
var InverseTime:TFloat;
begin
if aTime<=0.0 then begin
result:=self;
end else if aTime>=1.0 then begin
result:=aWith;
end else begin
InverseTime:=1.0-aTime;
result.x:=(x*InverseTime)+(aWith.x*aTime);
result.y:=(y*InverseTime)+(aWith.y*aTime);
end;
end;
function TpvCSGBSP.TVector2.ToVector:TpvVector2;
begin
result.x:=x;
result.y:=y;
end;
{ TpvCSGBSP.TVector3 }
constructor TpvCSGBSP.TVector3.Create(const aFrom:TpvVector3);
begin
x:=aFrom.x;
y:=aFrom.y;
z:=aFrom.z;
end;
constructor TpvCSGBSP.TVector3.Create(const aX,aY,aZ:TFloat);
begin
x:=aX;
y:=aY;
z:=aZ;
end;
class operator TpvCSGBSP.TVector3.Equal(const aLeft,aRight:TVector3):boolean;
begin
result:=SameValue(aLeft.x,aRight.x) and
SameValue(aLeft.y,aRight.y) and
SameValue(aLeft.z,aRight.z);
end;
class operator TpvCSGBSP.TVector3.NotEqual(const aLeft,aRight:TVector3):boolean;
begin
result:=not (SameValue(aLeft.x,aRight.x) and
SameValue(aLeft.y,aRight.y) and
SameValue(aLeft.z,aRight.z));
end;
class operator TpvCSGBSP.TVector3.Add(const aLeft,aRight:TVector3):TVector3;
begin
result.x:=aLeft.x+aRight.x;
result.y:=aLeft.y+aRight.y;
result.z:=aLeft.z+aRight.z;
end;
class operator TpvCSGBSP.TVector3.Subtract(const aLeft,aRight:TVector3):TVector3;
begin
result.x:=aLeft.x-aRight.x;
result.y:=aLeft.y-aRight.y;
result.z:=aLeft.z-aRight.z;
end;
class operator TpvCSGBSP.TVector3.Multiply(const aLeft:TVector3;const aRight:TFloat):TVector3;
begin
result.x:=aLeft.x*aRight;
result.y:=aLeft.y*aRight;
result.z:=aLeft.z*aRight;
end;
class operator TpvCSGBSP.TVector3.Divide(const aLeft:TVector3;const aRight:TFloat):TVector3;
begin
result.x:=aLeft.x/aRight;
result.y:=aLeft.y/aRight;
result.z:=aLeft.z/aRight;
end;
class operator TpvCSGBSP.TVector3.Negative(const aVector:TVector3):TVector3;
begin
result.x:=-aVector.x;
result.y:=-aVector.y;
result.z:=-aVector.z;
end;
function TpvCSGBSP.TVector3.Cross(const aWith:TVector3):TVector3;
begin
result.x:=(y*aWith.z)-(z*aWith.y);
result.y:=(z*aWith.x)-(x*aWith.z);
result.z:=(x*aWith.y)-(y*aWith.x);
end;
function TpvCSGBSP.TVector3.Spacing(const aWith:TVector3):TFloat;
begin
result:=abs(x-aWith.x)+abs(y-aWith.y)+abs(z-aWith.z);
end;
function TpvCSGBSP.TVector3.Dot(const aWith:TVector3):TFloat;
begin
result:=(x*aWith.x)+(y*aWith.y)+(z*aWith.z);
end;
function TpvCSGBSP.TVector3.Length:TFloat;
begin
result:=sqrt(sqr(x)+sqr(y)+sqr(z));
end;
function TpvCSGBSP.TVector3.SquaredLength:TFloat;
begin
result:=sqr(x)+sqr(y)+sqr(z);
end;
function TpvCSGBSP.TVector3.Lerp(const aWith:TVector3;const aTime:TFloat):TVector3;
begin
if aTime<=0.0 then begin
result:=self;
end else if aTime>=1.0 then begin
result:=aWith;
end else begin
result:=(self*(1.0-aTime))+(aWith*aTime);
end;
end;
function TpvCSGBSP.TVector3.Normalize:TVector3;
begin
result:=self/Length;
end;
function TpvCSGBSP.TVector3.Perpendicular:TVector3;
var v,p:TVector3;
begin
v:=self.Normalize;
p.x:=System.abs(v.x);
p.y:=System.abs(v.y);
p.z:=System.abs(v.z);
if (p.x<=p.y) and (p.x<=p.z) then begin
p.x:=1.0;
p.y:=0.0;
p.z:=0.0;
end else if (p.y<=p.x) and (p.y<=p.z) then begin
p.x:=0.0;
p.y:=1.0;
p.z:=0.0;
end else begin
p.x:=0.0;
p.y:=0.0;
p.z:=1.0;
end;
result:=p-(v*v.Dot(p));
end;
function TpvCSGBSP.TVector3.ToVector:TpvVector3;
begin
result.x:=x;
result.y:=y;
result.z:=z;
end;
{ TpvCSGBSP.TVector4 }
constructor TpvCSGBSP.TVector4.Create(const aFrom:TpvVector4);
begin
x:=aFrom.x;
y:=aFrom.y;
z:=aFrom.z;
w:=aFrom.w;
end;
constructor TpvCSGBSP.TVector4.Create(const aX,aY,aZ,aW:TFloat);
begin
x:=aX;
y:=aY;
z:=aZ;
w:=aW;
end;
class operator TpvCSGBSP.TVector4.Equal(const aLeft,aRight:TVector4):boolean;
begin
result:=SameValue(aLeft.x,aRight.x) and
SameValue(aLeft.y,aRight.y) and
SameValue(aLeft.z,aRight.z) and
SameValue(aLeft.w,aRight.w);
end;
class operator TpvCSGBSP.TVector4.NotEqual(const aLeft,aRight:TVector4):boolean;
begin
result:=not (SameValue(aLeft.x,aRight.x) and
SameValue(aLeft.y,aRight.y) and
SameValue(aLeft.z,aRight.z) and
SameValue(aLeft.w,aRight.w));
end;
class operator TpvCSGBSP.TVector4.Add(const aLeft,aRight:TVector4):TVector4;
begin
result.x:=aLeft.x+aRight.x;
result.y:=aLeft.y+aRight.y;
result.z:=aLeft.z+aRight.z;
result.w:=aLeft.w+aRight.w;
end;
class operator TpvCSGBSP.TVector4.Subtract(const aLeft,aRight:TVector4):TVector4;
begin
result.x:=aLeft.x-aRight.x;
result.y:=aLeft.y-aRight.y;
result.z:=aLeft.z-aRight.z;
result.w:=aLeft.w-aRight.w;
end;
class operator TpvCSGBSP.TVector4.Multiply(const aLeft:TVector4;const aRight:TFloat):TVector4;
begin
result.x:=aLeft.x*aRight;
result.y:=aLeft.y*aRight;
result.z:=aLeft.z*aRight;
result.w:=aLeft.w*aRight;
end;
class operator TpvCSGBSP.TVector4.Divide(const aLeft:TVector4;const aRight:TFloat):TVector4;
begin
result.x:=aLeft.x/aRight;
result.y:=aLeft.y/aRight;
result.z:=aLeft.z/aRight;
result.w:=aLeft.w/aRight;
end;
class operator TpvCSGBSP.TVector4.Negative(const aVector:TVector4):TVector4;
begin
result.x:=-aVector.x;
result.y:=-aVector.y;
result.z:=-aVector.z;
result.w:=-aVector.w;
end;
function TpvCSGBSP.TVector4.Length:TFloat;
begin
result:=sqrt(sqr(x)+sqr(y)+sqr(z)+sqr(w));
end;
function TpvCSGBSP.TVector4.SquaredLength:TFloat;
begin
result:=sqr(x)+sqr(y)+sqr(z)+sqr(w);
end;
function TpvCSGBSP.TVector4.Lerp(const aWith:TVector4;const aTime:TFloat):TVector4;
var InverseTime:TFloat;
begin
if aTime<=0.0 then begin
result:=self;
end else if aTime>=1.0 then begin
result:=aWith;
end else begin
InverseTime:=1.0-aTime;
result.x:=(x*InverseTime)+(aWith.x*aTime);
result.y:=(y*InverseTime)+(aWith.y*aTime);
result.z:=(z*InverseTime)+(aWith.z*aTime);
result.w:=(w*InverseTime)+(aWith.w*aTime);
end;
end;
function TpvCSGBSP.TVector4.ToVector:TpvVector4;
begin
result.x:=x;
result.y:=y;
result.z:=z;
result.w:=w;
end;
{ TpvCSGBSP.TVertex }
class operator TpvCSGBSP.TVertex.Equal(const aLeft,aRight:TVertex):boolean;
begin
result:=(aLeft.Position=aRight.Position) and
(aLeft.Normal=aRight.Normal) and
(aLeft.TexCoord=aRight.TexCoord) and
(aLeft.Color=aRight.Color);
end;
class operator TpvCSGBSP.TVertex.NotEqual(const aLeft,aRight:TVertex):boolean;
begin
result:=(aLeft.Position<>aRight.Position) or
(aLeft.Normal<>aRight.Normal) or
(aLeft.TexCoord<>aRight.TexCoord) or
(aLeft.Color<>aRight.Color);
end;
class operator TpvCSGBSP.TVertex.Add(const aLeft,aRight:TVertex):TVertex;
begin
result.Position:=aLeft.Position+aRight.Position;
result.Normal:=aLeft.Normal+aRight.Normal;
result.TexCoord:=aLeft.TexCoord+aRight.TexCoord;
result.Color:=aLeft.Color+aRight.Color;
end;
class operator TpvCSGBSP.TVertex.Subtract(const aLeft,aRight:TVertex):TVertex;
begin
result.Position:=aLeft.Position-aRight.Position;
result.Normal:=aLeft.Normal-aRight.Normal;
result.TexCoord:=aLeft.TexCoord-aRight.TexCoord;
result.Color:=aLeft.Color-aRight.Color;
end;
class operator TpvCSGBSP.TVertex.Multiply(const aLeft:TVertex;const aRight:TFloat):TVertex;
begin
result.Position:=aLeft.Position*aRight;
result.Normal:=aLeft.Normal*aRight;
result.TexCoord:=aLeft.TexCoord*aRight;
result.Color:=aLeft.Color*aRight;
end;
class operator TpvCSGBSP.TVertex.Divide(const aLeft:TVertex;const aRight:TFloat):TVertex;
begin
result.Position:=aLeft.Position/aRight;
result.Normal:=aLeft.Normal/aRight;
result.TexCoord:=aLeft.TexCoord/aRight;
result.Color:=aLeft.Color/aRight;
end;
class operator TpvCSGBSP.TVertex.Negative(const aLeft:TVertex):TVertex;
begin
result.Position:=-aLeft.Position;
result.Normal:=-aLeft.Normal;
result.TexCoord:=-aLeft.TexCoord;
result.Color:=-aLeft.Color;
end;
function TpvCSGBSP.TVertex.Lerp(const aWith:TVertex;const aTime:TFloat):TVertex;
begin
result.Position:=Position.Lerp(aWith.Position,aTime);
result.Normal:=Normal.Lerp(aWith.Normal,aTime);
result.TexCoord:=TexCoord.Lerp(aWith.TexCoord,aTime);
result.Color:=Color.Lerp(aWith.Color,aTime);
end;
procedure TpvCSGBSP.TVertex.Flip;
begin
Normal:=-Normal;
end;
function TpvCSGBSP.TVertex.CloneFlip:TVertex;
begin
result.Position:=Position;
result.Normal:=-Normal;
result.TexCoord:=TexCoord;
result.Color:=Color;
end;
function TpvCSGBSP.TVertex.Normalize:TVertex;
begin
result.Position:=Position;
result.Normal:=Normal.Normalize;
result.TexCoord:=TexCoord;
result.Color:=Color;
end;
{ TpvCSGBSP.TPlane }
constructor TpvCSGBSP.TPlane.Create(const aV0,aV1,aV2:TVector3);
begin
Normal:=((aV1-aV0).Cross(aV2-aV0)).Normalize;
Distance:=-Normal.Dot(aV0);
end;
constructor TpvCSGBSP.TPlane.Create(const aNormal:TVector3;const aDistance:TFloat);
begin
Normal:=aNormal;
Distance:=aDistance;
end;
class function TpvCSGBSP.TPlane.CreateEmpty;
begin
result.Normal.x:=0.0;
result.Normal.y:=0.0;
result.Normal.z:=0.0;
result.Distance:=0.0;
end;
function TpvCSGBSP.TPlane.DistanceTo(const aWith:TVector3):TFloat;
begin
result:=Normal.Dot(aWith)+Distance;
end;
function TpvCSGBSP.TPlane.IntersectWithPointToPoint(const aPointA,aPointB:TVector3;const aIntersectionPoint:PVector3=nil):boolean;
var NormalDotDirection,Time:TFloat;
Direction:TVector3;
begin
result:=false;
Direction:=aPointB-aPointA;
NormalDotDirection:=Normal.Dot(Direction);
if not IsZero(NormalDotDirection) then begin
Time:=-(DistanceTo(aPointA)/NormalDotDirection);
result:=(Time>=Epsilon) and (Time<=OneMinusEpsilon);
if result and assigned(aIntersectionPoint) then begin
aIntersectionPoint^:=aPointA.Lerp(aPointB,Time);
if (aIntersectionPoint^=aPointA) or
(aIntersectionPoint^=aPointB) then begin
result:=false;
end;
end;
end;
end;
function TpvCSGBSP.TPlane.IntersectWithPointToPoint(const aPointA,aPointB:TVertex;const aIntersectionPoint:PVertex=nil):boolean;
var NormalDotDirection,Time:TFloat;
Direction:TVector3;
begin
result:=false;
Direction:=aPointB.Position-aPointA.Position;
NormalDotDirection:=Normal.Dot(Direction);
if not IsZero(NormalDotDirection) then begin
Time:=-(DistanceTo(aPointA.Position)/NormalDotDirection);
result:=(Time>=Epsilon) and (Time<=OneMinusEpsilon);
if result and assigned(aIntersectionPoint) then begin
aIntersectionPoint^:=aPointA.Lerp(aPointB,Time);
if (aIntersectionPoint^.Position=aPointA.Position) or
(aIntersectionPoint^.Position=aPointB.Position) then begin
result:=false;
end;
end;
end;
end;
function TpvCSGBSP.TPlane.OK:boolean;
begin
result:=Normal.Length>0.0;
end;
function TpvCSGBSP.TPlane.Flip:TPlane;
begin
result.Normal:=-Normal;
result.Distance:=-Distance;
end;
procedure TpvCSGBSP.TPlane.SplitTriangles(var aVertices:TVertexList;
const aIndices:TIndexList;
const aCoplanarBackList:PIndexList;
const aCoplanarFrontList:PIndexList;
const aBackList:PIndexList;
const aFrontList:PIndexList);
var Index,Count,DummyIndex:TpvSizeInt;
Sides:array[0..2] of TpvSizeInt;
VertexIndices,PointIndices:array[0..2] of TIndex;
PlaneDistances:array[0..2] of TFloat;
begin
Index:=0;
Count:=aIndices.Count;
while (Index+2)<Count do begin
VertexIndices[0]:=aIndices.Items[Index+0];
VertexIndices[1]:=aIndices.Items[Index+1];
VertexIndices[2]:=aIndices.Items[Index+2];
PlaneDistances[0]:=DistanceTo(aVertices.Items[VertexIndices[0]].Position);
PlaneDistances[1]:=DistanceTo(aVertices.Items[VertexIndices[1]].Position);
PlaneDistances[2]:=DistanceTo(aVertices.Items[VertexIndices[2]].Position);
Sides[0]:=TpvCSGBSP.EpsilonSign(PlaneDistances[0]);
Sides[1]:=TpvCSGBSP.EpsilonSign(PlaneDistances[1]);
Sides[2]:=TpvCSGBSP.EpsilonSign(PlaneDistances[2]);
PlaneDistances[0]:=PlaneDistances[0]*abs(Sides[0]);
PlaneDistances[1]:=PlaneDistances[1]*abs(Sides[1]);
PlaneDistances[2]:=PlaneDistances[2]*abs(Sides[2]);
if (Sides[0]*Sides[1])<0 then begin
PointIndices[0]:=aVertices.Add(aVertices.Items[VertexIndices[0]].Lerp(aVertices.Items[VertexIndices[1]],abs(PlaneDistances[0])/(abs(PlaneDistances[0])+abs(PlaneDistances[1]))));
end;
if (Sides[1]*Sides[2])<0 then begin
PointIndices[1]:=aVertices.Add(aVertices.Items[VertexIndices[1]].Lerp(aVertices.Items[VertexIndices[2]],abs(PlaneDistances[1])/(abs(PlaneDistances[1])+abs(PlaneDistances[2]))));
end;
if (Sides[2]*Sides[0])<0 then begin
PointIndices[2]:=aVertices.Add(aVertices.Items[VertexIndices[2]].Lerp(aVertices.Items[VertexIndices[0]],abs(PlaneDistances[2])/(abs(PlaneDistances[2])+abs(PlaneDistances[0]))));
end;
case ((Sides[0]+1) shl 0) or
((Sides[1]+1) shl 2) or
((Sides[2]+1) shl 4) of
// All points are on one side of the plane (or on the plane)
// in this case we simply add the complete triangle to the proper halve of the subtree
(((-1)+1) shl 0) or (((-1)+1) shl 2) or (((-1)+1) shl 4),
(((-1)+1) shl 0) or (((-1)+1) shl 2) or (((0)+1) shl 4),
(((-1)+1) shl 0) or (((0)+1) shl 2) or (((-1)+1) shl 4),
(((-1)+1) shl 0) or (((0)+1) shl 2) or (((0)+1) shl 4),
(((0)+1) shl 0) or (((-1)+1) shl 2) or (((-1)+1) shl 4),
(((0)+1) shl 0) or (((-1)+1) shl 2) or (((0)+1) shl 4),
(((0)+1) shl 0) or (((0)+1) shl 2) or (((-1)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[0],VertexIndices[1],VertexIndices[2]]);
end;
end;
(((0)+1) shl 0) or (((0)+1) shl 2) or (((1)+1) shl 4),
(((0)+1) shl 0) or (((1)+1) shl 2) or (((0)+1) shl 4),
(((0)+1) shl 0) or (((1)+1) shl 2) or (((1)+1) shl 4),
(((1)+1) shl 0) or (((0)+1) shl 2) or (((0)+1) shl 4),
(((1)+1) shl 0) or (((0)+1) shl 2) or (((1)+1) shl 4),
(((1)+1) shl 0) or (((1)+1) shl 2) or (((0)+1) shl 4),
(((1)+1) shl 0) or (((1)+1) shl 2) or (((1)+1) shl 4):begin
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[0],VertexIndices[1],VertexIndices[2]]);
end;
end;
// Triangle on the dividing plane
(((0)+1) shl 0) or (((0)+1) shl 2) or (((0)+1) shl 4):begin
if aCoplanarFrontList<>aCoplanarBackList then begin
if Normal.Dot(TPlane.Create(aVertices.Items[VertexIndices[0]].Position,
aVertices.Items[VertexIndices[1]].Position,
aVertices.Items[VertexIndices[2]].Position).Normal)>0.0 then begin
if assigned(aCoplanarFrontList) then begin
aCoplanarFrontList^.Add([VertexIndices[0],VertexIndices[1],VertexIndices[2]]);
end;
end else begin
if assigned(aCoplanarBackList) then begin
aCoplanarBackList^.Add([VertexIndices[0],VertexIndices[1],VertexIndices[2]]);
end;
end;
end else if assigned(aCoplanarFrontList) then begin
aCoplanarFrontList^.Add([VertexIndices[0],VertexIndices[1],VertexIndices[2]]);
end;
end;
// And now all the ways that the triangle can be cut by the plane
(((1)+1) shl 0) or (((-1)+1) shl 2) or (((0)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[1],VertexIndices[2],PointIndices[0]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[2],VertexIndices[0],PointIndices[0]]);
end;
end;
(((-1)+1) shl 0) or (((0)+1) shl 2) or (((1)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[0],VertexIndices[1],PointIndices[2]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[1],VertexIndices[2],PointIndices[2]]);
end;
end;
(((0)+1) shl 0) or (((1)+1) shl 2) or (((-1)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[2],VertexIndices[0],PointIndices[1]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[0],VertexIndices[1],PointIndices[1]]);
end;
end;
(((-1)+1) shl 0) or (((1)+1) shl 2) or (((0)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[2],VertexIndices[0],PointIndices[0]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[1],VertexIndices[2],PointIndices[0]]);
end;
end;
(((1)+1) shl 0) or (((0)+1) shl 2) or (((-1)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[1],VertexIndices[2],PointIndices[2]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[0],VertexIndices[1],PointIndices[2]]);
end;
end;
(((0)+1) shl 0) or (((-1)+1) shl 2) or (((1)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[0],VertexIndices[1],PointIndices[1]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[2],VertexIndices[0],PointIndices[1]]);
end;
end;
(((1)+1) shl 0) or (((-1)+1) shl 2) or (((-1)+1) shl 4):begin
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[0],PointIndices[0],PointIndices[2]]);
end;
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[1],PointIndices[2],PointIndices[0]]);
aBackList^.Add([VertexIndices[1],VertexIndices[2],PointIndices[2]]);
end;
end;
(((-1)+1) shl 0) or (((1)+1) shl 2) or (((-1)+1) shl 4):begin
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[1],PointIndices[1],PointIndices[0]]);
end;
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[2],PointIndices[0],PointIndices[1]]);
aBackList^.Add([VertexIndices[2],VertexIndices[0],PointIndices[0]]);
end;
end;
(((-1)+1) shl 0) or (((-1)+1) shl 2) or (((1)+1) shl 4):begin
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[2],PointIndices[2],PointIndices[1]]);
end;
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[0],PointIndices[1],PointIndices[2]]);
aBackList^.Add([VertexIndices[0],VertexIndices[1],PointIndices[1]]);
end;
end;
(((-1)+1) shl 0) or (((1)+1) shl 2) or (((1)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[0],PointIndices[0],PointIndices[2]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[1],PointIndices[2],PointIndices[0]]);
aFrontList^.Add([VertexIndices[1],VertexIndices[2],PointIndices[2]]);
end;
end;
(((1)+1) shl 0) or (((-1)+1) shl 2) or (((1)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[1],PointIndices[1],PointIndices[0]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[0],PointIndices[0],PointIndices[1]]);
aFrontList^.Add([VertexIndices[2],VertexIndices[0],PointIndices[1]]);
end;
end;
(((1)+1) shl 0) or (((1)+1) shl 2) or (((-1)+1) shl 4):begin
if assigned(aBackList) then begin
aBackList^.Add([VertexIndices[2],PointIndices[2],PointIndices[1]]);
end;
if assigned(aFrontList) then begin
aFrontList^.Add([VertexIndices[0],PointIndices[1],PointIndices[2]]);
aFrontList^.Add([VertexIndices[0],VertexIndices[1],PointIndices[1]]);
end;
end;
// Otherwise it is a error
else begin
Assert(false);
end;
end;
inc(Index,3);
end;
end;
procedure TpvCSGBSP.TPlane.SplitPolygons(var aVertices:TVertexList;
const aIndices:TIndexList;
const aCoplanarBackList:PIndexList;
const aCoplanarFrontList:PIndexList;
const aBackList:PIndexList;
const aFrontList:PIndexList);
const Coplanar=0;
Front=1;
Back=2;
Spanning=3;
EpsilonSignToOrientation:array[0..3] of TpvInt32=(Back,Coplanar,Front,Spanning);
var Index,OtherIndex,Count,CountPolygonVertices,
IndexA,IndexB,
PolygonOrientation,
VertexOrientation,
VertexOrientationA,
VertexOrientationB:TpvSizeInt;
VertexOrientations:array of TpvSizeInt;
VectorDistance:TpvDouble;
BackVertexIndices,FrontVertexIndices:TIndexList;
VertexIndex:TIndex;
VertexA,VertexB:PVertex;
begin
VertexOrientations:=nil;
try
BackVertexIndices.Initialize;
try
FrontVertexIndices.Initialize;
try
Index:=0;
Count:=aIndices.Count;
while Index<Count do begin
CountPolygonVertices:=aIndices.Items[Index];
inc(Index);
if (CountPolygonVertices>0) and
((Index+(CountPolygonVertices-1))<Count) then begin
if CountPolygonVertices>2 then begin
PolygonOrientation:=0;
if length(VertexOrientations)<CountPolygonVertices then begin
SetLength(VertexOrientations,(CountPolygonVertices*3) shr 1);
end;
for IndexA:=0 to CountPolygonVertices-1 do begin
VertexIndex:=aIndices.Items[Index+IndexA];
VertexOrientation:=EpsilonSignToOrientation[(TpvCSGBSP.EpsilonSign(DistanceTo(aVertices.Items[VertexIndex].Position))+1) and 3];
PolygonOrientation:=PolygonOrientation or VertexOrientation;
VertexOrientations[IndexA]:=VertexOrientation;
end;
case PolygonOrientation of
Coplanar:begin
if assigned(aCoplanarFrontList) or assigned(aCoplanarBackList) then begin
if Normal.Dot(TPlane.Create(aVertices.Items[aIndices.Items[Index+0]].Position,
aVertices.Items[aIndices.Items[Index+1]].Position,
aVertices.Items[aIndices.Items[Index+2]].Position).Normal)>0.0 then begin
if assigned(aCoplanarFrontList) then begin
aCoplanarFrontList^.Add(CountPolygonVertices);
aCoplanarFrontList^.AddRangeFrom(aIndices,Index,CountPolygonVertices);
end;
end else begin
if assigned(aCoplanarBackList) then begin
aCoplanarBackList^.Add(CountPolygonVertices);
aCoplanarBackList^.AddRangeFrom(aIndices,Index,CountPolygonVertices);
end;
end;
end;
end;
Front:begin
if assigned(aFrontList) then begin
aFrontList^.Add(CountPolygonVertices);
aFrontList^.AddRangeFrom(aIndices,Index,CountPolygonVertices);
end;
end;
Back:begin
if assigned(aBackList) then begin
aBackList^.Add(CountPolygonVertices);
aBackList^.AddRangeFrom(aIndices,Index,CountPolygonVertices);
end;
end;
else {Spanning:}begin
BackVertexIndices.Count:=0;
FrontVertexIndices.Count:=0;
for IndexA:=0 to CountPolygonVertices-1 do begin
IndexB:=IndexA+1;
if IndexB>=CountPolygonVertices then begin
IndexB:=0;
end;
VertexIndex:=aIndices.Items[Index+IndexA];
VertexA:=@aVertices.Items[VertexIndex];
VertexOrientationA:=VertexOrientations[IndexA];
VertexOrientationB:=VertexOrientations[IndexB];
if VertexOrientationA<>Front then begin
BackVertexIndices.Add(VertexIndex);
end;
if VertexOrientationA<>Back then begin
FrontVertexIndices.Add(VertexIndex);
end;
if (VertexOrientationA or VertexOrientationB)=Spanning then begin
VertexB:=@aVertices.Items[aIndices.Items[Index+IndexB]];
VertexIndex:=aVertices.Add(VertexA^.Lerp(VertexB^,-(DistanceTo(VertexA^.Position)/Normal.Dot(VertexB^.Position-VertexA^.Position))));
BackVertexIndices.Add(VertexIndex);
FrontVertexIndices.Add(VertexIndex);
end;
end;
if assigned(aBackList) and (BackVertexIndices.Count>2) then begin
aBackList^.Add(BackVertexIndices.Count);
aBackList^.Add(BackVertexIndices);
end;
if assigned(aFrontList) and (FrontVertexIndices.Count>2) then begin
aFrontList^.Add(FrontVertexIndices.Count);
aFrontList^.Add(FrontVertexIndices);
end;
end;
end;
end;
end else begin
Assert(false);
end;
inc(Index,CountPolygonVertices);
end;
finally
FrontVertexIndices.Finalize;
end;
finally
BackVertexIndices.Finalize;
end;
finally
VertexOrientations:=nil;
end;
end;
{ TpvCSGBSP.TAABB }
function TpvCSGBSP.TAABB.Cost:TFloat;
begin
// result:=(self.Max.x-self.Min.x)+(self.Max.y-self.Min.y)+(self.Max.z-self.Min.z); // Manhattan distance
result:=(self.Max.x-self.Min.x)*(self.Max.y-self.Min.y)*(self.Max.z-self.Min.z); // Volume
end;
function TpvCSGBSP.TAABB.Combine(const aAABB:TAABB):TAABB;
begin
result.Min.x:=Math.Min(self.Min.x,aaABB.Min.x);
result.Min.y:=Math.Min(self.Min.y,aAABB.Min.y);
result.Min.z:=Math.Min(self.Min.z,aAABB.Min.z);
result.Max.x:=Math.Max(self.Max.x,aAABB.Max.x);
result.Max.y:=Math.Max(self.Max.y,aAABB.Max.y);
result.Max.z:=Math.Max(self.Max.z,aAABB.Max.z);
end;
function TpvCSGBSP.TAABB.Combine(const aVector:TVector3):TAABB;
begin
result.Min.x:=Math.Min(self.Min.x,aVector.x);
result.Min.y:=Math.Min(self.Min.y,aVector.y);
result.Min.z:=Math.Min(self.Min.z,aVector.z);
result.Max.x:=Math.Max(self.Max.x,aVector.x);
result.Max.y:=Math.Max(self.Max.y,aVector.y);
result.Max.z:=Math.Max(self.Max.z,aVector.z);
end;
function TpvCSGBSP.TAABB.Contains(const aAABB:TAABB;const aThreshold:TFloat=0.0):boolean;
begin
result:=((self.Min.x-aThreshold)<=(aAABB.Min.x+aThreshold)) and ((self.Min.y-aThreshold)<=(aAABB.Min.y+aThreshold)) and ((self.Min.z-aThreshold)<=(aAABB.Min.z+aThreshold)) and
((self.Max.x+aThreshold)>=(aAABB.Min.x+aThreshold)) and ((self.Max.y+aThreshold)>=(aAABB.Min.y+aThreshold)) and ((self.Max.z+aThreshold)>=(aAABB.Min.z+aThreshold)) and
((self.Min.x-aThreshold)<=(aAABB.Max.x-aThreshold)) and ((self.Min.y-aThreshold)<=(aAABB.Max.y-aThreshold)) and ((self.Min.z-aThreshold)<=(aAABB.Max.z-aThreshold)) and
((self.Max.x+aThreshold)>=(aAABB.Max.x-aThreshold)) and ((self.Max.y+aThreshold)>=(aAABB.Max.y-aThreshold)) and ((self.Max.z+aThreshold)>=(aAABB.Max.z-aThreshold));
end;
function TpvCSGBSP.TAABB.Intersects(const aAABB:TAABB;const aThreshold:TFloat=Epsilon):boolean;
begin
result:=(((self.Max.x+aThreshold)>=(aAABB.Min.x-aThreshold)) and ((self.Min.x-aThreshold)<=(aAABB.Max.x+aThreshold))) and
(((self.Max.y+aThreshold)>=(aAABB.Min.y-aThreshold)) and ((self.Min.y-aThreshold)<=(aAABB.Max.y+aThreshold))) and
(((self.Max.z+aThreshold)>=(aAABB.Min.z-aThreshold)) and ((self.Min.z-aThreshold)<=(aAABB.Max.z+aThreshold)));
end;
function TpvCSGBSP.TAABB.Intersection(const aAABB:TAABB;const aThreshold:TFloat=0.0):TAABB;
begin
result.Min.x:=Math.Max(Min.x,aAABB.Min.x)-aThreshold;
result.Min.y:=Math.Max(Min.y,aAABB.Min.y)-aThreshold;
result.Min.z:=Math.Max(Min.z,aAABB.Min.z)-aThreshold;
result.Max.x:=Math.Min(Max.x,aAABB.Max.x)+aThreshold;
result.Max.y:=Math.Min(Max.y,aAABB.Max.y)+aThreshold;
result.Max.z:=Math.Min(Max.z,aAABB.Max.z)+aThreshold;
end;
{ TpvCSGBSP.TDynamicAABBTree }
constructor TpvCSGBSP.TDynamicAABBTree.Create;
var i:TpvSizeInt;
begin
inherited Create;
Root:=daabbtNULLNODE;
NodeCount:=0;
NodeCapacity:=16;
GetMem(Nodes,NodeCapacity*SizeOf(TDynamicAABBTreeNode));
FillChar(Nodes^,NodeCapacity*SizeOf(TDynamicAABBTreeNode),#0);
for i:=0 to NodeCapacity-2 do begin
Nodes^[i].Next:=i+1;
Nodes^[i].Height:=-1;
end;
Nodes^[NodeCapacity-1].Next:=daabbtNULLNODE;
Nodes^[NodeCapacity-1].Height:=-1;
FreeList:=0;
Path:=0;
InsertionCount:=0;
StackCapacity:=16;
GetMem(Stack,StackCapacity*SizeOf(TpvSizeInt));
end;
destructor TpvCSGBSP.TDynamicAABBTree.Destroy;
begin
FreeMem(Nodes);
FreeMem(Stack);
inherited Destroy;
end;
function TpvCSGBSP.TDynamicAABBTree.AllocateNode:TpvSizeInt;
var Node:PDynamicAABBTreeNode;
i:TpvSizeInt;
begin
if FreeList=daabbtNULLNODE then begin
inc(NodeCapacity,NodeCapacity);
ReallocMem(Nodes,NodeCapacity*SizeOf(TDynamicAABBTreeNode));
FillChar(Nodes^[NodeCount],(NodeCapacity-NodeCount)*SizeOf(TDynamicAABBTreeNode),#0);
for i:=NodeCount to NodeCapacity-2 do begin
Nodes^[i].Next:=i+1;
Nodes^[i].Height:=-1;
end;
Nodes^[NodeCapacity-1].Next:=daabbtNULLNODE;
Nodes^[NodeCapacity-1].Height:=-1;
FreeList:=NodeCount;
end;
result:=FreeList;
FreeList:=Nodes^[result].Next;
Node:=@Nodes^[result];
Node^.Parent:=daabbtNULLNODE;
Node^.Children[0]:=daabbtNULLNODE;
Node^.Children[1]:=daabbtNULLNODE;
Node^.Height:=0;
Node^.UserData:=0;
inc(NodeCount);
end;
procedure TpvCSGBSP.TDynamicAABBTree.FreeNode(const aNodeID:TpvSizeInt);
var Node:PDynamicAABBTreeNode;
begin
Node:=@Nodes^[aNodeID];
Node^.Next:=FreeList;
Node^.Height:=-1;
FreeList:=aNodeID;
dec(NodeCount);
end;
function TpvCSGBSP.TDynamicAABBTree.Balance(const aNodeID:TpvSizeInt):TpvSizeInt;
var NodeA,NodeB,NodeC,NodeD,NodeE,NodeF,NodeG:PDynamicAABBTreeNode;
NodeBID,NodeCID,NodeDID,NodeEID,NodeFID,NodeGID,NodeBalance:TpvSizeInt;
begin
NodeA:=@Nodes^[aNodeID];
if (NodeA.Children[0]<0) or (NodeA^.Height<2) then begin
result:=aNodeID;
end else begin
NodeBID:=NodeA^.Children[0];
NodeCID:=NodeA^.Children[1];
NodeB:=@Nodes^[NodeBID];
NodeC:=@Nodes^[NodeCID];
NodeBalance:=NodeC^.Height-NodeB^.Height;
if NodeBalance>1 then begin
NodeFID:=NodeC^.Children[0];
NodeGID:=NodeC^.Children[1];
NodeF:=@Nodes^[NodeFID];
NodeG:=@Nodes^[NodeGID];
NodeC^.Children[0]:=aNodeID;
NodeC^.Parent:=NodeA^.Parent;
NodeA^.Parent:=NodeCID;
if NodeC^.Parent>=0 then begin
if Nodes^[NodeC^.Parent].Children[0]=aNodeID then begin
Nodes^[NodeC^.Parent].Children[0]:=NodeCID;
end else begin
Nodes^[NodeC^.Parent].Children[1]:=NodeCID;
end;
end else begin
Root:=NodeCID;
end;
if NodeF^.Height>NodeG^.Height then begin
NodeC^.Children[1]:=NodeFID;
NodeA^.Children[1]:=NodeGID;
NodeG^.Parent:=aNodeID;
NodeA^.AABB:=NodeB^.AABB.Combine(NodeG^.AABB);
NodeC^.AABB:=NodeA^.AABB.Combine(NodeF^.AABB);
NodeA^.Height:=1+Max(NodeB^.Height,NodeG^.Height);
NodeC^.Height:=1+Max(NodeA^.Height,NodeF^.Height);
end else begin
NodeC^.Children[1]:=NodeGID;
NodeA^.Children[1]:=NodeFID;
NodeF^.Parent:=aNodeID;
NodeA^.AABB:=NodeB^.AABB.Combine(NodeF^.AABB);
NodeC^.AABB:=NodeA^.AABB.Combine(NodeG^.AABB);
NodeA^.Height:=1+Max(NodeB^.Height,NodeF^.Height);
NodeC^.Height:=1+Max(NodeA^.Height,NodeG^.Height);
end;
result:=NodeCID;
end else if NodeBalance<-1 then begin
NodeDID:=NodeB^.Children[0];
NodeEID:=NodeB^.Children[1];
NodeD:=@Nodes^[NodeDID];
NodeE:=@Nodes^[NodeEID];
NodeB^.Children[0]:=aNodeID;
NodeB^.Parent:=NodeA^.Parent;
NodeA^.Parent:=NodeBID;
if NodeB^.Parent>=0 then begin
if Nodes^[NodeB^.Parent].Children[0]=aNodeID then begin
Nodes^[NodeB^.Parent].Children[0]:=NodeBID;
end else begin
Nodes^[NodeB^.Parent].Children[1]:=NodeBID;
end;
end else begin
Root:=NodeBID;
end;
if NodeD^.Height>NodeE^.Height then begin
NodeB^.Children[1]:=NodeDID;
NodeA^.Children[0]:=NodeEID;
NodeE^.Parent:=aNodeID;
NodeA^.AABB:=NodeC^.AABB.Combine(NodeE^.AABB);
NodeB^.AABB:=NodeA^.AABB.Combine(NodeD^.AABB);
NodeA^.Height:=1+Max(NodeC^.Height,NodeE^.Height);
NodeB^.Height:=1+Max(NodeA^.Height,NodeD^.Height);
end else begin
NodeB^.Children[1]:=NodeEID;
NodeA^.Children[0]:=NodeDID;
NodeD^.Parent:=aNodeID;
NodeA^.AABB:=NodeC^.AABB.Combine(NodeD^.AABB);
NodeB^.AABB:=NodeA^.AABB.Combine(NodeE^.AABB);
NodeA^.Height:=1+Max(NodeC^.Height,NodeD^.Height);
NodeB^.Height:=1+Max(NodeA^.Height,NodeE^.Height);
end;
result:=NodeBID;
end else begin
result:=aNodeID;
end;
end;
end;
procedure TpvCSGBSP.TDynamicAABBTree.InsertLeaf(const aLeaf:TpvSizeInt);
var Node:PDynamicAABBTreeNode;
LeafAABB,CombinedAABB,AABB:TAABB;
Index,Sibling,OldParent,NewParent:TpvSizeInt;
Children:array[0..1] of TpvSizeInt;
CombinedCost,Cost,InheritanceCost:TFloat;
Costs:array[0..1] of TFloat;
begin
inc(InsertionCount);
if Root<0 then begin
Root:=aLeaf;
Nodes^[aLeaf].Parent:=daabbtNULLNODE;
end else begin
LeafAABB:=Nodes^[aLeaf].AABB;
Index:=Root;
while Nodes^[Index].Children[0]>=0 do begin
Children[0]:=Nodes^[Index].Children[0];
Children[1]:=Nodes^[Index].Children[1];
CombinedAABB:=Nodes^[Index].AABB.Combine(LeafAABB);
CombinedCost:=CombinedAABB.Cost;
Cost:=CombinedCost*2.0;
InheritanceCost:=2.0*(CombinedCost-Nodes^[Index].AABB.Cost);
AABB:=LeafAABB.Combine(Nodes^[Children[0]].AABB);
if Nodes^[Children[0]].Children[0]<0 then begin
Costs[0]:=AABB.Cost+InheritanceCost;
end else begin
Costs[0]:=(AABB.Cost-Nodes^[Children[0]].AABB.Cost)+InheritanceCost;
end;
AABB:=LeafAABB.Combine(Nodes^[Children[1]].AABB);
if Nodes^[Children[1]].Children[1]<0 then begin
Costs[1]:=AABB.Cost+InheritanceCost;
end else begin
Costs[1]:=(AABB.Cost-Nodes^[Children[1]].AABB.Cost)+InheritanceCost;
end;
if (Cost<Costs[0]) and (Cost<Costs[1]) then begin
break;
end else begin
if Costs[0]<Costs[1] then begin
Index:=Children[0];
end else begin
Index:=Children[1];
end;
end;
end;
Sibling:=Index;
OldParent:=Nodes^[Sibling].Parent;
NewParent:=AllocateNode;
Nodes^[NewParent].Parent:=OldParent;
Nodes^[NewParent].UserData:=0;
Nodes^[NewParent].AABB:=LeafAABB.Combine(Nodes^[Sibling].AABB);
Nodes^[NewParent].Height:=Nodes^[Sibling].Height+1;
if OldParent>=0 then begin
if Nodes^[OldParent].Children[0]=Sibling then begin
Nodes^[OldParent].Children[0]:=NewParent;
end else begin
Nodes^[OldParent].Children[1]:=NewParent;
end;
Nodes^[NewParent].Children[0]:=Sibling;
Nodes^[NewParent].Children[1]:=aLeaf;
Nodes^[Sibling].Parent:=NewParent;
Nodes^[aLeaf].Parent:=NewParent;
end else begin
Nodes^[NewParent].Children[0]:=Sibling;
Nodes^[NewParent].Children[1]:=aLeaf;
Nodes^[Sibling].Parent:=NewParent;
Nodes^[aLeaf].Parent:=NewParent;
Root:=NewParent;
end;
Index:=Nodes^[aLeaf].Parent;
while Index>=0 do begin
Index:=Balance(Index);
Node:=@Nodes^[Index];
Node^.AABB:=Nodes^[Node^.Children[0]].AABB.Combine(Nodes^[Node^.Children[1]].AABB);
Node^.Height:=1+Max(Nodes^[Node^.Children[0]].Height,Nodes^[Node^.Children[1]].Height);
Index:=Node^.Parent;
end;
end;
end;
procedure TpvCSGBSP.TDynamicAABBTree.RemoveLeaf(const aLeaf:TpvSizeInt);
var Node:PDynamicAABBTreeNode;
Parent,GrandParent,Sibling,Index:TpvSizeInt;
begin
if Root=aLeaf then begin
Root:=daabbtNULLNODE;
end else begin
Parent:=Nodes^[aLeaf].Parent;
GrandParent:=Nodes^[Parent].Parent;
if Nodes^[Parent].Children[0]=aLeaf then begin
Sibling:=Nodes^[Parent].Children[1];
end else begin
Sibling:=Nodes^[Parent].Children[0];
end;
if GrandParent>=0 then begin
if Nodes^[GrandParent].Children[0]=Parent then begin
Nodes^[GrandParent].Children[0]:=Sibling;
end else begin
Nodes^[GrandParent].Children[1]:=Sibling;
end;
Nodes^[Sibling].Parent:=GrandParent;
FreeNode(Parent);
Index:=GrandParent;
while Index>=0 do begin
Index:=Balance(Index);
Node:=@Nodes^[Index];
Node^.AABB:=Nodes^[Node^.Children[0]].AABB.Combine(Nodes^[Node^.Children[1]].AABB);
Node^.Height:=1+Max(Nodes^[Node^.Children[0]].Height,Nodes^[Node^.Children[1]].Height);
Index:=Node^.Parent;
end;
end else begin
Root:=Sibling;
Nodes^[Sibling].Parent:=daabbtNULLNODE;
FreeNode(Parent);
end;
end;
end;
function TpvCSGBSP.TDynamicAABBTree.CreateProxy(const aAABB:TAABB;const aUserData:TpvPtrInt):TpvSizeInt;
var Node:PDynamicAABBTreeNode;
begin
result:=AllocateNode;
Node:=@Nodes^[result];
Node^.AABB.Min:=aAABB.Min-ThresholdAABBVector;
Node^.AABB.Max:=aAABB.Max+ThresholdAABBVector;
Node^.UserData:=aUserData;
Node^.Height:=0;
InsertLeaf(result);
end;
procedure TpvCSGBSP.TDynamicAABBTree.DestroyProxy(const aNodeID:TpvSizeInt);
begin
RemoveLeaf(aNodeID);
FreeNode(aNodeID);
end;
function TpvCSGBSP.TDynamicAABBTree.MoveProxy(const aNodeID:TpvSizeInt;const aAABB:TAABB;const aDisplacement:TVector3):boolean;
var Node:PDynamicAABBTreeNode;
b:TAABB;
d:TVector3;
begin
Node:=@Nodes^[aNodeID];
result:=not Node^.AABB.Contains(aAABB);
if result then begin
RemoveLeaf(aNodeID);
b.Min:=aAABB.Min-ThresholdAABBVector;
b.Max:=aAABB.Max+ThresholdAABBVector;
d:=aDisplacement*AABBMULTIPLIER;
if d.x<0.0 then begin
b.Min.x:=b.Min.x+d.x;
end else if d.x>0.0 then begin
b.Max.x:=b.Max.x+d.x;
end;
if d.y<0.0 then begin
b.Min.y:=b.Min.y+d.y;
end else if d.y>0.0 then begin
b.Max.y:=b.Max.y+d.y;
end;
if d.z<0.0 then begin
b.Min.z:=b.Min.z+d.z;
end else if d.z>0.0 then begin
b.Max.z:=b.Max.z+d.z;
end;
Node^.AABB:=b;
InsertLeaf(aNodeID);
end;
end;
procedure TpvCSGBSP.TDynamicAABBTree.Rebalance(const aIterations:TpvSizeInt);
var Counter,Node:TpvSizeInt;
Bit:TpvSizeUInt;
// Children:PDynamicAABBTreeSizeIntArray;
begin
if (Root>=0) and (Root<NodeCount) then begin
for Counter:=1 to aIterations do begin
Bit:=0;
Node:=Root;
while Nodes[Node].Children[0]>=0 do begin
Node:=Nodes[Node].Children[(Path shr Bit) and 1];
Bit:=(Bit+1) and 31;
end;
inc(Path);
if ((Node>=0) and (Node<NodeCount)) and (Nodes[Node].Children[0]<0) then begin
RemoveLeaf(Node);
InsertLeaf(Node);
end else begin
break;
end;
end;
end;
end;
{ TpvCSGBSP.TMesh }
constructor TpvCSGBSP.TMesh.Create(const aMode:TMode=TMode.Polygons);
begin
inherited Create;
fMode:=aMode;
fVertices.Initialize;
fIndices.Initialize;
fPointerToVertices:=@fVertices;
fPointerToIndices:=@fIndices;
end;
constructor TpvCSGBSP.TMesh.Create(const aFrom:TMesh);
begin
Create(aFrom.fMode);
if assigned(aFrom) then begin
SetVertices(aFrom.fVertices);
SetIndices(aFrom.fIndices);
end;
end;
constructor TpvCSGBSP.TMesh.Create(const aFrom:TSingleTreeNode);
var Mesh:TMesh;
begin
Mesh:=aFrom.ToMesh;
try
Create(Mesh.fMode);
fVertices.Assign(Mesh.fVertices);
fIndices.Assign(Mesh.fIndices);
Mesh.fVertices.Clear;
Mesh.fIndices.Clear;
finally
FreeAndNil(Mesh);
end;
end;
constructor TpvCSGBSP.TMesh.Create(const aFrom:TDualTree);
var Mesh:TMesh;
begin
Mesh:=aFrom.ToMesh;
try
Create(Mesh.fMode);
fVertices.Assign(Mesh.fVertices);
fIndices.Assign(Mesh.fIndices);
Mesh.fVertices.Clear;
Mesh.fIndices.Clear;
finally
FreeAndNil(Mesh);
end;
end;
constructor TpvCSGBSP.TMesh.Create(const aFrom:TAABB;const aMode:TMode=TMode.Polygons;const aAdditionalBounds:TFloat=0.0);
const SideVertexIndices:array[0..5,0..3] of TpvUInt8=
(
(0,4,6,2), // Left
(1,3,7,5), // Right
(0,1,5,4), // Bottom
(2,6,7,3), // Top
(0,2,3,1), // Back
(4,5,7,6) // Front
);
SideNormals:array[0..5] of TVector3=
(
(x:-1.0;y:0.0;z:0.0),
(x:1.0;y:0.0;z:0.0),
(x:0.0;y:-1.0;z:0.0),
(x:0.0;y:1.0;z:0.0),
(x:0.0;y:0.0;z:-1.0),
(x:0.0;y:0.0;z:1.0)
);
var SideIndex,SideVertexIndex,VertexIndex,BaseVertexIndex:TpvSizeInt;
Vertex:TVertex;
begin
Create(aMode);
for SideIndex:=0 to 5 do begin
BaseVertexIndex:=fVertices.Count;
for SideVertexIndex:=0 to 3 do begin
VertexIndex:=SideVertexIndices[SideIndex,SideVertexIndex];
Vertex.Position.x:=aFrom.MinMax[(VertexIndex shr 0) and 1].x+(((((VertexIndex shr 0) and 1) shl 1)-1)*aAdditionalBounds);
Vertex.Position.y:=aFrom.MinMax[(VertexIndex shr 1) and 1].y+(((((VertexIndex shr 1) and 1) shl 1)-1)*aAdditionalBounds);
Vertex.Position.z:=aFrom.MinMax[(VertexIndex shr 2) and 1].z+(((((VertexIndex shr 2) and 1) shl 1)-1)*aAdditionalBounds);
Vertex.Normal:=SideNormals[SideIndex];
Vertex.TexCoord.x:=SideVertexIndex and 1;
Vertex.TexCoord.y:=((SideVertexIndex shr 1) and 1) xor (SideVertexIndex and 1);
Vertex.Color.x:=1.0;
Vertex.Color.y:=1.0;
Vertex.Color.z:=1.0;
Vertex.Color.w:=1.0;
fVertices.Add(Vertex);
end;
case fMode of
TMode.Triangles:begin
fIndices.Add([BaseVertexIndex+0,BaseVertexIndex+1,BaseVertexIndex+2,
BaseVertexIndex+0,BaseVertexIndex+2,BaseVertexIndex+3]);
end;
else {TMode.Polygons:}begin
fIndices.Add([4,BaseVertexIndex+0,BaseVertexIndex+1,BaseVertexIndex+2,BaseVertexIndex+3]);
end;
end;
end;
RemoveDuplicateAndUnusedVertices;
end;
constructor TpvCSGBSP.TMesh.CreateCube(const aCX,aCY,aCZ,aRX,aRY,aRZ:TFloat;const aMode:TMode=TMode.Polygons);
const SideVertexIndices:array[0..5,0..3] of TpvUInt8=
(
(0,4,6,2), // Left
(1,3,7,5), // Right
(0,1,5,4), // Bottom
(2,6,7,3), // Top
(0,2,3,1), // Back
(4,5,7,6) // Front
);
SideNormals:array[0..5] of TVector3=
(
(x:-1.0;y:0.0;z:0.0),
(x:1.0;y:0.0;z:0.0),
(x:0.0;y:-1.0;z:0.0),
(x:0.0;y:1.0;z:0.0),
(x:0.0;y:0.0;z:-1.0),
(x:0.0;y:0.0;z:1.0)
);
var SideIndex,SideVertexIndex,VertexIndex,BaseVertexIndex:TpvSizeInt;
Vertex:TVertex;
begin
Create(aMode);
for SideIndex:=0 to 5 do begin
BaseVertexIndex:=fVertices.Count;
for SideVertexIndex:=0 to 3 do begin
VertexIndex:=SideVertexIndices[SideIndex,SideVertexIndex];
Vertex.Position.x:=aCX+(((((VertexIndex shr 0) and 1) shl 1)-1)*aRX);
Vertex.Position.y:=aCY+(((((VertexIndex shr 1) and 1) shl 1)-1)*aRY);
Vertex.Position.z:=aCZ+(((((VertexIndex shr 2) and 1) shl 1)-1)*aRZ);
Vertex.Normal:=SideNormals[SideIndex];
Vertex.TexCoord.x:=SideVertexIndex and 1;
Vertex.TexCoord.y:=((SideVertexIndex shr 1) and 1) xor (SideVertexIndex and 1);
Vertex.Color.x:=1.0;
Vertex.Color.y:=1.0;
Vertex.Color.z:=1.0;
Vertex.Color.w:=1.0;
fVertices.Add(Vertex);
end;
case fMode of
TMode.Triangles:begin
fIndices.Add([BaseVertexIndex+0,BaseVertexIndex+1,BaseVertexIndex+2,
BaseVertexIndex+0,BaseVertexIndex+2,BaseVertexIndex+3]);
end;
else {TMode.Polygons:}begin
fIndices.Add([4,BaseVertexIndex+0,BaseVertexIndex+1,BaseVertexIndex+2,BaseVertexIndex+3]);
end;
end;
end;
RemoveDuplicateAndUnusedVertices;
end;
constructor TpvCSGBSP.TMesh.CreateSphere(const aCX,aCY,aCZ,aRadius:TFloat;const aSlices:TpvSizeInt=16;const aStacks:TpvSizeInt=8;const aMode:TMode=TMode.Polygons);
function AddVertex(const aTheta,aPhi:TpvDouble):TIndex;
var Theta,Phi,dx,dy,dz:TFloat;
Vertex:TVertex;
begin
Theta:=aTheta*TwoPI;
Phi:=aPhi*PI;
dx:=cos(Theta)*sin(Phi);
dy:=cos(Phi);
dz:=sin(Theta)*sin(Phi);
Vertex.Position.x:=aCX+(dx*aRadius);
Vertex.Position.y:=aCY+(dy*aRadius);
Vertex.Position.z:=aCZ+(dz*aRadius);
Vertex.Normal.x:=dx;
Vertex.Normal.y:=dy;
Vertex.Normal.z:=dz;
Vertex.TexCoord.x:=aTheta;
Vertex.TexCoord.y:=aPhi;
Vertex.Color.x:=1.0;
Vertex.Color.y:=1.0;
Vertex.Color.z:=1.0;
Vertex.Color.w:=1.0;
result:=fVertices.Add(Vertex);
end;
var SliceIndex,StackIndex:TpvSizeInt;
PolygonIndices:TIndexList;
begin
Create(aMode);
PolygonIndices.Initialize;
try
for SliceIndex:=0 to aSlices-1 do begin
for StackIndex:=0 to aStacks-1 do begin
PolygonIndices.Clear;
PolygonIndices.Add(AddVertex(SliceIndex/aSlices,StackIndex/aStacks));
if StackIndex>0 then begin
PolygonIndices.Add(AddVertex((SliceIndex+1)/aSlices,StackIndex/aStacks));
end;
if StackIndex<(aStacks-1) then begin
PolygonIndices.Add(AddVertex((SliceIndex+1)/aSlices,(StackIndex+1)/aStacks));
end;
PolygonIndices.Add(AddVertex(SliceIndex/aSlices,(StackIndex+1)/aStacks));
case fMode of
TMode.Triangles:begin
case PolygonIndices.Count of
3:begin
fIndices.Add(PolygonIndices);
end;
4:begin
fIndices.Add([PolygonIndices.Items[0],PolygonIndices.Items[1],PolygonIndices.Items[2],
PolygonIndices.Items[0],PolygonIndices.Items[2],PolygonIndices.Items[3]]);
end;
else begin
Assert(false);
end;
end;
end;
else {TMode.Polygons:}begin
fIndices.Add(PolygonIndices.Count);
fIndices.Add(PolygonIndices);
end;
end;
end;
end;
finally
PolygonIndices.Finalize;
end;
RemoveDuplicateAndUnusedVertices;
end;
constructor TpvCSGBSP.TMesh.CreateFromCSGOperation(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGOperation:TCSGOperation;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
begin
Create;
case aCSGOperation of
TCSGOperation.Union:begin
Union(aLeftMesh,aRightMesh,aCSGMode,aCSGOptimization,aSplitSettings);
end;
TCSGOperation.Subtraction:begin
Subtraction(aLeftMesh,aRightMesh,aCSGMode,aCSGOptimization,aSplitSettings);
end;
TCSGOperation.Intersection:begin
Intersection(aLeftMesh,aRightMesh,aCSGMode,aCSGOptimization,aSplitSettings);
end;
else begin
Assert(false);
end;
end;
end;
constructor TpvCSGBSP.TMesh.CreateUnion(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
begin
Create;
Union(aLeftMesh,aRightMesh,aCSGMode,aCSGOptimization,aSplitSettings);
end;
constructor TpvCSGBSP.TMesh.CreateSubtraction(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
begin
Create;
Subtraction(aLeftMesh,aRightMesh,aCSGMode,aCSGOptimization,aSplitSettings);
end;
constructor TpvCSGBSP.TMesh.CreateIntersection(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
begin
Create;
Intersection(aLeftMesh,aRightMesh,aCSGMode,aCSGOptimization,aSplitSettings);
end;
constructor TpvCSGBSP.TMesh.CreateSymmetricDifference(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
begin
Create;
SymmetricDifference(aLeftMesh,aRightMesh,aCSGMode,aCSGOptimization,aSplitSettings);
end;
destructor TpvCSGBSP.TMesh.Destroy;
begin
fVertices.Finalize;
fIndices.Finalize;
fPointerToVertices:=nil;
fPointerToIndices:=nil;
inherited Destroy;
end;
procedure TpvCSGBSP.TMesh.SaveOBJToStream(const aStream:TStream);
function FloatStr(const aValue:TpvDouble):TpvRawByteString;
var Index:TpvSizeInt;
begin
Str(aValue:1:10,result);
if pos('.',result)>0 then begin
Index:=length(result);
while (Index>3) and (result[Index]='0') and (result[Index-2]<>'.') do begin
dec(Index);
end;
SetLength(result,Index);
end;
end;
procedure WriteOut(const aValue:TpvRawByteString);
begin
if length(aValue)>0 then begin
aStream.Write(aValue[1],length(aValue));
end;
end;
const NewLine={$ifdef Unix}#10{$else}#13#10{$endif};
var Index,Count,CountPolygonVertices,i:TpvSizeInt;
v:PVertex;
begin
for Index:=0 to fVertices.Count-1 do begin
v:=@fVertices.Items[Index];
WriteOut('v '+FloatStr(v^.Position.x)+' '+FloatStr(v^.Position.y)+' '+FloatStr(v^.Position.z)+NewLine);
WriteOut('vn '+FloatStr(v^.Normal.x)+' '+FloatStr(v^.Normal.y)+' '+FloatStr(v^.Normal.z)+NewLine);
WriteOut('vt '+FloatStr(v^.TexCoord.x)+' '+FloatStr(v^.TexCoord.y)+NewLine);
end;
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
WriteOut('f');
while (CountPolygonVertices>0) and (Index<Count) do begin
i:=fIndices.Items[Index]+1;
WriteOut(' '+IntToStr(i)+'/'+IntToStr(i)+'/'+IntToStr(i));
inc(Index);
dec(CountPolygonVertices);
end;
WriteOut(NewLine);
end;
end;
procedure TpvCSGBSP.TMesh.SaveOBJToFile(const aFileName:string);
var FileStream:TFileStream;
begin
FileStream:=TFileStream.Create(aFileName,fmCreate);
try
SaveOBJToStream(FileStream);
finally
FreeAndNil(FileStream);
end;
end;
procedure TpvCSGBSP.TMesh.SetMode(const aMode:TMode);
var Index,Count,CountPolygonVertices,PolygonVertexIndex:TpvSizeInt;
NewIndices:TIndexList;
begin
if fMode<>aMode then begin
NewIndices.Initialize;
try
if (fMode=TMode.Triangles) and (aMode=TMode.Polygons) then begin
Index:=0;
Count:=fIndices.Count;
while (Index+2)<Count do begin
NewIndices.Add([3,fIndices.Items[Index+0],fIndices.Items[Index+1],fIndices.Items[Index+2]]);
inc(Index,3);
end;
//Assert(Index=Count);
end else if (fMode=TMode.Polygons) and (aMode=TMode.Triangles) then begin
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
if (CountPolygonVertices>0) and
((Index+(CountPolygonVertices-1))<Count) then begin
if CountPolygonVertices>2 then begin
for PolygonVertexIndex:=2 to CountPolygonVertices-1 do begin
NewIndices.Add([fIndices.Items[Index+0],
fIndices.Items[Index+(PolygonVertexIndex-1)],
fIndices.Items[Index+PolygonVertexIndex]]);
end;
end;
inc(Index,CountPolygonVertices);
end else begin
Assert(false);
end;
end;
Assert(Index=Count);
end else begin
Assert(false);
end;
SetIndices(NewIndices);
finally
NewIndices.Finalize;
end;
fMode:=aMode;
end;
end;
procedure TpvCSGBSP.TMesh.SetVertices(const aVertices:TVertexList);
begin
fVertices.Assign(aVertices);
end;
procedure TpvCSGBSP.TMesh.SetIndices(const aIndices:TIndexList);
begin
fIndices.Assign(aIndices);
end;
procedure TpvCSGBSP.TMesh.Clear;
begin
fVertices.Clear;
fIndices.Clear;
end;
procedure TpvCSGBSP.TMesh.Assign(const aFrom:TMesh);
begin
fMode:=aFrom.fMode;
SetVertices(aFrom.fVertices);
SetIndices(aFrom.fIndices);
end;
procedure TpvCSGBSP.TMesh.Assign(const aFrom:TSingleTreeNode);
var Mesh:TMesh;
begin
Mesh:=aFrom.ToMesh;
try
fMode:=Mesh.fMode;
SetVertices(Mesh.fVertices);
SetIndices(Mesh.fIndices);
finally
FreeAndNil(Mesh);
end;
end;
procedure TpvCSGBSP.TMesh.Assign(const aFrom:TDualTree);
var Mesh:TMesh;
begin
Mesh:=aFrom.fMesh;
fMode:=Mesh.fMode;
fVertices.Assign(Mesh.fVertices);
fIndices.Clear;
aFrom.GetIndices(fIndices);
end;
procedure TpvCSGBSP.TMesh.Append(const aFrom:TMesh);
var Index,Count,CountPolygonVertices,Offset:TpvSizeInt;
Mesh:TMesh;
begin
Mesh:=TMesh.Create(aFrom);
try
Mesh.SetMode(fMode);
Offset:=fVertices.Count;
fVertices.Add(Mesh.fVertices);
Index:=0;
Count:=Mesh.fIndices.Count;
while Index<Count do begin
case fMode of
TMesh.TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMesh.TMode.Polygons:}begin
CountPolygonVertices:=Mesh.fIndices.Items[Index];
inc(Index);
AddIndex(CountPolygonVertices);
end;
end;
while (Index<Count) and (CountPolygonVertices>0) do begin
AddIndex(Mesh.fIndices.Items[Index]+Offset);
dec(CountPolygonVertices);
inc(Index);
end;
end;
finally
FreeAndNil(Mesh);
end;
end;
procedure TpvCSGBSP.TMesh.Append(const aFrom:TSingleTreeNode);
var Mesh:TMesh;
begin
Mesh:=aFrom.ToMesh;
try
Append(Mesh);
finally
FreeAndNil(Mesh);
end;
end;
procedure TpvCSGBSP.TMesh.Append(const aFrom:TDualTree);
var Mesh:TMesh;
begin
Mesh:=aFrom.ToMesh;
try
Append(Mesh);
finally
FreeAndNil(Mesh);
end;
end;
function TpvCSGBSP.TMesh.AddVertex(const aVertex:TVertex):TIndex;
begin
result:=fVertices.Add(aVertex);
end;
function TpvCSGBSP.TMesh.AddVertices(const aVertices:array of TVertex):TIndex;
begin
result:=fVertices.Add(aVertices);
end;
function TpvCSGBSP.TMesh.AddVertices(const aVertices:TVertexList):TIndex;
begin
result:=fVertices.Add(aVertices);
end;
function TpvCSGBSP.TMesh.AddIndex(const aIndex:TIndex):TpvSizeInt;
begin
result:=fIndices.Add(aIndex);
end;
function TpvCSGBSP.TMesh.AddIndices(const aIndices:array of TIndex):TpvSizeInt;
begin
result:=fIndices.Add(aIndices);
end;
function TpvCSGBSP.TMesh.AddIndices(const aIndices:TIndexList):TpvSizeInt;
begin
result:=fIndices.Add(aIndices);
end;
function TpvCSGBSP.TMesh.GetAxisAlignedBoundingBox:TAABB;
var Index:TpvSizeInt;
begin
if fVertices.Count>0 then begin
result.Min:=fVertices.Items[0].Position;
result.Max:=fVertices.Items[0].Position;
for Index:=1 to fVertices.Count-1 do begin
result:=result.Combine(fVertices.Items[Index].Position);
end;
end else begin
result.Min:=TVector3.Create(Infinity,Infinity,Infinity);
result.Max:=TVector3.Create(-Infinity,-Infinity,-Infinity);
end;
end;
procedure TpvCSGBSP.TMesh.Invert;
var Index,Count,CountPolygonVertices,PolygonVertexIndex,IndexA,IndexB:TpvSizeInt;
begin
for Index:=0 To fVertices.Count-1 do begin
fVertices.Items[Index].Flip;
end;
case fMode of
TMode.Triangles:begin
Index:=0;
Count:=fIndices.Count;
while (Index+2)<Count do begin
fIndices.Exchange(Index+0,Index+2);
inc(Index,3);
end;
end;
else {TMode.Polygons:}begin
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
if CountPolygonVertices>0 then begin
if (Index+(CountPolygonVertices-1))<Count then begin
for PolygonVertexIndex:=0 to (CountPolygonVertices shr 1)-1 do begin
IndexA:=Index+PolygonVertexIndex;
IndexB:=Index+(CountPolygonVertices-(PolygonVertexIndex+1));
if IndexA<>IndexB then begin
fIndices.Exchange(IndexA,IndexB);
end;
end;
inc(Index,CountPolygonVertices);
end else begin
Assert(false);
end;
end;
end;
end;
end;
end;
procedure TpvCSGBSP.TMesh.ConvertToPolygons;
begin
SetMode(TMode.Polygons);
end;
procedure TpvCSGBSP.TMesh.ConvertToTriangles;
begin
SetMode(TMode.Triangles);
end;
procedure TpvCSGBSP.TMesh.TriangleCSGOperation(const aLeftNode:TSingleTreeNode;
const aRightNode:TSingleTreeNode;
const aVertices:TVertexList;
const aInside:boolean;
const aKeepEdge:boolean;
const aInvert:boolean);
function ProcessTriangle(const aNode:TSingleTreeNode;
const aVertex0:TVertex;
const aVertex1:TVertex;
const aVertex2:TVertex;
const aInside:boolean;
const aKeepEdge:boolean;
const aKeepNow:boolean;
const aInvert:boolean):boolean;
type TWorkData=record
Node:TSingleTreeNode;
Vertex0:TVertex;
Vertex1:TVertex;
Vertex2:TVertex;
Inside:boolean;
KeepEdge:boolean;
KeepNow:boolean;
Invert:boolean;
Completed:boolean;
Clipped:boolean;
PreviousWorkData:TpvSizeInt;
OldCountVertices:TpvSizeInt;
OldCountIndices:TpvSizeInt;
end;
PWorkData=^TWorkData;
TJobStackItem=record
WorkData:TpvSizeInt;
Step:TpvSizeInt;
end;
TWorkDataArray=TDynamicArray<TWorkData>;
TJobStack=TDynamicStack<TJobStackItem>;
var WorkDataArray:TWorkDataArray;
JobStack:TJobStack;
function NewWorkData(const aNode:TSingleTreeNode;
const aVertex0:TVertex;
const aVertex1:TVertex;
const aVertex2:TVertex;
const aInside:boolean;
const aKeepEdge:boolean;
const aKeepNow:boolean;
const aInvert:boolean;
const aPreviousWorkData:TpvSizeInt):TpvSizeInt;
var WorkData:TWorkData;
begin
WorkData.Node:=aNode;
WorkData.Vertex0:=aVertex0;
WorkData.Vertex1:=aVertex1;
WorkData.Vertex2:=aVertex2;
WorkData.Inside:=aInside;
WorkData.KeepEdge:=aKeepEdge;
WorkData.KeepNow:=aKeepEdge;
WorkData.Invert:=aInvert;
WorkData.PreviousWorkData:=aPreviousWorkData;
WorkData.Completed:=true;
WorkData.Clipped:=true;
result:=WorkDataArray.Add(WorkData);
end;
procedure NewJobStackItem(const aWorkData:TpvSizeInt;
const aStep:TpvSizeInt);
var JobStackItem:TJobStackItem;
begin
JobStackItem.WorkData:=aWorkData;
JobStackItem.Step:=aStep;
JobStack.Push(JobStackItem);
end;
var WorkDataIndex:TpvSizeInt;
JobStackItem:TJobStackItem;
WorkData,OtherWorkData:PWorkData;
FunctionResult:boolean;
procedure Append(const aVertex0,aVertex1,aVertex2:TVertex);
begin
fIndices.Add(fVertices.Add(aVertex0));
fIndices.Add(fVertices.Add(aVertex1));
fIndices.Add(fVertices.Add(aVertex2));
end;
procedure NextTriangle(const aNode:TSingleTreeNode;
const aVertex0:TVertex;
const aVertex1:TVertex;
const aVertex2:TVertex;
const aInside:boolean;
const aKeepEdge:boolean;
const aKeepNow:boolean;
const aInvert:boolean);
var Completed:boolean;
begin
if assigned(aNode) then begin
NewJobStackItem(NewWorkData(aNode,
aVertex0,
aVertex1,
aVertex2,
aInside,
aKeepEdge,
aKeepNow,
aInvert,
WorkDataIndex),
0);
WorkData:=@WorkDataArray.Items[JobStackItem.WorkData];
end else begin
if aKeepNow then begin
if aInvert then begin
Append(aVertex2.CloneFlip,aVertex1.CloneFlip,aVertex0.CloneFlip);
end else begin
Append(aVertex0,aVertex1,aVertex2);
end;
end;
Completed:=aKeepNow;
if assigned(WorkData) then begin
WorkData^.Completed:=WorkData^.Completed and Completed;
end else begin
FunctionResult:=Completed;
end;
end;
end;
var Sides:array[0..2] of TpvSizeInt;
Points:array[0..2] of TVertex;
PlaneDistances:array[0..2] of TFloat;
begin
FunctionResult:=true;
try
WorkDataArray.Initialize;
try
JobStack.Initialize;
try
WorkDataIndex:=-1;
WorkData:=nil;
NextTriangle(aNode,
aVertex0,
aVertex1,
aVertex2,
aInside,
aKeepEdge,
aKeepNow,
aInvert);
while JobStack.Pop(JobStackItem) do begin
WorkDataIndex:=JobStackItem.WorkData;
WorkData:=@WorkDataArray.Items[WorkDataIndex];
case JobStackItem.Step of
0:begin
PlaneDistances[0]:=WorkData^.Node.fPlane.DistanceTo(WorkData^.Vertex0.Position);
PlaneDistances[1]:=WorkData^.Node.fPlane.DistanceTo(WorkData^.Vertex1.Position);
PlaneDistances[2]:=WorkData^.Node.fPlane.DistanceTo(WorkData^.Vertex2.Position);
Sides[0]:=TpvCSGBSP.EpsilonSign(PlaneDistances[0]);
Sides[1]:=TpvCSGBSP.EpsilonSign(PlaneDistances[1]);
Sides[2]:=TpvCSGBSP.EpsilonSign(PlaneDistances[2]);
PlaneDistances[0]:=PlaneDistances[0]*abs(Sides[0]);
PlaneDistances[1]:=PlaneDistances[1]*abs(Sides[1]);
PlaneDistances[2]:=PlaneDistances[2]*abs(Sides[2]);
if (Sides[0]*Sides[1])<0 then begin
Points[0]:=WorkData^.Vertex0.Lerp(WorkData^.Vertex1,abs(PlaneDistances[0])/(abs(PlaneDistances[0])+abs(PlaneDistances[1])));
end;
if (Sides[1]*Sides[2])<0 then begin
Points[1]:=WorkData^.Vertex1.Lerp(WorkData^.Vertex2,abs(PlaneDistances[1])/(abs(PlaneDistances[1])+abs(PlaneDistances[2])));
end;
if (Sides[2]*Sides[0])<0 then begin
Points[2]:=WorkData^.Vertex2.Lerp(WorkData^.Vertex0,abs(PlaneDistances[2])/(abs(PlaneDistances[2])+abs(PlaneDistances[0])));
end;
WorkData^.OldCountVertices:=fVertices.Count;
WorkData^.OldCountIndices:=fIndices.Count;
WorkData^.Completed:=true;
WorkData^.Clipped:=true;
NewJobStackItem(JobStackItem.WorkData,1);
case ((Sides[0]+1) shl 0) or
((Sides[1]+1) shl 2) or
((Sides[2]+1) shl 4) of
// All points are on one side of the plane (or on the plane)
// in this case we simply add the complete triangle to the proper halve of the subtree
(((-1)+1) shl 0) or (((-1)+1) shl 2) or (((-1)+1) shl 4),
(((-1)+1) shl 0) or (((-1)+1) shl 2) or (((0)+1) shl 4),
(((-1)+1) shl 0) or (((0)+1) shl 2) or (((-1)+1) shl 4),
(((-1)+1) shl 0) or (((0)+1) shl 2) or (((0)+1) shl 4),
(((0)+1) shl 0) or (((-1)+1) shl 2) or (((-1)+1) shl 4),
(((0)+1) shl 0) or (((-1)+1) shl 2) or (((0)+1) shl 4),
(((0)+1) shl 0) or (((0)+1) shl 2) or (((-1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex0,WorkData^.Vertex1,WorkData^.Vertex2,WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
WorkData^.Clipped:=false;
end;
(((0)+1) shl 0) or (((0)+1) shl 2) or (((1)+1) shl 4),
(((0)+1) shl 0) or (((1)+1) shl 2) or (((0)+1) shl 4),
(((0)+1) shl 0) or (((1)+1) shl 2) or (((1)+1) shl 4),
(((1)+1) shl 0) or (((0)+1) shl 2) or (((0)+1) shl 4),
(((1)+1) shl 0) or (((0)+1) shl 2) or (((1)+1) shl 4),
(((1)+1) shl 0) or (((1)+1) shl 2) or (((0)+1) shl 4),
(((1)+1) shl 0) or (((1)+1) shl 2) or (((1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex0,WorkData^.Vertex1,WorkData^.Vertex2,WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
WorkData^.Clipped:=false;
end;
// Triangle on the dividing plane
(((0)+1) shl 0) or (((0)+1) shl 2) or (((0)+1) shl 4):begin
if WorkData^.KeepEdge then begin
Append(WorkData^.Vertex0,WorkData^.Vertex1,WorkData^.Vertex2);
WorkData^.Clipped:=false;
end;
end;
// And now all the ways that the triangle can be cut by the plane
(((1)+1) shl 0) or (((-1)+1) shl 2) or (((0)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex1,WorkData^.Vertex2,Points[0],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex2,WorkData^.Vertex1,Points[0],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
(((-1)+1) shl 0) or (((0)+1) shl 2) or (((1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex0,WorkData^.Vertex1,Points[2],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex1,WorkData^.Vertex2,Points[2],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
(((0)+1) shl 0) or (((1)+1) shl 2) or (((-1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex2,WorkData^.Vertex0,Points[1],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex0,WorkData^.Vertex1,Points[1],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
(((-1)+1) shl 0) or (((1)+1) shl 2) or (((0)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex2,WorkData^.Vertex0,Points[0],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex1,WorkData^.Vertex2,Points[0],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
(((1)+1) shl 0) or (((0)+1) shl 2) or (((-1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex1,WorkData^.Vertex2,Points[2],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex0,WorkData^.Vertex1,Points[2],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
(((0)+1) shl 0) or (((-1)+1) shl 2) or (((1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex0,WorkData^.Vertex1,Points[1],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex2,WorkData^.Vertex0,Points[1],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
(((1)+1) shl 0) or (((-1)+1) shl 2) or (((-1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex0,Points[0],Points[2],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex1,Points[2],Points[0],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex1,WorkData^.Vertex2,Points[2],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
end;
(((-1)+1) shl 0) or (((1)+1) shl 2) or (((-1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex1,Points[1],Points[0],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex2,Points[0],Points[1],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex2,WorkData^.Vertex0,Points[0],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
end;
(((-1)+1) shl 0) or (((-1)+1) shl 2) or (((1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex2,Points[2],Points[1],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex0,Points[1],Points[2],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex0,WorkData^.Vertex1,Points[1],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
end;
(((-1)+1) shl 0) or (((1)+1) shl 2) or (((1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex0,Points[0],Points[2],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex1,Points[2],Points[0],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex1,WorkData^.Vertex2,Points[2],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
(((1)+1) shl 0) or (((-1)+1) shl 2) or (((1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex1,Points[1],Points[0],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex0,Points[0],Points[1],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex2,WorkData^.Vertex0,Points[1],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
(((1)+1) shl 0) or (((1)+1) shl 2) or (((-1)+1) shl 4):begin
NextTriangle(WorkData^.Node.fBack,WorkData^.Vertex2,Points[2],Points[1],WorkData^.Inside,WorkData^.KeepEdge,WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex0,Points[1],Points[2],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
NextTriangle(WorkData^.Node.fFront,WorkData^.Vertex0,WorkData^.Vertex1,Points[1],WorkData^.Inside,WorkData^.KeepEdge,not WorkData^.Inside,WorkData^.Invert);
end;
// Otherwise it is a error
else begin
WorkData^.Completed:=false;
end;
end;
end;
1:begin
if WorkData^.Completed and WorkData^.Clipped then begin
fVertices.Count:=WorkData^.OldCountVertices;
fIndices.Count:=WorkData^.OldCountIndices;
if WorkData^.Invert then begin
Append(WorkData^.Vertex2.CloneFlip,WorkData^.Vertex1.CloneFlip,WorkData^.Vertex0.CloneFlip);
end else begin
Append(WorkData^.Vertex0,WorkData^.Vertex1,WorkData^.Vertex2);
end;
end;
if WorkData^.PreviousWorkData>=0 then begin
OtherWorkData:=@WorkDataArray.Items[WorkData^.PreviousWorkData];
OtherWorkData^.Completed:=OtherWorkData^.Completed and WorkData^.Completed;
end else begin
FunctionResult:=WorkData^.Completed;
end;
dec(WorkDataArray.Count);
end;
end;
end;
finally
JobStack.Finalize;
end;
finally
WorkDataArray.Finalize;
end;
finally
result:=FunctionResult;
end;
end;
type TJobStack=TDynamicStack<TSingleTreeNode>;
var JobStack:TJobStack;
Node:TSingleTreeNode;
Index,Count:TpvSizeInt;
begin
if assigned(aLeftNode) and assigned(aRightNode) then begin
JobStack.Initialize;
try
JobStack.Push(aRightNode);
while JobStack.Pop(Node) do begin
if assigned(Node) then begin
Index:=0;
Count:=Node.fIndices.Count;
while (Index+2)<Count do begin
ProcessTriangle(aLeftNode,
aVertices.Items[Node.fIndices.Items[Index+0]],
aVertices.Items[Node.fIndices.Items[Index+1]],
aVertices.Items[Node.fIndices.Items[Index+2]],
aInside,
aKeepEdge,
false,
aInvert);
inc(Index,3);
end;
if assigned(Node.fFront) then begin
JobStack.Push(Node.fFront);
end;
if assigned(Node.fBack) then begin
JobStack.Push(Node.fBack);
end;
end;
end;
finally
JobStack.Finalize;
end;
end;
end;
procedure TpvCSGBSP.TMesh.FastSplitPolygonsIntoOuterAndInnerMeshsByInsideRangeAABB(const aOuterLeftMesh:TMesh;
const aInnerLeftMesh:TMesh;
const aInsideRangeAABB:TAABB);
var Index,Count,CountPolygonVertices,
OtherIndex:TpvSizeInt;
PolygonAABB:TAABB;
begin
aOuterLeftMesh.fMode:=fMode;
aInnerLeftMesh.fMode:=fMode;
aOuterLeftMesh.SetVertices(fVertices);
aInnerLeftMesh.SetVertices(fVertices);
aOuterLeftMesh.fIndices.Clear;
aInnerLeftMesh.fIndices.Clear;
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
case fMode of
TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMode.Polygons:}begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
end;
end;
if CountPolygonVertices>2 then begin
if (Index+(CountPolygonVertices-1))<Count then begin
PolygonAABB.Min:=fVertices.Items[fIndices.Items[Index]].Position;
PolygonAABB.Max:=fVertices.Items[fIndices.Items[Index]].Position;
for OtherIndex:=Index+1 to Index+(CountPolygonVertices-1) do begin
PolygonAABB:=PolygonAABB.Combine(fVertices.Items[fIndices.Items[OtherIndex]].Position);
end;
if aInsideRangeAABB.Intersects(PolygonAABB) then begin
if fMode=TMode.Polygons then begin
aInnerLeftMesh.fIndices.Add(CountPolygonVertices);
end;
aInnerLeftMesh.fIndices.AddRangeFrom(fIndices,Index,CountPolygonVertices);
end else begin
if fMode=TMode.Polygons then begin
aOuterLeftMesh.fIndices.Add(CountPolygonVertices);
end;
aOuterLeftMesh.fIndices.AddRangeFrom(fIndices,Index,CountPolygonVertices);
end;
end;
end;
inc(Index,CountPolygonVertices);
end;
end;
procedure TpvCSGBSP.TMesh.RemoveNearDuplicateIndices(var aIndices:TIndexList);
var Index:TpvSizeInt;
VertexIndices:array[0..1] of TIndex;
begin
Index:=0;
while (Index<aIndices.Count) and
(aIndices.Count>3) do begin
VertexIndices[0]:=aIndices.Items[Index];
if (Index+1)<aIndices.Count then begin
VertexIndices[1]:=aIndices.Items[Index+1];
end else begin
VertexIndices[1]:=aIndices.Items[0];
end;
if ((fVertices.Items[VertexIndices[0]].Position-fVertices.Items[VertexIndices[1]].Position).SquaredLength<SquaredNearPositionEpsilon) and
((fVertices.Items[VertexIndices[0]].Normal-fVertices.Items[VertexIndices[1]].Normal).SquaredLength<SquaredNearPositionEpsilon) and
((fVertices.Items[VertexIndices[0]].TexCoord-fVertices.Items[VertexIndices[1]].TexCoord).SquaredLength<SquaredNearPositionEpsilon) and
((fVertices.Items[VertexIndices[0]].Color-fVertices.Items[VertexIndices[1]].Color).SquaredLength<SquaredNearPositionEpsilon) then begin
aIndices.Delete(Index);
end else begin
inc(Index);
end;
end;
end;
procedure TpvCSGBSP.TMesh.DoUnion(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode;
const aSplitSettings:PSplitSettings=nil);
var LeftMesh,RightMesh:TMesh;
LeftSingleTreeNode,RightSingleTreeNode:TSingleTreeNode;
LeftDualTree,RightDualTree:TDualTree;
begin
case aCSGMode of
TCSGMode.SingleTree:begin
SetMode(TMode.Polygons);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Polygons);
LeftSingleTreeNode:=LeftMesh.ToSingleTreeNode(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Polygons);
RightSingleTreeNode:=RightMesh.ToSingleTreeNode(aSplitSettings);
try
LeftSingleTreeNode.ClipTo(RightSingleTreeNode);
RightSingleTreeNode.ClipTo(LeftSingleTreeNode);
RightSingleTreeNode.Invert;
RightSingleTreeNode.ClipTo(LeftSingleTreeNode);
RightSingleTreeNode.Invert;
LeftSingleTreeNode.Merge(RightSingleTreeNode,aSplitSettings);
finally
FreeAndNil(RightSingleTreeNode);
end;
finally
FreeAndNil(RightMesh);
end;
Assign(LeftSingleTreeNode);
finally
FreeAndNil(LeftSingleTreeNode);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
TCSGMode.DualTree:begin
SetMode(TMode.Polygons);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Polygons);
LeftDualTree:=LeftMesh.ToDualTree(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Polygons);
RightDualTree:=RightMesh.ToDualTree(aSplitSettings);
try
LeftDualTree.ClipTo(RightDualTree,false);
RightDualTree.ClipTo(LeftDualTree,false);
RightDualTree.Invert;
RightDualTree.ClipTo(LeftDualTree,false);
RightDualTree.Invert;
LeftDualTree.Merge(RightDualTree);
finally
FreeAndNil(RightDualTree);
end;
finally
FreeAndNil(RightMesh);
end;
Assign(LeftDualTree);
finally
FreeAndNil(LeftDualTree);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
TCSGMode.Triangles:begin
SetMode(TMode.Triangles);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Triangles);
LeftSingleTreeNode:=LeftMesh.ToSingleTreeNode(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Triangles);
RightSingleTreeNode:=RightMesh.ToSingleTreeNode(aSplitSettings);
try
TriangleCSGOperation(RightSingleTreeNode,LeftSingleTreeNode,LeftMesh.fVertices,false,false,false);
TriangleCSGOperation(LeftSingleTreeNode,RightSingleTreeNode,RightMesh.fVertices,false,true,false);
finally
FreeAndNil(RightSingleTreeNode);
end;
finally
FreeAndNil(RightMesh);
end;
finally
FreeAndNil(LeftSingleTreeNode);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
else begin
Assert(false);
end;
end;
RemoveDuplicateAndUnusedVertices;
if (aLeftMesh.fMode=TMode.Triangles) and (aRightMesh.fMode=TMode.Triangles) then begin
SetMode(TMode.Triangles);
end else if (aLeftMesh.fMode=TMode.Polygons) and (aRightMesh.fMode=TMode.Polygons) then begin
SetMode(TMode.Polygons);
end;
end;
procedure TpvCSGBSP.TMesh.Union(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var AABBLeft,AABBRight,AABBIntersection:TAABB;
AABBIntersectionMesh,
OuterLeftMesh,InnerLeftMesh,
OuterRightMesh,InnerRightMesh:TMesh;
begin
AABBLeft:=aLeftMesh.GetAxisAlignedBoundingBox;
AABBRight:=aRightMesh.GetAxisAlignedBoundingBox;
if AABBLeft.Intersects(AABBRight) then begin
case aCSGOptimization of
TMesh.TCSGOptimization.CSG:begin
AABBIntersection:=AABBLeft.Intersection(AABBRight);
AABBIntersectionMesh:=TMesh.Create(AABBIntersection,TMesh.TMode.Polygons,CSGOptimizationBoundEpsilon);
try
OuterLeftMesh:=TMesh.CreateSubtraction(aLeftMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
InnerLeftMesh:=TMesh.CreateIntersection(aLeftMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
OuterRightMesh:=TMesh.CreateSubtraction(aRightMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
InnerRightMesh:=TMesh.CreateIntersection(aRightMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
DoUnion(InnerLeftMesh,InnerRightMesh,aCSGMode,aSplitSettings);
finally
FreeAndNil(InnerRightMesh);
end;
Union(OuterRightMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
finally
FreeAndNil(OuterRightMesh);
end;
Union(OuterLeftMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
finally
FreeAndNil(InnerLeftMesh);
end;
finally
FreeAndNil(OuterLeftMesh);
end;
finally
FreeAndNil(AABBIntersectionMesh);
end;
end;
TMesh.TCSGOptimization.Polygons:begin
AABBIntersection:=AABBLeft.Intersection(AABBRight);
OuterLeftMesh:=TMesh.Create;
try
InnerLeftMesh:=TMesh.Create;
try
aLeftMesh.FastSplitPolygonsIntoOuterAndInnerMeshsByInsideRangeAABB(OuterLeftMesh,InnerLeftMesh,AABBIntersection);
OuterRightMesh:=TMesh.Create;
try
InnerRightMesh:=TMesh.Create;
try
aRightMesh.FastSplitPolygonsIntoOuterAndInnerMeshsByInsideRangeAABB(OuterRightMesh,InnerRightMesh,AABBIntersection);
DoUnion(InnerLeftMesh,InnerRightMesh,aCSGMode,aSplitSettings);
finally
FreeAndNil(InnerRightMesh);
end;
Append(OuterRightMesh);
finally
FreeAndNil(OuterRightMesh);
end;
finally
FreeAndNil(InnerLeftMesh);
end;
Append(OuterLeftMesh);
finally
FreeAndNil(OuterLeftMesh);
end;
end;
else begin
DoUnion(aLeftMesh,aRightMesh,aCSGMode,aSplitSettings);
end;
end;
end else begin
Assign(aLeftMesh);
Append(aRightMesh);
RemoveDuplicateAndUnusedVertices;
end;
end;
procedure TpvCSGBSP.TMesh.Union(const aWithMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var TemporaryMesh:TMesh;
begin
TemporaryMesh:=TMesh.Create(fMode);
try
TemporaryMesh.Union(self,aWithMesh,aCSGMode,aCSGOptimization,aSplitSettings);
Assign(TemporaryMesh);
finally
FreeAndNil(TemporaryMesh);
end;
end;
procedure TpvCSGBSP.TMesh.UnionOf(const aMeshs:array of TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var Index:TpvSizeInt;
begin
if length(aMeshs)>0 then begin
Assign(aMeshs[0]);
for Index:=1 to length(aMeshs)-1 do begin
Union(aMeshs[Index],aCSGMode,aCSGOptimization,aSplitSettings);
end;
end else begin
Clear;
end;
end;
procedure TpvCSGBSP.TMesh.DoSubtraction(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode;
const aSplitSettings:PSplitSettings=nil);
var LeftMesh,RightMesh:TMesh;
LeftSingleTreeNode,RightSingleTreeNode:TSingleTreeNode;
LeftDualTree,RightDualTree:TDualTree;
begin
case aCSGMode of
TCSGMode.SingleTree:begin
SetMode(TMode.Polygons);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Polygons);
LeftSingleTreeNode:=LeftMesh.ToSingleTreeNode(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Polygons);
RightSingleTreeNode:=RightMesh.ToSingleTreeNode(aSplitSettings);
try
LeftSingleTreeNode.Invert;
LeftSingleTreeNode.ClipTo(RightSingleTreeNode);
RightSingleTreeNode.ClipTo(LeftSingleTreeNode);
RightSingleTreeNode.Invert;
RightSingleTreeNode.ClipTo(LeftSingleTreeNode);
RightSingleTreeNode.Invert;
LeftSingleTreeNode.Merge(RightSingleTreeNode,aSplitSettings);
finally
FreeAndNil(RightSingleTreeNode);
end;
finally
FreeAndNil(RightMesh);
end;
LeftSingleTreeNode.Invert;
Assign(LeftSingleTreeNode);
finally
FreeAndNil(LeftSingleTreeNode);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
TCSGMode.DualTree:begin
SetMode(TMode.Polygons);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Polygons);
LeftDualTree:=LeftMesh.ToDualTree(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Polygons);
RightDualTree:=RightMesh.ToDualTree(aSplitSettings);
try
LeftDualTree.Invert;
LeftDualTree.ClipTo(RightDualTree,false);
{$undef UseReferenceBSPOperations}
{$ifdef UseReferenceBSPOperations}
RightDualTree.ClipTo(LeftDualTree,false);
RightDualTree.Invert;
RightDualTree.ClipTo(LeftDualTree,false);
RightDualTree.Invert;
{$else}
RightDualTree.ClipTo(LeftDualTree,true);
{$endif}
LeftDualTree.Merge(RightDualTree);
LeftDualTree.Invert;
finally
FreeAndNil(RightDualTree);
end;
finally
FreeAndNil(RightMesh);
end;
Assign(LeftDualTree);
finally
FreeAndNil(LeftDualTree);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
TCSGMode.Triangles:begin
SetMode(TMode.Triangles);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Triangles);
LeftSingleTreeNode:=LeftMesh.ToSingleTreeNode(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Triangles);
RightSingleTreeNode:=RightMesh.ToSingleTreeNode(aSplitSettings);
try
TriangleCSGOperation(RightSingleTreeNode,LeftSingleTreeNode,LeftMesh.fVertices,false,false,false);
TriangleCSGOperation(LeftSingleTreeNode,RightSingleTreeNode,RightMesh.fVertices,true,true,true);
finally
FreeAndNil(RightSingleTreeNode);
end;
finally
FreeAndNil(RightMesh);
end;
finally
FreeAndNil(LeftSingleTreeNode);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
else begin
Assert(false);
end;
end;
RemoveDuplicateAndUnusedVertices;
if (aLeftMesh.fMode=TMode.Triangles) and (aRightMesh.fMode=TMode.Triangles) then begin
SetMode(TMode.Triangles);
end else if (aLeftMesh.fMode=TMode.Polygons) and (aRightMesh.fMode=TMode.Polygons) then begin
SetMode(TMode.Polygons);
end;
end;
procedure TpvCSGBSP.TMesh.Subtraction(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var AABBLeft,AABBRight,AABBIntersection:TAABB;
AABBIntersectionMesh,
OuterLeftMesh,InnerLeftMesh,
OuterRightMesh,InnerRightMesh:TMesh;
begin
AABBLeft:=aLeftMesh.GetAxisAlignedBoundingBox;
AABBRight:=aRightMesh.GetAxisAlignedBoundingBox;
if AABBLeft.Intersects(AABBRight) then begin
case aCSGOptimization of
TMesh.TCSGOptimization.CSG:begin
AABBIntersection:=AABBLeft.Intersection(AABBRight);
AABBIntersectionMesh:=TMesh.Create(AABBIntersection,TMesh.TMode.Polygons,CSGOptimizationBoundEpsilon);
try
OuterLeftMesh:=TMesh.CreateSubtraction(aLeftMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
InnerLeftMesh:=TMesh.CreateIntersection(aLeftMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
InnerRightMesh:=TMesh.CreateIntersection(aRightMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
DoSubtraction(InnerLeftMesh,InnerRightMesh,aCSGMode,aSplitSettings);
finally
FreeAndNil(InnerRightMesh);
end;
Union(OuterLeftMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
finally
FreeAndNil(InnerLeftMesh);
end;
finally
FreeAndNil(OuterLeftMesh);
end;
finally
FreeAndNil(AABBIntersectionMesh);
end;
end;
TMesh.TCSGOptimization.Polygons:begin
AABBIntersection:=AABBLeft.Intersection(AABBRight);
OuterLeftMesh:=TMesh.Create;
try
InnerLeftMesh:=TMesh.Create;
try
aLeftMesh.FastSplitPolygonsIntoOuterAndInnerMeshsByInsideRangeAABB(OuterLeftMesh,InnerLeftMesh,AABBIntersection);
OuterRightMesh:=TMesh.Create;
try
InnerRightMesh:=TMesh.Create;
try
aRightMesh.FastSplitPolygonsIntoOuterAndInnerMeshsByInsideRangeAABB(OuterRightMesh,InnerRightMesh,AABBIntersection);
DoSubtraction(InnerLeftMesh,InnerRightMesh,aCSGMode,aSplitSettings);
finally
FreeAndNil(InnerRightMesh);
end;
finally
FreeAndNil(OuterRightMesh);
end;
finally
FreeAndNil(InnerLeftMesh);
end;
Append(OuterLeftMesh);
finally
FreeAndNil(OuterLeftMesh);
end;
end;
else begin
DoSubtraction(aLeftMesh,aRightMesh,aCSGMode,aSplitSettings);
end;
end;
end else begin
Assign(aLeftMesh);
RemoveDuplicateAndUnusedVertices;
end;
end;
procedure TpvCSGBSP.TMesh.Subtraction(const aWithMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var TemporaryMesh:TMesh;
begin
TemporaryMesh:=TMesh.Create(fMode);
try
TemporaryMesh.Subtraction(self,aWithMesh,aCSGMode,aCSGOptimization,aSplitSettings);
Assign(TemporaryMesh);
finally
FreeAndNil(TemporaryMesh);
end;
end;
procedure TpvCSGBSP.TMesh.SubtractionOf(const aMeshs:array of TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var Index:TpvSizeInt;
begin
if length(aMeshs)>0 then begin
Assign(aMeshs[0]);
for Index:=1 to length(aMeshs)-1 do begin
Subtraction(aMeshs[Index],aCSGMode,aCSGOptimization,aSplitSettings);
end;
end else begin
Clear;
end;
end;
procedure TpvCSGBSP.TMesh.DoIntersection(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode;
const aSplitSettings:PSplitSettings=nil);
var LeftMesh,RightMesh:TMesh;
LeftSingleTreeNode,RightSingleTreeNode:TSingleTreeNode;
LeftDualTree,RightDualTree:TDualTree;
begin
case aCSGMode of
TCSGMode.SingleTree:begin
SetMode(TMode.Polygons);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Polygons);
LeftSingleTreeNode:=LeftMesh.ToSingleTreeNode(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Polygons);
RightSingleTreeNode:=RightMesh.ToSingleTreeNode(aSplitSettings);
try
LeftSingleTreeNode.Invert;
RightSingleTreeNode.ClipTo(LeftSingleTreeNode);
RightSingleTreeNode.Invert;
LeftSingleTreeNode.ClipTo(RightSingleTreeNode);
RightSingleTreeNode.ClipTo(LeftSingleTreeNode);
LeftSingleTreeNode.Merge(RightSingleTreeNode,aSplitSettings);
finally
FreeAndNil(RightSingleTreeNode);
end;
finally
FreeAndNil(RightMesh);
end;
LeftSingleTreeNode.Invert;
Assign(LeftSingleTreeNode);
finally
FreeAndNil(LeftSingleTreeNode);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
TCSGMode.DualTree:begin
SetMode(TMode.Polygons);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Polygons);
LeftDualTree:=LeftMesh.ToDualTree(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Polygons);
RightDualTree:=RightMesh.ToDualTree(aSplitSettings);
try
LeftDualTree.Invert;
RightDualTree.ClipTo(LeftDualTree,false);
RightDualTree.Invert;
LeftDualTree.ClipTo(RightDualTree,false);
RightDualTree.ClipTo(LeftDualTree,false);
LeftDualTree.Merge(RightDualTree);
LeftDualTree.Invert;
finally
FreeAndNil(RightDualTree);
end;
finally
FreeAndNil(RightMesh);
end;
Assign(LeftDualTree);
finally
FreeAndNil(LeftDualTree);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
TCSGMode.Triangles:begin
SetMode(TMode.Triangles);
LeftMesh:=TMesh.Create(aLeftMesh);
try
LeftMesh.SetMode(TMode.Triangles);
LeftSingleTreeNode:=LeftMesh.ToSingleTreeNode(aSplitSettings);
try
RightMesh:=TMesh.Create(aRightMesh);
try
RightMesh.SetMode(TMode.Triangles);
RightSingleTreeNode:=RightMesh.ToSingleTreeNode(aSplitSettings);
try
TriangleCSGOperation(RightSingleTreeNode,LeftSingleTreeNode,LeftMesh.fVertices,true,false,false);
TriangleCSGOperation(LeftSingleTreeNode,RightSingleTreeNode,RightMesh.fVertices,true,true,false);
finally
FreeAndNil(RightSingleTreeNode);
end;
finally
FreeAndNil(RightMesh);
end;
finally
FreeAndNil(LeftSingleTreeNode);
end;
finally
FreeAndNil(LeftMesh);
end;
end;
else begin
Assert(false);
end;
end;
RemoveDuplicateAndUnusedVertices;
if (aLeftMesh.fMode=TMode.Triangles) and (aRightMesh.fMode=TMode.Triangles) then begin
SetMode(TMode.Triangles);
end else if (aLeftMesh.fMode=TMode.Polygons) and (aRightMesh.fMode=TMode.Polygons) then begin
SetMode(TMode.Polygons);
end;
end;
procedure TpvCSGBSP.TMesh.Intersection(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var AABBLeft,AABBRight,AABBIntersection:TAABB;
AABBIntersectionMesh,
OuterLeftMesh,InnerLeftMesh,
OuterRightMesh,InnerRightMesh:TMesh;
begin
AABBLeft:=aLeftMesh.GetAxisAlignedBoundingBox;
AABBRight:=aRightMesh.GetAxisAlignedBoundingBox;
if AABBLeft.Intersects(AABBRight) then begin
case aCSGOptimization of
TMesh.TCSGOptimization.CSG:begin
AABBIntersection:=AABBLeft.Intersection(AABBRight);
AABBIntersectionMesh:=TMesh.Create(AABBIntersection,TMesh.TMode.Polygons,CSGOptimizationBoundEpsilon);
try
InnerLeftMesh:=TMesh.CreateIntersection(aLeftMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
InnerRightMesh:=TMesh.CreateIntersection(aRightMesh,AABBIntersectionMesh,aCSGMode,TMesh.TCSGOptimization.None,aSplitSettings);
try
DoIntersection(InnerLeftMesh,InnerRightMesh,aCSGMode,aSplitSettings);
finally
FreeAndNil(InnerRightMesh);
end;
finally
FreeAndNil(InnerLeftMesh);
end;
finally
FreeAndNil(AABBIntersectionMesh);
end;
end;
TMesh.TCSGOptimization.Polygons:begin
AABBIntersection:=AABBLeft.Intersection(AABBRight);
OuterLeftMesh:=TMesh.Create;
try
InnerLeftMesh:=TMesh.Create;
try
aLeftMesh.FastSplitPolygonsIntoOuterAndInnerMeshsByInsideRangeAABB(OuterLeftMesh,InnerLeftMesh,AABBIntersection);
OuterRightMesh:=TMesh.Create;
try
InnerRightMesh:=TMesh.Create;
try
aRightMesh.FastSplitPolygonsIntoOuterAndInnerMeshsByInsideRangeAABB(OuterRightMesh,InnerRightMesh,AABBIntersection);
DoIntersection(InnerLeftMesh,InnerRightMesh,aCSGMode,aSplitSettings);
finally
FreeAndNil(InnerRightMesh);
end;
finally
FreeAndNil(OuterRightMesh);
end;
finally
FreeAndNil(InnerLeftMesh);
end;
finally
FreeAndNil(OuterLeftMesh);
end;
end;
else begin
DoIntersection(aLeftMesh,aRightMesh,aCSGMode,aSplitSettings);
end;
end;
end else begin
Clear;
end;
end;
procedure TpvCSGBSP.TMesh.Intersection(const aWithMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var TemporaryMesh:TMesh;
begin
TemporaryMesh:=TMesh.Create(fMode);
try
TemporaryMesh.Intersection(self,aWithMesh,aCSGMode,aCSGOptimization,aSplitSettings);
Assign(TemporaryMesh);
finally
FreeAndNil(TemporaryMesh);
end;
end;
procedure TpvCSGBSP.TMesh.IntersectionOf(const aMeshs:array of TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var Index:TpvSizeInt;
begin
if length(aMeshs)>0 then begin
Assign(aMeshs[0]);
for Index:=1 to length(aMeshs)-1 do begin
Intersection(aMeshs[Index],aCSGMode,aCSGOptimization,aSplitSettings);
end;
end else begin
Clear;
end;
end;
procedure TpvCSGBSP.TMesh.SymmetricDifference(const aLeftMesh:TMesh;
const aRightMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var a,b:TMesh;
begin
// Possible symmertic difference (boolean XOR) implementations:
// Intersection(Union(A,B),Inverse(Intersection(A,B)))
// Intersection(Union(A,B),Union(Inverse(A),Inverse(B)))
// Union(Subtraction(A,B),Subtraction(B,A)) <= used here, because it seems the most robust mnethod in this BSP-based triangle-based CSG implementation!
// Subtraction(Union(A,B),Intersection(A,B))
a:=TMesh.CreateSubtraction(aLeftMesh,aRightMesh,aCSGMode,aCSGOptimization,aSplitSettings);
try
b:=TMesh.CreateSubtraction(aRightMesh,aLeftMesh,aCSGMode,aCSGOptimization,aSplitSettings);
try
Union(a,b,aCSGMode,aCSGOptimization,aSplitSettings);
finally
FreeAndNil(b);
end;
finally
FreeAndNil(a);
end;
end;
procedure TpvCSGBSP.TMesh.SymmetricDifference(const aWithMesh:TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var TemporaryMesh:TMesh;
begin
TemporaryMesh:=TMesh.Create(fMode);
try
TemporaryMesh.SymmetricDifference(self,aWithMesh,aCSGMode,aCSGOptimization,aSplitSettings);
Assign(TemporaryMesh);
finally
FreeAndNil(TemporaryMesh);
end;
end;
procedure TpvCSGBSP.TMesh.SymmetricDifferenceOf(const aMeshs:array of TMesh;
const aCSGMode:TCSGMode=TCSGMode.DualTree;
const aCSGOptimization:TCSGOptimization=TCSGOptimization.None;
const aSplitSettings:PSplitSettings=nil);
var Index:TpvSizeInt;
begin
if length(aMeshs)>0 then begin
Assign(aMeshs[0]);
for Index:=1 to length(aMeshs)-1 do begin
SymmetricDifference(aMeshs[Index],aCSGMode,aCSGOptimization,aSplitSettings);
end;
end else begin
Clear;
end;
end;
procedure TpvCSGBSP.TMesh.Canonicalize;
var Index,Count,CountPolygonVertices:TpvSizeInt;
NewIndices,WorkIndices:TIndexList;
begin
NewIndices.Initialize;
try
WorkIndices.Initialize;
try
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
case fMode of
TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMode.Polygons:}begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
end;
end;
if CountPolygonVertices>2 then begin
if (Index+(CountPolygonVertices-1))<Count then begin
WorkIndices.Count:=0;
WorkIndices.AddRangeFrom(fIndices,Index,CountPolygonVertices);
RemoveNearDuplicateIndices(WorkIndices);
if WorkIndices.Count>2 then begin
case fMode of
TMode.Triangles:begin
end;
else {TMode.Polygons:}begin
NewIndices.Add(WorkIndices.Count);
end;
end;
NewIndices.Add(WorkIndices);
end;
end;
end;
inc(Index,CountPolygonVertices);
end;
finally
WorkIndices.Finalize;
end;
SetIndices(NewIndices);
finally
NewIndices.Finalize;
end;
RemoveDuplicateAndUnusedVertices;
end;
procedure TpvCSGBSP.TMesh.CalculateNormals(const aCreasedNormalAngleThreshold:TFloat=90.0;
const aSoftNormals:boolean=true;
const aAreaWeighting:boolean=true;
const aAngleWeighting:boolean=true;
const aCreasedNormalAngleWeighting:boolean=true;
const aCheckForCreasedNormals:boolean=true);
const DegreesToRadians=pi/180.0;
type TNormalItem=record
PolygonNormal:TVector3;
VertexNormal:TVector3;
end;
PNormalItem=^TNormalItem;
TNormalList=TDynamicArray<TNormalItem>;
PNormalList=^TNormalList;
TPositionUniqueVerticesHashMap=TVector3HashMap<TIndex>;
TPositionUniqueVerticesBuckets=TDynamicArray<TIndexList>;
TPositionUniqueVerticesReverseIndex=array of TpvSizeInt;
TPositionUniqueVerticesPositions=TDynamicArray<TVector3>;
var Index,Count,CountPolygonVertices,OtherIndex,NormalItemIndex:TpvSizeInt;
Position0,Position1,Position2:PVector3;
Index0,Index1,Index2:TIndex;
Vertex:TVertex;
PointerToVertex:PVertex;
CurrentNormal,PolygonNormal:TVector3;
NormalLists:array of TNormalList;
NormalList:PNormalList;
NormalListItem:PNormalItem;
d01,d12,d20,s,r,Angle,AngleThreshold:TFloat;
PositionUniqueVerticesHashMap:TPositionUniqueVerticesHashMap;
PositionUniqueVerticesBuckets:TPositionUniqueVerticesBuckets;
PositionUniqueVerticesReverseIndex:TPositionUniqueVerticesReverseIndex;
PositionUniqueVerticesPositions:TPositionUniqueVerticesPositions;
begin
// Clear all normals on the input vertices
for Index:=0 to fVertices.Count-1 do begin
fVertices.Items[Index].Normal:=TVector3.Create(0.0,0.0,0.0);
end;
// Remove duplicate input vertices after all normals were cleared
RemoveDuplicateAndUnusedVertices;
if aSoftNormals then begin
AngleThreshold:=Min(Max(cos(aCreasedNormalAngleThreshold*DegreesToRadians),-OneMinusEpsilon),OneMinusEpsilon);
if IsZero(AngleThreshold) or IsNaN(AngleThreshold) then begin
AngleThreshold:=0.0;
end;
PositionUniqueVerticesHashMap:=TPositionUniqueVerticesHashMap.Create(-1);
try
PositionUniqueVerticesBuckets.Initialize;
try
SetLength(PositionUniqueVerticesReverseIndex,fVertices.Count);
try
PositionUniqueVerticesPositions.Initialize;
try
// Gather all vertices with near-equal positions together
for Index:=0 to fVertices.Count-1 do begin
PointerToVertex:=@fVertices.Items[Index];
Index0:=PositionUniqueVerticesHashMap[PointerToVertex^.Position];
if Index0<0 then begin
Index0:=PositionUniqueVerticesBuckets.AddNew;
PositionUniqueVerticesBuckets.Items[Index0].Initialize;
PositionUniqueVerticesHashMap[PointerToVertex^.Position]:=Index0;
PositionUniqueVerticesPositions.Add(PointerToVertex^.Position);
end;
PositionUniqueVerticesBuckets.Items[Index0].Add(Index);
PositionUniqueVerticesReverseIndex[Index]:=Index0;
end;
Assert(PositionUniqueVerticesBuckets.Count=PositionUniqueVerticesPositions.Count);
NormalLists:=nil;
try
// Initialize
SetLength(NormalLists,PositionUniqueVerticesPositions.Count);
for Index:=0 to length(NormalLists)-1 do begin
NormalLists[Index].Initialize;
NormalLists[Index].Clear;
end;
// Pass 1 - Gathering
begin
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
case fMode of
TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMode.Polygons:}begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
end;
end;
if (CountPolygonVertices>2) and ((Index+(CountPolygonVertices-1))<Count) then begin
// Calculate and find valid whole-polygon normal (where degenerated convex
// tessellated triangles will be ignored here)
PolygonNormal:=TVector3.Create(0.0,0.0,0.0);
Index0:=fIndices.Items[Index+0];
Index1:=fIndices.Items[Index+1];
Position0:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index0]];
Position1:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index1]];
for OtherIndex:=2 to CountPolygonVertices-1 do begin
Index2:=fIndices.Items[Index+OtherIndex];
Position2:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index2]];
PolygonNormal:=(Position1^-Position0^).Cross(Position2^-Position0^);
if PolygonNormal.SquaredLength>SquaredEpsilon then begin
PolygonNormal:=PolygonNormal.Normalize;
break;
end else begin
Index1:=Index2;
Position1:=Position2;
end;
end;
// Gathering smooth normal information data
Index0:=fIndices.Items[Index+0];
Index1:=fIndices.Items[Index+1];
Position0:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index0]];
Position1:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index1]];
for OtherIndex:=2 to CountPolygonVertices-1 do begin
Index2:=fIndices.Items[Index+OtherIndex];
Position2:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index2]];
CurrentNormal:=(Position1^-Position0^).Cross(Position2^-Position0^);
if not aAreaWeighting then begin
CurrentNormal:=CurrentNormal.Normalize;
end;
d01:=(Position0^-Position1^).Length;
d12:=(Position1^-Position2^).Length;
d20:=(Position2^-Position0^).Length;
if aAngleWeighting and (d01>=Epsilon) and (d12>=Epsilon) and (d20>=Epsilon) then begin
s:=(d01+d12+d20)*0.5;
r:=sqrt(((s-d01)*(s-d12)*(s-d20))/s);
begin
NormalList:=@NormalLists[PositionUniqueVerticesReverseIndex[Index0]];
NormalItemIndex:=NormalList^.AddNew;
NormalListItem:=@NormalList^.Items[NormalItemIndex];
NormalListItem^.PolygonNormal:=PolygonNormal;
NormalListItem^.VertexNormal:=CurrentNormal*ArcTan2(r,s-d12);
end;
begin
NormalList:=@NormalLists[PositionUniqueVerticesReverseIndex[Index1]];
NormalItemIndex:=NormalList^.AddNew;
NormalListItem:=@NormalList^.Items[NormalItemIndex];
NormalListItem^.PolygonNormal:=PolygonNormal;
NormalListItem^.VertexNormal:=CurrentNormal*ArcTan2(r,s-d20);
end;
begin
NormalList:=@NormalLists[PositionUniqueVerticesReverseIndex[Index2]];
NormalItemIndex:=NormalList^.AddNew;
NormalListItem:=@NormalList^.Items[NormalItemIndex];
NormalListItem^.PolygonNormal:=PolygonNormal;
NormalListItem^.VertexNormal:=CurrentNormal*ArcTan2(r,s-d01);
end;
end else begin
begin
NormalList:=@NormalLists[PositionUniqueVerticesReverseIndex[Index0]];
NormalItemIndex:=NormalList^.AddNew;
NormalListItem:=@NormalList^.Items[NormalItemIndex];
NormalListItem^.PolygonNormal:=PolygonNormal;
NormalListItem^.VertexNormal:=CurrentNormal;
end;
begin
NormalList:=@NormalLists[PositionUniqueVerticesReverseIndex[Index1]];
NormalItemIndex:=NormalList^.AddNew;
NormalListItem:=@NormalList^.Items[NormalItemIndex];
NormalListItem^.PolygonNormal:=PolygonNormal;
NormalListItem^.VertexNormal:=CurrentNormal;
end;
begin
NormalList:=@NormalLists[PositionUniqueVerticesReverseIndex[Index2]];
NormalItemIndex:=NormalList^.AddNew;
NormalListItem:=@NormalList^.Items[NormalItemIndex];
NormalListItem^.PolygonNormal:=PolygonNormal;
NormalListItem^.VertexNormal:=CurrentNormal;
end;
end;
Index1:=Index2;
Position1:=Position2;
end;
end;
inc(Index,CountPolygonVertices);
end;
end;
// Pass 2 - Applying
begin
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
case fMode of
TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMode.Polygons:}begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
end;
end;
if (CountPolygonVertices>2) and ((Index+(CountPolygonVertices-1))<Count) then begin
// Calculate and find valid whole-polygon normal (where degenerated convex
// tessellated triangles will be ignored here)
PolygonNormal:=TVector3.Create(0.0,0.0,0.0);
Index0:=fIndices.Items[Index+0];
Index1:=fIndices.Items[Index+1];
Position0:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index0]];
Position1:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index1]];
for OtherIndex:=2 to CountPolygonVertices-1 do begin
Index2:=fIndices.Items[Index+OtherIndex];
Position2:=@PositionUniqueVerticesPositions.Items[PositionUniqueVerticesReverseIndex[Index2]];
PolygonNormal:=(Position1^-Position0^).Cross(Position2^-Position0^);
if PolygonNormal.SquaredLength>SquaredEpsilon then begin
PolygonNormal:=PolygonNormal.Normalize;
break;
end else begin
Index1:=Index2;
Position1:=Position2;
end;
end;
// Apply new ormals to all then-cloned vertices (they will be cloned for to be
// unique per polygon, the then old unused vertices will be removed later anyway)
for OtherIndex:=0 to CountPolygonVertices-1 do begin
Index0:=fIndices.Items[Index+OtherIndex];
CurrentNormal:=TVector3.Create(0.0,0.0,0.0);
NormalList:=@NormalLists[PositionUniqueVerticesReverseIndex[Index0]];
for NormalItemIndex:=0 to NormalList^.Count-1 do begin
NormalListItem:=@NormalList^.Items[NormalItemIndex];
Angle:=PolygonNormal.Dot(NormalListItem^.PolygonNormal);
if (not aCheckForCreasedNormals) or
(Angle>=AngleThreshold) then begin
if aCreasedNormalAngleWeighting then begin
if Angle<0.0 then begin
Angle:=0.0;
end;
end else begin
Angle:=1.0;
end;
CurrentNormal:=CurrentNormal+(NormalListItem^.VertexNormal*Angle);
end;
end;
Vertex:=fVertices.Items[Index0];
Vertex.Normal:=CurrentNormal.Normalize;
fIndices.Items[Index+OtherIndex]:=fVertices.Add(Vertex);
end;
end;
inc(Index,CountPolygonVertices);
end;
end;
// Clean up
for Index:=0 to length(NormalLists)-1 do begin
NormalLists[Index].Finalize;
end;
finally
SetLength(NormalLists,0);
end;
finally
PositionUniqueVerticesPositions.Finalize;
end;
finally
PositionUniqueVerticesReverseIndex:=nil;
end;
finally
PositionUniqueVerticesBuckets.Finalize;
end;
finally
FreeAndNil(PositionUniqueVerticesHashMap);
end;
end else begin
// Go through all indices polygon-wise
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
case fMode of
TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMode.Polygons:}begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
end;
end;
if (CountPolygonVertices>2) and ((Index+(CountPolygonVertices-1))<Count) then begin
// Calculate and find valid whole-polygon normal (where degenerated convex
// tessellated triangles will be ignored here)
PolygonNormal:=TVector3.Create(0.0,0.0,0.0);
Index0:=fIndices.Items[Index+0];
Index1:=fIndices.Items[Index+1];
Position0:=@fVertices.Items[Index0].Position;
Position1:=@fVertices.Items[Index1].Position;
for OtherIndex:=2 to CountPolygonVertices-1 do begin
Index2:=fIndices.Items[Index+OtherIndex];
Position2:=@fVertices.Items[Index2].Position;
PolygonNormal:=(Position1^-Position0^).Cross(Position2^-Position0^);
if PolygonNormal.SquaredLength>SquaredEpsilon then begin
PolygonNormal:=PolygonNormal.Normalize;
break;
end else begin
Index1:=Index2;
Position1:=Position2;
end;
end;
// Apply this normal to all then-cloned vertices (they will be cloned for to be
// unique per polygon, the then old unused vertices will be removed later anyway)
while (CountPolygonVertices>0) and (Index<Count) do begin
Vertex:=fVertices.Items[fIndices.Items[Index]];
Vertex.Normal:=PolygonNormal;
fIndices.Items[Index]:=fVertices.Add(Vertex);
inc(Index);
dec(CountPolygonVertices);
end;
end;
inc(Index,CountPolygonVertices);
end;
end;
// Remove old unused input vertices
RemoveDuplicateAndUnusedVertices;
end;
procedure TpvCSGBSP.TMesh.RemoveDuplicateAndUnusedVertices;
const HashBits=16;
HashSize=1 shl HashBits;
HashMask=HashSize-1;
type THashTableItem=record
Next:TpvSizeInt;
Hash:TpvUInt32;
VertexIndex:TIndex;
end;
PHashTableItem=^THashTableItem;
THashTableItems=array of THashTableItem;
THashTable=array of TpvSizeInt;
var Index,Count,CountPolygonVertices,
HashIndex,CountHashTableItems:TpvSizeInt;
Vertex,OtherVertex:PVertex;
VertexIndex:TIndex;
NewVertices:TVertexList;
NewIndices:TIndexList;
HashTable:THashTable;
HashTableItems:THashTableItems;
Hash:TpvUInt32;
HashTableItem:PHashTableItem;
begin
NewVertices.Initialize;
try
NewIndices.Initialize;
try
HashTable:=nil;
try
SetLength(HashTable,HashSize);
for Index:=0 to HashSize-1 do begin
HashTable[Index]:=-1;
end;
HashTableItems:=nil;
CountHashTableItems:=0;
try
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
case fMode of
TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMode.Polygons:}begin
CountPolygonVertices:=fIndices.Items[Index];
NewIndices.Add(CountPolygonVertices);
inc(Index);
end;
end;
while (CountPolygonVertices>0) and (Index<Count) do begin
dec(CountPolygonVertices);
Vertex:=@fVertices.Items[fIndices.Items[Index]];
VertexIndex:=-1;
Hash:=(round(Vertex.Position.x*4096)*73856093) xor
(round(Vertex.Position.y*4096)*19349653) xor
(round(Vertex.Position.z*4096)*83492791);
HashIndex:=HashTable[Hash and HashMask];
while HashIndex>=0 do begin
HashTableItem:=@HashTableItems[HashIndex];
if HashTableItem^.Hash=Hash then begin
OtherVertex:=@NewVertices.Items[HashTableItem^.VertexIndex];
if Vertex^=OtherVertex^ then begin
VertexIndex:=HashTableItem^.VertexIndex;
break;
end;
end;
HashIndex:=HashTableItem^.Next;
end;
if VertexIndex<0 then begin
VertexIndex:=NewVertices.Add(Vertex^);
HashIndex:=CountHashTableItems;
inc(CountHashTableItems);
if CountHashTableItems>length(HashTableItems) then begin
SetLength(HashTableItems,CountHashTableItems*2);
end;
HashTableItem:=@HashTableItems[HashIndex];
HashTableItem^.Next:=HashTable[Hash and HashMask];
HashTable[Hash and HashMask]:=HashIndex;
HashTableItem^.Hash:=Hash;
HashTableItem^.VertexIndex:=VertexIndex;
end;
NewIndices.Add(VertexIndex);
inc(Index);
end;
end;
SetVertices(NewVertices);
SetIndices(NewIndices);
finally
HashTableItems:=nil;
end;
finally
HashTable:=nil;
end;
finally
NewIndices.Finalize;
end;
finally
NewVertices.Finalize;
end;
end;
procedure TpvCSGBSP.TMesh.FixTJunctions(const aConsistentInputVertices:boolean=false);
function Wrap(const aIndex,aCount:TpvSizeInt):TpvSizeInt;
begin
result:=aIndex;
if aCount>0 then begin
while result<0 do begin
inc(result,aCount);
end;
while result>=aCount do begin
dec(result,aCount);
end;
end;
end;
procedure FixTJunctionsWithConsistentInputVertices;
type TPolygon=record
Indices:TIndexList;
end;
PPolygon=^TPolygon;
TPolygons=TDynamicArray<TPolygon>;
TEdgeVertexIndices=array[0..1] of TIndex;
PEdgeVertexIndices=^TEdgeVertexIndices;
TEdgeHashMap=THashMap<TEdgeVertexIndices,TpvSizeInt>;
TEdge=record
VertexIndices:TEdgeVertexIndices;
PolygonIndex:TpvSizeInT;
end;
PEdge=^TEdge;
TEdges=TDynamicArray<TEdge>;
PEdges=^TEdges;
TEdgesList=TDynamicArray<TEdges>;
TEdgeIndexList=TDynamicArray<TpvSizeInt>;
PEdgeIndexList=^TEdgeIndexList;
TEdgeVertexIndicesList=TDynamicArray<TEdgeVertexIndices>;
TVertexIndexToEdgeStartEndList=TDynamicArray<TEdgeVertexIndicesList>;
TVertexIndexToEdgeStartEndHashMap=THashMap<TIndex,TpvSizeInt>;
TEdgesToCheckHashMap=THashMap<TEdgeVertexIndices,boolean>;
var Index,Count,CountPolygonVertices,
PolygonIndex:TpvSizeInt;
Polygons:TPolygons;
Polygon:PPolygon;
NewIndices:TIndexList;
EdgeHashMap:TEdgeHashMap;
EdgesList:TEdgesList;
VertexIndexToEdgeStartList:TVertexIndexToEdgeStartEndList;
VertexIndexToEdgeEndList:TVertexIndexToEdgeStartEndList;
VertexIndexToEdgeStartHashMap:TVertexIndexToEdgeStartEndHashMap;
VertexIndexToEdgeEndHashMap:TVertexIndexToEdgeStartEndHashMap;
EdgeMapIsEmpty:boolean;
EdgesToCheck:TEdgesToCheckHashMap;
OldMode:TMode;
procedure ScanEdges;
var PolygonIndex,PolygonIndicesIndex,EdgesIndex:TpvSizeInt;
VertexIndex,NextVertexIndex:TIndex;
Polygon:PPolygon;
EdgeVertexIndices,
ReversedEdgeVertexIndices:TEdgeVertexIndices;
Edges:PEdges;
Edge:TEdge;
begin
for PolygonIndex:=0 to Polygons.Count-1 do begin
Polygon:=@Polygons.Items[PolygonIndex];
if Polygon^.Indices.Count>2 then begin
for PolygonIndicesIndex:=0 to Polygon^.Indices.Count-1 do begin
VertexIndex:=Polygon^.Indices.Items[PolygonIndicesIndex];
NextVertexIndex:=Polygon^.Indices.Items[Wrap(PolygonIndicesIndex+1,Polygon^.Indices.Count)];
EdgeVertexIndices[0]:=VertexIndex;
EdgeVertexIndices[1]:=NextVertexIndex;
ReversedEdgeVertexIndices[1]:=VertexIndex;
ReversedEdgeVertexIndices[0]:=NextVertexIndex;
if EdgeHashMap.TryGet(ReversedEdgeVertexIndices,EdgesIndex) then begin
Edges:=@EdgesList.Items[EdgesIndex];
if Edges^.Count>0 then begin
Edges^.Delete(Edges^.Count-1);
if Edges^.Count=0 then begin
EdgeHashMap.Delete(ReversedEdgeVertexIndices);
end;
end;
end else begin
if not EdgeHashMap.TryGet(EdgeVertexIndices,EdgesIndex) then begin
EdgesIndex:=EdgesList.AddNew;
Edges:=@EdgesList.Items[EdgesIndex];
Edges^.Initialize;
EdgeHashMap.Add(EdgeVertexIndices,EdgesIndex);
end;
Edges:=@EdgesList.Items[EdgesIndex];
Edge.VertexIndices:=EdgeVertexIndices;
Edge.PolygonIndex:=PolygonIndex;
Edges^.Add(Edge);
end;
end;
end;
end;
end;
procedure ScanVertices;
var EdgeHashMapKeyIndex,EdgesIndex,
VertexIndexToEdgeStartEndIndex:TpvSizeInt;
EdgeVertexIndices:PEdgeVertexIndices;
Entity:TEdgeHashMap.PHashMapEntity;
Edges:PEdges;
Edge:PEdge;
begin
EdgeMapIsEmpty:=true;
for EdgeHashMapKeyIndex:=0 to EdgeHashMap.fSize-1 do begin
if EdgeHashMap.fEntityToCellIndex[EdgeHashMapKeyIndex]>=0 then begin
EdgeMapIsEmpty:=false;
Entity:=@EdgeHashMap.fEntities[EdgeHashMapKeyIndex];
EdgesToCheck.Add(Entity^.Key,true);
Edges:=@EdgesList.Items[Entity^.Value];
for EdgesIndex:=0 to Edges^.Count-1 do begin
Edge:=@Edges^.Items[EdgesIndex];
begin
if not VertexIndexToEdgeStartHashMap.TryGet(Edge^.VertexIndices[0],VertexIndexToEdgeStartEndIndex) then begin
VertexIndexToEdgeStartEndIndex:=VertexIndexToEdgeStartList.AddNew;
VertexIndexToEdgeStartHashMap.Add(Edge^.VertexIndices[0],VertexIndexToEdgeStartEndIndex);
VertexIndexToEdgeStartList.Items[VertexIndexToEdgeStartEndIndex].Initialize;
end;
VertexIndexToEdgeStartList.Items[VertexIndexToEdgeStartEndIndex].Add(Entity^.Key);
end;
begin
if not VertexIndexToEdgeEndHashMap.TryGet(Edge^.VertexIndices[1],VertexIndexToEdgeStartEndIndex) then begin
VertexIndexToEdgeStartEndIndex:=VertexIndexToEdgeEndList.AddNew;
VertexIndexToEdgeEndHashMap.Add(Edge^.VertexIndices[1],VertexIndexToEdgeStartEndIndex);
VertexIndexToEdgeEndList.Items[VertexIndexToEdgeStartEndIndex].Initialize;
end;
VertexIndexToEdgeEndList.Items[VertexIndexToEdgeStartEndIndex].Add(Entity^.Key);
end;
end;
end;
end;
end;
procedure Process;
var EdgeHashMapKeyIndex,EdgesIndex,EdgeIndex,
VertexIndexToEdgeStartEndIndex,
EdgesToCheckIndex,
DirectionIndex,
MatchingEdgesListIndex,
PolygonIndicesIndex,
InsertionPolygonIndicesIndex:TpvSizeInt;
Entity:TEdgeHashMap.PHashMapEntity;
Edges:PEdges;
Edge,MatchingEdge:TEdge;
Done,DoneWithEdge:boolean;
EdgeVertexIndices,
NewEdgeVertexIndices0,
NewEdgeVertexIndices1:TEdgeVertexIndices;
StartVertexIndex,EndVertexIndex,
MatchingEdgeStartVertexIndex,
MatchingEdgeEndVertexIndex,
OtherIndex:TIndex;
MatchingEdgesList:TEdgeVertexIndicesList;
MatchingEdgeVertexIndices:TEdgeVertexIndices;
StartPosition,EndPosition,CheckPosition,
Direction,ClosestPoint:TVector3;
Time:TFloat;
Polygon:PPolygon;
NewPolygon:TPolygon;
procedure DeleteEdge(const aVertexIndex0,aVertexIndex1:TIndex;const aPolygonIndex:TpvSizeInt);
var Index,FoundIndex,EdgesIndex,OtherIndex:TpvSizeInt;
EdgeVertexIndices:TEdgeVertexIndices;
Edges:PEdges;
Edge:PEdge;
begin
EdgeVertexIndices[0]:=aVertexIndex0;
EdgeVertexIndices[1]:=aVertexIndex1;
EdgesIndex:=EdgeHashMap[EdgeVertexIndices];
Assert(EdgesIndex>=0);
Edges:=@EdgesList.Items[EdgesIndex];
FoundIndex:=-1;
for Index:=0 to Edges^.Count-1 do begin
Edge:=@Edges^.Items[Index];
if (Edge^.VertexIndices[0]<>aVertexIndex0) or
(Edge^.VertexIndices[1]<>aVertexIndex1) or
((aPolygonIndex>=0) and
(Edge^.PolygonIndex<>aPolygonIndex)) then begin
continue;
end;
FoundIndex:=Index;
break;
end;
Assert(FoundIndex>=0);
Edges^.Delete(FoundIndex);
if Edges^.Count=0 then begin
EdgeHashMap.Delete(EdgeVertexIndices);
end;
Index:=VertexIndexToEdgeStartHashMap[aVertexIndex0];
Assert(Index>=0);
FoundIndex:=-1;
for OtherIndex:=0 to VertexIndexToEdgeStartList.Items[Index].Count-1 do begin
if (VertexIndexToEdgeStartList.Items[Index].Items[OtherIndex][0]=EdgeVertexIndices[0]) and
(VertexIndexToEdgeStartList.Items[Index].Items[OtherIndex][1]=EdgeVertexIndices[1]) then begin
FoundIndex:=OtherIndex;
break;
end;
end;
Assert(FoundIndex>=0);
VertexIndexToEdgeStartList.Items[Index].Delete(FoundIndex);
if VertexIndexToEdgeStartList.Items[Index].Count=0 then begin
VertexIndexToEdgeStartHashMap.Delete(aVertexIndex0);
end;
Index:=VertexIndexToEdgeEndHashMap[aVertexIndex1];
Assert(Index>=0);
FoundIndex:=-1;
for OtherIndex:=0 to VertexIndexToEdgeEndList.Items[Index].Count-1 do begin
if (VertexIndexToEdgeEndList.Items[Index].Items[OtherIndex][0]=EdgeVertexIndices[0]) and
(VertexIndexToEdgeEndList.Items[Index].Items[OtherIndex][1]=EdgeVertexIndices[1]) then begin
FoundIndex:=OtherIndex;
break;
end;
end;
Assert(FoundIndex>=0);
VertexIndexToEdgeEndList.Items[Index].Delete(FoundIndex);
if VertexIndexToEdgeEndList.Items[Index].Count=0 then begin
VertexIndexToEdgeEndHashMap.Delete(aVertexIndex1);
end;
end;
function AddEdge(const aVertexIndex0,aVertexIndex1:TIndex;const aPolygonIndex:TpvSizeInt):TEdgeVertexIndices;
var EdgesIndex,
VertexIndexToEdgeStartEndIndex:TpvSizeInt;
EdgeVertexIndices,
ReversedEdgeVertexIndices:TEdgeVertexIndices;
Edges:PEdges;
Edge:TEdge;
begin
result[0]:=-1;
Assert(aVertexIndex0<>aVertexIndex1);
EdgeVertexIndices[0]:=aVertexIndex0;
EdgeVertexIndices[1]:=aVertexIndex1;
if EdgeHashMap.ExistKey(ReversedEdgeVertexIndices) then begin
DeleteEdge(aVertexIndex1,aVertexIndex0,-1);
exit;
end;
if not EdgeHashMap.TryGet(EdgeVertexIndices,EdgesIndex) then begin
EdgesIndex:=EdgesList.AddNew;
Edges:=@EdgesList.Items[EdgesIndex];
Edges^.Initialize;
EdgeHashMap.Add(EdgeVertexIndices,EdgesIndex);
end;
Edges:=@EdgesList.Items[EdgesIndex];
Edge.VertexIndices:=EdgeVertexIndices;
Edge.PolygonIndex:=aPolygonIndex;
Edges^.Add(Edge);
begin
if not VertexIndexToEdgeStartHashMap.TryGet(Edge.VertexIndices[0],VertexIndexToEdgeStartEndIndex) then begin
VertexIndexToEdgeStartEndIndex:=VertexIndexToEdgeStartList.AddNew;
VertexIndexToEdgeStartHashMap.Add(Edge.VertexIndices[0],VertexIndexToEdgeStartEndIndex);
VertexIndexToEdgeStartList.Items[VertexIndexToEdgeStartEndIndex].Initialize;
end;
VertexIndexToEdgeStartList.Items[VertexIndexToEdgeStartEndIndex].Add(EdgeVertexIndices);
end;
begin
if not VertexIndexToEdgeEndHashMap.TryGet(Edge.VertexIndices[1],VertexIndexToEdgeStartEndIndex) then begin
VertexIndexToEdgeStartEndIndex:=VertexIndexToEdgeEndList.AddNew;
VertexIndexToEdgeEndHashMap.Add(Edge.VertexIndices[1],VertexIndexToEdgeStartEndIndex);
VertexIndexToEdgeEndList.Items[VertexIndexToEdgeStartEndIndex].Initialize;
end;
VertexIndexToEdgeEndList.Items[VertexIndexToEdgeStartEndIndex].Add(EdgeVertexIndices);
end;
end;
begin
repeat
EdgeMapIsEmpty:=true;
for EdgeHashMapKeyIndex:=0 to EdgeHashMap.fSize-1 do begin
if EdgeHashMap.fEntityToCellIndex[EdgeHashMapKeyIndex]>=0 then begin
EdgeMapIsEmpty:=false;
Entity:=@EdgeHashMap.fEntities[EdgeHashMapKeyIndex];
EdgesToCheck.Add(Entity^.Key,true);
end;
end;
if EdgeMapIsEmpty then begin
break;
end;
Done:=false;
repeat
EdgeVertexIndices[0]:=-1;
EdgeVertexIndices[1]:=-1;
for EdgesToCheckIndex:=0 to EdgesToCheck.fSize-1 do begin
if EdgesToCheck.fEntityToCellIndex[EdgesToCheckIndex]>=0 then begin
EdgeVertexIndices:=EdgesToCheck.fEntities[EdgesToCheckIndex].Key;
break;
end;
end;
if EdgeVertexIndices[0]<0 then begin
break;
end;
DoneWithEdge:=true;
if EdgeHashMap.TryGet(EdgeVertexIndices,EdgesIndex) then begin
Edges:=@EdgesList.Items[EdgesIndex];
Assert(Edges^.Count>0);
Edge:=Edges^.Items[0];
for DirectionIndex:=0 to 1 do begin
if DirectionIndex=0 then begin
StartVertexIndex:=Edge.VertexIndices[0];
EndVertexIndex:=Edge.VertexIndices[1];
end else begin
StartVertexIndex:=Edge.VertexIndices[1];
EndVertexIndex:=Edge.VertexIndices[0];
end;
MatchingEdgesList.Initialize;
if DirectionIndex=0 then begin
if VertexIndexToEdgeEndHashMap.TryGet(StartVertexIndex,VertexIndexToEdgeStartEndIndex) then begin
MatchingEdgesList.Assign(VertexIndexToEdgeEndList.Items[VertexIndexToEdgeStartEndIndex]);
end;
end else begin
if VertexIndexToEdgeStartHashMap.TryGet(StartVertexIndex,VertexIndexToEdgeStartEndIndex) then begin
MatchingEdgesList.Assign(VertexIndexToEdgeStartList.Items[VertexIndexToEdgeStartEndIndex]);
end;
end;
for MatchingEdgesListIndex:=0 to MatchingEdgesList.Count-1 do begin
MatchingEdgeVertexIndices:=MatchingEdgesList.Items[MatchingEdgesListIndex];
EdgesIndex:=EdgeHashMap[MatchingEdgeVertexIndices];
Assert(EdgesIndex>=0);
Edges:=@EdgesList.Items[EdgesIndex];
Assert(Edges^.Count>0);
MatchingEdge:=Edges^.Items[0];
if DirectionIndex=0 then begin
MatchingEdgeStartVertexIndex:=MatchingEdge.VertexIndices[0];
MatchingEdgeEndVertexIndex:=MatchingEdge.VertexIndices[1];
end else begin
MatchingEdgeStartVertexIndex:=MatchingEdge.VertexIndices[1];
MatchingEdgeEndVertexIndex:=MatchingEdge.VertexIndices[0];
end;
Assert(MatchingEdgeEndVertexIndex=StartVertexIndex);
if MatchingEdgeStartVertexIndex=EndVertexIndex then begin
DeleteEdge(StartVertexIndex,EndVertexIndex,-1);
DeleteEdge(EndVertexIndex,StartVertexIndex,-1);
DoneWithEdge:=false;
Done:=true;
break;
end else begin
StartPosition:=fVertices.Items[StartVertexIndex].Position;
EndPosition:=fVertices.Items[EndVertexIndex].Position;
CheckPosition:=fVertices.Items[MatchingEdgeStartVertexIndex].Position;
Direction:=CheckPosition-StartPosition;
Time:=(EndPosition-StartPosition).Dot(Direction)/Direction.Dot(Direction);
if (Time>0.0) and (Time<1.0) then begin
ClosestPoint:=StartPosition.Lerp(CheckPosition,Time);
if (ClosestPoint-EndPosition).SquaredLength<1e-10 then begin
PolygonIndex:=MatchingEdge.PolygonIndex;
Polygon:=@Polygons.Items[PolygonIndex];
InsertionPolygonIndicesIndex:=-1;
for PolygonIndicesIndex:=0 to Polygon^.Indices.Count-1 do begin
if Polygon^.Indices.Items[PolygonIndicesIndex]=MatchingEdge.VertexIndices[1] then begin
InsertionPolygonIndicesIndex:=PolygonIndicesIndex;
break;
end;
end;
Assert(InsertionPolygonIndicesIndex>=0);
Polygons.Items[PolygonIndex].Indices.Insert(InsertionPolygonIndicesIndex,EndVertexIndex);
DeleteEdge(MatchingEdge.VertexIndices[0],MatchingEdge.VertexIndices[1],PolygonIndex);
NewEdgeVertexIndices0:=AddEdge(MatchingEdge.VertexIndices[0],EndVertexIndex,PolygonIndex);
NewEdgeVertexIndices1:=AddEdge(EndVertexIndex,MatchingEdge.VertexIndices[1],PolygonIndex);
if NewEdgeVertexIndices0[0]>=0 then begin
EdgesToCheck[NewEdgeVertexIndices0]:=true;
end;
if NewEdgeVertexIndices1[0]>=0 then begin
EdgesToCheck[NewEdgeVertexIndices1]:=true;
end;
DoneWithEdge:=false;
Done:=true;
break;
end;
end;
end;
end;
if Done then begin
break;
end;
end;
end;
if DoneWithEdge then begin
EdgesToCheck.Delete(EdgeVertexIndices);
end;
until false;
until Done;
end;
begin
OldMode:=fMode;
try
SetMode(TMode.Polygons);
try
Polygons.Initialize;
try
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
if (CountPolygonVertices>0) and
((Index+(CountPolygonVertices-1))<Count) then begin
if CountPolygonVertices>2 then begin
PolygonIndex:=Polygons.AddNew;
Polygon:=@Polygons.Items[PolygonIndex];
Polygon^.Indices.Initialize;
Polygon^.Indices.AddRangeFrom(fIndices,Index,CountPolygonVertices);
end;
end;
inc(Index,CountPolygonVertices);
end;
EdgeHashMap:=TEdgeHashMap.Create(-1);
try
EdgesList.Initialize;
try
ScanEdges;
VertexIndexToEdgeStartList.Initialize;
try
VertexIndexToEdgeEndList.Initialize;
try
VertexIndexToEdgeStartHashMap:=TVertexIndexToEdgeStartEndHashMap.Create(-1);
try
VertexIndexToEdgeEndHashMap:=TVertexIndexToEdgeStartEndHashMap.Create(-1);
try
EdgesToCheck:=TEdgesToCheckHashMap.Create(false);
try
ScanVertices;
if not EdgeMapIsEmpty then begin
Process;
end;
finally
FreeAndNil(EdgesToCheck);
end;
finally
FreeAndNil(VertexIndexToEdgeEndHashMap);
end;
finally
FreeAndNil(VertexIndexToEdgeStartHashMap);
end;
finally
VertexIndexToEdgeEndList.Finalize;
end;
finally
VertexIndexToEdgeStartList.Finalize;
end;
finally
EdgesList.Finalize;
end;
finally
FreeAndNil(EdgeHashMap);
end;
NewIndices.Initialize;
try
for PolygonIndex:=0 to Polygons.Count-1 do begin
Polygon:=@Polygons.Items[PolygonIndex];
NewIndices.Add(Polygon^.Indices.Count);
NewIndices.Add(Polygon^.Indices);
end;
SetIndices(NewIndices);
finally
NewIndices.Finalize;
end;
finally
Polygons.Finalize;
end;
finally
SetMode(OldMode);
end;
finally
RemoveDuplicateAndUnusedVertices;
end;
end;
procedure FixTJunctionsWithNonConsistentInputVertices;
type TPolygon=record
Indices:TIndexList;
Plane:TPlane;
AABB:TAABB;
end;
PPolygon=^TPolygon;
TPolygons=TDynamicArray<TPolygon>;
TPolygonAABBTreeStack=TDynamicStack<TpvSizeInt>;
var Index,Count,CountPolygonVertices,
PolygonIndex,
PolygonIndicesIndex,
PolygonAABBTreeNodeID,
OtherPolygonIndex,
OtherPolygonIndicesIndex,
PolygonVertexIndexA,
PolygonVertexIndexB,
OtherPolygonVertexIndex:TpvSizeInt;
Polygons:TPolygons;
Polygon,
OtherPolygon:PPolygon;
PolygonAABBTree:TDynamicAABBTree;
PolygonAABBTreeNode:PDynamicAABBTreeNode;
PolygonAABBTreeStack:TPolygonAABBTreeStack;
NewIndices:TIndexList;
OldMode:TMode;
DoTryAgain:boolean;
PolygonVertexA,
PolygonVertexB,
OtherPolygonVertex:PVertex;
Direction,
NormalizedDirection,
FromPolygonVertexAToOtherPolygonVertex:TVector3;
Time:TFloat;
begin
OldMode:=fMode;
try
SetMode(TMode.Polygons);
try
Polygons.Initialize;
try
PolygonAABBTree:=TDynamicAABBTree.Create;
try
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
if (CountPolygonVertices>0) and
((Index+(CountPolygonVertices-1))<Count) then begin
if CountPolygonVertices>2 then begin
PolygonIndex:=Polygons.AddNew;
Polygon:=@Polygons.Items[PolygonIndex];
Polygon^.Indices.Initialize;
Polygon^.Indices.AddRangeFrom(fIndices,Index,CountPolygonVertices);
Polygon^.Plane:=TpvCSGBSP.TPlane.Create(fVertices.Items[Polygon^.Indices.Items[0]].Position,
fVertices.Items[Polygon^.Indices.Items[1]].Position,
fVertices.Items[Polygon^.Indices.Items[2]].Position);
Polygon^.AABB.Min.x:=Infinity;
Polygon^.AABB.Min.y:=Infinity;
Polygon^.AABB.Min.z:=Infinity;
Polygon^.AABB.Max.x:=-Infinity;
Polygon^.AABB.Max.y:=-Infinity;
Polygon^.AABB.Max.z:=-Infinity;
for PolygonIndicesIndex:=0 to Polygon^.Indices.Count-1 do begin
Polygon^.AABB:=Polygon^.AABB.Combine(fVertices.Items[Polygon^.Indices.Items[PolygonIndicesIndex]].Position);
end;
PolygonAABBTree.CreateProxy(Polygon^.AABB,PolygonIndex);
end;
end;
inc(Index,CountPolygonVertices);
end;
PolygonAABBTreeStack.Initialize;
try
repeat
DoTryAgain:=false;
for PolygonIndex:=0 to Polygons.Count-1 do begin
Polygon:=@Polygons.Items[PolygonIndex];
if PolygonAABBTree.Root>=0 then begin
PolygonAABBTreeStack.Count:=0;
PolygonAABBTreeStack.Push(PolygonAABBTree.Root);
while PolygonAABBTreeStack.Pop(PolygonAABBTreeNodeID) and not DoTryAgain do begin
PolygonAABBTreeNode:=@PolygonAABBTree.Nodes[PolygonAABBTreeNodeID];
if PolygonAABBTreeNode^.AABB.Intersects(Polygon^.AABB) then begin
if PolygonAABBTreeNode^.Children[0]<0 then begin
OtherPolygonIndex:=PolygonAABBTreeNode^.UserData;
if PolygonIndex<>OtherPolygonIndex then begin
OtherPolygon:=@Polygons.Items[OtherPolygonIndex];
PolygonIndicesIndex:=0;
while PolygonIndicesIndex<Polygon^.Indices.Count do begin
PolygonVertexIndexA:=Polygon^.Indices.Items[PolygonIndicesIndex];
PolygonVertexIndexB:=Polygon^.Indices.Items[Wrap(PolygonIndicesIndex+1,Polygon^.Indices.Count)];
PolygonVertexA:=@fVertices.Items[PolygonVertexIndexA];
PolygonVertexB:=@fVertices.Items[PolygonVertexIndexB];
Direction:=PolygonVertexB^.Position-PolygonVertexA^.Position;
NormalizedDirection:=Direction.Normalize;
OtherPolygonIndicesIndex:=0;
while OtherPolygonIndicesIndex<OtherPolygon^.Indices.Count do begin
OtherPolygonVertexIndex:=OtherPolygon^.Indices.Items[OtherPolygonIndicesIndex];
OtherPolygonVertex:=@fVertices.Items[OtherPolygonVertexIndex];
if (PolygonVertexIndexA<>OtherPolygonVertexIndex) and
(PolygonVertexIndexB<>OtherPolygonVertexIndex) and
(PolygonVertexA^.Position<>OtherPolygonVertex^.Position) and
(PolygonVertexB^.Position<>OtherPolygonVertex^.Position) then begin
FromPolygonVertexAToOtherPolygonVertex:=OtherPolygonVertex^.Position-PolygonVertexA^.Position;
if (NormalizedDirection.Dot(FromPolygonVertexAToOtherPolygonVertex.Normalize)>=TJunctionOneMinusEpsilon) and
(NormalizedDirection.Dot((PolygonVertexB^.Position-OtherPolygonVertex^.Position).Normalize)>=TJunctionOneMinusEpsilon) then begin
Time:=FromPolygonVertexAToOtherPolygonVertex.Dot(Direction)/Direction.Dot(Direction);
if ((Time>=TJunctionEpsilon) and (Time<=TJunctionOneMinusEpsilon)) and
(((Direction*Time)-FromPolygonVertexAToOtherPolygonVertex).SquaredLength<TJunctionEpsilon) then begin
Polygon^.Indices.Insert(PolygonIndicesIndex+1,fVertices.Add(PolygonVertexA^.Lerp(PolygonVertexB^,Time)));
begin
// Reload polygon vertex pointers, because the old ones could be invalid here now
PolygonVertexA:=@fVertices.Items[PolygonVertexIndexA];
PolygonVertexB:=@fVertices.Items[PolygonVertexIndexB];
end;
// And we do not need update the AABB of the polygon, because the new inserted
// vertex is coplanar between two end points of a old edge of the polygon
DoTryAgain:=true;
end;
end;
end;
inc(OtherPolygonIndicesIndex);
end;
inc(PolygonIndicesIndex);
end;
end;
end else begin
if PolygonAABBTreeNode^.Children[1]>=0 then begin
PolygonAABBTreeStack.Push(PolygonAABBTreeNode^.Children[1]);
end;
if PolygonAABBTreeNode^.Children[0]>=0 then begin
PolygonAABBTreeStack.Push(PolygonAABBTreeNode^.Children[0]);
end;
end;
end;
end;
end;
end;
until not DoTryAgain;
finally
PolygonAABBTreeStack.Finalize;
end;
NewIndices.Initialize;
try
for PolygonIndex:=0 to Polygons.Count-1 do begin
Polygon:=@Polygons.Items[PolygonIndex];
NewIndices.Add(Polygon^.Indices.Count);
NewIndices.Add(Polygon^.Indices);
end;
SetIndices(NewIndices);
finally
NewIndices.Finalize;
end;
finally
FreeAndNil(PolygonAABBTree);
end;
finally
Polygons.Finalize;
end;
finally
SetMode(OldMode);
end;
finally
RemoveDuplicateAndUnusedVertices;
end;
end;
begin
if aConsistentInputVertices then begin
FixTJunctionsWithConsistentInputVertices;
end else begin
FixTJunctionsWithNonConsistentInputVertices;
end;
end;
procedure TpvCSGBSP.TMesh.MergeCoplanarConvexPolygons;
const HashBits=16;
HashSize=1 shl HashBits;
HashMask=HashSize-1;
type TPolygon=record
Indices:TIndexList;
Plane:TPlane;
end;
PPolygon=^TPolygon;
TPolygons=TDynamicArray<TPolygon>;
TPolygonIndices=TDynamicArray<TpvSizeInt>;
TPolygonPlane=record
Plane:TPlane;
PolygonIndices:TPolygonIndices;
end;
PPolygonPlane=^TPolygonPlane;
TPolygonPlanes=TDynamicArray<TPolygonPlane>;
THashTableItem=record
Next:TpvSizeInt;
Hash:TpvUInt32;
PolygonPlaneIndex:TpvSizeInt;
end;
PHashTableItem=^THashTableItem;
THashTableItems=array of THashTableItem;
THashTable=array of TpvSizeInt;
var Index,Count,CountPolygonVertices,
HashIndex,CountHashTableItems,
InputPolygonIndex,
PolygonPlaneIndex,
PolygonIndex,
IndexA,
IndexB,
Pass:TpvSizeInt;
InputPolygons,OutputPolygons,
TemporaryPolygons:TPolygons;
InputPolygon,OutputPolygon:PPolygon;
TemporaryOutputPolygon:TPolygon;
PolygonPlanes:TPolygonPlanes;
PolygonPlane:PPolygonPlane;
NewIndices:TIndexList;
HashTable:THashTable;
HashTableItems:THashTableItems;
Hash:TpvUInt32;
HashTableItem:PHashTableItem;
DoTryAgain:boolean;
function Wrap(const aIndex,aCount:TpvSizeInt):TpvSizeInt;
begin
result:=aIndex;
if aCount>0 then begin
while result<0 do begin
inc(result,aCount);
end;
while result>=aCount do begin
dec(result,aCount);
end;
end;
end;
function IsPolygonConvex(const aPolygon:TPolygon):boolean;
var Index:TpvSizeInt;
n,p,q:TVector3;
a,k:TFloat;
Sign:boolean;
va,vb,vc:PVector3;
pa,pb,pc,pba,pcb:TVector2;
begin
result:=aPolygon.Indices.Count>2;
if result then begin
n:=aPolygon.Plane.Normal.Normalize;
if abs(n.z)>0.70710678118 then begin
a:=sqr(n.y)+sqr(n.z);
k:=1.0/sqrt(a);
p.x:=0.0;
p.y:=-(n.z*k);
p.z:=n.y*k;
q.x:=a*k;
q.y:=-(n.x*p.z);
q.z:=n.x*p.y;
end else begin
a:=sqr(n.x)+sqr(n.y);
k:=1.0/sqrt(a);
p.x:=-(n.y*k);
p.y:=n.x*k;
p.z:=0.0;
q.x:=-(n.z*p.y);
q.y:=n.z*p.x;
q.z:=a*k;
end;
p:=p.Normalize;
q:=q.Normalize;
Sign:=false;
for Index:=0 to aPolygon.Indices.Count-1 do begin
va:=@fVertices.Items[aPolygon.Indices.Items[Wrap(Index-1,aPolygon.Indices.Count)]].Position;
vb:=@fVertices.Items[aPolygon.Indices.Items[Index]].Position;
vc:=@fVertices.Items[aPolygon.Indices.Items[Wrap(Index+1,aPolygon.Indices.Count)]].Position;
pa.x:=p.Dot(va^);
pa.y:=q.Dot(va^);
pb.x:=p.Dot(vb^);
pb.y:=q.Dot(vb^);
pc.x:=p.Dot(vc^);
pc.y:=q.Dot(vc^);
pba:=pb-pa;
pcb:=pc-pb;
a:=(pba.x*pcb.y)-(pba.y*pcb.x);
if Index=0 then begin
Sign:=a>EPSILON;
end else if Sign<>(a>EPSILON) then begin
result:=false;
break;
end;
end;
end;
end;
procedure RemoveCoplanarEdges(var aPolygon:TPolygon);
type TSideCrossPlaneNormals=TDynamicArray<TVector3>;
var Index:TpvSizeInt;
LastVertexIndex,VertexIndex,NextVertexIndex:TIndex;
v0,v1,v2:PVector3;
Normal,v10,SideCrossPlaneNormal:TVector3;
SideCrossPlaneNormals:TSideCrossPlaneNormals;
begin
// Remove coplanar edges
SideCrossPlaneNormals.Initialize;
try
Normal:=aPolygon.Plane.Normal.Normalize;
Index:=0;
while (aPolygon.Indices.Count>3) and
(Index<aPolygon.Indices.Count) do begin
LastVertexIndex:=aPolygon.Indices.Items[Wrap(Index-1,aPolygon.Indices.Count)];
VertexIndex:=aPolygon.Indices.Items[Index];
NextVertexIndex:=aPolygon.Indices.Items[Wrap(Index+1,aPolygon.Indices.Count)];
v0:=@fVertices.Items[LastVertexIndex].Position;
v1:=@fVertices.Items[VertexIndex].Position;
v2:=@fVertices.Items[NextVertexIndex].Position;
v10:=v1^-v0^;
SideCrossPlaneNormal:=v10.Cross(Normal);
if Index<SideCrossPlaneNormals.Count then begin
SideCrossPlaneNormals.Items[Index]:=SideCrossPlaneNormal;
end else begin
SideCrossPlaneNormals.Add(SideCrossPlaneNormal);
end;
if (abs((v2^-v0^).Normalize.Dot(v10.Normalize))>OneMinusEpsilon) or
(abs(SideCrossPlaneNormal.Length)<Epsilon) then begin
aPolygon.Indices.Delete(Index);
if Index>0 then begin
dec(Index);
end;
end else begin
inc(Index);
end;
end;
for Index:=0 to SideCrossPlaneNormals.Count-1 do begin
SideCrossPlaneNormals.Items[Index]:=SideCrossPlaneNormals.Items[Index].Normalize;
end;
Index:=0;
while (aPolygon.Indices.Count>3) and
(Index<aPolygon.Indices.Count) do begin
if SideCrossPlaneNormals.Items[Index].Dot(SideCrossPlaneNormals.Items[Wrap(Index+1,aPolygon.Indices.Count)])>OneMinusEpsilon then begin
aPolygon.Indices.Delete(Index);
SideCrossPlaneNormals.Delete(Index);
if Index>0 then begin
dec(Index);
end;
end else begin
inc(Index);
end;
end;
finally
SideCrossPlaneNormals.Finalize;
end;
end;
function MergeTwoPolygons(const aPolygonA,aPolygonB:TPolygon;out aOutputPolygon:TPolygon):boolean;
var Index,OtherIndex,CurrentIndex,IndexA,IndexB:TpvSizeInt;
i0,i1,i2,i3,LastVertexIndex,VertexIndex:TIndex;
Found,KeepA,KeepB:boolean;
begin
result:=false;
if IsPolygonConvex(aPolygonA) and
IsPolygonConvex(aPolygonB) then begin
// Find shared edge
Found:=false;
i0:=0;
i1:=1;
IndexA:=0;
IndexB:=0;
for Index:=0 to aPolygonA.Indices.Count-1 do begin
i0:=aPolygonA.Indices.Items[Index];
i1:=aPolygonA.Indices.Items[Wrap(Index+1,aPolygonA.Indices.Count)];
for OtherIndex:=0 to aPolygonB.Indices.Count-1 do begin
i2:=aPolygonB.Indices.Items[OtherIndex];
i3:=aPolygonB.Indices.Items[Wrap(OtherIndex+1,aPolygonB.Indices.Count)];
if (i0=i3) and (i1=i2) then begin
IndexA:=Index;
IndexB:=OtherIndex;
Found:=true;
break;
end;
end;
if Found then begin
break;
end;
end;
if not Found then begin
exit;
end;
aOutputPolygon.Indices.Initialize;
aOutputPolygon.Plane:=aPolygonA.Plane;
// Check for coplanar edges near shared edges
KeepA:=abs((fVertices.Items[aPolygonB.Indices.Items[Wrap(IndexB+2,aPolygonB.Indices.Count)]].Position-
fVertices.Items[i0].Position).Dot(aPolygonA.Plane.Normal.Cross(fVertices.Items[i0].Position-fVertices.Items[aPolygonA.Indices.Items[Wrap(IndexA-1,aPolygonA.Indices.Count)]].Position).Normalize))>EPSILON;
KeepB:=abs((fVertices.Items[aPolygonB.Indices.Items[Wrap(IndexB-1,aPolygonB.Indices.Count)]].Position-
fVertices.Items[i1].Position).Dot(aPolygonA.Plane.Normal.Cross(fVertices.Items[aPolygonA.Indices.Items[Wrap(IndexA+2,aPolygonA.Indices.Count)]].Position-fVertices.Items[i1].Position).Normalize))>EPSILON;
// Construct hopefully then convex polygons
LastVertexIndex:=-1;
for CurrentIndex:=1+(ord(not KeepB) and 1) to aPolygonA.Indices.Count-1 do begin
Index:=Wrap(CurrentIndex+IndexA,aPolygonA.Indices.Count);
VertexIndex:=aPolygonA.Indices.Items[Index];
if not (((LastVertexIndex=i0) and (VertexIndex=i1)) or
((LastVertexIndex=i1) and (VertexIndex=i0))) then begin
aOutputPolygon.Indices.Add(VertexIndex);
LastVertexIndex:=VertexIndex;
end;
end;
for CurrentIndex:=1+(ord(not KeepA) and 1) to aPolygonB.Indices.Count-1 do begin
Index:=Wrap(CurrentIndex+IndexB,aPolygonB.Indices.Count);
VertexIndex:=aPolygonB.Indices.Items[Index];
if not (((LastVertexIndex=i0) and (VertexIndex=i1)) or
((LastVertexIndex=i1) and (VertexIndex=i0))) then begin
aOutputPolygon.Indices.Add(VertexIndex);
LastVertexIndex:=VertexIndex;
end;
end;
if (aOutputPolygon.Indices.Count>1) and
(((aOutputPolygon.Indices.Items[0]=i0) and (aOutputPolygon.Indices.Items[aOutputPolygon.Indices.Count-1]=i1)) or
((aOutputPolygon.Indices.Items[0]=i1) and (aOutputPolygon.Indices.Items[aOutputPolygon.Indices.Count-1]=i0))) then begin
aOutputPolygon.Indices.Delete(aOutputPolygon.Indices.Count-1);
end;
result:=IsPolygonConvex(aOutputPolygon);
end;
end;
procedure MergePolygons(var aPolygons:TPolygons);
begin
end;
function HashPolygonPlane(const aPlane:TPlane):TpvSizeInt;
var HashIndex:TpvSizeInt;
Hash:TpvUInt32;
HashTableItem:PHashTableItem;
PolygonPlane:PPolygonPlane;
begin
Hash:=(trunc(aPlane.Normal.x*4096)*73856093) xor
(trunc(aPlane.Normal.y*4096)*19349653) xor
(trunc(aPlane.Normal.z*4096)*83492791) xor
(trunc(aPlane.Distance*4096)*41728657);
HashIndex:=HashTable[Hash and HashMask];
while HashIndex>=0 do begin
HashTableItem:=@HashTableItems[HashIndex];
if HashTableItem^.Hash=Hash then begin
PolygonPlane:=@PolygonPlanes.Items[HashTableItem^.PolygonPlaneIndex];
if (aPlane.Normal=PolygonPlane^.Plane.Normal) and
SameValue(aPlane.Distance,PolygonPlane^.Plane.Distance) then begin
result:=HashTableItem^.PolygonPlaneIndex;
exit;
end;
end;
HashIndex:=HashTableItem^.Next;
end;
result:=PolygonPlanes.AddNew;
PolygonPlane:=@PolygonPlanes.Items[result];
PolygonPlane^.Plane:=aPlane;
PolygonPlane^.PolygonIndices.Initialize;
HashIndex:=CountHashTableItems;
inc(CountHashTableItems);
if CountHashTableItems>length(HashTableItems) then begin
SetLength(HashTableItems,CountHashTableItems*2);
end;
HashTableItem:=@HashTableItems[HashIndex];
HashTableItem^.Next:=HashTable[Hash and HashMask];
HashTable[Hash and HashMask]:=HashIndex;
HashTableItem^.Hash:=Hash;
HashTableItem^.PolygonPlaneIndex:=result;
end;
begin
RemoveDuplicateAndUnusedVertices;
SetMode(TMode.Polygons);
try
InputPolygons.Initialize;
try
PolygonPlanes.Initialize;
try
HashTable:=nil;
try
SetLength(HashTable,HashSize);
for Index:=0 to HashSize-1 do begin
HashTable[Index]:=-1;
end;
HashTableItems:=nil;
CountHashTableItems:=0;
try
Index:=0;
Count:=fIndices.Count;
while Index<Count do begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
if (CountPolygonVertices>0) and
((Index+(CountPolygonVertices-1))<Count) then begin
if CountPolygonVertices>2 then begin
InputPolygonIndex:=InputPolygons.AddNew;
InputPolygon:=@InputPolygons.Items[InputPolygonIndex];
InputPolygon^.Indices.Initialize;
InputPolygon^.Indices.AddRangeFrom(fIndices,Index,CountPolygonVertices);
InputPolygon^.Plane:=TpvCSGBSP.TPlane.Create(fVertices.Items[InputPolygon^.Indices.Items[0]].Position,
fVertices.Items[InputPolygon^.Indices.Items[1]].Position,
fVertices.Items[InputPolygon^.Indices.Items[2]].Position);
PolygonPlaneIndex:=HashPolygonPlane(InputPolygon^.Plane);
PolygonPlane:=@PolygonPlanes.Items[PolygonPlaneIndex];
PolygonPlane^.PolygonIndices.Add(InputPolygonIndex);
end;
end;
inc(Index,CountPolygonVertices);
end;
finally
HashTableItems:=nil;
end;
finally
HashTable:=nil;
end;
OutputPolygons.Initialize;
try
for PolygonPlaneIndex:=0 to PolygonPlanes.Count-1 do begin
PolygonPlane:=@PolygonPlanes.Items[PolygonPlaneIndex];
{ if not (SameValue(PolygonPlane^.Plane.Normal.x,1.0) and
SameValue(PolygonPlane^.Plane.Normal.y,0.0) and
SameValue(PolygonPlane^.Plane.Normal.z,0.0)) then begin
continue;
end;{}
if PolygonPlane^.PolygonIndices.Count>0 then begin
if PolygonPlane^.PolygonIndices.Count<2 then begin
for PolygonIndex:=0 to PolygonPlane^.PolygonIndices.Count-1 do begin
OutputPolygons.Add(InputPolygons.Items[PolygonPlane^.PolygonIndices.Items[PolygonIndex]]);
end;
end else begin
TemporaryPolygons.Initialize;
try
for PolygonIndex:=0 to PolygonPlane^.PolygonIndices.Count-1 do begin
TemporaryPolygons.Add(InputPolygons.Items[PolygonPlane^.PolygonIndices.Items[PolygonIndex]]);
end;
for Pass:=0 to 1 do begin
repeat
DoTryAgain:=false;
Count:=TemporaryPolygons.Count;
IndexA:=0;
while IndexA<Count do begin
IndexB:=IndexA+1;
while IndexB<Count do begin
TemporaryOutputPolygon.Indices.Initialize;
if MergeTwoPolygons(TemporaryPolygons.Items[IndexA],
TemporaryPolygons.Items[IndexB],
TemporaryOutputPolygon) then begin
TemporaryPolygons.Items[IndexA]:=TemporaryOutputPolygon;
TemporaryPolygons.Delete(IndexB);
Count:=TemporaryPolygons.Count;
DoTryAgain:=true;
end;
inc(IndexB);
end;
inc(IndexA);
end;
until not DoTryAgain;
MergePolygons(TemporaryPolygons);
break;
{ for PolygonIndex:=0 to TemporaryPolygons.Count-1 do begin
RemoveCoplanarEdges(TemporaryPolygons.Items[PolygonIndex]);
end;}
end;
OutputPolygons.Add(TemporaryPolygons);
finally
TemporaryPolygons.Finalize;
end;
end;
end;
end;
NewIndices.Initialize;
try
for PolygonIndex:=0 to OutputPolygons.Count-1 do begin
OutputPolygon:=@OutputPolygons.Items[PolygonIndex];
NewIndices.Add(OutputPolygon^.Indices.Count);
NewIndices.Add(OutputPolygon^.Indices);
end;
SetIndices(NewIndices);
finally
NewIndices.Finalize;
end;
finally
OutputPolygons.Finalize;
end;
finally
PolygonPlanes.Finalize;
end;
finally
InputPolygons.Finalize;
end;
finally
RemoveDuplicateAndUnusedVertices;
end;
end;
procedure TpvCSGBSP.TMesh.Optimize;
begin
Canonicalize;
MergeCoplanarConvexPolygons;
end;
function TpvCSGBSP.TMesh.ToSingleTreeNode(const aSplitSettings:PSplitSettings=nil):TSingleTreeNode;
begin
result:=TSingleTreeNode.Create(self);
result.Build(fIndices,aSplitSettings);
end;
function TpvCSGBSP.TMesh.ToDualTree(const aSplitSettings:PSplitSettings=nil):TDualTree;
begin
result:=TDualTree.Create(self,aSplitSettings);
result.AddIndices(fIndices);
end;
{ TpvCSGBSP.TNode }
constructor TpvCSGBSP.TSingleTreeNode.Create(const aMesh:TMesh);
begin
inherited Create;
fMesh:=aMesh;
fIndices.Initialize;
fPointerToIndices:=@fIndices;
fBack:=nil;
fFront:=nil;
end;
destructor TpvCSGBSP.TSingleTreeNode.Destroy;
type TJobStack=TDynamicStack<TSingleTreeNode>;
var JobStack:TJobStack;
Node:TSingleTreeNode;
begin
fIndices.Finalize;
if assigned(fFront) or assigned(fBack) then begin
JobStack.Initialize;
try
JobStack.Push(self);
while JobStack.Pop(Node) do begin
if assigned(Node.fFront) then begin
JobStack.Push(Node.fFront);
Node.fFront:=nil;
end;
if assigned(Node.fBack) then begin
JobStack.Push(Node.fBack);
Node.fBack:=nil;
end;
if Node<>self then begin
FreeAndNil(Node);
end;
end;
finally
JobStack.Finalize;
end;
end;
fPointerToIndices:=nil;
inherited Destroy;
end;
procedure TpvCSGBSP.TSingleTreeNode.SetIndices(const aIndices:TIndexList);
begin
fIndices.Assign(aIndices);
end;
procedure TpvCSGBSP.TSingleTreeNode.Invert;
type TJobStack=TDynamicStack<TSingleTreeNode>;
var JobStack:TJobStack;
Node,TempNode:TSingleTreeNode;
Index,Count,
CountPolygonVertices,PolygonVertexIndex,
IndexA,IndexB:TpvSizeInt;
begin
fMesh.Invert;
JobStack.Initialize;
try
JobStack.Push(self);
while JobStack.Pop(Node) do begin
case fMesh.fMode of
TMesh.TMode.Triangles:begin
Index:=0;
Count:=Node.fIndices.Count;
while (Index+2)<Count do begin
Node.fIndices.Exchange(Index+0,Index+2);
inc(Index,3);
end;
end;
else {TMesh.TMode.Polygons:}begin
Index:=0;
Count:=Node.fIndices.Count;
while Index<Count do begin
CountPolygonVertices:=Node.fIndices.Items[Index];
inc(Index);
if CountPolygonVertices>0 then begin
if (Index+(CountPolygonVertices-1))<Count then begin
for PolygonVertexIndex:=0 to (CountPolygonVertices shr 1)-1 do begin
IndexA:=Index+PolygonVertexIndex;
IndexB:=Index+(CountPolygonVertices-(PolygonVertexIndex+1));
if IndexA<>IndexB then begin
Node.fIndices.Exchange(IndexA,IndexB);
end;
end;
end else begin
Assert(false);
end;
inc(Index,CountPolygonVertices);
end;
end;
end;
end;
Node.fPlane:=Node.fPlane.Flip;
TempNode:=Node.fBack;
Node.fBack:=Node.fFront;
Node.fFront:=TempNode;
if assigned(Node.fFront) then begin
JobStack.Push(Node.fFront);
end;
if assigned(Node.fBack) then begin
JobStack.Push(Node.fBack);
end;
end;
finally
JobStack.Finalize;
end;
end;
procedure TpvCSGBSP.TSingleTreeNode.EvaluateSplitPlane(const aPlane:TPlane;
out aCountPolygonsSplits:TpvSizeInt;
out aCountBackPolygons:TpvSizeInt;
out aCountFrontPolygons:TpvSizeInt);
const TriangleSplitMask=(0 shl 0) or (1 shl 2) or (1 shl 2) or (1 shl 3) or (1 shl 4) or (1 shl 5) or (1 shl 6) or (0 shl 7);
BackTriangleMask=(1 shl 0) or (2 shl 2) or (2 shl 4) or (1 shl (3 shl 1)) or (2 shl (4 shl 1)) or (1 shl (5 shl 1)) or (1 shl (6 shl 1)) or (0 shl (7 shl 1));
FrontTriangleMask=(0 shl 0) or (1 shl 2) or (1 shl 4) or (2 shl (3 shl 1)) or (1 shl (4 shl 1)) or (2 shl (5 shl 1)) or (2 shl (6 shl 1)) or (1 shl (7 shl 1));
var Index,Count,CountPolygonVertices,Code:TpvSizeInt;
Vertices:TVertexList;
begin
aCountPolygonsSplits:=0;
aCountBackPolygons:=0;
aCountFrontPolygons:=0;
Count:=fIndices.Count;
if Count>0 then begin
Vertices:=fMesh.fVertices;
Index:=0;
while Index<Count do begin
case fMesh.fMode of
TMesh.TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMesh.TMode.Polygons:}begin
CountPolygonVertices:=fIndices.Items[Index];
inc(Index);
end;
end;
if (CountPolygonVertices>2) and ((Index+(CountPolygonVertices-1))<Count) then begin
Code:=((ord(aPlane.DistanceTo(Vertices.Items[fIndices.Items[Index+0]].Position)>0.0) and 1) shl 2) or
((ord(aPlane.DistanceTo(Vertices.Items[fIndices.Items[Index+1]].Position)>0.0) and 1) shl 1) or
((ord(aPlane.DistanceTo(Vertices.Items[fIndices.Items[Index+2]].Position)>0.0) and 1) shl 0);
inc(aCountPolygonsSplits,(TriangleSplitMask shr Code) and 1);
inc(aCountBackPolygons,(BackTriangleMask shr (Code shl 1)) and 3);
inc(aCountFrontPolygons,(FrontTriangleMask shr (Code shl 1)) and 3);
end;
inc(Index,CountPolygonVertices);
end;
end;
end;
function TpvCSGBSP.TSingleTreeNode.FindSplitPlane(const aIndices:TIndexList;
const aSplitSettings:PSplitSettings):TPlane;
var Index,Count,TriangleCount,VertexBaseIndex,
CountPolygonsSplits,CountBackPolygons,CountFrontPolygons,
CountPolygonVertices,LoopCount:TpvSizeInt;
Plane:TPlane;
Score,BestScore:TFloat;
Vertices:TVertexList;
SplitSettings:PSplitSettings;
DoRandomPicking:boolean;
begin
if assigned(aSplitSettings) then begin
SplitSettings:=aSplitSettings;
end else begin
SplitSettings:=@DefaultSplitSettings;
end;
if IsZero(SplitSettings^.SearchBestFactor) or (SplitSettings^.SearchBestFactor<=0.0) then begin
if aIndices.Count>2 then begin
{ if SplitSettings^.SearchBestFactor<0.0 then begin
Index:=Random(aPolygonNodes.Count);
if Index>=aPolygonNodes.Count then begin
Index:=0;
end;
end else begin
Index:=0;
end;}
Index:=0;
case fMesh.fMode of
TMesh.TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMesh.TMode.Polygons:}begin
CountPolygonVertices:=aIndices.Items[Index];
inc(Index);
end;
end;
Count:=aIndices.Count;
if (CountPolygonVertices>2) and ((Index+(CountPolygonVertices-1))<Count) then begin
result:=TPlane.Create(fMesh.fVertices.Items[aIndices.Items[Index+0]].Position,
fMesh.fVertices.Items[aIndices.Items[Index+1]].Position,
fMesh.fVertices.Items[aIndices.Items[Index+2]].Position);
end;
end else begin
result:=TPlane.CreateEmpty;
end;
end else begin
result:=TPlane.CreateEmpty;
case fMesh.fMode of
TMesh.TMode.Triangles:begin
Count:=aIndices.Count;
TriangleCount:=Count div 3;
Vertices:=fMesh.fVertices;
BestScore:=Infinity;
if SameValue(SplitSettings^.SearchBestFactor,1.0) or (SplitSettings^.SearchBestFactor>=1.0) then begin
LoopCount:=TriangleCount;
DoRandomPicking:=false;
end else begin
LoopCount:=Min(Max(round(TriangleCount*SplitSettings^.SearchBestFactor),1),TriangleCount);
DoRandomPicking:=true;
end;
for Index:=0 to LoopCount-1 do begin
if DoRandomPicking then begin
VertexBaseIndex:=Random(TriangleCount)*3;
end else begin
VertexBaseIndex:=(Index mod TriangleCount)*3;
end;
Plane:=TPlane.Create(Vertices.Items[aIndices.Items[VertexBaseIndex+0]].Position,
Vertices.Items[aIndices.Items[VertexBaseIndex+1]].Position,
Vertices.Items[aIndices.Items[VertexBaseIndex+2]].Position);
EvaluateSplitPlane(Plane,CountPolygonsSplits,CountBackPolygons,CountFrontPolygons);
Score:=(CountPolygonsSplits*SplitSettings^.PolygonSplitCost)+
(abs(CountBackPolygons-CountFrontPolygons)*SplitSettings^.PolygonImbalanceCost);
if (Index=0) or (BestScore>Score) then begin
BestScore:=Score;
result:=Plane;
end;
end;
end;
else {TMesh.TMode.Polygons:}begin
Count:=aIndices.Count;
Vertices:=fMesh.fVertices;
BestScore:=Infinity;
Index:=0;
while Index<Count do begin
case fMesh.fMode of
TMesh.TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMesh.TMode.Polygons:}begin
CountPolygonVertices:=aIndices.Items[Index];
inc(Index);
end;
end;
if (CountPolygonVertices>2) and ((Index+(CountPolygonVertices-1))<Count) then begin
VertexBaseIndex:=Index;
Plane:=TPlane.Create(Vertices.Items[aIndices.Items[VertexBaseIndex+0]].Position,
Vertices.Items[aIndices.Items[VertexBaseIndex+1]].Position,
Vertices.Items[aIndices.Items[VertexBaseIndex+2]].Position);
EvaluateSplitPlane(Plane,CountPolygonsSplits,CountBackPolygons,CountFrontPolygons);
Score:=(CountPolygonsSplits*SplitSettings^.PolygonSplitCost)+
(abs(CountBackPolygons-CountFrontPolygons)*SplitSettings^.PolygonImbalanceCost);
if (Index=0) or (BestScore>Score) then begin
BestScore:=Score;
result:=Plane;
end;
end;
inc(Index,CountPolygonVertices);
end;
end;
end;
end;
end;
procedure TpvCSGBSP.TSingleTreeNode.Build(const aIndices:TIndexList;
const aSplitSettings:PSplitSettings=nil);
type TJobStackItem=record
Node:TSingleTreeNode;
Indices:TIndexList;
end;
TJobStack=TDynamicStack<TJobStackItem>;
var JobStack:TJobStack;
JobStackItem,NewJobStackItem,FrontJobStackItem,BackJobStackItem:TJobStackItem;
Index,CountVertexIndices:TpvSizeInt;
begin
JobStack.Initialize;
try
NewJobStackItem.Node:=self;
NewJobStackItem.Indices:=aIndices;
JobStack.Push(NewJobStackItem);
while JobStack.Pop(JobStackItem) do begin
try
CountVertexIndices:=JobStackItem.Indices.Count;
if ((fMesh.fMode=TMesh.TMode.Triangles) and (CountVertexIndices>2)) or
((fMesh.fMode in [TMesh.TMode.Polygons]) and (CountVertexIndices>1)) then begin
FrontJobStackItem.Indices.Initialize;
BackJobStackItem.Indices.Initialize;
if not JobStackItem.Node.fPlane.OK then begin
JobStackItem.Node.fPlane:=FindSplitPlane(JobStackItem.Indices,aSplitSettings);
end;
case fMesh.fMode of
TMesh.TMode.Triangles:begin
JobStackItem.Node.fPlane.SplitTriangles(fMesh.fVertices,
JobStackItem.Indices,
@JobStackItem.Node.fIndices,
@JobStackItem.Node.fIndices,
@BackJobStackItem.Indices,
@FrontJobStackItem.Indices);
end;
else {TMesh.TMode.Polygons:}begin
JobStackItem.Node.fPlane.SplitPolygons(fMesh.fVertices,
JobStackItem.Indices,
@JobStackItem.Node.fIndices,
@JobStackItem.Node.fIndices,
@BackJobStackItem.Indices,
@FrontJobStackItem.Indices);
end;
end;
if BackJobStackItem.Indices.Count>0 then begin
if not assigned(JobStackItem.Node.fBack) then begin
JobStackItem.Node.fBack:=TSingleTreeNode.Create(fMesh);
end;
BackJobStackItem.Node:=JobStackItem.Node.fBack;
JobStack.Push(BackJobStackItem);
end;
if FrontJobStackItem.Indices.Count>0 then begin
if not assigned(JobStackItem.Node.fFront) then begin
JobStackItem.Node.fFront:=TSingleTreeNode.Create(fMesh);
end;
FrontJobStackItem.Node:=JobStackItem.Node.fFront;
JobStack.Push(FrontJobStackItem);
end;
end;
finally
JobStackItem.Indices.Finalize;
end;
end;
finally
JobStack.Finalize;
end;
end;
function TpvCSGBSP.TSingleTreeNode.ClipPolygons(var aVertices:TVertexList;const aIndices:TIndexList):TIndexList;
type TJobStackItem=record
Node:TSingleTreeNode;
Indices:TIndexList;
end;
TJobStack=TDynamicStack<TJobStackItem>;
var JobStack:TJobStack;
JobStackItem,NewJobStackItem,FrontJobStackItem,BackJobStackItem:TJobStackItem;
Index,Count:TpvSizeInt;
BackIndices:PIndexList;
begin
result.Initialize;
try
JobStack.Initialize;
try
NewJobStackItem.Node:=self;
NewJobStackItem.Indices.Assign(aIndices);
JobStack.Push(NewJobStackItem);
while JobStack.Pop(JobStackItem) do begin
try
if JobStackItem.Node.fPlane.OK then begin
FrontJobStackItem.Indices.Initialize;
try
if assigned(JobStackItem.Node.fBack) then begin
BackJobStackItem.Indices.Initialize;
BackIndices:=@BackJobStackItem.Indices;
end else begin
BackIndices:=nil;
end;
try
case fMesh.fMode of
TMesh.TMode.Triangles:begin
JobStackItem.Node.fPlane.SplitTriangles(aVertices,
JobStackItem.Indices,
BackIndices,
@FrontJobStackItem.Indices,
BackIndices,
@FrontJobStackItem.Indices);
end;
else {TMesh.TMode.Polygons:}begin
JobStackItem.Node.fPlane.SplitPolygons(aVertices,
JobStackItem.Indices,
BackIndices,
@FrontJobStackItem.Indices,
BackIndices,
@FrontJobStackItem.Indices);
end;
end;
if assigned(JobStackItem.Node.fBack) then begin
BackJobStackItem.Node:=JobStackItem.Node.fBack;
JobStack.Push(BackJobStackItem);
end;
if assigned(JobStackItem.Node.fFront) then begin
FrontJobStackItem.Node:=JobStackItem.Node.fFront;
JobStack.Push(FrontJobStackItem);
end else if FrontJobStackItem.Indices.Count>0 then begin
result.Add(FrontJobStackItem.Indices);
end;
finally
BackJobStackItem.Indices.Finalize;
end;
finally
FrontJobStackItem.Indices.Finalize;
end;
end else if JobStackItem.Indices.Count>0 then begin
result.Add(JobStackItem.Indices);
end;
finally
JobStackItem.Indices.Finalize;
end;
end;
finally
JobStack.Finalize;
end;
except
result.Finalize;
raise;
end;
end;
procedure TpvCSGBSP.TSingleTreeNode.ClipTo(const aNode:TSingleTreeNode);
type TJobStack=TDynamicStack<TSingleTreeNode>;
var JobStack:TJobStack;
Node:TSingleTreeNode;
begin
JobStack.Initialize;
try
JobStack.Push(self);
while JobStack.Pop(Node) do begin
Node.SetIndices(aNode.ClipPolygons(Node.fMesh.fVertices,Node.fIndices));
if assigned(Node.fFront) then begin
JobStack.Push(Node.fFront);
end;
if assigned(Node.fBack) then begin
JobStack.Push(Node.fBack);
end;
end;
finally
JobStack.Finalize;
end;
end;
procedure TpvCSGBSP.TSingleTreeNode.Merge(const aNode:TSingleTreeNode;
const aSplitSettings:PSplitSettings=nil);
var Index,Offset,Count,CountPolygonVertices:TpvSizeInt;
OtherMesh:TMesh;
begin
Offset:=fMesh.fVertices.Count;
OtherMesh:=aNode.ToMesh;
try
OtherMesh.SetMode(fMesh.fMode);
fMesh.fVertices.Add(OtherMesh.fVertices);
case fMesh.fMode of
TMesh.TMode.Triangles:begin
for Index:=0 to OtherMesh.fIndices.Count-1 do begin
OtherMesh.fIndices.Items[Index]:=OtherMesh.fIndices.Items[Index]+Offset;
end;
end;
else {TMesh.TMode.Polygons:}begin
Index:=0;
Count:=OtherMesh.fIndices.Count;
while Index<Count do begin
CountPolygonVertices:=OtherMesh.fIndices.Items[Index];
inc(Index);
while (CountPolygonVertices>0) and (Index<Count) do begin
OtherMesh.fIndices.Items[Index]:=OtherMesh.fIndices.Items[Index]+Offset;
inc(Index);
dec(CountPolygonVertices);
end;
end;
end;
end;
Build(OtherMesh.fIndices,aSplitSettings);
finally
FreeAndNil(OtherMesh);
end;
end;
function TpvCSGBSP.TSingleTreeNode.ToMesh:TMesh;
type TJobStack=TDynamicStack<TSingleTreeNode>;
var JobStack:TJobStack;
Node:TSingleTreeNode;
begin
result:=TMesh.Create(fMesh.fMode);
try
result.SetVertices(fMesh.fVertices);
JobStack.Initialize;
try
JobStack.Push(self);
while JobStack.Pop(Node) do begin
result.fIndices.Add(Node.fIndices);
if assigned(Node.fFront) then begin
JobStack.Push(Node.fFront);
end;
if assigned(Node.fBack) then begin
JobStack.Push(Node.fBack);
end;
end;
finally
JobStack.Finalize;
end;
finally
result.RemoveDuplicateAndUnusedVertices;
end;
end;
{ TpvCSGBSP.TTree.TPolygon }
procedure TpvCSGBSP.TDualTree.TPolygon.Invert;
var IndexA,IndexB:TpvSizeInt;
begin
if Indices.Count>0 then begin
for IndexA:=0 to (Indices.Count shr 1)-1 do begin
IndexB:=(Indices.Count-(IndexA+1));
if IndexA<>IndexB then begin
Indices.Exchange(IndexA,IndexB);
end;
end;
end;
end;
{ TpvCSGBSP.TTree.TPolygonNode }
constructor TpvCSGBSP.TDualTree.TPolygonNode.Create(const aTree:TDualTree;const aParent:TPolygonNode);
begin
inherited Create;
fTree:=aTree;
if assigned(fTree.fLastPolygonNode) then begin
fAllPrevious:=fTree.fLastPolygonNode;
fAllPrevious.fAllNext:=self;
end else begin
fTree.fFirstPolygonNode:=self;
fAllPrevious:=nil;
end;
fTree.fLastPolygonNode:=self;
fAllNext:=nil;
fParent:=aParent;
if assigned(fParent) then begin
if assigned(fParent.fLastChild) then begin
fParentPrevious:=fParent.fLastChild;
fParentPrevious.fParentNext:=self;
end else begin
fParent.fFirstChild:=self;
fParentPrevious:=nil;
end;
fParent.fLastChild:=self;
end;
fRemoved:=false;
fPolygon.Indices.Initialize;
end;
destructor TpvCSGBSP.TDualTree.TPolygonNode.Destroy;
begin
fPolygon.Indices.Finalize;
RemoveFromParent;
if assigned(fAllPrevious) then begin
fAllPrevious.fAllNext:=fAllNext;
end else if fTree.fFirstPolygonNode=self then begin
fTree.fFirstPolygonNode:=fAllNext;
end;
if assigned(fAllNext) then begin
fAllNext.fAllPrevious:=fAllPrevious;
end else if fTree.fLastPolygonNode=self then begin
fTree.fLastPolygonNode:=fAllPrevious;
end;
fAllPrevious:=nil;
fAllNext:=nil;
inherited Destroy;
end;
procedure TpvCSGBSP.TDualTree.TPolygonNode.RemoveFromParent;
begin
if assigned(fParent) then begin
if assigned(fParentPrevious) then begin
fParentPrevious.fParentNext:=fParentNext;
end else if fParent.fFirstChild=self then begin
fParent.fFirstChild:=fParentNext;
end;
if assigned(fParentNext) then begin
fParentNext.fParentPrevious:=fParentPrevious;
end else if fParent.fLastChild=self then begin
fParent.fLastChild:=fParentPrevious;
end;
fParent:=nil;
end;
fParentPrevious:=nil;
fParentNext:=nil;
end;
function TpvCSGBSP.TDualTree.TPolygonNode.AddPolygon(const aPolygon:TPolygon):TPolygonNode;
begin
result:=TPolygonNode.Create(fTree,self);
result.fPolygon:=aPolygon;
end;
function TpvCSGBSP.TDualTree.TPolygonNode.AddPolygonIndices(const aIndices:TIndexList):TDualTree.TPolygonNode;
begin
result:=TPolygonNode.Create(fTree,self);
result.fPolygon.Indices.Assign(aIndices);
end;
procedure TpvCSGBSP.TDualTree.TPolygonNode.Remove;
var Index:TpvSizeInt;
PolygonNode:TPolygonNode;
begin
if not fRemoved then begin
fRemoved:=true;
PolygonNode:=self;
while assigned(PolygonNode) and
(PolygonNode.fPolygon.Indices.Count>0) do begin
PolygonNode.fPolygon.Indices.Clear;
PolygonNode:=PolygonNode.fParent;
end;
RemoveFromParent;
end;
end;
procedure TpvCSGBSP.TDualTree.TPolygonNode.Invert;
type TJobQueue=TDynamicQueue<TPolygonNode>;
var Index:TpvSizeInt;
JobQueue:TJobQueue;
PolygonNode:TPolygonNode;
begin
JobQueue.Initialize;
try
JobQueue.Enqueue(self);
while JobQueue.Dequeue(PolygonNode) do begin
if not PolygonNode.fRemoved then begin
PolygonNode.fPolygon.Invert;
PolygonNode:=PolygonNode.fFirstChild;
while assigned(PolygonNode) do begin
if not PolygonNode.fRemoved then begin
JobQueue.Enqueue(PolygonNode);
end;
PolygonNode:=PolygonNode.fParentNext;
end;
end;
end;
finally
JobQueue.Finalize;
end;
end;
procedure TpvCSGBSP.TDualTree.TPolygonNode.DrySplitByPlane(const aPlane:TPlane;var aCountSplits,aCoplanarBackList,aCoplanarFrontList,aBackList,aFrontList:TpvSizeInt);
const Coplanar=0;
Front=1;
Back=2;
Spanning=3;
EpsilonSignToOrientation:array[0..3] of TpvInt32=(Back,Coplanar,Front,Spanning);
type TJobQueue=TDynamicQueue<TPolygonNode>;
var Index,OtherIndex,Count,CountPolygonVertices,
IndexA,IndexB,
PolygonOrientation,
VertexOrientation,
VertexOrientationA,
VertexOrientationB:TpvSizeInt;
JobQueue:TJobQueue;
PolygonNode:TPolygonNode;
Polygon:PPolygon;
VertexOrientations:array of TpvSizeInt;
VectorDistance:TpvDouble;
BackVertexIndices,FrontVertexIndices:TIndexList;
VertexIndex:TIndex;
VertexA,VertexB:PVertex;
Vertices:PVertexList;
PolygonAABB:TAABB;
PolygonSphereRadius,
PolygonSphereDistance:TFloat;
begin
VertexOrientations:=nil;
try
BackVertexIndices.Initialize;
try
FrontVertexIndices.Initialize;
try
Vertices:=@fTree.fMesh.fVertices;
JobQueue.Initialize;
try
JobQueue.Enqueue(self);
while JobQueue.Dequeue(PolygonNode) do begin
if not PolygonNode.fRemoved then begin
if assigned(PolygonNode.fFirstChild) then begin
PolygonNode:=PolygonNode.fFirstChild;
while assigned(PolygonNode) do begin
if not PolygonNode.fRemoved then begin
JobQueue.Enqueue(PolygonNode);
end;
PolygonNode:=PolygonNode.fParentNext;
end;
end else begin
Polygon:=@PolygonNode.fPolygon;
CountPolygonVertices:=Polygon^.Indices.Count;
if CountPolygonVertices>2 then begin
VertexA:=@Vertices^.Items[Polygon^.Indices.Items[0]];
PolygonAABB.Min:=VertexA^.Position;
PolygonAABB.Max:=VertexA^.Position;
for IndexA:=1 to CountPolygonVertices-1 do begin
PolygonAABB:=PolygonAABB.Combine(Vertices^.Items[Polygon^.Indices.Items[IndexA]].Position);
end;
PolygonSphereRadius:=((PolygonAABB.Max-PolygonAABB.Min)*0.5).Length+Epsilon;
PolygonSphereDistance:=aPlane.DistanceTo((PolygonAABB.Min+PolygonAABB.Max)*0.5);
if PolygonSphereDistance<-PolygonSphereRadius then begin
inc(aBackList);
end else if PolygonSphereDistance>PolygonSphereRadius then begin
inc(aFrontList);
end else begin
PolygonOrientation:=0;
if length(VertexOrientations)<CountPolygonVertices then begin
SetLength(VertexOrientations,(CountPolygonVertices*3) shr 1);
end;
for IndexA:=0 to CountPolygonVertices-1 do begin
VertexOrientation:=EpsilonSignToOrientation[(TpvCSGBSP.EpsilonSign(aPlane.DistanceTo(Vertices^.Items[Polygon^.Indices.Items[IndexA]].Position))+1) and 3];
PolygonOrientation:=PolygonOrientation or VertexOrientation;
VertexOrientations[IndexA]:=VertexOrientation;
end;
case PolygonOrientation of
Coplanar:begin
if aPlane.Normal.Dot(TPlane.Create(Vertices^.Items[Polygon^.Indices.Items[0]].Position,
Vertices^.Items[Polygon^.Indices.Items[1]].Position,
Vertices^.Items[Polygon^.Indices.Items[2]].Position).Normal)<0.0 then begin
inc(aCoplanarBackList);
end else begin
inc(aCoplanarFrontList);
end;
end;
Front:begin
inc(aFrontList);
end;
Back:begin
inc(aBackList);
end;
else {Spanning:}begin
inc(aCountSplits);
BackVertexIndices.Count:=0;
FrontVertexIndices.Count:=0;
for IndexA:=0 to CountPolygonVertices-1 do begin
IndexB:=IndexA+1;
if IndexB>=CountPolygonVertices then begin
IndexB:=0;
end;
VertexIndex:=Polygon^.Indices.Items[IndexA];
VertexA:=@Vertices^.Items[VertexIndex];
VertexOrientationA:=VertexOrientations[IndexA];
VertexOrientationB:=VertexOrientations[IndexB];
if VertexOrientationA<>Front then begin
BackVertexIndices.Add(VertexIndex);
end;
if VertexOrientationA<>Back then begin
FrontVertexIndices.Add(VertexIndex);
end;
if (VertexOrientationA or VertexOrientationB)=Spanning then begin
VertexB:=@Vertices^.Items[Polygon^.Indices.Items[IndexB]];
VertexIndex:=Vertices^.Add(VertexA^.Lerp(VertexB^,-(aPlane.DistanceTo(VertexA^.Position)/aPlane.Normal.Dot(VertexB^.Position-VertexA^.Position))));
BackVertexIndices.Add(VertexIndex);
FrontVertexIndices.Add(VertexIndex);
end;
end;
if BackVertexIndices.Count>2 then begin
fTree.fMesh.RemoveNearDuplicateIndices(BackVertexIndices);
if BackVertexIndices.Count>2 then begin
inc(aBackList);
end;
end;
if FrontVertexIndices.Count>2 then begin
fTree.fMesh.RemoveNearDuplicateIndices(FrontVertexIndices);
if FrontVertexIndices.Count>2 then begin
inc(aFrontList);
end;
end;
end;
end;
end;
end;
end;
end;
end;
finally
JobQueue.Finalize;
end;
finally
FrontVertexIndices.Finalize;
end;
finally
BackVertexIndices.Finalize;
end;
finally
VertexOrientations:=nil;
end;
end;
procedure TpvCSGBSP.TDualTree.TPolygonNode.SplitByPlane(const aPlane:TPlane;var aCoplanarBackList,aCoplanarFrontList,aBackList,aFrontList:TPolygonNodeList);
const Coplanar=0;
Front=1;
Back=2;
Spanning=3;
EpsilonSignToOrientation:array[0..3] of TpvInt32=(Back,Coplanar,Front,Spanning);
type TJobQueue=TDynamicQueue<TPolygonNode>;
var Index,OtherIndex,Count,CountPolygonVertices,
IndexA,IndexB,
PolygonOrientation,
VertexOrientation,
VertexOrientationA,
VertexOrientationB:TpvSizeInt;
JobQueue:TJobQueue;
PolygonNode:TPolygonNode;
Polygon:PPolygon;
VertexOrientations:array of TpvSizeInt;
VectorDistance:TpvDouble;
BackVertexIndices,FrontVertexIndices:TIndexList;
VertexIndex:TIndex;
VertexA,VertexB:PVertex;
Vertices:PVertexList;
PolygonAABB:TAABB;
PolygonSphereRadius,
PolygonSphereDistance:TFloat;
begin
VertexOrientations:=nil;
try
BackVertexIndices.Initialize;
try
FrontVertexIndices.Initialize;
try
Vertices:=@fTree.fMesh.fVertices;
JobQueue.Initialize;
try
JobQueue.Enqueue(self);
while JobQueue.Dequeue(PolygonNode) do begin
if not PolygonNode.fRemoved then begin
if assigned(PolygonNode.fFirstChild) then begin
PolygonNode:=PolygonNode.fFirstChild;
while assigned(PolygonNode) do begin
if not PolygonNode.fRemoved then begin
JobQueue.Enqueue(PolygonNode);
end;
PolygonNode:=PolygonNode.fParentNext;
end;
end else begin
Polygon:=@PolygonNode.fPolygon;
CountPolygonVertices:=Polygon^.Indices.Count;
if CountPolygonVertices>2 then begin
VertexA:=@Vertices^.Items[Polygon^.Indices.Items[0]];
PolygonAABB.Min:=VertexA^.Position;
PolygonAABB.Max:=VertexA^.Position;
for IndexA:=1 to CountPolygonVertices-1 do begin
PolygonAABB:=PolygonAABB.Combine(Vertices^.Items[Polygon^.Indices.Items[IndexA]].Position);
end;
PolygonSphereRadius:=((PolygonAABB.Max-PolygonAABB.Min)*0.5).Length+Epsilon;
PolygonSphereDistance:=aPlane.DistanceTo((PolygonAABB.Min+PolygonAABB.Max)*0.5);
if PolygonSphereDistance<-PolygonSphereRadius then begin
aBackList.Add(PolygonNode);
end else if PolygonSphereDistance>PolygonSphereRadius then begin
aFrontList.Add(PolygonNode);
end else begin
PolygonOrientation:=0;
if length(VertexOrientations)<CountPolygonVertices then begin
SetLength(VertexOrientations,(CountPolygonVertices*3) shr 1);
end;
for IndexA:=0 to CountPolygonVertices-1 do begin
VertexOrientation:=EpsilonSignToOrientation[(TpvCSGBSP.EpsilonSign(aPlane.DistanceTo(Vertices^.Items[Polygon^.Indices.Items[IndexA]].Position))+1) and 3];
PolygonOrientation:=PolygonOrientation or VertexOrientation;
VertexOrientations[IndexA]:=VertexOrientation;
end;
case PolygonOrientation of
Coplanar:begin
if aPlane.Normal.Dot(TPlane.Create(Vertices^.Items[Polygon^.Indices.Items[0]].Position,
Vertices^.Items[Polygon^.Indices.Items[1]].Position,
Vertices^.Items[Polygon^.Indices.Items[2]].Position).Normal)<0.0 then begin
aCoplanarBackList.Add(PolygonNode);
end else begin
aCoplanarFrontList.Add(PolygonNode);
end;
end;
Front:begin
aFrontList.Add(PolygonNode);
end;
Back:begin
aBackList.Add(PolygonNode);
end;
else {Spanning:}begin
BackVertexIndices.Count:=0;
FrontVertexIndices.Count:=0;
for IndexA:=0 to CountPolygonVertices-1 do begin
IndexB:=IndexA+1;
if IndexB>=CountPolygonVertices then begin
IndexB:=0;
end;
VertexIndex:=Polygon^.Indices.Items[IndexA];
VertexA:=@Vertices^.Items[VertexIndex];
VertexOrientationA:=VertexOrientations[IndexA];
VertexOrientationB:=VertexOrientations[IndexB];
if VertexOrientationA<>Front then begin
BackVertexIndices.Add(VertexIndex);
end;
if VertexOrientationA<>Back then begin
FrontVertexIndices.Add(VertexIndex);
end;
if (VertexOrientationA or VertexOrientationB)=Spanning then begin
VertexB:=@Vertices^.Items[Polygon^.Indices.Items[IndexB]];
VertexIndex:=Vertices^.Add(VertexA^.Lerp(VertexB^,-(aPlane.DistanceTo(VertexA^.Position)/aPlane.Normal.Dot(VertexB^.Position-VertexA^.Position))));
BackVertexIndices.Add(VertexIndex);
FrontVertexIndices.Add(VertexIndex);
end;
end;
if BackVertexIndices.Count>2 then begin
fTree.fMesh.RemoveNearDuplicateIndices(BackVertexIndices);
if BackVertexIndices.Count>2 then begin
aBackList.Add(PolygonNode.AddPolygonIndices(BackVertexIndices));
end;
end;
if FrontVertexIndices.Count>2 then begin
fTree.fMesh.RemoveNearDuplicateIndices(FrontVertexIndices);
if FrontVertexIndices.Count>2 then begin
aFrontList.Add(PolygonNode.AddPolygonIndices(FrontVertexIndices));
end;
end;
end;
end;
end;
end;
end;
end;
end;
finally
JobQueue.Finalize;
end;
finally
FrontVertexIndices.Finalize;
end;
finally
BackVertexIndices.Finalize;
end;
finally
VertexOrientations:=nil;
end;
end;
{ TpvCSGBSP.TTree.TNode }
constructor TpvCSGBSP.TDualTree.TNode.Create(const aTree:TDualTree);
begin
inherited Create;
fTree:=aTree;
fPolygonNodes.Initialize;
fBack:=nil;
fFront:=nil;
end;
destructor TpvCSGBSP.TDualTree.TNode.Destroy;
type TJobStack=TDynamicStack<TDualTree.TNode>;
var JobStack:TJobStack;
Node:TDualTree.TNode;
begin
fPolygonNodes.Finalize;
if assigned(fFront) or assigned(fBack) then begin
JobStack.Initialize;
try
JobStack.Push(self);
while JobStack.Pop(Node) do begin
if assigned(Node.fFront) then begin
JobStack.Push(Node.fFront);
Node.fFront:=nil;
end;
if assigned(Node.fBack) then begin
JobStack.Push(Node.fBack);
Node.fBack:=nil;
end;
if Node<>self then begin
FreeAndNil(Node);
end;
end;
finally
JobStack.Finalize;
end;
end;
inherited Destroy;
end;
procedure TpvCSGBSP.TDualTree.TNode.Invert;
type TJobStack=TDynamicStack<TDualTree.TNode>;
var JobStack:TJobStack;
Node,TempNode:TDualTree.TNode;
begin
JobStack.Initialize;
try
JobStack.Push(self);
while JobStack.Pop(Node) do begin
Node.fPlane:=Node.fPlane.Flip;
TempNode:=Node.fBack;
Node.fBack:=Node.fFront;
Node.fFront:=TempNode;
if assigned(Node.fFront) then begin
JobStack.Push(Node.fFront);
end;
if assigned(Node.fBack) then begin
JobStack.Push(Node.fBack);
end;
end;
finally
JobStack.Finalize;
end;
end;
procedure TpvCSGBSP.TDualTree.TNode.ClipPolygons(const aPolygonNodes:TPolygonNodeList;const aAlsoRemoveCoplanarFront:boolean=false);
type TJobStackItem=record
Node:TDualTree.TNode;
PolygonNodes:TPolygonNodeList;
end;
TJobStack=TDynamicStack<TJobStackItem>;
var JobStack:TJobStack;
JobStackItem,NewJobStackItem,FrontJobStackItem,BackJobStackItem:TJobStackItem;
Index,Count:TpvSizeInt;
CoplanarFrontNodes:PPolygonNodeList;
PolygonNode:TPolygonNode;
BackIndices:PIndexList;
begin
JobStack.Initialize;
try
NewJobStackItem.Node:=self;
NewJobStackItem.PolygonNodes:=aPolygonNodes;
JobStack.Push(NewJobStackItem);
while JobStack.Pop(JobStackItem) do begin
try
if JobStackItem.Node.fPlane.OK then begin
BackJobStackItem.PolygonNodes.Initialize;
try
FrontJobStackItem.PolygonNodes.Initialize;
try
if aAlsoRemoveCoplanarFront then begin
CoplanarFrontNodes:=@BackJobStackItem.PolygonNodes;
end else begin
CoplanarFrontNodes:=@FrontJobStackItem.PolygonNodes;
end;
for Index:=0 to JobStackItem.PolygonNodes.Count-1 do begin
PolygonNode:=JobStackItem.PolygonNodes.Items[Index];
if not PolygonNode.fRemoved then begin
PolygonNode.SplitByPlane(JobStackItem.Node.Plane,
BackJobStackItem.PolygonNodes,
CoplanarFrontNodes^,
BackJobStackItem.PolygonNodes,
FrontJobStackItem.PolygonNodes);
end;
end;
if assigned(JobStackItem.Node.fBack) and (BackJobStackItem.PolygonNodes.Count>0) then begin
BackJobStackItem.Node:=JobStackItem.Node.fBack;
JobStack.Push(BackJobStackItem);
end else begin
for Index:=0 to BackJobStackItem.PolygonNodes.Count-1 do begin
BackJobStackItem.PolygonNodes.Items[Index].Remove;
end;
end;
if assigned(JobStackItem.Node.fFront) and (FrontJobStackItem.PolygonNodes.Count>0) then begin
FrontJobStackItem.Node:=JobStackItem.Node.fFront;
JobStack.Push(FrontJobStackItem);
end;
finally
FrontJobStackItem.PolygonNodes.Finalize;
end;
finally
BackJobStackItem.PolygonNodes.Finalize;
end;
end;
finally
JobStackItem.PolygonNodes.Finalize;
end;
end;
finally
JobStack.Finalize;
end;
end;
procedure TpvCSGBSP.TDualTree.TNode.ClipTo(const aTree:TDualTree;const aAlsoRemoveCoplanarFront:boolean=false);
type TJobStack=TDynamicStack<TDualTree.TNode>;
var JobStack:TJobStack;
Node:TDualTree.TNode;
begin
JobStack.Initialize;
try
JobStack.Push(self);
while JobStack.Pop(Node) do begin
aTree.fRootNode.ClipPolygons(Node.fPolygonNodes,aAlsoRemoveCoplanarFront);
if assigned(Node.fFront) then begin
JobStack.Push(Node.fFront);
end;
if assigned(Node.fBack) then begin
JobStack.Push(Node.fBack);
end;
end;
finally
JobStack.Finalize;
end;
end;
function TpvCSGBSP.TDualTree.TNode.FindSplitPlane(const aPolygonNodes:TPolygonNodeList):TPlane;
var Index,OtherIndex,Count,
CountPolygonsSplits,
CountBackPolygons,CountFrontPolygons,CountSum,
BestCountBackPolygons,BestCountFrontPolygons,BestCountSum:TpvSizeInt;
Polygon:PPolygon;
Score,BestScore:TFloat;
Plane:TPlane;
SplitSettings:PSplitSettings;
NoScoring,DoRandomPicking:boolean;
Vertices:PVertexList;
begin
SplitSettings:=@fTree.fSplitSettings;
Vertices:=@fTree.fMesh.fVertices;
if IsZero(SplitSettings^.SearchBestFactor) or (SplitSettings^.SearchBestFactor<=0.0) then begin
if aPolygonNodes.Count>0 then begin
if SplitSettings^.SearchBestFactor<0.0 then begin
Index:=Random(aPolygonNodes.Count);
if Index>=aPolygonNodes.Count then begin
Index:=0;
end;
end else begin
Index:=0;
end;
Polygon:=@aPolygonNodes.Items[Index].fPolygon;
result:=TPlane.Create(Vertices^.Items[Polygon^.Indices.Items[0]].Position,
Vertices^.Items[Polygon^.Indices.Items[1]].Position,
Vertices^.Items[Polygon^.Indices.Items[2]].Position);
end else begin
result:=TPlane.CreateEmpty;
end;
exit;
{ Count:=1;
DoRandomPicking:=false;}
end else if SameValue(SplitSettings^.SearchBestFactor,1.0) or (SplitSettings^.SearchBestFactor>=1.0) then begin
Count:=aPolygonNodes.Count;
DoRandomPicking:=false;
end else begin
Count:=Min(Max(round(aPolygonNodes.Count*SplitSettings^.SearchBestFactor),1),aPolygonNodes.Count);
DoRandomPicking:=true;
end;
result:=TPlane.CreateEmpty;
BestScore:=Infinity;
BestCountBackPolygons:=High(TpvSizeInt);
BestCountFrontPolygons:=High(TpvSizeInt);
BestCountSum:=High(TpvSizeInt);
NoScoring:=IsZero(SplitSettings^.PolygonSplitCost) and IsZero(SplitSettings^.PolygonImbalanceCost);
for Index:=0 to Count-1 do begin
if DoRandomPicking then begin
OtherIndex:=Random(aPolygonNodes.Count);
if OtherIndex>=aPolygonNodes.Count then begin
OtherIndex:=0;
end;
end else begin
OtherIndex:=Index;
end;
Polygon:=@aPolygonNodes.Items[OtherIndex].fPolygon;
Plane:=TPlane.Create(Vertices^.Items[Polygon^.Indices.Items[0]].Position,
Vertices^.Items[Polygon^.Indices.Items[1]].Position,
Vertices^.Items[Polygon^.Indices.Items[2]].Position);
CountPolygonsSplits:=0;
CountBackPolygons:=0;
CountFrontPolygons:=0;
for OtherIndex:=0 to aPolygonNodes.Count-1 do begin
aPolygonNodes.Items[OtherIndex].DrySplitByPlane(Plane,CountPolygonsSplits,CountBackPolygons,CountFrontPolygons,CountBackPolygons,CountFrontPolygons);
end;
if NoScoring then begin
CountSum:=CountBackPolygons+CountFrontPolygons;
if (Index=0) or
((BestCountSum>CountSum) or
((BestCountSum=CountSum) and
(abs(BestCountBackPolygons-BestCountFrontPolygons)>abs(CountBackPolygons-CountFrontPolygons)))) then begin
BestCountBackPolygons:=CountBackPolygons;
BestCountFrontPolygons:=CountFrontPolygons;
BestCountSum:=CountSum;
result:=Plane;
end;
end else begin
Score:=(CountPolygonsSplits*SplitSettings^.PolygonSplitCost)+
(abs(CountBackPolygons-CountFrontPolygons)*SplitSettings^.PolygonImbalanceCost);
if (Index=0) or (BestScore>Score) then begin
BestScore:=Score;
result:=Plane;
end;
end;
end;
end;
procedure TpvCSGBSP.TDualTree.TNode.AddPolygonNodes(const aPolygonNodes:TPolygonNodeList);
type TJobStackItem=record
Node:TDualTree.TNode;
PolygonNodes:TPolygonNodeList;
end;
TJobStack=TDynamicStack<TJobStackItem>;
var Index:TpvSizeInt;
JobStack:TJobStack;
JobStackItem,NewJobStackItem,BackJobStackItem,FrontJobStackItem:TJobStackItem;
begin
JobStack.Initialize;
try
BackJobStackItem.PolygonNodes.Initialize;
try
FrontJobStackItem.PolygonNodes.Initialize;
try
NewJobStackItem.Node:=self;
NewJobStackItem.PolygonNodes:=aPolygonNodes;
JobStack.Push(NewJobStackItem);
while JobStack.Pop(JobStackItem) do begin
if JobStackItem.PolygonNodes.Count>0 then begin
//write(#13,JobStackItem.PolygonNodes.Count:10);
if not JobStackItem.Node.fPlane.OK then begin
JobStackItem.Node.fPlane:=FindSplitPlane(JobStackItem.PolygonNodes);
end;
BackJobStackItem.PolygonNodes.Count:=0;
FrontJobStackItem.PolygonNodes.Count:=0;
for Index:=0 to JobStackItem.PolygonNodes.Count-1 do begin
JobStackItem.PolygonNodes.Items[Index].SplitByPlane(JobStackItem.Node.Plane,
BackJobStackItem.PolygonNodes,
JobStackItem.Node.fPolygonNodes,
BackJobStackItem.PolygonNodes,
FrontJobStackItem.PolygonNodes);
end;
if FrontJobStackItem.PolygonNodes.Count>0 then begin
if not assigned(JobStackItem.Node.fFront) then begin
JobStackItem.Node.fFront:=TDualTree.TNode.Create(fTree);
end;
FrontJobStackItem.Node:=JobStackItem.Node.fFront;
JobStack.Push(FrontJobStackItem);
end;
if BackJobStackItem.PolygonNodes.Count>0 then begin
if not assigned(JobStackItem.Node.fBack) then begin
JobStackItem.Node.fBack:=TDualTree.TNode.Create(fTree);
end;
BackJobStackItem.Node:=JobStackItem.Node.fBack;
JobStack.Push(BackJobStackItem);
end;
end;
end;
finally
FrontJobStackItem.PolygonNodes.Finalize;
end;
finally
BackJobStackItem.PolygonNodes.Finalize;
end;
finally
JobStack.Finalize;
end;
end;
procedure TpvCSGBSP.TDualTree.TNode.AddIndices(const aIndices:TIndexList);
begin
end;
{ TpvCSGBSP.TTree }
constructor TpvCSGBSP.TDualTree.Create(const aMesh:TMesh;const aSplitSettings:PSplitSettings=nil);
begin
inherited Create;
fMesh:=aMesh;
if assigned(aSplitSettings) then begin
fSplitSettings:=aSplitSettings^;
end else begin
fSplitSettings:=DefaultSplitSettings;
end;
fFirstPolygonNode:=nil;
fLastPolygonNode:=nil;
fPolygonRootNode:=TDualTree.TPolygonNode.Create(self,nil);
fRootNode:=TDualTree.TNode.Create(self);
end;
destructor TpvCSGBSP.TDualTree.Destroy;
begin
while assigned(fLastPolygonNode) do begin
fLastPolygonNode.Free;
end;
fPolygonRootNode:=nil;
FreeAndNil(fRootNode);
inherited Destroy;
end;
procedure TpvCSGBSP.TDualTree.Invert;
begin
fMesh.Invert;
fPolygonRootNode.Invert;
fRootNode.Invert;
end;
procedure TpvCSGBSP.TDualTree.ClipTo(const aWithTree:TDualTree;const aAlsoRemoveCoplanarFront:boolean=false);
begin
fRootNode.ClipTo(aWithTree,aAlsoRemoveCoplanarFront);
end;
procedure TpvCSGBSP.TDualTree.AddPolygons(const aPolygons:TPolygonList);
var Index:TpvSizeInt;
PolygonNodes:TPolygonNodeList;
begin
PolygonNodes.Initialize;
try
for Index:=0 to aPolygons.Count-1 do begin
PolygonNodes.Add(fPolygonRootNode.AddPolygon(aPolygons.Items[Index]));
end;
fRootNode.AddPolygonNodes(PolygonNodes);
finally
PolygonNodes.Finalize;
end;
end;
procedure TpvCSGBSP.TDualTree.AddIndices(const aIndices:TIndexList);
var Index,Count,CountPolygonVertices:TpvSizeInt;
Polygon:TPolygon;
Polygons:TPolygonList;
begin
Polygons.Initialize;
try
Index:=0;
Count:=aIndices.Count;
while Index<Count do begin
case fMesh.fMode of
TMesh.TMode.Triangles:begin
CountPolygonVertices:=3;
end;
else {TMesh.TMode.Polygons:}begin
CountPolygonVertices:=aIndices.Items[Index];
inc(Index);
end;
end;
if CountPolygonVertices>2 then begin
if (Index+(CountPolygonVertices-1))<Count then begin
Polygon.Indices.Initialize;
Polygon.Indices.AddRangeFrom(aIndices,Index,CountPolygonVertices);
Polygons.Add(Polygon);
end;
end;
inc(Index,CountPolygonVertices);
end;
AddPolygons(Polygons);
finally
Polygons.Finalize;
end;
end;
procedure TpvCSGBSP.TDualTree.GetPolygons(var aPolygons:TPolygonList);
type TJobQueue=TDynamicQueue<TPolygonNode>;
var Index:TpvSizeInt;
JobQueue:TJobQueue;
PolygonNode:TPolygonNode;
begin
JobQueue.Initialize;
try
JobQueue.Enqueue(fPolygonRootNode);
while JobQueue.Dequeue(PolygonNode) do begin
if not PolygonNode.fRemoved then begin
if PolygonNode.fPolygon.Indices.Count>0 then begin
aPolygons.Add(PolygonNode.fPolygon);
end else begin
PolygonNode:=PolygonNode.fFirstChild;
while assigned(PolygonNode) do begin
if not PolygonNode.fRemoved then begin
JobQueue.Enqueue(PolygonNode);
end;
PolygonNode:=PolygonNode.fParentNext;
end;
end;
end;
end;
finally
JobQueue.Finalize;
end;
end;
procedure TpvCSGBSP.TDualTree.GetIndices(var aIndices:TIndexList);
var PolygonIndex,IndicesIndex:TpvSizeInt;
Polygons:TPolygonList;
Polygon:PPolygon;
begin
Polygons.Initialize;
try
GetPolygons(Polygons);
case fMesh.fMode of
TMesh.TMode.Triangles:begin
for PolygonIndex:=0 to Polygons.Count-1 do begin
Polygon:=@Polygons.Items[PolygonIndex];
if Polygon^.Indices.Count>2 then begin
for IndicesIndex:=2 to Polygon^.Indices.Count-1 do begin
aIndices.Add([Polygon^.Indices.Items[0],
Polygon^.Indices.Items[IndicesIndex-1],
Polygon^.Indices.Items[IndicesIndex]]);
end;
end;
end;
end;
else {TMesh.TMode.Polygons:}begin
for PolygonIndex:=0 to Polygons.Count-1 do begin
Polygon:=@Polygons.Items[PolygonIndex];
if Polygon^.Indices.Count>2 then begin
aIndices.Add(Polygon^.Indices.Count);
aIndices.Add(Polygon^.Indices);
end;
end;
end;
end;
finally
Polygons.Finalize;
end;
end;
procedure TpvCSGBSP.TDualTree.Merge(const aTree:TDualTree);
var Index,OtherIndex,Offset,Count,CountPolygonVertices:TpvSizeInt;
Polygons:TPolygonList;
Polygon:PPolygon;
PolygonNodes:TPolygonNodeList;
begin
Offset:=fMesh.fVertices.Count;
fMesh.fVertices.Add(aTree.fMesh.fVertices);
Polygons.Initialize;
try
aTree.GetPolygons(Polygons);
for Index:=0 to Polygons.Count-1 do begin
Polygon:=@Polygons.Items[Index];
for OtherIndex:=0 to Polygon^.Indices.Count-1 do begin
inc(Polygon^.Indices.Items[OtherIndex],Offset);
end;
end;
AddPolygons(Polygons);
finally
Polygons.Finalize;
end;
end;
function TpvCSGBSP.TDualTree.ToMesh:TMesh;
begin
result:=TMesh.Create(fMesh.fMode);
try
result.SetVertices(fMesh.fVertices);
GetIndices(result.fIndices);
finally
result.RemoveDuplicateAndUnusedVertices;
end;
end;
end.
|
unit Unit2;
interface
uses
Grids,SysUtils;
Type
Tinf=record
aj: extended;
j: word;
end;
Tsel=^Sel;
Sel=record
inf: Tinf;
a: Tsel;
end;
Tlists=class(TObject)
sp1,sp: Tsel;
Procedure adds(inf: TInf);
Procedure addsj(inf: TInf);
Function readsj(j: word):extended;
Procedure dels;
end;
TmsLists=array [1..1] of TLists;
Tms=class(TLists)
ms:^TmsLists;
m,n: word;
Constructor Create(m0,n0: word);
Destructor Free;
Procedure Add(i,j:word; a:extended);
Procedure Addj(i,j:word; a:extended);
Function Read(i,j:word):extended;
Procedure Print(Stg: TStringGrid);
end;
Tobj=class(Tms)
k: word;
s: extended;
Constructor Create(m0,n0:word);
Procedure Vip;
end;
implementation
Function TLists.readsj;
begin
sp:=sp1;
while (sp<>Nil) and (sp^.inf.j<>j) do
sp:=sp^.a;
if sp=nil then
result:=0
else
result:=sp^.inf.aj;
end;
Procedure TLists.adds;
begin
New(sp);
sp^.inf:=inf;
sp^.a:=sp1;
sp1:=sp;
end;
Procedure TLists.addsj;
var spt: Tsel;
j: word;
begin
New(sp);
sp^.inf:=inf;
if sp1=nil then
begin
sp1:=sp;
sp1^.a:=nil;
end
else
if sp1^.inf.j>=inf.j then
begin
sp^.a:=sp1;
sp1:=sp;
end
else
begin
spt:=sp1;
while (spt^.a<>nil) and (spt^.a^.inf.j<inf.j) do
spt:=spt^.a;
sp^.a:=spt^.a;
spt^.a:=sp;
end;
end;
Procedure Tlists.dels;
begin
sp:=sp1;
sp1:=sp1^.a;
Dispose(sp);
end;
//Tms
Constructor Tms.Create;
var i: word;
begin
m:=m0;
n:=n0;
Inherited Create;
GetMem(ms,4*m);
for i:=1 to m do
begin
ms[i]:=TLists.Create;
ms[i].sp1:=nil;
end;
end;
Destructor Tms.Free;
var i: word;
begin
for i:=1 to m do
while ms[i].sp1<>nil do
ms[i].dels;
FreeMem(ms,4*m);
end;
Procedure Tms.add;
Var inf: Tinf;
begin
inf.aj:=a;
inf.j:=j;
ms[i].adds(inf);
end;
Procedure Tms.addj;
var inf:Tinf;
begin
inf.aj:=a;
inf.j:=j;
ms[i].addsj(inf);
end;
Function Tms.read;
Var inf:Tinf;
begin
result:=ms[i].readsj(j);
end;
Procedure Tms.Print;
Var i,j:word;
begin
for i:=1 to m do
for j:=1 to n do
StG.Cells[j,i]:=FloatToStr(ms[i].readsj(j))
end;
//TObj
Constructor Tobj.Create;
begin
Inherited Create(m0,n0);
k:=0;
s:=0;
end;
Procedure Tobj.vip;
var i: word;
sp: TSel;
begin
k:=0;
s:=0;
for i:=1 to m do
begin
sp:=ms[i].sp1;
while sp<>Nil do
begin
if sp^.inf.aj<>0 then
begin
inc(k);
s:=s+sp^.inf.aj;
end;
sp:=sp^.a;
end;
end;
s:=s/k;
end;
end.
|
{*******************************************************************************
* *
* PentireFMX *
* *
* https://github.com/gmurt/PentireFMX *
* *
* Copyright 2020 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* 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 forthe specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
unit ksTabControl;
interface
uses
Classes, FMX.Types, FMX.Controls, FMX.Graphics, Types, System.UITypes,
FMX.StdCtrls, System.Generics.Collections, FMX.Objects,
System.UIConsts, FMX.Layouts;
type
TksTabControl = class;
TksTabItem = class;
TksTabBarTheme = (ksTbCustom, ksTbLightTabs, ksTbDarkTabs);
TksTabBarPosition = (ksTbpBottom, ksTbpNone, ksTbpTop);
TksTabBarHighlightStyle = (ksTbHighlightSingleColor, ksTbHighlightFullColour);
TksTabBarClickTabEvent = procedure(Sender: TObject; ATab: TksTabItem) of object;
TksTabItemIcon = (Custom, AlarmClock, BarChart, Barcode, Bell, BookCover, BookCoverMinus, BookCoverPlus, BookMark, BookOpen,
Calendar, Camera, Car, Clock, CloudDownload, CloudUpload, Cross, Document, Download, Earth, Email,
Fax, FileList, FileMinus, FilePlus, Files, FileStar, FileTick, Flag, Folder, FolderMinus,
FolderPlus, FolderStar, Home, Inbox, Incoming, ListBullets, ListCheckBoxes, ListImages, ListNumbered, ListTicked,
Location, More, Note, Outgoing,
PaperClip, Photo, PieChart, Pin, Presentation, Search, Settings, Share, ShoppingCart, Spanner, Speaker,
Star, Tablet, Tag, Telephone, Telephone2, TelephoneBook, Tick, Timer, Trash, Upload,
User, UserEdit, UserGroup, Users, UserSearch,
VideoCamera, VideoPlayer, Viewer,
Wifi, Window, Write);
TksTabBarAppearence = class(TPersistent)
private
[weak]FTabControl: TksTabControl;
FSelected: TAlphaColor;
FNormal: TAlphaColor;
FBackground: TAlphaColor;
FBadgeColor: TAlphaColor;
FTheme: TksTabBarTheme;
FSelectedBackground: TAlphaColor;
procedure SetColours(ASelected, ANormal, ABackground, ASelectedBackground, ABadge: TAlphaColor);
procedure SetBackground(const Value: TAlphaColor);
procedure SetNormal(const Value: TAlphaColor);
procedure SetSelected(const Value: TAlphaColor);
procedure SetTheme(const Value: TksTabBarTheme);
procedure Changed;
procedure SetBadgeColor(const Value: TAlphaColor);
procedure SetSelectedBackground(const Value: TAlphaColor);
public
constructor Create(ATabControl: TksTabControl);
published
property SelectedColor: TAlphaColor read FSelected write SetSelected default claDodgerblue;
property NormalColor: TAlphaColor read FNormal write SetNormal default claGray;
property BackgroundColor: TAlphaColor read FBackground write SetBackground default $FFEEEEEE;
property SelectedBackgroundColor: TAlphaColor read FSelectedBackground write SetSelectedBackground default claWhite;
property BadgeColor: TAlphaColor read FBadgeColor write SetBadgeColor default claDodgerblue;
property Theme: TksTabBarTheme read FTheme write SetTheme default ksTbLightTabs;
end;
TksTabItem = class(TControl)
private
FIcon: TBitmap;
FIconType: TksTabItemIcon;
FBackground: TAlphaColor;
FTabIndex: integer;
FText: string;
FBadgeValue: integer;
FBadge: TBitmap;
FHighlightStyle: TksTabBarHighlightStyle;
procedure SetText(const Value: string);
procedure SetBadgeValue(const Value: integer);
procedure UpdateTabs;
procedure SetIcon(const Value: TBitmap);
procedure SetIconType(const Value: TksTabItemIcon);
procedure SetTabIndex(const Value: integer);
procedure SetHighlightStyle(const Value: TksTabBarHighlightStyle);
procedure FadeOut(ADuration: single);
procedure FadeIn(ADuration: single);
procedure SetBackground(const Value: TAlphaColor);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeforeDestruction; override;
procedure DrawTab(ACanvas: TCanvas; AIndex: integer; ARect: TRectF);
procedure RedrawBadge;
published
property Text: string read FText write SetText;
property BadgeValue: integer read FBadgeValue write SetBadgeValue default 0;
property Icon: TBitmap read FIcon write SetIcon;
property StandardIcon: TksTabItemIcon read FIconType write SetIconType;
property TabIndex: integer read FTabIndex write SetTabIndex;// stored False;
property HitTest;
property HighlightStyle: TksTabBarHighlightStyle read FHighlightStyle write SetHighlightStyle default ksTbHighlightSingleColor;
property Background: TAlphaColor read FBackground write SetBackground default claWhite;
end;
TksTabItemList = class(TObjectList<TksTabItem>)
private
[weak]FTabControl: TksTabControl;
protected
procedure Notify(const Value: TksTabItem; Action: TCollectionNotification); override;
public
constructor Create(ATabControl: TksTabControl);
end;
TksTabBar = class(TControl)
private
[weak]FTabControl: TksTabControl;
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
public
constructor Create(AOwner: TComponent); override;
property Width;
property Height;
property Position;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TksTabControl = class(TControl, IItemsContainer)
private
FTabBar: TksTabBar;
FTabIndex: integer;
FTabs: TksTabItemList;
FAppearence: TksTabBarAppearence;
FBeforeChange: TNotifyEvent;
FOnChange: TNotifyEvent;
FOnClickTab: TksTabBarClickTabEvent;
FTabPosition: TksTabBarPosition;
FHasIOSHomeBar: Boolean;
procedure SetTabIndex(const Value: integer);
function GetTabRect(AIndex: integer): TRectF;
function GetTabIndexFromXPos(AXPos: single): integer;
function GetTabFromXPos(AXPos: single): TksTabItem;
function GetTabCount: integer;
function GetActiveTab: TksTabItem;
function GetSelectedTab: TksTabItem;
procedure SetTabBarPosition(const Value: TksTabBarPosition);
procedure SetActiveTab(const Value: TksTabItem);
function GetNextTabName: string;
procedure SetHasIosHomeBar(const Value: Boolean);
protected
procedure DoRealign; override;
procedure Resize; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure Paint; override;
procedure DoAddObject(const AObject: TFmxObject); override;
function GetItemsCount: Integer;
function GetItem(const AIndex: Integer): TFmxObject;
procedure DoClickTab(ATab: TksTabItem);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UpdateTabs;
function AddTab: TksTabItem;
function GetTabBarHeight: integer;
procedure PrevTab;
procedure NextTab;
property ActiveTab: TksTabItem read GetActiveTab write SetActiveTab;
property Tabs: TksTabItemList read FTabs;
property SelectedTab: TksTabItem read GetSelectedTab;
procedure FadeToNextTab(const ADelaySeconds: single = 0.5);
procedure FadeToPrevTab(const ADelaySeconds: single = 0.5);
procedure FadeToTab(ATab: TksTabItem; const ADelaySeconds: single = 0.5);
published
property Align;
property Appearence: TksTabBarAppearence read FAppearence write FAppearence;
property TabIndex: integer read FTabIndex write SetTabIndex default -1;
property Margins;
property Position;
property Width;
property Size;
property HasIosHomeBar: Boolean read FHasIOSHomeBar write SetHasIosHomeBar default False;
property Height;
property Opacity;
property TabPosition: TksTabBarPosition read FTabPosition write SetTabBarPosition default ksTbpBottom;
property Visible;
// events
property BeforeChange: TNotifyEvent read FBeforeChange write FBeforeChange;
property OnResize;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnClickTab: TksTabBarClickTabEvent read FOnClickTab write FOnClickTab;
end;
{$R *.dcr}
{$R glyphs.res}
procedure Register;
implementation
uses SysUtils, Math, FMX.Forms, TypInfo, FMX.Ani, FMX.Utils, FMX.Platform;
var
AScreenScale: single;
procedure Register;
begin
RegisterComponents('Pentire FMX', [TksTabControl]);
end;
function GetScreenScale: single;
var
Service: IFMXScreenService;
begin
if AScreenScale > 0 then
begin
Result := AScreenScale;
Exit;
end
else
begin
Service := IFMXScreenService(TPlatformServices.Current.GetPlatformService(IFMXScreenService));
Result := Service.GetScreenScale;
{$IFDEF IOS}
if Result < 2 then
Result := 2;
AScreenScale := Result;
{$ENDIF}
end;
{$IFDEF ANDROID}
AScreenScale := Result;
{$ENDIF}
end;
procedure ReplaceOpaqueColor(ABmp: TBitmap; Color : TAlphaColor);
var
AMap: TBitmapData;
PixelColor: TAlphaColor;
PixelWhiteColor: TAlphaColor;
C: PAlphaColorRec;
begin
TThread.Synchronize(TThread.CurrentThread,procedure
var
x,y: Integer;
begin
if (Assigned(ABmp)) then
begin
if ABmp.Map(TMapAccess.ReadWrite, AMap) then
try
AlphaColorToPixel(Color , @PixelColor, AMap.PixelFormat);
AlphaColorToPixel(claWhite, @PixelWhiteColor, AMap.PixelFormat);
for y := 0 to ABmp.Height - 1 do
begin
for x := 0 to ABmp.Width - 1 do
begin
C := @PAlphaColorArray(AMap.Data)[y * (AMap.Pitch div 4) + x];
if (C^.Color<>claWhite) and (C^.A>0) then
C^.Color := PremultiplyAlpha(MakeColor(PixelColor, C^.A / $FF));
end;
end;
finally
ABmp.Unmap(AMap);
end;
end;
end);
end;
{ TksTabSheTksTabItemet }
procedure TksTabItem.BeforeDestruction;
begin
inherited;
if (Parent is TksTabControl) then
TksTabControl(Parent).Tabs.Remove(Self);
end;
constructor TksTabItem.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIcon := TBitmap.Create;
ClipChildren := True;
Stored := True;
Locked := True;
Text := Name;
FHighlightStyle := ksTbHighlightSingleColor;
FBackground := claWhite;
FBadgeValue := 0;
end;
destructor TksTabItem.Destroy;
begin
FreeAndNil(FIcon);
inherited;
end;
procedure TksTabItem.DrawTab(ACanvas: TCanvas; AIndex: integer; ARect: TRectF);
procedure DrawEllipse(ACanvas: TCanvas; ARect: TRectF; AColor: TAlphaColor);
begin
ACanvas.Fill.Color := AColor;
ACanvas.FillEllipse(ARect, 1);
ACanvas.Stroke.Color := AColor;
ACanvas.Stroke.Thickness := 1;
ACanvas.DrawEllipse(ARect, 1);
end;
var
AAppearence: TksTabBarAppearence;
ABmp: TBitmap;
ADestRect: TRectF;
r: TRectF;
ABadgeRect: TRectF;
begin
r := ARect;
AAppearence := TksTabControl(Parent).Appearence;
ACanvas.Fill.Color := AAppearence.NormalColor;
if AIndex = TksTabControl(Parent).TabIndex then
begin
ACanvas.Fill.Color := AAppearence.SelectedBackgroundColor;
ACanvas.FillRect(r, 0, 0, AllCorners, 1);
ACanvas.Fill.Color := AAppearence.SelectedColor;
end;
r.Bottom := 50;
InflateRect(r, 0, -3);
ACanvas.Font.Size := 10;
ACanvas.FillText(r, FText, False, 1, [], TTextAlign.Center, TTextAlign.Trailing);
InflateRect(r, 0, -3);
ADestRect := RectF(0, 0, 25, 25);
OffsetRect(ADestRect, ARect.Left + ((ARect.Width - ADestRect.Width) / 2), 6);
ABmp := TBitmap.Create;
try
ABmp.Assign(FIcon);
if FHighlightStyle = ksTbHighlightSingleColor then
begin
// single colour selected/unselected icons...
if (AIndex = TksTabControl(Parent).TabIndex) then
ReplaceOpaqueColor(ABmp, AAppearence.SelectedColor)
else
ReplaceOpaqueColor(ABmp, AAppearence.NormalColor);
end
else
begin
// single colour selected/unselected icons...
if (AIndex <> TksTabControl(Parent).TabIndex) then
ReplaceOpaqueColor(ABmp, AAppearence.NormalColor);
end;
ACanvas.DrawBitmap(ABmp, RectF(0,0,ABmp.Width,ABmp.Height), ADestRect, 1, True);
if (FBadgeValue <> 0) and (FBadge <> nil) then
begin
ABadgeRect := RectF(ADestRect.Left, ADestRect.Top, ADestRect.Left+ 16, ADestRect.Top+16);
OffsetRect(ABadgeRect, ADestRect.Width-7, -2);
ACanvas.DrawBitmap(FBadge, RectF(0, 0, FBadge.Width, FBadge.Height), ABadgeRect, 1);
ACanvas.Fill.Color := claWhite;
ACanvas.Font.Size := 10;
if FBadgeValue > 0 then
ACanvas.FillText(ABadgeRect, IntToStr(FBadgeValue), False, 1, [], TTextAlign.Center);
end;
finally
FreeAndNil(ABmp);
end;
end;
procedure TksTabItem.FadeIn(ADuration: single);
begin
TAnimator.AnimateFloatWait(Self, 'Opacity', 1, ADuration);
end;
procedure TksTabItem.FadeOut(ADuration: single);
begin
TAnimator.AnimateFloatWait(Self, 'Opacity', 0, ADuration);
end;
procedure TksTabItem.RedrawBadge;
//var
// s: single;
begin
{ if FBadgeValue = 0 then
FreeAndNil(FBadge)
else
begin
s := GetScreenScale;
FBadge := TBitmap.Create(Round(32*s), Round(32*s));
FBadge.Clear(claNull);
//FBadge.Canvas.Fill.Color := claRed;
FBadge.Canvas.Fill.Kind := TBrushKind.Solid;
FBadge.Canvas.FillEllipse(RectF(0, 0, FBadge.Width, FBadge.Height), 1);
end; }
end;
procedure TksTabItem.SetIconType(const Value: TksTabItemIcon);
var
AStream: TResourceStream;
AEnumName: String;
begin
if Value <> TksTabItemIcon.Custom then
begin
AEnumName := GetENumName(TypeInfo(TksTabItemIcon), Ord(Value));
AStream := TResourceStream.Create(HInstance, AEnumName, RT_RCDATA);
try
FIcon.LoadFromStream(AStream);
finally
AStream.Free;
end;
FHighlightStyle := TksTabBarHighlightStyle.ksTbHighlightSingleColor;
end;
FIconType := Value;
UpdateTabs;
end;
procedure TksTabItem.SetBackground(const Value: TAlphaColor);
begin
if FBackground <> Value then
begin
FBackground := Value;
TksTabControl(Parent).Repaint;
end;
end;
procedure TksTabItem.SetBadgeValue(const Value: integer);
begin
if FBadgeValue <> Value then
begin
FBadgeValue := Value;
RedrawBadge;
UpdateTabs;
end;
end;
procedure TksTabItem.SetHighlightStyle(const Value: TksTabBarHighlightStyle);
begin
if FHighlightStyle <> Value then
begin
FHighlightStyle := Value;
UpdateTabs;
end;
end;
procedure TksTabItem.SetIcon(const Value: TBitmap);
begin
FIcon.Assign(Value);
FIconType := TksTabItemIcon.Custom;
UpdateTabs;
end;
procedure TksTabItem.SetTabIndex(const Value: integer);
var
ATabs: TksTabItemList;
ANewIndex: integer;
ICount: integer;
begin
if FTabIndex <> Value then
begin
ATabs := TksTabControl(Parent).Tabs;
ANewIndex := Value;
if ANewIndex < 0 then FTabIndex := 0;
if ANewIndex > ATabs.Count-1 then ANewIndex := ATabs.Count-1;
//ATabs.Move(FTabIndex, ANewIndex);
ATabs.Exchange(FTabIndex, ANewIndex);
for ICount := 0 to ATabs.Count-1 do
ATabs[ICount].FTabIndex := ICount;
UpdateTabs;
end;
end;
procedure TksTabItem.SetText(const Value: string);
begin
if FText <> Value then
begin
FText := Value;
UpdateTabs;
end;
end;
procedure TksTabItem.UpdateTabs;
begin
TksTabControl(Parent).UpdateTabs;
end;
{ TksTabControl }
function TksTabControl.AddTab: TksTabItem;
var
ATab: TksTabItem;
begin
ATab := TksTabItem.Create(Root.GetObject as TForm);
AddObject(ATab);
Result := ATab;
end;
constructor TksTabControl.Create(AOwner: TComponent);
begin
inherited;
FHasIOSHomeBar := False;
FTabs := TksTabItemList.Create(Self);
FTabBar := TksTabBar.Create(Self);
FAppearence := TksTabBarAppearence.Create(Self);
SetAcceptsControls(True);
Size.Height := 250;
Size.Width := 250;
FTabBar.Align := TAlignLayout.Bottom;
FTabPosition := ksTbpBottom;
AddObject(FTabBar);
end;
destructor TksTabControl.Destroy;
begin
FreeAndNil(FTabs);
FAppearence.DisposeOf;
inherited;
end;
procedure TksTabControl.DoAddObject(const AObject: TFmxObject);
var
ATab: TksTabItem;
begin
inherited;
if AObject.ClassType = TksTabItem then
begin
ATab := TksTabItem(AObject);
FTabs.Add(ATab);
if not (csLoading in ComponentState) then
begin
ATab.Name := GetNextTabName;
ATab.Text := ATab.Name;
end;
UpdateTabs;
Exit;
end;
if (SelectedTab <> nil) and (AObject <> FTabBar) then
begin
SelectedTab.AddObject(AObject);
end;
end;
procedure TksTabControl.DoClickTab(ATab: TksTabItem);
begin
if Assigned(FOnClickTab) then
FOnClickTab(Self, ATab);
end;
procedure TksTabControl.DoRealign;
begin
inherited;
UpdateTabs;
Repaint;
end;
function TksTabControl.GetActiveTab: TksTabItem;
begin
if InRange(TabIndex, 0, GetTabCount - 1) then
Result := Tabs[TabIndex]
else
Result := nil;
end;
function TksTabControl.GetItem(const AIndex: Integer): TFmxObject;
begin
Result := Tabs[AIndex];
end;
function TksTabControl.GetItemsCount: Integer;
begin
Result := FTabs.Count;
end;
function TksTabControl.GetNextTabName: string;
var
AIndex: integer;
AForm: TForm;
begin
AForm := (Root.GetObject as TForm);
AIndex := 0;
while AForm.FindComponent('ksTabItem'+IntToStr(AIndex)) <> nil do
Inc(AIndex);
Result := 'ksTabItem'+IntToStr(AIndex);
end;
function TksTabControl.GetSelectedTab: TksTabItem;
begin
Result := nil;
if (FTabIndex > -1) and (FTabIndex <= FTabs.Count-1) then
Result := FTabs[FTabIndex];
end;
function TksTabControl.GetTabBarHeight: integer;
begin
Result := 50;
if FHasIOSHomeBar then
Result := Result + 20;
end;
function TksTabControl.GetTabCount: integer;
begin
Result := 0;
if FTabs <> nil then
Result := FTabs.Count;
end;
function TksTabControl.GetTabFromXPos(AXPos: single): TksTabItem;
var
ICount: integer;
begin
Result := nil;
for ICount := 0 to GetTabCount-1 do
begin
if PtInRect(GetTabRect(ICount), PointF(AXPos, 1)) then
begin
Result := Tabs[ICount];
Exit;
end;
end;
end;
function TksTabControl.GetTabIndexFromXPos(AXPos: single): integer;
var
ICount: integer;
begin
Result := -1;
for ICount := 0 to GetTabCount-1 do
begin
if PtInRect(GetTabRect(ICount), PointF(AXPos, 1)) then
begin
Result := ICount;
Exit;
end;
end;
end;
function TksTabControl.GetTabRect(AIndex: integer): TRectF;
var
AWidth: single;
begin
AWidth := Width / GetTabCount;
Result := RectF(0, 0, AWidth, GetTabBarHeight);
OffsetRect(Result, AWidth * AIndex, 0)
end;
procedure TksTabControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
inherited;
end;
procedure TksTabControl.NextTab;
begin
TabIndex := TabIndex +1;
end;
procedure TksTabControl.Paint;
var
ARect: TRectF;
begin
inherited;
if Locked then
Exit;
Canvas.Fill.Color := FAppearence.BackgroundColor;
if (SelectedTab <> nil) then
begin
Canvas.Fill.Color := FAppearence.BackgroundColor;
if (SelectedTab <> nil) then
begin
if SelectedTab.Background <> claNull then
Canvas.Fill.Color := SelectedTab.Background;
end;
Canvas.Fill.Kind := TBrushKind.Solid;
ARect := ClipRect;
if TabPosition <> TksTabBarPosition.ksTbpNone then
ARect.Bottom := ARect.Bottom - FTabBar.Height;
if SelectedTab.Background <> claNull then
Canvas.Fill.Color := SelectedTab.Background;
end;
Canvas.Fill.Kind := TBrushKind.Solid;
ARect := ClipRect;
if TabPosition <> TksTabBarPosition.ksTbpNone then
ARect.Bottom := ARect.Bottom - FTabBar.Height;
Canvas.FillRect(ARect, 0, 0, AllCorners, 1);
if (csDesigning in ComponentState) then
begin
DrawDesignBorder(claDimgray, claDimgray);
Canvas.Fill.Color := claDimgray;;
Canvas.FillRect(ARect, 0, 0, AllCorners, 1);
if (csDesigning in ComponentState) then
begin
DrawDesignBorder(claDimgray, claDimgray);
Canvas.Fill.Color := claDimgray;;
{$IFDEF MSWINDOWS}
if GetTabCount = 0 then
begin
Canvas.Font.Size := 14;
Canvas.FillText(ClipRect, 'Right-click to add tabs', True, 1, [], TTextAlign.Center);
end;
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
if GetTabCount = 0 then
begin
Canvas.Font.Size := 14;
Canvas.FillText(ClipRect, 'Right-click to add tabs', True, 1, [], TTextAlign.Center);
end;
{$ENDIF}
end;
end;
procedure TksTabControl.PrevTab;
begin
TabIndex := TabIndex -1;
end;
procedure TksTabControl.Resize;
begin
inherited;
UpdateTabs;
Repaint;
end;
procedure TksTabControl.SetActiveTab(const Value: TksTabItem);
begin
if Value <> nil then
begin
TabIndex := Tabs.IndexOf(Value);
end;
end;
procedure TksTabControl.SetHasIosHomeBar(const Value: Boolean);
begin
FHasIOSHomeBar := Value;
FTabBar.Height := GetTabBarHeight;
UpdateTabs;
end;
procedure TksTabControl.FadeToNextTab(const ADelaySeconds: single = 0.5);
begin
if TabIndex < FTabs.Count-1 then
FadeToTab(Tabs[TabIndex+1], ADelaySeconds);
end;
procedure TksTabControl.FadeToPrevTab(const ADelaySeconds: single = 0.5);
begin
if TabIndex > 0 then
FadeToTab(Tabs[TabIndex-1], ADelaySeconds);
end;
procedure TksTabControl.FadeToTab(ATab: TksTabItem; const ADelaySeconds: single = 0.5);
var
APrevTab: TksTabItem;
begin
APrevTab := ActiveTab;
ActiveTab.FadeOut(ADelaySeconds/2);
ATab.Opacity := 0;
ActiveTab := ATab;
ATab.FadeIn(ADelaySeconds/2);
APrevTab.Opacity := 1;
end;
procedure TksTabControl.SetTabBarPosition(const Value: TksTabBarPosition);
begin
if FTabPosition <> Value then
begin
FTabPosition := Value;
UpdateTabs;
end;
end;
procedure TksTabControl.SetTabIndex(const Value: integer);
begin
if (Tabs.Count > 0) and ((Value < 0) or (Value > Tabs.Count-1)) then
Exit;
if FTabIndex <> Value then
begin
if Assigned(FBeforeChange) then
FBeforeChange(Self);
FTabIndex := Value;
UpdateTabs;
if Assigned(FOnChange) then
FOnChange(Self);
end;
end;
procedure TksTabControl.UpdateTabs;
var
ICount: integer;
ATab: TksTabItem;
begin
for ICount := 0 to GetTabCount-1 do
begin
case FTabPosition of
ksTbpBottom: FTabBar.Align := TAlignLayout.Bottom;
ksTbpTop: FTabBar.Align := TAlignLayout.Top;
end;
ATab := Tabs[ICount];
ATab.RedrawBadge;
ATab.FTabIndex := ICount;
ATab.Width := Self.Width;
case FTabPosition of
ksTbpBottom: ATab.Height := Self.Height-GetTabBarHeight;
ksTbpNone: ATab.Height := Self.Height;
ksTbpTop: ATab.Height := Self.Height-50;
end;
ATab.Position.Y := 0;
if FTabPosition = ksTbpTop then
ATab.Position.Y := 50;
ATab.Position.X := 0;
ATab.Visible := (ICount = FTabIndex);
ATab.Realign;
end;
InvalidateRect(ClipRect);
{$IFDEF ANDROID}
Application.ProcessMessages;
{$ENDIF}
end;
{ TksTabBar }
constructor TksTabBar.Create(AOwner: TComponent);
begin
inherited;
FTabControl := (AOwner as TksTabControl);
Size.Height := FTabControl.GetTabBarHeight;
Stored := False;
FDesignInteractive := True;
end;
procedure TksTabBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
ATab: TksTabItem;
begin
inherited;
ATab := TksTabControl(FTabControl).GetTabFromXPos(X);
if ATab.HitTest = False then
Exit;
TksTabControl(Parent).TabIndex := TksTabControl(FTabControl).GetTabIndexFromXPos(X);
{$IFDEF MSWINDOWS}
if (csDesigning in ComponentState) and
(TCommonCustomForm(FTabControl.Owner).Designer <> nil) then
begin
if ATab <> nil then
begin
if ATab.HitTest = False then
Exit;
TCommonCustomForm(FTabControl.Owner).Focused := nil;
TCommonCustomForm(FTabControl.Owner).Designer.SelectComponent(ATab);
TCommonCustomForm(FTabControl.Owner).Designer.Modified;
end;
Repaint;
end;
{$ENDIF}
if (ATab <> nil) then
begin
if ATab.HitTest then
FTabControl.DoClickTab(ATab);
end;
end;
procedure TksTabBar.Paint;
var
AState: TCanvasSaveState;
ICount: integer;
ARect: TRectF;
ATabControl: TksTabControl;
begin
inherited;
if Locked then
Exit;
ATabControl := TksTabControl(FTabControl);
with Canvas do
begin
AState := SaveState;
try
ARect := RectF(0, 0, Size.Width, Size.Height);
if (csDesigning in ComponentState) then
InflateRect(ARect, -1, -1);
IntersectClipRect(ARect);
if FTabControl.TabPosition = ksTbpNone then
Exit;
Fill.Kind := TBrushKind.Solid;
if ATabControl.Appearence.BackgroundColor <> claNull then
Canvas.Clear(ATabControl.Appearence.BackgroundColor);
Stroke.Kind := TBrushKind.Solid;
Stroke.Color := claDimgray;
if (csDesigning in ComponentState) then
DrawDesignBorder(claDimgray, claDimgray);
for ICount := 0 to TksTabControl(FTabControl).GetTabCount-1 do
ATabControl.Tabs[ICount].DrawTab(Canvas, ICount, ATabControl.GetTabRect(ICount));
case ATabControl.TabPosition of
ksTbpBottom: DrawRectSides(ARect, 0, 0, AllCorners,1, [TSide.Top]);
ksTbpTop: DrawRectSides(ARect, 0, 0, AllCorners,1, [TSide.Bottom]);
end;
finally
RestoreState(AState);
Font.Size := 10;
end;
end;
end;
{ TksTabBarAppearence }
procedure TksTabBarAppearence.Changed;
begin
TksTabControl(FTabControl).UpdateTabs;
end;
constructor TksTabBarAppearence.Create(ATabControl: TksTabControl);
begin
inherited Create;
FTabControl := ATabControl;
FSelected := claDodgerblue;
FNormal := claGray;
FBackground := $FFEEEEEE;
FSelectedBackground := claWhite;
FBadgeColor := claDodgerblue;
FTheme := ksTbLightTabs;
end;
procedure TksTabBarAppearence.SetBackground(const Value: TAlphaColor);
begin
if FBackground <> Value then
begin
FBackground := Value;
FTheme := ksTbCustom;
Changed;
end;
end;
procedure TksTabBarAppearence.SetBadgeColor(const Value: TAlphaColor);
begin
if FBadgeColor <> Value then
begin
FBadgeColor := Value;
FTheme := ksTbCustom;
Changed;
end;
end;
procedure TksTabBarAppearence.SetColours(ASelected, ANormal, ABackground, ASelectedBackground, ABadge: TAlphaColor);
begin
FSelected := ASelected;
FNormal := ANormal;
FBackground := ABackground;
FSelectedBackground := ASelectedBackground;
FBadgeColor := ABadge;
end;
procedure TksTabBarAppearence.SetNormal(const Value: TAlphaColor);
begin
if FNormal <> Value then
begin
FNormal := Value;
FTheme := ksTbCustom;
Changed;
end;
end;
procedure TksTabBarAppearence.SetSelected(const Value: TAlphaColor);
begin
if FSelected <> Value then
begin
FSelected := Value;
FTheme := ksTbCustom;
Changed;
end;
end;
procedure TksTabBarAppearence.SetSelectedBackground(const Value: TAlphaColor);
begin
if FSelectedBackground <> Value then
begin
FSelectedBackground := Value;
Changed;
end;
end;
procedure TksTabBarAppearence.SetTheme(const Value: TksTabBarTheme);
begin
if FTheme <> Value then
begin
if Value = ksTbLightTabs then SetColours(claDodgerblue, claGray, $FFEEEEEE, claWhite, claDodgerblue);
if Value = ksTbDarkTabs then SetColours(claWhite, claGray, $FF202020, $FF3C3C3C, claRed);
FTheme := Value;
Changed;
end;
end;
{ TksTabItemList }
constructor TksTabItemList.Create(ATabControl: TksTabControl);
begin
inherited Create(False);
FTabControl := ATabControl;
end;
procedure TksTabItemList.Notify(const Value: TksTabItem; Action: TCollectionNotification);
begin
inherited;
if csDestroying in FTabControl.ComponentState then
Exit;
if (Action = TCollectionNotification.cnRemoved) and (not (csDesigning in FTabControl.ComponentState)) then
begin
Value.DisposeOf;
FTabControl.UpdateTabs;
end;
end;
initialization
RegisterFmxClasses([TksTabControl, TksTabItem]);
AScreenScale := 0;
end.
|
unit RRManagerLicenseConditionTypeEditFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, CommonIDObjectEditFrame, StdCtrls, ExtCtrls, ComCtrls, LicenseZone,
BaseObjects;
type
TfrmLicenseConditionTypeEditFrame = class(TfrmIDObjectEditFrame)
chbxRelativeDates: TCheckBox;
chbxBoundingDates: TCheckBox;
private
{ Private declarations }
protected
procedure FillControls(ABaseObject: TIDObject); override;
procedure ClearControls; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure Save(AObject: TIDObject = nil); override;
end;
var
frmLicenseConditionTypeEditFrame: TfrmLicenseConditionTypeEditFrame;
implementation
uses DateUtils, CommonFrame;
{$R *.dfm}
{ TfrmLicenseConditionTypeEditFrame }
procedure TfrmLicenseConditionTypeEditFrame.ClearControls;
begin
inherited;
chbxRelativeDates.Checked := false;
chbxBoundingDates.Checked := false;
end;
constructor TfrmLicenseConditionTypeEditFrame.Create(AOwner: TComponent);
begin
inherited;
EditingClass := TLicenseConditionType;
ShowShortName := false;
end;
procedure TfrmLicenseConditionTypeEditFrame.FillControls(
ABaseObject: TIDObject);
begin
inherited;
with EditingObject as TLicenseConditionType do
begin
chbxRelativeDates.Checked := HasRelativeDate;
chbxBoundingDates.Checked := BoundingDates;
end;
end;
procedure TfrmLicenseConditionTypeEditFrame.Save;
begin
inherited;
with EditingObject as TLicenseConditionType do
begin
HasRelativeDate := chbxRelativeDates.Checked;
BoundingDates := chbxBoundingDates.Checked;
end;
end;
end.
|
๏ปฟunit TextEditor.Search.RegularExpressions;
interface
uses
System.Classes, System.RegularExpressions, TextEditor.Lines, TextEditor.Search.Base;
type
TTextEditorRegexSearch = class(TTextEditorSearchBase)
strict private
FLengths: TList;
FOptions: TRegexOptions;
protected
function GetLength(const AIndex: Integer): Integer; override;
procedure CaseSensitiveChanged; override;
public
constructor Create;
destructor Destroy; override;
function SearchAll(const ALines: TTextEditorLines): Integer; override;
procedure Clear; override;
end;
implementation
uses
System.SysUtils;
constructor TTextEditorRegexSearch.Create;
begin
inherited Create;
FOptions := [roMultiLine, roNotEmpty];
FLengths := TList.Create;
end;
destructor TTextEditorRegexSearch.Destroy;
begin
inherited;
FLengths.Free;
end;
procedure TTextEditorRegexSearch.CaseSensitiveChanged;
begin
if CaseSensitive then
Exclude(FOptions, roIgnoreCase)
else
Include(FOptions, roIgnoreCase);
end;
function TTextEditorRegexSearch.SearchAll(const ALines: TTextEditorLines): Integer;
procedure AddResult(const APos, ALength: Integer);
begin
FResults.Add(Pointer(APos));
FLengths.Add(Pointer(ALength));
end;
var
LRegex: TRegEx;
LMatch: TMatch;
begin
Result := 0;
Clear;
Status := '';
try
LRegex := TRegEx.Create(FPattern, FOptions);
LMatch := LRegex.Match(ALines.Text);
while LMatch.Success do
begin
AddResult(LMatch.Index, LMatch.Length);
LMatch := LMatch.NextMatch;
Inc(Result);
end;
except
on E: Exception do
Status := E.Message;
end;
end;
procedure TTextEditorRegexSearch.Clear;
begin
inherited;
FLengths.Clear;
end;
function TTextEditorRegexSearch.GetLength(const AIndex: Integer): Integer;
begin
Result := Integer(FLengths[AIndex]);
end;
end.
|
๏ปฟunit DSE_Bitmap;
interface
uses
Windows, Messages, vcl.Forms, Classes, vcl.StdCtrls, vcl.Graphics, vcl.Controls, Contnrs, SysUtils, vcl.extctrls, DSE_defs ;
type
SE_Bitmap = class;
SE_Bitmap = class
private
fBmpName: string;
fBitmap: TBitmap;
fAlpha : double;
fWidth, fHeight: integer;
function AllocateImage: boolean;
function GetPixel(x, y: integer): Tcolor;
function GetPixel24(x, y: integer): TRGB;
function GetPPixel24(x, y: integer): PRGB;
procedure SetPixel(x, y: integer; value: TRGB);
procedure SetPixel24(x, y: integer; Value: TRGB);
procedure DestroyBitmapScanlines;
procedure CreateBitmapScanlines;
function GetMemory(): pointer;
procedure CopyToTBitmap(Dest: TBitmap);
procedure CopyBitmap(Source, Dest: TBitmap);
function GetRow(Row: integer): pointer;
protected
function GetCanvas: TCanvas;
procedure SetAlpha(Value: double);
procedure SetWidth(Value: integer);
procedure SetHeight(Value: integer);
function GetScanLine(Row: integer): pointer;
procedure Render24(dbitmapscanline: ppointerarray; var ABitmap: SE_Bitmap; XLUT, YLUT: pinteger; xSrc, ySrc: integer; xDst, yDst: integer; cx1, cy1, cx2, cy2: integer; rx, ry: integer); virtual;
procedure SetBitmap(bmp: TBitmap);
public
fbitmapAlpha: TBitmap;
fBitmapScanlines: ppointerarray;
fdata: pointer;
info: TBitmapInfo;
DIB_SectionHandle: HBITMAP;
fRowLen: integer;
BlendMode: SE_BlendMode;
constructor Create(); overload;
constructor Create(aWidth, aHeight: integer); overload;
constructor Create(const FileName: string); overload;
constructor Create(image: SE_Bitmap); overload;
constructor Create(image: SE_Bitmap; Rect: TRect); overload;
constructor Create(image: TBitmap; Rect: TRect); overload;
destructor Destroy; override;
procedure TakeTBitmap(aBitmap: TBitmap);
function LoadFromStreamBMP(Stream: TStream): TBitmap;
function LoadFromFileBMP(const FileName: WideString): TBitmap;
property BmpName: string read FBmpName write FBmpName;
property Alpha: double read fAlpha write SetAlpha;
property Width: integer read fWidth write SetWidth;
property Height: integer read fHeight write SetHeight;
procedure Assign(Source: TObject); // for SE_Bitmap and TBitmap
procedure AssignImage(Source: SE_Bitmap); // assign without alpha channel
property ScanLine[Row: integer]: pointer read GetScanLine;
procedure UpdateFromTBitmap;
function GetSegment(Row: integer; Col: integer; Width: integer): pointer;
property Memory: pointer read GetMemory;
property TBitmapScanlines: ppointerarray read fBitmapScanlines;
property Canvas: TCanvas read GetCanvas;
function Allocate(aWidth, aHeight: integer): boolean;
procedure FreeImage;
procedure CopyFromTBitmap(Source: TBitmap);
procedure CopyRectTo(DestBitmap: SE_Bitmap; SrcX, SrcY, DstX, DstY: integer; RectWidth, RectHeight: integer; Transparent: boolean;wTrans: integer); overload;
// procedure CopyRectTo(DestBitmap: SE_Bitmap; DstX, DstY: integer; RectSource: Trect); overload;
procedure Resize(NewWidth, NewHeight: integer; BackgroundColor: double);
procedure InternalRender(ABitmap: SE_Bitmap; var ABitmapScanline: ppointerarray;
xDst, yDst, dxDst, dyDst: integer; xSrc, ySrc, dxSrc, dySrc: integer);
procedure Flip(Direction: TFlipDirection);
procedure Rotate(Angle: double); overload;
function Rotate(Angle: integer): SE_Bitmap; overload;
procedure Stretch ( NewWidth, Newheight : integer );
procedure GrayScale;
procedure Blend(var src: PRGB; var dst: PRGB; BlendMode: SE_BlendMode; var PixAlpha: PRGB);
property Pixel[x, y: integer]: TColor read GetPixel;
property Pixel24[x, y: integer]: TRGB read GetPixel24 write SetPixel24;
property PPixel24[x, y: integer]: PRGB read GetPPixel24;
procedure Fill(Value: double); overload;
procedure FillRect(x1, y1, x2, y2: integer; Value: double);
property Bitmap: TBitmap read fBitmap write SetBitmap;
end;
procedure BMPReadStream(fs: TStream; Bitmap: SE_Bitmap);
function GetNextZoomValue(CurrentZoom: double; bZoomIn: boolean; SuggestedZoom: double) : double;
function BmpRowLen(Width: integer): int64;
implementation
uses math, DSE_misc, DSE_Theater ;
var
SE_CosineTab: array[0..255] of integer;
{$R-}
function BmpRowLen(Width: integer): int64;
begin
result := (((Width * 24) + 31) shr 5) shl 2; // row byte length
// result := (Width*3);
// result := (((Width * 24) + (24 - 1)) div 24) * 3;
// result := (((Width * 32) + (32 - 1)) div 32) * 4;
end;
procedure Stretch(BitsPerPixel: integer; dest: pbyte; dxDst, dyDst, xSrc, ySrc, dxSrc, dySrc: integer; src: pbyte; srcWidth, srcHeight: integer; fx1, fy1, fx2, fy2: integer);
var
rx, ry, sy: integer;
y2, x2: integer;
x, y: integer;
px1, px2, px3: pbyte;
destRowlen, srcRowLen: integer;
ffx1, ffy1, ffx2, ffy2: integer;
zx, zy: double;
arx, arxp: pinteger;
begin
if (dxDst < 1) or (dyDst < 1) then
exit;
destRowlen := (((DxDst * 24) + (24 - 1)) div 24) * 3;
zeromemory(dest, destRowlen * dyDst);
srcRowLen := (((srcWidth * 24) + (24 - 1)) div 24) * 3;
ry := trunc((dySrc / dyDst) * 16384);
rx := trunc((dxSrc / dxDst) * 16384);
y2 := dyDst - 1;
x2 := dxDst - 1;
zx := dxDst / dxSrc;
zy := dyDst / dySrc;
ffy1 := imax(trunc(zy * (fy1 - ySrc)), 0);
ffx1 := imax(trunc(zx * (fx1 - xSrc)), 0);
ffy2 := imin(trunc(zy * (fy2 - ySrc + 1)), y2);
ffx2 := imin(trunc(zx * (fx2 - xSrc + 1)), x2);
if (ffx2-ffx1+1)<=0 then
exit;
zeromemory(dest, (((DxDst * 24) + (24 - 1)) div 24) * 3);
getmem(arx, sizeof(integer) * (ffx2 - ffx1 + 1));
arxp := arx;
for x := ffx1 to ffx2 do begin
arxp^ := ((rx * x) shr 14) + xSrc;
inc(arxp);
end;
for y := ffy1 to ffy2 do begin
px2 := pbyte(uint64(dest) + (dyDst - y - 1) * destRowlen);
sy := imin( SrcHeight-1, ((ry * y) shr 14) + ySrc );
px1 := pbyte(uint64(src) + (srcHeight - sy - 1) * srcRowlen);
arxp := arx;
for x := ffx1 to ffx2 do begin
pbytearray(px2)^[x] := pbytearray(px1)^[arxp^];
inc(arxp);
end;
end;
freemem(arx);
end;
constructor SE_Bitmap.Create();
var
i: integer;
begin
inherited;
fWidth := 0;
fHeight := 0;
fBitmap := nil;
fBitmapScanlines := nil;
for i := 0 to 255 do
SE_CosineTab[i] := Round(64 - Cos(i * Pi / 255) * 64);
end;
constructor SE_Bitmap.Create(aWidth, aHeight: integer);
begin
Create();
Allocate(aWidth, aHeight);
end;
constructor SE_Bitmap.Create(const FileName: string);
begin
Create();
LoadFromFileBMP(filename);
FBmpName:= Filename;
end;
constructor SE_Bitmap.Create(image: SE_Bitmap);
begin
Create();
Assign(image);
end;
constructor SE_Bitmap.Create(image: SE_Bitmap; Rect: TRect);
begin
Create();
Allocate(Rect.Right - Rect.Left + 1, Rect.Bottom - Rect.Top + 1);
image.CopyRectTo(self, Rect.Left, Rect.Top, 0, 0, Width, Height,false,0);
end;
constructor SE_Bitmap.Create(image: TBitmap; Rect: TRect);
var
bmp: SE_Bitmap;
begin
Create();
Allocate(Rect.Right - Rect.Left + 1, Rect.Bottom - Rect.Top + 1);
bmp := SE_Bitmap.Create();
try
bmp.CopyFromTBitmap (image);
bmp.CopyRectTo(self, Rect.Left, Rect.Top, 0, 0, Width, Height,false,0);
finally
bmp.Free();
end;
end;
procedure SE_Bitmap.UpdateFromTBitmap;
begin
if assigned(fBitmap) then
if (fWidth <> fBitmap.Width) or (fHeight <> fBitmap.Height) then
begin
fWidth := fBitmap.Width;
fHeight := fBitmap.Height;
fRowLen := BmpRowLen(fWidth);
CreateBitmapScanlines;
end;
if (fHeight > 0) and assigned(fBitmapScanlines) and (fBitmapScanlines[0] <> fBitmap.Scanline[0]) then
CreateBitmapScanlines;
end;
destructor SE_Bitmap.Destroy;
begin
FreeImage;
inherited;
end;
procedure SE_Bitmap.DestroyBitmapScanlines;
begin
if fBitmapScanlines <> nil then
freemem(fBitmapScanlines);
fBitmapScanlines := nil;
end;
procedure SE_Bitmap.CreateBitmapScanlines;
var
i: integer;
begin
DestroyBitmapScanlines;
if assigned(fBitmap) then begin
getmem(fBitmapScanlines, (sizeof(pointer) * fHeight) );
for i := 0 to fHeight - 1 do begin
fBitmapScanlines[i] := fBitmap.Scanline[i];
end;
end;
end;
procedure SE_Bitmap.SetAlpha(Value: double);
begin
fAlpha := value;
end;
procedure SE_Bitmap.SetWidth(Value: integer);
begin
if Value <> fWidth then begin
if fBitmap = nil then fBitmap := TBitmap.Create;
fBitmap.Width := Value;
fWidth := fBitmap.Width;
fRowLen := BmpRowLen(fWidth);
CreateBitmapScanlines;
end;
end;
procedure SE_Bitmap.SetHeight(Value: integer);
begin
if Value <> fHeight then begin
if fBitmap = nil then fBitmap := TBitmap.Create;
fBitmap.Height := Value;
fHeight := fBitmap.Height;
CreateBitmapScanlines;
end;
end;
procedure DoAlignAfter(Bitmap: SE_Bitmap; OldWidth, OldHeight: integer; BackgroundColor: double );
begin
if Bitmap.Width > OldWidth then
begin
Bitmap.FillRect(OldWidth, 0, Bitmap.Width - 1, Bitmap.Height - 1, BackgroundColor);
end;
if Bitmap.Height > OldHeight then
begin
Bitmap.FillRect(0, OldHeight, Bitmap.Width - 1, Bitmap.Height - 1, BackgroundColor);
end;
end;
procedure SE_Bitmap.Resize(NewWidth, NewHeight: integer; BackgroundColor: double);
var
lw, lh: integer;
begin
lw := Width;
lh := Height;
SetWidth(NewWidth);
SetHeight(NewHeight);
DoAlignAfter(self, lw, lh, BackgroundColor);
end;
procedure SE_Bitmap.Stretch ( NewWidth, Newheight : integer );
var
Dst: SE_Bitmap;
x, y: Integer;
zx, zy: Double;
sxarr: array of Integer;
dst_rgb: PRGB;
src_rgb: PRGBROW;
begin
dst:= SE_Bitmap.Create (NewWidth,Newheight);
dst.Bitmap.PixelFormat := pf24bit;
// StretchBlt(dst.Bitmap.Canvas.Handle,0,0,NewWidth,Newheight, fbitmap.Canvas.Handle ,0,0,fbitmap.Width,fbitmap.Height,SRCCOPY );
zx := fbitmap.Width / NewWidth;
zy := fbitmap.Height / Newheight;
SetLength(sxarr, NewWidth);
for x := 0 to NewWidth - 1 do
sxarr[x] := trunc(x * zx);
for y := 0 to Newheight - 1 do begin
src_rgb := fbitmap.Scanline[trunc(y * zy)];
dst_rgb := Dst.Scanline[y];
for x := 0 to Dst.Width - 1 do begin
dst_rgb^ := src_rgb[sxarr[x]];
inc(dst_rgb);
end;
end;
// sxarr := nil;
AssignImage(dst);
FreeAndNil(dst);
end;
procedure SE_Bitmap.Rotate(Angle: double);
var
dst: SE_Bitmap;
parx1, parx2: pinteger;
a, tsin, tcos, cxSrc, cySrc, cxDest, cyDest: Double;
fx, fy: Integer;
dw, dh, x, y: Integer;
px: pbyte;
arx1, arx2: pintegerarray;
ary1, ary2: Integer;
ps, pd: pbyte;
dw1, dh1: Integer;
prgb_s, prgb_d: PRGB;
srcrows: ppointerarray;
iangle: Integer;
aTRGB:trgb;
wtrans: double;
procedure Rot90(inv: Boolean);
var
x, y: Integer;
mulx, muly, addx, addy: Integer;
begin
dw := height; dw1 := dw-1;
dh := Width; dh1 := dh-1;
dst:= SE_Bitmap.Create (dw,dh);
aTRGB:= Pixel24 [0,0];
wtrans:= RGB2TColor (aTRGB.b, aTRGB.g , aTRGB.r) ;
dst.Fill(wtrans);
if inv then begin
mulx := -1;
muly := 1;
addx := dw1;
addy := 0;
end
else begin
mulx := 1;
muly := -1;
addx := 0;
addy := dh1;
end;
for x := 0 to dw1 do begin
ps := ScanLine[addx+x*mulx];
prgb_s := PRGB(ps);
for y := 0 to dh1 do begin
prgb_d := dst.Scanline[addy+y*muly];
inc(prgb_d, x);
prgb_d^ := prgb_s^;
inc(prgb_s);
end;
end;
end;
procedure Rot180;
var
x, y: Integer;
begin
dw := width; dw1 := dw-1;
dh := height; dh1 := dh-1;
dst:= SE_Bitmap.Create (dw,dh);
aTRGB:= Pixel24 [0,0];
wtrans:= RGB2TColor (aTRGB.b, aTRGB.g , aTRGB.r) ;
dst.Fill(wtrans);
for y := 0 to dh1 do begin
pd := dst.ScanLine[dh1 - y];
ps := Scanline[y];
prgb_d := PRGB(pd);
prgb_s := PRGB(ps);
inc(prgb_s, dw1);
for x := 0 to dw1 do begin
prgb_d^ := prgb_s^;
inc(prgb_d);
dec(prgb_s);
end;
end;
end;
begin
if (Frac(angle) = 0) and ((trunc(angle) mod 90) = 0) then
begin
iangle := trunc(angle) mod 360;
case iangle of
90 : Rot90(false);
180 : Rot180;
270 : Rot90(true);
-90 : Rot90(true);
-180 : Rot180;
-270 : Rot90(false);
end;
AssignImage(dst);
FreeAndNil(dst);
exit;
end;
a := angle * pi / 180;
dw := round(abs(width * cos(a)) + abs(height * sin(a)));
dh := round(abs(width * sin(a)) + abs(height * cos(a)));
dw1 := dw-1;
dh1 := dh-1;
{ TODO -cbug : verificare bug fill color non clblack }
dst:= SE_Bitmap.Create (dw,dh);
aTRGB:= Pixel24 [0,0];
wtrans:= RGB2TColor (aTRGB.b, aTRGB.g , aTRGB.r) ;
dst.Fill(wtrans);
tsin := sin(a);
tcos := cos(a);
cxSrc := (Width - 1) / 2;
cySrc := (Height - 1) / 2;
cxDest := (dst.Width - 1) / 2;
cyDest := (dst.Height - 1) / 2;
getmem(arx1, sizeof(integer) * dst.Width);
getmem(arx2, sizeof(integer) * dst.Width);
for x := 0 to dst.Width - 1 do begin
arx1[x] := round( cxSrc + (x - cxDest) * tcos );
arx2[x] := round( cySrc + (x - cxDest) * tsin );
end;
// per := 100 / (dst.Height);
getmem(srcrows, height*sizeof(pointer));
for y := 0 to height-1 do
srcrows[y] := GetRow(y);
for y := 0 to dh1 do begin
px := dst.Scanline[y];
ary1 := round( (y - cyDest) * tsin );
ary2 := round( (y - cyDest) * tcos );
parx1 := @arx1[0];
parx2 := @arx2[0];
prgb_d := prgb(px);
for x := 0 to dw1 do begin
fx := parx1^ - ary1;
if (fx >= 0) and (fx < width )then begin
fy := parx2^ + ary2;
if (fy >= 0) and (fy < height) then begin
prgb_s := srcrows[fy];
inc(prgb_s, fx);
prgb_d^ := prgb_s^;
end;
end;
inc(prgb_d);
inc(parx1);
inc(parx2);
end;
end;
freemem(srcrows);
freemem(arx1);
freemem(arx2);
AssignImage(dst);
FreeAndNil(dst);
end;
function SE_Bitmap.Rotate(Angle: integer): SE_Bitmap;
var
dst: SE_Bitmap;
parx1, parx2: pinteger;
a, tsin, tcos, cxSrc, cySrc, cxDest, cyDest: Double;
fx, fy: Integer;
dw, dh, x, y: Integer;
px: pbyte;
arx1, arx2: pintegerarray;
ary1, ary2: Integer;
ps, pd: pbyte;
dw1, dh1: Integer;
prgb_s, prgb_d: PRGB;
srcrows: ppointerarray;
iangle: Integer;
aTRGB:trgb;
wtrans: double;
procedure Rot90(inv: Boolean);
var
x, y: Integer;
mulx, muly, addx, addy: Integer;
begin
dw := height; dw1 := dw-1;
dh := Width; dh1 := dh-1;
dst:= SE_Bitmap.Create (dw,dh);
aTRGB:= Pixel24 [0,0];
wtrans:= RGB2TColor (aTRGB.b, aTRGB.g , aTRGB.r) ;
dst.Fill(wtrans);
if inv then begin
mulx := -1;
muly := 1;
addx := dw1;
addy := 0;
end
else begin
mulx := 1;
muly := -1;
addx := 0;
addy := dh1;
end;
for x := 0 to dw1 do begin
ps := ScanLine[addx+x*mulx];
prgb_s := PRGB(ps);
for y := 0 to dh1 do begin
prgb_d := dst.Scanline[addy+y*muly];
inc(prgb_d, x);
prgb_d^ := prgb_s^;
inc(prgb_s);
end;
end;
end;
procedure Rot180;
var
x, y: Integer;
begin
dw := width; dw1 := dw-1;
dh := height; dh1 := dh-1;
dst:= SE_Bitmap.Create (dw,dh);
aTRGB:= Pixel24 [0,0];
wtrans:= RGB2TColor (aTRGB.b, aTRGB.g , aTRGB.r) ;
dst.Fill(wtrans);
for y := 0 to dh1 do begin
pd := dst.ScanLine[dh1 - y];
ps := Scanline[y];
prgb_d := PRGB(pd);
prgb_s := PRGB(ps);
inc(prgb_s, dw1);
for x := 0 to dw1 do begin
prgb_d^ := prgb_s^;
inc(prgb_d);
dec(prgb_s);
end;
end;
end;
begin
if (Frac(angle) = 0) and ((trunc(angle) mod 90) = 0) then begin
iangle := trunc(angle) mod 360;
case iangle of
90 : Rot90(false);
180 : Rot180;
270 : Rot90(true);
-90 : Rot90(true);
-180 : Rot180;
-270 : Rot90(false);
end;
AssignImage(dst);
FreeAndNil(dst);
exit;
end;
a := angle * pi / 180;
dw := round(abs(width * cos(a)) + abs(height * sin(a)));
dh := round(abs(width * sin(a)) + abs(height * cos(a)));
dw1 := dw-1;
dh1 := dh-1;
{ TODO -cbug : verificare bug fill color non clblack }
dst:= SE_Bitmap.Create (dw,dh);
aTRGB:= Pixel24 [0,0];
wtrans:= RGB2TColor (aTRGB.b, aTRGB.g , aTRGB.r) ;
dst.Fill(wtrans);
tsin := sin(a);
tcos := cos(a);
cxSrc := (Width - 1) / 2;
cySrc := (Height - 1) / 2;
cxDest := (dst.Width - 1) / 2;
cyDest := (dst.Height - 1) / 2;
getmem(arx1, sizeof(integer) * dst.Width);
getmem(arx2, sizeof(integer) * dst.Width);
for x := 0 to dst.Width - 1 do begin
arx1[x] := round( cxSrc + (x - cxDest) * tcos );
arx2[x] := round( cySrc + (x - cxDest) * tsin );
end;
getmem(srcrows, height*sizeof(pointer));
for y := 0 to height-1 do
srcrows[y] := GetRow(y);
for y := 0 to dh1 do begin
px := dst.Scanline[y];
ary1 := round( (y - cyDest) * tsin );
ary2 := round( (y - cyDest) * tcos );
parx1 := @arx1[0];
parx2 := @arx2[0];
prgb_d := prgb(px);
for x := 0 to dw1 do begin
fx := parx1^ - ary1;
if (fx >= 0) and (fx < width )then begin
fy := parx2^ + ary2;
if (fy >= 0) and (fy < height) then begin
prgb_s := srcrows[fy];
inc(prgb_s, fx);
prgb_d^ := prgb_s^;
end;
end;
inc(prgb_d);
inc(parx1);
inc(parx2);
end;
end;
freemem(srcrows);
freemem(arx1);
freemem(arx2);
Result := dst;
end;
procedure SE_Bitmap.Flip(Direction: TFlipDirection);
var
x, y, w, h: Integer;
newbitmap: SE_Bitmap;
newpx, oldpx: PRGB;
begin
newbitmap := SE_Bitmap.create;
newbitmap.Allocate(Width, Height);
w := width - 1;
h := height - 1;
case direction of
FlipH:
for y := 0 to h do begin
newpx := newbitmap.ScanLine[y];
oldpx := ScanLine[y];
inc(oldpx, w);
for x := 0 to w do begin
newpx^ := oldpx^;
inc(newpx);
dec(oldpx);
end;
end;
FlipV:
for y := 0 to h do
copymemory(newbitmap.scanline[y], scanline[h - y], 3 * Width)
end;
AssignImage(newbitmap);
FreeAndNil(newbitmap);
end;
procedure SE_Bitmap.FreeImage;
begin
DestroyBitmapScanlines;
if fBitmap <> nil then FreeAndNil(fBitmap);
fBitmap := nil;
fWidth := 0;
fHeight := 0;
fRowlen := 0;
end;
function SE_Bitmap.AllocateImage: boolean;
begin
result := false;
if (fWidth > 0) and (fHeight > 0) then begin
fRowLen := BmpRowLen(fWidth);
fBitmap := TBitmap.Create;
fBitmap.Width := fWidth;
fBitmap.Height := fHeight;
fBitmap.PixelFormat := pf24bit;
CreateBitmapScanlines;
result := true;
end;
end;
function SE_Bitmap.Allocate(aWidth, aHeight: integer): boolean;
begin
if fbitmap <> nil then fBitmap.PixelFormat := pf24bit;
FreeImage;
fWidth := aWidth;
fHeight := aHeight;
result := AllocateImage;
if result=false then begin
fWidth := 0;
fHeight := 0;
end;
end;
procedure SE_Bitmap.Assign(Source: TObject);
var
src: SE_Bitmap;
row, mi: integer;
begin
if Source is SE_Bitmap then begin
src := Source as SE_Bitmap;
fWidth := src.fWidth;
fHeight := src.fHeight;
if fBitmap = nil then
fBitmap := TBitmap.Create;
fBitmap.Width := 4;
fBitmap.Height := 4;
fbitmap.PixelFormat := pf24bit;
fBitmap.Width := fWidth;
fBitmap.Height := fHeight;
fRowLen := BmpRowLen(fWidth);
CreateBitmapScanlines;
mi := imin(fRowLen, src.fRowLen);
for row := 0 to fHeight - 1 do
copymemory(ScanLine[row], src.ScanLine[row], mi);
end
else
if Source is TBitmap then
CopyFromTBitmap(Source as TBitmap);
end;
procedure SE_Bitmap.AssignImage(Source: SE_Bitmap);
var
row, mi: integer;
begin
fWidth := Source.fWidth;
fHeight := Source.fHeight;
if fBitmap = nil then
fBitmap := TBitmap.Create;
fBitmap.Width := fWidth;
fBitmap.Height := fHeight;
fBitmap.PixelFormat := pf24bit;
fRowLen := BmpRowLen(fWidth);
CreateBitmapScanlines;
mi := imin(fRowLen, Source.fRowLen);
for row := 0 to fHeight - 1 do
CopyMemory(ScanLine[row], Source.ScanLine[row], mi);
end;
function SE_Bitmap.GetSegment(Row: integer; Col: integer; Width: integer): pointer;
begin
result := Scanline[Row];
inc(pbyte(result), Col * 3);
end;
function SE_Bitmap.GetScanLine(Row: integer): pointer;
begin
result := fBitmapScanlines[row];
end;
function SE_Bitmap.GetRow(Row: integer): pointer;
begin
result := fBitmapScanlines[row];
end;
procedure SE_Bitmap.GrayScale;
var
x, y,v: integer;
ppx: PRGB;
begin
for y := 0 to height - 1 do begin
ppx := ScanLine[y];
for x := 0 to Width -1 do begin
with ppx^ do begin
v := (r * 21 + g * 71 + b * 8) div 100;
r := v;
g := v;
b := v;
end;
inc(ppx);
end;
end;
end;
procedure SE_Bitmap.CopyToTBitmap(Dest: TBitmap);
var
row, mi: integer;
begin
Dest.Width := fWidth;
Dest.Height := fHeight;
Dest.PixelFormat := pf24bit;
mi := imin(fRowLen, BmpRowLen(Dest.Width));
for row := 0 to fHeight - 1 do
CopyMemory(Dest.Scanline[row], Scanline[row], mi);
end;
procedure SE_Bitmap.CopyRectTo(DestBitmap: SE_Bitmap; SrcX, SrcY, DstX, DstY: integer; RectWidth, RectHeight: integer; Transparent: boolean;wTrans: integer);
var
y,x: integer;
ps, pd: pbyte;
rl: integer;
ppRGBCurrentFrame,ppVirtualRGB,ppRGBCurrentFrameAlpha: pRGB;
aTrgb: Trgb;
label skip;
begin
if Transparent then begin
aTRGB:= DSE_Misc.TColor2TRGB (wtrans);
SrcX:=0;
SrcY:=0;
// DstX:= DrawingRect.Left ;
// DstY:= DrawingRect.Top;
// RectWidth:=fbitmap.width;
// rectheight:=fbitmap.height;
if DstX < 0 then begin
inc(SrcX, -DstX);
dec(RectWidth, -DstX);
DstX := 0;
end;
if DstY < 0 then begin
inc(SrcY, -DstY);
dec(RectHeight, -DstY);
DstY := 0;
end;
DstX := imin(DstX, DestBitmap.Width - 1);
DstY := imin(DstY, DestBitmap.Height - 1);
SrcX := imin(imax(SrcX, 0), fbitmap.Width - 1);
SrcY := imin(imax(SrcY, 0), fbitmap.Height - 1);
// if SrcX + RectWidth > Width then //begin
// exit;
// if SrcY + RectHeight > Height then //begin
// exit;
if SrcX + RectWidth > fbitmap.Width then
RectWidth := fbitmap.Width - SrcX;
if SrcY + RectHeight > fbitmap.Height then
RectHeight := fbitmap.Height - SrcY;
if DstX + RectWidth > DestBitmap.Width then
RectWidth := DestBitmap.Width - DstX;
if DstY + RectHeight > DestBitmap.Height then
RectHeight := DestBitmap.Height - DstY;
for y := 0 to RectHeight - 1 do begin
ppRGBCurrentFrame := GetSegment(SrcY + y, SrcX, RectWidth);
if Alpha <> 0 then begin
ppRGBCurrentFrameAlpha := fBitmapAlpha.Scanline[SrcY + y];
inc(pbyte(ppRGBCurrentFrameAlpha), SrcX * 3);
end;
ppVirtualRGB := DestBitmap.GetSegment(DstY + y, DstX, RectWidth);
for x := SrcX to SrcX + RectWidth - 1 do begin
// if not((ppRGBCurrentFrame.b = aTRGB.b) and (ppRGBCurrentFrame.g = aTRGB.g) and (ppRGBCurrentFrame.r = aTRGB.r)) then begin
if (ppRGBCurrentFrame.b <> aTRGB.b) or (ppRGBCurrentFrame.g <> aTRGB.g) or (ppRGBCurrentFrame.r <> aTRGB.r) then begin
if fAlpha <> 0 then begin
if (ppRGBCurrentFrameAlpha.B <> 255) and (ppRGBCurrentFrameAlpha.G <> 255) and (ppRGBCurrentFrameAlpha.R <> 255) then begin
// se non รจ 0 in alpha
// Blend ( ppRGBCurrentFrame,ppVirtualRGB,SE_BlendAlpha,0); ; // trovare alpha AND ????
Blend ( ppRGBCurrentFrame,ppVirtualRGB,SE_BlendAlpha,ppRGBCurrentFrameAlpha ); ; // trovare alpha AND ????
end
else begin // se รจ 0 in alpha
if BlendMode = SE_BlendNormal then begin
ppVirtualRGB.b := ppRGBCurrentFrame.b;
ppVirtualRGB.g:= ppRGBCurrentFrame.g;
ppVirtualRGB.r:= ppRGBCurrentFrame.r;
end
else begin
Blend ( ppRGBCurrentFrame,ppVirtualRGB,BlendMode,ppRGBCurrentFrame); ;
end;
end;
end
else begin
if BlendMode = SE_BlendNormal then begin
ppVirtualRGB.b := ppRGBCurrentFrame.b;
ppVirtualRGB.g:= ppRGBCurrentFrame.g;
ppVirtualRGB.r:= ppRGBCurrentFrame.r;
end
else begin
Blend ( ppRGBCurrentFrame,ppVirtualRGB,BlendMode,ppRGBCurrentFrame); ;
end;
end;
end;
SKIP:
if fAlpha <> 0 then inc(pbyte(ppRGBCurrentFrameAlpha),3);
inc(pbyte(ppRGBCurrentFrame),3);
inc(pbyte(ppVirtualRGB),3);
end;
end;
end
else begin // non transparent
// RectWidth:=fbitmap.width;
// rectheight:=fbitmap.height;
if DstX < 0 then begin
inc(SrcX, -DstX);
dec(RectWidth, -DstX);
DstX := 0;
end;
if DstY < 0 then begin
inc(SrcY, -DstY);
dec(RectHeight, -DstY);
DstY := 0;
end;
DstX := imin(DstX, DestBitmap.Width - 1);
DstY := imin(DstY, DestBitmap.Height - 1);
SrcX := imin(imax(SrcX, 0), Width - 1);
SrcY := imin(imax(SrcY, 0), Height - 1);
// if SrcX + RectWidth > Width then //begin
// exit;
// if SrcY + RectHeight > Height then //begin
// exit;
// end;
if SrcX + RectWidth > Width then
RectWidth := Width - SrcX;
if SrcY + RectHeight > Height then
RectHeight := Height - SrcY;
if DstX + RectWidth > DestBitmap.Width then
RectWidth := DestBitmap.Width - DstX;
if DstY + RectHeight > DestBitmap.Height then
RectHeight := DestBitmap.Height - DstY;
// pf24bit
rl := (((RectWidth * 24) + 31) shr 5) shl 2; // row byte length
if BlendMode = SE_BlendNormal then begin
for y := 0 to RectHeight - 1 do begin
ps := GetSegment(SrcY + y, SrcX, RectWidth);
pd := DestBitmap.GetSegment(DstY + y, DstX, RectWidth);
CopyMemory(pd, ps, rl);
end;
end
else begin
for y := 0 to RectHeight - 1 do begin
ppRGBCurrentFrame := GetSegment(SrcY + y, SrcX, RectWidth);
ppVirtualRGB := DestBitmap.GetSegment(DstY + y, DstX, RectWidth);
for x := SrcX to SrcX + RectWidth - 1 do begin
if not((ppRGBCurrentFrame.b = aTRGB.b) and (ppRGBCurrentFrame.g = aTRGB.g) and (ppRGBCurrentFrame.r = aTRGB.r)) then begin
if BlendMode = SE_BlendNormal then begin
ppVirtualRGB.b := ppRGBCurrentFrame.b;
ppVirtualRGB.g:= ppRGBCurrentFrame.g;
ppVirtualRGB.r:= ppRGBCurrentFrame.r;
end
else begin
Blend ( ppRGBCurrentFrame,ppVirtualRGB,BlendMode,ppRGBCurrentFrame); ;
end;
end;
inc(pbyte(ppRGBCurrentFrame),sizeof(TRGB));
inc(pbyte(ppVirtualRGB),sizeof(TRGB));
end;
end;
end;
end;
end;
{procedure SE_Bitmap.CopyRectTo(DestBitmap: SE_Bitmap; DstX, DstY: integer; RectSource: Trect );
var
rectDest: TRect;
y,X: integer;
rectDestBlock, rectIntersect: TRect;
nSrcBlockWidth, nSrcBlockHeight: integer;
nSrcX, nSrcY: integer;
nOffSrc, nIncSrc: integer;
nOffDest, nIncDest: integer;
pSource, pDest: pointer;
nSrcWidth3, nSrcX3, nSrcBlockWidth3, nDestX3, inverter: integer;
begin
// al momento c'รจ un bug. procedura non utilizzata
Inverter:= DestBitmap.Height -1;
pDest := DestBitmap.Memory;//.ScanLine[Theater.fVirtualBitmap.Height -1];
pSource := memory;//.Scanline[BmpCurrentFrame.height-1];
nSrcBlockWidth := RectSource.Width +1;
nSrcBlockHeight := RectSource.Height +1;
nSrcX := RectSource.left;
nSrcY := RectSource.top;
X:= DstX;
Y:= dSTY;
rectDest := Rect( 0, 0, DestBitmap.Width - 1, DestBitmap.Height - 1 );
rectDestBlock := Rect( X, Y, X + nSrcBlockWidth -1, Y + nSrcBlockHeight -1 );
if not IntersectRect( rectIntersect, rectDest, rectDestBlock ) then
Exit;
(* Taglia i bitmap se escono dalla visuale *)
if X < 0 then
begin
Inc( nSrcX, Abs( X ) );
Dec( nSrcBlockWidth, Abs( X ) );
X:= 0;
end;
if ( X + nSrcBlockWidth - 1 ) >= DestBitmap.Width then
Dec( nSrcBlockWidth, ( ( X + nSrcBlockWidth ) - DestBitmap.Width ) );
if Y < 0 then
begin
Dec( nSrcBlockHeight, Abs( Y ) );
Inc( nSrcY, Abs( Y ) );
Y:=0;
end;
if ( Y + nSrcBlockHeight - 1 ) >= DestBitmap.Height then
Dec( nSrcBlockHeight, ( ( Y + nSrcBlockHeight ) - DestBitmap.Height ) );
nSrcWidth3 := Width * sizeof(TRGB);
nSrcX3 := nSrcX * sizeof(TRGB);
nSrcBlockWidth3 := nSrcBlockWidth * sizeof(TRGB);
nDestX3 := X * sizeof(TRGB);
nOffSrc := nSrcWidth3 * ( Height - nSrcY - 1 ) + nSrcX3;
nIncSrc := -( nSrcWidth3 + nSrcBlockWidth3 );
nOffDest :=DestBitmap.Width*sizeof(TRGB) * ( inverter - Y ) + nDestX3;
nIncDest := -( DestBitmap.Width*sizeof(TRGB) + nSrcBlockWidth3 );
// nOffDest := (Theater.fVirtualBitmap.Width * sizeof(TRGB)) * inverter ;
// nIncDest := -( nSrcWidth3 + nSrcBlockWidth3 );
// nOffDest := Theater.fVirtualBitmap.Width * sizeof(TRGB) * Y + nDestX3; // ribaltato
// nIncDest := Theater.fVirtualBitmap.Width * sizeof(TRGB) - nSrcBlockWidth3;
asm
push esi
push edi
push ebx
// imposto source/destination
mov esi,[pSource]
mov edi,[pDest]
add esi,[nOffSrc]
add edi,[nOffDest]
// quante righe copiare
mov edx,[nSrcBlockHeight]
mov eax,[nSrcBlockWidth]
mov ebx, eax
push eax
shr ebx,1
mov eax, ebx
shr ebx,1
add eax, ebx
mov ebx,eax
pop eax
and eax,$01
// inizio copie delle righe
@OuterLoop:
mov ecx,ebx
rep movsd
mov ecx,eax
rep movsw
// dopo ogni riga aggiorno i puntatori
add esi,[nIncSrc]
add edi,[nIncDest]
dec edx
jnz @OuterLoop
pop ebx
pop edi
pop esi
end;
end; }
procedure SE_Bitmap.CopyFromTBitmap(Source: TBitmap);
begin
FreeImage;
fBitmap := TBitmap.Create;
fWidth := Source.Width;
fHeight := Source.Height;
fBitmap.Width := Source.Width ;
fBitmap.height := Source.Height ;
fBitmap.PixelFormat := pf24bit;
Source.PixelFormat := pf24bit;
CopyBitmap(Source, fBitmap);
fRowLen := BmpRowLen(fWidth);
CreateBitmapScanlines;
end;
procedure SE_Bitmap.CopyBitmap(Source, Dest: TBitmap);
var
ps, pd: pbyte;
l: Integer;
begin
if (Source.Width = 0) or (Source.Height = 0) then
begin
Dest.Width := 1;
Dest.Height := 1;
Dest.Pixelformat := pf24bit;
end
else
begin
if (Dest.Width <> Source.Width) or (Dest.Height <> Source.Height) then
begin
Dest.Width := Source.Width;
Dest.Height := Source.height;
Dest.Pixelformat := pf24bit;
end;
ps := pbyte(imin(uint64(Source.Scanline[0]), uint64(Source.Scanline[Source.Height - 1])));
pd := pbyte(imin(uint64(Dest.Scanline[0]), uint64(Dest.Scanline[Dest.Height - 1])));
l := BmpRowLen(Dest.Width);
copymemory(pd, ps, l * Dest.height);
end;
end;
function SE_Bitmap.GetPixel24(x, y: integer): TRGB;
begin
result := PRGB(GetSegment(y, x, 1))^;
end;
function SE_Bitmap.GetPixel(x, y: integer): TColor;
var
aTrgb: trgb;
begin
aTRGB:= Pixel24 [x,y];
Result:= RGB2TColor (aTRGB.r, aTRGB.g , aTRGB.b) ;
end;
function SE_Bitmap.GetPPixel24(x, y: integer): PRGB;
begin
result := @(PRGBROW(Scanline[y])^[x]);
end;
procedure SE_Bitmap.SetPixel24(x, y: integer; value: TRGB);
begin
Canvas.Pixels [x,y] := DSE_misc.TRGB2TColor (Value);
// Pixel24[x, y] := value;
end;
procedure SE_Bitmap.SetPixel(x, y: integer; Value: TRGB);
begin
PRGBROW(Scanline[y])^[x] := Value;
end;
procedure SE_Bitmap.Fill(Value: double);
var
row, col, iValue: integer;
pxrgb: PRGB;
vrgb: TRGB;
pxb: pbyte;
begin
ivalue := trunc(Value);
vrgb := DSE_misc.TColor2TRGB(TColor(iValue));
if fHeight>0 then begin
getmem(pxb, fRowlen);
pxrgb := PRGB(pxb);
for col := 0 to fWidth - 1 do begin
pxrgb^ := vrgb;
inc(pxrgb);
end;
for row := 0 to fHeight-1 do
CopyMemory(Scanline[row], pxb, fRowLen);
freemem(pxb);
end;
end;
procedure SE_Bitmap.FillRect(x1, y1, x2, y2: integer; Value: double);
var
row, col, iValue: integer;
pxrgb: PRGB;
vrgb: TRGB;
ww: integer;
begin
x1 := imax(x1, 0);
y1 := imax(y1, 0);
x2 := imin(x2, fWidth - 1);
y2 := imin(y2, fHeight - 1);
ww := x2 - x1 + 1;
iValue := trunc(Value);
vrgb := DSE_misc.TColor2TRGB(TColor(iValue));
for row := y1 to y2 do begin
pxrgb := GetSegment(row, x1, ww);
for col := x1 to x2 do begin
pxrgb^ := vrgb;
inc(pxrgb);
end;
end;
end;
function SE_Bitmap.GetCanvas: TCanvas;
begin
result := fBitmap.Canvas;
end;
procedure SE_Bitmap.InternalRender(ABitmap: SE_Bitmap; var ABitmapScanline: ppointerarray;
xDst, yDst, dxDst, dyDst: integer; xSrc, ySrc, dxSrc, dySrc: integer);
var
i, y, x, ww, hh: integer;
DBitmapScanline: ppointerarray;
x2, y2: integer;
rx, ry: integer;
cx1, cy1, cx2, cy2: integer;
sxarr, psx, syarr, psy: pinteger;
dummy1, dummy2: pinteger;
zx, zy: double;
begin
if (dxDst = 0) or (dyDst = 0) or (dxSrc = 0) or (dySrc = 0) then
exit;
if yDst > ABitmap.Height - 1 then
exit;
if xDst > ABitmap.Width - 1 then
exit;
zy := dySrc / dyDst;
zx := dxSrc / dxDst;
if yDst < 0 then begin
y := -yDst;
yDst := 0;
dec(dyDst, y);
inc(ySrc, round(y * zy));
dec(dySrc, round(y * zy));
end;
if xDst < 0 then begin
x := -xDst;
xDst := 0;
dec(dxDst, x);
inc(xSrc, round(x * zx));
dec(dxSrc, round(x * zx));
end;
if yDst + dyDst > ABitmap.Height then begin
y := yDst + dyDst - ABitmap.Height;
dyDst := ABitmap.Height - yDst;
dec(dySrc, trunc(y * zy));
end;
if xDst + dxDst > ABitmap.Width then begin
x := xDst + dxDst - ABitmap.Width;
dxDst := ABitmap.Width - xDst;
dec(dxSrc, trunc(x * zx));
end;
xDst := imax(imin(xDst, ABitmap.Width - 1), 0);
yDst := imax(imin(yDst, ABitmap.Height - 1), 0);
dxDst := imax(imin(dxDst, ABitmap.Width), 0);
dyDst := imax(imin(dyDst, ABitmap.Height), 0);
xSrc := imax(imin(xSrc, Width - 1), 0);
ySrc := imax(imin(ySrc, Height - 1), 0);
dxSrc := imax(imin(dxSrc, Width), 0);
dySrc := imax(imin(dySrc, Height), 0);
if (dxDst = 0) or (dyDst = 0) or (dxSrc = 0) or (dySrc = 0) then
exit;
if (dxDst = 0) or (dyDst = 0) or (dxSrc = 0) or (dySrc = 0) then
exit;
ww := ABitmap.Width;
hh := ABitmap.Height;
if ABitmapScanline = nil then
begin
getmem(DBitmapScanline, hh * sizeof(pointer));
for y := 0 to hh - 1 do
DBitmapScanline[y] := ABitmap.Scanline[y];
end
else
DBitmapScanline := ABitmapScanline;
if (dxDst <> 0) and (dyDst <> 0) then begin
sxarr := nil;
syarr := nil;
ry := trunc((dySrc / dyDst) * 16384);
rx := trunc((dxSrc / dxDst) * 16384);
y2 := imin(yDst + dyDst - 1, hh - 1);
x2 := imin(xDst + dxDst - 1, ww - 1);
cx1 := -2147483646;
cy1 := -2147483646;
cx2 := 2147483646;
cy2 := 2147483646;
cx1 := imax(cx1, xDst);
cx2 := imin(cx2, x2);
cy1 := imax(cy1, yDst);
cy2 := imin(cy2, y2);
cx1 := imax(cx1, 0);
cx1 := imin(cx1, ABitmap.Width - 1);
cx2 := imax(cx2, 0);
cx2 := imin(cx2, ABitmap.Width - 1);
cy1 := imax(cy1, 0);
cy1 := imin(cy1, ABitmap.Height - 1);
cy2 := imax(cy2, 0);
cy2 := imin(cy2, ABitmap.Height - 1);
if (ry <> 16384) or (rx <> 16384) then begin
getmem(sxarr, (cx2 - cx1 + 1) * sizeof(integer));
psx := sxarr;
for x := cx1 to cx2 do
begin
psx^ := ilimit(trunc( zx*(x-xDst) + xSrc ), 0, fWidth-1);
inc(psx);
end;
getmem(syarr, (cy2 - cy1 + 1) * sizeof(integer));
psy := syarr;
for y := cy1 to cy2 do
begin
psy^ := ilimit(trunc( zy*(y-yDst) + ySrc ), 0, fHeight-1);
inc(psy);
end;
end;
Render24(dbitmapscanline, ABitmap, sxarr, syarr, xSrc, ySrc, xDst, yDst, cx1, cy1, cx2, cy2, rx, ry);
if (sxarr <> nil) then
freemem(sxarr);
if (syarr <> nil) then
freemem(syarr);
end;
if ABitmapScanline = nil then begin
freemem(DBitmapScanline)
end;
end;
procedure SE_Bitmap.Render24(dbitmapscanline: ppointerarray; var ABitmap: SE_Bitmap; XLUT, YLUT: pinteger; xSrc, ySrc: integer; xDst, yDst: integer; cx1, cy1, cx2, cy2: integer; rx, ry: integer );
var
psy, syarr, psx, sxarr: pinteger;
x, y, l, rl: integer;
px4, px2: prgb;
px1: PRGBROW;
rl2, rl4: integer;
begin
sxarr := XLUT;
syarr := YLUT;
l := -1;
rl := ABitmap.fRowLen;
if (ry = 16384) and (rx = 16384) then begin
rl2 := uint64(dbitmapscanline[1]) - uint64(dbitmapscanline[0]);
px2 := dbitmapscanline[cy1];
inc(px2, cx1);
rl4 := (cx2 - cx1 + 1) * 3;
for y := cy1 to cy2 do
begin
px4 := scanline[ySrc + (y - yDst)];
inc(px4, xSrc + (cx1 - xDst));
copymemory(px2, px4, rl4);
inc(pbyte(px2), rl2);
end;
end
else begin
psy := syarr;
for y := cy1 to cy2 do begin
if (l = psy^) then begin
copymemory(dbitmapscanline[y], dbitmapscanline[y - 1], rl);
end
else begin
px2 := dBitmapScanline[y];
inc(px2, cx1);
px1 := Scanline[psy^];
psx := sxarr;
for x := cx1 to cx2 do begin
px2^ := px1[psx^];
inc(px2);
inc(psx);
end;
l := psy^;
end;
inc(psy);
end
end;
end;
function SE_Bitmap.GetMemory(): pointer;
begin
result := self.fBitmapScanlines[fHeight - 1]
end;
function GetNextZoomValue(CurrentZoom: double; bZoomIn: boolean; SuggestedZoom: double) : double;
var
ZoomInc: integer;
begin
result := CurrentZoom;
if bZoomIn then begin
ZoomInc := 25;
result := result + 1;
end
else begin
if result < 6 then begin
Result := 1;
exit
end
else begin
ZoomInc := 0;
result := result - 1;
end;
end;
if result < 26 then
result := ((trunc(result) div 5) * 5) + (ZoomInc div 5)
else
if result < 300 then
result := ((trunc(result) div 25) * 25) + ZoomInc
else
result := ((trunc(result) div 100) * 100) + (ZoomInc * 4);
if (SuggestedZoom > 0) and
(SuggestedZoom <> CurrentZoom) and
(trunc(SuggestedZoom) <> trunc(CurrentZoom)) and
(SuggestedZoom > Min(trunc(result), trunc(CurrentZoom))) and
(SuggestedZoom < Max(trunc(result), trunc(CurrentZoom))) then
result := SuggestedZoom;
end;
procedure SE_Bitmap.TakeTBitmap(aBitmap: TBitmap);
begin
if (aBitmap<>nil) and ((aBitmap<>fBitmap) or (aBitmap.Width<>fWidth) or (aBitmap.Height<>fHeight) ) then begin
fWidth := aBitmap.Width;
fHeight := aBitmap.Height;
fRowLen := BmpRowLen(fWidth);
fBitmap := aBitmap;
CreateBitmapScanlines;
end;
end;
function SE_Bitmap.LoadFromStreamBMP(Stream: TStream): TBitmap;
begin
if assigned(fBitmap) then
TakeTBitmap(fBitmap);
BMPReadStream(Stream, Self );
result:= fBitmap;
end;
function SE_Bitmap.LoadFromFileBMP(const FileName: WideString): TBitmap;
var
aStream: TFileStream;
begin
aStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
LoadFromStreamBMP(aStream);
Result:= fBitmap;
FreeAndNil(aStream);
end;
procedure SE_Bitmap.SetBitmap(bmp: TBitmap);
begin
CopyFromTBitmap(fBitmap);
end;
type
TBITMAPINFOHEADER2 = packed record
biSize: DWORD;
biWidth: Longint;
biHeight: Longint;
biPlanes: Word;
biBitCount: Word;
biCompression: DWORD;
biSizeImage: DWORD;
biXPelsPerMeter: Longint;
biYPelsPerMeter: Longint;
biClrUsed: DWORD;
biClrImportant: DWORD;
biUnits: word;
biReserved: word;
biRecording: word;
biRendering: word;
biSize1: dword;
biSize2: dword;
biColorencoding: dword;
biIdentifier: dword;
end;
procedure BMPReadStream(fs: TStream; Bitmap: SE_Bitmap );
var
FileHead: TBITMAPFILEHEADER;
InfoHead: ^TBITMAPINFOHEADER2;
CoreHead: ^TBITMAPCOREHEADER;
dm: integer;
p0: int64;
y: integer;
lw: integer;
inverter: integer;
begin
InfoHead := AllocMem(sizeof(TBITMAPINFOHEADER2));
CoreHead := AllocMem(sizeof(TBITMAPCOREHEADER));
try
p0 := fs.Position;
fs.Read(FileHead, sizeof(TBITMAPFILEHEADER));
if FileHead.bfSize > 0 then
if FileHead.bfType <> 19778 then exit;
fs.Read(dm, sizeof(dm));
fs.Seek(-4, soCurrent);
FillChar(InfoHead^, sizeof(TBITMAPINFOHEADER2), 0);
fs.Read(InfoHead^, imin(sizeof(TBITMAPINFOHEADER2), dm));
if dm > sizeof(TBITMAPINFOHEADER2) then
fs.Seek(dm - 40, soCurrent);
if dm <> 40 then exit;
if InfoHead^.biHeight < 0 then begin
InfoHead^.biHeight := -InfoHead^.biHeight;
inverter := InfoHead^.biHeight - 1;
end
else
inverter := 0;
if InfoHead.biBitCount <> 24 then
raise Exception.Create( ' BitCount is not 24 ! ');
if (InfoHead^.biCompression= BI_RLE4) or (InfoHead^.biCompression = BI_RLE8) then
raise Exception.Create('Compressed Bitmap not supported!');
if FileHead.bfOffBits > 0 then
fs.Position := p0 + FileHead.bfOffBits;
if not Bitmap.Allocate(InfoHead^.biWidth, InfoHead^.biHeight ) then exit;
// lw := (((Bitmap.width * 24) + (24 - 1)) div 24) * 3;
// lw := (((Bitmap.width * 32) + (32 - 1)) div 32) * 4;
lw := (((Bitmap.Width * 24) + 31) shr 5) shl 2; // row byte length
// lw:= BmpRowLen (Bitmap.width);
for y := Bitmap.Height - 1 downto 0 do
begin
fs.read(pbyte(Bitmap.Scanline[abs(inverter - y)])^, lw);
end;
finally
freemem(InfoHead);
freemem(CoreHead);
end;
end;
procedure RGB2HSL(px: PRGB; var Hue, Sat, Lum: Double);
var
delta, r, g, b, cmax, cmin: Double;
begin
r := px.r / 255;
g := px.g / 255;
b := px.b / 255;
cmax := dmax(r, dmax(g, b));
cmin := dmin(r, dmin(g, b));
Lum := (cmax + cmin) / 2;
if cmax = cmin then begin
Sat := 0;
Hue := 0;
end
else begin
if Lum < 0.5 then
Sat := (cmax - cmin) / (cmax + cmin)
else
Sat := (cmax - cmin) / (2 - cmax - cmin);
delta := cmax - cmin;
if r = cmax then
Hue := (g - b) / delta
else
if g = cmax then
Hue := 2 + (b - r) / delta
else
Hue := 4 + (r - g) / delta;
Hue := Hue / 6;
if Hue < 0 then
Hue := Hue + 1;
end;
end;
// iHue, iSat, iLum 0..1
procedure HSL2RGB(var px: PRGB; iHue, iSat, iLum: Double);
function HueToRGB(m1, m2, h: Double): Double;
const
C1 = 2 / 3;
begin
if h < 0 then
h := h + 1
else
if h > 1 then
h := h - 1;
if 6 * h < 1 then
result := (m1 + (m2 - m1) * h * 6)
else
if 2 * h < 1 then
result := m2
else
if 3 * h < 2 then
result := (m1 + (m2 - m1) * (C1 - h) * 6)
else
result := m1;
end;
const
C1 = 1 / 3;
var
r, g, b: Double;
m1, m2: Double;
begin
// check limits
if iHue < 0 then
iHue := 1 + iHue
else
if iHue > 1 then
iHue := iHue - 1;
if iSat < 0 then
iSat := 0
else
if iSat > 1 then
iSat := 1;
if iLum < 0 then
iLum := 0
else
if iLum > 1 then
iLum := 1;
//
if iSat = 0 then
begin
r := iLum;
g := iLum;
b := iLum;
end
else
begin
if iLum <= 0.5 then
m2 := iLum * (1 + iSat)
else
m2 := iLum + iSat - iLum * iSat;
m1 := 2 * iLum - m2;
r := HueToRGB(m1, m2, iHue + C1);
g := HueToRGB(m1, m2, iHue);
b := HueToRGB(m1, m2, iHue - C1);
end;
px.r := blimit(round(r * 255));
px.g := blimit(round(g * 255));
px.b := blimit(round(b * 255));
end;
procedure RGB2YCbCr(rgb: PRGB; var Y, Cb, Cr: integer);
begin
// with rgb do
// begin
Y := blimit(trunc(0.29900 * rgb.R + 0.58700 * rgb.G + 0.11400 * rgb.B));
Cb := blimit(trunc(-0.16874 * rgb.R - 0.33126 * rgb.G + 0.50000 * rgb.B + 128));
Cr := blimit(trunc(0.50000 * rgb.R - 0.41869 * rgb.G - 0.08131 * rgb.B + 128));
// end;
end;
procedure YCbCr2RGB(var rgb: PRGB; Y, Cb, Cr: integer);
begin
Cb := Cb-128;
Cr := Cr-128;
rgb.r := blimit(trunc(Y + 1.40200 * Cr));
rgb.g := blimit(trunc(Y - 0.34414 * Cb - 0.71414 * Cr));
rgb.b := blimit(trunc(Y + 1.77200 * Cb));
end;
procedure SE_Bitmap.Blend(var src: PRGB; var dst: PRGB; BlendMode: SE_BlendMode; var PixAlpha: PRGB);
// filters
function softlight(ib, ia: integer): integer; inline;
var
a, b, r: double;
begin
a := ia / 255;
b := ib / 255;
if b < 0.5 then
r := 2 * a * b + sqr(a) * (1 - 2 * b)
else
r := sqrt(a) * (2 * b - 1) + (2 * a) * (1 - b);
result := trunc(r * 255);
end;
function reflect(b, a: integer): integer; inline;
var
c: integer;
begin
if b = 255 then
result := 255
else begin
c := a * a div (255 - b);
if c > 255 then
result := 255
else
result := c;
end;
end;
function stamp(b, a: integer): integer; inline;
var
c: integer;
begin
c := a + 2 * b - 256;
if c < 0 then
result := 0
else
if c > 255 then
result := 255
else
result := c;
end;
//
function MixBytes(FG, BG, TRANS: byte): byte;
asm
push bx
push cx
push dx
mov DH,TRANS
mov BL,FG
mov AL,DH
mov CL,BG
xor AH,AH
xor BH,BH
xor CH,CH
mul BL
mov BX,AX
xor AH,AH
mov AL,DH
xor AL,$FF
mul CL
add AX,BX
shr AX,8
pop dx
pop cx
pop bx
end;
var
Ha, Sa, La: double;
Hb, Sb, Lb: double;
tmp: TRGB;
v1, v2: byte;
Y_1, Cb_1, Cr_1: integer;
Y_2, Cb_2, Cr_2: integer;
i: integer;
Table: array[-255..255] of Integer;
Begin
case BlendMode of
SE_BlendAlpha:
begin
// dst.R := Trunc(src.R * alpha + pixAlpha.R * (1.0 - alpha)); { TODO : da fixare }
// dst.G := Trunc(src.G * alpha + pixAlpha.G * (1.0 - alpha));
// dst.B := Trunc(src.B * alpha + pixAlpha.B * (1.0 - alpha));
// dst.R := MixBytes (src.r, pixAlpha.R, Byte(Trunc(alpha)) );
// dst.G := MixBytes (src.g, pixAlpha.G, Byte(Trunc(alpha)) );
// dst.B := MixBytes (src.b, pixAlpha.B, Byte(Trunc(alpha)) );
// dst.R := MixBytes (dst.r, src.R, Byte(Trunc(alpha)) );
// dst.G := MixBytes (dst.g, src.G, Byte(Trunc(alpha)) );
// dst.B := MixBytes (dst.b, src.B, Byte(Trunc(alpha)) );
// for i := -255 to 255 do
// Table[i] := (Round( FAlpha) * i) shr 8;
// dst.b := Table[src.b - dst.b] + dst.b;
// dst.g := Table[src.b - dst.g] + dst.g;
// dst.r := Table[src.b - dst.r] + dst.r;
// dst.r := (dst.r * (256 - Trunc(Alpha)) + pixAlpha.r * Trunc(Alpha)) shr 8; // al posto di pixelalpha src ... inverte l'effetto
// dst.g := (dst.g * (256 - Trunc(Alpha)) + pixAlpha.g * Trunc(Alpha)) shr 8;
// dst.b := (dst.b * (256 - Trunc(Alpha)) + pixAlpha.b * Trunc(Alpha)) shr 8;
dst.r := (dst.r * (256 - Trunc(Alpha)) + src.r * Trunc(Alpha)) shr 8; // al posto di pixelalpha src ... inverte l'effetto
dst.g := (dst.g * (256 - Trunc(Alpha)) + src.g * Trunc(Alpha)) shr 8;
dst.b := (dst.b * (256 - Trunc(Alpha)) + src.b * Trunc(Alpha)) shr 8;
// dst.r := (Trunc(Alpha) * (pixAlpha.r - dst.r) shr 8) + dst.r ;
// dst.g := (Trunc(Alpha) * (pixAlpha.g - dst.g) shr 8) + dst.g ;
// dst.b := (Trunc(Alpha) * (pixAlpha.b - dst.b) shr 8) + dst.b ;
// dst.r := (Trunc(Alpha) * (src.r - dst.r) shr 8) + dst.r ;
// dst.g := (Trunc(Alpha) * (src.g - dst.g) shr 8) + dst.g ;
// dst.b := (Trunc(Alpha) * (src.b - dst.b) shr 8) + dst.b ;
end;
SE_BlendOR:
begin
dst.r := blimit(dst.r or src.r);
dst.g := blimit(dst.g or src.g);
dst.b := blimit(dst.b or src.b);
end;
SE_BlendAND:
begin
dst.r := blimit(dst.r and src.r);
dst.g := blimit(dst.g and src.g);
dst.b := blimit(dst.b and src.b);
end;
SE_BlendXOR:
begin
dst.r := blimit(dst.r xor src.r);
dst.g := blimit(dst.g xor src.g);
dst.b := blimit(dst.b xor src.b);
end;
SE_BlendMAX:
begin
dst.r := imax(dst.r, src.r);
dst.g := imax(dst.g, src.g);
dst.b := imax(dst.b, src.b);
end;
SE_BlendMIN:
begin
dst.r := imin(dst.r, src.r);
dst.g := imin(dst.g, src.g);
dst.b := imin(dst.b, src.b);
end;
SE_BlendAverage:
begin
dst.r := (dst.r + src.r) shr 1;
dst.g := (dst.g + src.g) shr 1;
dst.b := (dst.b + src.b) shr 1;
end;
SE_BlendHardLight:
begin
if src.r < 128 then
dst.r := (src.r * dst.r) shr 7
else
dst.r := 255 - ((255 - src.r) * (255 - dst.r) shr 7);
if src.g < 128 then
dst.g := (src.g * dst.g) shr 7
else
dst.g := 255 - ((255 - src.g) * (255 - dst.g) shr 7);
if src.b < 128 then
dst.b := (src.b * dst.b) shr 7
else
dst.b := 255 - ((255 - src.b) * (255 - dst.b) shr 7);
end;
SE_BlendSoftLight:
begin
dst.r := softlight(src.r, dst.r);
dst.g := softlight(src.r, dst.g);
dst.b := softlight(src.r, dst.b);
end;
SE_BlendReflect:
begin
dst.r := Reflect(src.r, dst.r);
dst.g := Reflect(src.g, dst.g);
dst.b := Reflect(src.b, dst.b);
end;
SE_BlendStamp:
begin
dst.r := Stamp(src.r, dst.r);
dst.g := Stamp(src.g, dst.g);
dst.b := Stamp(src.b, dst.b);
end;
SE_BlendLuminosity:
begin
RGB2HSL(src, Ha, Sa, La);
RGB2HSL(dst, Hb, Sb, Lb);
HSL2RGB(dst, Hb, Sb, La);
end;
SE_BlendLuminosity2:
begin
RGB2YCbCr(src, Y_1, Cb_1, Cr_1);
RGB2YCbCr(dst, Y_2, Cb_2, Cr_2);
YCbCr2RGB(dst, Y_1, Cb_2, Cr_2);
end;
end;
end;
end.
|
unit ListaEnlazadaUnit;
interface
type Nodo = record
dato: integer;
sig: ^Nodo;
end;
type posicion = ^Nodo;
type Lista = ^Nodo;
type PNodo = ^Nodo;
procedure Init(var L: Lista);
function Cantidad(var L: Lista): integer;
function Inicio(var L: Lista): posicion;
function Fin(L: Lista): posicion;
function Siguiente(var L: Lista; pos: posicion): posicion;
procedure Insertar(var L: Lista; valor: integer; pos: posicion);
procedure Suprimir(var L: Lista; pos: posicion);
function Obtener(var L: Lista; pos: posicion): integer;
implementation
procedure Init(var L: Lista);
begin
new(L);
L^.sig:=nil;
end;
function Cantidad(var L: Lista): integer;
var
p: posicion;
cant: integer;
begin
p:= L;
cant:=0;
while(p^.sig <> nil) do
begin
cant:= cant +1;
p := Siguiente(L, p);
end;
Cantidad := cant;
end;
function Inicio(var L: Lista): posicion;
begin
Inicio:=L;
end;
function Fin(L: Lista): posicion;
var p: posicion;
begin
p:= L;
while(p^.sig <> nil) do
begin
p := Siguiente(L, p);
end;
Fin := p;
end;
procedure Insertar(var L: Lista; valor: integer; pos: posicion);
var
temp: posicion;
nuevo: ^Nodo;
begin
temp:= pos^.sig;
new(pos^.sig);
pos^.sig^.dato:=valor;
pos^.sig^.sig:= temp;
end;
procedure Suprimir(var L: Lista; pos: posicion);
begin
pos^.sig:=pos^.sig^.sig;
end;
function Obtener(var L: Lista; pos: posicion): integer;
begin
Obtener:=pos^.dato;
end;
function Siguiente(var L: Lista; pos: posicion): posicion;
begin
Siguiente:=pos^.sig;
end;
end.
|
(******************************************************************************
* 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.Archive.ZIP;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Math,
PasVulkan.Types,
PasVulkan.Collections,
PasVulkan.Compression.Deflate;
type EpvArchiveZIP=class(Exception);
PpvArchiveZIPHeaderSignature=^TpvArchiveZIPHeaderSignature;
TpvArchiveZIPHeaderSignature=packed record
case TpvUInt8 of
0:(
Chars:array[0..3] of TpvRawByteChar;
);
1:(
Value:TpvUInt32;
);
end;
TpvArchiveZIPHeaderSignatures=class
public
const LocalFileHeaderSignature:TpvArchiveZIPHeaderSignature=(Chars:('P','K',#3,#4));
CentralFileHeaderSignature:TpvArchiveZIPHeaderSignature=(Chars:('P','K',#1,#2));
EndCentralFileHeaderSignature:TpvArchiveZIPHeaderSignature=(Chars:('P','K',#5,#6));
end;
TpvArchiveZIPCompressionLevel=0..5;
TpvArchiveZIPDateTimeUtils=class
public
class procedure ConvertDateTimeToZIPDateTime(const aDateTime:TDateTime;out aZIPDate,aZIPTime:TpvUInt16); static;
class function ConvertZIPDateTimeToDateTime(const aZIPDate,aZIPTime:TpvUInt16):TDateTime; static;
end;
PpvArchiveZIPOS=^TpvArchiveZIPOS;
TpvArchiveZIPOS=
(
FAT=0,
UNIX=3,
OS2=6,
NTFS=10,
VFAT=14,
OSX=19
);
PpvArchiveZIPCRC32=^TpvArchiveZIPCRC32;
TpvArchiveZIPCRC32=record
private
const CRC32Table:array[0..255] of TpvUInt32=($00000000,$77073096,$ee0e612c,$990951ba,$076dc419,$706af48f,$e963a535,$9e6495a3,
$0edb8832,$79dcb8a4,$e0d5e91e,$97d2d988,$09b64c2b,$7eb17cbd,$e7b82d07,$90bf1d91,
$1db71064,$6ab020f2,$f3b97148,$84be41de,$1adad47d,$6ddde4eb,$f4d4b551,$83d385c7,
$136c9856,$646ba8c0,$fd62f97a,$8a65c9ec,$14015c4f,$63066cd9,$fa0f3d63,$8d080df5,
$3b6e20c8,$4c69105e,$d56041e4,$a2677172,$3c03e4d1,$4b04d447,$d20d85fd,$a50ab56b,
$35b5a8fa,$42b2986c,$dbbbc9d6,$acbcf940,$32d86ce3,$45df5c75,$dcd60dcf,$abd13d59,
$26d930ac,$51de003a,$c8d75180,$bfd06116,$21b4f4b5,$56b3c423,$cfba9599,$b8bda50f,
$2802b89e,$5f058808,$c60cd9b2,$b10be924,$2f6f7c87,$58684c11,$c1611dab,$b6662d3d,
$76dc4190,$01db7106,$98d220bc,$efd5102a,$71b18589,$06b6b51f,$9fbfe4a5,$e8b8d433,
$7807c9a2,$0f00f934,$9609a88e,$e10e9818,$7f6a0dbb,$086d3d2d,$91646c97,$e6635c01,
$6b6b51f4,$1c6c6162,$856530d8,$f262004e,$6c0695ed,$1b01a57b,$8208f4c1,$f50fc457,
$65b0d9c6,$12b7e950,$8bbeb8ea,$fcb9887c,$62dd1ddf,$15da2d49,$8cd37cf3,$fbd44c65,
$4db26158,$3ab551ce,$a3bc0074,$d4bb30e2,$4adfa541,$3dd895d7,$a4d1c46d,$d3d6f4fb,
$4369e96a,$346ed9fc,$ad678846,$da60b8d0,$44042d73,$33031de5,$aa0a4c5f,$dd0d7cc9,
$5005713c,$270241aa,$be0b1010,$c90c2086,$5768b525,$206f85b3,$b966d409,$ce61e49f,
$5edef90e,$29d9c998,$b0d09822,$c7d7a8b4,$59b33d17,$2eb40d81,$b7bd5c3b,$c0ba6cad,
$edb88320,$9abfb3b6,$03b6e20c,$74b1d29a,$ead54739,$9dd277af,$04db2615,$73dc1683,
$e3630b12,$94643b84,$0d6d6a3e,$7a6a5aa8,$e40ecf0b,$9309ff9d,$0a00ae27,$7d079eb1,
$f00f9344,$8708a3d2,$1e01f268,$6906c2fe,$f762575d,$806567cb,$196c3671,$6e6b06e7,
$fed41b76,$89d32be0,$10da7a5a,$67dd4acc,$f9b9df6f,$8ebeeff9,$17b7be43,$60b08ed5,
$d6d6a3e8,$a1d1937e,$38d8c2c4,$4fdff252,$d1bb67f1,$a6bc5767,$3fb506dd,$48b2364b,
$d80d2bda,$af0a1b4c,$36034af6,$41047a60,$df60efc3,$a867df55,$316e8eef,$4669be79,
$cb61b38c,$bc66831a,$256fd2a0,$5268e236,$cc0c7795,$bb0b4703,$220216b9,$5505262f,
$c5ba3bbe,$b2bd0b28,$2bb45a92,$5cb36a04,$c2d7ffa7,$b5d0cf31,$2cd99e8b,$5bdeae1d,
$9b64c2b0,$ec63f226,$756aa39c,$026d930a,$9c0906a9,$eb0e363f,$72076785,$05005713,
$95bf4a82,$e2b87a14,$7bb12bae,$0cb61b38,$92d28e9b,$e5d5be0d,$7cdcefb7,$0bdbdf21,
$86d3d2d4,$f1d4e242,$68ddb3f8,$1fda836e,$81be16cd,$f6b9265b,$6fb077e1,$18b74777,
$88085ae6,$ff0f6a70,$66063bca,$11010b5c,$8f659eff,$f862ae69,$616bffd3,$166ccf45,
$a00ae278,$d70dd2ee,$4e048354,$3903b3c2,$a7672661,$d06016f7,$4969474d,$3e6e77db,
$aed16a4a,$d9d65adc,$40df0b66,$37d83bf0,$a9bcae53,$debb9ec5,$47b2cf7f,$30b5ffe9,
$bdbdf21c,$cabac28a,$53b39330,$24b4a3a6,$bad03605,$cdd70693,$54de5729,$23d967bf,
$b3667a2e,$c4614ab8,$5d681b02,$2a6f2b94,$b40bbe37,$c30c8ea1,$5a05df1b,$2d02ef8d);
private
fState:TpvUInt32;
public
procedure Initialize;
procedure Update(const aData;const aDataLength:TpvSizeUInt); overload;
procedure Update(const aStream:TStream); overload;
function Finalize:TpvUInt32;
property State:TpvUInt32 read fState write fState;
end;
PpvArchiveZIPLocalFileHeader=^TpvArchiveZIPLocalFileHeader;
TpvArchiveZIPLocalFileHeader=packed record
public
Signature:TpvArchiveZIPHeaderSignature;
ExtractVersion:TpvUInt16;
BitFlags:TpvUInt16;
CompressMethod:TpvUInt16;
Time:TpvUInt16;
Date:TpvUInt16;
CRC32:TpvUInt32;
CompressedSize:TpvUInt32;
UncompressedSize:TpvUInt32;
FileNameLength:TpvUInt16;
ExtraFieldLength:TpvUInt16;
procedure SwapEndiannessIfNeeded;
end;
PpvArchiveZIPExtensibleDataFieldHeader=^TpvArchiveZIPExtensibleDataFieldHeader;
TpvArchiveZIPExtensibleDataFieldHeader=packed record
public
HeaderID:TpvUInt16;
DataSize:TpvUInt16;
procedure SwapEndiannessIfNeeded;
end;
PpvArchiveZIP64ExtensibleInfoFieldHeader=^TpvArchiveZIP64ExtensibleInfoFieldHeader;
TpvArchiveZIP64ExtensibleInfoFieldHeader=packed record
public
OriginalSize:TpvUInt64;
CompressedSize:TpvUInt64;
RelativeHeaderOffset:TpvUInt64;
DiskStartNumber:TpvUInt32;
procedure SwapEndiannessIfNeeded;
end;
PpvArchiveZIPCentralFileHeader=^TpvArchiveZIPCentralFileHeader;
TpvArchiveZIPCentralFileHeader=packed record
public
Signature:TpvArchiveZIPHeaderSignature;
CreatorVersion:TpvUInt16;
ExtractVersion:TpvUInt16;
BitFlags:TpvUInt16;
CompressMethod:TpvUInt16;
Time:TpvUInt16;
Date:TpvUInt16;
CRC32:TpvUInt32;
CompressedSize:TpvUInt32;
UncompressedSize:TpvUInt32;
FileNameLength:TpvUInt16;
ExtraFieldLength:TpvUInt16;
FileCommentLength:TpvUInt16;
StartDiskNumber:TpvUInt16;
InternalAttrributes:TpvUInt16;
ExternalAttrributes:TpvUInt32;
LocalFileHeaderOffset:TpvUInt32;
procedure SwapEndiannessIfNeeded;
end;
PpvArchiveZIPEndCentralFileHeader=^TpvArchiveZIPEndCentralFileHeader;
TpvArchiveZIPEndCentralFileHeader=packed record
public
Signature:TpvArchiveZIPHeaderSignature;
DiskNumber:TpvUInt16;
CentralDirectoryStartDisk:TpvUInt16;
EntriesThisDisk:TpvUInt16;
TotalEntries:TpvUInt16;
CentralDirectorySize:TpvUInt32;
StartDiskOffset:TpvUInt32;
CommentLength:TpvUInt16;
procedure SwapEndiannessIfNeeded;
end;
PpvArchiveZIP64EndCentralFileHeader=^TpvArchiveZIP64EndCentralFileHeader;
TpvArchiveZIP64EndCentralFileHeader=packed record
public
Signature:TpvArchiveZIPHeaderSignature;
RecordSize:TpvUInt64;
VersionMadeBy:TpvUInt16;
ExtractVersionRequired:TpvUInt16;
DiskNumber:TpvUInt32;
CentralDirectoryStartDisk:TpvUInt32;
EntriesThisDisk:TpvUInt64;
TotalEntries:TpvUInt64;
CentralDirectorySize:TpvUInt64;
StartDiskOffset:TpvUInt64;
procedure SwapEndiannessIfNeeded;
end;
PpvArchiveZIP64EndCentralLocator=^TpvArchiveZIP64EndCentralLocator;
TpvArchiveZIP64EndCentralLocator=packed record
public
Signature:TpvArchiveZIPHeaderSignature;
EndOfCentralDirectoryStartDisk:TpvUInt32;
CentralDirectoryOffset:TpvUInt64;
TotalDisks:TpvUInt32;
procedure SwapEndiannessIfNeeded;
end;
TpvArchiveZIP=class;
TpvArchiveZIPEntry=class(TCollectionItem)
private
fFileName:TpvRawByteString;
fAttributes:TpvUInt32;
fDateTime:TDateTime;
fCentralHeaderPosition:TpvInt64;
fHeaderPosition:TpvInt64;
fRequiresZIP64:boolean;
fOS:TpvArchiveZIPOS;
fSize:TpvInt64;
fStream:TStream;
fSourceArchive:TpvArchiveZIP;
fCompressionLevel:TpvArchiveZIPCompressionLevel;
fLocalFileHeader:TpvArchiveZIPLocalFileHeader;
procedure SetFileName(const aFileName:TpvRawByteString);
function GetDirectory:boolean;
function GetLink:boolean;
protected
property CentralHeaderPosition:TpvInt64 read fCentralHeaderPosition write fCentralHeaderPosition;
property HeaderPosition:TpvInt64 read fHeaderPosition write fHeaderPosition;
property RequiresZIP64:boolean read fRequiresZIP64 write fRequiresZIP64;
public
constructor Create(aCollection:TCollection); override;
destructor Destroy; override;
procedure Assign(aSource:TPersistent); override;
procedure LoadFromStream(const aStream:TStream);
procedure LoadFromFile(const aFileName:string);
procedure SaveToStream(const aStream:TStream);
procedure SaveToFile(const aFileName:string);
property Stream:TStream read fStream write fStream;
property SourceArchive:TpvArchiveZIP read fSourceArchive write fSourceArchive;
property Directory:boolean read GetDirectory;
property Link:boolean read GetLink;
published
property FileName:TpvRawByteString read fFileName write SetFileName;
property Attributes:TpvUInt32 read fAttributes write fAttributes;
property DateTime:TDateTime read fDateTime write fDateTime;
property OS:TpvArchiveZIPOS read fOS write fOS;
property Size:TpvInt64 read fSize write fSize;
property CompressionLevel:TpvArchiveZIPCompressionLevel read fCompressionLevel write fCompressionLevel;
end;
TpvArchiveZIPEntriesFileNameHashMap=TpvStringHashMap<TpvArchiveZIPEntry>;
TpvArchiveZIPEntries=class(TCollection)
private
fFileNameHashMap:TpvArchiveZIPEntriesFileNameHashMap;
function GetEntry(const aIndex:TpvSizeInt):TpvArchiveZIPEntry;
procedure SetEntry(const aIndex:TpvSizeInt;const aEntry:TpvArchiveZIPEntry);
public
constructor Create; reintroduce;
destructor Destroy; override;
function Add(const aFileName:TpvRawByteString):TpvArchiveZIPEntry; reintroduce;
function Find(const aFileName:TpvRawByteString):TpvArchiveZIPEntry; reintroduce;
property Entries[const aIndex:TpvSizeInt]:TpvArchiveZIPEntry read GetEntry write SetEntry; default;
end;
TpvArchiveZIP=class
private
fEntries:TpvArchiveZIPEntries;
fStream:TStream;
public
constructor Create;
destructor Destroy; override;
class function CorrectPath(const aFileName:TpvRawByteString):TpvRawByteString; static;
procedure Clear;
procedure LoadFromStream(const aStream:TStream);
procedure LoadFromFile(const aFileName:string);
procedure SaveToStream(const aStream:TStream);
procedure SaveToFile(const aFileName:string);
published
property Entries:TpvArchiveZIPEntries read fEntries;
end;
implementation
procedure TpvArchiveZIPLocalFileHeader.SwapEndiannessIfNeeded;
begin
end;
procedure TpvArchiveZIPExtensibleDataFieldHeader.SwapEndiannessIfNeeded;
begin
end;
procedure TpvArchiveZIP64ExtensibleInfoFieldHeader.SwapEndiannessIfNeeded;
begin
end;
procedure TpvArchiveZIPCentralFileHeader.SwapEndiannessIfNeeded;
begin
end;
procedure TpvArchiveZIPEndCentralFileHeader.SwapEndiannessIfNeeded;
begin
end;
procedure TpvArchiveZIP64EndCentralFileHeader.SwapEndiannessIfNeeded;
begin
end;
procedure TpvArchiveZIP64EndCentralLocator.SwapEndiannessIfNeeded;
begin
end;
class procedure TpvArchiveZIPDateTimeUtils.ConvertDateTimeToZIPDateTime(const aDateTime:TDateTime;out aZIPDate,aZIPTime:TpvUInt16);
var Year,Month,Day,Hour,Minute,Second,Millisecond:TpvUInt16;
begin
DecodeDate(aDateTime,Year,Month,Day);
DecodeTime(aDateTime,Hour,Minute,Second,Millisecond);
if Year<1980 then begin
Year:=0;
Month:=1;
Day:=1;
Hour:=0;
Minute:=0;
Second:=0;
Millisecond:=0;
end else begin
dec(Year,1980);
end;
aZIPDate:=Day+(32*Month)+(512*Year);
aZIPTime:=(Second div 2)+(32*Minute)+(2048*Hour);
end;
class function TpvArchiveZIPDateTimeUtils.ConvertZIPDateTimeToDateTime(const aZIPDate,aZIPTime:TpvUInt16):TDateTime;
begin
result:=EncodeDate(((aZIPDate shr 9) and 127)+1980,
Max(1,(aZIPDate shr 5) and 15),
Max(1,aZIPDate and 31))+
EncodeTime(aZIPTime shr 11,
(aZIPTime shr 5) and 63,
(aZIPTime and 31) shl 1,
0);
end;
procedure TpvArchiveZIPCRC32.Initialize;
begin
fState:=$ffffffff;
end;
procedure TpvArchiveZIPCRC32.Update(const aData;const aDataLength:TpvSizeUInt);
var b:PpvUInt8;
Index:TpvSizeUInt;
begin
b:=@aData;
for Index:=1 to aDataLength do begin
fState:=CRC32Table[(fState and $ff) xor b^] xor ((fState shr 8) and $00ffffff);
inc(b);
end;
end;
procedure TpvArchiveZIPCRC32.Update(const aStream:TStream);
var b:TpvUInt8;
Index:TpvSizeUInt;
begin
if aStream is TMemoryStream then begin
Update(TMemoryStream(aStream).Memory^,aStream.Size);
end else begin
aStream.Seek(0,soBeginning);
for Index:=1 to aStream.Size do begin
aStream.ReadBuffer(b,SizeOf(TpvUInt8));
fState:=CRC32Table[(fState and $ff) xor b] xor ((fState shr 8) and $00ffffff);
end;
end;
end;
function TpvArchiveZIPCRC32.Finalize:TpvUInt32;
begin
result:=not fState;
end;
constructor TpvArchiveZIPEntry.Create(aCollection:TCollection);
begin
inherited Create(aCollection);
fFileName:='';
fOS:=TpvArchiveZIPOS.FAT;
//fOS:={$if defined(Unix) or defined(Posix)}TpvArchiveZIPOS.UNIX{$else}TpvArchiveZIPOS.FAT{$ifend};
fCompressionLevel:=0;
fDateTime:=Now;
fRequiresZIP64:=false;
fAttributes:=0;
fStream:=nil;
end;
destructor TpvArchiveZIPEntry.Destroy;
begin
if (Collection is TpvArchiveZIPEntries) and
(length(fFileName)>0) then begin
(Collection as TpvArchiveZIPEntries).fFileNameHashMap.Delete(fFileName);
end;
FreeAndNil(fStream);
inherited Destroy;
end;
procedure TpvArchiveZIPEntry.SetFileName(const aFileName:TpvRawByteString);
var NewFileName:TpvRawByteString;
begin
NewFileName:=TpvArchiveZIP.CorrectPath(aFileName);
if fFileName<>NewFileName then begin
if (Collection is TpvArchiveZIPEntries) and
(length(fFileName)>0) then begin
(Collection as TpvArchiveZIPEntries).fFileNameHashMap.Delete(fFileName);
end;
fFileName:=NewFileName;
if (Collection is TpvArchiveZIPEntries) and
(length(fFileName)>0) then begin
(Collection as TpvArchiveZIPEntries).fFileNameHashMap.Add(fFileName,self);
end;
end;
end;
procedure TpvArchiveZIPEntry.Assign(aSource:TPersistent);
var Source:TpvArchiveZIPEntry;
begin
if assigned(aSource) and (aSource is TpvArchiveZIPEntry) then begin
Source:=aSource as TpvArchiveZIPEntry;
SetFileName(Source.fFileName);
fAttributes:=Source.fAttributes;
fDateTime:=Source.fDateTime;
fCentralHeaderPosition:=Source.fCentralHeaderPosition;
fHeaderPosition:=Source.fHeaderPosition;
fRequiresZIP64:=Source.fRequiresZIP64;
fOS:=Source.fOS;
fSize:=Source.fSize;
if assigned(Source.fStream) then begin
fStream:=TMemoryStream.Create;
Source.fStream.Seek(0,soBeginning);
fStream.CopyFrom(Source.fStream,Source.fStream.Size);
fStream.Seek(0,soBeginning);
end else begin
FreeAndNil(fStream);
end;
fSourceArchive:=Source.fSourceArchive;
fCompressionLevel:=Source.fCompressionLevel;
end else begin
inherited Assign(aSource);
end;
end;
function TpvArchiveZIPEntry.GetDirectory:boolean;
begin
result:=((Attributes=0) and (length(fFileName)>0) and (fFileName[length(fFileName)-1]='/')) or
((Attributes<>0) and
((((fOS=TpvArchiveZIPOS.FAT) and ((fAttributes and faDirectory)<>0))) or
((fOS=TpvArchiveZIPOS.UNIX) and ((fAttributes and $f000)=$4000))));
end;
function TpvArchiveZIPEntry.GetLink:boolean;
begin
result:=(Attributes<>0) and
((((fOS=TpvArchiveZIPOS.FAT) and ((fAttributes and faSymLink)<>0))) or
((fOS=TpvArchiveZIPOS.UNIX) and ((fAttributes and $f000)=$a000)));
end;
procedure TpvArchiveZIPEntry.LoadFromStream(const aStream:TStream);
begin
FreeAndNil(fStream);
fStream:=TMemoryStream.Create;
aStream.Seek(0,soBeginning);
fStream.CopyFrom(aStream,aStream.Size);
aStream.Seek(0,soBeginning);
fSourceArchive:=nil;
end;
procedure TpvArchiveZIPEntry.LoadFromFile(const aFileName:string);
var Stream:TStream;
begin
Stream:=TFileStream.Create(aFileName,fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TpvArchiveZIPEntry.SaveToStream(const aStream:TStream);
var LocalFileHeader:TpvArchiveZIPLocalFileHeader;
BitBuffer,OriginalCRC:TpvUInt32;
BitsInBitBuffer,FilePosition,InputBufferPosition,SlideWindowPosition:TpvSizeInt;
ReachedSize,CompressedSize,UncompressedSize:TpvInt64;
Offset,StartPosition,From:TpvInt64;
CRC32:TpvArchiveZIPCRC32;
ItIsAtEnd:boolean;
ExtensibleDataFieldHeader:TpvArchiveZIPExtensibleDataFieldHeader;
ExtensibleInfoFieldHeader:TpvArchiveZIP64ExtensibleInfoFieldHeader;
function Decompress(const InStream,OutStream:TStream):boolean;
const StatusOk=0;
StatusCRCErr=-1;
StatusWriteErr=-2;
StatusReadErr=-3;
StatusZipFileErr=-4;
StatusUserAbort=-5;
StatusNotSupported=-6;
StatusEncrypted=-7;
StatusInUse=-8;
StatusInternalError=-9;
StatusNoMoreItems=-10;
StatusFileError=-11;
StatusNoTpvArchiveZIPfile=-12;
StatusHeaderTooLarge=-13;
StatusZipFileOpenError=-14;
StatusSeriousError=-100;
StatusMissingParameter=-500;
HuffmanTreeComplete=0;
HuffmanTreeIncomplete=1;
HuffmanTreeError=2;
HuffmanTreeOutOfMemory=3;
MaxMax=31*1024;
SlidingDictionaryWindowSize=$8000;
InBufferSize=1024*4;
DefaultLiteralBits=9;
DefaultDistanceBits=6;
BitLengthCountMax=16;
OrderOfBitLengthMax=288;
HuffManTreeBuildMaxValue=16;
MaxCode=8192;
MaxStack=8192;
InitialCodeSize=9;
FinalCodeSize=13;
TFileBufferSize=high(TpvInt32)-16;
TFileNameSize=259;
SupportedMethods=1 or (1 shl 1) or (1 shl 6) or (1 shl 8);
MaskBits:array[0..16] of TpvUInt16=($0000,$0001,$0003,$0007,$000f,$001f,$003f,$007f,$00ff,$01ff,$03ff,$07ff,$0fff,$1fff,$3fff,$7fff,$ffff);
Border:array[0..18] of TpvUInt8=(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15);
CopyLengthLiteralCodes:array[0..30] of TpvUInt16=(3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0);
ExtraBitsLiteralCodes:array[0..30] of TpvUInt16=(0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,99,99);
CopyOffsetDistanceCodes:array[0..29] of TpvUInt16=(1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577);
ExtraBitsDistanceCodes:array[0..29] of TpvUInt16=(0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13);
CopyLength2:array[0..63] of TpvUInt16=(2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65);
CopyLength3:array[0..63] of TpvUInt16=(3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66);
ExtraBitsTable:array[0..63] of TpvUInt16=(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8);
CopyOffserDistanceCodes4:array[0..63] of TpvUInt16 =(1,65,129,193,257,321,385,449,513,577,641,705,769,833,897,961,1025,1089,1153,1217,1281,1345,1409,1473,1537,1601,1665,1729,1793,1857,1921,1985,2049,2113,2177,2241,2305,2369,2433,2497,2561,2625,2689,2753,2817,2881,2945,3009,3073,3137,3201,3265,3329,3393,3457,3521,3585,3649,3713,3777,3841,3905,3969,4033);
CopyOffserDistanceCodes8:array[0..63] of TpvUInt16=(1,129,257,385,513,641,769,897,1025,1153,1281,1409,1537,1665,1793,1921,2049,2177,2305,2433,2561,2689,2817,2945,3073,3201,3329,3457,3585,3713,3841,3969,4097,4225,4353,4481,4609,4737,4865,4993,5121,5249,5377,5505,5633,5761,5889,6017,6145,6273,6401,6529,6657,6785,6913,7041,7169,7297,7425,7553,7681,7809,7937,8065);
type PUSBList=^TUSBList;
TUSBList=array[0..MaxMax] of TpvUInt16;
PIOBuffer=^TIOBuffer;
TIOBuffer=array[0..InBufferSize-1] of TpvUInt8;
PPHuffManTree=^PHuffManTree;
PHuffManTree=^THuffManTree;
PHuffManTreeList=^THuffManTreeList;
THuffManTree=record
ExtraBits,CodeBits:TpvUInt8;
ByteSize:TpvUInt16;
LinkList:PHuffManTreeList;
end;
THuffManTreeList=array[0..8190] of THuffManTree;
PPreviousCodeTrie=^TPreviousCodeTrie;
TPreviousCodeTrie=array[257..MaxCode] of TpvInt32;
PActualCodeTrie=^TActualCodeTrie;
TActualCodeTrie=array[257..MaxCode] of TpvUInt8;
PStack=^TStack;
TStack=array[0..MaxStack] of TpvUInt8;
PSlide=^TSlide;
TSlide=array[0..SlidingDictionaryWindowSize-1] of TpvUInt8;
var Slide:PSlide;
InputBuffer:TIOBuffer;
InputBufferPosition:TpvInt32;
FilePosition:TpvInt32;
SlideWindowPosition:TpvUInt16;
BitBuffer:TpvUInt32;
BitsInBitBuffer:TpvUInt8;
ReachedSize:int64;
BitsFlagsType:TpvUInt16;
UserAbort,ItIsAtEnd:boolean;
PreviousCode:PPreviousCodeTrie;
ActualCode:PActualCodeTrie;
Stack:PStack;
NextFreeCodeInTrie:TpvInt32;
procedure UpdateCRC(const IOBuffer:TIOBuffer;InLen:TpvInt32);
begin
CRC32.Update(IOBuffer,InLen);
end;
procedure Idle;
begin
end;
procedure ReadBuffer;
begin
if ReachedSize>(CompressedSize+2) then begin
FilePosition:=SizeOf(TIOBuffer);
ItIsAtEnd:=true;
end else begin
Idle;
FilePosition:=InStream.Read(InputBuffer,SizeOf(TIOBuffer));
if FilePosition<=0 then begin
FilePosition:=SizeOf(TIOBuffer);
ItIsAtEnd:=true;
end;
inc(ReachedSize,FilePosition);
dec(FilePosition);
end;
InputBufferPosition:=0;
end;
procedure ReadByte(var B:TpvUInt8);
begin
if InputBufferPosition>FilePosition then begin
ReadBuffer;
end;
B:=InputBuffer[InputBufferPosition];
inc(InputBufferPosition);
end;
procedure NeedBits(Count:TpvUInt8);
var Value:TpvUInt32;
begin
while BitsInBitBuffer<Count do begin
if InputBufferPosition>FilePosition then begin
ReadBuffer;
end;
Value:=InputBuffer[InputBufferPosition];
inc(InputBufferPosition);
BitBuffer:=BitBuffer or (Value shl BitsInBitBuffer);
inc(BitsInBitBuffer,8);
end;
end;
procedure DumpBits(Count:TpvUInt8);
begin
BitBuffer:=BitBuffer shr Count;
dec(BitsInBitBuffer,Count);
end;
function ReadBits(Count:TpvInt32):TpvInt32;
begin
if Count>0 then begin
NeedBits(Count);
result:=BitBuffer and ((1 shl Count)-1);
DumpBits(Count);
end else begin
result:=0;
end;
end;
function Flush(Bytes:TpvUInt32):boolean;
begin
result:=OutStream.Write(Slide^[0],Bytes)=TpvInt32(Bytes);
CRC32.Update(Slide^[0],Bytes);
end;
procedure HuffManTreeFree(T:PHuffManTreeList);
var P,Q:PHuffManTreeList;
Z:TpvInt32;
begin
P:=T;
while assigned(P) do begin
dec(TpvPtrUInt(P),SizeOf(THuffManTree));
Q:=P^[0].LinkList;
Z:=P^[0].ByteSize;
FreeMem(P,(Z+1)*SizeOf(THuffManTree));
P:=Q;
end;
end;
function HuffManTreeBuild(B:pword;N:TpvUInt16;S:TpvUInt16;D,E:PUSBList;T:PPHuffManTree;var M:TpvInt32):TpvInt32;
type TBitLengthCountTable=array[0..BitLengthCountMax+1] of TpvUInt16;
var CodeLengthKCount:TpvUInt16;
BitLengthCountTable:TBitLengthCountTable;
CurrentCodeCounterRepeatsEveryFEntries:TpvUInt16;
MaxCodeLength:TpvInt32;
TableLevel:TpvInt32;
CurrentCodeCounter:TpvUInt16;
Counter:TpvUInt16;
NumberOfBitsInCurrentCode:TpvInt32;
P:pword;
CurrentTable:PHuffManTreeList;
TableEntry:THuffManTree;
TableStack:array[0..BitLengthCountMax] of PHuffManTreeList;
ValuesInOrderOfBitsLength:array[0..OrderOfBitLengthMax] of TpvUInt16;
BitsBeforeThisTable:TpvInt32;
BitOffsets:array[0..BitLengthCountMax+1] of TpvUInt16;
LLevelBitsInTableOfLevel:array[-1..BitLengthCountMax+1] of TpvUInt16;
BitOffsetPointer:pword;
NumberOfDummyCodesAdded:TpvInt32;
NumberOfEntriesInCurrentTable:TpvUInt16;
PT:PHuffManTree;
EOBCodeLength:TpvUInt16;
begin
if N>256 then begin
EOBCodeLength:=pword(TpvPtrUInt(TpvPtrUInt(B)+(256*SizeOf(TpvUInt16))))^;
end else begin
EOBCodeLength:=HuffManTreeBuildMaxValue;
end;
FillChar(BitLengthCountTable,SizeOf(TBitLengthCountTable),#0);
P:=B;
CurrentCodeCounter:=N;
repeat
if P^>BitLengthCountMax then begin
T^:=nil;
M:=0;
HuffManTreeBuild:=HuffmanTreeError;
exit;
end;
inc(BitLengthCountTable[P^]);
inc(TpvPtrUInt(P),SizeOf(TpvUInt16));
dec(CurrentCodeCounter);
until CurrentCodeCounter=0;
if BitLengthCountTable[0]=N then begin
T^:=nil;
M:=0;
HuffManTreeBuild:=HuffmanTreeComplete;
exit;
end;
Counter:=1;
while (Counter<=BitLengthCountMax) and (BitLengthCountTable[Counter]=0) do inc(Counter);
NumberOfBitsInCurrentCode:=Counter;
if M<Counter then M:=Counter;
CurrentCodeCounter:=BitLengthCountMax;
while (CurrentCodeCounter>0) and (BitLengthCountTable[CurrentCodeCounter]=0) do dec(CurrentCodeCounter);
MaxCodeLength:=CurrentCodeCounter;
if M>CurrentCodeCounter then M:=CurrentCodeCounter;
NumberOfDummyCodesAdded:=1 shl Counter;
while Counter<CurrentCodeCounter do begin
dec(NumberOfDummyCodesAdded,BitLengthCountTable[Counter]);
if NumberOfDummyCodesAdded<0 then begin
HuffManTreeBuild:=HuffmanTreeError;
exit;
end;
NumberOfDummyCodesAdded:=NumberOfDummyCodesAdded shl 1;
inc(Counter);
end;
dec(NumberOfDummyCodesAdded,BitLengthCountTable[CurrentCodeCounter]);
if NumberOfDummyCodesAdded<0 then begin
HuffManTreeBuild:=HuffmanTreeError;
exit;
end;
inc(BitLengthCountTable[CurrentCodeCounter],NumberOfDummyCodesAdded);
BitOffsets[1]:=0;
Counter:=0;
P:=pword(@BitLengthCountTable);
inc(TpvPtrUInt(P),SizeOf(TpvUInt16));
BitOffsetPointer:=pword(@BitOffsets);
inc(TpvPtrUInt(BitOffsetPointer),2*SizeOf(TpvUInt16));
dec(CurrentCodeCounter);
while CurrentCodeCounter<>0 do begin
inc(Counter,P^);
BitOffsetPointer^:=Counter;
inc(TpvPtrUInt(P),SizeOf(TpvUInt16));
inc(TpvPtrUInt(BitOffsetPointer),SizeOf(TpvUInt16));
dec(CurrentCodeCounter);
end;
P:=B;
CurrentCodeCounter:=0;
repeat
Counter:=P^;
inc(TpvPtrUInt(P),SizeOf(TpvUInt16));
if Counter<>0 then begin
ValuesInOrderOfBitsLength[BitOffsets[Counter]]:=CurrentCodeCounter;
inc(BitOffsets[Counter]);
end;
inc(CurrentCodeCounter);
until CurrentCodeCounter>=N;
BitOffsets[0]:=0;
CurrentCodeCounter:=0;
P:=pword(@ValuesInOrderOfBitsLength);
TableLevel:=-1;
LLevelBitsInTableOfLevel[-1]:=0;
BitsBeforeThisTable:=0;
TableStack[0]:=nil;
CurrentTable:=nil;
NumberOfEntriesInCurrentTable:=0;
for NumberOfBitsInCurrentCode:=NumberOfBitsInCurrentCode to MaxCodeLength do begin
for CodeLengthKCount:=BitLengthCountTable[NumberOfBitsInCurrentCode] downto 1 do begin
while NumberOfBitsInCurrentCode>(BitsBeforeThisTable+LLevelBitsInTableOfLevel[TableLevel]) do begin
inc(BitsBeforeThisTable,LLevelBitsInTableOfLevel[TableLevel]);
inc(TableLevel);
NumberOfEntriesInCurrentTable:=MaxCodeLength-BitsBeforeThisTable;
if NumberOfEntriesInCurrentTable>M then NumberOfEntriesInCurrentTable:=M;
Counter:=NumberOfBitsInCurrentCode-BitsBeforeThisTable;
CurrentCodeCounterRepeatsEveryFEntries:=1 shl Counter;
if CurrentCodeCounterRepeatsEveryFEntries>(CodeLengthKCount+1) then begin
dec(CurrentCodeCounterRepeatsEveryFEntries,CodeLengthKCount+1);
BitOffsetPointer:=@BitLengthCountTable[NumberOfBitsInCurrentCode];
inc(Counter);
while Counter<NumberOfEntriesInCurrentTable do begin
CurrentCodeCounterRepeatsEveryFEntries:=CurrentCodeCounterRepeatsEveryFEntries shl 1;
inc(TpvPtrUInt(BitOffsetPointer),SizeOf(TpvUInt16));
if CurrentCodeCounterRepeatsEveryFEntries<=BitOffsetPointer^ then begin
break;
end else begin
dec(CurrentCodeCounterRepeatsEveryFEntries,BitOffsetPointer^);
inc(Counter);
end;
end;
end;
if (BitsBeforeThisTable+Counter>EOBCodeLength) and (BitsBeforeThisTable<EOBCodeLength) then Counter:=EOBCodeLength-BitsBeforeThisTable;
if BitsBeforeThisTable=0 then Counter:=M;
NumberOfEntriesInCurrentTable:=1 shl Counter;
LLevelBitsInTableOfLevel[TableLevel]:=Counter;
GETMEM(CurrentTable,(NumberOfEntriesInCurrentTable+1)*SizeOf(THuffManTree));
if not assigned(CurrentTable) then begin
if TableLevel<>0 then HuffManTreeFree(TableStack[0]);
HuffManTreeBuild:=HuffmanTreeOutOfMemory;
exit;
end;
FillChar(CurrentTable^,(NumberOfEntriesInCurrentTable+1)*SizeOf(THuffManTree),#0);
CurrentTable^[0].ByteSize:=NumberOfEntriesInCurrentTable;
T^:=@CurrentTable^[1];
T:=PPHuffManTree(@CurrentTable^[0].LinkList);
T^:=nil;
CurrentTable:=PHuffManTreeList(@CurrentTable^[1]);
TableStack[TableLevel]:=CurrentTable;
if TableLevel<>0 then begin
BitOffsets[TableLevel]:=CurrentCodeCounter;
TableEntry.CodeBits:=LLevelBitsInTableOfLevel[TableLevel-1];
TableEntry.ExtraBits:=16+Counter;
TableEntry.LinkList:=CurrentTable;
Counter:=(CurrentCodeCounter and ((1 shl BitsBeforeThisTable)-1)) shr (BitsBeforeThisTable-LLevelBitsInTableOfLevel[TableLevel-1]);
PT:=PHuffManTree(TpvPtrUInt(TpvPtrUInt(TableStack[TableLevel-1])-SizeOf(THuffManTree)));
if Counter>PT^.ByteSize then begin
HuffManTreeFree(TableStack[0]);
HuffManTreeBuild:=HuffmanTreeError;
exit;
end;
PT:=@TableStack[TableLevel-1]^[Counter];
PT^:=TableEntry;
end;
end;
TableEntry.CodeBits:=TpvUInt16(NumberOfBitsInCurrentCode-BitsBeforeThisTable);
TableEntry.LinkList:=nil;
if TpvPtrUInt(P)>=TpvPtrUInt(@ValuesInOrderOfBitsLength[N]) then begin
TableEntry.ExtraBits:=99;
end else if P^<S then begin
if P^<256 then begin
TableEntry.ExtraBits:=16;
end else begin
TableEntry.ExtraBits:=15;
end;
TableEntry.ByteSize:=P^;
inc(TpvPtrUInt(P),SizeOf(TpvUInt16));
end else begin
if not (assigned(D) and assigned(E)) then begin
HuffManTreeFree(TableStack[0]);
HuffManTreeBuild:=HuffmanTreeError;
exit;
end;
TableEntry.ExtraBits:=TpvUInt16(E^[P^-S]);
TableEntry.ByteSize:=D^[P^-S];
inc(TpvPtrUInt(P),SizeOf(TpvUInt16));
end;
CurrentCodeCounterRepeatsEveryFEntries:=1 shl(NumberOfBitsInCurrentCode-BitsBeforeThisTable);
Counter:=CurrentCodeCounter shr BitsBeforeThisTable;
while Counter<NumberOfEntriesInCurrentTable do begin
CurrentTable^[Counter]:=TableEntry;
inc(Counter,CurrentCodeCounterRepeatsEveryFEntries);
end;
Counter:=1 shl(NumberOfBitsInCurrentCode-1);
while(CurrentCodeCounter and Counter)<> 0 do begin
CurrentCodeCounter:=CurrentCodeCounter xor Counter;
Counter:=Counter shr 1;
end;
CurrentCodeCounter:=CurrentCodeCounter xor Counter;
while ((CurrentCodeCounter and ((1 shl BitsBeforeThisTable)-1))<>BitOffsets[TableLevel]) do begin
dec(TableLevel);
dec(BitsBeforeThisTable,LLevelBitsInTableOfLevel[TableLevel]);
end;
end;
end;
if (NumberOfDummyCodesAdded<>0) and (MaxCodeLength<>1) then begin
result:=HuffmanTreeIncomplete;
end else begin
result:=HuffmanTreeComplete;
end;
end;
function InflateCodes(LiteralLengthCodeTable,DistanceCodeTable:PHuffManTreeList;LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits:TpvInt32):TpvInt32;
var N,D,ElementLength:TpvUInt16;
LMask,DMask:TpvUInt16;
T:PHuffManTree;
TableEntry:TpvUInt8;
begin
LMask:=MaskBits[LiteralLengthCodeTableLookupBits];
DMask:=MaskBits[DistanceCodeTableLookupBits];
while not (UserAbort or ItIsAtEnd) do begin
NeedBits(LiteralLengthCodeTableLookupBits);
T:=@LiteralLengthCodeTable^[BitBuffer and LMask];
TableEntry:=T^.ExtraBits;
if TableEntry>16 then begin
repeat
if TableEntry=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(TableEntry,16);
NeedBits(TableEntry);
T:=@T^.LinkList^[BitBuffer and MaskBits[TableEntry]];
TableEntry:=T^.ExtraBits;
until TableEntry<=16;
end;
DumpBits(T^.CodeBits);
if TableEntry=16 then begin
Slide^[SlideWindowPosition]:=T^.ByteSize;
inc(SlideWindowPosition);
if SlideWindowPosition=SlidingDictionaryWindowSize then begin
if not Flush(SlideWindowPosition) then begin
InflateCodes:=StatusWriteErr;
exit;
end;
SlideWindowPosition:=0;
end;
end else begin
if TableEntry=15 then begin
InflateCodes:=StatusOk;
exit;
end;
NeedBits(TableEntry);
N:=T^.ByteSize+(BitBuffer and MaskBits[TableEntry]);
DumpBits(TableEntry);
NeedBits(DistanceCodeTableLookupBits);
T:=@DistanceCodeTable^[BitBuffer and DMask];
TableEntry:=T^.ExtraBits;
if TableEntry>16 then begin
repeat
if TableEntry=99 then begin
InflateCodes:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(TableEntry,16);
NeedBits(TableEntry);
T:=@T^.LinkList^[BitBuffer and MaskBits[TableEntry]];
TableEntry:=T^.ExtraBits;
until TableEntry<=16;
end;
DumpBits(T^.CodeBits);
NeedBits(TableEntry);
D:=SlideWindowPosition-T^.ByteSize-TpvUInt16(BitBuffer and MaskBits[TableEntry]);
DumpBits(TableEntry);
repeat
D:=D and (SlidingDictionaryWindowSize-1);
if D>SlideWindowPosition then begin
ElementLength:=SlidingDictionaryWindowSize-D;
end else begin
ElementLength:=SlidingDictionaryWindowSize-SlideWindowPosition;
end;
if ElementLength>N then ElementLength:=N;
dec(N,ElementLength);
if (SlideWindowPosition-D)>=ElementLength then begin
Move(Slide^[D],Slide^[SlideWindowPosition],ElementLength);
inc(SlideWindowPosition,ElementLength);
inc(D,ElementLength);
end else begin
repeat
Slide^[SlideWindowPosition]:=Slide^[D];
inc(SlideWindowPosition);
inc(D);
dec(ElementLength);
until ElementLength=0;
end;
if SlideWindowPosition=SlidingDictionaryWindowSize then begin
if not Flush(SlideWindowPosition) then begin
result:=StatusWriteErr;
exit;
end;
SlideWindowPosition:=0;
end;
until N=0;
end;
end;
if UserAbort then begin
result:=Statususerabort
end else begin
result:=StatusreadErr;
end;
end;
function InflateStored:TpvInt32;
var NumberOfBlockInBlock:TpvUInt16;
begin
NumberOfBlockInBlock:=BitsInBitBuffer and 7;
DumpBits(NumberOfBlockInBlock);
NeedBits(16);
NumberOfBlockInBlock:=BitBuffer and $ffff;
DumpBits(16);
NeedBits(16);
if NumberOfBlockInBlock<>((not BitBuffer) and $ffff) then begin
result:=StatuszipFileErr;
exit;
end;
DumpBits(16);
while (NumberOfBlockInBlock>0) and not (UserAbort or ItIsAtEnd) do begin
dec(NumberOfBlockInBlock);
NeedBits(8);
Slide^[SlideWindowPosition]:=BitBuffer;
inc(SlideWindowPosition);
if SlideWindowPosition=SlidingDictionaryWindowSize then begin
if not Flush(SlideWindowPosition)then begin
result:=StatusWriteErr;
exit;
end;
SlideWindowPosition:=0;
end;
DumpBits(8);
end;
if UserAbort then begin
result:=StatusUserAbort;
end else if ItIsAtEnd then begin
result:=StatusreadErr;
end else begin
result:=StatusOk;
end;
end;
function InflateFixed:TpvInt32;
var Counter,Value:TpvInt32;
LiteralLengthCodeTable,DistanceCodeTable:PHuffManTreeList;
LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits:TpvInt32;
LengthList:array[0..287] of TpvUInt16;
begin
for Counter:=0 to 143 do LengthList[Counter]:=8;
for Counter:=144 to 255 do LengthList[Counter]:=9;
for Counter:=256 to 279 do LengthList[Counter]:=7;
for Counter:=280 to 287 do LengthList[Counter]:=8;
LiteralLengthCodeTableLookupBits:=7;
Value:=HuffManTreeBuild(pword(@LengthList),288,257,PUSBList(@CopyLengthLiteralCodes),PUSBList(@ExtraBitsLiteralCodes),PPHuffManTree(@LiteralLengthCodeTable),LiteralLengthCodeTableLookupBits); {@@}
if Value<>HuffmanTreeComplete then begin
result:=Value;
exit;
end;
for Counter:=0 to 29 do LengthList[Counter]:=5;
DistanceCodeTableLookupBits:=5;
if HuffManTreeBuild(pword(@LengthList),30,0,PUSBList(@CopyOffsetDistanceCodes),PUSBList(@ExtraBitsDistanceCodes),PPHuffManTree(@DistanceCodeTable),DistanceCodeTableLookupBits)>HuffmanTreeIncomplete then begin
HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
result:=InflateCodes(LiteralLengthCodeTable,DistanceCodeTable,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits);
HuffManTreeFree(LiteralLengthCodeTable);
HuffManTreeFree(DistanceCodeTable);
end;
function InflateDynamic:TpvInt32;
var I:TpvInt32;
J:TpvUInt16;
LastLength:TpvUInt16;
BitLengthTableMask:TpvUInt16;
NumberOfLengthsToGet:TpvUInt16;
LiteralLengthCodeTable,
DistanceCodeTable:PHuffManTreeList;
LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits:TpvInt32;
NumberOfBitLengthCodes,NumberOfLiteralLengthCodes,NumberOfDistanceCodes:TpvUInt16;
LiteralLengthDistanceCodeLengths:array[0..288+32-1] of TpvUInt16;
begin
NeedBits(5);
NumberOfLiteralLengthCodes:=257+TpvUInt16(BitBuffer) and $1f;
DumpBits(5);
NeedBits(5);
NumberOfDistanceCodes:=1+TpvUInt16(BitBuffer) and $1f;
DumpBits(5);
NeedBits(4);
NumberOfBitLengthCodes:=4+TpvUInt16(BitBuffer) and $f;
DumpBits(4);
if (NumberOfLiteralLengthCodes>288) or (NumberOfDistanceCodes>32) then begin
result:=1;
exit;
end;
FillChar(LiteralLengthDistanceCodeLengths,SizeOf(LiteralLengthDistanceCodeLengths),#0);
for J:=0 to NumberOfBitLengthCodes-1 do begin
NeedBits(3);
LiteralLengthDistanceCodeLengths[Border[J]]:=BitBuffer and 7;
DumpBits(3);
end;
for J:=NumberOfBitLengthCodes to 18 do LiteralLengthDistanceCodeLengths[Border[J]]:=0;
LiteralLengthCodeTableLookupBits:=7;
I:=HuffManTreeBuild(pword(@LiteralLengthDistanceCodeLengths),19,19,nil,nil,PPHuffManTree(@LiteralLengthCodeTable),LiteralLengthCodeTableLookupBits); {@@}
if I<>HuffmanTreeComplete then begin
if I=HuffmanTreeIncomplete then HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
NumberOfLengthsToGet:=NumberOfLiteralLengthCodes+NumberOfDistanceCodes;
BitLengthTableMask:=MaskBits[LiteralLengthCodeTableLookupBits];
I:=0;
LastLength:=0;
while TpvUInt16(I)<NumberOfLengthsToGet do begin
NeedBits(LiteralLengthCodeTableLookupBits);
DistanceCodeTable:=PHuffManTreeList(@LiteralLengthCodeTable^[BitBuffer and BitLengthTableMask]);
J:=PHuffManTree(DistanceCodeTable)^.CodeBits;
DumpBits(J);
J:=PHuffManTree(DistanceCodeTable)^.ByteSize;
if J<16 then begin
LastLength:=J;
LiteralLengthDistanceCodeLengths[I]:=LastLength;
inc(I)
end else if J=16 then begin
NeedBits(2);
J:=3+(BitBuffer and 3);
DumpBits(2);
if (I+J)>NumberOfLengthsToGet then begin
result:=1;
exit;
end;
while J>0 do begin
LiteralLengthDistanceCodeLengths[I]:=LastLength;
dec(J);
inc(I);
end;
end else if J=17 then begin
NeedBits(3);
J:=3+(BitBuffer and 7);
DumpBits(3);
if (I+J)>NumberOfLengthsToGet then begin
result:=1;
exit;
end;
while J>0 do begin
LiteralLengthDistanceCodeLengths[I]:=0;
inc(I);
dec(J);
end;
LastLength:=0;
end else begin
NeedBits(7);
J:=11+(BitBuffer and $7f);
DumpBits(7);
if (I+J)>NumberOfLengthsToGet then begin
result:=StatuszipfileErr;
exit;
end;
while J>0 do begin
LiteralLengthDistanceCodeLengths[I]:=0;
dec(J);
inc(I);
end;
LastLength:=0;
end;
end;
HuffManTreeFree(LiteralLengthCodeTable);
LiteralLengthCodeTableLookupBits:=DefaultLiteralBits;
I:=HuffManTreeBuild(pword(@LiteralLengthDistanceCodeLengths),NumberOfLiteralLengthCodes,257,PUSBList(@CopyLengthLiteralCodes),PUSBList(@ExtraBitsLiteralCodes),PPHuffManTree(@LiteralLengthCodeTable),LiteralLengthCodeTableLookupBits);
if I<>HuffmanTreeComplete then begin
if I=HuffmanTreeIncomplete then HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
DistanceCodeTableLookupBits:=DefaultDistanceBits;
I:=HuffManTreeBuild(pword(@LiteralLengthDistanceCodeLengths[NumberOfLiteralLengthCodes]),NumberOfDistanceCodes,0,PUSBList(@CopyOffsetDistanceCodes),PUSBList(@ExtraBitsDistanceCodes),PPHuffManTree(@DistanceCodeTable),DistanceCodeTableLookupBits);
if I>HuffmanTreeIncomplete then begin
if I=HuffmanTreeIncomplete then HuffManTreeFree(DistanceCodeTable);
HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
InflateDynamic:=InflateCodes(LiteralLengthCodeTable,DistanceCodeTable,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits);
HuffManTreeFree(LiteralLengthCodeTable);
HuffManTreeFree(DistanceCodeTable);
end;
function InflateBlock(var E:TpvInt32):TpvInt32;
var T:TpvUInt16;
begin
NeedBits(1);
E:=BitBuffer and 1;
DumpBits(1);
NeedBits(2);
T:=BitBuffer and 3;
DumpBits(2);
case T of
0:result:=InflateStored;
1:result:=InflateFixed;
2:result:=InflateDynamic;
else result:=StatusZipFileErr;
end;
end;
function Inflate:TpvInt32;
var LastBlockFlag:TpvInt32;
begin
InputBufferPosition:=0;
FilePosition:=-1;
SlideWindowPosition:=0;
BitsInBitBuffer:=0;
BitBuffer:=0;
repeat
result:=InflateBlock(LastBlockFlag);
if result<>0 then begin
exit;
end;
until LastBlockFlag<>0;
if not Flush(SlideWindowPosition) then begin
result:=StatusWriteErr;
end else begin
result:=StatusOk;
end;
end;
function CopyStored:TpvInt32;
var DoReadInBytes,ReadInBytes:TpvInt32;
begin
while (ReachedSize<CompressedSize) and not UserAbort do begin
DoReadInBytes:=CompressedSize-ReachedSize;
if DoReadInBytes>SlidingDictionaryWindowSize then begin
DoReadInBytes:=SlidingDictionaryWindowSize;
end;
ReadInBytes:=InStream.Read(Slide^[0],DoReadInBytes);
if ReadInBytes<>DoReadInBytes then begin
result:=StatusReadErr;
exit;
end;
if not Flush(ReadInBytes) then begin
result:=StatusWriteErr;
exit;
end;
inc(ReachedSize,ReadInBytes);
Idle;
end;
if UserAbort then begin
result:=StatusUserabort;
end else begin
result:=StatusOk;
end;
end;
function GetTree(l:pword;N:TpvUInt16):TpvInt32;
var I,K,J,B:TpvUInt16;
ByteBuffer:TpvUInt8;
begin
ReadByte(ByteBuffer);
I:=ByteBuffer;
inc(I);
K:=0;
repeat
ReadByte(ByteBuffer);
J:=ByteBuffer;
B:=(J and $f)+1;
J:=((J and $f0) shr 4)+1;
if (K+J)>N then begin
result:=4;
exit;
end;
repeat
l^:=B;
inc(TpvPtrUInt(l),SizeOf(TpvUInt16));
inc(K);
dec(J);
until J=0;
dec(I);
until I=0;
if K<>N then begin
result:=4;
end else begin
result:=0;
end;
end;
function ExplodeLiteral8k(BitLengthCodeTable,LiteralLengthCodeTable,DistanceCodeTable:PHuffManTreeList;BitLengthCodeTableLookupBits,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits:TpvInt32): TpvInt32;
var S:TpvInt32;
E:TpvUInt16;
N,D:TpvUInt16;
W:TpvUInt16;
T:PHuffManTree;
BMask,LMask,DMask:TpvUInt16;
U:TpvUInt16;
begin
BitBuffer:=0;
BitsInBitBuffer:=0;
W:=0;
U:=1;
BMask:=MaskBits[BitLengthCodeTableLookupBits];
LMask:=MaskBits[LiteralLengthCodeTableLookupBits];
DMask:=MaskBits[DistanceCodeTableLookupBits];
S:=UncompressedSize;
while (S>0) and not (UserAbort or ItIsAtEnd) do begin
NeedBits(1);
if(BitBuffer and 1)<>0 then begin
DumpBits(1);
dec(S);
NeedBits(BitLengthCodeTableLookupBits);
T:=@BitLengthCodeTable^[BMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then begin
repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
end;
DumpBits(T^.CodeBits);
Slide^[W]:=T^.ByteSize;
inc(W);
if W=SlidingDictionaryWindowSize then begin
if not Flush(W) then begin
result:=StatusWriteErr;
exit;
end;
W:=0;
U:=0;
end;
end else begin
DumpBits(1);
NeedBits(7);
D:=BitBuffer and $7f;
DumpBits(7);
NeedBits(DistanceCodeTableLookupBits);
T:=@DistanceCodeTable^[DMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then begin
repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.Extrabits;
until E<=16;
end;
DumpBits(T^.CodeBits);
D:=W-D-T^.ByteSize;
NeedBits(LiteralLengthCodeTableLookupBits);
T:=@LiteralLengthCodeTable^[LMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then begin
repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
end;
DumpBits(T^.CodeBits);
N:=T^.ByteSize;
if E<>0 then begin
NeedBits(8);
inc(N,TpvUInt8(BitBuffer) and $ff);
DumpBits(8);
end;
dec(S,N);
repeat
D:=D and (SlidingDictionaryWindowSize-1);
if D>W then begin
E:=SlidingDictionaryWindowSize-D;
end else begin
E:=SlidingDictionaryWindowSize-W;
end;
if E>N then E:=N;
dec(N,E);
if (U<>0) and (W<=D) then begin
FillChar(Slide^[W],E,#0);
inc(W,E);
inc(D,E);
end else if(W-D>=E)then begin
Move(Slide^[D],Slide^[W],E);
inc(W,E);
inc(D,E);
end else begin
repeat
Slide^[W]:=Slide^[D];
inc(W);
inc(D);
dec(E);
until E=0;
end;
if W=SlidingDictionaryWindowSize then begin
if not Flush(W)then begin
result:=StatusWriteErr;
exit;
end;
W:=0;
U:=0;
end;
until N=0;
end;
end;
if UserAbort then begin
result:=StatusUserAbort;
end else if not Flush(W) then begin
result:=StatusWriteErr;
end else if ItIsAtEnd then begin
result:=StatusReadErr;
end else begin
result:=StatusOk;
end;
end;
function ExplodeLiteral4k(BitLengthCodeTable,LiteralLengthCodeTable,DistanceCodeTable:PHuffManTreeList;BitLengthCodeTableLookupBits,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits:TpvInt32): TpvInt32;
var S:TpvInt32;
E:TpvUInt16;
N,D:TpvUInt16;
W:TpvUInt16;
T:PHuffManTree;
BMask,LMask,DMask:TpvUInt16;
U:TpvUInt16;
begin
BitBuffer:=0;
BitsInBitBuffer:=0;
W:=0;
U:=1;
BMask:=MaskBits[BitLengthCodeTableLookupBits];
LMask:=MaskBits[LiteralLengthCodeTableLookupBits];
DMask:=MaskBits[DistanceCodeTableLookupBits];
S:=UncompressedSize;
while (S>0) and not (UserAbort or ItIsAtEnd) do begin
NeedBits(1);
if (BitBuffer and 1)<>0 then begin
DumpBits(1);
dec(S);
NeedBits(BitLengthCodeTableLookupBits);
T:=@BitLengthCodeTable^[BMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then begin
repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
end;
DumpBits(T^.CodeBits);
Slide^[W]:=T^.ByteSize;
inc(W);
if W=SlidingDictionaryWindowSize then begin
if not Flush(W) then begin
result:=StatusWriteErr;
exit;
end;
W:=0;
U:=0;
end;
end else begin
DumpBits(1);
NeedBits(6);
D:=BitBuffer and $3f;
DumpBits(6);
NeedBits(DistanceCodeTableLookupBits);
T:=@DistanceCodeTable^[DMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then begin
repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
end;
DumpBits(T^.CodeBits);
D:=W-D-T^.ByteSize;
NeedBits(LiteralLengthCodeTableLookupBits);
T:=@LiteralLengthCodeTable^[LMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then begin
repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
end;
DumpBits(T^.CodeBits);
N:=T^.ByteSize;
if E<>0 then begin
NeedBits(8);
inc(N,BitBuffer and $ff);
DumpBits(8);
end;
dec(S,N);
repeat
D:=D and (SlidingDictionaryWindowSize-1);
if D>W then begin
E:=SlidingDictionaryWindowSize-D;
end else begin
E:=SlidingDictionaryWindowSize-W;
end;
if E>N then E:=N;
dec(N,E);
if (U<>0) and (W<=D) then begin
FillChar(Slide^[W],E,#0);
inc(W,E);
inc(D,E);
end else if (W-D)>=E then begin
Move(Slide^[D],Slide^[W],E);
inc(W,E);
inc(D,E);
end else begin
repeat
Slide^[W]:=Slide^[D];
inc(W);
inc(D);
dec(E);
until E=0;
end;
if W=SlidingDictionaryWindowSize then begin
if not Flush(W) then begin
result:=StatusWriteErr;
exit;
end;
W:=0;
U:=0;
end;
until N=0;
end;
end;
if UserAbort then begin
result:=StatusUserAbort;
end else if not Flush(W) then begin
result:=StatusWriteErr;
end else if ItIsAtEnd then begin
result:=StatusReadErr;
end else begin
result:=StatusOk;
end;
end;
function ExplodeNoLiteral8k(LiteralLengthCodeTable,DistanceCodeTable:PHuffManTreeList;LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits:TpvInt32): TpvInt32;
var S:TpvInt32;
E:TpvUInt16;
N,D:TpvUInt16;
W:TpvUInt16;
T:PHuffManTree;
LMask,DMask:TpvUInt16;
U:TpvUInt16;
begin
BitBuffer:=0;
BitsInBitBuffer:=0;
W:=0;
U:=1;
LMask:=MaskBits[LiteralLengthCodeTableLookupBits];
DMask:=MaskBits[DistanceCodeTableLookupBits];
S:=UncompressedSize;
while (S>0) and not (UserAbort or ItIsAtEnd) do begin
NeedBits(1);
if(BitBuffer and 1)<>0 then begin
DumpBits(1);
dec(S);
NeedBits(8);
Slide^[W]:=BitBuffer;
inc(W);
if W=SlidingDictionaryWindowSize then begin
if not Flush(W)then begin
result:=StatusWriteErr;
exit;
end;
W:=0;
U:=0;
end;
DumpBits(8);
end else begin
DumpBits(1);
NeedBits(7);
D:=BitBuffer and $7f;
DumpBits(7);
NeedBits(DistanceCodeTableLookupBits);
T:=@DistanceCodeTable^[DMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then begin
repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
end;
DumpBits(T^.CodeBits);
D:=W-D-T^.ByteSize;
NeedBits(LiteralLengthCodeTableLookupBits);
T:=@LiteralLengthCodeTable^[LMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then begin
repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
end;
DumpBits(T^.CodeBits);
N:=T^.ByteSize;
if E<>0 then begin
NeedBits(8);
inc(N,BitBuffer and $ff);
DumpBits(8);
end;
dec(S,N);
repeat
D:=D and (SlidingDictionaryWindowSize-1);
if D>W then begin
E:=SlidingDictionaryWindowSize-D;
end else begin
E:=SlidingDictionaryWindowSize-W;
end;
if E>N then E:=N;
dec(N,E);
if (U<>0) and (W<=D) then begin
FillChar(Slide^[W],E,#0);
inc(W,E);
inc(D,E);
end else if(W-D>=E)then begin
Move(Slide^[D],Slide^[W],E);
inc(W,E);
inc(D,E);
end else begin
repeat
Slide^[W]:=Slide^[D];
inc(W);
inc(D);
dec(E);
until E=0;
end;
if W=SlidingDictionaryWindowSize then begin
if not Flush(W)then begin
result:=StatusWriteErr;
exit;
end;
W:=0;
U:=0;
end;
until N=0;
end;
end;
if UserAbort then begin
result:=StatusUserAbort;
end else if not Flush(W) then begin
result:=StatusWriteErr;
end else if ItIsAtEnd then begin
result:=StatusReadErr;
end else begin
result:=StatusOk;
end;
end;
function ExplodeNoLiteral4k(LiteralLengthCodeTable,DistanceCodeTable:PHuffManTreeList;LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits:TpvInt32): TpvInt32;
var S:TpvInt32;
E:TpvUInt16;
N,D:TpvUInt16;
W:TpvUInt16;
T:PHuffManTree;
LMask,DMask:TpvUInt16;
U:TpvUInt16;
begin
BitBuffer:=0;
BitsInBitBuffer:=0;
W:=0;
U:=1;
LMask:=MaskBits[LiteralLengthCodeTableLookupBits];
DMask:=MaskBits[DistanceCodeTableLookupBits];
S:=UncompressedSize;
while (S>0) and not (UserAbort or ItIsAtEnd) do begin
NeedBits(1);
if(BitBuffer and 1)<>0 then begin
DumpBits(1);
dec(S);
NeedBits(8);
Slide^[W]:=BitBuffer;
inc(W);
if W=SlidingDictionaryWindowSize then begin
if not Flush(W) then begin
result:=StatusWriteErr;
exit;
end;
W:=0;
U:=0;
end;
DumpBits(8);
end else begin
DumpBits(1);
NeedBits(6);
D:=BitBuffer and $3f;
DumpBits(6);
NeedBits(DistanceCodeTableLookupBits);
T:=@DistanceCodeTable^[DMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
DumpBits(T^.CodeBits);
D:=W-D-T^.ByteSize;
NeedBits(LiteralLengthCodeTableLookupBits);
T:=@LiteralLengthCodeTable^[LMask and not BitBuffer];
E:=T^.ExtraBits;
if E>16 then repeat
if E=99 then begin
result:=StatusZipFileErr;
exit;
end;
DumpBits(T^.CodeBits);
dec(E,16);
NeedBits(E);
T:=@T^.LinkList^[MaskBits[E] and not BitBuffer];
E:=T^.ExtraBits;
until E<=16;
DumpBits(T^.CodeBits);
N:=T^.ByteSize;
if E<>0 then begin
NeedBits(8);
inc(N,BitBuffer and $ff);
DumpBits(8);
end;
dec(S,N);
repeat
D:=D and (SlidingDictionaryWindowSize-1);
if D>W then begin
E:=SlidingDictionaryWindowSize-D;
end else begin
E:=SlidingDictionaryWindowSize-W;
end;
if E>N then E:=N;
dec(N,E);
if (U<>0) and (W<=D) then begin
FillChar(Slide^[W],E,#0);
inc(W,E);
inc(D,E);
end else if (W-D>=E) then begin
Move(Slide^[D],Slide^[W],E);
inc(W,E);
inc(D,E);
end else begin
repeat
Slide^[W]:=Slide^[D];
inc(W);
inc(D);
dec(E);
until E=0;
end;
if W=SlidingDictionaryWindowSize then begin
if not Flush(W) then begin
result:=StatusWriteErr;
exit;
end;
W:=0;
U:=0;
end;
until N=0;
end;
end;
if UserAbort then begin
result:=StatusUserAbort;
end else if not Flush(W) then begin
result:=StatusWriteErr;
end else if ItIsAtEnd then begin
result:=StatusReadErr;
end else begin
result:=StatusOk;
end;
end;
function Explode:TpvInt32;
var BitLengthCodeTable,LiteralLengthCodeTable,DistanceCodeTable:PHuffManTreeList;
BitLengthCodeTableLookupBits,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits:TpvInt32;
TreeTable:array[0..255] of TpvUInt16;
begin
InputBufferPosition:=0;
FilePosition:=-1;
LiteralLengthCodeTableLookupBits:=7;
if CompressedSize>200000 then begin
DistanceCodeTableLookupBits:=8;
end else begin
DistanceCodeTableLookupBits:=7;
end;
if (BitsFlagsType and 4)<>0 then begin
BitLengthCodeTableLookupBits:=9;
result:=GetTree(@TreeTable[0],256);
if result<>0 then begin
result:=StatusZipFileErr;
exit;
end;
result:=HuffManTreeBuild(pword(@TreeTable),256,256,nil,nil,PPHuffManTree(@BitLengthCodeTable),BitLengthCodeTableLookupBits);
if result<>0 then begin
if result=HuffmanTreeIncomplete then begin
HuffManTreeFree(BitLengthCodeTable);
end;
result:=StatusZipFileErr;
exit;
end;
result:=GetTree(@TreeTable[0],64);
if result<>0 then begin
HuffManTreeFree(BitLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
result:=HuffManTreeBuild(pword(@TreeTable),64,0,PUSBList(@CopyLength3),PUSBList(@ExtraBitsTable),PPHuffManTree(@LiteralLengthCodeTable),LiteralLengthCodeTableLookupBits);
if result<>0 then begin
if result=HuffmanTreeIncomplete then begin
HuffManTreeFree(LiteralLengthCodeTable);
end;
HuffManTreeFree(BitLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
result:=GetTree(@TreeTable[0],64);
if result<>0 then begin
HuffManTreeFree(BitLengthCodeTable);
HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
if (BitsFlagsType and 2)<>0 then begin
result:=HuffManTreeBuild(pword(@TreeTable),64,0,PUSBList(@CopyOffserDistanceCodes8),PUSBList(@ExtraBitsTable),PPHuffManTree(@DistanceCodeTable),DistanceCodeTableLookupBits);
if result<>0 then begin
if result=HuffmanTreeIncomplete then begin
HuffManTreeFree(DistanceCodeTable);
end;
HuffManTreeFree(BitLengthCodeTable);
HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
result:=ExplodeLiteral8k(BitLengthCodeTable,LiteralLengthCodeTable,DistanceCodeTable,BitLengthCodeTableLookupBits,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits);
end else begin
result:=HuffManTreeBuild(pword(@TreeTable),64,0,PUSBList(@CopyOffserDistanceCodes4),PUSBList(@ExtraBitsTable),PPHuffManTree(@DistanceCodeTable),DistanceCodeTableLookupBits);
if result<>0 then begin
if result=HuffmanTreeIncomplete then begin
HuffManTreeFree(DistanceCodeTable);
end;
HuffManTreeFree(BitLengthCodeTable);
HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
result:=ExplodeLiteral4k(BitLengthCodeTable,LiteralLengthCodeTable,DistanceCodeTable,BitLengthCodeTableLookupBits,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits);
end;
HuffManTreeFree(DistanceCodeTable);
HuffManTreeFree(LiteralLengthCodeTable);
HuffManTreeFree(BitLengthCodeTable);
end else begin
result:=GetTree(@TreeTable[0],64);
if result<>0 then begin
result:=StatusZipFileErr;
exit;
end;
result:=HuffManTreeBuild(pword(@TreeTable),64,0,PUSBList(@CopyLength2),PUSBList(@ExtraBitsTable),PPHuffManTree(@LiteralLengthCodeTable),LiteralLengthCodeTableLookupBits);
if result<>0 then begin
if result=HuffmanTreeIncomplete then begin
HuffManTreeFree(LiteralLengthCodeTable);
end;
result:=StatusZipFileErr;
exit;
end;
result:=GetTree(@TreeTable[0],64);
if result<>0 then begin
HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
if (BitsFlagsType and 2)<>0 then begin
result:=HuffManTreeBuild(pword(@TreeTable),64,0,PUSBList(@CopyOffserDistanceCodes8),PUSBList(@ExtraBitsTable),PPHuffManTree(@DistanceCodeTable),DistanceCodeTableLookupBits);
if result<>0 then begin
if result=HuffmanTreeIncomplete then begin
HuffManTreeFree(DistanceCodeTable);
end;
HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
result:=ExplodeNoLiteral8k(LiteralLengthCodeTable,DistanceCodeTable,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits);
end else begin
result:=HuffManTreeBuild(pword(@TreeTable),64,0,PUSBList(@CopyOffserDistanceCodes4),PUSBList(@ExtraBitsTable),PPHuffManTree(@DistanceCodeTable),DistanceCodeTableLookupBits);
if result<>0 then begin
if result=HuffmanTreeIncomplete then begin
HuffManTreeFree(DistanceCodeTable);
end;
HuffManTreeFree(LiteralLengthCodeTable);
result:=StatusZipFileErr;
exit;
end;
result:=ExplodeNoLiteral4k(LiteralLengthCodeTable,DistanceCodeTable,LiteralLengthCodeTableLookupBits,DistanceCodeTableLookupBits);
end;
HuffManTreeFree(DistanceCodeTable);
HuffManTreeFree(LiteralLengthCodeTable);
end;
end;
function WriteChar(C:TpvUInt8):boolean;
begin
result:=OutStream.Write(C,SizeOf(TpvUInt8))=SizeOf(TpvUInt8);
CRC32.Update(C,SizeOf(TpvUInt8));
end;
procedure ClearLeafNodes;
var PreviousCodeValue:TpvInt32;
index:TpvInt32;
MaxActualCode:TpvInt32;
CurrentPreviousCodeTrie:PPreviousCodeTrie;
begin
CurrentPreviousCodeTrie:=PreviousCode;
MaxActualCode:=NextFreeCodeInTrie-1;
for index:=257 to MaxActualCode do begin
CurrentPreviousCodeTrie^[index]:=CurrentPreviousCodeTrie^[index] or $8000;
end;
for index:=257 to MaxActualCode do begin
PreviousCodeValue:=CurrentPreviousCodeTrie^[index] and not $8000;
if PreviousCodeValue>256 then begin
CurrentPreviousCodeTrie^[PreviousCodeValue]:=CurrentPreviousCodeTrie^[PreviousCodeValue] and not $8000;
end;
end;
PreviousCodeValue:=-1;
NextFreeCodeInTrie:=-1;
for index:=257 to MaxActualCode do begin
if (CurrentPreviousCodeTrie^[index] and $c000)<>0 then begin
if PreviousCodeValue<>-1 then begin
CurrentPreviousCodeTrie^[PreviousCodeValue]:=-index;
end else begin
NextFreeCodeInTrie:=index;
end;
PreviousCodeValue:=index;
end;
end;
if PreviousCodeValue<>-1 then begin
CurrentPreviousCodeTrie^[PreviousCodeValue]:=-MaxActualCode-1;
end;
end;
function Unshrink:TpvInt32;
function DoIt:TpvInt32;
var InputCode:TpvInt32;
LastInputCode:TpvInt32;
LastOutputCode:TpvUInt8;
ActualCodeSize:TpvUInt8;
StackPtr:TpvInt32;
NewCode:TpvInt32;
CodeMask:TpvInt32;
index:TpvInt32;
BitsToRead:TpvInt32;
begin
InputBufferPosition:=0;
FilePosition:=-1;
SlideWindowPosition:=0;
BitsInBitBuffer:=0;
BitBuffer:=0;
FillChar(PreviousCode^,SizeOf(TPreviousCodeTrie),#0);
FillChar(ActualCode^,SizeOf(TActualCodeTrie),#0);
FillChar(Stack^,SizeOf(TStack),#0);
for index:=257 to MaxCode do begin
PreviousCode^[index]:=-(index+1);
end;
NextFreeCodeInTrie:=257;
StackPtr:=MaxStack;
ActualCodeSize:=InitialCodeSize;
CodeMask:=MaskBits[ActualCodeSize];
NeedBits(ActualCodeSize);
InputCode:=BitBuffer and CodeMask;
DumpBits(ActualCodeSize);
LastInputCode:=InputCode;
LastOutputCode:=InputCode and $ff;
if not WriteChar(LastOutputCode) then begin
result:=StatuswriteErr;
exit;
end;
BitsToRead:=(8*CompressedSize)-ActualCodeSize;
while (BitsToRead>=ActualCodeSize) and not UserAbort do begin
NeedBits(ActualCodeSize);
InputCode:=BitBuffer and CodeMask;
DumpBits(ActualCodeSize);
dec(BitsToRead,ActualCodeSize);
if InputCode=256 then begin
NeedBits(ActualCodeSize);
InputCode:=BitBuffer and CodeMask;
DumpBits(ActualCodeSize);
dec(BitsToRead,ActualCodeSize);
case InputCode of
1:begin
inc(ActualCodeSize);
if ActualCodeSize>FinalCodeSize then begin
result:=StatusZipFileErr;
exit;
end;
CodeMask:=MaskBits[ActualCodeSize];
end;
2:begin
ClearLeafNodes;
end;
else begin
result:=StatusZipFileErr;
exit;
end;
end;
end else begin
NewCode:=InputCode;
if InputCode<256 then begin
LastOutputCode:=InputCode and $ff;
if not WriteChar(LastOutputCode) then begin
result:=StatusWriteErr;
exit;
end;
end else begin
if PreviousCode^[InputCode]<0 then begin
Stack^[StackPtr]:=LastOutputCode;
dec(StackPtr);
InputCode:=LastInputCode;
end;
while InputCode>256 do begin
Stack^[StackPtr]:=ActualCode^[InputCode];
dec(StackPtr);
InputCode:=PreviousCode^[InputCode];
end;
LastOutputCode:=InputCode and $ff;
if not WriteChar(LastOutputCode) then begin
result:=StatusWriteErr;
exit;
end;
for index:=StackPtr+1 to MaxStack do begin
if not WriteChar(Stack^[index]) then begin
result:=StatusWriteErr;
exit;
end;
end;
StackPtr:=MaxStack;
end;
InputCode:=NextFreeCodeInTrie;
if InputCode<=MaxCode then begin
NextFreeCodeInTrie:=-PreviousCode^[InputCode];
PreviousCode^[InputCode]:=LastInputCode;
ActualCode^[InputCode]:=LastOutputCode;
end;
LastInputCode:=NewCode;
end;
end;
if UserAbort then begin
result:=StatusUserAbort;
end else begin
result:=StatusOk;
end;
end;
begin
if CompressedSize=MAXLONGINT then begin
result:=StatusNotSupported;
exit;
end;
New(PreviousCode);
New(ActualCode);
New(Stack);
try
result:=DoIt;
finally
Dispose(PreviousCode);
Dispose(ActualCode);
Dispose(Stack);
end;
end;
function Unreduce(InputFactor:TpvInt32):TpvInt32;
const DLE=144;
type PFArray=^TFArray;
TFArray=array[0..63] of TpvUInt8;
PFollowers=^TFollowers;
TFollowers=array[0..255] of TFArray;
PSlen=^TSlen;
TSlen=array[0..255] of TpvUInt8;
const L_table:array[0..4] of TpvInt32=($00,$7f,$3f,$1f,$0f);
D_shift:array[0..4] of TpvInt32=($00,$07,$06,$05,$04);
D_mask:array[0..4] of TpvInt32=($00,$01,$03,$07,$0f);
B_table:array[0..255] of TpvInt32=(8,1,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8);
var Slen:PSLen;
Followers:PFollowers;
function DoIt:TpvInt32;
var lchar,nchar,ExState,v,Len,s,u,Factor,Follower,BitsNeeded,x,i:TpvInt32;
e,n,d:TpvUInt32;
begin
u:=1;
v:=0;
lchar:=0;
Len:=0;
ExState:=0;
Factor:=InputFactor;
for x:=255 downto 0 do begin
Slen^[x]:=ReadBits(6);
for i:=0 to Slen^[x]-1 do begin
Followers^[x,i]:=ReadBits(8);
end;
end;
SlideWindowPosition:=0;
S:=UncompressedSize;
while (S>0) and not (UserAbort or ItIsAtEnd) do begin
if Slen^[lchar]=0 then begin
nchar:=ReadBits(8);
end else begin
nchar:=ReadBits(1);
if nchar<>0 then begin
nchar:=ReadBits(8);
end else begin
BitsNeeded:=B_table[Slen^[lchar]];
Follower:=ReadBits(BitsNeeded);
nchar:=Followers[lchar,follower];
end;
end;
case ExState of
0:begin
if nchar<>DLE then begin
dec(s);
Slide^[SlideWindowPosition]:=TpvUInt8(nchar);
inc(SlideWindowPosition);
if SlideWindowPosition=$4000 then begin
if not Flush(SlideWindowPosition) then begin
result:=StatusWriteErr;
exit;
end;
SlideWindowPosition:=0;
u:=0;
end;
end else begin
ExState:=1;
end;
end;
1:begin
if nchar<>0 then begin
v:=nchar;
Len:=v and L_table[Factor];
if Len=L_table[Factor] then begin
ExState:=2;
end else begin
ExState:=3;
end;
end else begin
dec(s);
Slide^[SlideWindowPosition]:=TpvUInt8(DLE);
inc(SlideWindowPosition);
if SlideWindowPosition=$4000 then begin
if not Flush(SlideWindowPosition) then begin
result:=StatusWriteErr;
exit;
end;
SlideWindowPosition:=0;
u:=0;
end;
ExState:=0;
end;
end;
2:begin
inc(Len,nchar);
ExState:=3;
end;
3:begin
n:=Len+3;
d:=SlideWindowPosition-(((((v shr D_shift[Factor]) and D_mask[Factor]) shl 8)+nchar)+1);
dec(s,n);
repeat
d:=d and $3fff;
if d>TpvUInt32(SlideWindowPosition) then begin
e:=d;
end else begin
e:=SlideWindowPosition;
end;
e:=$4000-e;
if e>n then begin
e:=n;
end;
dec(n,e);
if (u<>0) and (SlideWindowPosition<=d) then begin
FillChar(Slide^[SlideWindowPosition],e,#0);
inc(SlideWindowPosition,e);
inc(d,e);
end else if (TpvUInt32(SlideWindowPosition)-d)<e then begin
repeat
Slide^[SlideWindowPosition]:=Slide^[d];
inc(SlideWindowPosition);
inc(d);
dec(e);
until e=0;
end else begin
Move(Slide^[d],Slide^[SlideWindowPosition],e);
inc(SlideWindowPosition,e);
inc(d,e);
end;
if SlideWindowPosition=$4000 then begin
if not Flush(SlideWindowPosition) then begin
result:=StatusWriteErr;
exit;
end;
SlideWindowPosition:=0;
u:=0;
end;
until n=0;
ExState:=0;
end;
end;
lchar:=nchar;
end;
if UserAbort then begin
result:=StatusUserAbort;
end else if s=0 then begin
result:=StatusOk;
end else begin
result:=StatusReadErr;
end;
end;
begin
if CompressedSize=MAXLONGINT then begin
result:=StatusNotSupported;
exit;
end;
New(Slen);
New(Followers);
try
result:=DoIt;
finally
Dispose(Slen);
Dispose(Followers);
end;
end;
function DoDecompress(InStream,OutStream:TStream):TpvInt32;
begin
GetMem(Slide,SlidingDictionaryWindowSize);
FillChar(Slide^,SlidingDictionaryWindowSize,#0);
try
ReachedSize:=0;
UserAbort:=false;
ItIsAtEnd:=false;
BitsFlagsType:=LocalFileHeader.BitFlags;
case LocalFileHeader.CompressMethod of
0:begin
result:=CopyStored;
end;
1:begin
result:=Unshrink;
end;
2..5:begin
result:=Unreduce(LocalFileHeader.CompressMethod-1);
end;
6:begin
result:=Explode;
end;
8:begin
result:=Inflate;
end;
else begin
result:=StatusNotSupported;
end;
end;
if (result=Statusok) and ((BitsFlagsType and 8)<>0) then begin
DumpBits(BitsInBitBuffer and 7);
NeedBits(16);
DumpBits(16);
NeedBits(16);
OriginalCRC:=(BitBuffer and $ffff) shl 16;
DumpBits(16);
end;
finally
FreeMem(Slide);
end;
end;
begin
result:=DoDecompress(InStream,OutStream)=StatusOk;
end;
procedure Inflate;
var InData:TpvPointer;
DestData:TpvPointer;
DestLen:TpvSizeUInt;
begin
if CompressedSize>0 then begin
DestData:=nil;
DestLen:=0;
try
GetMem(InData,CompressedSize);
try
fSourceArchive.fStream.ReadBuffer(InData^,CompressedSize);
DoInflate(InData,CompressedSize,DestData,DestLen,false);
finally
FreeMem(InData);
end;
if DestLen>0 then begin
CRC32.Update(DestData^,DestLen);
aStream.WriteBuffer(DestData^,DestLen);
end;
finally
if assigned(DestData) then begin
FreeMem(DestData);
end;
end;
end;
end;
begin
if assigned(aStream) then begin
if aStream is TMemoryStream then begin
(aStream as TMemoryStream).Clear;
end else if (aStream is TFileStream) and ((aStream as TFileStream).Size>0) then begin
(aStream as TFileStream).Size:=0;
end;
if assigned(fSourceArchive) then begin
if fSourceArchive.fStream.Seek(fHeaderPosition,soBeginning)<>fHeaderPosition then begin
raise EpvArchiveZIP.Create('Seek error');
end;
fSourceArchive.fStream.ReadBuffer(LocalFileHeader,SizeOf(TpvArchiveZIPLocalFileHeader));
if LocalFileHeader.Signature.Value<>TpvArchiveZIPHeaderSignatures.LocalFileHeaderSignature.Value then begin
raise EpvArchiveZIP.Create('Invalid or corrupt ZIP archive');
end;
LocalFileHeader.SwapEndiannessIfNeeded;
Offset:=fSourceArchive.fStream.Position+LocalFileHeader.FileNameLength+LocalFileHeader.ExtraFieldLength;
if (LocalFileHeader.BitFlags and 8)=0 then begin
CompressedSize:=LocalFileHeader.CompressedSize;
UncompressedSize:=LocalFileHeader.UncompressedSize;
OriginalCRC:=LocalFileHeader.CRC32;
end else begin
CompressedSize:=High(TpvInt64);
UncompressedSize:=High(TpvInt64);
OriginalCRC:=0;
end;
if LocalFileHeader.ExtraFieldLength>=SizeOf(TpvArchiveZIPExtensibleDataFieldHeader) then begin
StartPosition:=fSourceArchive.fStream.Position;
while (fSourceArchive.fStream.Position+(SizeOf(ExtensibleDataFieldHeader)-1))<(StartPosition+LocalFileHeader.ExtraFieldLength) do begin
fSourceArchive.fStream.ReadBuffer(ExtensibleDataFieldHeader,SizeOf(TpvArchiveZIPExtensibleDataFieldHeader));
ExtensibleDataFieldHeader.SwapEndiannessIfNeeded;
From:=fSourceArchive.fStream.Position;
case ExtensibleDataFieldHeader.HeaderID of
$0001:begin
fSourceArchive.fStream.ReadBuffer(ExtensibleInfoFieldHeader,SizeOf(TpvArchiveZIP64ExtensibleInfoFieldHeader));
ExtensibleInfoFieldHeader.SwapEndiannessIfNeeded;
if (LocalFileHeader.BitFlags and 8)=0 then begin
CompressedSize:=ExtensibleInfoFieldHeader.CompressedSize;
UncompressedSize:=ExtensibleInfoFieldHeader.OriginalSize;
end;
end;
$7075:begin
end;
end;
if fSourceArchive.fStream.Seek(From+ExtensibleDataFieldHeader.DataSize,soBeginning)<>From+ExtensibleDataFieldHeader.DataSize then begin
raise EpvArchiveZIP.Create('Seek error');
end;
end;
end;
if (LocalFileHeader.BitFlags and 1)<>0 then begin
raise EpvArchiveZIP.Create('Encrypted ZIP archive');
end;
if (LocalFileHeader.BitFlags and 32)<>0 then begin
raise EpvArchiveZIP.Create('Patched ZIP archive');
end;
if fSourceArchive.fStream.Seek(Offset,soBeginning)<>Offset then begin
raise EpvArchiveZIP.Create('Seek error');
end;
if CompressedSize>0 then begin
CRC32.Initialize;
case LocalFileHeader.CompressMethod of
0:begin
if aStream.CopyFrom(fSourceArchive.fStream,CompressedSize)<>CompressedSize then begin
raise EpvArchiveZIP.Create('Read error');
end;
CRC32.Update(aStream);
end;
1..6:begin
if not Decompress(fSourceArchive.fStream,aStream) then begin
raise EpvArchiveZIP.Create('Decompression failed');
end;
end;
8:begin
if (CompressedSize<high(TpvUInt16)) and
(UncompressedSize<high(TpvUInt16)) then begin
Inflate;
end else begin
if not Decompress(fSourceArchive.fStream,aStream) then begin
raise EpvArchiveZIP.Create('Decompression failed');
end;
end;
end;
else
begin
raise EpvArchiveZIP.Create('Non-supported compression method');
end;
end;
if (aStream.Size<>0) and (CRC32.Finalize<>OriginalCRC) then begin
raise EpvArchiveZIP.Create('Checksum mismatch');
end;
end;
end else if assigned(fStream) then begin
fStream.Seek(0,soBeginning);
aStream.CopyFrom(fStream,fStream.Size);
end;
end;
end;
procedure TpvArchiveZIPEntry.SaveToFile(const aFileName:string);
var Stream:TStream;
begin
Stream:=TFileStream.Create(aFileName,fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
constructor TpvArchiveZIPEntries.Create;
begin
inherited Create(TpvArchiveZIPEntry);
fFileNameHashMap:=TpvArchiveZIPEntriesFileNameHashMap.Create(nil);
end;
destructor TpvArchiveZIPEntries.Destroy;
begin
Clear;
FreeAndNil(fFileNameHashMap);
inherited Destroy;
end;
function TpvArchiveZIPEntries.GetEntry(const aIndex:TpvSizeInt):TpvArchiveZIPEntry;
begin
result:=inherited Items[aIndex] as TpvArchiveZIPEntry;
end;
procedure TpvArchiveZIPEntries.SetEntry(const aIndex:TpvSizeInt;const aEntry:TpvArchiveZIPEntry);
begin
inherited Items[aIndex]:=aEntry;
end;
function TpvArchiveZIPEntries.Add(const aFileName:TpvRawByteString):TpvArchiveZIPEntry;
begin
result:=TpvArchiveZIPEntry.Create(self);
result.SetFileName(aFileName);
end;
function TpvArchiveZIPEntries.Find(const aFileName:TpvRawByteString):TpvArchiveZIPEntry;
begin
result:=fFileNameHashMap[TpvArchiveZIP.CorrectPath(aFileName)];
end;
constructor TpvArchiveZIP.Create;
begin
inherited Create;
fEntries:=TpvArchiveZIPEntries.Create;
fStream:=nil;
end;
destructor TpvArchiveZIP.Destroy;
begin
FreeAndNil(fEntries);
//FreeAndNil(fStream);
inherited Destroy;
end;
class function TpvArchiveZIP.CorrectPath(const aFileName:TpvRawByteString):TpvRawByteString;
var Index:TpvSizeInt;
begin
result:=aFileName;
for Index:=1 to length(result) do begin
case result[Index] of
'\':begin
result[Index]:='/';
end;
end;
end;
end;
procedure TpvArchiveZIP.Clear;
begin
FreeAndNil(fStream);
fEntries.Clear;
end;
procedure TpvArchiveZIP.LoadFromStream(const aStream:TStream);
var LocalFileHeader:TpvArchiveZIPLocalFileHeader;
EndCentralFileHeader:TpvArchiveZIPEndCentralFileHeader;
CentralFileHeader:TpvArchiveZIPCentralFileHeader;
Size,CentralFileHeaderOffset:TpvInt64;
Index,Count,FileCount:TpvSizeInt;
FileName:TpvRawByteString;
OK:boolean;
FileEntry:TpvArchiveZIPEntry;
begin
Clear;
fStream:=aStream;
Size:=fStream.Size;
OK:=false;
fStream.Seek(0,soFromBeginning);
fStream.ReadBuffer(LocalFileHeader,SizeOf(TpvArchiveZIPLocalFileHeader));
if LocalFileHeader.Signature.Value=TpvArchiveZIPHeaderSignatures.LocalFileHeaderSignature.Value then begin
for Index:=Size-SizeOf(TpvArchiveZipEndCentralFileHeader) downto Size-(65535+SizeOf(TpvArchiveZipEndCentralFileHeader)) do begin
if Index<0 then begin
break;
end else begin
fStream.Seek(Index,soFromBeginning);
if fStream.Read(EndCentralFileHeader,SizeOf(TpvArchiveZipEndCentralFileHeader))=SizeOf(TpvArchiveZipEndCentralFileHeader) then begin
if EndCentralFileHeader.Signature.Value=TpvArchiveZIPHeaderSignatures.EndCentralFileHeaderSignature.Value then begin
EndCentralFileHeader.SwapEndiannessIfNeeded;
OK:=true;
break;
end;
end;
end;
end;
end;
if not OK then begin
raise EpvArchiveZIP.Create('Invalid ZIP archive');
end;
Count:=0;
fStream.Seek(EndCentralFileHeader.StartDiskOffset,soFromBeginning);
repeat
CentralFileHeaderOffset:=fStream.Position;
if fStream.Read(CentralFileHeader,SizeOf(TpvArchiveZIPCentralFileHeader))<>SizeOf(TpvArchiveZIPCentralFileHeader) then begin
break;
end;
if CentralFileHeader.Signature.Value<>TpvArchiveZIPHeaderSignatures.CentralFileHeaderSignature.Value then begin
break;
end;
CentralFileHeader.SwapEndiannessIfNeeded;
SetLength(FileName,CentralFileHeader.FileNameLength);
if CentralFileHeader.FileNameLength>0 then begin
if fStream.Read(FileName[1],CentralFileHeader.FileNameLength)<>CentralFileHeader.FileNameLength then begin
break;
end;
end;
if Count<EndCentralFileHeader.EntriesThisDisk then begin
fStream.Seek(CentralFileHeader.ExtraFieldLength+CentralFileHeader.FileCommentLength,soFromCurrent);
if length(FileName)>0 then begin
FileEntry:=fEntries.Add(FileName);
FileEntry.fCentralHeaderPosition:=CentralFileHeaderOffset;
FileEntry.fHeaderPosition:=CentralFileHeader.LocalFileHeaderOffset;
FileEntry.Size:=CentralFileHeader.UncompressedSize;
FileEntry.fSourceArchive:=self;
end;
inc(Count);
end else begin
Count:=not EndCentralFileHeader.EntriesThisDisk;
break;
end;
until false;
if EndCentralFileHeader.EntriesThisDisk<>Count then begin
raise EpvArchiveZIP.Create('Invalid ZIP archive');
end;
end;
procedure TpvArchiveZIP.LoadFromFile(const aFileName:string);
var Stream:TStream;
begin
Stream:=TFileStream.Create(aFileName,fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
end;
end;
procedure TpvArchiveZIP.SaveToStream(const aStream:TStream);
function CompressShrink(InStream,OutStream:TStream):boolean;
const BufSize=10240;
MINBITS=9;
MAXBITS=13;
TABLESIZE=8191;
SPECIAL=256;
INCSIZE=1;
CLEARCODE=2;
FIRSTENTRY=257;
UNUSED=-1;
STDATTR=$23;
type TCodeTableItem=record
Child:TpvInt32;
Sibling:TpvInt32;
Suffix:TpvUInt8;
end;
PCodeTable=^TCodeTable;
TCodeTable=array[0..TABLESIZE] of TCodeTableItem;
PFreeList=^TFreeList;
TFreeList=array[FIRSTENTRY..TABLESIZE] of longword;
PClearList=^TClearList;
TClearList=array[0..1023] of TpvUInt8;
var FirstByte:boolean;
TableFull:boolean;
SaveByte:TpvUInt8;
BitsUsed:TpvUInt8;
CodeSize:TpvUInt8;
MaxCode:TpvUInt16;
CodeTable:PCodeTable;
FreeList:PFreeList;
ClearList:PClearList;
NextFree:TpvUInt16;
LastCode:TpvInt32;
procedure Prune(Parent:TpvUInt16);
var CurrentChild,NextSibling:TpvInt32;
begin
CurrentChild:=CodeTable^[Parent].Child;
while (CurrentChild>=0) and (CodeTable^[CurrentChild].Child<0) do begin
CodeTable^[Parent].Child:=CodeTable^[CurrentChild].Sibling;
CodeTable^[CurrentChild].Sibling:=-1;
ClearList^[CurrentChild shr 3]:=(ClearList^[CurrentChild shr 3] or (1 shl (CurrentChild and 7)));
CurrentChild:=CodeTable^[Parent].Child;
end;
if CurrentChild>=0 then begin
Prune(CurrentChild);
NextSibling:=CodeTable^[CurrentChild].Sibling;
while NextSibling>=0 do begin
if CodeTable^[NextSibling].Child<0 then begin
CodeTable^[CurrentChild].Sibling:=CodeTable^[NextSibling].Sibling;
CodeTable^[NextSibling].Sibling:=-1;
ClearList^[NextSibling shr 3]:=(ClearList^[NextSibling shr 3] or (1 shl (NextSibling and 7)));
NextSibling:=CodeTable^[CurrentChild].Sibling;
end else begin
CurrentChild:=NextSibling;
Prune(CurrentChild);
NextSibling:=CodeTable^[CurrentChild].Sibling;
end;
end;
end;
end;
procedure TableClear;
var Node:TpvUInt16;
begin
FillChar(ClearList^,sizeof(TClearList),#0);
for Node:=0 to 255 do begin
Prune(Node);
end;
NextFree:=TABLESIZE+1;
for Node:=TABLESIZE downto FIRSTENTRY do begin
if (ClearList^[Node shr 3] and (1 shl (Node and 7)))<>0 then begin
dec(NextFree);
FreeList^[NextFree]:=Node;
end;
end;
if NextFree<=TABLESIZE then begin
TableFull:=false;
end;
end;
procedure TableAdd(Prefix:TpvUInt16;Suffix:TpvUInt8);
var FreeNode:TpvUInt16;
begin
if NextFree<=TABLESIZE then begin
FreeNode:=FreeList^[NextFree];
inc(NextFree);
CodeTable^[FreeNode].Child:=-1;
CodeTable^[FreeNode].Sibling:=-1;
CodeTable^[FreeNode].Suffix:=Suffix;
if CodeTable^[Prefix].Child=-1 then begin
CodeTable^[Prefix].Child:=FreeNode;
end else begin
Prefix:=CodeTable^[Prefix].Child;
while CodeTable^[Prefix].Sibling<>-1 do begin
Prefix:=CodeTable^[Prefix].Sibling;
end;
CodeTable^[Prefix].Sibling:=FreeNode;
end;
end;
if NextFree>TABLESIZE then begin
TableFull:=true;
end;
end;
function TableLookup(TargetPrefix:TpvInt32;TargetSuffix:TpvUInt8;var FoundAt:TpvInt32):boolean;
var TempChild:TpvInt32;
begin
result:=false;
FoundAt:=-1;
if CodeTable^[TargetPrefix].Child=-1 then begin
exit;
end;
TempChild:=CodeTable^[TargetPrefix].Child;
while true do begin
with CodeTable^[TempChild] do begin
if Suffix=TargetSuffix then begin
FoundAt:=TempChild;
result:=true;
break;
end;
if Sibling=-1 then begin
break;
end;
TempChild:=Sibling;
end;
end;
end;
procedure PutByte(Value:TpvUInt8);
begin
OutStream.WriteBuffer(Value,sizeof(TpvUInt8));
end;
procedure PutCode(Code:smallint);
var Mask:TpvUInt16;
Agent,LocalSaveByte,LocalBitsUsed,LocalCodeSize:TpvUInt8;
begin
LocalSaveByte:=SaveByte;
LocalBitsUsed:=BitsUsed;
LocalCodeSize:=CodeSize;
if Code=-1 then begin
if LocalBitsUsed<>0 then begin
PutByte(LocalSaveByte);
end;
end else begin
Mask:=$0001;
repeat
Agent:=0;
if (Code and Mask)<>0 then begin
inc(Agent);
end;
Mask:=Mask shl 1;
Agent:=Agent shl LocalBitsUsed;
inc(LocalBitsUsed);
LocalSaveByte:=LocalSaveByte or Agent;
if LocalBitsUsed=8 then begin
PutByte(LocalSaveByte);
LocalSaveByte:=0;
LocalBitsUsed:=0;
end;
dec(LocalCodeSize);
until LocalCodeSize=0;
SaveByte:=LocalSaveByte;
BitsUsed:=LocalBitsUsed;
end;
end;
procedure ProcessSuffix(Suffix:TpvInt32);
var WhereFound:TpvInt32;
begin
if FirstByte then begin
SaveByte:=0;
BitsUsed:=0;
CodeSize:=MINBITS;
MaxCode:=(1 shl CodeSize)-1;
LastCode:=Suffix;
FirstByte:=false;
end else begin
if Suffix<>-1 then begin
if TableFull then begin
PutCode(LastCode);
PutCode(SPECIAL);
PutCode(CLEARCODE);
TableClear;
TableAdd(LastCode,Suffix);
LastCode:=Suffix;
end else begin
if TableLookup(LastCode,Suffix,WhereFound) then begin
LastCode:=WhereFound;
end else begin
PutCode(LastCode);
TableAdd(LastCode,Suffix);
LastCode:=Suffix;
if (FreeList^[NextFree]>MaxCode) and (CodeSize<MaxBits) then begin
PutCode(SPECIAL);
PutCode(INCSIZE);
inc(CodeSize);
MaxCode:=(1 shl CodeSize)-1;
end;
end;
end;
end else begin
PutCode(LastCode);
PutCode(-1);
end;
end;
end;
var Counter:TpvInt32;
b:TpvUInt8;
begin
result:=false;
New(CodeTable);
New(FreeList);
New(ClearList);
try
for Counter:=0 to TABLESIZE do begin
with CodeTable^[Counter] do begin
Child:=-1;
Sibling:=-1;
if Counter<=255 then begin
Suffix:=Counter;
end;
end;
if Counter>=FIRSTENTRY then begin
FreeList^[Counter]:=Counter;
end;
end;
NextFree:=FIRSTENTRY;
TableFull:=false;
FirstByte:=true;
LastCode:=0;
InStream.Seek(0,soBeginning);
for Counter:=1 to InStream.Size do begin
InStream.ReadBuffer(b,SizeOf(TpvUInt8));
ProcessSuffix(b);
end;
ProcessSuffix(-1);
result:=true;
finally
Dispose(CodeTable);
Dispose(FreeList);
Dispose(ClearList);
end;
end;
var LocalFileHeader:TpvArchiveZIPLocalFileHeader;
CentralFileHeader:TpvArchiveZIPCentralFileHeader;
EndCentralFileHeader:TpvArchiveZIPEndCentralFileHeader;
Counter:TpvSizeInt;
CompressedStream:TStream;
LocalFile:TpvArchiveZIPEntry;
Entries:TpvSizeInt;
StartDiskOffset:TpvInt64;
CentralFileDirectorySize:TpvInt64;
CRC32:TpvArchiveZIPCRC32;
InData:TpvPointer;
DestData:TpvPointer;
DestLen:TpvSizeUInt;
begin
if fEntries.Count=0 then begin
exit;
end;
if aStream is TMemoryStream then begin
(aStream as TMemoryStream).Clear;
end else if (aStream is TFileStream) and ((aStream as TFileStream).Size>0) then begin
(aStream as TFileStream).Size:=0;
end;
for Counter:=0 to fEntries.Count-1 do begin
LocalFile:=fEntries[Counter];
if assigned(LocalFile) then begin
CompressedStream:=TMemoryStream.Create;
try
FillChar(LocalFileHeader,SizeOf(TpvArchiveZIPLocalFileHeader),#0);
LocalFileHeader.Signature:=TpvArchiveZIPHeaderSignatures.LocalFileHeaderSignature;
LocalFileHeader.ExtractVersion:=10;
LocalFileHeader.BitFlags:=0;
if LocalFile.Stream.Size>0 then begin
if LocalFile.CompressionLevel>1 then begin
LocalFileHeader.BitFlags:=2;
LocalFileHeader.CompressMethod:=8;
if LocalFile.Stream.Size>0 then begin
DestData:=nil;
DestLen:=0;
try
GetMem(InData,LocalFile.Stream.Size);
try
LocalFile.Stream.Seek(0,soBeginning);
LocalFile.Stream.ReadBuffer(InData^,LocalFile.Stream.Size);
case LocalFile.CompressionLevel of
2:begin
DoDeflate(InData,LocalFile.Stream.Size,DestData,DestLen,TpvDeflateMode.VeryFast,false);
end;
3:begin
DoDeflate(InData,LocalFile.Stream.Size,DestData,DestLen,TpvDeflateMode.Fast,false);
end;
4:begin
DoDeflate(InData,LocalFile.Stream.Size,DestData,DestLen,TpvDeflateMode.Medium,false);
end;
else begin
DoDeflate(InData,LocalFile.Stream.Size,DestData,DestLen,TpvDeflateMode.Slow,false);
end;
end;
finally
FreeMem(InData);
end;
if DestLen>0 then begin
CompressedStream.WriteBuffer(DestData^,DestLen);
end;
finally
if assigned(DestData) then begin
FreeMem(DestData);
end;
end;
end;
end else if (LocalFile.CompressionLevel=1) and CompressShrink(LocalFile.Stream,CompressedStream) then begin
LocalFileHeader.CompressMethod:=1;
end else begin
LocalFileHeader.CompressMethod:=0;
LocalFile.Stream.Seek(0,soBeginning);
CompressedStream.CopyFrom(LocalFile.Stream,LocalFile.Stream.Size);
end;
CompressedStream.Seek(0,soBeginning);
end else begin
LocalFileHeader.CompressMethod:=0;
end;
TpvArchiveZIPDateTimeUtils.ConvertDateTimeToZIPDateTime(LocalFile.DateTime,
LocalFileHeader.Date,
LocalFileHeader.Time);
LocalFileHeader.FileNameLength:=length(LocalFile.FileName);
LocalFileHeader.CompressedSize:=CompressedStream.Size;
LocalFile.Stream.Seek(0,soBeginning);
CRC32.Initialize;
CRC32.Update(LocalFile.Stream);
LocalFileHeader.CRC32:=CRC32.Finalize;
LocalFileHeader.UncompressedSize:=LocalFile.Stream.Size;
LocalFile.fHeaderPosition:=aStream.Position;
LocalFile.fLocalFileHeader:=LocalFileHeader;
LocalFileHeader.SwapEndiannessIfNeeded;
aStream.WriteBuffer(LocalFileHeader,SizeOf(TpvArchiveZIPLocalFileHeader));
LocalFileHeader.SwapEndiannessIfNeeded;
if LocalFileHeader.FileNameLength>0 then begin
aStream.WriteBuffer(LocalFile.FileName[1],LocalFileHeader.FileNameLength);
end;
if LocalFileHeader.CompressedSize>0 then begin
if aStream.CopyFrom(CompressedStream,LocalFileHeader.CompressedSize)<>TpvInt32(LocalFileHeader.CompressedSize) then begin
raise EpvArchiveZIP.Create('Copy error');
end;
end;
finally
CompressedStream.Free;
end;
end;
end;
Entries:=0;
StartDiskOffset:=aStream.Position;
CentralFileDirectorySize:=0;
for Counter:=0 to fEntries.Count-1 do begin
LocalFile:=fEntries[Counter];
if assigned(LocalFile) then begin
FillChar(CentralFileHeader,SizeOf(TpvArchiveZIPCentralFileHeader),#0);
CentralFileHeader.Signature:=TpvArchiveZIPHeaderSignatures.CentralFileHeaderSignature;
CentralFileHeader.CreatorVersion:=LocalFile.fLocalFileHeader.ExtractVersion;
CentralFileHeader.ExtractVersion:=LocalFile.fLocalFileHeader.ExtractVersion;
CentralFileHeader.BitFlags:=LocalFile.fLocalFileHeader.BitFlags;
CentralFileHeader.CompressMethod:=LocalFile.fLocalFileHeader.CompressMethod;
CentralFileHeader.Time:=LocalFile.fLocalFileHeader.Time;
CentralFileHeader.Date:=LocalFile.fLocalFileHeader.Date;
CentralFileHeader.CRC32:=LocalFile.fLocalFileHeader.CRC32;
CentralFileHeader.CompressedSize:=LocalFile.fLocalFileHeader.CompressedSize;
CentralFileHeader.UncompressedSize:=LocalFile.fLocalFileHeader.UncompressedSize;
CentralFileHeader.FileNameLength:=LocalFile.fLocalFileHeader.FileNameLength;
CentralFileHeader.ExtraFieldLength:=LocalFile.fLocalFileHeader.ExtraFieldLength;
CentralFileHeader.ExternalAttrributes:=$20;
CentralFileHeader.LocalFileHeaderOffset:=LocalFile.fHeaderPosition;
CentralFileHeader.SwapEndiannessIfNeeded;
LocalFile.fCentralHeaderPosition:=aStream.Position;
aStream.WriteBuffer(CentralFileHeader,SizeOf(TpvArchiveZIPCentralFileHeader));
if CentralFileHeader.FileNameLength>0 then begin
aStream.WriteBuffer(LocalFile.FileName[1],CentralFileHeader.FileNameLength);
end;
inc(Entries);
inc(CentralFileDirectorySize,SizeOf(TpvArchiveZIPCentralFileHeader)+CentralFileHeader.FileNameLength);
end;
end;
FillChar(EndCentralFileHeader,SizeOf(TpvArchiveZIPEndCentralFileHeader),#0);
EndCentralFileHeader.Signature:=TpvArchiveZIPHeaderSignatures.EndCentralFileHeaderSignature;
EndCentralFileHeader.EntriesThisDisk:=Entries;
EndCentralFileHeader.TotalEntries:=Entries;
EndCentralFileHeader.StartDiskOffset:=StartDiskOffset;
EndCentralFileHeader.CentralDirectorySize:=CentralFileDirectorySize;
aStream.WriteBuffer(EndCentralFileHeader,SizeOf(TpvArchiveZIPEndCentralFileHeader));
end;
procedure TpvArchiveZIP.SaveToFile(const aFileName:string);
var Stream:TStream;
begin
Stream:=TFileStream.Create(aFileName,fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
end.
|
unit UUtilitarios;
interface
uses
SysUtils
, Controls
, StdCtrls
, ExtCtrls
, ComCtrls
, Mask
, UMensagens
;
type
TTipoOperacaoUsuario = (touIndefinida
, touInsercao
, touAtualizacao
, touExclusao);
EValidacaoNegocio = class(Exception);
TUtilitario = class
public
class function LimpaFormulario(const coParent: TWinControl): Boolean;
class function ComponenteValido(const coCompClass: TClass): Boolean;
end;
TPapelUsuario = (tpluAdministrativo,
tpluAuxiliarAdministrativo,
tpluTecnico);
TListaPapeisUsuario = set of TPapelUsuario;
TPermissaoUsuario = (tpruCadastrarMaterial,
tpruCadastrarCiente,
tpruCadastrarEquipamento,
tpruCadastrarUsuario,
tpruCadastrarTecnico,
tpruCadastrarOs);
TListaPermissoesUsuario = set of TPermissaoUsuario;
TTipoPessoa = (tpFisica, tpJuridica);
const
CNT_MASCARA_CPF = '999.999.999-99;0;_';
CNT_MASCARA_CNPJ = '99.999.999/9999-99;0;_';
CNT_TIPO_INSCRICAO_PESSOA:
array[TTipoPessoa] of String = (STR_CLIENTE_CPF, STR_CLIENTE_CNPJ);
CNT_TIPO_MASCARA_PESSOA:
array[TTipoPessoa] of String = (CNT_MASCARA_CPF, CNT_MASCARA_CNPJ);
CNT_TIPO_OPERACAO_USUARIO:
array[TTipoOperacaoUsuario] of String = ('',
STR_GRAVADO,
STR_ATUALIZADO,
STR_EXCLUIDO);
const
CNT_COMPONENTES_VALIDADOS: array[0..8]
of TClass = (TEdit
, TLabeledEdit
, TMaskEdit
, TDateTimePicker
, TRadioGroup
, TRadioButton
, TCheckBox
, TStaticText
, TComboBox);
implementation
{ TUtilitario }
class function TUtilitario.ComponenteValido
(const coCompClass: TClass): Boolean;
var
loCompClass: TClass;
liIndice: Integer;
begin
for liIndice := 0 to Pred(Length(CNT_COMPONENTES_VALIDADOS)) do
begin
loCompClass := CNT_COMPONENTES_VALIDADOS[liIndice];
Result := loCompClass = coCompClass;
if Result then
Exit;
end;
Result := False;
end;
class function TUtilitario.LimpaFormulario(const coParent: TWinControl): Boolean;
var
loComponent: TControl;
liIndice: Integer;
begin
for liIndice := 0 to Pred(coParent.ControlCount) do
begin
loComponent := coParent.Controls[liIndice];
if ComponenteValido(loComponent.ClassType) then
begin
if loComponent is TComboBox then
TComboBox(loComponent).ItemIndex := 0
else if (loComponent is TEdit)
or (loComponent is TLabeledEdit)
or (loComponent is TMaskEdit) then
TEdit(loComponent).Clear
else if loComponent is TDateTimePicker then
TDateTimePicker(loComponent).DateTime := Now
else if loComponent is TRadioGroup then
TRadioGroup(loComponent).ItemIndex := 0
else if loComponent is TRadioButton then
TRadioButton(loComponent).Checked := False
else if loComponent is TStaticText then
TStaticText(loComponent).Caption := EmptyStr
else
TCheckBox(loComponent).Checked := False;
end
else
if (loComponent is TCustomControl)
or (loComponent is TCustomTabControl)
or (loComponent is TTabSheet) then {Agrupadores}
begin
Result := LimpaFormulario(TCustomControl(loComponent));
if Result then
Exit;
end;
end;
Result := False;
end;
end.
|
unit u_xmlfillcombobutton;
{$IFDEF FPC}
{$mode Delphi}{$H+}
{$ENDIF}
interface
uses
Classes, SysUtils, ExtJvXPButtons, Graphics,
{$IFDEF VERSIONS}
fonctions_version,
{$ENDIF}
u_fillcombobutton, Forms;
{$IFDEF VERSIONS}
const
gVer_XMLFillCombo : T_Version = ( Component : 'Bouton personnalisรฉ de remplissage de combo box avec lien XML' ;
FileUnit : 'u_xmlfillcombobutton' ;
Owner : 'Matthieu Giroux' ;
Comment : 'Composant bouton de remplissage de lien 1-N avec lien XML.' ;
BugsStory : '1.0.0.1 : CreateForm can inherit.' + #13#10
+ '1.0.0.0 : Working on DELPHI.' + #13#10
+ '0.8.0.0 : Not Finished.';
UnitType : 3 ;
Major : 1 ; Minor : 0 ; Release : 0 ; Build : 1 );
{$ENDIF}
type
{ TXMLFillCombo }
TXMLFillCombo = class ( TExtFillCombo )
protected
procedure CreateForm(const aico_Icon: TIcon); override;
End;
implementation
uses fonctions_xmlform;
{ TExtFillCombo }
// procedure TXMLFillCombo.CreateForm
// Creating the registered xml form
// aico_Icon : parameter not used because not needed
procedure TXMLFillCombo.CreateForm(const aico_Icon: TIcon);
begin
FFormModal := fxf_ExecuteFonctionFile ( FormRegisteredName, False );
if not assigned ( FFormModal ) Then
inherited CreateForm ( aico_Icon );
end;
{$IFDEF VERSIONS}
initialization
p_ConcatVersion ( gVer_XMLFillCombo );
{$ENDIF}
end.
|
(*******************************************************************************
Jean-Pierre LESUEUR (@DarkCoderSc)
https://www.phrozen.io/
jplesueur@phrozen.io
License : MIT
*******************************************************************************)
unit UntFunctions;
interface
uses Windows, SysUtils;
type
TDebugLevel = (
dlInfo,
dlSuccess,
dlWarning,
dlError
);
procedure DumpLastError(APrefix : String = '');
procedure Debug(AMessage : String; ADebugLevel : TDebugLevel = dlInfo);
function GetSystemDirectory() : string;
function UpdateConsoleAttributes(AConsoleAttributes : Word) : Word;
function GetCommandLineOption(AOption : String; var AValue : String; ACommandLine : String = '') : Boolean; overload;
function GetCommandLineOption(AOption : String; var AValue : String; var AOptionExists : Boolean; ACommandLine : String = '') : Boolean; overload;
procedure WriteColoredWord(AString : String);
implementation
uses UntGlobalDefs, UntApiDefs;
{-------------------------------------------------------------------------------
Write colored word(s) on current console
-------------------------------------------------------------------------------}
procedure WriteColoredWord(AString : String);
var AOldAttributes : Word;
begin
AOldAttributes := UpdateConsoleAttributes(FOREGROUND_INTENSITY or FOREGROUND_GREEN);
Write(AString);
UpdateConsoleAttributes(AOldAttributes);
end;
{-------------------------------------------------------------------------------
Command Line Parser
AOption : Search for specific option Ex: -c.
AValue : Next argument string if option is found.
AOptionExists : Set to true if option is found in command line string.
ACommandLine : Command Line String to parse, by default, actual program command line.
-------------------------------------------------------------------------------}
function GetCommandLineOption(AOption : String; var AValue : String; var AOptionExists : Boolean; ACommandLine : String = '') : Boolean;
var ACount : Integer;
pElements : Pointer;
I : Integer;
ACurArg : String;
type
TArgv = array[0..0] of PWideChar;
begin
result := False;
///
AOptionExists := False;
if NOT Assigned(CommandLineToArgvW) then
Exit();
if (ACommandLine = '') then begin
ACommandLine := GetCommandLineW();
end;
pElements := CommandLineToArgvW(PWideChar(ACommandLine), ACount);
if NOT Assigned(pElements) then
Exit();
AOption := '-' + AOption;
if (Length(AOption) > 2) then
AOption := '-' + AOption;
for I := 0 to ACount -1 do begin
ACurArg := UnicodeString((TArgv(pElements^)[I]));
///
if (ACurArg <> AOption) then
continue;
AOptionExists := True;
// Retrieve Next Arg
if I <> (ACount -1) then begin
AValue := UnicodeString((TArgv(pElements^)[I+1]));
///
result := True;
end;
end;
end;
function GetCommandLineOption(AOption : String; var AValue : String; ACommandLine : String = '') : Boolean;
var AExists : Boolean;
begin
result := GetCommandLineOption(AOption, AValue, AExists, ACommandLine);
end;
{-------------------------------------------------------------------------------
Retrieve \Windows\System32\ Location
-------------------------------------------------------------------------------}
function GetSystemDirectory() : string;
var ALen : Cardinal;
begin
SetLength(result, MAX_PATH);
ALen := Windows.GetSystemDirectory(@result[1], MAX_PATH);
if (ALen > 0) then begin
SetLength(result, ALen);
result := IncludeTrailingPathDelimiter(result);
end else
result := '';
end;
{-------------------------------------------------------------------------------
Update Console Attributes (Changing color for example)
Returns previous attributes.
-------------------------------------------------------------------------------}
function UpdateConsoleAttributes(AConsoleAttributes : Word) : Word;
var AConsoleHandle : THandle;
AConsoleScreenBufInfo : TConsoleScreenBufferInfo;
b : Boolean;
begin
result := 0;
///
AConsoleHandle := GetStdHandle(STD_OUTPUT_HANDLE);
if (AConsoleHandle = INVALID_HANDLE_VALUE) then
Exit();
///
b := GetConsoleScreenBufferInfo(AConsoleHandle, AConsoleScreenBufInfo);
if b then begin
SetConsoleTextAttribute(AConsoleHandle, AConsoleAttributes);
///
result := AConsoleScreenBufInfo.wAttributes;
end;
end;
{-------------------------------------------------------------------------------
Debug Defs
-------------------------------------------------------------------------------}
procedure Debug(AMessage : String; ADebugLevel : TDebugLevel = dlInfo);
var AConsoleHandle : THandle;
AConsoleScreenBufInfo : TConsoleScreenBufferInfo;
b : Boolean;
AStatus : String;
AColor : Integer;
begin
if (NOT G_Debug) then
Exit();
///
AConsoleHandle := GetStdHandle(STD_OUTPUT_HANDLE);
if (AConsoleHandle = INVALID_HANDLE_VALUE) then
Exit();
///
b := GetConsoleScreenBufferInfo(AConsoleHandle, AConsoleScreenBufInfo);
case ADebugLevel of
dlSuccess : begin
AStatus := #32 + 'OK' + #32;
AColor := FOREGROUND_GREEN;
end;
dlWarning : begin
AStatus := #32 + '!!' + #32;
AColor := (FOREGROUND_RED or FOREGROUND_GREEN);
end;
dlError : begin
AStatus := #32 + 'KO' + #32;
AColor := FOREGROUND_RED;
end;
else begin
AStatus := 'INFO';
AColor := FOREGROUND_BLUE;
end;
end;
Write('[');
if b then
b := SetConsoleTextAttribute(AConsoleHandle, FOREGROUND_INTENSITY or (AColor));
try
Write(AStatus);
finally
if b then
SetConsoleTextAttribute(AConsoleHandle, AConsoleScreenBufInfo.wAttributes);
end;
Write(']' + #32);
///
WriteLn(AMessage);
end;
procedure DumpLastError(APrefix : String = '');
var ACode : Integer;
AFinalMessage : String;
begin
ACode := GetLastError();
AFinalMessage := '';
if (ACode <> 0) then begin
AFinalMessage := Format('Error_Msg=[%s], Error_Code=[%d]', [SysErrorMessage(ACode), ACode]);
if (APrefix <> '') then
AFinalMessage := Format('%s: %s', [APrefix, AFinalMessage]);
///
Debug(AFinalMessage, dlError);
end;
end;
end.
|
unit ray_model;
{$mode objfpc}{$H+}
//is test module
interface
uses
ray_header, ray_math, classes;
type
TModelDrawMode = (dmNormal, dmEx, dmWires, dmWiresEx);
TModelEngineCameraMode = (cmCustom, cmFree, cmOrbital, cmFirstPerson, cmThirdPerson);
{ TModelEngine }
TModelEngine = class
private
FEngineCameraMode: TModelEngineCameraMode;
FEngineCameraPosition: TVector3;
FGridSlices: longint;
FGridSpacing: single;
FWorld: TVector3;
FCamera: TCamera;
FDrawsGrid: Boolean;
procedure SetCamera(AValue: TCamera);
procedure SetDrawsGrid(AValue: boolean);
procedure SetEngineCameraMode(AValue: TModelEngineCameraMode);
procedure SetEngineCameraPosition(AValue: TVector3);
procedure SetGridSlices(AValue: longint);
procedure SetGridSpacing(AValue: single);
procedure SetWorldX(Value: Single);
procedure SetWorldY(Value: Single);
public
List: TList;
DeadList: TList;
procedure Draw();
procedure ClearDeadModel;
procedure Move(MoveCount: Double);
constructor Create;
destructor Destroy; override;
property Camera: TCamera read FCamera write SetCamera;
property WorldX: Single read FWorld.X write SetWorldX;
property WorldY: Single read FWorld.Y write SetWorldY;
property DrawsGrid:boolean read FDrawsGrid write SetDrawsGrid;
property GridSlices:longint read FGridSlices write SetGridSlices;
property GridSpacing: single read FGridSpacing write SetGridSpacing;
property EngineCameraMode: TModelEngineCameraMode read FEngineCameraMode write SetEngineCameraMode;
property EngineCameraPosition: TVector3 read FEngineCameraPosition write SetEngineCameraPosition;
end;
{ T3dModel }
T3dModel = class
private
FAngle: Single;
FAngleX: Single;
FAngleY: Single;
FAngleZ: Single;
FAxis: TVector3;
FAxisX: Single;
FAxisY: Single;
FAxisZ: Single;
FColor: TColor;
FDrawMode: TModelDrawMode;
FScale: Single;
FScaleEx: TVector3;
FPosition: TVector3;
FAnims : PModelAnimation;
procedure SetScale(AValue: Single);
protected
FEngine: TModelEngine;
FModel: TModel;
FTexture: TTexture2d;
public
IsModelDead: Boolean;
Visible: Boolean;
procedure Draw();
procedure Move(MoveCount: Double); virtual;
procedure Dead();
procedure Load3dModel(FileName: String);
procedure Load3dModelTexture(FileName: String);
procedure Load3dModelAnimations(FileName:String; AnimCoint:integer);
procedure Update3dModelAnimations(Frame:longint);
constructor Create(Engine: TModelEngine); virtual;
destructor Destroy; override;
property AxisX: Single read FAxisX write FAxisX;
property AxisY: Single read FAxisY write FAxisY;
property AxisZ: Single read FAxisZ write FAxisZ;
property Angle: Single read FAngle write FAngle;
property AngleX: Single read FAngleX write FAngleX;
property AngleY: Single read FAngleY write FAngleY;
property AngleZ: Single read FAngleZ write FAngleZ;
property X: Single read FPosition.X write FPosition.X;
property Y: Single read FPosition.Y write FPosition.Y;
property Z: Single read FPosition.Z write FPosition.Z;
property Scale: Single read FScale write SetScale;
property Color: TColor read FColor write FColor;
property DrawMode: TModelDrawMode read FDrawMode write FDrawMode;
property Anims: PModelAnimation read FAnims write FAnims;
end;
implementation
{ T3dModel }
procedure T3dModel.SetScale(AValue: Single);
begin
if FScale=AValue then Exit;
FScale:=AValue;
Vector3Set(@FScaleEx,FScale,FScale,FScale);
end;
procedure T3dModel.Draw();
begin
if Assigned(FEngine) then
case FDrawMode of
dmNormal: DrawModel(FModel, FPosition, FScale, WHITE); // Draw 3d model with texture
dmEx: DrawModelEx(FModel, FPosition, FAxis, FAngle, FScaleEx, FColor); // Draw a model with extended parameters
dmWires: DrawModelWires(FModel, FPosition, FScale, FColor); // Draw a model wires (with texture if set)
dmWiresEX: DrawModelWiresEx(FModel,FPosition,FAxis, FAngle, FScaleEx,FColor);
end;
end;
procedure T3dModel.Move(MoveCount: Double);
begin
FModel.transform:=MatrixRotateXYZ(Vector3Create(DEG2RAD*FAxisX,DEG2RAD*FAxisY,DEG2RAD*FAxisZ));
// DEG2RAD
Vector3Set(@FAxis,FAxisX,FAxisY,FAxisZ);
end;
procedure T3dModel.Dead();
begin
if IsModelDead = False then
begin
IsModelDead := True;
FEngine.DeadList.Add(Self);
Self.Visible := False;
end;
end;
procedure T3dModel.Load3dModel(FileName: String);
begin
FModel:=LoadModel(PChar(FileName));
end;
procedure T3dModel.Load3dModelTexture(FileName: String);
begin
FTexture:= LoadTexture(PChar(FileName));
SetMaterialTexture(FModel.materials[0], MATERIAL_MAP_DIFFUSE, FTexture);//todo
end;
procedure T3dModel.Load3dModelAnimations(FileName: String; AnimCoint: integer);
begin
FAnims:=LoadModelAnimations(PChar(FileName),AnimCoint);
end;
procedure T3dModel.Update3dModelAnimations(Frame: longint);
begin
UpdateModelAnimation(FModel,FAnims[0],Frame);
end;
constructor T3dModel.Create(Engine: TModelEngine);
begin
FEngine := Engine;
FEngine.List.Add(Self);
FScale:=1.0;
FDrawMode:=dmNormal;
FColor:=WHITE;
FAngle:=1.0;
FPosition:=Vector3Create(0.0,0.0,0.0);
FAxis:=Vector3Create(0.0,0.0,0.0);
FScaleEx:= Vector3Create(1.0,1.0,1.0);
FAngleX:=0.0;
end;
destructor T3dModel.Destroy;
begin
UnloadTexture(Self.FTexture);
UnloadModel(Self.FModel);
inherited Destroy;
end;
procedure TModelEngine.SetCamera(AValue: TCamera);
begin
FCamera:=AValue;
end;
procedure TModelEngine.SetDrawsGrid(AValue: boolean);
begin
FDrawsGrid:= AValue;
end;
procedure TModelEngine.SetEngineCameraMode(AValue: TModelEngineCameraMode);
begin
if FEngineCameraMode=AValue then Exit;
FEngineCameraMode:=AValue;
case FEngineCameraMode of
cmCustom :SetCameraMode(FCamera, CAMERA_CUSTOM);
cmFree :SetCameraMode(FCamera, CAMERA_FREE);
cmOrbital :SetCameraMode(FCamera, CAMERA_ORBITAL);
cmFirstPerson :SetCameraMode(FCamera, CAMERA_FIRST_PERSON);
cmThirdPerson :SetCameraMode(FCamera, CAMERA_THIRD_PERSON);
end;
end;
procedure TModelEngine.SetEngineCameraPosition(AValue: TVector3);
begin
// if FEngineCameraPosition=AValue then Exit;
FEngineCameraPosition:=AValue;
// FCamera.position:=FEngineCameraPosition;
FCamera.target:=FEngineCameraPosition;
end;
procedure TModelEngine.SetGridSlices(AValue: longint);
begin
if FGridSlices=AValue then Exit;
FGridSlices:=AValue;
end;
procedure TModelEngine.SetGridSpacing(AValue: single);
begin
if FGridSpacing=AValue then Exit;
FGridSpacing:=AValue;
end;
procedure TModelEngine.SetWorldX(Value: Single);
begin
FWorld.X := Value;
end;
procedure TModelEngine.SetWorldY(Value: Single);
begin
FWorld.Y := Value;
end;
procedure TModelEngine.Draw();
var
i: Integer;
begin
BeginMode3d(FCamera);
for i := 0 to List.Count - 1 do
begin
T3dModel(List.Items[i]).Draw();
end;
if FDrawsGrid then DrawGrid(FGridSlices, FGridSpacing);
EndMode3d();
end;
procedure TModelEngine.ClearDeadModel;
var
i: Integer;
begin
for i := 0 to DeadList.Count - 1 do
begin
if DeadList.Count >= 1 then
begin
if T3dModel(DeadList.Items[i]).IsModelDead = True then
begin
T3dModel(DeadList.Items[i]).FEngine.List.Remove(DeadList.Items[i]);
end;
end;
end;
DeadList.Clear;
end;
procedure TModelEngine.Move(MoveCount: Double);
var
i: Integer;
begin
UpdateCamera(FCamera); // Update camera
for i := 0 to List.Count - 1 do
begin
T3dModel(List.Items[i]).Move(MoveCount);
end;
end;
constructor TModelEngine.Create;
begin
List := TList.Create;
DeadList := TList.Create;
FCamera.position := Vector3Create(3.0, 4.0, 0.0);
FCamera.target := Vector3Create(0.0, 0.5, 0.0);
FCamera.up := Vector3Create(0.0, 1.0, 0.0);
FCamera.fovy := 75.0;
FCamera.projection := CAMERA_PERSPECTIVE;
SetEngineCameraMode(cmCustom);
FGridSpacing:=0.5;
FGridSlices:=10;
end;
destructor TModelEngine.Destroy;
var
i: Integer;
begin
for i := 0 to List.Count - 1 do
begin
T3dModel(List.Items[i]).Destroy;
end;
List.Destroy;
DeadList.Destroy;
inherited Destroy;
end;
end.
|
unit Lbdbedit;
interface
Uses SysUtils,StdCtrls,Classes,Buttons,Controls,ExtCtrls,Menus,
Messages,DBCtrls,DB;
Type TLabelDBEdit=class(TWinControl)
protected
BackUp:String;
procedure WriteCaption(s:string);
Function ReadCaption:String;
procedure WriteDS(s:TDataSource);
Function ReadDS:TDataSource;
procedure WriteDF(s:string);
Function ReadDF:string;
procedure LEOnEnter(Sender:TObject);
procedure LEOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
public
Lbl:TLabel;
Edit:TDBEdit;
constructor Create(AOwner:TComponent); override;
procedure WMSize(var Msg:TMessage); message WM_SIZE;
function GetHeight:integer;
published
property Caption:String read ReadCaption write WriteCaption;
property DataSource:TDataSource read ReadDS write WriteDS;
property DataField:string read ReadDF write WriteDF;
end;
Type TLabelDBMemo=class(TWinControl)
protected
BackUp:TStringList;
procedure WriteCaption(s:string);
Function ReadCaption:String;
procedure WriteDS(s:TDataSource);
Function ReadDS:TDataSource;
procedure WriteDF(s:string);
Function ReadDF:string;
procedure MemoOnEnter(Sender:TObject);
procedure MemoOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
public
Lbl:TLabel;
Memo:TDBMemo;
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure WMSize(var Msg:TMessage); message WM_SIZE;
function GetHeight:integer;
published
property Caption:String read ReadCaption write WriteCaption;
property DataSource:TDataSource read ReadDS write WriteDS;
property DataField:string read ReadDF write WriteDF;
end;
procedure Register;
implementation
Uses WinTypes;
function TLabelDBEdit.GetHeight:integer;
begin
GetHeight:=-Lbl.Font.Height+13-Edit.Font.Height
end;
constructor TLabelDBEdit.Create(AOwner:TComponent);
begin
inherited create(AOwner);
Lbl:=TLabel.Create(self);
Edit:=TDBEdit.Create(self);
Lbl.Parent:=self;
Edit.Parent:=self;
Lbl.Left:=0;
Lbl.Top:=0;
Edit.Left:=0;
Edit.OnEnter:=LEOnEnter;
Edit.OnKeyUp:=LEOnKeyUp
end;
procedure TLabelDBEdit.LEOnEnter(Sender:TObject);
begin
Edit.SetFocus;
BackUp:=Edit.Text
end;
procedure TLabelDBEdit.LEOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=VK_ESCAPE then
Edit.Text:=BackUp
end;
procedure TLabelDBEdit.WMSize(var Msg:TMessage);
begin
Lbl.Height:=-Lbl.Font.Height+3;
Lbl.Width:=Msg.LParamLo;
Edit.Top:=Lbl.Height;
Edit.Height:=-Edit.Font.Height+10;
Edit.Width:=Msg.LParamLo;
Height:=Edit.Height+Lbl.Height+1;
Width:=Msg.LParamLo;
end;
procedure TLabelDBEdit.WriteCaption(s:String);
begin
Lbl.Caption:=s
end;
function TLabelDBEdit.ReadCaption:String;
begin
ReadCaption:=Lbl.Caption
end;
procedure TLabelDBEdit.WriteDS(s:TDataSource);
begin
Edit.DataSource:=s
end;
function TLabelDBEdit.ReadDS:TDataSource;
begin
ReadDS:=Edit.DataSource
end;
procedure TLabelDBEdit.WriteDF(s:string);
begin
Edit.DataField:=s
end;
function TLabelDBEdit.ReadDF:string;
begin
ReadDF:=Edit.DataField
end;
function TLabelDBMemo.GetHeight:integer;
begin
GetHeight:=-Lbl.Font.Height+13-Memo.Font.Height
end;
destructor TLabelDBMemo.Destroy;
begin
Lbl.Free;
Memo.Free;
BackUp.Free;
inherited Destroy
end;
constructor TLabelDBMemo.Create(AOwner:TComponent);
begin
inherited create(AOwner);
Lbl:=TLabel.Create(self);
Memo:=TDBMemo.Create(self);
BackUp:=TStringList.Create;
Memo.OnEnter:=MemoOnEnter;
Memo.OnKeyUp:=MemoOnKeyUp;
Lbl.Parent:=self;
Memo.Parent:=self;
Lbl.Left:=0;
Lbl.Top:=0;
Memo.Left:=0
end;
procedure TLabelDBMemo.MemoOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=VK_ESCAPE then begin
Memo.Clear;
Memo.Lines.AddStrings(BackUp)
end
end;
procedure TLabelDBMemo.MemoOnEnter(Sender:TObject);
begin
Memo.SetFocus;
BackUp.Clear;
BackUp.AddStrings(Memo.Lines)
end;
procedure TLabelDBMemo.WMSize(var Msg:TMessage);
begin
Lbl.Height:=-Lbl.Font.Height+3;
Lbl.Width:=Msg.LParamLo;
Memo.Top:=Lbl.Height;
Memo.Height:=Msg.LParamHi-Memo.Top;
Memo.Width:=Msg.LParamLo;
Height:=Msg.LParamHi;
Width:=Msg.LParamLo;
end;
procedure TLabelDBMemo.WriteCaption(s:String);
begin
Lbl.Caption:=s
end;
function TLabelDBMemo.ReadCaption:String;
begin
ReadCaption:=Lbl.Caption
end;
procedure TLabelDBMemo.WriteDS(s:TDataSource);
begin
Memo.DataSource:=s
end;
function TLabelDBMemo.ReadDS:TDataSource;
begin
ReadDS:=Memo.DataSource
end;
procedure TLabelDBMemo.WriteDF(s:string);
begin
Memo.DataField:=s
end;
function TLabelDBMemo.ReadDF:string;
begin
ReadDF:=Memo.DataField
end;
procedure Register;
begin
RegisterComponents('MyOwn',[TLabelDBEdit]);
RegisterComponents('MyOwn',[TLabelDBMemo])
end;
end.
|
unit SRUtils;
{----------------------------------------------------------------------}
{ Version : 1.30 }
{ Autor : Simon Reinhardt }
{ eMail : reinhardt@picsoft.de }
{ Internet : http://www.picsoft.de }
{ }
{ Hilfreiche Prozeduren und Funktionen, die die Borland-Programmierer }
{ offensichtlich vergessen haben. }
{----------------------------------------------------------------------}
{----------------------------------------------------------------------}
{ Version 1.30: }
{ Neu: GetShiftState }
{ }
{ Version 1.29: }
{ Neu: ExtractFileDir, LastDelimiter }
{ Geรคndert: GetExeForProtocol, FindAssociatedProgram }
{ }
{ Version 1.28: }
{ Geรคndert: DateTimeToStrDef, DateToStrDef }
{ Neu: Konstante PeriodNames }
{ }
{ Version 1.27: }
{ Neu: GetWindowState, GetSystemWorkArea }
{ }
{ Version 1.26: }
{ Neu: GetFirstDayOfWeek }
{ Geรคndert: IsSummerTime, }
{ Initialisierung von FirstWeekDay und FirstWeekDate in Delphi 1 }
{ }
{ Version 1.25: }
{ Neu: GetHourFromTime, GetMinuteFromTime, GetSecondFromTime }
{ Geรคndert: GetDayFromDate, GetMonthFromDate, GetYearFromDate }
{ }
{ Version 1.24: }
{ Geรคndert: Konstanten ShortForbiddenChars und LongForbiddenChars }
{ }
{ Version 1.23: }
{ Geรคndert: GetWeekOfYear, GetWeeksPerYear }
{ }
{ Version 1.22: }
{ Neu: DateToStrDef, StrToDateDef, GetWeeksPerYear }
{ Geรคndert: GetFirstPartOfString, AddBackSlash }
{ }
{----------------------------------------------------------------------}
interface
{$I SRDefine.inc}
{$IFDEF SR_Delphi1}
uses WinTypes, WinProcs, Graphics, Classes;
{$ELSE}
uses Windows, Graphics, Classes;
{$ENDIF}
const
{ Standard Encarta & FlatStyle Color Constants }
{ Diese konstanten hat maik Porkert am 31.10.2000 }
{ in de.comp.lang.delphi.non-tech gepostet. }
{ Ich stelle Sie hier zur Verfรผgung: }
ecDarkBlue = TColor($00996633);
ecBlue = TColor($00CF9030);
ecLightBlue = TColor($00CFB78F);
ecDarkRed = TColor($00302794);
ecRed = TColor($005F58B0);
ecLightRed = TColor($006963B6);
ecDarkGreen = TColor($00385937);
ecGreen = TColor($00518150);
ecLightGreen = TColor($0093CAB1);
ecDarkYellow = TColor($004EB6CF);
ecYellow = TColor($0057D1FF);
ecLightYellow = TColor($00B3F8FF);
ecDarkBrown = TColor($00394D4D);
ecBrown = TColor($00555E66);
ecLightBrown = TColor($00829AA2);
ecDarkKaki = TColor($00D3D3D3);
ecKaki = TColor($00C8D7D7);
ecLightKaki = TColor($00E0E9EF);
{$IFDEF SR_Delphi1}
Max_Path = 255;
{$ENDIF}
{ Ungรผltige Zeichen fuer 8.3-Dateinamen im DOS-Format: }
ShortForbiddenChars :
set of char = [':','?','*',';','=','+','<','>','|','"','[',']',' ','\',#39];
{ Ungรผltige Zeichen fuer lange Dateinamen im Win9x-Format: }
LongForbiddenChars :
set of char = ['\','/',':','*','?','"','<','>','|'];
{ Bezeichner fรผr relative Datumsangaben in DateTimeToStrDef und DateToStrDef: }
PeriodNames :
array [0..4] of string = ('รbermorgen', 'Morgen', 'Heute', 'Gestern', 'Vorgestern');
type
TFileSizeFormat = (fsByte, fsKilobyte, fsMegabyte);
{ Rรผckgabe-Formate fรผr die Funktion GetFileSize }
{---------------------------------------}
{ Funktionen fรผr alle Delphi-Versionen: }
{---------------------------------------}
function AddBackslash(FileName:string):string;
{ erweitert den Dateinamen mit einem abschlieรenden Backslash }
function CutBackSlash(FileName:string):string;
{ entfernt den abschlieรenden Backslash aus dem Dateinamen }
function CutRootDirectory(FName:string):string;
{ entfernt das Stammverzeichnis aus einem Dateinamen }
function DateTimeToStrDef(ADate:TDateTime;Default:string;CompareToday:boolean):string;
{ Umwandlung DateTime->String mit Rรผckgabe eines Default-Wertes bei Fehlern }
function DateToStrDef(ADate:TDateTime;Default:string;CompareToday:boolean):string;
{ Umwandlung Date->String mit Rรผckgabe eines Default-Wertes bei Fehlern }
function ExecAndWait(const Filename,Params:string;WindowState:word):boolean;
{ Startet ein Programm und wartet auf dessen Ende }
function ExpandString(S:string;AChar:char;ALength:word):string;
{ Erweitert einen String mit dem Zeichen "AChar" auf die Lรคnge ALength }
function ExtractRawFileName(DName:string):string;
{ Gibt von einem vollen Dateinamen mit Pfad nur den Dateinamen ohne Erweiterung zurรผck }
function GetBuildInfo(const AFilename:String; var V1,V2,V3,V4:Word):Boolean;
{ Ermittelt die vier Versionsnummern einer Exe- oder Dll-Datei }
function GetDayFromDate(ADate:TDateTime):word;
{ Gibt den Tag im Monat aus einem Datums-Wert zurรผck }
function GetDayOfYear(ADate:TDateTime):word;
{ Gibt den Tag im Jahr aus einem Datums-Wert zurรผck }
function GetDaysPerMonth(AYear,AMonth:integer):integer;
{ Gibt die Anzahl Tage in einem Monat zurรผck }
function GetFileSize(FileName:string;AFormat:TFileSizeFormat):integer;
{ Ermittelt die Grรถรe der Datei "FileName" im Format "AFormat" }
function GetFirstDayOfWeek(ADate:TDateTime):TDateTime;
{ Gibt den ersten Tag der Woche zurรผck, in dem das Datum ADate liegt }
function GetFirstPartOfString(var AText:string;Delimiter:char;IncludeDelimiter:boolean):string;
{ Extrahiert aus einem String den ersten Teil bis zum Zeichen "Delimiter" und entfernt
diesen Teil aus dem String "AText" }
function GetHourFromTime(ATime:TDateTime):byte;
{ Gibt die Stunde aus einem Zeit-Wert zurรผck }
function GetMinuteFromTime(ATime:TDateTime):byte;
{ Gibt die Minute aus einem Zeit-Wert zurรผck }
function GetMonthFromDate(ADate:TDateTime):word;
{ Gibt den Monat aus einem Datums-Wert zurรผck }
function GetSecondFromTime(ATime:TDateTime):byte;
{ Gibt die Sekunde aus einem Zeit-Wert zurรผck }
function GetShiftState:TShiftState;
{ Ermittelt den Zustand der Shift-, Alt- und Ctrl-Tasten }
function GetSystemDir:string;
{ Ermittelt das Windows-System-Verzeichnis }
function GetVersionNr(ExeName:string;BuildNr:boolean):string;
{ Generiert einen Versionsnummern-string zu einer Exe- oder Dll-Datei }
function GetWeekOfYear(ADate:TDateTime):byte;
{ Gibt die Woche im Jahr aus einem Datums-Wert zurรผck }
function GetWeeksPerYear(AYear:word):byte;
{ Gibt die Wochenzahl der letzten Woche im Jahr "AYear" zurรผck }
function GetWindowsDir:string;
{ Ermittelt das Windows-Verzeichnis }
function GetYearFromDate(ADate:TDateTime):word;
{ Gibt das Jahr aus einem Datums-Wert zurรผck }
function IntToStrFixed(IntValue:integer;OutDigits:byte):string;
{ Umwandlung Int->String mit fester Stellenzahl und fรผhrenden Nullen }
function IsSummertime(ADate:TDateTime):boolean;
{ Ermmittelt, ob ein Datum in der Sommerzeit liegt }
function ReverseString(AText:string):string;
{ Spiegelt einen String, die Buchstabenfolge wird umgedreht }
function RGBToStr(RGBColor:integer):string;
{ Umwandlung Windows-RGB-Wert -> HTML-RGB-Wert }
function StripForbiddenChars(AText:string):string;
{ Entfernt fรผr Dateinamen nicht erlaubte Zeichen aus einem String }
function StrToDateDef(S:string;Def:TDateTime):TDateTime;
{ Umwandlung String->Date mit Rรผckgabe eines Default-Wertes bei Fehlern }
function StrToDateTimeDef(S:string;Def:TDateTime):TDateTime;
{ Umwandlung String->DateTime mit Rรผckgabe eines Default-Wertes bei Fehlern }
function StrToFloatDef(S:string;Def:extended):extended;
{ Umwandlung String->Extended mit Rรผckgabe eines Default-Wertes bei Fehlern }
function ValidFileName(DName:string):boolean;
{ Ermittelt, ob es sich um einen gรผltigen Dateinamen handelt }
{---------------------------------------}
{ Funktionen nur fรผr Delphi 1: }
{---------------------------------------}
{$IFDEF SR_Delphi1}
procedure DrawEdge(ACanvas:TCanvas;ARect:TRect;Raised:boolean);
{ Zeichnet einen 3D-Rahmen auf der Zeichenflรคche ACanvas }
procedure SetFileDate(FName:string;FDate:LongInt);
{ Setzt das Erstellungs-Datum einer Datei }
function Trim(const S:string):string;
{ Entfernt fรผhrende und abschlieรende Leerzeichen aus einem String }
{$ENDIF}
{---------------------------------------}
{ Funktionen nur fรผr alle 32Bit- }
{ Delphi-Versionen }
{---------------------------------------}
{$IFDEF SR_Delphi2_Up}
function ConvertStrToDateTime(s:String):TDateTime;
{ Versucht, einen String in einen Datumswert zu wandeln
(zuvor muร InitLocale aufgerufen werden) }
function FindAssociatedProgram(DateiName:String):String;
{ Ermittelt das mit einer Dateierweiterung verknรผpfte Programm }
function GetExeForProtocol(URL:string):string;
{ Ermittelt das mit einem รbertragungs-Protokoll verknรผpfte Programm }
function GetFocussedControl:HWnd;
{ Ermittelt das Fensterelement mit dem Eingabefokus }
function GetLongPathName(APath:String):String;
{ Wandelt einen verkรผrzten DOS-Dateinamen in einen langen Windows9x-Dateinamen }
function GetSystemFileDescription(FileName:string):string;
{ Liefert die in Windows registrierte Dateibeschreibung zu einem Dateinamen zurรผck }
function GetSystemWorkArea:TRect;
{ Gibt das Windows-Desktop-Rechteck ohne die Taskbar zurรผck }
function GetWindowState(WHandle:HWnd):integer;
{ Gibt den Anzeige-Zustand des Fenster mit dem Handle "WHandle" zurรผck }
function GetWinUsername:string;
{ Ermittelt den aktuell angemeldeten Windows-Benutzer }
procedure InitLocale;
{ Ermittelt die aktuellen Lokalisierungseinstellungen
(muร vor ConvertStrToDateTime aufgerufen werden) }
function IsWindowsNT:boolean;
{ Ermittelt ob es sich bei dem Betriebssystem um eine Windows-NT-Version handelt }
procedure SendKeys(AText:string);
{ Sendet einen String als Folge von Tastendrรผcken an ein Fensterelement }
function SetFileDate(FName:string;FDate:Integer):boolean;
{ Setzt das Erstellungs-Datum einer Datei }
procedure SimulateKeyDown(Key : byte);
{ Sendet eine KeyDown-Nachricht an ein Fensterelement }
procedure SimulateKeystroke(Key:byte; extra:DWORD);
{ Sendet einen vollstรคndigen Tatendruck (KeyDown+KeyUp) an ein Fensterelement }
procedure SimulateKeyUp(Key : byte);
{ Sendet eine KeyUp-Nachricht an ein Fensterelement }
{$ENDIF}
{---------------------------------------}
{ Funktionen nur fรผr bestimmte }
{ Delphi-Versionen }
{---------------------------------------}
{$IFNDEF SR_Delphi4_Up}
procedure FreeAndNil(var Obj);
{ Gibt ein Objekt frei und setzt den Objektzeiger auf NIL (Delphi 1..3) }
{$ENDIF}
{$IFNDEF SR_Delphi3_Up}
function ExtractFileDir(APath:string):string;
{ Gibt wie ExtractFilePath den Pfad eines Dateinamens zurรผck,
aber ohne abschlieรenden Backslash }
function IsLeapYear(AYear: Integer):boolean;
{ Ermittelt, ob ein Jahr ein Schaltjahr ist (Delphi 1..2) }
function LastDelimiter(AChar:char;AText:string):integer;
{ Ermittelt die letzte Position des Zeichens AChar im string AText (Delphi 1..2) }
{$ENDIF}
implementation
uses SysUtils {$IFDEF SR_Delphi2_Up}, Registry, ShellAPI {$ELSE}, Forms, Ver {$ENDIF};
var
{$IFDEF SR_Delphi2_Up}
FirstWeekDay : Integer = 2; { Wochentag, mit dem die Woche beginnt
(siehe Delphi-Wochentage)
2 : Montag (nach DIN 1355) }
FirstWeekDate : Integer = 4; { 1 : Beginnt am ersten Januar
4 : Erste-4 Tage-Woche (nach DIN 1355)
7 : Erste volle Woche }
{$ELSE}
FirstWeekDay : Integer;
FirstWeekDate : Integer;
{$ENDIF}
LocaleIDate,
LocaleILDate,
CurrentYear2Digit,
CurrentCentury : Integer;
function AddBackslash(Filename:string):string;
begin
if (length(Filename)>0) and (Filename[length(Filename)]<>'\') then
Result:=Filename+'\'
else
Result:=Filename;
end; {AddBackslash}
{$IFDEF SR_Delphi2_Up}
function ConvertStrToDateTime(s:String):TDateTime;
var
p,p2 : PChar;
i1,i2,i3 : Integer; { einzelne Datumsangaben }
Mode : Integer; { Reihenfolge beim Datum }
t1,t2 : String; { Separator }
t : String; { Zeit }
function GetNumber:Integer;
var s : String;
begin
p:=p2;
while p2^ in ['0'..'9'] do
Inc(p2);
SetString(s,p,p2-p);
Result:=StrToIntDef(s,-1);
end; {GetNumber}
function GetSeparator:String;
begin
p:=p2;
while Not (p2^ in ['0'..'9',#0]) do
Inc(p2);
SetString(Result,p,p2-p);
Result:=Trim(Result);
end; {GetSeparator}
procedure ConvertTo4Digit(var AYear:Integer);
begin
if AYear in [0..100] then begin
if AYear>CurrentYear2Digit then
Dec(AYear,100);
Inc(AYear,CurrentCentury);
end;
end; {ConvertTo4Digit}
begin
Result:=0;
p:=Pointer(s);
if p=Nil then
Exit;
p2:=p;
i1:=GetNumber;
t1:=GetSeparator;
i2:=GetNumber;
t2:=GetSeparator;
i3:=GetNumber;
SetString(t,p2,StrLen(p2));
t:=Trim(t);
Mode:=-1;
if (i1<1) or (i1>31) then { y/m/d }
Mode:=2
else begin
if (i3<1) or (i3>31) then begin { x/x/y }
if Not (i1 in [1..31]) then { m/d/y }
Mode:=0
else
if Not (i2 in [1..31]) then { d/m/y }
Mode:=1;
end
else
if i1=i2 then { Tag=Monat, Format egal }
Mode:=1;
end;
if Mode<0 then begin { Format nicht auswertbar }
if LocaleIDate in [0..1] then
Mode:=LocaleIDate { Reihenfolge kurzes Datum }
else begin
if LocaleILDate in [0..1] then
Mode:=LocaleILDate { Reihenfolge langes Datum }
else // evtl. User befragen
Mode:=1;
end;
end;
// Jahr auf vierstellig bringen
case Mode of
0..1 : ConvertTo4Digit(i3);
2 : ConvertTo4Digit(i1);
end;
// Datum konvertieren
case Mode of
0 : Result:=EncodeDate(i3,i1,i2);
1 : Result:=EncodeDate(i3,i2,i1);
2 : Result:=EncodeDate(i1,i2,i3);
end;
if Length(t)>0 then
Result:=Result+StrToTime(t);
end; {ConvertStrToDateTime}
{$ENDIF}
function CutBackSlash(FileName:string):string;
begin
if (length(FileName)>0) and (FileName[length(FileName)]='\') then
Result:=copy(FileName,1,length(FileName)-1)
else
Result:=FileName;
end; {CutBackSlash}
function CutRootDirectory(FName:string):string;
var P : integer;
begin
P:=Pos(':',FName);
if (P>0) and (P<length(FName)) then
delete(FName,1,P+1);
Result:=FName;
end; {CutRootDirectory}
function DateTimeToStrDef(ADate:TDateTime;Default:string;CompareToday:boolean):string;
var DayDiff : integer;
begin
try
Result:='';
if CompareToday then begin
DayDiff:=trunc(Date)-trunc(ADate);
if (abs(DayDiff))<=2 then
Result:=PeriodNames[DayDiff+2]+', '+TimeToStr(frac(ADate));
end;
if Result='' then
Result:=DateTimeToStr(ADate);
except
Result:=Default;
end;
end; {DateTimeToStrDef}
function DateToStrDef(ADate:TDateTime;Default:string;CompareToday:boolean):string;
var DayDiff : integer;
begin
try
Result:='';
if CompareToday then begin
DayDiff:=trunc(Date)-trunc(ADate);
if (abs(DayDiff))<=2 then
Result:=PeriodNames[DayDiff+2];
end;
if Result='' then
Result:=DateToStr(ADate);
except
Result:=Default;
end;
end; {DateToStrDef}
{$IFDEF SR_Delphi1}
procedure DrawEdge(ACanvas:TCanvas;ARect:TRect;Raised:boolean);
begin
with ACanvas do begin
if Raised then
Pen.Color:=clBtnHighlight
else
Pen.Color:=clBtnShadow;
MoveTo(ARect.Right-1,ARect.Top);
LineTo(ARect.Left,ARect.Top);
LineTo(ARect.Left,ARect.Bottom-2);
if Raised then
Pen.Color:=clBtnShadow
else
Pen.Color:=clBtnHighlight;
MoveTo(ARect.Left,ARect.Bottom-2);
LineTo(ARect.Right-1,ARect.Bottom-2);
LineTo(ARect.Right-1,ARect.Top);
Pen.Color:=clWindowFrame;
MoveTo(ARect.Left,ARect.Bottom-1);
LineTo(ARect.Right,ARect.Bottom-1);
LineTo(ARect.Right,ARect.Top);
end;
end; {DrawEdge}
{$ENDIF}
function ExecAndWait(const Filename, Params: string;
WindowState: word): boolean;
{$IFDEF SR_Delphi2_Up}
var
SUInfo: TStartupInfo;
ProcInfo: TProcessInformation;
CmdLine: string;
begin
{ Enclose filename in quotes to take care of
long filenames with spaces. }
CmdLine := '"' + Filename + '" ' + Params;
FillChar(SUInfo, SizeOf(SUInfo), #0);
with SUInfo do begin
cb := SizeOf(SUInfo);
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := WindowState;
end;
Result := CreateProcess(NIL, PChar(CmdLine), NIL, NIL, FALSE,
CREATE_NEW_CONSOLE or
NORMAL_PRIORITY_CLASS, NIL,
PChar(ExtractFilePath(Filename)),
SUInfo, ProcInfo);
{ Wait for it to finish. }
if Result then
WaitForSingleObject(ProcInfo.hProcess, INFINITE);
{$ELSE}
var
InstanceID : THandle;
Buff: array[0..255] of char;
begin
StrPCopy(Buff, Filename + ' ' + Params);
InstanceID := WinExec(Buff, WindowState);
if InstanceID < 32 then
{ a value less than 32 indicates an Exec error }
Result := FALSE
else begin
Result := TRUE;
repeat
Application.ProcessMessages;
until Application.Terminated or
(GetModuleUsage(InstanceID) = 0);
end;
{$ENDIF}
end;
function ExpandString(S:string;AChar:char;ALength:word):string;
begin
while length(S)<ALength do
S:=AChar+S;
Result:=S;
end; {ExpandString}
{$IFNDEF SR_Delphi3_Up}
function ExtractFileDir(APath:string):string;
begin
Result:=CutBackslash(ExtractFilePath(APath));
end; {ExtractFileDir}
{$ENDIF}
function ExtractRawFileName(DName:string):string;
begin
Result:=ChangeFileExt(ExtractFileName(DName),'');
end; {ExtractRawFileName}
{$IFDEF SR_Delphi2_Up}
function FindAssociatedProgram(DateiName:String):String;
var Reg : TRegistry;
Res : boolean;
AKey : string;
i : integer;
begin
Result:='';
{$IFDEF SR_Delphi4_Up}
Reg := TRegistry.Create(Key_Read);
{$ELSE}
Reg := TRegistry.Create;
{$ENDIF}
try
Reg.RootKey := HKEY_CLASSES_ROOT;
Res:=Reg.OpenKey(ExtractFileExt(DateiName), false);
if Res then begin
AKey:=Reg.ReadString('');
Reg.CloseKey;
if AKey<>'' then begin
Res:=Reg.OpenKey(AKey+'\shell\open\command', false);
if Res then begin
Result:=Reg.ReadString('');
for i:=length(Result) downto 1 do
if Result[i]='"' then
delete(Result, i, 1);
i:=Pos(LowerCase('.exe'), LowerCase(Result));
if i>0 then
delete(Result, i+4, length(Result)-i-3);
Result:=GetLongPathName(Result);
Reg.CloseKey;
end;
end;
end;
finally
Reg.Free;
end;
end; {FindAssociatedProgram}
{$ENDIF}
{$IFNDEF SR_Delphi4_Up}
procedure FreeAndNil(var Obj);
var P : TObject;
begin
P:=TObject(Obj);
TObject(Obj):=nil;
P.Free;
end; {FreeAndNil}
{$ENDIF}
function GetBuildInfo(const AFilename:String; var V1,V2,V3,V4:Word):Boolean;
var
VerInfoSize : Integer;
{$IFDEF SR_Delphi2_Up}
VerValueSize : DWord;
Dummy : DWord;
VerValue : PVSFixedFileInfo;
{$ELSE}
VerValueSize : Word;
Dummy : LongInt;
VerValue : ^TVS_FixedFileInfo;
{$ENDIF}
VerInfo : Pointer;
FName : PChar;
begin
FName:=StrAlloc(Max_Path);
try
StrPCopy(FName,AFileName);
VerInfoSize:=GetFileVersionInfoSize(FName,Dummy);
Result:=False;
if VerInfoSize>0 then begin
GetMem(VerInfo,VerInfoSize);
try
if GetFileVersionInfo(FName,0,VerInfoSize,VerInfo) then begin
if VerQueryValue(VerInfo,'\',Pointer(VerValue),VerValueSize) then
with VerValue^ do begin
V1:=dwFileVersionMS shr 16;
V2:=dwFileVersionMS and $FFFF;
V3:=dwFileVersionLS shr 16;
V4:=dwFileVersionLS and $FFFF;
end;
Result:=True;
end;
finally
FreeMem(VerInfo,VerInfoSize);
end;
end;
finally
StrDispose(FName);
end;
end; {GetBuildInfo}
function GetDayFromDate(ADate:TDateTime):word;
var Y,M,D : word;
begin
try
Decodedate(ADate, Y, M, D);
except
D:=0;
end;
Result:=D;
end; {GetDayFromDate}
function GetDayOfYear(ADate:TDateTime):word;
{ liefert den Tag im Jahr }
var T,M,J : word;
Erster : TDateTime;
begin
try
DecodeDate(ADate,J,M,T);
Erster:=EncodeDate(J,1,1);
Result:=trunc(ADate-Erster+1);
except
Result:=0;
end;
end; {GetDayOfYear}
function GetDaysPerMonth(AYear,AMonth:integer):integer;
const
DaysInMonth: array [1..12] of Integer =
(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
begin
Result:=DaysInMonth[AMonth];
if (AMonth=2) and IsLeapYear(AYear) then
Inc(Result);
end; {GetDaysPerMonth}
{$IFDEF SR_Delphi2_Up}
function GetExeForProtocol(URL:string):string;
var Reg : TRegistry;
Res : boolean;
Temp : string;
P : integer;
begin
Result:='';
P:=Pos(':', URL);
if P>1 then
delete(URL, P, length(URL)-P+1);
{$IFDEF SR_Delphi4_Up}
Reg := TRegistry.Create(Key_Read);
{$ELSE}
Reg := TRegistry.Create;
{$ENDIF}
try
Reg.Rootkey:=HKEY_CLASSES_ROOT;
Res:=Reg.OpenKey(URL+'\shell\open\command', false);
if Res then begin
Temp:=Reg.ReadString('');
while (length(Temp)>0) and ((Temp[1]='"') or (Temp[1]=' ')) do
delete(Temp, 1, 1);
P:=Pos('"', Temp);
if P>0 then
delete(Temp, P, length(Temp)-P+1);
Result:=Temp;
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end; {GetExeForProtocol}
{$ENDIF}
function GetFileSize(FileName:string;AFormat:TFileSizeFormat):integer;
var SR : TSearchRec;
begin
if FindFirst(FileName, faAnyFile, SR)=0 then begin
Result:=SR.Size;
if AFormat=fsKilobyte then
Result:=Result div 1024;
if AFormat=fsMegabyte then
Result:=Result div (1024*1024);
FindClose(SR);
end
else
Result:=-1;
end; {GetFileSize}
function GetFirstDayOfWeek(ADate:TDateTime):TDateTime;
begin
while DayOfWeek(ADate)<>1 do
ADate:=ADate-1;
Result:=ADate;
end; {GetFirstDayOfWeek}
function GetFirstPartOfString(var AText:string;Delimiter:char;IncludeDelimiter:boolean):string;
var P : integer;
begin
P:=Pos(Delimiter,AText);
if P>0 then begin
if IncludeDelimiter then
Result:=copy(AText,1,P)
else
Result:=copy(AText,1,P-1);
delete(AText,1,P);
end
else
Result:=AText;
end; {GetFirstPartOfString}
function GetHourFromTime(ATime:TDateTime):byte;
var H,M,S,MS : word;
begin
try
DecodeTime(ATime, H, M, S, MS);
except
H:=0;
end;
Result:=H;
end; {GetHourFromTime}
function GetMinuteFromTime(ATime:TDateTime):byte;
var H,M,S,MS : word;
begin
try
DecodeTime(ATime, H, M, S, MS);
except
M:=0;
end;
Result:=M;
end; {GetMinuteFromTime}
{$IFDEF SR_Delphi2_Up}
function GetFocussedControl:HWnd;
var OtherThreadID,
Buffer : DWord;
ParentWnd : HWnd;
begin
Result:=0;
ParentWnd:=GetForegroundWindow;
if ParentWnd<>0 then begin
OtherThreadID:=GetWindowThreadProcessID(ParentWnd, @Buffer);
if AttachThreadInput(GetCurrentThreadID, OtherThreadID, true) then begin
Result:=GetFocus;
AttachThreadInput(GetCurrentThreadID, OtherThreadID, false);
end;
end;
end; {GetFocussedControl}
function GetLongPathName(APath:String):String;
var
i : Integer;
h : THandle;
Data : TWin32FindData;
IsBackSlash : Boolean;
begin
APath:=ExpandFileName(APath);
i:=Pos('\',APath);
Result:=Copy(APath,1,i);
Delete(APath,1,i);
repeat
i:=Pos('\',APath);
IsBackSlash:=i>0;
if Not IsBackSlash then
i:=Length(APath)+1;
h:=FindFirstFile(PChar(Result+Copy(APath,1,i-1)),Data);
if h<>INVALID_HANDLE_VALUE then begin
try
Result:=Result+Data.cFileName;
if IsBackSlash then
Result:=Result+'\';
finally
Windows.FindClose(h);
end;
end
else begin
Result:=Result+APath;
Exit;
end;
Delete(APath,1,i);
until Length(APath)=0;
end; {GetLongPathName}
{$ENDIF}
function GetMonthFromDate(ADate:TDateTime):word;
var Y,M,D : word;
begin
try
Decodedate(ADate,Y,M,D);
except
M:=0;
end;
Result:=M;
end; {GetMonthFromDate}
function GetSecondFromTime(ATime:TDateTime):byte;
var H,M,S,MS : word;
begin
try
DecodeTime(ATime, H, M, S, MS);
except
S:=0;
end;
Result:=S;
end; {GetSecondFromTime}
function GetShiftState:TShiftState;
const Key_Pressed = 65535;
{$IFDEF SR_Delphi1}
var AState : integer;
{$ELSE}
var AState : short;
{$ENDIF}
begin
Result:=[];
AState:=GetAsyncKeyState(VK_Shift);
if (AState and Key_Pressed)>0 then
Include(Result, ssShift);
AState:=GetAsyncKeyState(VK_Menu);
if (AState and Key_Pressed)>0 then
Include(Result, ssAlt);
AState:=GetAsyncKeyState(VK_Control);
if (AState and Key_Pressed)>0 then
Include(Result, ssCtrl);
end; {GetShiftState}
function GetSystemDir:string;
var SysDir : array [0..Max_Path] of char;
begin
GetSystemDirectory(SysDir,Max_Path);
Result:=AddBackSlash(String(SysDir));
end; {GetSystemDir}
{$IFDEF SR_Delphi2_Up}
function GetSystemFileDescription(FileName:string):string;
var
SysIL : UInt;
Info : TSHFileInfo;
begin
SysIL:=SHGetFileInfo(PChar(FileName), 0, Info, SizeOf(TSHFileInfo), SHGFI_TYPENAME);
if SysIL<>0 then
Result:=Info.szTypeName
else
Result:='';
end; {GetSystemFileDescr}
function GetSystemWorkArea:TRect;
var PRect : ^TRect;
begin
Result:=Rect(0, 0, 0, 0);
GetMem(PRect, SizeOf(TRect));
try
if SystemParametersInfo(SPI_GetWorkArea, 0, PRect, 0) then begin
Result:=PRect^;
end;
finally
FreeMem(PRect);
end;
end; {GetSystemWorkArea}
{$ENDIF}
function GetVersionNr(ExeName:string;BuildNr:boolean):string;
var V1,V2,V3,V4 : Word;
begin
if GetBuildInfo(ExeName, V1, V2, V3, V4) then begin
if BuildNr then
Result:=IntToStr(V1)+'.'+IntToStr(V2)+IntToStr(V3)+' (Build '+IntToStr(V4)+')'
else
Result:=IntToStr(V1)+'.'+IntToStr(V2)+IntToStr(V3);
end
else
Result:='';
end; {GetVersionNr}
function GetWeekOfYear(ADate:TDateTime):byte;
var Year,Month,Day : Word;
begin
ADate:=ADate-((DayOfWeek(ADate)-FirstWeekDay+7) mod 7)+ 7-FirstWeekDate;
DecodeDate(ADate, Year, Month, Day);
Result:=(Trunc(ADate-EncodeDate(Year,1,1)) div 7)+1;
end; {GetWeekOfYear}
function GetWeeksPerYear(AYear:word):byte;
var AWeek : byte;
begin
AWeek:=GetWeekOfYear(EncodeDate(AYear,12,31));
if AWeek=1 then
Result:=52
else
Result:=AWeek;
end; {GetWeeksPerYear}
function GetWindowsDir:string;
var WinDir : array [0..Max_Path] of char;
begin
GetWindowsDirectory(WinDir,Max_Path);
Result:=AddBackSlash(String(WinDir));
end; {GetWindowsDir}
{$IFDEF SR_Delphi2_Up}
function GetWindowState(WHandle:HWnd):integer;
{$IFNDEF SR_Delphi4_Up}
var PPlcmnt : TWindowPlacement;
{$ELSE}
var PPlcmnt : WindowPlacement;
{$ENDIF}
{ Die Rรผckgabewerte der Funktion entsprechen folgenden Konstanten
aus der Unit Windows.pas:
SW_HIDE = 0;
SW_SHOWNORMAL = 1;
SW_SHOWMINIMIZED = 2;
SW_SHOWMAXIMIZED = 3;
SW_SHOWNOACTIVATE = 4;
SW_SHOW = 5;
SW_MINIMIZE = 6;
SW_SHOWMINNOACTIVE = 7;
SW_SHOWNA = 8;
SW_RESTORE = 9;
SW_SHOWDEFAULT = 10; }
begin
{$IFNDEF SR_Delphi4_Up}
PPlcmnt.Length:=SizeOf(TWindowPlacement);
{$ELSE}
PPlcmnt.Length:=SizeOf(WindowPlacement);
{$ENDIF}
if GetWindowPlacement(WHandle, @PPlcmnt) then
Result:=PPlcmnt.ShowCmd
else
Result:=-1;
end; {GetWindowState}
function GetWinUsername:string;
var UName : PChar;
USize : DWord;
begin
USize:=Max_Path;
UName:=StrAlloc(USize);
try
GetUserName(UName,USize);
Result:=string(UName);
finally
StrDispose(UName);
end;
end; {GetWinUsername}
{$ENDIF}
function GetYearFromDate(ADate:TDateTime):word;
var Y,M,D : word;
begin
try
Decodedate(ADate, Y, M, D);
except
Y:=0;
end;
Result:=Y;
end; {GetYearFromDate}
{$IFDEF SR_Delphi2_Up}
procedure InitLocale;
var SystemTime: TSystemTime;
function GetLocaleInt(AInfo:LCTYPE):Integer;
var
Buffer: array[0..1] of Char;
begin
if GetLocaleInfo(GetThreadLocale, AInfo, Buffer, 2) > 0 then
Result:=Ord(Buffer[0])-Ord('0')
else
Result:=-1;
end; {GetLocaleInt}
begin
LocaleIDate :=GetLocaleInt(LOCALE_IDATE);
LocaleILDate:=GetLocaleInt(LOCALE_ILDATE);
GetLocalTime(SystemTime);
CurrentYear2Digit:=SystemTime.wYear mod 100;
CurrentCentury:=SystemTime.wYear-CurrentYear2Digit;
end; {InitLocale}
{$ENDIF}
function IntToStrFixed(IntValue:integer;OutDigits:byte):string;
begin
try
Result:=IntToStr(Abs(IntValue));
while (length(Result)<OutDigits) do
Result:='0'+Result;
if (IntValue<0) then
Result:='-'+Result;
except
Result:='';
end;
end; {IntToStrFixed}
{$IFNDEF SR_Delphi3_Up}
function IsLeapYear(AYear:integer):boolean;
begin
Result:=(AYear mod 4=0) and ((AYear mod 100<>0) or (AYear mod 400=0));
end; {IsLeapYear}
{$ENDIF}
function IsSummertime(ADate:TDateTime):boolean;
{ Ermmittelt, ob ein Datum in der Sommerzeit liegt }
var AYear,
AMonth,
ADay : word;
Beginn,
Ende : TDateTime;
begin
try
DecodeDate(ADate, AYear, AMonth, ADay);
if AYear<1980 then
{ Keine Sommerzeit vor 1980 }
Result:=false
else begin
{ Beginn der Sommerzeit: }
Beginn:=EncodeDate(AYear, 3, 31);
while DayOfWeek(Beginn)<>1 do
Beginn:=Beginn-1;
{ Ende der Sommerzeit: }
if AYear<=1995 then
{ bis 1995: letzter So im September }
Ende:=EncodeDate(AYear, 9, 30)
else
{ ab 1996: letzter So im Oktober }
Ende:=EncodeDate(AYear, 10, 31);
while DayOfWeek(Ende)<>1 do
Ende:=Ende-1;
Result:=(ADate>=Beginn) and (ADate<Ende);
end;
except
Result:=false;
end;
end; {IsSummertime}
{$IFDEF SR_Delphi2_Up}
function IsWindowsNT:boolean;
var OsVinfo : TOSVERSIONINFO;
begin
ZeroMemory(@OsVinfo,sizeOf(OsVinfo));
OsVinfo.dwOSVersionInfoSize := sizeof(TOSVERSIONINFO);
if GetVersionEx(OsVinfo) then
Result:=OsVinfo.dwPlatformId = VER_PLATFORM_WIN32_NT
else
Result:=false;
end; {IsWindowsNT}
{$ENDIF}
{$IFNDEF SR_Delphi3_Up}
function LastDelimiter(AChar:char;AText:string):integer;
var i : integer;
begin
Result:=0;
if length(AText)=0 then
Exit;
for i:=length(AText) downto 1 do begin
if AText[i]=AChar then begin
Result:=i;
Exit;
end;
end;
end;
{$ENDIF}
function ReverseString(AText:string):string;
var i : byte;
begin
Result:='';
for i:=length(AText) downto 1 do
Result:=Result+AText[i];
end; {ReverseString}
function RGBToStr(RGBColor:integer):string;
var ColText : string;
begin
ColText:=IntToHex(RGBColor,6);
Result:=copy(ColText,5,2)+copy(ColText,3,2)+copy(ColText,1,2);
end; {RGBToStr}
{$IFDEF SR_Delphi2_Up}
procedure SendKeys(AText:string);
var i : integer;
w : word;
begin
for i:=1 to Length(AText) do begin
w:=VkKeyScan(AText[i]);
if ((HiByte(w)<>$FF) and (LoByte(w)<>$FF)) then begin
{If the key requires the shift key down - hold it down}
if HiByte(w) and 1 = 1 then
SimulateKeyDown(VK_SHIFT);
{Send the VK_KEY}
SimulateKeystroke(LoByte(w), 0);
{If the key required the shift key down - release it}
if HiByte(w) and 1 = 1 then
SimulateKeyUp(VK_SHIFT);
end;
end;
end; {SendKeys}
{$ENDIF}
{$IFDEF SR_Delphi1}
procedure SetFileDate(FName:string;FDate:LongInt);
var F : TFileStream;
begin
try
F:=TFileStream.Create(FName,fmOpenWrite);
FileSetDate(F.Handle,FDate);
finally
F.Free;
end;
end;
{$ELSE}
function SetFileDate(FName:string;FDate:Integer):boolean;
var F : TFileStream;
begin
try
F:=TFileStream.Create(FName,fmOpenWrite);
Result:=(FileSetDate(F.Handle,FDate)=0);
F.Free;
except
Result:=false;
end;
end; {SetFileDate}
{$ENDIF}
{$IFDEF SR_Delphi2_Up}
procedure SimulateKeyDown(Key : byte);
begin
Keybd_Event(Key, 0, 0, 0);
end; {SimulateKeyDown}
procedure SimulateKeystroke(Key:byte; extra:DWORD);
begin
Keybd_Event(Key, extra, 0, 0);
Keybd_Event(Key, extra, KEYEVENTF_KEYUP, 0);
end; {SimulateKeystroke}
procedure SimulateKeyUp(Key : byte);
begin
Keybd_Event(Key, 0, KEYEVENTF_KEYUP, 0);
end; {SimulateKeyUp}
{$ENDIF}
function StripForbiddenChars(AText:string):string;
var i : integer;
begin
if length(AText)>0 then
for i:=length(AText) downto 0 do
{$IFDEF SR_Delphi1}
if AText[i] in ShortForbiddenChars then
delete(AText,i,1);
{$ELSE}
if AText[i] in LongForbiddenChars then
delete(AText,i,1);
{$ENDIF}
Result:=AText;
end; {StripForbiddenChars}
function StrToDateDef(S:string;Def:TDateTime):TDateTime;
begin
try
Result:=StrToDate(S);
except
Result:=Def;
end;
end; {StrToDateDef}
function StrToDateTimeDef(S:string;Def:TDateTime):TDateTime;
begin
try
Result:=StrToDateTime(S);
except
Result:=Def;
end;
end; {StrToDateTimeDef}
function StrToFloatDef(S:string;Def:extended):extended;
begin
try
Result:=StrToFloat(S);
except
Result:=Def;
end;
end; {StrToFloatDef}
{$IFDEF SR_Delphi1}
function Trim(const S:string):string;
var i,L: Integer;
begin
L:=length(S);
i:=1;
while (i<=L) and (S[i]<=' ') do
inc(i);
if i>L then
Result:=''
else begin
while S[L]<=' ' do
dec(L);
Result:=Copy(S, i, L-i+1);
end;
end; {Trim}
{$ENDIF}
function ValidFileName(DName:string):boolean;
var i : integer;
begin
Result:=true;
for i:=1 to length(DName) do
{$IFDEF SR_Delphi1}
if DName[i] in ShortForbiddenChars then
Result:=false;
{$ELSE}
if DName[i] in LongForbiddenChars then
Result:=false;
{$ENDIF}
end; {ValidFileName}
{$IFDEF SR_Delphi1}
initialization
FirstWeekDay := 2; { Wochentag, mit dem die Woche beginnt
(siehe Delphi-Wochentage)
2 : Montag (nach DIN 1355) }
FirstWeekDate := 4; { 1 : Beginnt am ersten Januar
4 : Erste-4 Tage-Woche (nach DIN 1355)
7 : Erste volle Woche }
{$ENDIF}
end.
|
unit Tests.Grijjy.MongoDB.Settings;
interface
const
// Host and port of the MongoDB Server for the purpose of the unit tests.
// Defaults to the local host with the default port.
TEST_SERVER_HOST = 'localhost';
TEST_SERVER_PORT = 27017;
implementation
end.
|
{
***************************************************************************
* *
* This file is part of Lazarus DBF Designer *
* *
* Copyright (C) 2012 Vadim Vitomsky *
* *
* This source 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 code is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details. *
* *
* A copy of the GNU General Public License is available on the World *
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also *
* obtain it by writing to the Free Software Foundation, *
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
***************************************************************************}
unit useltype;
{$mode objfpc}{$H+}
interface
uses
LResources, Forms, StdCtrls, Buttons, urstrrings;
type
{ TFormSelectDbType }
TFormSelectDbType = class(TForm)
CancelBitBtn: TBitBtn;
CreateBitBtn: TBitBtn;
cbTableTypeComboBox: TComboBox;
TableTypeLabel: TLabel;
procedure CreateBitBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
end;
var
FormSelectDbType: TFormSelectDbType;
tl : Integer; //TableLevel property for new table
implementation
uses ustruct;
{ TFormSelectDbType }
procedure TFormSelectDbType.CreateBitBtnClick(Sender: TObject);
begin
tl := 4;// for default LableLevel
case cbTableTypeComboBox.ItemIndex of
0 : tl := 3;
1 : tl := 4;
2 : tl := 7;
3 : tl := 25;
end;//case
isNew := true;
FormDBSructureDesigner.ShowModal;
end;
procedure TFormSelectDbType.FormCreate(Sender: TObject);
begin
Caption:=rsCreateTable;
TableTypeLabel.Caption:=rsTableType;
CreateBitBtn.Caption:=rsCreate;
CancelBitBtn.Caption:=rsCancel;
end;
initialization
{$I useltype.lrs}
end.
|
program testord01(output);
{tests basic use of ord function}
const letterq = 'q';
var mycharint:integer;mychar:char;mybool:boolean;myint:integer;
begin
mycharint:=ord(letterq);
writeln(mycharint);
mychar:= 'F';
writeln(ord(mychar));
mybool:=True;
writeln(ord(mybool));
writeln(ord(not mybool));
myint:= 32769;
writeln(ord(myint));
myint:= -30973;
writeln(ord(myint));
end.
|
unit HotkeyManager;
interface
uses Classes, Controls, Menus, Windows, Messages, SysUtils;
const
ArrCount = 4;
type
THotkeyType = (HT_Nothing,HT_SimpleClick, HT_RecordMouse, HT_Playback);
THotkeyInfo = record
Hotkey: TShortCut;
HotkeyRegsteredID: Integer;
HotkeyType: THotkeyType;
end;
THotkeyInfoArr = array[0..ArrCount] of THotkeyInfo;
{ THotkeyManager }
THotkeyManager = class(TComponent)
private
FHandle: THandle;
FHotkeyInfoArr: THotkeyInfoArr;
FOnSimpleClick,
FOnRecordMouse,
FOnPlayback: TNotifyEvent;
Shoutcut_SimpleClick:Integer;
Shoutcut_RecordMouse:Integer;
Shoutcut_Playback:Integer;
function GetHotkeyTypeFromID(HotkeyID: Integer): THotkeyType;
protected
procedure WndProc(var Msg: TMessage);
public
procedure RegisterOneHotKey(hkType: THotkeyType; shortCut:TShortCut);
procedure RegisterAllHotKey(HotkeyInfoArr: THotkeyInfoArr);
procedure UnRegisterHotKeyNow;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property OnSimpleClick: TNotifyEvent read FOnSimpleClick write FOnSimpleClick;
property OnRecordMouse: TNotifyEvent read FOnRecordMouse write FOnRecordMouse;
property OnShowPlayback: TNotifyEvent read FOnPlayback write FOnPlayback;
end;
implementation
{ TRegisterAllHotkeys }
constructor THotkeyManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHandle := AllocateHWnd(WndProc);
end;
destructor THotkeyManager.Destroy;
begin
UnRegisterHotKeyNow;
DeallocateHWnd(FHandle);
inherited Destroy;
end;
function THotkeyManager.GetHotkeyTypeFromID(HotkeyID: Integer): THotkeyType;
var
i: Integer;
begin
Result := HT_Nothing;
for i := Low(FHotkeyInfoArr)+1 to High(FHotkeyInfoArr) do
if FHotkeyInfoArr[i].HotkeyRegsteredID = HotkeyID then
begin
Result := FHotkeyInfoArr[i].HotkeyType;
Break;
end;
end;
procedure THotkeyManager.WndProc(var Msg: TMessage);
var
HotkeyType: THotkeyType;
begin
if (not Assigned(OnSimpleClick)) or (not Assigned(OnRecordMouse))
or (not Assigned(FOnPlayback)) then
begin
MessageBox(0, 'An Error occured while Loading Hotkeys', 'Error', 0);
exit;
end;
with Msg do
if Msg = WM_Hotkey then
begin
HotkeyType := GetHotkeyTypeFromID(wParam);
if HotkeyType = HT_SimpleClick then FOnSimpleClick(Self);
if HotkeyType = HT_RecordMouse then FOnRecordMouse(Self);
if HotkeyType = HT_Playback then FOnPlayback(Self);
Result := 1;
end
else
Result := DefWindowProc(FHandle, Msg, wParam, lParam);
end;
procedure SeparateHotkey(Hotkey: Integer; var Modifiers, Vkey: Word);
var
Shift: TShiftState;
begin
Modifiers := 0; Vkey := 0;
ShortCutToKey(Hotkey, Vkey, Shift);
if ssShift in Shift then
Modifiers := Modifiers or MOD_SHIFT;
if ssCtrl in Shift then
Modifiers := Modifiers or MOD_CONTROL;
if ssAlt in Shift then
Modifiers := Modifiers or MOD_ALT;
end;
procedure THotkeyManager.RegisterOneHotKey(hkType: THotkeyType; shortCut:TShortCut);
var
i: Integer;
Hotkey: Integer;
Modifiers, Vkey: Word;
begin
for i := Low(FHotkeyInfoArr)+1 to High(FHotkeyInfoArr) do
if FHotkeyInfoArr[i].HotkeyType=hkType then
begin
if FHotkeyInfoArr[i].HotkeyRegsteredID<>0 then
UnRegisterHotKey(FHandle, FHotkeyInfoArr[i].HotkeyRegsteredID);
Hotkey := shortCut;
SeparateHotkey(Hotkey, Modifiers, Vkey);
FHotkeyInfoArr[i].HotkeyRegsteredID := GlobalAddAtom(PChar(Chr(i * i))) - $C000;
RegisterHotKey(FHandle, FHotkeyInfoArr[i].HotkeyRegsteredID, Modifiers, Vkey);
break;
end;
end;
procedure THotkeyManager.RegisterAllHotKey(HotkeyInfoArr: THotkeyInfoArr);
var
i: Integer;
Hotkey: Integer;
Modifiers, Vkey: Word;
begin
FHotkeyInfoArr := HotkeyInfoArr;
for i := Low(FHotkeyInfoArr)+1 to High(FHotkeyInfoArr) do
if FHotkeyInfoArr[i].Hotkey <> 0 then
begin
Hotkey := FHotkeyInfoArr[i].Hotkey;
SeparateHotkey(Hotkey, Modifiers, Vkey);
FHotkeyInfoArr[i].HotkeyRegsteredID := GlobalAddAtom(PChar(Chr(i * i))) - $C000;
RegisterHotKey(FHandle, FHotkeyInfoArr[i].HotkeyRegsteredID, Modifiers, Vkey);
// if not RegisterHotKey(FHandle, FHotkeyInfoArr[i].HotkeyRegsteredID, Modifiers, Vkey) then
// MessageBox(0, 'aaa', '', 0);
end;
end;
procedure THotkeyManager.UnRegisterHotKeyNow;
var
i: Integer;
begin
for i := Low(FHotkeyInfoArr)+1 to High(FHotkeyInfoArr) do
if FHotkeyInfoArr[i].HotkeyRegsteredID <> 0 then
UnRegisterHotKey(FHandle, FHotkeyInfoArr[i].HotkeyRegsteredID);
end;
end.
|
{
ID: a_zaky01
PROG: maze1
LANG: PASCAL
}
var
r0,c0,i,j,startr1,startr2,startc1,startc2,ans:longint;
input:string;
entrance1,entrance2:boolean;
path,path1,path2:array[1..100,1..38] of longint;
connected:array[1..100,1..38,1..100,1..38] of boolean;
fin,fout:text;
procedure dijkstra1(r,c,k:integer);
begin
if (path1[r,c]=0) or (path1[r,c]>k) then
begin
path1[r,c]:=k;
if c-1>0 then
if connected[r,c,r,c-1] then dijkstra1(r,c-1,k+1);
if c+1<=c0 then
if connected[r,c,r,c+1] then dijkstra1(r,c+1,k+1);
if r-1>0 then
if connected[r,c,r-1,c] then dijkstra1(r-1,c,k+1);
if r+1<=r0 then
if connected[r,c,r+1,c] then dijkstra1(r+1,c,k+1);
end;
end;
procedure dijkstra2(r,c,k:integer);
begin
if (path2[r,c]=0) or (path2[r,c]>k) then
begin
path2[r,c]:=k;
if c-1>0 then
if connected[r,c,r,c-1] then dijkstra2(r,c-1,k+1);
if c+1<=c0 then
if connected[r,c,r,c+1] then dijkstra2(r,c+1,k+1);
if r-1>0 then
if connected[r,c,r-1,c] then dijkstra2(r-1,c,k+1);
if r+1<=r0 then
if connected[r,c,r+1,c] then dijkstra2(r+1,c,k+1);
end;
end;
begin
assign(fin,'maze1.in');
assign(fout,'maze1.out');
reset(fin);
rewrite(fout);
entrance1:=false;
entrance2:=false;
readln(fin,c0,r0);
for i:=0 to r0 do
begin
if i>0 then
begin
readln(fin,input);
if input[1]=' ' then
if not entrance1 then
begin
startr1:=i;
startc1:=1;
entrance1:=true;
end
else
begin
startr2:=i;
startc2:=1;
entrance2:=true;
end;
if input[2*c0+1]=' ' then
if not entrance1 then
begin
startr1:=i;
startc1:=c0;
entrance1:=true;
end
else
begin
startr2:=i;
startc2:=c0;
entrance2:=true;
end;
for j:=1 to c0-1 do
if input[2*j+1]=' ' then
begin
connected[i,j,i,j+1]:=true;
connected[i,j+1,i,j]:=true;
end;
end;
readln(fin,input);
if i=0 then
for j:=1 to c0 do
if input[2*j]=' ' then
if not entrance1 then
begin
startr1:=1;
startc1:=j;
entrance1:=true;
end
else
begin
startr2:=1;
startc2:=j;
entrance2:=true;
end;
if i=r0 then
for j:=1 to c0 do
if input[2*j]=' ' then
if not entrance1 then
begin
startr1:=r0;
startc1:=j;
entrance1:=true;
end
else
begin
startr2:=r0;
startc2:=j;
entrance2:=true;
end;
if not(i=0) and not(i=r0) then
for j:=1 to c0 do
if input[2*j]=' ' then
begin
connected[i,j,i+1,j]:=true;
connected[i+1,j,i,j]:=true;
end;
end;
fillchar(path1,sizeof(path1),0);
fillchar(path2,sizeof(path2),0);
dijkstra1(startr1,startc1,1);
dijkstra2(startr2,startc2,1);
ans:=0;
for i:=1 to r0 do
for j:=1 to c0 do
begin
if (path1[i,j]=0) or ((path2[i,j]<>0) and (path1[i,j]>path2[i,j])) then path[i,j]:=path2[i,j]
else path[i,j]:=path1[i,j];
if ans<path[i,j] then ans:=path[i,j];
end;
writeln(fout,ans);
close(fin);
close(fout);
end.
|
{
Translation of the libv4l2 headers for FreePascal
Copyright (C) 2013 Yuriy Pilgun
libv4l2.h
(C) 2008 Hans de Goede <hdegoede@redhat.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
}
unit libv4l2;
interface
{$L libv4l2.so.0}
uses
ctypes;
type
PFILE=Pointer;
int64_t=clong;
{$ifdef cpu64}
size_t = cuint64;
ssize_t = cint64;
{$else}
size_t = cuint32;
ssize_t = cint32;
{$endif}
{ Point this to a FILE opened for writing when you want to log error and
status messages to a file, when NULL errors will get send to stderr }
var
// You should use libc fopen() if you want to assign this external variable.
v4l2_log_file: PFILE; external name 'v4l2_log_file';
{ Just like your regular open/close/etc, except that format conversion is
done if necessary when capturing. That is if you (try to) set a capture
format which is not supported by the cam, but is supported by libv4lconvert,
then the try_fmt / set_fmt will succeed as if the cam supports the format
and on dqbuf / read the data will be converted for you and returned in
the request format. enum_fmt will also report support for the formats to
which conversion is possible.
Another difference is that you can make v4l2_read() calls even on devices
which do not support the regular read() method.
Note the device name passed to v4l2_open must be of a video4linux2 device,
if it is anything else (including a video4linux1 device), v4l2_open will
fail.
Note that the argument to v4l2_ioctl after the request must be a valid
memory address of structure of the appropriate type for the request (for
v4l2 requests which expect a structure address). Passing in NULL or an
invalid memory address will not lead to failure with errno being EFAULT,
as it would with a real ioctl, but will cause libv4l2 to break, and you
get to keep both pieces.
}
function v4l2_open(filename:Pchar; oflag:longint;args:array of const):longint; cdecl; external name 'v4l2_open';
function v4l2_open(filename:Pchar; oflag:longint):longint; cdecl; varargs; external name 'v4l2_open';
function v4l2_close(fd:longint):longint; cdecl; external name 'v4l2_close';
function v4l2_dup(fd:longint):longint; cdecl; external name 'v4l2_dup';
function v4l2_ioctl(fd:longint; request:dword;args:array of const):longint; cdecl; external name 'v4l2_ioctl';
function v4l2_ioctl(fd:longint; request:dword):longint;cdecl; varargs; external name 'v4l2_ioctl';
function v4l2_ioctl(fd:longint; request:dword;data:pointer):longint; cdecl; external name 'v4l2_ioctl';
function v4l2_read(fd:longint; buffer:pointer; n:size_t):ssize_t; cdecl; external name 'v4l2_read';
function v4l2_write(fd:longint; buffer:pointer; n:size_t):ssize_t; cdecl; external name 'v4l2_write';
function v4l2_mmap(start:pointer; length:size_t; prot:longint; flags:longint; fd:longint; offset:int64_t):pointer; cdecl; external name 'v4l2_mmap';
function v4l2_munmap(_start:pointer; length:size_t):longint; cdecl; external name 'v4l2_munmap';
{ Misc utility functions }
{ This function takes a value of 0 - 65535, and then scales that range to
the actual range of the given v4l control id, and then if the cid exists
and is not locked sets the cid to the scaled value.
Normally returns 0, even if the cid did not exist or was locked, returns
non 0 when an other error occured. }
function v4l2_set_control(fd:longint; cid:longint; value:longint):longint;external name 'v4l2_set_control';
{ This function returns a value of 0 - 65535, scaled to from the actual range
of the given v4l control id. When the cid does not exist, or could not be
accessed -1 is returned. }
function v4l2_get_control(fd:longint; cid:longint):longint;external name 'v4l2_get_control';
{ "low level" access functions, these functions allow somewhat lower level
access to libv4l2 (currently there only is v4l2_fd_open here) }
{ Flags for v4l2_fd_open's v4l2_flags argument }
const
{ Disable all format conversion done by libv4l2, this includes the software
whitebalance, gamma correction, flipping, etc. libv4lconvert does. Use this
if you want raw frame data, but still want the additional error checks and
the read() emulation libv4l2 offers. }
V4L2_DISABLE_CONVERSION = $01;
{ This flag is *OBSOLETE*, since version 0.5.98 libv4l *always* reports
emulated formats to ENUM_FMT, except when conversion is disabled. }
V4L2_ENABLE_ENUM_FMT_EMULATION = $02;
{ v4l2_fd_open: open an already opened fd for further use through
v4l2lib and possibly modify libv4l2's default behavior through the
v4l2_flags argument.
Returns fd on success, -1 if the fd is not suitable for use through libv4l2
(note the fd is left open in this case). }
function v4l2_fd_open(fd:longint; v4l2_flags:longint):longint;external name 'v4l2_fd_open';
implementation
end.
|
unit MD4;
interface
uses
Windows, Classes, Sysutils, Forms;//,DebugLog;
type
PMD4Digest = ^TMD4Digest;
TMD4Digest = packed record
case Integer of
0: (A, B, C, D: DWORD);
1: (v: array[0..15] of Byte);
end;
TMD4Context = record
Hash: array[0..3] of DWORD;
Hi, Lo: longword;
Buffer: array[0..63] of Byte;
Index: DWord;
end;
const
CEmptyMD4: TMD4Digest = (A: 0; B: 0; C: 0; D: 0);
CMD4Size = SizeOf( TMD4Digest );
function MD4String(const S: string): TMD4Digest;
function MD4File(const FileName: string; var Digest: TMD4Digest; PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean;
function MD4Stream(const Stream: TStream; var Digest: TMD4Digest; PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean;
function MD4Buffer(const Buffer; Size: Integer): TMD4Digest;
function MD4DigestToStr(const Digest: TMD4Digest): string;
function StrToMD4Digest(str: string; var AMD4: TMD4Digest): Boolean;
function MD4DigestCompare(const Digest1, Digest2: TMD4Digest): Boolean;
function EmptyMD4(const Digest: TMD4Digest): Boolean;
procedure MD4Init(var Context: TMD4Context);
procedure MD4Update(var Context: TMD4Context; const Buffer; Len: longword);
procedure MD4Final(var Context: TMD4Context; var Digest: TMD4Digest);
/// <summary>
/// ่ฎก็ฎWebHash๏ผๅไธๅๆฐๆฎ่ฟ่ก่ฎก็ฎ๏ผๆฏๅๅคงๅฐๅฐไบ็ญไบ256K
/// ๅฆๆๅชๆไธๅๅฐฑๅช็ฎไธๅ๏ผๅฆๆๅชๆไธคๅๅฐฑ็ฎไธคๅ๏ผๅคไบไธๅๅฐฑ็ฎ
/// ๅไธญๅไธๅ
/// </summary>
/// <param name="FileName">ๆไปถๅ</param>
/// <param name="WebHash">WebHash</param>
/// <returns>ๆๅ่ฟๅTrueใๅคฑ่ดฅFalse</returns>
function GetWebHash(const FileName: string; var WebHash: TMD4Digest):Boolean; overload;
function GetWebHash(const FileStream: TStream; var WebHash: TMD4Digest; PAbort: PBoolean = nil):Boolean; overload;
/// <summary>
/// ่ฎก็ฎๅๆฎตHash
/// </summary>
/// <param name="Stream">ๆไปถๆต</param>
/// <param name="AStartPos">่ฎก็ฎ่ตทๅงไฝ็ฝฎ</param>
/// <param name="ALen">่ฎก็ฎๆฐๆฎ้ฟๅบฆ</param>
/// <param name="ASegmentHash">ๅๆฎตHash</param>
/// <param name="PAbort">่ฟ็จ็ปๆๆ ๅฟ</param>
/// <param name="AFastCalc">ๆฏๅฆๅฟซ้่ฎก็ฎ</param>
/// <returns>ๆๅ่ฟๅTrueใๅคฑ่ดฅFalse</returns>
function ed2kSegmentHash(const Stream: TStream; AStartPos: Int64; ALen: Int64; var ASegmentHash: TMD4Digest;
PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean;
/// <summary>
/// ่ฎก็ฎed2kHash
/// </summary>
/// <param name="FileName">่ฎก็ฎๅ</param>
/// <param name="Digest">่ฎก็ฎ็ปๆHash</param>
/// <param name="ASegmentHash">ๅๅHashไธฒ</param>
/// <param name="PAbort">่ฟ็จ็ปๆๆ ๅฟ</param>
/// <param name="AFastCalc">ๆฏๅฆๅฟซ้่ฎก็ฎ</param>
/// <returns>ๆๅ่ฟๅTrueใๅคฑ่ดฅFalse</returns>
function ed2kFile(const FileName: string; var Digest: TMD4Digest;
ASegmentHash: PChar; PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean;
/// <summary>
/// ่ฎก็ฎed2kHash
/// </summary>
/// <param name="Stream">ๆไปถๆต</param>
/// <param name="Digest">่ฎก็ฎ็ปๆHash</param>
/// <param name="ASegmentHash">ๅๅHashไธฒ</param>
/// <param name="PAbort">่ฟ็จ็ปๆๆ ๅฟ</param>
/// <param name="AFastCalc">ๆฏๅฆๅฟซ้่ฎก็ฎ</param>
/// <returns>ๆๅ่ฟๅTrueใๅคฑ่ดฅFalse</returns>
function ed2kStream(const Stream: TStream; var Digest: TMD4Digest;
ASegmentHash: PChar; PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean;
implementation
{$R-}{$Q-}
function LRot32(a, b: longword): longword;
begin
Result := (a shl b) or (a shr (32 - b));
end;
procedure MD4Compress(var Context: TMD4Context);
var
Data: array[0..15] of dword;
A, B, C, D: dword;
begin
Move(Context.Buffer, Data, Sizeof(Data));
A := Context.Hash[0];
B := Context.Hash[1];
C := Context.Hash[2];
D := Context.Hash[3];
A := LRot32(A + (D xor (B and (C xor D))) + Data[0], 3);
D := LRot32(D + (C xor (A and (B xor C))) + Data[1], 7);
C := LRot32(C + (B xor (D and (A xor B))) + Data[2], 11);
B := LRot32(B + (A xor (C and (D xor A))) + Data[3], 19);
A := LRot32(A + (D xor (B and (C xor D))) + Data[4], 3);
D := LRot32(D + (C xor (A and (B xor C))) + Data[5], 7);
C := LRot32(C + (B xor (D and (A xor B))) + Data[6], 11);
B := LRot32(B + (A xor (C and (D xor A))) + Data[7], 19);
A := LRot32(A + (D xor (B and (C xor D))) + Data[8], 3);
D := LRot32(D + (C xor (A and (B xor C))) + Data[9], 7);
C := LRot32(C + (B xor (D and (A xor B))) + Data[10], 11);
B := LRot32(B + (A xor (C and (D xor A))) + Data[11], 19);
A := LRot32(A + (D xor (B and (C xor D))) + Data[12], 3);
D := LRot32(D + (C xor (A and (B xor C))) + Data[13], 7);
C := LRot32(C + (B xor (D and (A xor B))) + Data[14], 11);
B := LRot32(B + (A xor (C and (D xor A))) + Data[15], 19);
A := LRot32(A + ((B and C) or (B and D) or (C and D)) + Data[0] + $5A827999, 3);
D := LRot32(D + ((A and B) or (A and C) or (B and C)) + Data[4] + $5A827999, 5);
C := LRot32(C + ((D and A) or (D and B) or (A and B)) + Data[8] + $5A827999, 9);
B := LRot32(B + ((C and D) or (C and A) or (D and A)) + Data[12] + $5A827999, 13);
A := LRot32(A + ((B and C) or (B and D) or (C and D)) + Data[1] + $5A827999, 3);
D := LRot32(D + ((A and B) or (A and C) or (B and C)) + Data[5] + $5A827999, 5);
C := LRot32(C + ((D and A) or (D and B) or (A and B)) + Data[9] + $5A827999, 9);
B := LRot32(B + ((C and D) or (C and A) or (D and A)) + Data[13] + $5A827999, 13);
A := LRot32(A + ((B and C) or (B and D) or (C and D)) + Data[2] + $5A827999, 3);
D := LRot32(D + ((A and B) or (A and C) or (B and C)) + Data[6] + $5A827999, 5);
C := LRot32(C + ((D and A) or (D and B) or (A and B)) + Data[10] + $5A827999, 9);
B := LRot32(B + ((C and D) or (C and A) or (D and A)) + Data[14] + $5A827999, 13);
A := LRot32(A + ((B and C) or (B and D) or (C and D)) + Data[3] + $5A827999, 3);
D := LRot32(D + ((A and B) or (A and C) or (B and C)) + Data[7] + $5A827999, 5);
C := LRot32(C + ((D and A) or (D and B) or (A and B)) + Data[11] + $5A827999, 9);
B := LRot32(B + ((C and D) or (C and A) or (D and A)) + Data[15] + $5A827999, 13);
A := LRot32(A + (B xor C xor D) + Data[0] + $6ED9EBA1, 3);
D := LRot32(D + (A xor B xor C) + Data[8] + $6ED9EBA1, 9);
C := LRot32(C + (D xor A xor B) + Data[4] + $6ED9EBA1, 11);
B := LRot32(B + (C xor D xor A) + Data[12] + $6ED9EBA1, 15);
A := LRot32(A + (B xor C xor D) + Data[2] + $6ED9EBA1, 3);
D := LRot32(D + (A xor B xor C) + Data[10] + $6ED9EBA1, 9);
C := LRot32(C + (D xor A xor B) + Data[6] + $6ED9EBA1, 11);
B := LRot32(B + (C xor D xor A) + Data[14] + $6ED9EBA1, 15);
A := LRot32(A + (B xor C xor D) + Data[1] + $6ED9EBA1, 3);
D := LRot32(D + (A xor B xor C) + Data[9] + $6ED9EBA1, 9);
C := LRot32(C + (D xor A xor B) + Data[5] + $6ED9EBA1, 11);
B := LRot32(B + (C xor D xor A) + Data[13] + $6ED9EBA1, 15);
A := LRot32(A + (B xor C xor D) + Data[3] + $6ED9EBA1, 3);
D := LRot32(D + (A xor B xor C) + Data[11] + $6ED9EBA1, 9);
C := LRot32(C + (D xor A xor B) + Data[7] + $6ED9EBA1, 11);
B := LRot32(B + (C xor D xor A) + Data[15] + $6ED9EBA1, 15);
Inc(Context.Hash[0], A);
Inc(Context.Hash[1], B);
Inc(Context.Hash[2], C);
Inc(Context.Hash[3], D);
Context.Index := 0;
FillChar(Context.Buffer, Sizeof(Context.Buffer), 0);
end;
procedure MD4Burn(var Context: TMD4Context);
begin
Context.Hi := 0; Context.Lo := 0;
Context.Index := 0;
FillChar(Context.Buffer, Sizeof(Context.Buffer), 0);
FillChar(Context.Hash, Sizeof(Context.Hash), 0);
end;
procedure MD4Init(var Context: TMD4Context);
begin
MD4Burn(Context);
Context.Hash[0] := $67452301;
Context.Hash[1] := $EFCDAB89;
Context.Hash[2] := $98BADCFE;
Context.Hash[3] := $10325476;
end;
procedure MD4Update(var Context: TMD4Context; const Buffer; Len: longword);
var
PBuf: ^byte;
begin
Inc(Context.Hi, Len shr 29);
Inc(Context.Lo, Len * 8);
if Context.Lo < (Len * 8) then
Inc(Context.Hi);
PBuf := @Buffer;
while Len > 0 do
begin
if (Sizeof(Context.Buffer) - Context.Index) <= DWord(Len) then
begin
Move(PBuf^, Context.Buffer[Context.Index], Sizeof(Context.Buffer) - Context.Index);
Dec(Len, Sizeof(Context.Buffer) - Context.Index);
Inc(PBuf, Sizeof(Context.Buffer) - Context.Index);
MD4Compress(Context);
end
else
begin
Move(PBuf^, Context.Buffer[Context.Index], Len);
Inc(Context.Index, Len);
Len := 0;
end;
end;
end;
procedure MD4Final(var Context: TMD4Context; var Digest: TMD4Digest);
begin
Context.Buffer[Context.Index] := $80;
if Context.Index >= 56 then
MD4Compress(Context);
PDWord(@Context.Buffer[56])^ := Context.Lo;
PDWord(@Context.Buffer[60])^ := Context.Hi;
MD4Compress(Context);
Move(Context.Hash, Digest, Sizeof(Context.Hash));
MD4Burn(Context);
end;
function MD4Buffer(const Buffer; Size: Integer): TMD4Digest;
var
Context: TMD4Context;
begin
MD4Init(Context);
MD4Update(Context, Buffer, Size);
MD4Final(Context, Result);
end;
function MD4String(const S: string): TMD4Digest;
begin
Result := MD4Buffer(PChar(S)^, Length(S));
end;
function MD4File(const FileName: string; var Digest: TMD4Digest; PAbort: PBoolean; AFastCalc: Boolean): Boolean;
var
hFile: THandle;
Stream: TFileStream;
begin
Result := False;
//่ฟๆ ทๆๅผ๏ผๅฏไปฅไผๅๆไปถ่ฏปๅ๏ผ่ไธๆไปถๆๅผๅคฑ่ดฅ(ไธๅญๅจ)ไนไธไผ่งฆๅๅผๅธธ
hFile := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0);
if hFile = INVALID_HANDLE_VALUE then //ๆไปถๆๅผๅคฑ่ดฅ
Exit;
Stream := TFileStream.Create(hFile);
try
Result := MD4Stream(Stream, Digest, PAbort, AFastCalc);
finally
Stream.Free;
end;
end;
function MD4Stream(const Stream: TStream; var Digest: TMD4Digest; PAbort: PBoolean; AFastCalc: Boolean): Boolean;
var
Context: TMD4Context;
Buffer: array[0..16383] of Byte;
ReadBytes: Int64;
SavePos: Int64;
begin
Result := True;
MD4Init(Context);
SavePos := Stream.Position;
try
Stream.Seek(0, soFromBeginning);
repeat
ReadBytes := Stream.Read(Buffer, SizeOf(Buffer));
MD4Update(Context, Buffer, ReadBytes);
if (PAbort <> nil) and PAbort^ then //ๆฏๅฆๅๆญข่ฎก็ฎ
begin
Result := False;
Exit;
end;
if (not AFastCalc) then
begin
if GetCurrentThreadID = MainThreadID then
Application.ProcessMessages;
Sleep(3);
end;
until (ReadBytes <> SizeOf(Buffer));
finally
Stream.Seek(SavePos, soFromBeginning);
end;
MD4Final(Context, Digest);
end;
function MD4DigestToStr(const Digest: TMD4Digest): string;
begin
SetLength(Result, Sizeof(TMD4Digest) * 2);
BinToHex(@Digest, PChar(Result), Sizeof(TMD4Digest));
end;
function StrToMD4Digest(str: string; var AMD4: TMD4Digest): Boolean;
begin
Result := False;
ZeroMemory(@AMD4, Sizeof(TMD4Digest));
if Length(Str) <> Sizeof(TMD4Digest) * 2 then
Exit;
HexToBin(PChar(Str), @AMD4, Sizeof(TMD4Digest));
Result := True;
end;
function MD4DigestCompare(const Digest1, Digest2: TMD4Digest): Boolean;
begin
Result := CompareMem(@Digest1, @Digest2, Sizeof(TMD4Digest));
end;
function EmptyMD4(const Digest: TMD4Digest): Boolean;
begin
Result := (Digest.A = 0) and (Digest.B = 0) and (Digest.C = 0) and (Digest.D = 0);
end;
function ed2kFile(const FileName: string; var Digest: TMD4Digest;
ASegmentHash: PChar; PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean;
var
hFile: THandle;
Stream: TFileStream;
begin
Result := False;
//่ฟๆ ทๆๅผ๏ผๅฏไปฅไผๅๆไปถ่ฏปๅ๏ผ่ไธๆไปถๆๅผๅคฑ่ดฅ(ไธๅญๅจ)ไนไธไผ่งฆๅๅผๅธธ
hFile := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0);
if hFile = INVALID_HANDLE_VALUE then //ๆไปถๆๅผๅคฑ่ดฅ
Exit;
Stream := TFileStream.Create(hFile);
try
Result := ed2kStream(Stream, Digest, ASegmentHash, PAbort, AFastCalc);
finally
Stream.Free;
end;
end;
function GetWebHash(const FileStream: TStream; var WebHash: TMD4Digest; PAbort: PBoolean = nil):Boolean;
type
TSegment = record
SegmentID: Integer; //ไป0ๅผๅง
SegmentSize: Int64;
SegmentHash: TMD4Digest;
end;
TFileSegmentInfo = record
FileSize: Int64;
SegmentSize: Int64;
SegmentCount: Integer;
Segments: array of TSegment;
end;
const
CSegmentSize = 256*1024;
var
AInfo: TFileSegmentInfo;
MemStream: TMemoryStream;
I,ModCount:Integer;
begin
Result := False;
MemStream := TMemoryStream.Create;
try
AInfo.FileSize := FileStream.Size;
ModCount := 0;
AInfo.SegmentSize := CSegmentSize;
if AInfo.FileSize <= CSegmentSize then
begin
AInfo.SegmentCount := 1;
AInfo.SegmentSize := AInfo.FileSize;
end else
begin
AInfo.SegmentSize := CSegmentSize;
ModCount := AInfo.FileSize mod AInfo.SegmentSize;
AInfo.SegmentCount := AInfo.FileSize div AInfo.SegmentSize;
if ModCount > 0 then
Inc(AInfo.SegmentCount);
end;
SetLength(AInfo.Segments, AInfo.SegmentCount);
ZeroMemory(@AInfo.Segments[0], Sizeof(TSegment) * AInfo.SegmentCount);
for I := 0 to AInfo.SegmentCount - 1 do
begin
if Assigned(PAbort) and PAbort^ then Exit;
AInfo.Segments[I].SegmentID := I;
if (I < AInfo.SegmentCount - 1) or (ModCount = 0) then
begin
AInfo.Segments[I].SegmentSize := AInfo.SegmentSize;
if (I =0) or (I = AInfo.SegmentCount - 1) or
(I = ((AInfo.SegmentCount - 1) div 2)) then
begin
Result := ed2kSegmentHash(FileStream, I * CSegmentSize, AInfo.Segments[I].SegmentSize, AInfo.Segments[I].SegmentHash);
if not Result then Exit;
MemStream.WriteBuffer(AInfo.Segments[I].SegmentHash, SizeOf(TMD4Digest));
//AddLogStrToFile(Format('็ฌฌ%dๅHash๏ผ%s',[I,MD4DigestToStr(AInfo.Segments[I].SegmentHash)]));
end;
end
else
begin
AInfo.Segments[I].SegmentSize := ModCount;
if (I =0) or (I = AInfo.SegmentCount - 1) or
(I = ((AInfo.SegmentCount - 1) div 2)) then
begin
Result := ed2kSegmentHash(FileStream, I * CSegmentSize, AInfo.Segments[I].SegmentSize, AInfo.Segments[I].SegmentHash);
if not Result then Exit;
MemStream.WriteBuffer(AInfo.Segments[I].SegmentHash, SizeOf(TMD4Digest));
//AddLogStrToFile(Format('็ฌฌ%dๅHash๏ผ%s',[I,MD4DigestToStr(AInfo.Segments[I].SegmentHash)]));
end;
end;
end;
Result := MD4Stream(MemStream,WebHash);
//AddLogStrToFile(Format('WebHash๏ผ%s',[MD4DigestToStr(WebHash)]));
finally
MemStream.free;
end;
end;
function GetWebHash(const FileName: string; var WebHash: TMD4Digest):Boolean;
type
TSegment = record
SegmentID: Integer; //ไป0ๅผๅง
SegmentSize: Int64;
SegmentHash: TMD4Digest;
end;
TFileSegmentInfo = record
FileSize: Int64;
SegmentSize: Int64;
SegmentCount: Integer;
Segments: array of TSegment;
end;
const
CSegmentSize = 256*1024;
var
hFile: THandle;
Stream: TFileStream;
AInfo: TFileSegmentInfo;
MemStream: TMemoryStream;
I,ModCount:Integer;
begin
Result := False;
//่ฟๆ ทๆๅผ๏ผๅฏไปฅไผๅๆไปถ่ฏปๅ๏ผ่ไธๆไปถๆๅผๅคฑ่ดฅ(ไธๅญๅจ)ไนไธไผ่งฆๅๅผๅธธ
hFile := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0);
if hFile = INVALID_HANDLE_VALUE then //ๆไปถๆๅผๅคฑ่ดฅ
Exit;
Stream := TFileStream.Create(hFile);
MemStream := TMemoryStream.Create;
try
AInfo.FileSize := Stream.Size;
ModCount := 0;
AInfo.SegmentSize := CSegmentSize;
if AInfo.FileSize <= CSegmentSize then
begin
AInfo.SegmentCount := 1;
AInfo.SegmentSize := AInfo.FileSize;
end else
begin
AInfo.SegmentSize := CSegmentSize;
ModCount := AInfo.FileSize mod AInfo.SegmentSize;
AInfo.SegmentCount := AInfo.FileSize div AInfo.SegmentSize;
if ModCount > 0 then
Inc(AInfo.SegmentCount);
end;
SetLength(AInfo.Segments, AInfo.SegmentCount);
ZeroMemory(@AInfo.Segments[0], Sizeof(TSegment) * AInfo.SegmentCount);
for I := 0 to AInfo.SegmentCount - 1 do
begin
AInfo.Segments[I].SegmentID := I;
if (I < AInfo.SegmentCount - 1) or (ModCount = 0) then
begin
AInfo.Segments[I].SegmentSize := AInfo.SegmentSize;
if (I =0) or (I = AInfo.SegmentCount - 1) or
(I = ((AInfo.SegmentCount - 1) div 2)) then
begin
Result := ed2kSegmentHash(Stream, I * CSegmentSize, AInfo.Segments[I].SegmentSize, AInfo.Segments[I].SegmentHash);
if not Result then
Exit;
MemStream.WriteBuffer(AInfo.Segments[I].SegmentHash, SizeOf(TMD4Digest));
//AddLogStrToFile(Format('็ฌฌ%dๅHash๏ผ%s',[I,MD4DigestToStr(AInfo.Segments[I].SegmentHash)]));
end;
end
else
begin
AInfo.Segments[I].SegmentSize := ModCount;
if (I =0) or (I = AInfo.SegmentCount - 1) or
(I = ((AInfo.SegmentCount - 1) div 2)) then
begin
Result := ed2kSegmentHash(Stream, I * CSegmentSize, AInfo.Segments[I].SegmentSize, AInfo.Segments[I].SegmentHash);
if not Result then
Exit;
MemStream.WriteBuffer(AInfo.Segments[I].SegmentHash, SizeOf(TMD4Digest));
//AddLogStrToFile(Format('็ฌฌ%dๅHash๏ผ%s',[I,MD4DigestToStr(AInfo.Segments[I].SegmentHash)]));
end;
end;
end;
Result := MD4Stream(MemStream,WebHash);
//AddLogStrToFile(Format('WebHash๏ผ%s',[MD4DigestToStr(WebHash)]));
finally
Stream.Free;
MemStream.free;
end;
end;
function ed2kSegmentHash(const Stream: TStream; AStartPos: Int64; ALen: Int64; var ASegmentHash: TMD4Digest;
PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean;
var
ReadBytes: Integer;
LeftBytes: Integer;
Context: TMD4Context;
SavePos: Int64;
Buffer: array[0..16383] of Byte;
begin
Result := False;
SavePos := Stream.Position;
if (Stream = nil) or (ALen <= 0) then
Exit;
try
LeftBytes := ALen;
ZeroMemory(@ASegmentHash, SizeOf(TMD4Digest));
MD4Init(Context);
Stream.Seek(AStartPos, soFromBeginning);
repeat
if LeftBytes >= SizeOf(Buffer) then
ReadBytes := Stream.Read(Buffer, SizeOf(Buffer))
else
ReadBytes := Stream.Read(Buffer, LeftBytes);
LeftBytes := LeftBytes - ReadBytes;
MD4Update(Context, Buffer, ReadBytes);
if (PAbort <> nil) and PAbort^ then //ๆฏๅฆๅๆญข่ฎก็ฎ
begin
Exit;
end;
if (not AFastCalc) then
begin
if GetCurrentThreadID = MainThreadID then
Application.ProcessMessages;
Sleep(3);
end;
until (ReadBytes = 0) or (LeftBytes <= 0);
MD4Final(Context, ASegmentHash);
Result := True;
finally
Stream.Seek(SavePos, soFromBeginning);
end;
end;
function ed2kStream(const Stream: TStream; var Digest: TMD4Digest;
ASegmentHash: PChar; PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean;
type
TSegment = record
SegmentID: Integer; //ไป0ๅผๅง
SegmentSize: Int64;
SegmentHash: TMD4Digest;
end;
TFileSegmentInfo = record
FileSize: Int64;
SegmentSize: Int64;
SegmentCount: Integer;
Segments: array of TSegment;
end;
const
CSegmentSize = 9728000;
var
MemStream: TMemoryStream;
AInfo: TFileSegmentInfo;
I: Integer;
ModCount: Integer;
Buffer: array[0..16383] of Byte;
SavePos: Int64;
function CalcHash(ASegmentID: Integer; var ASegmentHash: TMD4Digest): Boolean;
var
ReadBytes: Integer;
LeftBytes: Integer;
Context: TMD4Context;
begin
Result := True;
if (Stream = nil) or (ASegmentID < 0) or (ASegmentID >= AInfo.SegmentCount) then
Exit;
LeftBytes := AInfo.Segments[ASegmentID].SegmentSize;
ZeroMemory(@ASegmentHash, SizeOf(TMD4Digest));
MD4Init(Context);
Stream.Seek(ASegmentID * AInfo.SegmentSize, soFromBeginning);
repeat
if LeftBytes >= SizeOf(Buffer) then
ReadBytes := Stream.Read(Buffer, SizeOf(Buffer))
else
ReadBytes := Stream.Read(Buffer, LeftBytes);
LeftBytes := LeftBytes - ReadBytes;
MD4Update(Context, Buffer, ReadBytes);
if (PAbort <> nil) and PAbort^ then //ๆฏๅฆๅๆญข่ฎก็ฎ
begin
Result := False;
Exit;
end;
if (not AFastCalc) then
begin
if GetCurrentThreadID = MainThreadID then
Application.ProcessMessages;
Sleep(3);
end;
until (ReadBytes = 0) or (LeftBytes <= 0);
MD4Final(Context, ASegmentHash);
end;
begin
Result := True;
SavePos := Stream.Position;
MemStream := TMemoryStream.Create;
try
AInfo.FileSize := Stream.Size;
ModCount := 0;
AInfo.SegmentSize := CSegmentSize;
if AInfo.FileSize <= CSegmentSize then
begin
AInfo.SegmentCount := 1;
AInfo.SegmentSize := AInfo.FileSize;
end else
begin
AInfo.SegmentSize := CSegmentSize;
ModCount := AInfo.FileSize mod AInfo.SegmentSize;
AInfo.SegmentCount := AInfo.FileSize div AInfo.SegmentSize;
if ModCount > 0 then
Inc(AInfo.SegmentCount);
end;
SetLength(AInfo.Segments, AInfo.SegmentCount);
ZeroMemory(@AInfo.Segments[0], Sizeof(TSegment) * AInfo.SegmentCount);
for I := 0 to AInfo.SegmentCount - 1 do
begin
AInfo.Segments[I].SegmentID := I;
if (I < AInfo.SegmentCount - 1) or (ModCount = 0) then
begin
AInfo.Segments[I].SegmentSize := AInfo.SegmentSize;
Result := CalcHash(I, AInfo.Segments[I].SegmentHash);
if not Result then
Exit;
end
else
begin
AInfo.Segments[I].SegmentSize := ModCount;
Result := CalcHash(I, AInfo.Segments[I].SegmentHash);
if not Result then
Exit;
end;
if (PAbort <> nil) and PAbort^ then //ๆฏๅฆๅๆญข่ฎก็ฎ
begin
Result := False;
Exit;
end;
if (not AFastCalc) then
begin
if GetCurrentThreadID = MainThreadID then
Application.ProcessMessages;
Sleep(3);
end;
MemStream.WriteBuffer(AInfo.Segments[I].SegmentHash, SizeOf(TMD4Digest));
if ASegmentHash <> nil then
Move(AInfo.Segments[I].SegmentHash, ASegmentHash[I * Sizeof(TMD4Digest)], SizeOf(TMD4Digest));
end;
if AInfo.SegmentCount > 1 then
Result := MD4Stream(MemStream, Digest, PAbort, AFastCalc)
else if AInfo.SegmentCount = 1 then
begin
Digest := AInfo.Segments[0].SegmentHash;
Result := True;
end;
finally
Stream.Seek(SavePos, soFromBeginning);
SetLength(AInfo.Segments, 0);
MemStream.Free;
end;
end;
end.
|
{
Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit DataGrabber.FieldInspector;
interface
{ A TField inspector for any given TDataSet descendant. }
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes, System.Actions,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ActnList,
Data.DB,
zObjInspector,
VirtualTrees;
type
TfrmFieldInspector = class(TForm)
{$REGION 'designer controls'}
aclMain : TActionList;
actInspect : TAction;
pnlLeft : TPanel;
pnlRight : TPanel;
splVertical : TSplitter;
{$ENDREGION}
procedure FVSTFieldsGetText(
Sender : TBaseVirtualTree;
Node : PVirtualNode;
Column : TColumnIndex;
TextType : TVSTTextType;
var CellText : string
);
procedure FVSTFieldsFocusChanged(
Sender : TBaseVirtualTree;
Node : PVirtualNode;
Column : TColumnIndex
);
procedure actInspectExecute(Sender: TObject);
private
FDataSet : TDataSet;
FOIField : TzObjectInspector;
FVSTFields : TVirtualStringTree;
function GetDataSet: TDataSet;
procedure SetDataSet(const Value: TDataSet);
protected
procedure UpdateActions; override;
public
constructor Create(
AOwner : TComponent;
ADataSet : TDataSet = nil
); reintroduce; virtual;
procedure UpdateView;
property DataSet : TDataSet
read GetDataSet write SetDataSet;
end;
implementation
{$R *.dfm}
uses
System.Math, System.UITypes,
Spring,
DDuce.Factories.VirtualTrees, DDuce.Factories.zObjInspector,
DDuce.ObjectInspector.zObjectInspector;
{$REGION 'construction and destruction'}
constructor TfrmFieldInspector.Create(AOwner: TComponent; ADataSet: TDataSet);
var
C: TVirtualTreeColumn;
begin
inherited Create(AOwner);
FDataSet := ADataSet;
FOIField := TzObjectInspectorFactory.Create(Self, pnlRight);
FVSTFields := TVirtualStringTreeFactory.CreateGrid(Self, pnlLeft);
// cell in first column is fully selected
FVSTFields.TreeOptions.PaintOptions :=
FVSTFields.TreeOptions.PaintOptions - [toHideSelection];
FVSTFields.TreeOptions.PaintOptions :=
FVSTFields.TreeOptions.PaintOptions + [toPopupMode];
FVSTFields.TreeOptions.SelectionOptions :=
FVSTFields.TreeOptions.SelectionOptions - [toDisableDrawSelection];
FVSTFields.TreeOptions.SelectionOptions :=
FVSTFields.TreeOptions.SelectionOptions + [toAlwaysSelectNode];
FVSTFields.OnGetText := FVSTFieldsGetText;
FVSTFields.OnFocusChanged := FVSTFieldsFocusChanged;
FVSTFields.LineStyle := lsSolid;
FVSTFields.Header.Font.Style := FVSTFields.Header.Font.Style + [fsBold];
// required when using it as a grid
FVSTFields.Indent := 0;
C := FVSTFields.Header.Columns.Add;
C.CaptionAlignment := taCenter;
C.Text := 'Fieldname';
C := FVSTFields.Header.Columns.Add;
C.CaptionAlignment := taCenter;
C.Text := 'Field class';
C.CaptionAlignment := taCenter;
C.Alignment := taCenter;
C.Width := 120;
FVSTFields.Margins.Right := 0;
end;
{$ENDREGION}
{$REGION 'property access methods'}
function TfrmFieldInspector.GetDataSet: TDataSet;
begin
Result := FDataSet;
end;
procedure TfrmFieldInspector.SetDataSet(const Value: TDataSet);
begin
if Value <> DataSet then
begin
FDataSet := Value;
if FDataSet.FieldCount > 0 then
begin
FOIField.Component := DataSet.Fields[0];
end
else
FOIField.Component := nil;
UpdateView;
end;
end;
{$ENDREGION}
{$REGION 'action handlers'}
procedure TfrmFieldInspector.actInspectExecute(Sender: TObject);
begin
InspectObject(FVSTFields);
end;
{$ENDREGION}
{$REGION 'event handlers'}
procedure TfrmFieldInspector.FVSTFieldsFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
begin
FOIField.Component := DataSet.Fields[Node.Index];
FOIField.SelectItem(-1); // this prevents any invalid selection
end;
procedure TfrmFieldInspector.FVSTFieldsGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
begin
if Column = 0 then
CellText := DataSet.Fields[Node.Index].FieldName
else if Column = 1 then
CellText := DataSet.Fields[Node.Index].ClassName;
end;
{$ENDREGION}
{$REGION 'protected methods'}
procedure TfrmFieldInspector.UpdateActions;
begin
inherited UpdateActions;
FOIField.Invalidate;
end;
{$ENDREGION}
{$REGION 'public methods'}
procedure TfrmFieldInspector.UpdateView;
begin
FVSTFields.RootNodeCount := IfThen(Assigned(DataSet), DataSet.FieldCount, 0);
end;
{$ENDREGION}
end.
|
unit bmkg_integration;
{
DEPRECATED:
no update from bmkg data
-----------------------------------
INFO GEMPA dari BMKG
[x] USAGE
with TBMKGIntegration.Create do
begin
Result := SimpleInfo;
Free;
end;
}
{$mode objfpc}{$H+}
interface
uses
common, http_lib, json_lib, logutil_lib,
fpjson, jsonparser,
{$if FPC_FULlVERSION >= 30200}
opensslsockets,
{$endif}
Classes, SysUtils;
type
{ TBMKGIntegration }
TBMKGIntegration = class(TInterfacedObject)
private
FResultCode: integer;
FResultText: string;
public
constructor Create;
destructor Destroy;
property ResultCode: integer read FResultCode;
property ResultText: string read FResultText;
function SimpleInfo: string;
function InfoGempaXML: string;
end;
implementation
const
_BMKG_DATA_URL = 'http://data.bmkg.go.id/data.txt';
_BMKG_INFOGEMPA_URL = 'http://data.bmkg.go.id/autogempa.xml';
var
Response: IHTTPResponse;
{ TBMKGIntegration }
constructor TBMKGIntegration.Create;
begin
end;
destructor TBMKGIntegration.Destroy;
begin
end;
function TBMKGIntegration.SimpleInfo: string;
begin
Result := '';
with THTTPLib.Create(_BMKG_DATA_URL) do
begin
//AddHeader('Cache-Control', 'no-cache');
Response := Get;
FResultCode := Response.ResultCode;
FResultText := Response.ResultText;
if FResultCode = 200 then
begin
Result := FResultText;
end;
Free;
end;
end;
function TBMKGIntegration.InfoGempaXML: string;
begin
Result := '';
with THTTPLib.Create(_BMKG_INFOGEMPA_URL) do
begin
//AddHeader('Cache-Control', 'no-cache');
Response := Get;
FResultCode := Response.ResultCode;
FResultText := Response.ResultText;
if FResultCode = 200 then
begin
Result := FResultText;
end;
Free;
end;
end;
end.
|
unit MainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.ListBox, Maze.Grid, Maze.Cell, FMX.Layouts,
FMX.ExtCtrls, FMX.Edit, Maze.Algorithms;
type
TForm1 = class(TForm)
ToolBar: TToolBar;
btnNew: TSpeedButton;
cmbDistance: TComboBox;
btnPlayStepped: TSpeedButton;
btnPlay: TSpeedButton;
ImageViewer: TImageViewer;
edtCellSize: TEdit;
btnStop: TSpeedButton;
cmbAlgorithm: TComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure btnNewClick(Sender: TObject);
procedure edtCellSizeKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure btnPlaySteppedClick(Sender: TObject);
procedure btnPlayClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure cmbDistanceChange(Sender: TObject);
private
FGrid : IGrid;
FStopPlaying : Boolean;
procedure RecreateGrid;
procedure PaintGrid;
function CellSize: Integer;
procedure DoDijkstra;
function GetMazeGenerationProc: TMazeGenerationProc;
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
System.Math, Maze.DistanceDijkstra;
{ TForm1 }
constructor TForm1.Create(AOwner: TComponent);
begin
inherited;
FStopPlaying := false;
RecreateGrid;
end;
destructor TForm1.Destroy;
begin
inherited;
end;
procedure TForm1.edtCellSizeKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
begin
if Key = vkReturn then begin
RecreateGrid;
PaintGrid;
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
PaintGrid;
end;
procedure TForm1.RecreateGrid;
var
R, C : Integer;
begin
C := Trunc(ImageViewer.Width / CellSize) - 1;
R := Trunc(ImageViewer.Height / CellSize) - 1;
// Limit the small size
C := Max(C, 2);
R := Max(R, 2);
FGrid := CreateGrid(R, C);
end;
function TForm1.CellSize : Integer;
begin
Result := 50;
TryStrToInt(edtCellSize.Text, Result);
end;
procedure TForm1.PaintGrid;
var
CellDistPainting : TCellPainting;
begin
CellDistPainting := TCellPainting(cmbDistance.ItemIndex);
ImageViewer.Bitmap.Assign(FGrid.Repaint(CellSize, CellDistPainting));
Invalidate;
end;
procedure TForm1.btnNewClick(Sender: TObject);
begin
RecreateGrid;
PaintGrid;
end;
function TForm1.GetMazeGenerationProc : TMazeGenerationProc;
begin
Result := nil;
case cmbAlgorithm.ItemIndex of
0 : Result := BinaryTree;
1 : Result := AldousBroder;
2 : Result := RecursiveBacktracker;
end;
end;
procedure TForm1.btnPlayClick(Sender: TObject);
var
MazeGenProc : TMazeGenerationProc;
begin
MazeGenProc := GetMazeGenerationProc();
MazeGenProc(FGrid);
DoDijkstra;
PaintGrid;
end;
function ShouldStopPlaying : Boolean;
begin
Result := Form1.FStopPlaying;
Form1.FStopPlaying := false; // Once checked once
end;
procedure TForm1.DoDijkstra;
begin
case TCellPainting(cmbDistance.ItemIndex) of
//cdNone : ClearCellDistances;
cdDistance, cdColour : CalcDijkstraDistance(FGrid);
cdSolution : CalcDijkstraSolve(FGrid);
end;
end;
procedure TForm1.btnPlaySteppedClick(Sender: TObject);
var
MazeGenProc : TMazeGenerationProc;
PauseTimeMs : Integer;
begin
btnStop.Enabled := true;
btnPlayStepped.Enabled := false;
btnPlay.Enabled := false;
MazeGenProc := GetMazeGenerationProc();
PauseTimeMs := 10000 div FGrid.NumCells;
// PauseTimeMs := 50; // For slow ones, eg Aldous-Broder
PauseTimeMs := Max(PauseTimeMs, 1);
MazeGenProc(FGrid, procedure
var
Pause : Boolean;
begin
Pause := true;
// If very short sleep, don't sleep every time
if PauseTimeMs < 50 then
Pause := Random(50 div PauseTimeMs) = 0;
if Pause then begin
PaintGrid;
Application.ProcessMessages; // Ugh
Sleep(PauseTimeMs);
end;
end,
ShouldStopPlaying);
DoDijkstra;
PaintGrid;
btnStop.Enabled := false;
btnPlayStepped.Enabled := true;
btnPlay.Enabled := true;
end;
procedure TForm1.btnStopClick(Sender: TObject);
begin
FStopPlaying := true;
end;
procedure TForm1.cmbDistanceChange(Sender: TObject);
begin
DoDijkstra;
PaintGrid;
end;
end.
|
unit BIFFRecsII;
{
********************************************************************************
******* XLSReadWriteII V1.14 *******
******* *******
******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
interface
const MAXCOL = 256;
const MAXROW = 65536;
const MAXRECSZ_40 = 2080;
const MAXRECSZ_97 = 8224;
const DEFAULT_FORMAT = 15;
const DEFAULT_FORMATS_COUNT_50 = 16;
const DEFAULT_FORMATS_COUNT_97 = 21;
const DEFAULT_FORMAT40 = 20;
const BIFFRECID_INTEGER_20 = $0002;
const BIFFRECID_NUMBER_20 = $0003;
const BIFFRECID_LABEL_20 = $0004;
const BIFFRECID_STRING_20 = $0007;
const BIFFRECID_1904 = $0022;
const BIFFRECID_ARRAY = $0221;
const BIFFRECID_BACKUP = $0040;
const BIFFRECID_BLANK = $0201;
const BIFFRECID_BOF = $0009;
const BIFFRECID_BOOKBOOL = $00DA;
const BIFFRECID_BOOLERR = $0205;
const BIFFRECID_BOTTOMMARGIN = $0029;
const BIFFRECID_BOUNDSHEET = $0085;
const BIFFRECID_CALCMODE = $000D;
const BIFFRECID_CALCCOUNT = $000C;
//const BIFFRECID_CODENAME = $00??;
const BIFFRECID_CODENAME_VBE = $0042;
const BIFFRECID_CODEPAGE = $0042;
const BIFFRECID_COLINFO = $007D;
const BIFFRECID_CONTINUE = $003C;
const BIFFRECID_COUNTRY = $008C;
const BIFFRECID_CRN = $005A;
const BIFFRECID_DBCELL = $00D7;
const BIFFRECID_DCONREF = $0051;
const BIFFRECID_DEFAULTROWHEIGHT = $0225;
const BIFFRECID_DEFCOLWIDTH = $0055;
const BIFFRECID_DELTA = $0010;
const BIFFRECID_DIMENSIONS_20 = $0000;
const BIFFRECID_DIMENSIONS = $0200;
const BIFFRECID_DSF = $0161;
const BIFFRECID_DV = $01BE;
const BIFFRECID_DVAL = $01B2;
const BIFFRECID_EOF = $000A;
const BIFFRECID_EXCEL9FILE = $01C0;
const BIFFRECID_EXTERNCOUNT = $0016;
const BIFFRECID_EXTERNNAME = $0023;
const BIFFRECID_EXTERNSHEET = $0017;
const BIFFRECID_EXTSST = $00FF;
const BIFFRECID_FILESHARING = $005B;
const BIFFRECID_FILEPASS = $002F;
const BIFFRECID_FNGROUPCOUNT = $009C;
const BIFFRECID_FONT = $0031;
const BIFFRECID_FOOTER = $0015;
const BIFFRECID_FORMAT = $041E;
const BIFFRECID_FORMULA = $0006;
const BIFFRECID_FORMULA_30 = $0206;
const BIFFRECID_FORMULA_40 = $0406;
const BIFFRECID_GRIDSET = $0082;
const BIFFRECID_GUTS = $0080;
const BIFFRECID_HCENTER = $0083;
const BIFFRECID_HEADER = $0014;
const BIFFRECID_HIDEOBJ = $008D;
const BIFFRECID_HLINK = $01B8;
const BIFFRECID_HORIZONTALPAGEBREAKS = $001B;
const BIFFRECID_INDEX = $020B;
const BIFFRECID_INTERFACEHDR = $00E1;
const BIFFRECID_INTERFACEEND = $00E2;
const BIFFRECID_ITERATION = $0011;
const BIFFRECID_LABEL = $0204;
const BIFFRECID_LABELSST = $00FD;
const BIFFRECID_LEFTMARGIN = $0026;
const BIFFRECID_MERGEDCELLS = $00E5;
const BIFFRECID_MSODRAWING = $00EC;
const BIFFRECID_MSODRAWINGGROUP = $00EB;
const BIFFRECID_MSODRAWINGSELECTION=$00ED;
const BIFFRECID_MULRK = $00BD;
const BIFFRECID_MULBLANK = $00BE;
const BIFFRECID_NAME = $0018;
const BIFFRECID_NOTE = $001C;
const BIFFRECID_NUMBER = $0203;
const BIFFRECID_OBJ = $005D;
const BIFFRECID_OBPROJ = $00D3;
const BIFFRECID_PALETTE = $0092;
const BIFFRECID_PANE = $0041;
const BIFFRECID_PASSWORD = $0013;
const BIFFRECID_PRECISION = $000E;
const BIFFRECID_PRINTGRIDLINES = $002B;
const BIFFRECID_PRINTHEADERS = $002A;
const BIFFRECID_PROT4REV = $01AF;
const BIFFRECID_PROT4REVPASS = $01BC;
const BIFFRECID_PROTECT = $0012;
const BIFFRECID_RECALCID = $01C1;
const BIFFRECID_REFRESHALL = $01B7;
const BIFFRECID_REFMODE = $000F;
const BIFFRECID_RIGHTMARGIN = $0027;
const BIFFRECID_RK = $007E;
const BIFFRECID_RK7 = $027E;
const BIFFRECID_PLS = $004D;
const BIFFRECID_ROW = $0208;
const BIFFRECID_RSTRING = $00D6;
const BIFFRECID_SAVERECALC = $005F;
const BIFFRECID_SCL = $00A0;
const BIFFRECID_SELECTION = $001D;
const BIFFRECID_SETUP = $00A1;
const BIFFRECID_SHRFMLA = $00BC;
const BIFFRECID_SHRFMLA_20 = $04BC;
const BIFFRECID_SST = $00FC;
const BIFFRECID_STRING = $0207;
const BIFFRECID_STYLE = $0293;
const BIFFRECID_SUPBOOK = $01AE;
const BIFFRECID_SXIDSTM = $00D5;
const BIFFRECID_SXVS = $00E3;
const BIFFRECID_TABID = $013D;
const BIFFRECID_TOPMARGIN = $0028;
const BIFFRECID_TXO = $01B6;
const BIFFRECID_UNCALCED = $005E;
const BIFFRECID_USESELFS = $0160;
const BIFFRECID_VCENTER = $0084;
const BIFFRECID_VERTICALPAGEBREAKS =$001A;
const BIFFRECID_WINDOW1 = $003D;
const BIFFRECID_WINDOW2 = $023E;
const BIFFRECID_WINDOWPROTECT = $0019;
const BIFFRECID_WRITEACCESS = $005C;
const BIFFRECID_WSBOOL = $0081;
const BIFFRECID_XCTCRN = $0059;
const BIFFRECID_XF = $00E0;
const BIFFRECID_XF_30 = $0243;
const BIFFRECID_XF_40 = $0443;
const CHARTRECID_3D = $103A;
const CHARTRECID_AI = $1051;
const CHARTRECID_ALRUNS = $1050;
const CHARTRECID_AREA = $101A;
const CHARTRECID_AREAFORMAT = $100A;
const CHARTRECID_ATTACHEDLABEL = $100C;
const CHARTRECID_AXCEXT = $1062;
const CHARTRECID_AXESUSED = $1046;
const CHARTRECID_AXIS = $101D;
const CHARTRECID_AXISLINEFORMAT = $1021;
const CHARTRECID_AXISPARENT = $1041;
const CHARTRECID_BAR = $1017;
const CHARTRECID_BEGIN = $1033;
const CHARTRECID_BOPPOP = $1061;
const CHARTRECID_BOPPOPCUSTOM = $1067;
const CHARTRECID_CATSERRANGE = $1020;
const CHARTRECID_CHART = $1002;
const CHARTRECID_CHARTFORMAT = $1014;
const CHARTRECID_CHARTFORMATLINK = $1022;
const CHARTRECID_CHARTLINE = $101C;
const CHARTRECID_DAT = $1063;
const CHARTRECID_DATAFORMAT = $1006;
const CHARTRECID_DEFAULTTEXT = $1024;
const CHARTRECID_DROPBAR = $103D;
const CHARTRECID_END = $1034;
const CHARTRECID_FBI = $1060;
const CHARTRECID_FONTX = $1026;
const CHARTRECID_FRAME = $1032;
const CHARTRECID_GELFRAME = $1066;
const CHARTRECID_IFMT = $104E;
const CHARTRECID_LEGEND = $1015;
const CHARTRECID_LEGENDXN = $1043;
const CHARTRECID_LINE = $1018;
const CHARTRECID_LINEFORMAT = $1007;
const CHARTRECID_MARKERFORMAT = $1009;
const CHARTRECID_OBJECTLINK = $1027;
const CHARTRECID_PICF = $103C;
const CHARTRECID_PIE = $1019;
const CHARTRECID_PIEFORMAT = $100B;
const CHARTRECID_PLOTAREA = $1035;
const CHARTRECID_PLOTGROWTH = $1064;
const CHARTRECID_POS = $104F;
const CHARTRECID_RADAR = $103E;
const CHARTRECID_RADARAREA = $1040;
const CHARTRECID_SBASEREF = $1048;
const CHARTRECID_SCATTER = $101B;
const CHARTRECID_SERAUXERRBAR = $105B;
const CHARTRECID_SERAUXTREND = $104B;
const CHARTRECID_SERFMT = $105D;
const CHARTRECID_SERIES = $1003;
const CHARTRECID_SERIESLIST = $1016;
const CHARTRECID_SERIESTEXT = $100D;
const CHARTRECID_SERPARENT = $104A;
const CHARTRECID_SERTOCRT = $1045;
const CHARTRECID_SHTPROPS = $1044;
const CHARTRECID_SIINDEX = $1065;
const CHARTRECID_SURFACE = $103F;
const CHARTRECID_TEXT = $1025;
const CHARTRECID_TICK = $101E;
const CHARTRECID_UNITS = $1001;
const CHARTRECID_VALUERANGE = $101F;
Const OBJ_END = $00;
Const OBJ_MACRO = $04;
Const OBJ_BUTTON = $05;
Const OBJ_GMO = $06;
Const OBJ_CF = $07;
Const OBJ_PIOGRBIT = $08;
Const OBJ_PICTFMLA = $09;
Const OBJ_CBLS = $0A;
Const OBJ_RBO = $0B;
Const OBJ_SBS = $0C;
Const OBJ_NTS = $0D;
Const OBJ_SBSFMLA = $0E;
Const OBJ_GBODATA = $0F;
Const OBJ_EDODATA = $10;
Const OBJ_RBODATA = $11;
Const OBJ_CBLSDATA = $12;
Const OBJ_LBSDATA = $13;
Const OBJ_CBLSFMLA = $14;
Const OBJ_CMO = $15;
const
ptgExp = $01;
ptgTbl = $02;
ptgAdd = $03;
ptgSub = $04;
ptgMul = $05;
ptgDiv = $06;
ptgPower = $07;
ptgConcat = $08;
ptgLT = $09;
ptgLE = $0A;
ptgEQ = $0B;
ptgGE = $0C;
ptgGT = $0D;
ptgNE = $0E;
ptgIsect = $0F;
ptgUnion = $10;
ptgRange = $11;
ptgUplus = $12;
ptgUminus = $13;
ptgPercent = $14;
ptgParen = $15;
ptgMissArg = $16;
ptgStr = $17;
ptgAttr = $19;
ptgSheet = $1A;
ptgEndSheet = $1B;
ptgErr = $1C;
ptgBool = $1D;
ptgInt = $1E;
ptgNum = $1F;
ptgArray = $20;
ptgFunc = $21;
ptgFuncVar = $22;
ptgName = $23;
ptgRef = $24;
ptgArea = $25;
ptgMemArea = $26;
ptgMemErr = $27;
ptgMemNoMem = $28;
ptgMemFunc = $29;
ptgRefErr = $2A;
ptgAreaErr = $2B;
ptgRefN = $2C;
ptgAreaN = $2D;
ptgMemAreaN = $2E;
ptgMemNoMemN = $2F;
ptgNameX = $39;
ptgRef3d = $3A;
ptgArea3d = $3B;
ptgRefErr3d = $3C;
ptgAreaErr3d = $3D;
ptgArrayV = $40;
ptgFuncV = $41;
ptgFuncVarV = $42;
ptgNameV = $43;
ptgRefV = $44;
ptgAreaV = $45;
ptgMemAreaV = $46;
ptgMemErrV = $47;
ptgMemNoMemV = $48;
ptgMemFuncV = $49;
ptgRefErrV = $4A;
ptgAreaErrV = $4B;
ptgRefNV = $4C;
ptgAreaNV = $4D;
ptgMemAreaNV = $4E;
ptgMemNoMemNV = $4F;
ptgFuncCEV = $58;
ptgNameXV = $59;
ptgRef3dV = $5A;
ptgArea3dV = $5B;
ptgRefErr3dV = $5C;
ptgAreaErr3dV = $5D;
ptgArrayA = $60;
ptgFuncA = $61;
ptgFuncVarA = $62;
ptgNameA = $63;
ptgRefA = $64;
ptgAreaA = $65;
ptgMemAreaA = $66;
ptgMemErrA = $67;
ptgMemNoMemA = $68;
ptgMemFuncA = $69;
ptgRefErrA = $6A;
ptgAreaErrA = $6B;
ptgRefNA = $6C;
ptgAreaNA = $6D;
ptgMemAreaNA = $6E;
ptgMemNoMemNA = $6F;
ptgFuncCEA = $78;
ptgNameXA = $79;
ptgRef3dA = $7A;
ptgArea3dA = $7B;
ptgRefErr3dA = $7C;
ptgAreaErr3dA = $7D;
const CellErrorNames: array[0..7] of string =
('[int] No error value','#NULL!','#DIV/0!','#VALUE!','#REF!','#NAME?','#NUM!','N/A');
const ERR_NULL = 1;
const ERR_DIV = 2;
const ERR_VALUE = 3;
const ERR_REF = 4;
const ERR_NAME = 5;
const ERR_NUM = 6;
const ERR_NA = 7;
// errError = internal, there is no defined error value.
type TCellError = (errError,errNull,errDiv0,errValue,errRef,errName,errNum,errNA);
type TExcelColor = (xc0,xc1,xc2,xc3,xc4,xc5,xc6,xc7,
xcBlack,xcWhite,xcRed,xcBrightGreen,xcBlue,xcYellow,xcPink,xcTurquoise,
xcDarkRed,xcGreen,xcDarkBlue,xcBrownGreen,xcViolet,xcBlueGreen,xcGrey25,xcGrey50,
xc24,xc25,xc26,xc27,xc28,xc29,xc30,xc31,
xc32,xc33,xc34,xc35,xc36,xc37,xc38,xc39,
xcSky,xcPaleTurquois,xcPaleGreen,xcLightYellow,xcPaleSky,xcRose,xcLilac,xcLightBrown,
xcDarkSky,xcDarkTurquois,xcGrass,xcGold,xcLightOrange,xcOrange,xcDarkBlueGrey,xcGrey40,
xcDarkGreenGrey,xcEmerald,xcDarkGreen,xcOlive,xcBrown,xcCherry,xcIndigo,xcGrey80,xcAutomatic);
const TDefaultExcelColorPalette: array[0..64] of integer = (
$000000,$000000,$000000,$000000,$000000,$000000,$000000,$000000,
$000000,$FFFFFE,$0004FF,$00FF00,$FF0400,$00FFFF,$FF04FF,$FFFF00,
$000484,$008600,$840400,$008684,$840484,$848600,$C6C7C6,$848684,
$FF9694,$633494,$C6FFFF,$FFFFC6,$630463,$8486FF,$C66500,$FFC7C6,
$840400,$FF04FF,$00FFFF,$FFFF00,$840484,$000484,$848600,$FF0400,
$FFC700,$FFFFC6,$C6FFC6,$94FFFF,$FFCF94,$C696FF,$FF96C6,$94CFFF,
$FF6531,$C6C731,$00C794,$00C7FF,$0096FF,$0065FF,$946563,$949694,
$633400,$639631,$003400,$003431,$003494,$633494,$943431,$313431,
$FFFFFF);
var TExcelColorPalette: array[0..High(TDefaultExcelColorPalette)] of integer;
type TSubStreamType = (stGlobals,stVBModule,stWorksheet,stChart,stExcel4Macro,stWorkspace);
type TWordBit = (b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15);
type TWordBits = set of TWordBit;
type TExcelVersion = (xvNone,xvExcelUnknown,xvExcel21,xvExcel30,xvExcel40,xvExcel50,xvExcel97);
{
type T2ByteWord = packed record
case word of
0: (W: word);
1: (B: array[0..1] of byte);
end;
}
// ****** For OBJ records. ******
const OBJREC_END = $00;
const OBJREC_CF = $07;
const OBJREC_PIOGRBIT = $08;
const OBJREC_NTS = $0D;
const OBJREC_CMO = $15;
type TPageBreak = packed record
Val1: word;
Val2: word;
Val3: word;
end;
type PRecTXORUN = ^TRecTXORUN;
TRecTXORUN = packed record
CharIndex: word;
FontIndex: word;
Reserved: longword;
end;
type PObjCMO = ^TObjCMO;
TObjCMO = packed record
ObjType: word;
ObjId: word;
Options: word;
Reserved: array[0..11] of byte;
end;
// ********** BIFF Records *******
type PFormatRun = ^TFormatRun;
TFormatRun = packed record
Index: word;
FontIndex: word;
end;
type PBIFFHeader = ^TBIFFHeader;
TBIFFHeader = packed record
RecID: word;
Length: word;
end;
type PRec2INTEGER = ^TRec2INTEGER;
TRec2INTEGER = packed record
Row: word;
Col: byte;
Res: byte;
Attribute: array[0..2] of byte;
Value: word;
end;
type PRec2NUMBER = ^TRec2NUMBER;
TRec2NUMBER = packed record
Row: word;
Col: byte;
Res: byte;
Attribute: array[0..2] of byte;
Value: double;
end;
type PRec2LABEL = ^TRec2LABEL;
TRec2LABEL = packed record
Row: word;
Col: byte;
Res: byte;
Attribute: array[0..2] of byte;
Len: byte;
Data: array[0..255] of byte;
end;
type PRec2FORMULA = ^TRec2FORMULA;
TRec2FORMULA = packed record
Row: word;
Col: byte;
Res: byte;
Attribute: array[0..2] of byte;
Value: double;
Options: byte;
ParseLen: byte;
Data: array[0..255] of byte;
end;
type PRec2STRING = ^TRec2STRING;
TRec2STRING = packed record
Len: byte;
Data: array[0..255] of byte;
end;
type PRecBLANK = ^TRecBLANK;
TRecBLANK = packed record
Row: word;
Col: word;
FormatIndex: word;
end;
type PRecBOF8 = ^TRecBOF8;
TRecBOF8 = packed record
VersionNumber: word;
SubstreamType: word;
BuildIdentifier: word;
BuildYear: word;
FileHistoryFlags: longint;
LowBIFF: longint;
end;
type PRecBOF7 = ^TRecBOF7;
TRecBOF7 = packed record
VersionNumber: word;
SubstreamType: word;
BuildIdentifier: word;
BuildYear: word;
end;
type PRecBOF4 = ^TRecBOF4;
TRecBOF4 = packed record
A: word; // Don't know what this is.
B: word; //
C: word; //
end;
type PRecBOOLERR = ^TRecBOOLERR;
TRecBOOLERR = packed record
Row: word;
Col: word;
FormatIndex: word;
BoolErr: byte;
Error: byte;
end;
type PRecBOUNDSHEET7 = ^TRecBOUNDSHEET7;
TRecBOUNDSHEET7 = packed record
BOFPos: longint;
Options: word;
NameLen: byte;
Name: array[0..255] of byte;
end;
type PRecBOUNDSHEET8 = ^TRecBOUNDSHEET8;
TRecBOUNDSHEET8 = packed record
BOFPos: longint;
Options: word;
NameLen: byte;
Name: array[0..65535] of byte;
end;
type PRecCODEPAGE = ^TRecCODEPAGE;
TRecCODEPAGE = packed record
Codepage: word;
end;
type PRecCOLINFO = ^TRecCOLINFO;
TRecCOLINFO = packed record
Col1,Col2: word;
Width: word;
FormatIndex: word;
Options: word;
Reserved: word;
end;
type PRecCOUNTRY = ^TRecCOUNTRY;
TRecCOUNTRY = packed record
DefaultCountryIndex: word;
WinIniCountry: word;
end;
type PRecDEFAULTROWHEIGHT = ^TRecDEFAULTROWHEIGHT;
TRecDEFAULTROWHEIGHT = packed record
Options: word;
Height: word;
end;
type PRecDBCELL = ^TRecDBCELL;
TRecDBCELL = packed record
RowOffset: longint;
Offsets: array[0..32768] of smallint;
end;
type PRecDIMENSIONS2 = ^TRecDIMENSIONS2;
TRecDIMENSIONS2 = packed record
FirstRow,LastRow: word;
FirstCol,LastCol: word;
end;
type PRecDIMENSIONS7 = ^TRecDIMENSIONS7;
TRecDIMENSIONS7 = packed record
FirstRow,LastRow: word;
FirstCol,LastCol: word;
Reserved: word;
end;
type PRecDIMENSIONS8 = ^TRecDIMENSIONS8;
TRecDIMENSIONS8 = packed record
FirstRow,LastRow: longint;
FirstCol,LastCol: word;
Reserved: word;
end;
type PRecDVAL = ^TRecDVAL;
TRecDVAL = packed record
Options: word;
X,Y: longword;
DropDownId: longword;
DVCount: longword;
end;
type TRecISSTINF = packed record
Pos: longint;
Offset: word;
Reserved: word;
end;
type PRecEXTSST = ^TRecEXTSST;
TRecEXTSST = packed record
Count: word;
ISSTINF: array[0..32768] of TRecISSTINF;
end;
type PRecEXTERNNAME8 = ^TRecEXTERNNAME8;
TRecEXTERNNAME8 = packed record
Options: word;
Reserved: longint;
LenName: byte;
Data: array[0..65535] of byte;
end;
type PRecEXTERNNAME5 = ^TRecEXTERNNAME5;
TRecEXTERNNAME5 = packed record
Options: word;
Reserved: longint;
NameLen: byte;
Name: array[0..255] of byte;
end;
type PRecEXTERNNAME3 = ^TRecEXTERNNAME3;
TRecEXTERNNAME3 = packed record
Options: word;
NameLen: byte;
Name: array[0..255] of byte;
end;
type PRecEXTERNSHEET7 = ^TRecEXTERNSHEET7;
TRecEXTERNSHEET7 = packed record
Len: byte;
Data: array[0..255] of byte;
end;
type TXTI = packed record
SupBook: word;
FirstTab: word;
LastTab: word;
end;
type PRecEXTERNSHEET8 = ^TRecEXTERNSHEET8;
TRecEXTERNSHEET8 = packed record
XTICount: word;
XTI: array[0..255] of TXTI;
end;
type PRecFILESHARING = ^TRecFILESHARING;
TRecFILESHARING = packed record
ReadOnly: word;
Encrypted: word;
LenUsername: byte;
Dummy: byte;
end;
type PRecFONT30 = ^TRecFONT30;
TRecFONT30 = packed record
Height: word;
Attributes: word;
ColorIndex: word;
NameLen: byte;
Name: array[0..255] of byte;
end;
type PRecFONT = ^TRecFONT;
TRecFONT = packed record
Height: word;
Attributes: word;
ColorIndex: word;
Bold: word;
SubSuperScript: word;
Underline: byte;
Family: byte;
CharSet: byte;
Reserved: byte;
NameLen: byte;
Name: array[0..255] of byte;
end;
type PRecFORMAT = ^TRecFORMAT;
TRecFORMAT = packed record
Index: word;
Len: byte;
Data: array[0..255] of byte;
end;
type PRecFORMAT97 = ^TRecFORMAT97;
TRecFORMAT97 = packed record
Index: word;
Len: word;
Data: array[0..$FFFF] of byte;
end;
type PRecFORMAT2 = ^TRecFORMAT2;
TRecFORMAT2 = packed record
Len: byte;
Data: array[0..255] of byte;
end;
type PRecFORMULA = ^TRecFORMULA;
TRecFORMULA = packed record
Row,Col: word;
FormatIndex: word;
Value: double;
Options: word;
Reserved: longint;
ParseLen: word;
Data: array[0..High(word)] of byte;
end;
type TRecFORMULA_ = packed record
Row,Col: word;
FormatIndex: word;
Value: double;
Options: word;
Reserved: longint;
ParseLen: word;
end;
type PRecFORMULA3 = ^TRecFORMULA3;
TRecFORMULA3 = packed record
Row,Col: word;
FormatIndex: word;
Value: double;
Options: word;
ParseLen: word;
Data: array[0..High(word)] of byte;
end;
type PRecGUTS = ^TRecGUTS;
TRecGUTS = packed record
SizeRow: word;
SizeCol: word;
LevelRow: word;
LevelCol: word;
end;
type PRecHLINK = ^TRecHLINK;
TRecHLINK = packed record
Row1,Row2: word;
Col1,Col2: word;
D1,D2: double;
Options1: longint;
Options2: longint;
end;
type PRecHORIZONTALPAGEBREAKS = ^TRecHORIZONTALPAGEBREAKS;
TRecHORIZONTALPAGEBREAKS = packed record
Count: word;
Breaks: array[0..1024] of TPageBreak;
end;
type PRecINDEX7 = ^TRecINDEX7;
TRecINDEX7 = packed record
Reserved1: longint;
Row1: word;
Row2: word;
Reserved2: longint;
Offsets: array[0..(High(integer) div 4) - 4] of integer;
end;
type PRecINDEX8 = ^TRecINDEX8;
TRecINDEX8 = packed record
Reserved1: longint;
Row1: longint;
Row2: longint;
Reserved2: longint;
Offsets: array[0..(High(integer) div 4) - 40] of integer;
end;
type PRecLABELSST = ^TRecLABELSST;
TRecLABELSST = packed record
Row,Col: word;
FormatIndex: word;
SSTIndex: longint;
end;
type PRecLABEL = ^TRecLABEL;
TRecLABEL = packed record
Row,Col: word;
FormatIndex: word;
Len: word; // String lengths may not exceed 255 bytes.
Data: array[0..255] of byte;
end;
// Left, Right, Top, Bottom margins
type PRecMARGIN = ^TRecMARGIN;
TRecMARGIN = packed record
Value: double;
end;
type TCellRect = packed record
Row1,Row2: word;
Col1,Col2: word;
end;
type PRecMERGEDCELLS = ^TRecMERGEDCELLS;
TRecMERGEDCELLS = packed record
Count: word;
Cells: array[0..8191] of TCellRect;
end;
type PRecMULBLANK = ^TRecMULBLANK;
TRecMULBLANK = packed record
Row: word;
Col1: word;
FormatIndexes: array[0..65535] of word;
end;
type TMULRK = packed record
FormatIndex: word;
Value: longint;
end;
type PRecMULRK = ^TRecMULRK;
TRecMULRK = packed record
Row: word;
Col1: word;
RKs: array[0..65535] of TMulRK;
end;
type PRecNUMBER = ^TRecNUMBER;
TRecNUMBER = packed record
Row,Col: word;
FormatIndex: word;
Value: double;
end;
type PRecNAME = ^TRecNAME;
TRecNAME = packed record
Options: word;
KeyShortcut: byte;
LenName: byte;
LenNameDef: word;
SheetIndex: word;
TabIndex: word;
LenCustMenu: byte;
LenDescText: byte;
LenHelpText: byte;
LenStatusText: byte;
Data: array[0..255] of byte;
end;
type PRecNAME3 = ^TRecNAME3;
TRecNAME3 = packed record
Options: word;
Res1: byte;
LenName: byte;
Res2: word;
Data: array[0..255] of byte;
end;
type PRecNOTE = ^TRecNOTE;
TRecNOTE = packed record
Row: word;
Col: word;
Options: word;
ObjId: word;
AuthorNameLen: word;
end;
// Only first subrecord OBJ record.
type PRecOBJ = ^TRecOBJ;
TRecOBJ = packed record
RecId: word;
Length: word;
ObjType: word;
ObjId: word;
Options: word;
Reserved: array[0..11] of byte;
end;
type PRecPALETTE = ^TRecPALETTE;
TRecPALETTE = packed record
Count: word;
Color: array[0..65535] of longint;
end;
type PRecPANE = ^TRecPANE;
TRecPANE = packed record
X,Y: word;
TopRow: word;
LeftCol: word;
PaneNumber: word;
end;
type PRecRECALCID = ^TRecRECALCID;
TRecRECALCID = packed record
RecordIdRepeated: word;
Reserved: word;
RecalcEngineId: longword;
end;
type PRecROW = ^TRecROW;
TRecROW = packed record
Row: word;
Col1,Col2: word;
Height: word;
Reserved1,Reserved2: word;
Options: word;
FormatIndex: word;
end;
type TRK = packed record
case integer of
0: (V: double);
1: (DW: array [0..1] of longint);
end;
type PRecRK = ^TRecRK;
TRecRK = packed record
Row,Col: word;
FormatIndex: word;
Value: longint;
end;
type PRecRSTRING = ^TRecRSTRING;
TRecRSTRING = packed record
Row,Col: word;
FormatIndex: word;
Len: word;
Data: array[0..65535] of byte;
end;
type PRecSCL = ^TRecSCL;
TRecSCL = packed record
Numerator: word;
Denominator: word;
end;
type PRecSELECTION = ^TRecSELECTION;
TRecSELECTION = packed record
Pane: byte;
ActiveRow: word;
ActiveCol: word;
ActiveRef: word;
Refs: word;
Row1,Row2: word;
Col1,Col2:byte
end;
type PRecSETUP = ^TRecSETUP;
TRecSETUP = packed record
PaperSize: word;
Scale: word;
PageStart: word;
FitWidth: word;
FitHeight: word;
Options: word;
Resolution: word;
VertResolution: word;
HeaderMargin: double;
FooterMargin: double;
Copies: word;
end;
type PRecSHRFMLA = ^TRecSHRFMLA;
TRecSHRFMLA = packed record
Row1,Row2: word;
Col1,Col2: byte;
Reserved: word;
ParseLen: word;
Data: array[0..65535] of byte;
end;
type PRecSST = ^TRecSST;
TRecSST = packed record
Total: longword;
Unique: longword;
Data: array[0..MAXINT div 2] of byte;
end;
type PRecSTRING = ^TRecSTRING;
TRecSTRING = packed record
Len: word;
Data: array[0..65535] of byte;
end;
type PRecSTRING1Byte = ^TRecSTRING1Byte;
TRecSTRING1Byte = packed record
Len: byte;
Data: array[0..255] of byte;
end;
type PRecSTYLE = ^TRecSTYLE;
TRecSTYLE = packed record
FormatIndex: word;
BuiltInStyle: byte;
Level: byte;
end;
type PRecSUPBOOK = ^TRecSUPBOOK;
TRecSUPBOOK = packed record
Tabs: word;
Data: array[0..65535] of byte;
end;
type PRecTXO = ^TRecTXO;
TRecTXO = packed record
Options: word;
Orientation: word;
Reserved: array[0..5] of byte;
TextLen: word;
FormatLen: word;
Reserved2: array[0..3] of byte;
end;
type PRecVERTICALPAGEBREAKS = ^TRecVERTICALPAGEBREAKS;
TRecVERTICALPAGEBREAKS = packed record
Count: word;
Breaks: array[0..1024] of TPageBreak;
end;
type PRecWINDOW1 = ^TRecWINDOW1;
TRecWINDOW1 = packed record
Left: word;
Top: word;
Width: word;
Height: word;
Options: word;
SelectedTabIndex: word;
FirstDispTabIndex: word;
SelectedTabs: word;
TabRatio: word;
end;
type PRecWINDOW2_7 = ^TRecWINDOW2_7;
TRecWINDOW2_7 = packed record
Options: word;
TopRow: word;
LeftCol: word;
HeaderColorIndex: longint;
end;
type PRecWINDOW2_8 = ^TRecWINDOW2_8;
TRecWINDOW2_8 = packed record
Options: word;
TopRow: word;
LeftCol: word;
HeaderColorIndex: longint;
ZoomPreview: word;
Zoom: word;
Reserved: longint;
end;
type PRecWINDOW2_3 = ^TRecWINDOW2_3;
TRecWINDOW2_3 = packed record
Options: word;
TopRow: word;
LeftCol: word;
Unknown: longint;
end;
type PRecXF3 = ^TRecXF3;
TRecXF3 = packed record
FontIndex: byte;
Data: array[0..10] of byte;
end;
type PRecXF4 = ^TRecXF4;
TRecXF4 = packed record
FontIndex: byte;
FormatIndex: byte;
Data1: word;
Data2: byte;
UsedAttributes: byte;
CellColor: word;
TopBorder: byte;
LeftBorder: byte;
BottomBorder: byte;
RightBorder: byte;
end;
type PRecXF7 = ^TRecXF7;
TRecXF7 = packed record
FontIndex: word;
FormatIndex: word;
Data1: word;
Data2: word;
Data3: word;
Data4: word;
Data5: word;
Data6: word;
end;
type PRecXF8 = ^TRecXF8;
TRecXF8 = packed record
FontIndex: word;
FormatIndex: word;
Data1: word;
Data2: word;
Data3: word;
Data4: word;
Data5: word;
Data6: longword;
Data7: word;
end;
// *** Chart Records ***
type PCRec3D = ^TCRec3D;
TCRec3D = packed record
Rotation: word;
Elevation: word;
Distance: word;
PlotHeight: word;
Depth: word;
Space: word;
Flags: word;
end;
type PCRecAI = ^TCRecAI;
TCRecAI = packed record
LinkType: byte;
ReferenceType: byte;
Flags: word;
FormatIndex: word;
FormulaSize: word;
end;
type PCRecAREA = ^TCRecAREA;
TCRecAREA = packed record
Flags: word;
end;
type PCRecAREAFORMAT = ^TCRecAREAFORMAT;
TCRecAREAFORMAT = packed record
ColorFgRGB: longword;
ColorBgRGB: longword;
Pattern: word;
Format: word;
ColorFgIndex: word;
ColorBgIndex: word;
end;
type PCRecAXCEXT = ^TCRecAXCEXT;
TCRecAXCEXT = packed record
MinCategory: word;
MaxCategory: word;
ValueMajor: word;
UnitsMajor: word;
ValueMinor: word;
UnitsMinor: word;
BaseUnit: word;
CrossingPoint: word;
Flags: word;
end;
type PCRecAXESUSED = ^TCRecAXESUSED;
TCRecAXESUSED = packed record
AxesSets: word;
end;
type PCRecAXISLINEFORMAT = ^TCRecAXISLINEFORMAT;
TCRecAXISLINEFORMAT = packed record
LineId: word;
end;
type PCRecAXISPARENT = ^TCRecAXISPARENT;
TCRecAXISPARENT = packed record
AxixIndex: word;
Top: longword;
Left: longword;
Width: longword;
Height: longword;
end;
type PCRecAXIS = ^TCRecAXIS;
TCRecAXIS = packed record
AxisType: word;
Reserved: array[0..15] of byte;
end;
type PCRecBAR = ^TCRecBAR;
TCRecBAR = packed record
SpaceBars: word;
SpaceCategories: word;
Flags: word;
end;
type PCRecCATSERRANGE = ^TCRecCATSERRANGE;
TCRecCATSERRANGE = packed record
CrossingPoint: word;
FreqLabels: word;
FreqMarks: word;
Flags: word;
end;
type PCRecCHART = ^TCRecCHART;
TCRecCHART = packed record
Top: array[0..1] of word;
Left: array[0..1] of word;
Width: array[0..1] of word;
Height: array[0..1] of word;
end;
type PCRecCHARTFORMAT = ^TCRecCHARTFORMAT;
TCRecCHARTFORMAT = packed record
Reserved: array[0..15] of byte;
Flags: word;
DrawingOrder: word;
end;
type PCRecDATAFORMAT = ^TCRecDATAFORMAT;
TCRecDATAFORMAT = packed record
PointNumber: word;
SeriesIndex: word;
SeriesNumber: word;
Flags: word;
end;
type PCRecDEFAULTTEXT = ^TCRecDEFAULTTEXT;
TCRecDEFAULTTEXT = packed record
Id: word;
end;
type PCRecFBI = ^TCRecFBI;
TCRecFBI = packed record
Width: word;
Height: word;
HeightApplied: word;
Scale: word;
Index: word;
end;
type PCRecFONTX = ^TCRecFONTX;
TCRecFONTX = packed record
FontIndex: word;
end;
type PCRecFRAME = ^TCRecFRAME;
TCRecFRAME = packed record
FrameType: word;
Flags: word;
end;
type PCRecLEGEND_ = ^TCRecLEGEND_;
TCRecLEGEND_ = packed record
Top: longword;
Left: longword;
Width: longword;
Height: longword;
LegendType: byte;
Spacing: byte;
Flags: word;
end;
type PCRecLINE = ^TCRecLINE;
TCRecLINE = packed record
Flags: word;
end;
type PCRecLINEFORMAT = ^TCRecLINEFORMAT;
TCRecLINEFORMAT = packed record
ColorRGB: longword;
Pattern: word;
Weight: word;
Format: word;
ColorIndex: word;
end;
type PCRecOBJECTLINK = ^TCRecOBJECTLINK;
TCRecOBJECTLINK = packed record
LinkedTo: word;
IndexSeries: word;
IndexData: word;
end;
type PCRecPLOTGROWTH = ^TCRecPLOTGROWTH;
TCRecPLOTGROWTH = packed record
Horizontal: longword;
Vertical: longword;
end;
type PCRecPIE = ^TCRecPIE;
TCRecPIE = packed record
Angle: word;
Donut: word;
Flags: word;
end;
type PCRecPIEFORMAT = ^TCRecPIEFORMAT;
TCRecPIEFORMAT = packed record
Percent: word;
end;
type PCRecPOS = ^TCRecPOS;
TCRecPOS = packed record
TopLt: word;
TopRt: word;
X1: longword;
Y1: longword;
X2: longword;
Y2: longword;
end;
type PCRecRADAR = ^TCRecRADAR;
TCRecRADAR = packed record
Flags: word;
end;
type PCRecRADARAREA = ^TCRecRADARAREA;
TCRecRADARAREA = packed record
Flags: word;
end;
type PCRecSERIES = ^TCRecSERIES;
TCRecSERIES = packed record
CategoriesType: word;
ValuesType: word;
CategoriesCount: word;
ValuesCount: word;
BubbleType: word;
BubbleCount: word;
end;
type PCRecSERIESTEXT = ^TCRecSERIESTEXT;
TCRecSERIESTEXT = packed record
TextId: word;
Length: byte;
{ Text <var> }
end;
type PCRecSERTOCRT = ^TCRecSERTOCRT;
TCRecSERTOCRT = packed record
ChartGroupIndex: word;
end;
type PCRecSHTPROPS = ^TCRecSHTPROPS;
TCRecSHTPROPS = packed record
Flags: word;
BlanksAs: byte;
Unknown: byte;
end;
type PCRecSIINDEX = ^TCRecSIINDEX;
TCRecSIINDEX = packed record
Index: word;
end;
type PCRecSURFACE = ^TCRecSURFACE;
TCRecSURFACE = packed record
Flags: word;
end;
type PCRecTEXT = ^TCRecTEXT;
TCRecTEXT = packed record
HorizAlignment: byte;
VertAlignment: byte;
BkgMode: word;
ColorRGB: longword;
Left: longword;
Top: longword;
Width: longword;
Height: longword;
Flags1: word;
ColorIndex: word;
Flags2: word;
Rotation: word;
end;
type PCRecTICK = ^TCRecTICK;
TCRecTICK = packed record
MajorMark: byte;
MinorMark: byte;
LabelPos: byte;
BkgMode: byte;
ColorRGB: longword;
Reserved1: array[0..15] of byte;
Flags: word;
ColorIndex: word;
Reserved2: word;
end;
type PCRecVALUERANGE = ^TCRecVALUERANGE;
TCRecVALUERANGE = packed record
MinValue: double;
MaxValue: double;
MajorInc: double;
MinorInc: double;
AxisCrosses: double;
Flags: word;
end;
implementation
end.
|
unit URelatorioDetalhamento;
interface
uses
Windows,
SysUtils,
Messages,
Classes,
Graphics,
Controls,
QuickRpt,
QRPrntr,
QRCtrls,
DB,
DBClient,
QRPDFFilt,
URelatorioDesenho;
type
TDetalhamento = class(TObject)
private
fDataSet: TDataSet;
fCabecalho: TDesenho;
fBandCabecalho: TQRBand;
fNomeDetalhamento: String;
fDetalhe: TDesenho;
fBandDetalhe: TQRCustomBand;
fRodape: TDesenho;
fBandRodape: TQRBand;
fBandSeparador: TQRChildBand;
fRelatorioParent: TWinControl;
fDataSource: TDataSource;
procedure SetDataSet(const Value: TDataSet);
procedure Configurar();
procedure setDataSource(const Value: TDataSource);
property BandDetalhe: TQRCustomBand read fBandDetalhe;
property BandCabecalho: TQRBand read fBandCabecalho;
property BandRodape: TQRBand read fBandRodape;
property BandSeparador: TQRChildBand read fBandSeparador;
public
procedure Cores(CorCabecalho, CorDetalhe, CorRodape: TColor); virtual;
constructor Create(AOwner: TComponent; ANomeDetalhamento: String); overload;
constructor Create(AOwner: TComponent; ANomeDetalhamento: String; ACabecaho, ADetalhe, ARodape: TQRCustomBand); overload;
destructor Destroy; override;
property NomeDetalhamento: String read fNomeDetalhamento;
property RelatorioParent: TWinControl read fRelatorioParent write fRelatorioParent;
property DataSet: TDataSet read fDataSet write SetDataSet;
property DataSource: TDataSource read fDataSource;
property Detalhe: TDesenho read fDetalhe;
property Cabecalho: TDesenho read fCabecalho;
property Rodape: TDesenho read fRodape;
end;
implementation
{ TDetalhamento }
constructor TDetalhamento.Create(AOwner: TComponent; ANomeDetalhamento: String);
begin
fNomeDetalhamento := ANomeDetalhamento;
fRelatorioParent := TWinControl(AOwner);
fBandCabecalho := TQRBand.Create(RelatorioParent);
fBandDetalhe := TQRBand.Create(RelatorioParent);
fBandSeparador := TQRChildBand.Create(RelatorioParent);
fBandRodape := TQRBand.Create(RelatorioParent);
fBandCabecalho.Name := 'Cabecalho' + NomeDetalhamento;
fBandDetalhe.Name := 'Detalhe' + NomeDetalhamento;
fBandRodape.Name := 'Rodape' + NomeDetalhamento;
fBandCabecalho.Parent := RelatorioParent;
fBandDetalhe.Parent := RelatorioParent;
fBandRodape.Parent := RelatorioParent;
fBandCabecalho.BandType := rbPageHeader;
TQRBand(fBandDetalhe).BandType := rbDetail;
TQRBand(fBandDetalhe).ForceNewPage := true;
TQRBand(fBandDetalhe).HasChild := true;
fBandRodape.BandType := rbPageFooter;
fBandSeparador.ParentBand := TQRBand(fBandDetalhe);
fDataSource := TDataSource.Create(RelatorioParent);
Configurar();
end;
constructor TDetalhamento.Create(AOwner: TComponent; ANomeDetalhamento: String; ACabecaho, ADetalhe, ARodape: TQRCustomBand);
begin
fNomeDetalhamento := ANomeDetalhamento;
fRelatorioParent := TWinControl(AOwner);
fBandCabecalho := TQRBand(ACabecaho);
fBandDetalhe := TQRBand(ADetalhe);
fBandRodape := TQRBand(ARodape);
fDataSource := TDataSource.Create(RelatorioParent);
Configurar();
end;
destructor TDetalhamento.Destroy;
begin
FreeAndNil(fCabecalho);
FreeAndNil(fDetalhe);
FreeAndNil(fRodape);
fDataSet := nil;
fBandCabecalho := nil;
fBandDetalhe := nil;
fBandRodape := nil;
fRelatorioParent := nil;
inherited;
end;
procedure TDetalhamento.Cores(CorCabecalho, CorDetalhe, CorRodape: TColor);
begin
BandCabecalho.Color := CorCabecalho;
BandDetalhe.Color := CorDetalhe;
BandRodape.Color := CorRodape;
end;
procedure TDetalhamento.Configurar();
begin
BandCabecalho.Height := 0;
BandDetalhe.Height := 0;
BandRodape.Height := 0;
fCabecalho := TDesenho.Create(RelatorioParent, BandCabecalho);
fDetalhe := TDesenho.Create(RelatorioParent, BandDetalhe);
fRodape := TDesenho.Create(RelatorioParent, BandRodape);
end;
procedure TDetalhamento.SetDataSet(const Value: TDataSet);
begin
fDataSet := Value;
TQuickRep(RelatorioParent).DataSet := fDataSet; // estava comentado
fDataSource.DataSet := DataSet;
end;
procedure TDetalhamento.setDataSource(const Value: TDataSource);
begin
fDataSource := Value;
end;
end.
|
unit grammar;
interface
uses
stdlib,
stdio,
Global,
AsmInstruction,
cstring,
memory_utils,
hash;
const
Keywords: array[0..10] of TToken = (
(Spelling: 'var'; Kind: TTokenKind.VAR_STATEMENT; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.NONE; Mnemonic: TAsmMnemonic.X86_INVALID; Next: nil),
(Spelling: 'const'; Kind: TTokenKind.CONST_STATEMENT; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.NONE; Mnemonic: TAsmMnemonic.X86_INVALID; Next: nil),
(Spelling: 'mov'; Kind: TTokenKind.ASM_MNEMONIC; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.NONE; Mnemonic: TAsmMnemonic.X86_MOV; Next: nil),
(Spelling: 'add'; Kind: TTokenKind.ASM_MNEMONIC; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.NONE; Mnemonic: TAsmMnemonic.X86_ADD; Next: nil),
(Spelling: 'sub'; Kind: TTokenKind.ASM_MNEMONIC; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.NONE; Mnemonic: TAsmMnemonic.X86_SUB; Next: nil),
(Spelling: 'mul'; Kind: TTokenKind.ASM_MNEMONIC; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.NONE; Mnemonic: TAsmMnemonic.X86_MUL; Next: nil),
(Spelling: 'jp'; Kind: TTokenKind.ASM_MNEMONIC; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.NONE; Mnemonic: TAsmMnemonic.X86_JP; Next: nil),
(Spelling: 'eax'; Kind: TTokenKind.ASM_REGISTER; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.EAX; Mnemonic: TAsmMnemonic.X86_INVALID; Next: nil),
(Spelling: 'ebx'; Kind: TTokenKind.ASM_REGISTER; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.EBX; Mnemonic: TAsmMnemonic.X86_INVALID; Next: nil),
(Spelling: 'ecx'; Kind: TTokenKind.ASM_REGISTER; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.ECX; Mnemonic: TAsmMnemonic.X86_INVALID; Next: nil),
(Spelling: 'edx'; Kind: TTokenKind.ASM_REGISTER; Address: 0; Size: TAsmOperandSize.UNSET; Reg: TAsmRegister.EDX; Mnemonic: TAsmMnemonic.X86_INVALID; Next: nil)
);
procedure initializeKeywords();
procedure Expect(msg: PAnsiChar);
implementation
procedure initializeKeywords();
var
iter: Integer;
TokenPtr: TTokenPtr;
begin
for iter := Low(Keywords) to High(Keywords) do
begin
TokenPtr := @Keywords[iter];
InsertIntoSymbolTable(TokenPtr);
end;
end;
(*****************************************************************
* Funรงรฃo: Erro rรกpido, falta um certo componente de sintaxe aqui
* msg : Quais componentes gramaticais sรฃo necessรกrios
************************************************** **************)
procedure Expect(msg: PAnsiChar);
begin
Error('Faltando %s', msg);
end;
end.
|
unit MyStr;
interface
uses
SysUtils, Classes, Graphics, Dialogs;
type
TMyStrArray = array of String;
function Transform(n: Real; FPicture: String): String;
function RTrim(s: String): String;
function LTrim(s: String): String;
function AllTrim(s: String): String;
function Replicate(c: Char; n: Integer): String;
function Left(s: String; n: Integer): String;
function Right(s: String; n: Integer): String;
function PadL(s: String; n: Integer; c_preenche: Char): String;
function PadC(s: String; n: Integer; c_preenche: Char): String;
function PadR(s: String; n: Integer; c_preenche: Char): String;
function IncrementoAlfa(s: String; TamanhoMaximo: Integer): String;
function InteiroDe(s: String): Longint;
function RealDe(const S: String): Real;
function BooleanoDe(s: String): Boolean;
function BoolToStr(l: Boolean): String;
function Cripto(s, Senha: String): String;
function DeCripto(s, Senha: String): String;
function Split(sep, s: String): TMyStrArray;
function ValorDoElemento(Lista: TMyStrArray; Indice: Integer): String;
function Explode(sep, s: String): TMyStrArray;
function Implode(Cola: String; Lista: TMyStrArray): String;
function ValorExisteNaLista(Valor: string; Lista: TMyStrArray): Boolean;
procedure Desmembr(texto: String; separador: Char; lista: TStringList);
function Substituir(s, Origem, Destino: String): String;
function SubstituirDelimitado (Texto, Busca, Subst: String): String;
function ReplaceMultiplo (Texto: String; Antigos, Novos: array of String): String;
function ProximaOcorrencia(s: String; c: Char; Inicio: Integer): Integer;
function FontToStr(AFont: TFont; SemCor: Boolean = False): String;
procedure StrToFont(s: String; AFont: TFont; SemCor: Boolean = False);
procedure QuebrarEmLinhas(n: Integer; s: String; Lista: TStringList);
function GetQuebraEmLinhas(s: String; n: Integer): TMyStrArray;
function TimeToSeconds(Horario: TDateTime): Longint;
function TimeToSecondsR(Horario: TDateTime): Real;
function SecondsToTime(Segundos: Longint): TDateTime;
function IIfStr(BoolExpr: Boolean; RetTrue, RetFalse: String): String;
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: Longint): Longint; overload;
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: Real): Real; overload;
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: String): String; overload;
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: TMsgDlgBtn): TMsgDlgBtn; overload;
function ExprOrDefault(Expr, Default: String): String;
// function IIf(BoolExpr: Boolean; RetTrue, RetFalse: TDateTime): TDateTime; overload;
function AddBarra(Caminho: String): String;
function DelBarra(Caminho: String): String;
function L2Bin(Valor: Longint): String;
function Bin2L(s: String): Longint;
function HexToInt(sHex: String): Longint;
function IntToBin(i: Integer): String;
function HbIsInt(s: String): Boolean;
function PreencherPosicao(nPos: Integer; sOrigem, sInsert: String): String;
function Capitalize(s: String): String;
function CapitalizeTexto(Texto: String): String;
function Mac2DecStr(MACAddr: String): String;
function RightPos(Substr: string; S: string): Integer;
function LeftPos(Substr: string; S: string): Integer;
function MensagemMsSQLFiltrada(s: String): String;
function MensagemPostgresFiltrada(s: String): String;
procedure SubstituirMacro(Nome, Valor: String; Lista: TStrings);
function RemoverAcentos(Str: String): String;
function PosicaoFechamento (S, DelimAbre,
DelimFecha: String; Inicio: Integer=1): Integer;
function RemoverComentariosSql (Sql: String): String;
function StartsWith(const S, Search: String): Boolean;
function EndsWith(const S, Search: String): Boolean;
function IsNumeric(const S: String): Boolean;
function ValueBetween(const Value, Lower, Upper: Real): Boolean;
function EscapeSQL(const Sql: String): String;
function PosExCaseInsensitive(const Procurado, Texto: String;
Offset: Cardinal = 1): Integer;
function PosicaoDaUltimaOcorrencia(const Procurado, Texto: String;
CaseSensitive: Boolean = False): Integer;
function PosicaoDoPrimeiroSeparador(const Texto: String): Integer;
function PosicaoDoUltimoSeparador(const Texto: String): Integer;
function GetPrimeiraPalavra(const Texto: String): String;
function FloatToSql(Valor: Real): String;
function InMyStrArray(Valor: String; UmArray: TMyStrArray): Boolean;
procedure AppendToMyStrArray(Valor: String; var UmArray: TMyStrArray);
function GetItemDaListaDelimitada(UmaListaDelimitada, UmDelimitador: String;
UmItem: Integer): String;
function getVariantDateAsString(varDate: Variant): String;
function StrToVarDate(StrDate: String): Variant;
function RemoverMascara(Valor: String): String;
function ConcatenarComSeparador(Destino, Adicionar, Separador: String): String;
implementation
uses StrUtils, Variants;
const
MatrizHex = '0123456789ABCDEF';
var
UnidadeTDateTime: Double;
(* Transform
;
; funciona como o transform do Clipper
; mas sรณ para nรบmeros
;
*)
function Transform(n: Real; FPicture: String): String;
var
i, l: Integer;
t, s: String;
p, w, d: Integer;
begin
s := '';
w := Length(FPicture);
{ calcular o nรบmero de casas }
{ decimais definidas pela mรกscara }
p := Pos(',', FPicture);
if p = 0 then d := 0
else d := Length(FPicture)-p;
{ converte o valor para string }
Str(n:w:d, t);
t := AllTrim(t);
{ monta o texto default }
for i := 1 to w do begin
if FPicture[i] = '9'
then s := s+'0'
else s := s+FPicture[i];
end;
{ agora preenche com o texto }
l := Length(t);
i := Length(FPicture);
if l > 0 then repeat
while (i > 0) and ((s[i] = ',') or (s[i] = '.')) do Dec(i);
while (l > 0) and not ((t[l] >= '0') and (t[l] <= '9')) do Dec(l);
if (i > 0) and (l > 0) then s[i] := t[l];
Dec(i);
Dec(l);
until (i = 0) or (l = 0);
{ dรก um trim nos zeros ร esquerda }
if d <= 0 then d := 1 else d := d+2;
while (Length(s) > d) and (s[ 1] in ['0', '.']) do Delete( s, 1, 1);
Result := s;
end;
function RTrim(s: String): String;
begin
{ espaรงos ร direita }
while (Length(s) > 0) and (s[Length(s)] = ' ') do Delete( s, Length(s), 1);
Result := s;
end;
function LTrim(s: String): String;
begin
{ espaรงos ร esquerda }
while (Length(s) > 0) and (s[ 1] = ' ') do Delete( s, 1, 1);
Result := s;
end;
(* AllTrim
;
; Idรชntica ร funรงรฃo homรดnima do Clipper
; Poda os espaรงos em branco ร direita
; e a esquerda
;
*)
function AllTrim( s: String ): String;
begin
{ espaรงos ร esquerda }
while (Length(s) > 0) and (s[ 1] = ' ') do Delete( s, 1, 1);
{ espaรงos ร direita }
while (Length(s) > 0) and (s[Length(s)] = ' ') do Delete( s, Length(s), 1);
AllTrim := s;
end;
(* Left, Right
;
; Adivinha...
;
*)
function Left(s: String; n: Integer): String;
begin
Result := Copy(s, 1, n);
end;
function Right(s: String; n: Integer): String;
var
l: Integer;
begin
l := Length(s);
if n >= l then Result := s else
Result := Copy(s, l-n+1, n);
end;
(* Replicate
;
; igual ร do Clipper
;
*)
function Replicate(c: Char; n: Integer): String;
var
i: Integer;
s: String;
begin
if n < 1 then Result := ''
else begin
s := '';
for i := 1 to n do s := s+c;
Result := s;
end;
end;
(* Pad
;
; serve para PadL, PadC e PadR
;
*)
function Pad(s: String; n: Integer; c_preenche, c_tipo: Char): String;
var
s1, s2: String;
l1, l2: Integer;
begin
s1 := AllTrim(s);
l1 := Length(s1);
l2 := n-l1;
if l2 = 0 then s2 := s1
else if l2 < 0 then begin
{ preenchimento ร esquerda significa alinhamento ร direita e vice-versa }
if c_tipo = 'L' then s2 := Copy(s1, -l2+1, n) else
if c_tipo = 'C' then s2 := Copy(s1, (-l2+2) div 2, n)
else s2 := Copy(s1, 1, n);
end else case c_tipo of
'L': s2 := Replicate(c_preenche, l2)+s1;
'R': s2 := s1+Replicate(c_preenche, l2);
'C': begin
if l2 < 2 then
s2 := c_preenche+s1
else
s2 := Replicate(c_preenche, l2 div 2)+s1
+Replicate(c_preenche, l2-(l2 div 2));
end;
end;
Pad := s2;
end;
(* PadL, PadC e PadR
;
; funรงรตes de preenchimento
; iguais ร s do Clipper
;
*)
function PadL(s: String; n: Integer; c_preenche: Char): String;
begin
Result := Pad(s, n, c_preenche, 'L');
end;
function PadC(s: String; n: Integer; c_preenche: Char): String;
begin
Result := Pad(s, n, c_preenche, 'C');
end;
function PadR(s: String; n: Integer; c_preenche: Char): String;
begin
Result := Pad(s, n, c_preenche, 'R');
end;
(* Substituir
;
; todas as ocorrencias de Origem
; na string s sรฃo substituidas por Destino
;
*)
function Substituir(s, Origem, Destino: String): String;
begin
Result := StringReplace(s, Origem, Destino, [rfReplaceAll, rfIgnoreCase]);
end;
(** SubstituirDelimitado
*
* substitui somente delimitados
* considera como delimitador
* qualquer caracter diferente de letras, nรบmeros e underline
*
*)
function SubstituirDelimitado (Texto, Busca, Subst: String): String;
var
dAntesOk, dDepoisOk: Boolean;
n, l, lt, i: Integer;
sRet, sTexto, sBusca: String;
begin
sBusca := AnsiLowerCase(Busca);
sTexto := Texto;
// se nรฃo tem busca ou estรก substituindo pela mesma coisa, ignora
if (Length(sBusca) = 0) or (sBusca = AnsiLowerCase (Subst)) then
Exit;
l := Length (sBusca);
sRet := '';
repeat
lt := Length (sTexto);
n := Pos (sBusca, AnsiLowerCase (sTexto));
if n > 0 then
begin
// verifica se tem delimitadores
// antes
if n = 1 then
dAntesOk := True
else
dAntesOk := not (sTexto[n-1] in ['a'..'z', 'A'..'Z', '0'..'9', '_']);
// depois
if n+l > lt then
dDepoisOk := True
else
dDepoisOk := not (sTexto[n+l] in ['a'..'z', 'A'..'Z', '0'..'9', '_']);
if dAntesOk and dDepoisOk then
// 1234567890
// xxxbusca_yy
begin
sRet := sRet+Copy (sTexto, 1, n-1)+Subst;
sTexto := Copy (sTexto, n+l, lt);
end else
begin
sRet := sRet+Copy (sTexto, 1, n+l-1);
sTexto := Copy (sTexto, n+l, lt);
// adiciona atรฉ o fim da palavra
lt := Length (sTexto);
n := 1;
repeat
sRet := sRet+sTexto[n];
n := n+1;
until (n = lt) or (not (sTexto[n] in ['a'..'z', 'A'..'Z', '0'..'9', '_']));
sTexto := Copy (sTexto, n, lt);
end;
end else
sRet := sRet+sTexto;
until n = 0;
Result := sRet;
end;
function ReplaceMultiplo(Texto: String; Antigos, Novos: array of String): String;
var
i, i_novo, len_antigos, len_novos: Integer;
begin
Result := Texto;
len_antigos := Length(antigos);
len_novos := Length(novos);
if (len_antigos < 1) or (len_novos < 1) then begin
Exit;
end;
for i := 0 to len_antigos - 1 do begin
if len_novos < (i+1) then begin
i_novo := len_novos-1
end else begin
i_novo := i;
end;
Result := Substituir(Result, antigos[i], novos[i_novo]);
end;
end;
(* RealDe
;
; converte s para um valor Real
;
*)
function RealDe(const S: String): Real;
var
PosicaoOndeOcorreuErro: Integer;
Resultado: Real;
ValorStr: String;
begin
if Pos(',', S) > 0 then
ValorStr := Trim(Substituir(Substituir(S, '.', ''), ',', '.'))
else
ValorStr := Trim(S);
Val(ValorStr, Resultado, PosicaoOndeOcorreuErro);
Result := IIf(PosicaoOndeOcorreuErro > 0, 0, Resultado);
end;
(* InteiroDe
;
; converte s para um valor
; de tipo inteiro
;
*)
function InteiroDe(s: String): Longint;
begin
Result := Round(RealDe(s));
end;
(* BooleanoDe
;
; converte a string
; para True ou False
;
*)
function BooleanoDe(s: String): Boolean;
begin
Result := StrToBool(s);
end;
function BoolToStr(l: Boolean): String;
begin
if l then Result := 'TRUE' else Result := 'FALSE';
end;
(* Split
;
; igual ร funรงรฃo split do Perl
;
*)
function Split(sep, s: String): TMyStrArray;
var
n, l, ls, t: Integer;
a: TMyStrArray;
begin
a := nil;
Result := a;
// HBB - 2011-08-22
// se s for uma string vazia, retorna vazio
if s = '' then
Exit;
l := 0;
t := Length(sep);
ls := Length(s);
n := Pos(sep, s);
while n > 0
do begin
SetLength(a, l+1);
a[l] := Copy(s, 1, n-1); // atribui a prรณxima entrada da lista ao elemento atual
s := Copy(s, n+t, ls); // e poda esta ponta de s
n := Pos(sep, s);
Inc(l);
end;
(*
// verifica a sobra
if s <> ''
then begin
SetLength(a, l+1);
a[l] := s;
end;
*)
// adiciona a sobra
SetLength(a, l+1);
a[l] := s;
// retorna a
Result := a;
end;
function ValorDoElemento(Lista: TMyStrArray; Indice: Integer): String;
begin
Result := '';
if ( Length(Lista) >= Indice + 1 ) then begin
Result := Lista[Indice];
end;
end;
function Explode(sep, s: String): TMyStrArray;
begin
Result := Split(sep, s);
end;
function Implode(Cola: String; Lista: TMyStrArray): String;
var
i, l: Integer;
begin
Result := '';
l := Length(Lista);
if l < 1 then
Exit;
for i := 0 to l-1 do
Result := Result + IIfStr(Result <> '', Cola, '') + Lista[i];
end;
function ValorExisteNaLista(Valor: string; Lista: TMyStrArray): Boolean;
var
Indice: Integer;
begin
Result := False;
for Indice := 0 to Length(Lista)-1 do
if SameText(Valor, Lista[Indice]) then
begin
Result := True;
Exit;
end;
end;
(* Desmembr
;
; procedure de desmembramento de strings
; armazena o resultado na string list
; recebida como parametro
;
*)
procedure Desmembr( texto: String; separador: Char; lista: TStringList);
var
i, l: Integer;
s: String;
begin
{ antes de mais nada, limpa a lista }
lista.Clear;
s := '';
l := Length(texto);
if (l > 0) then begin
for i := 1 to l do begin
if (texto[i] <> separador) then
s := s+texto[i]
else begin
lista.Add(s);
s := '';
end;
end;
{ como nรฃo hรก separador apรณs o รบltimo item,
ele ainda estรก armazenado em S
}
lista.Add(s);
end;
end;
(* ProximoChar
;
; Determina o prรณximo caractere
; alfa ou numรฉrico
;
*)
function ProximoChar(const c: Char; var Virou: Boolean): Char;
var
p: Char;
begin
p := c;
Virou := False;
{ se for espaรงo, vira para 1 }
if p = ' ' then p := '1'
else
{ verifica se รฉ A..Z }
if p in ['A'..'Z'] then begin
Inc(p);
if p > 'Z' then begin
p := 'A';
Virou := True;
end;
end else
{ verifica se รฉ a..z }
if p in ['a'..'z'] then begin
Inc(p);
if p > 'z' then begin
p := 'a';
Virou := True;
end;
end else
{ verifica se รฉ 0..9 }
if p in ['0'..'9'] then begin
Inc(p);
if p > '9' then begin
p := '0';
Virou := True;
end;
{ se nรฃo for nenhum dos anteriores }
{ considera como separador (como / . - etc.) }
{ entรฃo nรฃo muda o caracter mas retorna }
{ virou = True para forรงar o incremento do }
{ prรณximo dรญgito ร esquerda }
end else Virou := True;
Result := p;
end;
(* IncrementoAlfa
;
; retorna o valor incrementado
; para uma seqรผรชncia alfanumรฉrica
;
; o paramentro TamanhoMaximo sรณ
; รฉ relevante se "s" vier vazio
;
*)
function IncrementoAlfa(s: String; TamanhoMaximo: Integer): String;
var
Virou: Boolean;
i: Integer;
begin
Result := '';
if (s = '') then begin
Exit;
end;
s := PadL(s, TamanhoMaximo, ' ');
Virou := True;
i := Length(AllTrim(s));
if i = 0 then
s := Replicate('0', TamanhoMaximo-1)+'1'
else begin
i := Length(s);
while (i > 0) and Virou do begin
s[i] := ProximoChar(s[i], Virou);
Dec(i);
end;
end;
Result := Trim(s);
end;
(* Cripto
;
; criptografa a string s com Senha
;
*)
function Cripto(s, Senha: String): String;
var
i, j, l: Integer;
nSenha: Integer;
b: Integer;
r: String;
begin
r := '';
j := 0;
l := Length(Senha);
if l = 0 then r := s;
if (l > 0) and (Length(s) > 0) then
for i := 1 to Length(s) do begin
Inc(j); if j > l then j := 1;
nSenha := Ord(Senha[j]);
b := Ord(s[i]);
Inc(b, nSenha);
r := r+Chr(b);
end;
Result := r;
end;
function DeCripto(s, Senha: String): String;
var
i, j, l: Integer;
nSenha: Integer;
b: Integer;
r: String;
begin
r := '';
j := 0;
l := Length(Senha);
if l = 0 then r := s;
if (l > 0) and (Length(s) > 0) then
for i := 1 to Length(s) do begin
Inc(j); if j > l then j := 1;
nSenha := Ord(Senha[j]);
b := Ord(s[i]);
Dec(b, nSenha);
r := r+Chr(b);
end;
Result := r;
end;
(* ProximaOcorrencia
;
; retorna a prรณxima ocorrencia
; do caracter c na string s
; a partir da posiรงรฃo Inicio
;
*)
function ProximaOcorrencia(s: String; c: Char; Inicio: Integer): Integer;
var
i, l, n: Integer;
begin
i := Inicio;
l := Length(s);
n := 0;
while (i < l) and (n = 0) do begin
Inc(i);
if s[i] = c then n := i;
end;
Result := n;
end;
function FontToStr(AFont: TFont; SemCor: Boolean = False): String;
var
s: String;
begin
if not SemCor then
s := IntToStr(AFont.Color)+';'
else
s := '';
s := s + AFont.Name+';'+IntToStr(AFont.Size)+';[';
if fsBold in AFont.Style then s := s+'fsBold,';
if fsItalic in AFont.Style then s := s+'fsItalic,';
if fsUnderline in AFont.Style then s := s+'fsUnderline,';
if fsStrikeOut in AFont.Style then s := s+'fsStrikeOut,';
if Copy(s, Length(s), 1) = ',' then s := Copy(s, 1, Length(s)-1);
s := s+']';
Result := s;
end;
procedure StrToFont(s: String; AFont: TFont; SemCor: Boolean = False);
var
i, Indice: Integer;
Lista: TSTringList;
sStyle: String;
begin
Lista := TStringList.Create;
try
Indice := -1;
Desmembr(s, ';', Lista);
if (Lista.Count >= 4) or (SemCor and (Lista.Count >= 3)) then
begin
if not SemCor then
begin
AFont.Color := StrToInt(Lista[0]);
Indice := 0;
end;
AFont.Name := Lista[Indice+1];
AFont.Size := StrToInt(Lista[Indice+2]);
AFont.Style := [];
sStyle := Lista[Indice+3];
sStyle := Copy(sStyle, 2, Length(sStyle)-2); { remove os [] }
Desmembr(sStyle, ',', Lista);
if Lista.Count > 0
then for i := 0 to Lista.Count-1 do begin
if Lista[i] = 'fsBold' then AFont.Style := AFont.Style+[fsBold] else
if Lista[i] = 'fsItalic' then AFont.Style := AFont.Style+[fsItalic] else
if Lista[i] = 'fsUnderline' then AFont.Style := AFont.Style+[fsUnderline] else
if Lista[i] = 'fsStrikeOut' then AFont.Style := AFont.Style+[fsStrikeOut];
end;
end;
finally
Lista.Free;
end;
end;
(* ExtrairProximaPalavra
;
; retorna a prรณxima palavra em s
; e devolve s sem ela
;
*)
function ExtrairProximaPalavra(var s: String): String;
var
c: Char;
i, l: Integer;
begin
Result := '';
s := Trim(s);
if s <> '' then begin
i := 1;
l := Length(s);
repeat
c := s[i];
Result := Result+c;
Inc(i);
until (i > l) or (c in [' ', ',', '.', '-', '/']);
if i > l then s := '' else s := Copy(s, i, l);
end;
end;
(* GetProximaPalavra
;
; retorna a prรณxima palavra em s
;
*)
function GetProximaPalavra(s: String): String;
var
c: Char;
i, l: Integer;
begin
Result := '';
// s := Trim(s);
if s <> '' then begin
i := 1;
l := Length(s);
repeat
c := s[i];
Result := Result+c;
Inc(i);
until (i > l) or (c in [' ', ',', '.', '-', '/']);
// verfica se tem espaรงos depois do separador e adiciona
while (i <= l) and (s[i] in [' ', ',', '.', '-', '/'])
do begin
Result := Result+s[i];
Inc(i);
end;
end;
end;
(* QuebrarEmLinhas
;
; quebra s em linhas com largura mรกxima n
;
*)
procedure QuebrarEmLinhas(n: Integer; s: String; Lista: TStringList);
var
Excedeu: Boolean;
Linha, Proxima: String;
begin
Lista.Clear;
if n > 0
then repeat
Excedeu := False;
Linha := '';
repeat
Proxima := GetProximaPalavra(s);
if Length(Proxima) > n then Proxima := Copy(Proxima, 1, n);
// se a palavra cabe na linha
// adiciona e poda s
if Length(Linha+Proxima) <= n
then begin
Linha := Linha+Proxima;
s := Copy(s, Length(Proxima)+1, Length(s));
end
else Excedeu := True;
until Excedeu or (s = '');
if Linha <> '' then Lista.Add(Linha);
until (s = '');
end;
function GetQuebraEmLinhas(s: String; n: Integer): TMyStrArray;
var
i: Integer;
a: TMyStrArray;
Lista: TStringList;
begin
a := nil;
Lista := TStringList.Create;
try
QuebrarEmLinhas(n, s, Lista);
if Lista.Count > 0
then begin
SetLength(a, Lista.Count);
for i := 0 to Lista.Count-1
do a[i] := Lista[i];
end;
finally
Lista.Free;
Result := a;
end;
end;
function TimeToSeconds(Horario: TDateTime): Longint;
begin
Result := Trunc(Horario/UnidadeTDateTime);
end;
function TimeToSecondsR(Horario: TDateTime): Real;
begin
Result := Horario/UnidadeTDateTime;
end;
function SecondsToTime(Segundos: Longint): TDateTime;
begin
Result := Segundos*UnidadeTDateTime;
end;
function IIfStr(BoolExpr: Boolean; RetTrue, RetFalse: String): String;
begin
if BoolExpr then Result := RetTrue else Result := RetFalse;
end;
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: Longint): Longint; overload;
begin
if BoolExpr then Result := RetTrue else Result := RetFalse;
end;
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: Real): Real; overload;
begin
if BoolExpr then Result := RetTrue else Result := RetFalse;
end;
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: String): String; overload;
begin
if BoolExpr then Result := RetTrue else Result := RetFalse;
end;
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: TMsgDlgBtn): TMsgDlgBtn; overload;
begin
if BoolExpr then Result := RetTrue else Result := RetFalse;
end;
function ExprOrDefault(Expr, Default: String): String;
begin
Result := IIfStr(Trim(Expr) = '', Default, Expr);
end;
{
function IIf(BoolExpr: Boolean; RetTrue, RetFalse: TDateTime): TDateTime; overload;
begin
if BoolExpr then Result := RetTrue else Result := RetFalse;
end;
}
function AddBarra(Caminho: String): String;
begin
Result := IncludeTrailingPathDelimiter(Caminho);
end;
function DelBarra(Caminho: String): String;
begin
Result := ExcludeTrailingPathDelimiter(Caminho);
end;
(*
function IntToBin (Valor: Longint; Digitos: Integer): String;
begin
Result := StringOfChar('0', Digitos) ;
while Valor > 0 do
begin
if (Valor and 1) = 1 then
Result[Digits] := '1';
Dec(Digitos);
Valor := Valor shr 1;
end;
end;
*)
function L2Bin(Valor: Longint): String;
var
i,
b1, b2, b3, b4: Integer;
begin
i := Valor;
b1 := i mod 255;
b2 := (i div 255) mod 255;
b3 := ((i div 255) div 255) mod 255;
b4 := ((i div 255) div 255) div 255;
Result := Chr(b1)+Chr(b2)+Chr(b3)+Chr(b4);
end;
function Bin2L(s: String): Longint;
var
i, n, l: Integer;
begin
Result := 0;
l := Length(s);
if l > 0 then
for i := 1 to l do begin
n := l-i;
if Copy(s, i, 1) = '1'
then Result := Result+Trunc(Exp(Ln(2) * n)); // Exp(Ln(r1) * r2); { r1 elevado a r2 }
end;
end;
function HexToInt(sHex: String): Longint;
var
i, n, Base: Integer;
begin
Result := 0;
if Length(sHex) > 0
then begin
Base := 1;
for i := Length(sHex) downto 1
do begin
n := Pos(Copy(sHex, i, 1), MatrizHex)-1;
Result := Result+n*Base;
Base := Base*16;
end;
end;
end;
function IntToBin(i: Integer): String;
var
n: Integer;
s: String;
begin
n := 1;
s := '';
while n <= i do begin
if (n and i) > 0
then s := s+'1'
else s := s+'0';
n := n*2;
end;
if i <= 0 then s := '0';
Result := '';
for n := Length(s) downto 1
do Result := Result+s[n];
end;
function HbIsInt(s: String): Boolean;
var
i: Integer;
begin
Result := True;
if Length(s) > 0
then for i := 1 to Length(s)
do if not (s[i] in ['0'..'9'])
then begin
Result := False;
Break;
end;
end;
function PreencherPosicao(nPos: Integer; sOrigem, sInsert: String): String;
var
l: Integer;
begin
l := Length(sInsert);
Delete(sOrigem, nPos, l);
Insert(sInsert, sOrigem, nPos);
Result := sOrigem;
end;
function Capitalize(s: String): String;
begin
Result := '';
if Length (s) < 1 then
Exit;
s := AnsiLowerCase(s);
s[1] := UpCase(s[1]);
Result := s;
end;
function CapitalizeTexto(Texto: String): String;
var
i: integer;
c: string;
begin
if Length(Texto) < 1 then Exit;
Texto := Trim(Texto);
Texto := Capitalize(Texto);
for i:=2 to Length(Texto) do
begin
if (Texto[I] = ' ') or (Texto[I] = '(') or (Texto[I] = '.') then
begin
try
if (Texto[I+2] <> ' ') then
begin
c := UpperCase(Texto[I+1]);
Texto[I+1] := c[1];
end;
except
end;
end;
end;
result := Texto;
end;
function Mac2DecStr(MACAddr: String): String;
var
i: Integer;
s: String;
GruposMAC: TMyStrArray;
begin
Result := '';
GruposMAC := Split(':', MACAddr);
if Length(GruposMAC) > 0
then begin
for i := 0 to Length(GruposMAC)-1
do begin
s := IntToStr(HexToInt(GruposMAC[i]));
Result := Result+IIfStr(i > 0, ' ', '')+s;
end;
end;
end;
function RightPos(Substr: string; S: string): Integer;
var
i, ls, lss: Integer;
begin
Result := 0;
ls := Length(S);
lss := Length(Substr);
if (ls > 0) and (ls >= lss) then
for i := ls downto 1 do
begin
if Copy(s, i, lss) = Substr then
begin
Result := i;
Break;
end;
end;
end;
function LeftPos(Substr: string; S: string): Integer;
var
i, ls, lss: Integer;
begin
Result := 0;
ls := Length(S);
lss := Length(Substr);
if (ls > 0) and (ls >= lss) then
for i := 1 to ls do
begin
if Copy(s, i, lss) = Substr then
begin
Result := i;
Break;
end;
end;
end;
(* MensagemMsSQLFiltrada
;
; filtra uma mensagem de erro do SQL Server
; para exibir somente a parte "legรญvel"
;
*)
function MensagemMsSQLFiltrada(s: String): String;
var
n: Integer;
begin
n := RightPos(']', s);
if n > 0 then
Result := Copy(s, n+1, Length(s))
else
Result := s;
end;
(* MensagemPostgresFiltrada
;
; a mensagem do postgres comeรงa sempre
; com 'Key violation.' <quebra de linha> 'ERROR: '
;
*)
function MensagemPostgresFiltrada(s: String): String;
var
i: Integer;
begin
i := Pos('ERROR:', s);
if i < 1 then
i := Pos(':', s)
else
i := i+6;
Result := Trim(Copy(s, i+1, Length(s)));
end;
procedure SubstituirMacro(Nome, Valor: String; Lista: TStrings);
var
i: Integer;
begin
if Lista.Count > 0 then
for i := 0 to Lista.Count-1 do
Lista[i] := Substituir(Lista[i], '&'+Nome, Valor);
end;
function RemoverAcentos(Str: String): String;
const
ComAcento = 'ร รขรชรฎรดรปรฃรตรกรฉรจรญรฌรณรฒรบรนรงรผรรรรรรรรรรรรรรรรรรรยด`~"ยยยง#%&*@ยบยชยฐยฎยฅรฑ?ยยงรยตยฑยฃยฎรรรรรฅรฆรซรฏรถยคยฃยฆยย';
SemAcento = 'aaeiouaoaeeiioouucuAAEIOUAOAEEIIOOUUCU ';
var
x : Integer;
begin
for x := 1 to Length(Str) do
begin
if Pos(str[x],ComAcento)<>0 Then
begin
str[x] := SemAcento[Pos(Str[x],ComAcento)];
end;//if..then
end;//for..do
result := str;
end;
function PosicaoFechamento (S, DelimAbre,
DelimFecha: String; Inicio: Integer=1): Integer;
var
posAbre, Contagem,
i, ls, lss: Integer;
c: String;
begin
Result := -1;
ls := Length(S);
if ls < Inicio then
Exit;
// procura o primeiro delimitador
posAbre := 0;
for i := Inicio to ls do
begin
if Copy(S, i, 1) = DelimAbre then
begin
posAbre := i;
Break;
end;
end;
// se nรฃo encontrou o delimitador de abertura,
// retorna com erro
if posAbre = 0 then
Exit;
// a partir desse ponto,
// conta aberturas e fechamentos
Contagem := 1;
for i := posAbre+1 to ls do
begin
c := Copy(S, i, 1);
if c = DelimAbre then
Contagem := Contagem+1
else if c = DelimFecha then
Contagem := Contagem-1;
if Contagem = 0 then
begin
Result := i;
Exit;
end;
end;
end;
function RemoverComentariosSql (Sql: String): String;
var
i, n, nAbre, nFecha: Integer;
Lista: TStringList;
begin
// primeiro remove os comentรกrios /* */
repeat
nAbre := Pos ('/*', Sql);
nFecha := Pos ('*/', Sql);
if nAbre > 0 then
Delete (Sql, nAbre, nFecha-nAbre+2);
until nAbre = 0;
Lista := TStringList.Create;
try
Lista.Text := Sql;
for i := 0 to Lista.Count-1 do
begin
n := Pos ('--', Lista [i]);
if n > 0 then
Lista [i] := Copy (Lista [i], 1, n-1);
end;
Result := Lista.Text;
finally
Lista.Free;
end;
end;
(** StartsWith
*
* verifica se S comeรงa com Search
* case insensitive
*
*)
function StartsWith(const S, Search: String): Boolean;
var
Verif: String;
begin
Verif := Copy(S, 1, Length(Search));
Result := CompareText(Search, Verif) = 0;
end;
function EndsWith(const S, Search: String): Boolean;
var
LSearch, LS: Integer;
begin
Result := False;
LSearch := Length(Search);
LS := Length(S);
if ( LSearch > LS ) then begin
Exit;
end;
Result := CompareText(Search, Copy(S, LS-LSearch+1, LS)) = 0;
end;
function IsNumeric(const S: String): Boolean;
begin
Result := True;
try
StrToFloat (S);
except
Result := False;
end;
end;
function ValueBetween(const Value, Lower, Upper: Real): Boolean;
begin
Result := (Value >= Lower) and (Value <= Upper);
end;
function EscapeSQL(const Sql: String): String;
begin
Result := StringReplace(StringReplace(Sql, '''', '''''', [rfReplaceAll]), '\', '\\', [rfReplaceAll]);
end;
function PosExCaseInsensitive(const Procurado, Texto: String;
Offset: Cardinal = 1): Integer;
begin
Result := PosEx(AnsiUpperCase(Procurado), AnsiUpperCase(Texto), Offset);
end;
function PosicaoDaUltimaOcorrencia(const Procurado, Texto: String;
CaseSensitive: Boolean = False): Integer;
var
PosicaoAnterior: Integer;
begin
PosicaoAnterior := 0;
repeat
if CaseSensitive then
Result := PosEx(Procurado, Texto, PosicaoAnterior+1)
else
Result := PosExCaseInsensitive(Procurado, Texto, PosicaoAnterior+1);
if Result > 0 then
PosicaoAnterior := Result;
until
Result = 0;
Result := PosicaoAnterior;
end;
function PosicaoDoPrimeiroSeparador(const Texto: String): Integer;
var
Indice: Integer;
begin
Result := 0;
if Texto = '' then
Exit;
for Indice := 1 to Length(Texto) do
if Texto[Indice] in [#32..#47] then
begin
Result := Indice;
Exit;
end;
end;
function PosicaoDoUltimoSeparador(const Texto: String): Integer;
var
Indice: Integer;
begin
Result := 0;
if Texto = '' then
Exit;
for Indice := Length(Texto) downto 1 do
if Texto[Indice] in [#32..#47] then
begin
Result := Indice;
Exit;
end;
end;
function GetPrimeiraPalavra(const Texto: String): String;
begin
Result := LeftStr(Texto, Pos(' ', Texto)-1);
end;
function FloatToSql(Valor: Real): String;
begin
Result := Substituir(FloatToStr(Valor), ',', '.');
end;
function InMyStrArray(Valor: String; UmArray: TMyStrArray): Boolean;
var
Indice: Integer;
begin
Result := True;
for Indice := 0 to Length(UmArray)-1 do
if SameText(Valor, Trim(UmArray[Indice])) then
Exit;
Result := False;
end;
procedure AppendToMyStrArray(Valor: String; var UmArray: TMyStrArray);
var
Len: Integer;
begin
Len := Length(UmArray);
SetLength(UmArray, Len+1);
UmArray[Len] := Valor;
end;
function GetItemDaListaDelimitada(UmaListaDelimitada, UmDelimitador: String;
UmItem: Integer): String;
var
Lista: TMyStrArray;
begin
Result := '';
Lista := Explode(UmDelimitador, UmaListaDelimitada);
if Length(Lista) > UmItem then
Result := Lista[UmItem];
end;
function getVariantDateAsString(varDate: Variant): String;
begin
Result := '';
if ( not VarIsNull(varDate) ) then begin
Result := FormatDateTime('dd/mm/yyyy', VarToDateTime(varDate));
end;
end;
function StrToVarDate(StrDate: String): Variant;
begin
Result := Null;
if ( Trim(StrDate) <> '' ) then begin
Result := StrToDate(StrDate);
end;
end;
function RemoverMascara(Valor: String): String;
begin
Result := Substituir(Substituir(Substituir(Substituir(Substituir(
Substituir(Valor, '.', ''), '-', ''), '/', ''), ',', ''), '(', ''), ')', '');
end;
function ConcatenarComSeparador(Destino, Adicionar, Separador: String): String;
begin
Result := Destino + IIfStr((Destino = '') or (Adicionar = ''), '', Separador) + Adicionar;
end;
var
lt, lf: Integer;
initialization
UnidadeTDateTime := 1/86400; { 1/(24*3600) }
// extende as listas de conversรฃo para StrToBool (em SysUtils)
lt := Length(TrueBoolStrs);
lf := Length(FalseBoolStrs);
SetLength(TrueBoolStrs, lt+6);
SetLength(FalseBoolStrs, lf+6);
TrueBoolStrs[lt] := 'True';
TrueBoolStrs[lt+1] := 'T';
TrueBoolStrs[lt+2] := 'Verdadeiro';
TrueBoolStrs[lt+3] := 'V';
TrueBoolStrs[lt+4] := 'Sim';
TrueBoolStrs[lt+5] := 'S';
FalseBoolStrs[lf] := 'False';
FalseBoolStrs[lf+1]:= 'F';
FalseBoolStrs[lf+2]:= 'Falso';
FalseBoolStrs[lf+3]:= 'Nao';
FalseBoolStrs[lf+4]:= 'Nรฃo';
FalseBoolStrs[lf+5]:= 'N';
end.
|
(*======================================================================*
| GraphFlip unit |
| |
| Simple functions to flip and rotate 24-bit bitmaps |
| |
| 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 2002 All Rights Reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 29/08/2002 CPWW Original |
*======================================================================*)
unit GraphFlip;
interface
uses Windows, Classes, Sysutils, Graphics;
function RotateBitmap270 (const bitmap : TBitmap) : TBitmap;
function RotateBitmap90 (const bitmap : TBitmap) : TBitmap;
function ConvertToGrayscale (const bitmap : TBitmap) : TBitmap;
function ConvertToNegative (const bitmap : TBitmap) : TBitmap;
procedure DrawTextW(DC: HDC; lpString: PWideChar; nCount: Integer; var lpRect: TRect; uFormat: Cardinal;
AdjustRight: Boolean);
implementation
function BytesPerScanline(PixelsPerScanline, BitsPerPixel, Alignment: Longint): Longint;
begin
Dec(Alignment);
Result := ((PixelsPerScanline * BitsPerPixel) + Alignment) and not Alignment;
Result := Result div 8;
end;
function RotateBitmap270 (const bitmap : TBitmap) : TBitmap;
var
x, y : Integer;
ps, ps1, pr, pr1 : PRGBTriple;
bpss, bpsr : Integer;
begin
if bitmap.PixelFormat <> pf24Bit then
raise Exception.Create ('Invalid pixel format');
result := TBitmap.Create;
result.PixelFormat := bitmap.PixelFormat;
result.Height := bitmap.Width;
result.Width := bitmap.Height;
ps1 := bitmap.ScanLine [0];
pr1 := result.ScanLine [bitmap.Width - 1];
bpss := BytesPerScanLine (bitmap.Width, 24, 32);
bpsr := BytesPerScanLine (result.Width, 24, 32);
for y := 0 to bitmap.Height - 1 do
begin
ps := PRGBTriple (PChar (ps1) - bpss * y);
for x := 0 to bitmap.Width - 1 do
begin
pr := PRGBTriple (PChar (pr1) + bpsr * x);
Inc (pr, y);
pr^ := ps^;
Inc (ps)
end
end;
GDIFlush
end;
function RotateBitmap90 (const bitmap : TBitmap) : TBitmap;
var
x, y : Integer;
ps, ps1, pr, pr1 : PRGBTriple;
bpss, bpsr : Integer;
begin
if bitmap.PixelFormat <> pf24Bit then
raise Exception.Create ('Invalid pixel format');
result := TBitmap.Create;
result.PixelFormat := bitmap.PixelFormat;
result.Height := bitmap.Width;
result.Width := bitmap.Height;
ps1 := bitmap.ScanLine [bitmap.Height - 1];
pr1 := result.ScanLine [0];
bpss := BytesPerScanLine (bitmap.Width, 24, 32);
bpsr := BytesPerScanLine (result.Width, 24, 32);
for y := 0 to bitmap.Height - 1 do
begin
ps := PRGBTriple (PChar (ps1) + bpss * y);
for x := 0 to Bitmap.Width - 1 do
begin
pr := PRGBTriple (PChar (pr1) - bpsr * x);
Inc (pr, y);
pr^ := ps^;
Inc (ps)
end
end;
GDIFlush
end;
function ConvertToGrayscale (const bitmap : TBitmap) : TBitmap;
var
x, y : Integer;
ps, ps1, pr, pr1 : PRGBTriple;
bps : Integer;
n : Integer;
begin
if bitmap.PixelFormat <> pf24Bit then
raise Exception.Create ('Invalid pixel format');
result := TBitmap.Create;
result.PixelFormat := bitmap.PixelFormat;
result.Height := bitmap.Height;
result.Width := bitmap.Width;
ps1 := bitmap.ScanLine [0];
pr1 := result.ScanLine [0];
bps := BytesPerScanLine (bitmap.Width, 24, 32);
for y := 0 to bitmap.Height - 1 do
begin
ps := PRGBTriple (PChar (ps1) - bps * y);
pr := PRGBTriple (PChar (pr1) - bps * y);
for x := 0 to Bitmap.Width - 1 do
begin
n := (ps^.rgbtBlue + ps^.rgbtGreen + ps^.rgbtRed) div 3;
pr^.rgbtBlue := n;
pr^.rgbtGreen := n;
pr^.rgbtRed := n;
Inc (pr);
Inc (ps)
end
end;
GDIFlush
end;
function ConvertToNegative (const bitmap : TBitmap) : TBitmap;
var
x, y : Integer;
ps, ps1, pr, pr1 : PRGBTriple;
bps : Integer;
begin
if bitmap.PixelFormat <> pf24Bit then
raise Exception.Create ('Invalid pixel format');
result := TBitmap.Create;
result.PixelFormat := bitmap.PixelFormat;
result.Height := bitmap.Height;
result.Width := bitmap.Width;
ps1 := bitmap.ScanLine [0];
pr1 := result.ScanLine [0];
bps := BytesPerScanLine (bitmap.Width, 24, 32);
for y := 0 to bitmap.Height - 1 do
begin
ps := PRGBTriple (PChar (ps1) - bps * y);
pr := PRGBTriple (PChar (pr1) - bps * y);
for x := 0 to Bitmap.Width - 1 do
begin
pr^.rgbtBlue := 255 - ps^.rgbtBlue;
pr^.rgbtGreen := 255 - ps^.rgbtGreen;
pr^.rgbtRed := 255 - ps^.rgbtRed;
Inc (pr);
Inc (ps)
end
end;
GDIFlush
end;
const
WideNull = WideChar(#0);
WideCR = WideChar(#13);
WideLF = WideChar(#10);
WideLineSeparator = WideChar(#2028);
procedure DrawTextW(DC: HDC; lpString: PWideChar; nCount: Integer; var lpRect: TRect; uFormat: Cardinal;
AdjustRight: Boolean);
// This procedure implements a subset of Window's DrawText API for Unicode which is not available for
// Windows 9x. For a description of the parameters see DrawText in the online help.
// Supported flags are currently:
// - DT_LEFT
// - DT_TOP
// - DT_CALCRECT
// - DT_NOCLIP
// - DT_RTLREADING
// - DT_SINGLELINE
// - DT_VCENTER
// Differences to the DrawTextW Windows API:
// - The additional parameter AdjustRight determines whether to adjust the right border of the given rectangle to
// accomodate the largest line in the text. It has only a meaning if also DT_CALCRECT is specified.
var
Head, Tail: PWideChar;
Size: TSize;
MaxWidth: Integer;
TextOutFlags: Integer;
TextAlign,
OldTextAlign: Cardinal;
TM: TTextMetric;
TextHeight: Integer;
LineRect: TRect;
TextPosY,
TextPosX: Integer;
CalculateRect: Boolean;
begin
// Prepare some work variables.
MaxWidth := 0;
Head := lpString;
GetTextMetrics(DC, TM);
TextHeight := TM.tmHeight;
if uFormat and DT_SINGLELINE <> 0 then
LineRect := lpRect
else
LineRect := Rect(lpRect.Left, lpRect.Top, lpRect.Right, lpRect.Top + TextHeight);
CalculateRect := uFormat and DT_CALCRECT <> 0;
// Prepare text output.
TextOutFlags := 0;
if uFormat and DT_NOCLIP = 0 then
TextOutFlags := TextOutFlags or ETO_CLIPPED;
if uFormat and DT_RTLREADING <> 0 then
TextOutFlags := TextOutFlags or ETO_RTLREADING;
// Determine horizontal and vertical text alignment.
OldTextAlign := GetTextAlign(DC);
TextAlign := TA_LEFT or TA_TOP;
TextPosX := lpRect.Left;
if uFormat and DT_RIGHT <> 0 then
begin
TextAlign := TextAlign or TA_RIGHT and not TA_LEFT;
TextPosX := lpRect.Right;
end
else
if uFormat and DT_CENTER <> 0 then
begin
TextAlign := TextAlign or TA_CENTER and not TA_LEFT;
TextPosX := (lpRect.Left + lpRect.Right) div 2;
end;
TextPosY := lpRect.Top;
if uFormat and DT_VCENTER <> 0 then
begin
// Note: vertical alignment does only work with single line text ouput!
TextPosY := (lpRect.Top + lpRect.Bottom - TextHeight) div 2;
end;
SetTextAlign(DC, TextAlign);
if uFormat and DT_SINGLELINE <> 0 then
begin
if CalculateRect then
begin
GetTextExtentPoint32W(DC, Head, nCount, Size);
if Size.cx > MaxWidth then
MaxWidth := Size.cx;
end
else
ExtTextOutW(DC, TextPosX, TextPosY, TextOutFlags, @LineRect, Head, nCount, nil);
OffsetRect(LineRect, 0, TextHeight);
end
else
begin
while (nCount > 0) and (Head^ <> WideNull) do
begin
Tail := Head;
// Look for the end of the current line. A line is finished either by the string end or a line break.
while (nCount > 0) and not (Tail^ in [WideNull, WideCR, WideLF]) and (Tail^ <> WideLineSeparator) do
begin
Inc(Tail);
Dec(nCount);
end;
if CalculateRect then
begin
GetTextExtentPoint32W(DC, Head, Tail - Head, Size);
if Size.cx > MaxWidth then
MaxWidth := Size.cx;
end
else
ExtTextOutW(DC, TextPosX, LineRect.Top, TextOutFlags, @LineRect, Head, Tail - Head, nil);
OffsetRect(LineRect, 0, TextHeight);
// Get out of the loop if the rectangle is filled up.
if (nCount = 0) or (not CalculateRect and (LineRect.Top >= lpRect.Bottom)) then
Break;
if (nCount > 0) and (Tail^ = WideCR) or (Tail^ = WideLineSeparator) then
begin
Inc(Tail);
Dec(nCount);
end;
if (nCount > 0) and (Tail^ = WideLF) then
begin
Inc(Tail);
Dec(nCount);
end;
Head := Tail;
end;
end;
SetTextAlign(DC, OldTextAlign);
if CalculateRect then
begin
if AdjustRight then
lpRect.Right := lpRect.Left + MaxWidth;
lpRect.Bottom := LineRect.Top;
end;
end;
end.
|
unit KAllDicts;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, UniButtonsFrame, BaseGUI, CoreDescription;
type
TfrmAllDicts = class;
TAllDictsGUIAdapter = class (TCollectionGUIAdapter)
private
function GetFrameOwner: TfrmAllDicts;
public
property FrameOwner: TfrmAllDicts read GetFrameOwner;
procedure Reload; override;
function Add: integer; override;
function Delete: integer; override;
function StartFind: integer; override;
constructor Create(AOwner: TComponent); override;
end;
TfrmAllDicts = class(TFrame, IGUIAdapter)
GroupBox1: TGroupBox;
lstAllDicts: TListBox;
frmButtons: TfrmButtons;
private
FDictGUIAdapter: TAllDictsGUIAdapter;
function GetActiveDict: TDictionary;
public
property ActiveDict: TDictionary read GetActiveDict;
property GUIAdapter: TAllDictsGUIAdapter read FDictGUIAdapter implements IGUIAdapter;
destructor Destroy; override;
constructor Create(AOnwer: TComponent); override;
end;
implementation
uses Facade;
{$R *.dfm}
{ TAllDictsGUIAdapter }
function TAllDictsGUIAdapter.Add: integer;
var o: TDictionary;
begin
Result := 0;
try
o := (TMainFacade.GetInstance as TMainFacade).Dicts.Add as TDictionary;
except
Result := -1;
end;
if Result >= 0 then inherited Add;
end;
constructor TAllDictsGUIAdapter.Create(AOwner: TComponent);
begin
inherited;
Buttons := [abReload, abAdd, abDelete, abSort];
end;
function TAllDictsGUIAdapter.Delete: integer;
begin
Result := 0;
if FrameOwner.ActiveDict.Roots.Count = 0 then
begin
(TMainFacade.GetInstance as TMainFacade).Dicts.Remove(FrameOwner.ActiveDict);
inherited Delete;
end
else MessageBox(0, 'ะะตะปัะทั ัะดะฐะปะธัั ัะปะพะฒะฐัั, ั.ะบ. ัััะตััะฒััั ัะฒัะทะฐะฝะฝัะต ั ะฝะธะผ ัะปะตะผะตะฝัั.', 'ะกะพะพะฑัะตะฝะธะต', MB_OK + MB_ICONINFORMATION + MB_APPLMODAL);
end;
function TAllDictsGUIAdapter.GetFrameOwner: TfrmAllDicts;
begin
Result := Owner as TfrmAllDicts;
end;
procedure TAllDictsGUIAdapter.Reload;
begin
if StraightOrder then (TMainFacade.GetInstance as TMainFacade).Dicts.Sort(SortOrders.Items[OrderBY].Compare)
else (TMainFacade.GetInstance as TMainFacade).Dicts.Sort(SortOrders.Items[OrderBY].ReverseCompare);
(TMainFacade.GetInstance as TMainFacade).Dicts.MakeList(FrameOwner.lstAllDicts.Items);
inherited;
end;
function TAllDictsGUIAdapter.StartFind: integer;
begin
Result := 0;
end;
{ TfrmAllDicts }
constructor TfrmAllDicts.Create(AOnwer: TComponent);
begin
inherited;
(TMainFacade.GetInstance as TMainFacade).Dicts.MakeList(lstAllDicts.Items);
FDictGUIAdapter := TAllDictsGUIAdapter.Create(Self);
FDictGUIAdapter.List := lstAllDicts;
frmButtons.GUIAdapter := FDictGUIAdapter;
end;
destructor TfrmAllDicts.Destroy;
begin
FDictGUIAdapter.Free;
inherited;
end;
function TfrmAllDicts.GetActiveDict: TDictionary;
begin
Result := nil;
if (lstAllDicts.ItemIndex > -1) and (lstAllDicts.Count > 0) then
Result := lstAllDicts.Items.Objects[lstAllDicts.ItemIndex] as TDictionary;
end;
end.
|
program CircleArea;
uses TerminalUserInput;
procedure Main();
var
cirRadius, cirArea: Single;
roundedValue: Integer;
begin
cirRadius := ReadInteger('Enter a radius: ');
cirArea := Pi() * Sqr(cirRadius);
WriteLn('Circles area is ', cirArea:4:2);
roundedValue := Round(cirArea);
WriteLn('Which rounded off has a value of ', roundedValue);
ReadLn();
end;
begin
Main();
end. |
unit luaclientfunctions;
{$mode objfpc}{$H+}
interface
uses
windows, Classes, SysUtils, syncobjs;
function CELUA_Initialize(pipename: pchar): BOOL; stdcall;
function CELUA_ExecuteFunction(script: pchar; parameters: UINT_PTR): UINT_PTR; stdcall;
function CELUA_ExecuteFunctionAsync(script: pchar; parameters: UINT_PTR): UINT_PTR; stdcall;
function CELUA_GetFunctionReferenceFromName(functionname: pchar): integer; stdcall;
function CELUA_ExecuteFunctionByReference(ref: integer; paramcount: integer; AddressOfParameters: PPointer; async: BOOLEAN): UINT_PTR; stdcall;
var CELUA_ServerName: array [0..255] of char;
implementation
var
pipe: THandle=INVALID_HANDLE_VALUE;
cs: TCriticalSection;
procedure CELUA_Error;
begin
closehandle(pipe);
pipe:=INVALID_HANDLE_VALUE;
end;
function CELUA_ExecuteFunctionByReference(ref: integer; paramcount: integer; AddressOfParameters: PPointer; async: BOOLEAN): UINT_PTR; stdcall;
type TParamType=(ptNil=0, ptBoolean=1, ptInt64=2, ptInt32=3, ptNumber=4, ptString=5, ptTable=6, ptUnknown=255);
var
command: byte;
bw: dword;
a: byte;
i: integer;
valtype: TParamType;
vtb: byte;
returncount: byte;
v: qword;
d: double;
stringlength: word;
s: pchar;
begin
if pipe=INVALID_HANDLE_VALUE then
CELUA_Initialize(CELUA_ServerName);
result:=0;
command:=3;
{$ifdef cpu32}
valtype:=ptInt32;
{$else}
valtype:=ptInt64;
{$endif}
vtb:=byte(valtype);
cs.enter;
try
if pipe<>INVALID_HANDLE_VALUE then
begin
if writefile(pipe, command, sizeof(command), bw, nil) then
if async then a:=1 else a:=0;
if writefile(pipe, a, sizeof(a), bw, nil) then
begin
if writefile(pipe, ref, sizeof(ref), bw, nil) then
begin
if writefile(pipe, paramcount, 1, bw, nil) then
begin
for i:=0 to paramcount-1 do
begin
WriteFile(pipe, vtb, sizeof(vtb),bw,nil);
WriteFile(pipe, AddressOfParameters[i],sizeof(pointer),bw,nil);
end;
returncount:=1;
if writefile(pipe, returncount, sizeof(returncount),bw,nil) then
begin
//the lua function is being called now
if readfile(pipe, returncount, sizeof(returncount), bw, nil) then
begin
if returncount>0 then
begin
for i:=0 to returncount-1 do
begin
if readfile(pipe, vtb, sizeof(vtb), bw, nil) then
begin
case TParamType(vtb) of
ptNil, ptUnknown: exit(0);
ptBoolean:
begin
readfile(pipe, a, sizeof(a), bw, nil);
exit(a);
end;
ptInt64:
begin
readfile(pipe, v, sizeof(v), bw, nil);
exit(v);
end;
ptNumber:
begin
readfile(pipe, d, sizeof(d), bw, nil);
exit(trunc(d));
end;
ptString:
begin
readfile(pipe, stringlength, sizeof(stringlength), bw, nil);
getmem(s, stringlength+1);
readfile(pipe, s[0], stringlength, bw, nil);
s[stringlength]:=#0;
try
result:=StrToInt(s);
except
end;
end;
end;
end else
begin
CELUA_Error;
exit;
end;
end;
end;
end;
end;
end;
end;
end;
CELUA_Error;
end;
finally
cs.leave;
end;
end;
function CELUA_ExecuteFunction_Internal(script: pchar; parameters: UINT_PTR; async: boolean=false): UINT_PTR;
var
command: byte;
bw: dword;
l: integer;
p: qword; //biggest common denominator
r: qword;
begin
if pipe=INVALID_HANDLE_VALUE then
CELUA_Initialize(CELUA_ServerName);
bw:=0;
r:=0;
cs.enter;
try
if pipe<>INVALID_HANDLE_VALUE then
begin
if async then
command:=4 //async
else
command:=1; //sync
if writefile(pipe, command,sizeof(command), bw, nil) then
begin
l:=strlen(script);
if writefile(pipe, l, sizeof(l), bw, nil) then
begin
if writefile(pipe, script^, l, bw, nil) then
begin
p:=parameters;
if writefile(pipe, p, sizeof(p), bw, nil) then
begin
//get the result (also 8 bytes, even for a 32-bit app)
if ReadFile(pipe, r, sizeof(r), bw, nil) then
result:=r
else
CELUA_Error;
end;
end
else
CELUA_Error;
end
else
CELUA_Error;
end
else
CELUA_Error;
end;
finally
cs.leave;
end;
end;
function CELUA_ExecuteFunction(script: pchar; parameters: UINT_PTR): UINT_PTR; stdcall;
begin
result:=CELUA_ExecuteFunction_Internal(script, parameters, false);
end;
function CELUA_ExecuteFunctionAsync(script: pchar; parameters: UINT_PTR): UINT_PTR; stdcall;
begin
result:=CELUA_ExecuteFunction_Internal(script, parameters, true);
end;
function CELUA_GetFunctionReferenceFromName(functionname: pchar): integer; stdcall;
begin
result:=CELUA_ExecuteFunction(pchar('return createRef('+functionname+')'), 0);
end;
function CELUA_Initialize(pipename: pchar): BOOL; stdcall;
begin
if cs=nil then
cs:=TCriticalSection.create;
if pipename<>CELUA_ServerName then
strcopy(CELUA_ServerName,pipename);
cs.enter;
try
if pipe<>INVALID_HANDLE_VALUE then
closehandle(pipe);
pipe:=CreateFile(pchar('\\.\pipe\'+pipename), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0);
result:=pipe<>INVALID_HANDLE_VALUE;
finally
cs.leave;
end;
end;
initialization
ZeroMemory(@CELUA_ServerName,255);
strcopy(CELUA_ServerName,pchar('CELUASERVER'));
end.
|
{$include kode.inc}
unit kode_osc_polyblep;
// Polynomial Bandlimited Step
// http://martin-finke.de/blog/articles/audio-plugins-018-polyblep-oscillator/
// http://www.kvraudio.com/forum/viewtopic.php?f=33&t=375517
// look at:
// http://www.kvraudio.com/forum/viewtopic.php?t=398553
// http://code.google.com/p/foo-plugins/source/browse/trunk/incubator/foo-yc20/polyblep.cpp?r=211
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
function KOsc_Saw_PolyBlep(t,dt:Single) : Single; inline;
function KOsc_Squ_PolyBlep(t,dt:Single) : Single; inline;
function KOsc_Tri_PolyBlep(t,dt:Single; out x1:Single) : Single; inline;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
function KPolyBlep(t,dt:Single) : Single; inline;
begin
// 0 <= t < 1
if t < dt then
begin
t /= dt;
result := t+t - t*t - 1; // 2 * (t - t^2/2 - 0.5)
end
// -1 < t < 0
else if t > (1-dt) then
begin
t := (t-1) / dt;
result := t*t + t+t + 1; // 2 * (t^2/2 + t + 0.5)
end
else result := 0;
end;
//----------------------------------------------------------------------
//----------------------------------------------------------------------
function KOsc_Saw_PolyBlep(t,dt:Single) : Single; inline;
var
saw : Single;
begin
// Correct phase, so it would be in line with sin(2.*M_PI * t)
t += 0.5;
if t >= 1 then t -= 1;
saw := 2*t - 1;
saw -= KPolyBlep(t,dt);
result := saw;
end;
//----------------------------------------------------------------------
function KOsc_Squ_PolyBlep(t,dt:Single) : Single; inline;
var
saw{,saw2} : Single;
begin
// Correct phase, so it would be in line with sin(2.*M_PI * t)
{t += 0.5;
if t >= 1 then t -= 1;}
saw := 2*t - 1;
saw -= KPolyBlep(t,dt);
result := saw;
t += 0.5;
if t >= 1 then t -= 1;
saw := 2*t - 1;
saw -= KPolyBlep(t,dt);
result -= saw;
end;
//----------------------------------------------------------------------
function KOsc_Tri_PolyBlep(t,dt:Single; out x1:Single) : Single; inline;
var
a : single;
begin
a := KOsc_Squ_PolyBlep(t,dt);
result := (dt * a) + ((1 - dt) * x1);
x1 := result;
result *= 4;
end;
//----------------------------------------------------------------------
end.
//----------------------------------------------------------------------
(*
http://www.kvraudio.com/forum/viewtopic.php?p=5965741#p5965741
function poly_blep(t, dt)
{
if (t < dt)
{
t = t/dt - 1;
return -t*t;
}
else if (t > 1 - dt)
{
t = (t - 1)/dt + 1;
return t*t;
}
else
{
return 0;
}
}
// Setup oscillator.
double freq = 220; // Hz
double pw = 0.5; // [0.0..1.0]
double phase = 0;
double phase_inc = freq / sample_rate;
// Generate samples.
for (int i = 0; i < num_samples; ++i)
{
// Start with naive PW square.
double sample;
if (phase < pw) { sample = 1; }
else { sample = -1; }
// Correct rising discontinuity.
sample = sample + poly_blep(phase, phase_inc);
// Correct falling discontinuity.
double phase2 = phase + 1 - pw;
phase2 = phase2 - floor(phase2);
sample = sample - poly_blep(phase2, phase_inc);
// Increment phase for next sample.
phase = phase + phase_inc;
phase = phase - floor(phase);
// Output current sample.
output_buffer[i] = sample;
}
*)
//----------------------------------------------------------------------
{
http://www.kvraudio.com/forum/viewtopic.php?p=5939531#p5939531
desc:Naive saw
slider1:440<20,20000,1>Frequency (Hz)
@slider
dt = slider1 / srate;
@sample
y = 2*t - 1;
t += dt;
t -= floor(t);
spl0 = spl1 = 0.25 * y;
desc:PolyBLEP saw
slider1:440<20,20000,1>Frequency (Hz)
@slider
dt = slider1 / srate;
@sample
y1 = y0;
y0 = 0;
t += dt;
t -= floor(t);
t < dt ? (
x = t / dt;
y1 -= 0.5*x*x;
x = 1 - x;
y0 += 0.5*x*x;
);
y0 += t;
y1 = 2*y1 - 1;
spl0 = spl1 = 0.25 * y1;
desc:Naive hard-sync saw
slider1:440<20,20000,1>Master (Hz)
slider2:1000<20,20000,1>Slave (Hz)
@slider
dt0 = slider1 / srate;
dt1 = slider2 / srate;
@sample
y = 2*t1 - 1;
t0 += dt0;
t0 -= floor(t0);
t1 += dt1;
t1 -= floor(t1);
t0 < dt0 ? t1 = t0 / dt0 * dt1;
spl0 = spl1 = 0.25 * y;
desc:PolyBLEP hard-sync saw
slider1:440<20,20000,1>Master (Hz)
slider2:1000<20,20000,1>Slave (Hz)
@slider
dt0 = slider1 / srate;
dt1 = slider2 / srate;
@sample
y1 = y0;
y0 = 0;
t0 += dt0;
t0 -= floor(t0);
t1 += dt1;
t1 -= floor(t1);
t0 < dt0 ? t1 = t0 / dt0 * dt1;
t = t0;
n = ceil(dt1 / dt0);
a = dt1 / dt0 - (n - 1);
loop(n,
t < dt0 ? (
x = t / dt0;
y1 -= a * 0.5*x*x;
x = 1 - x;
y0 += a * 0.5*x*x;
);
t += 1 - dt0 / dt1;
t -= floor(t);
a = 1;
);
y0 += t1;
y1 = 2*y1 - 1;
spl0 = spl1 = 0.25 * y1;
}
|
{
Change persistent flag on selected references.
Collapse and expand cell group to see changes.
}
unit UserScript;
var
bPersistent: boolean;
function Initialize: integer;
var
i: integer;
begin
i := MessageDlg('Set [YES] or clear [NO] Persistent flag?', mtConfirmation, [mbYes, mbNo, mbCancel], 0);
if i = mrYes then bPersistent := true else
if i = mrNo then bPersistent := false else begin
Result := 1;
Exit;
end;
end;
function Process(e: IInterface): integer;
var
s: string;
begin
s := Signature(e);
if (s <> 'REFR') and (s <> 'ACHR') and (s <> 'ACRE') and (s <> 'PGRE') and (s <> 'PMIS') and (s <> 'PHZD') then
Exit;
SetIsPersistent(e, bPersistent);
end;
end.
|
unit uInterface;
interface
type
IFileRead = interface
['{0C1716F3-ABD8-4145-A869-9842ACEFE703}']
procedure ReadToFile;
end;
IFileWrite = interface
['{0F549E12-7F75-4214-957C-8C048CDF6B29}']
procedure SaveToFile;
end;
implementation
end.
|
{**********************************************************
* Copyright (c) Zeljko Cvijanovic Teslic RS/BiH
* www.zeljus.com
* Created by: 30-8-15 19:28:32
***********************************************************}
unit AZCEditFile;
{$mode objfpc}{$H+}
{$modeswitch unicodestrings}
{$namespace zeljus.com.units}
interface
uses androidr15, Rjava, AZCDialogs;
type
{ AEditFile }
AEditFile = class(AZCDialog,
ACDialogInterface.InnerOnClickListener)
private
fContext : ACContext;
fFileName: JLString;
fEditText: AWEditText;
fHorizontalScropllView : AWHorizontalScrollView;
strict protected
procedure LoadFile;
procedure WriteFile;
public
constructor create(para1: ACContext; aFileName: JLString); overload; //override;
procedure show; overload; override;
//ACDialogInterface.InnerOnClickListener
procedure onClick(para1: ACDialogInterface; para2: jint); overload;
// procedure onCreate(para1: AOBundle); overload; override;
end;
implementation
uses ADBDataBase;
{ AEditFile }
procedure AEditFile.onClick(para1: ACDialogInterface; para2: jint);
begin
case para2 of
-1: WriteFile;
end;
end;
procedure AEditFile.LoadFile;
var
reader: JIBufferedReader;
line: JLString;
Data: JLString;
begin
line := string(''); Data := string('');
if checkExistsFile(fFileName) then begin
reader := JIBufferedReader.create((JIFileReader.create(fFileName)));
while not (line = nil) do begin
try
line := reader.readLine;
if line <> nil then
Data := JLString(Data).concat(line).concat(string(#10));
finally
end;
end;
end;
fEditText.setText(Data);
end;
procedure AEditFile.WriteFile;
var
fw: JIFileWriter;
begin
fw:= JIFileWriter.create(fFileName);
fw.append(fEditText.getText.toString);
fw.close;
end;
constructor AEditFile.create(para1: ACContext; aFileName: JLString);
begin
fContext := para1;
fFileName := aFileName;
inherited create(fContext);
// setIcon(R.drawable.ic_launcher);
// setIcon(AAActivity(para1).getPackageManager.getApplicationIcon(AAActivity(para1).getApplicationInfo));
setTitle(JLString('EDIT INI FILE '));
fHorizontalScropllView := AWHorizontalScrollView.create(fContext);
fEditText:= AWEditText.create(fContext);
fHorizontalScropllView.addView(fEditText);
setView(fHorizontalScropllView);
setButton(JLString('Save'), Self);
setButton2(JLString('Cancel'), Self);
end;
procedure AEditFile.show;
begin
LoadFile;
inherited show;
end;
end.
|
unit LuaApplication;
{
This unit will be used to register TCanvas class methods to lua
}
{$mode delphi}
interface
uses
Classes, SysUtils, forms, lua, lualib, lauxlib, LuaHandler, fpcanvas, LCLType, LCLIntf;
implementation
uses luaclass, luaobject;
function application_bringToFront(L: PLua_State): integer; cdecl;
begin
TApplication(luaclass_getClassObject(L)).BringToFront;
result:=0;
end;
function application_processMessages(L: PLua_State): integer; cdecl;
begin
TApplication(luaclass_getClassObject(L)).ProcessMessages;
result:=0;
end;
function application_terminate(L: PLua_State): integer; cdecl;
begin
TApplication(luaclass_getClassObject(L)).Terminate;
result:=0;
end;
function application_minimize(L: PLua_State): integer; cdecl;
begin
TApplication(luaclass_getClassObject(L)).Minimize;
result:=0;
end;
function application_getExeName(L: PLua_State): integer; cdecl;
var
app: TApplication;
begin
result:=0;
app:=luaclass_getClassObject(L);
lua_pushstring(L, app.ExeName);
result:=1;
end;
function application_getMainFormOnTaskBar(L: PLua_State): integer; cdecl;
var
app: TApplication;
begin
result:=0;
app:=luaclass_getClassObject(L);
lua_pushboolean(L, not app.MainFormOnTaskBar); //bug in laz 2.0.6, it's inverted
result:=1;
end;
function application_setMainFormOnTaskBar(L: PLua_State): integer; cdecl;
var
app: TApplication;
begin
result:=0;
if lua_gettop(L)>=1 then
begin
app:=luaclass_getClassObject(L);
app.MainFormOnTaskBar:=not lua_toboolean(L,1);
end;
end;
function application_getTitle(L: PLua_State): integer; cdecl;
var
app: TApplication;
begin
result:=0;
app:=luaclass_getClassObject(L);
lua_pushstring(L, app.Title);
result:=1;
end;
function application_setTitle(L: PLua_State): integer; cdecl;
begin
TApplication(luaclass_getClassObject(L)).title:=Lua_ToString(L, 1);
result:=0;
end;
function application_getIcon(L: PLua_State): integer; cdecl;
begin
luaclass_newClass(L, TApplication(luaclass_getClassObject(L)).Icon);
result:=1;
end;
function application_setIcon(L: PLua_State): integer; cdecl;
begin
result:=0;
TApplication(luaclass_getClassObject(L)).icon:=lua_ToCEUserData(L, 1);
end;
procedure application_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
begin
object_addMetaData(L, metatable, userdata);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'bringToFront', application_bringToFront);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'processMessages', application_processMessages);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'terminate', application_terminate);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'minimize', application_minimize);
Luaclass_addPropertyToTable(L, metatable, userdata, 'Title', application_getTitle, application_setTitle);
Luaclass_addPropertyToTable(L, metatable, userdata, 'Icon', application_getIcon, application_setIcon);
Luaclass_addPropertyToTable(L, metatable, userdata, 'ExeName', application_getExeName, nil);
Luaclass_addPropertyToTable(L, metatable, userdata, 'MainFormOnTaskBar', application_getMainFormOnTaskBar, application_setMainFormOnTaskBar);
end;
initialization
luaclass_register(Tapplication, application_addMetaData);
end.
|
๏ปฟnamespace Sugar.Test;
interface
uses
Sugar,
Sugar.Xml,
Sugar.TestFramework;
type
DocumentTest = public class (Testcase)
private
Data: XmlDocument;
public
method Setup; override;
method DocumentElement;
method DocumentType;
method NodeType;
method Element;
method AddChild;
method RemoveChild;
method ReplaceChild;
method CreateAttribute;
method CreateXmlNs;
method CreateCDataSection;
method CreateComment;
method CreateElement;
method CreateProcessingInstruction;
method CreateTextNode;
method GetElementsByTagName;
method FromFile;
method FromBinary;
method FromString;
method CreateDocument;
method Save;
end;
implementation
method DocumentTest.Setup;
begin
Data := XmlDocument.CreateDocument;
Assert.IsNotNull(Data);
end;
method DocumentTest.AddChild;
begin
Assert.IsNull(Data.DocumentElement);
Assert.CheckInt(0, Data.ChildCount);
Data.AddChild(Data.CreateElement("root"));
Assert.IsNotNull(Data.DocumentElement);
Assert.CheckInt(1, Data.ChildCount);
Assert.IsException(->Data.AddChild(Data.CreateElement("root"))); //only one root element
Assert.IsException(->Data.AddChild(nil));
Assert.IsException(->Data.AddChild(Data.CreateAttribute("id")));
Assert.IsException(->Data.AddChild(Data.CreateTextNode("Test")));
Data.AddChild(Data.CreateComment("Comment"));
Assert.CheckInt(2, Data.ChildCount);
Data.AddChild(Data.CreateProcessingInstruction("xml-stylesheet", "type=""text/xsl"" href=""style.xsl"""));
end;
method DocumentTest.CreateAttribute;
begin
var Item := Data.CreateElement("root");
Assert.IsNotNull(Item);
Data.AddChild(Item);
Item.AddChild(Data.CreateXmlNs("cfg", "http://example.com/config/"));
Assert.CheckInt(1, length(Item.GetAttributes));
Item := Data.CreateElement("item");
Data.DocumentElement.AddChild(Item);
var Value := Data.CreateAttribute("id");
Value.Value := "0";
Assert.IsNotNull(Value);
Item.SetAttributeNode(Value);
Assert.CheckInt(1, length(Item.GetAttributes));
Assert.CheckString("0", Item.GetAttribute("id"));
Value := Data.CreateAttribute("cfg:Saved", "http://example.com/config/");
Value.Value := "true";
Assert.IsNotNull(Value);
Item.SetAttributeNode(Value);
Assert.CheckInt(2, length(Item.GetAttributes));
Assert.CheckString("true", Item.GetAttribute("Saved", "http://example.com/config/"));
Assert.IsException(->Data.CreateAttribute(nil));
Assert.IsException(->Data.CreateAttribute("<xml>"));
Assert.IsException(->Data.CreateAttribute(nil, "http://example.com/config/"));
Assert.IsException(->Data.CreateAttribute("cfg:Saved", nil));
Assert.IsException(->Data.CreateAttribute("<abc>", "http://example.com/config/"));
end;
method DocumentTest.CreateXmlNs;
begin
var Item := Data.CreateElement("root");
Assert.IsNotNull(Item);
Data.AddChild(Item);
Item.AddChild(Data.CreateXmlNs("cfg", "http://example.com/config/"));
Assert.CheckInt(1, length(Item.GetAttributes));
Assert.IsException(->Data.CreateXmlNs(nil, "http://example.com/config/"));
Assert.IsException(->Data.CreateXmlNs("cfg", nil));
Assert.IsException(->Data.CreateXmlNs("<xml>", "http://example.com/config/"));
end;
method DocumentTest.CreateCDataSection;
begin
var Item := Data.CreateElement("root");
Assert.IsNotNull(Item);
Data.AddChild(Item);
var Value := Data.CreateCDataSection("Text");
Assert.IsNotNull(Value);
Item.AddChild(Value);
Assert.CheckInt(1, Item.ChildCount);
Assert.CheckBool(true, Item[0].NodeType = XmlNodeType.CDATA);
Assert.CheckString("Text", Item.ChildNodes[0].Value);
end;
method DocumentTest.CreateComment;
begin
var Item := Data.CreateElement("root");
Assert.IsNotNull(Item);
Data.AddChild(Item);
var Value := Data.CreateComment("Comment");
Assert.IsNotNull(Value);
Item.AddChild(Value);
Assert.CheckInt(1, Item.ChildCount);
Assert.CheckBool(true, Item[0].NodeType = XmlNodeType.Comment);
Assert.CheckString("Comment", Item.ChildNodes[0].Value);
end;
method DocumentTest.CreateDocument;
begin
var Item := XmlDocument.CreateDocument;
Assert.IsNotNull(Item);
end;
method DocumentTest.CreateElement;
begin
var Item := Data.CreateElement("root");
Assert.IsNotNull(Item);
Data.AddChild(Item);
Assert.CheckInt(1, Data.ChildCount);
Assert.CheckBool(true, Data.Item[0].NodeType = XmlNodeType.Element);
Assert.CheckString("root", Data.Item[0].LocalName);
end;
method DocumentTest.CreateProcessingInstruction;
begin
var Item := Data.CreateElement("root");
Assert.IsNotNull(Item);
Data.AddChild(Item);
var Value := Data.CreateProcessingInstruction("Custom", "Save=""true""");
Assert.IsNotNull(Value);
Item.AddChild(Value);
Assert.CheckInt(1, Item.ChildCount);
Assert.CheckBool(true, Item[0].NodeType = XmlNodeType.ProcessingInstruction);
Value := Item[0] as XmlProcessingInstruction;
Assert.CheckString("Custom", Value.Target);
Assert.CheckString("Save=""true""", Value.Data);
end;
method DocumentTest.CreateTextNode;
begin
var Item := Data.CreateElement("root");
Assert.IsNotNull(Item);
Data.AddChild(Item);
var Value := Data.CreateTextNode("Text");
Assert.IsNotNull(Value);
Item.AddChild(Value);
Assert.CheckInt(1, Item.ChildCount);
Assert.CheckBool(true, Item[0].NodeType = XmlNodeType.Text);
Assert.CheckString("Text", Item.ChildNodes[0].Value);
end;
method DocumentTest.DocumentElement;
begin
Assert.IsNull(Data.DocumentElement);
Assert.CheckInt(0, Data.ChildCount);
var Value := Data.CreateElement("root");
Assert.IsNotNull(Value);
Data.AddChild(Value);
Assert.IsNotNull(Data.DocumentElement);
Assert.CheckInt(1, Data.ChildCount);
Assert.CheckBool(true, Data.DocumentElement.Equals(Value));
end;
method DocumentTest.DocumentType;
begin
Assert.IsNull(Data.DocumentType);
Data := XmlDocument.FromString(XmlTestData.CharXml);
Assert.IsNotNull(Data.DocumentType);
Assert.CheckString("-//W3C//DTD XHTML 1.0 Transitional//EN", Data.DocumentType.PublicId);
Assert.CheckString("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", Data.DocumentType.SystemId);
end;
method DocumentTest.Element;
begin
Data := XmlDocument.FromString(XmlTestData.PIXml);
Assert.IsNotNull(Data.Element["Root"]);
Assert.IsNotNull(Data["Readers"]);
var Value := Data["User"];
Assert.IsNotNull(Value);
Assert.CheckString("First", Value.GetAttribute("Name"));
Assert.IsNull(Data[nil]);
end;
method DocumentTest.FromBinary;
begin
var Bin := new Binary(XmlTestData.PIXml.ToByteArray);
Data := XmlDocument.FromBinary(Bin);
Assert.IsNotNull(Data);
Assert.CheckInt(3, Data.ChildCount);
Assert.IsNotNull(Data.Element["Root"]);
Assert.IsNotNull(Data["Readers"]);
end;
method DocumentTest.FromFile;
begin
var File := Sugar.IO.Folder.UserLocal.CreateFile("sugartest.xml", false);
try
//File.WriteText(XmlTestData.PIXml);
Sugar.IO.FileUtils.WriteText(File.Path, XmlTestData.PIXml);
Data := XmlDocument.FromFile(File);
Assert.IsNotNull(Data);
Assert.CheckInt(3, Data.ChildCount);
Assert.IsNotNull(Data.Element["Root"]);
Assert.IsNotNull(Data["Readers"]);
finally
File.Delete;
end;
end;
method DocumentTest.FromString;
begin
Data := XmlDocument.FromString(XmlTestData.PIXml);
Assert.IsNotNull(Data);
Assert.CheckInt(3, Data.ChildCount);
Assert.IsNotNull(Data.Element["Root"]);
Assert.IsNotNull(Data["Readers"]);
end;
method DocumentTest.GetElementsByTagName;
begin
Data := XmlDocument.FromString(XmlTestData.PIXml);
var Actual := Data.GetElementsByTagName("User");
var Expected := new Sugar.Collections.List<String>;
Expected.Add("First");
Expected.Add("Second");
Expected.Add("Third");
Expected.Add("Admin");
Assert.CheckInt(4, length(Actual));
for i: Integer := 0 to length(Actual) - 1 do begin
Assert.CheckBool(true, Actual[i].NodeType = XmlNodeType.Element);
Assert.CheckBool(true, Expected.Contains(Actual[i].GetAttribute("Name")));
end;
Actual := Data.GetElementsByTagName("mail", "http://example.com/config/");
Assert.CheckInt(1, length(Actual));
Assert.CheckBool(true, Actual[0].NodeType = XmlNodeType.Element);
Assert.CheckString("first@example.com", Actual[0].Value);
end;
method DocumentTest.NodeType;
begin
Assert.CheckBool(true, Data.NodeType = XmlNodeType.Document);
end;
method DocumentTest.RemoveChild;
begin
Assert.IsNull(Data.DocumentElement);
Assert.CheckInt(0, Data.ChildCount);
Data.AddChild(Data.CreateElement("root"));
Assert.IsNotNull(Data.DocumentElement);
Assert.CheckInt(1, Data.ChildCount);
Data.RemoveChild(Data.DocumentElement);
Assert.IsNull(Data.DocumentElement);
Assert.CheckInt(0, Data.ChildCount);
Assert.IsException(->Data.RemoveChild(nil));
end;
method DocumentTest.ReplaceChild;
begin
Assert.IsNull(Data.DocumentElement);
Assert.CheckInt(0, Data.ChildCount);
Data.AddChild(Data.CreateElement("root"));
Assert.IsNotNull(Data.DocumentElement);
Assert.CheckInt(1, Data.ChildCount);
Assert.CheckString("root", Data.DocumentElement.LocalName);
var Value := Data.CreateElement("items");
Data.ReplaceChild(Data.DocumentElement, Value);
Assert.CheckInt(1, Data.ChildCount);
Assert.CheckString("items", Data.DocumentElement.LocalName);
Assert.IsException(->Data.ReplaceChild(nil, Data.DocumentElement));
Assert.IsException(->Data.ReplaceChild(Data.DocumentElement, nil));
Assert.IsException(->Data.ReplaceChild(Data.CreateElement("NotExisting"), Data.DocumentElement));
end;
method DocumentTest.Save;
begin
var File := Sugar.IO.Folder.UserLocal.CreateFile("sugartest.xml", false);
try
Data := XmlDocument.FromString(XmlTestData.CharXml);
Assert.IsNotNull(Data);
Data.Save(File);
Data := XmlDocument.FromFile(File);
Assert.IsNotNull(Data);
Assert.IsNotNull(Data.DocumentType);
Assert.CheckString("-//W3C//DTD XHTML 1.0 Transitional//EN", Data.DocumentType.PublicId);
Assert.CheckString("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", Data.DocumentType.SystemId);
Assert.IsNotNull(Data["Book"]);
Data := XmlDocument.CreateDocument;
Data.AddChild(Data.CreateElement("items"));
Data.DocumentElement.AddChild(Data.CreateElement("item"));
Data.DocumentElement.AddChild(Data.CreateElement("item"));
Data.DocumentElement.AddChild(Data.CreateElement("item"));
Data.Save(File, new XmlDocumentDeclaration("1.0", "UTF-8", true));
Data := XmlDocument.FromFile(File);
Assert.IsNotNull(Data);
Assert.IsNull(Data.DocumentType);
Assert.IsNotNull(Data.DocumentElement);
Assert.CheckString("items", Data.DocumentElement.LocalName);
Assert.CheckInt(3, Data.DocumentElement.ChildCount);
finally
File.Delete;
end;
end;
end.
|
{******************************************************************************}
{ }
{ ScreensaverKit }
{ }
{ The contents of this file are subject to the MIT License (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at https://opensource.org/licenses/MIT }
{ }
{ 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 ScreensaverKit.SettingUtils.pas. }
{ }
{ Contains an embedabble and kiosk like web browser class }
{ }
{ Unit owner: Misel Krstovic }
{ Last modified: March 2, 2019 }
{ }
{******************************************************************************}
unit ScreensaverKit.WebBrowserUtils;
interface
uses
MSHTML, SHDocVw, WinInet, IdIcmpClient, Types;
const
// Local system has a valid connection to the Internet, but it might or might
// not be currently connected.
INTERNET_CONNECTION_CONFIGURED = $40;
// Local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_LAN = $02;
// Local system uses a modem to connect to the Internet
INTERNET_CONNECTION_MODEM = $01;
// Local system is in offline mode.
INTERNET_CONNECTION_OFFLINE = $20;
// Local system uses a proxy server to connect to the Internet
INTERNET_CONNECTION_PROXY = $04;
// Local system has RAS installed.
INTERNET_RAS_INSTALLED = $10;
SCREENSAVERKIT_USER_AGENT = 'ScreensaverKit/1.0';
SCREENSAVERKIT_PING_HOST = 'https://www.google.com/';
type
TScreensaverWebBrowser = class(TWebBrowser)
// TODO: Refactor TWebBrowser from example
class function CheckInternetConnection: boolean;
end;
implementation
class function TScreensaverWebBrowser.CheckInternetConnection: boolean;
var
InetState: DWORD;
hHttpSession, hReqUrl: HInternet;
begin
Result := InternetGetConnectedState(@InetState, 0);
if (Result (*and (InetState and INTERNET_CONNECTION_CONFIGURED = INTERNET_CONNECTION_CONFIGURED) *)) then begin
// So far we ONLY know there's a valid connection. See if we can grab some
// known URL ...
hHttpSession := InternetOpen(
PChar(SCREENSAVERKIT_USER_AGENT),
INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0
);
try
hReqUrl := InternetOpenURL(hHttpSession, PChar(SCREENSAVERKIT_PING_HOST), nil, 0, 0, 0);
Result := hReqUrl <> nil;
InternetCloseHandle(hReqUrl);
finally
InternetCloseHandle(hHttpSession);
end;
end else begin
if (InetState and INTERNET_CONNECTION_OFFLINE = INTERNET_CONNECTION_OFFLINE) then
Result := False; // We know for sure we are offline.
end;
end;
end.
|
unit Configuration.AppConfig;
interface
type
IAppConfiguration = interface(IInvokable)
['{974BDED1-7D77-4C34-8D3B-76EBADD58D9E}']
procedure Initialize;
function GetSourceFolders: TArray<string>;
function GetOutputFile: string;
function HasFilters: boolean;
function GetFilterComplexityLevel: integer;
function GetFilterMethodLength: integer;
end;
implementation
end.
|
unit PointerscanSettingsIPConnectionList;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ExtCtrls, StdCtrls, Controls;
resourcestring
rsPSSICLAdd = 'Add';
rsPSSICLRemove = 'Remove';
rsPSSICLHost = 'Host';
rsPSSICLPort = 'Port';
rsPSSICLPassword = 'Password';
rsPSSICLStable = 'Stable';
type
TIpinfo=class(tobject)
private
edtHost: TEdit;
edtPort: Tedit;
edtPassword: Tedit;
cbStable: TCheckBox;
resizing: boolean;
function getHost: string;
function getPort: string;
function getPassword: string;
function getStableState: boolean;
procedure setHost(h: string);
procedure setPort(p: string);
procedure setPassword(p: string);
procedure setStableState(s: boolean);
public
procedure clean;
constructor create(TheOwner: TComponent);
destructor destroy; override;
property host: string read getHost write setHost;
property port: string read getPort write setPort;
property password: string read getPassword write setPassword;
property stable: boolean read getStableState write setStableState;
end;
TIpList=class(TPanel)
private
btnAdd: TButton;
btnRemove: TButton;
ipinfo: TList;
lblHost: TLabel;
lblPassword: TLabel;
lblPort: TLabel;
lblStable: TLabel;
resizingmyself: boolean;
fOnWantedToDeleteLastItem: TNotifyEvent;
pnlHPPS: tpanel;
procedure addIpInfo(sender: tobject);
procedure removeIpInfo(sender: tobject);
procedure updatePositions;
function getCount: integer;
function getItem(index: integer): TIpInfo;
public
procedure clear;
procedure add;
destructor destroy; override;
constructor create(TheOwner: TComponent); override;
property OnWantedToDeleteLastItem: TNotifyEvent read fOnWantedToDeleteLastItem write fOnWantedToDeleteLastItem;
property count: integer read getCount;
property item[index: integer]: TIpInfo read getItem; default;
end;
implementation
procedure TIpinfo.setHost(h: string);
begin
edtHost.text:=h;
end;
procedure TIpinfo.setPort(p: string);
begin
edtPort.text:=p;
end;
procedure TIpinfo.setPassword(p: string);
begin
edtPassword.text:=p;
end;
procedure TIpinfo.setStableState(s: boolean);
begin
cbStable.checked:=s;
end;
function TIpinfo.getHost: string;
begin
result:=edtHost.Text;
end;
function TIpinfo.getPort: string;
begin
result:=edtPort.text;
end;
function TIpinfo.getPassword: string;
begin
result:=edtPassword.text;
end;
function TIpinfo.getStableState: boolean;
begin
result:=cbStable.Checked;
end;
procedure TIpinfo.clean;
begin
edtHost.text:='';
edtPort.text:='52737';
edtPassword.text:='';
cbStable.checked:=false;
end;
constructor TIpinfo.create(TheOwner: TComponent);
begin
inherited create;
if TheOwner is TWinControl then
begin
edtHost:=Tedit.create(theowner);
edtPort:=Tedit.create(theowner);
edtPort.text:='52737';
edtPassword:=Tedit.create(theowner);
cbStable:=TCheckBox.create(theowner);
cbStable.caption:='';
cbStable.autoSize:=true;
edtPassword.PasswordChar:='*';
edtPassword.MaxLength:=255;
edtHost.Parent:=twincontrol(theowner);
edtPort.Parent:=twincontrol(theowner);
edtPassword.Parent:=twincontrol(theowner);
cbStable.Parent:=twincontrol(theowner);
end;
end;
destructor TIpinfo.destroy;
var p: TWinControl;
begin
p:=cbStable.Parent;
p.BeginUpdateBounds;
cbStable.free;
edtPassword.free;
edtPort.free;
edtHost.free;
p.EndUpdateBounds;
end;
{}
function TIpList.getCount: integer;
begin
result:=ipinfo.count;
end;
function TIpList.getItem(index: integer): TIpInfo;
begin
if index<count then
result:=TIpInfo(ipinfo[index])
else
result:=nil;
end;
procedure TIpList.addIpInfo(sender: tobject);
var newipinfo: TIpInfo;
begin
newipinfo:=TIpInfo.Create(pnlHPPS);
ipinfo.Add(newipinfo);
updatePositions;
end;
procedure TIpList.removeIpInfo(sender: tobject);
begin
if ipinfo.count>1 then
begin
tipinfo(ipinfo[ipinfo.count-1]).Free;
ipinfo.delete(ipinfo.count-1);
end
else
begin
tipinfo(ipinfo[ipinfo.count-1]).clean;
if assigned(fOnWantedToDeleteLastItem) then
fOnWantedToDeleteLastItem(self);
end;
updatePositions;
end;
procedure TIpList.updatePositions;
var
currentipinfo: TIpInfo;
i: integer;
currenttop: integer;
begin
resizingmyself:=true;
try
currentipinfo:=nil;
currenttop:=lblHost.height;
for i:=0 to ipinfo.count-1 do
begin
currentipinfo:=TIpinfo(ipinfo[i]);
currentipinfo.edtHost.Constraints.MinWidth:=canvas.TextWidth(' XXX.XXX.XXX.XXX ');
currentipinfo.edtHost.Constraints.MaxWidth:=canvas.TextWidth(' XXX.XXX.XXX.XXX ');
currentipinfo.edtPort.Constraints.MinWidth:=canvas.TextWidth('XXXXX');
currentipinfo.edtPort.Constraints.MaxWidth:=canvas.TextWidth(' XXXXX ');
currentipinfo.edtPassword.Constraints.MinWidth:=canvas.TextWidth('XXXXXXXXX');
currentipinfo.edtPassword.Constraints.MaxWidth:=canvas.TextWidth(' XXXXXXXXX ');
end;
// height:=btnAdd.top+btnAdd.height+4;
finally
resizingmyself:=false;
end;
end;
procedure TIpList.add;
begin
addIpInfo(self);
end;
procedure TIpList.clear;
begin
while ipinfo.count>0 do
begin
TIpinfo(ipinfo[0]).free;
ipinfo.Delete(0);
end;
end;
destructor TIpList.destroy;
begin
if btnAdd<>nil then
btnAdd.free;
if btnRemove<>nil then
btnRemove.free;
clear;
if ipinfo<>nil then
freeandnil(ipinfo);
inherited destroy;
end;
constructor TIpList.create(TheOwner: TComponent);
begin
inherited create(TheOwner);
ipinfo:=TList.create;
bevelouter:=bvNone;
visible:=false;
if theowner is TWinControl then
begin
parent:=TWinControl(TheOwner);
pnlHPPS:=tpanel.Create(self);
pnlHPPS.BevelOuter:=bvNone;
pnlHPPS.parent:=self;
pnlHPPS.ChildSizing.ControlsPerLine:=4;
pnlHPPS.ChildSizing.EnlargeHorizontal:=crsHomogenousChildResize;
pnlHPPS.ChildSizing.HorizontalSpacing:=3;
pnlHPPS.ChildSizing.VerticalSpacing:=1;
pnlHPPS.ChildSizing.Layout:=cclLeftToRightThenTopToBottom;
pnlHPPS.autosize:=true;
//pnlHPPS.color:=$ff0000;
//width:=twincontrol(TheOwner).ClientWidth;
btnAdd:=tbutton.create(self);
btnRemove:=tbutton.create(self);
btnAdd.caption:=rsPSSICLAdd;
btnRemove.caption:=rsPSSICLRemove;
btnAdd.parent:=self;
btnRemove.parent:=self;
btnAdd.autosize:=true;
btnRemove.AutoSize:=true;
btnRemove.ClientWidth:=self.Canvas.GetTextWidth(btnRemove.caption)+8;
btnAdd.Width:=btnRemove.Width;
btnAdd.OnClick:=@addIpInfo;
btnRemove.OnClick:=@removeIpInfo;
lblHost:=tlabel.create(self);
lblHost.caption:=rsPSSICLHost;
lblHost.parent:=pnlhpps;
lblPort:=tlabel.create(self);
lblPort.caption:=rsPSSICLPort;
lblPort.parent:=pnlhpps;
lblPassword:=tlabel.Create(self);
lblPassword.caption:=rsPSSICLPassword;
lblPassword.parent:=pnlhpps;
lblStable:=tlabel.create(self);
lblStable.caption:=rsPSSICLStable;
lblStable.parent:=pnlhpps;
pnlHPPS.AnchorSideTop.control:=self;
pnlHPPS.AnchorSideTop.Side:=asrTop;
pnlHPPS.AnchorSideLeft.control:=self;
pnlHPPS.AnchorSideLeft.Side:=asrLeft;
btnAdd.AnchorSideTop.control:=pnlHPPS;
btnAdd.AnchorSideTop.Side:=asrbottom;
btnAdd.AnchorSideLeft.control:=self;
btnAdd.AnchorSideLeft.Side:=asrleft;
btnAdd.BorderSpacing.Top:=3;
btnRemove.AnchorSideTop.control:=btnAdd;
btnRemove.AnchorSideTop.Side:=asrTop;
btnRemove.AnchorSideLeft.control:=btnAdd;
btnRemove.AnchorSideLeft.Side:=asrRight;
btnRemove.BorderSpacing.Left:=4;
autosize:=true;
//color:=$00ff00;
addIpInfo(self);
end;
end;
end.
|
unit Geometry;
interface
uses Geom1, Graphics, Windows;
type
TCheckingType = ( CC_ONLY_INTEGER, CC_ONLY_FLOAT, CC_NUMBERS,
CC_LETTERS, CC_ALL );
BresenhamesLine = object
InCanvas : TCanvas;
p1, p2 : TPoint3D;
linecolor : longint;
negative : boolean;
IsEnded : boolean;
GetCurPoint : TPoint3D;
dx, dy, sx, sy : integer;
d, d1, d2 : integer;
x, y, i : integer;
constructor Init( x1, y1, x2, y2 : integer; vCanvas : TCanvas );
procedure Negate;
procedure NextMovement;
procedure ShowLine ( col : longint );
destructor Done;
end;
procedure MakeNormal ( var n : TVector; p1, p2, p3 : TMyPoint);
function col_bounds( col0: TColor; b1, b2: byte; col: byte ): TColor;
function Correctness ( StringLine: string; CheckingType: TCheckingType ): boolean;
implementation
procedure HLine( vCanvas : TCanvas; x1, x2, y: Integer; c: Byte );
begin
vCanvas.Pen.Color := RGB( c, c, c );
vCanvas.MoveTo( x1, y );
vCanvas.LineTo( x2, y );
end;
procedure DrawPoly( vCanvas : TCanvas; x1,y1, x2,y2, x3,y3: Integer; c: Byte);
var
p1,p2,p3: TPoint3D; {Die 3 Eckpunkte}
ml, mr: LongInt; {Steigungen der Dreiecksseiten}
y: Integer; {Laufvariable}
xstart, xend: LongInt;{Anfang und Ende der horiz. Linie}
xs, xe: Integer;
{
ml / \ mr
/ /
/ / mr
// }
BEGIN
{Zuerst werden die Eckpunkte nach ihrer Y-Koordinate sortiert.
p1.y >= p2.y >= p3.y}
if y1 >= y2 then begin
p1.x:=x2;
p1.y:=y2;
p3.x:=x1;
p3.y:=y1;
end
else begin
p1.x:=x1;
p1.y:=y1;
p3.x:=x2;
p3.y:=y2;
end;
if (y3 >= p1.y) and (y3 <= p3.y) then begin {Position ist in der Mitte}
p2.x:=x3;
p2.y:=y3;
end
else if y3 < p1.y then begin {oberster Punkt}
p2:=p1;
p1.x:=x3;
p1.y:=y3;
end
else if y3 > p3.y then begin {unterster Punkt}
p2:=p3;
p3.x:=x3;
p3.y:=y3;
end;
{Steigung der lรngsten Geraden bestimmen nach der Formel
x2-x1
m= ------
y2-y1 }
{Falls das Dreieck eine Linie bildet}
if (p3.y=p2.y) and (p3.y=p1.y) then
exit;
ml:=Trunc((p3.x - p1.x) SHL 16) div (p3.y - p1.y); {lรngere Gerade}
{Falls p1 und p2 die gleiche Y-Koordinate besitzen, zeichnet man nur eine
horizontale Linie zwischen den Punkten. Das erste Teilstรck besteht also
praktisch aus einer Linie}
if p2.y-p1.y <> 0 then begin
{Steigung auf dem ersten Teilstรck}
mr:=Trunc((p2.x - p1.x) SHL 16) div (p2.y - p1.y);
{erstes Teilstรck zeichnen}
xstart:=p1.x SHL 16;
xend:=p1.x SHL 16;
HLine ( vCanvas, p1.x, p1.x, p1.y, c );
for y:=p1.y+1 to p2.y do begin {Zeilenweise Linien zeichnen}
Inc(xstart,ml);
Inc(xend,mr);
HLine ( vCanvas, xstart SHR 16, xend SHR 16, y, c );
end;
end
else begin {Das erste Teilstรck war eine Linie}
xstart:=p1.x shl 16;
xend:=p2.x shl 16;
HLine ( vCanvas, p1.x, p2.x, p1.y , c );
end;
{Falls P3 und P2 die gleiche Y-Koordinate haben, nur eine horiz. Linie
zeichnen}
if p3.y-p2.y <> 0 then begin
{Steigung auf dem zweiten Teilstรck berechnen}
mr:=((p3.x - p2.x) SHL 16) div (p3.y - p2.y);
for y:=p2.y+1 to p3.y do begin
Inc(xstart,ml);
Inc(xend,mr);
HLine ( vCanvas, xstart SHR 16, xend SHR 16, y, c );
end;
end
{Das zweite Teilstรck ist eine Linie}
else
HLine ( vCanvas, p2.x, p3.x, p2.y, c );
END;
constructor BresenhamesLine.Init ( x1, y1, x2, y2 : integer; vCanvas : TCanvas );
begin
InCanvas := vCanvas;
Negative := false;
IsEnded := false;
p1.x := x1;
p1.y := y1;
p1.z := InCanvas.Pixels [ x1, y1 ] and $ff;
p2.x := x2;
p2.y := y2;
p2.z := InCanvas.Pixels [ x2, y2 ] and $ff;
dx := abs ( x2 - x1 );
dy := abs ( y2 - y1 );
if x2 >= x1
then sx := 1
else sx :=-1;
if y2 >= y1
then sy := 1
else sy :=-1;
if dy <= dx then begin
d1 := dy shl 1;
d := ( d1 ) - dx;
d2 := ( dy - dx ) shl 1;
GetCurPoint.x := p1.x;
GetCurPoint.y := p1.y;
GetCurPoint.z := p1.z;
x := p1.x + sx;
y := p1.y;
i := 1;
end
else begin
d1 := dx shl 1;
d := ( d1 ) - dy;
d2 := ( dx - dy ) shl 1;
GetCurPoint.x := p1.x;
GetCurPoint.y := p1.y;
GetCurPoint.z := p1.z;
x := p1.x;
y := p1.y + sy;
i := 1;
end;
end;
procedure BresenhamesLine.Negate;
var
vd, vx, vy, vi : integer;
c : longint;
begin
Negative := not Negative;
vd := d;
vi := i;
vx := x;
vy := y;
if dy <= dx then begin
while vi <= dx do begin
if vd > 0 then begin
vd := vd + d2;
vy := vy + sy;
end
else vd := vd + d1;
c := 255 - ( InCanvas.Pixels [ vx, vy ] and $ff );
InCanvas.Pixels [ vx, vy ] := RGB ( c, c, c );
vi := vi + 1;
vx := vx + sx;
end
end
else begin
while vi <= dy do begin
if vd > 0 then begin
vd := vd + d2;
vx := vx + sx;
end
else vd := vd + d1;
c := 255 - ( InCanvas.Pixels [ vx, vy ] and $ff );
InCanvas.Pixels [ vx, vy ] := RGB ( c, c, c );
// c := clWhite - InCanvas.Pixels [ vx, vy ];
// varCanvas.Pixels [ vx, vy ] := c;
vi := vi + 1;
vy := vy + sy;
end
end;
end;
procedure BresenhamesLine.NextMovement;
begin
if dy <= dx then begin
IsEnded := not ( i <= dx );
if not IsEnded then begin
if d > 0 then begin
d := d + d2;
y := y + sy;
end
else d := d + d1;
GetCurPoint.x := x;
GetCurPoint.y := y;
GetCurPoint.z := ( p1.z + ( p2.z - p1.z ) * i / dx );
i := i + 1;
x := x + sx;
end
end
else begin
IsEnded := not ( i <= dy );
if not IsEnded then begin
if d > 0 then begin
d := d + d2;
x := x + sx;
end
else d := d + d1;
GetCurPoint.x := x;
GetCurPoint.y := y;
GetCurPoint.z := ( p1.z + ( p2.z - p1.z ) * i / dy );
i := i + 1;
y := y + sy;
end
end;
end;
procedure BresenhamesLine.ShowLine ( col : longint );
var
vd, vx, vy, vi : integer;
begin
vd := d;
vi := i;
vx := x;
vy := y;
if dy <= dx then begin
while vi <= dx do begin
if vd > 0 then begin
vd := vd + d2;
vy := vy + sy;
end
else vd := vd + d1;
InCanvas.Pixels [ vx, vy ] := RGB ( col, col, col );
vi := vi + 1;
vx := vx + sx;
end
end
else begin
while vi <= dy do begin
if vd > 0 then begin
vd := vd + d2;
vx := vx + sx;
end
else vd := vd + d1;
InCanvas.Pixels [ vx, vy ] := RGB ( col, col, col );
vi := vi + 1;
vy := vy + sy;
end
end;
end;
destructor BresenhamesLine.Done;
begin
end;
procedure MakeNormal ( var n : TVector; p1, p2, p3 : TMyPoint );
var
d : real;
a, b : TVector;
begin
a.x := p1.x - p2.x;
a.y := p1.y - p2.y;
a.z := p1.z - p2.z;
b.x := p3.x - p2.x;
b.y := p3.y - p2.y;
b.z := p3.z - p2.z;
n.x := a.x * b.y - a.y * b.x;
n.y := a.z * b.x - a.x * b.z;
n.z := a.y * b.z - a.z * b.y;
d := sqrt ( n.x * n.x + n.y * n.y + n.z * n.z );
if d = 0 then d := 1;
n.x := n.x / d;
n.y := n.y / d;
n.z := n.z / d;
end;
function col_bounds( col0: TColor; b1, b2: byte; col: byte ): TColor;
var
r, g, b: byte;
begin
r := col0 and $ff;
r := trunc( r / 255 * (integer( b2 - b1 ) * col / 255 + b1) );
g := ( col0 and $ff00 ) shr 8;
g := trunc( g / 255 * (integer( b2 - b1 ) * col / 255 + b1) );
b := ( col0 and $ff0000 ) shr 16;
b := trunc( b / 255 * (integer( b2 - b1 ) * col / 255 + b1) );
col_bounds := r or ( g shl 8 ) or ( b shl 16 );
end;
function Correctness ( StringLine: string; CheckingType: TCheckingType ): boolean;
var
i: integer;
correct: boolean;
c: char;
begin
correct := true;
for i := 1 to length ( StringLine ) do begin
c := StringLine[i];
case CheckingType of
CC_ONLY_INTEGER: correct := correct and ( c in ['0'..'9','-'] );
CC_ONLY_FLOAT: correct := correct and ( c in ['0'..'9','-',','] );
CC_NUMBERS: correct := correct and ( c in ['0'..'9','-',','] );
CC_LETTERS: correct := correct and ( c in ['A'..'Z','a'..'z','ล'..'ร','ล'..'ห'] );
CC_ALL: correct := true;
end;
if not correct then break;
end;
Correctness := correct;
end;
end.
|
{
ะะพัะพะณะพะน ะดััะณ! ะขั ะดะตะปะฐะตัั ะฟะตัะฒัะต ัะฐะณะธ ะฒ ะฟัะพะณัะฐะผะผะธัะพะฒะฐะฝะธะธ ะธ
ะธัะฟะพะปัะทัะตัั ะดะปั ััะพะณะพ ะฟัะพััะพะน ะธ ัะดะพะฑะฝัะน ัะทัะบ Pascal. ะะปั
ะฑะพะปะตะต ะฑััััะพะณะพ ััะฒะฐะธะฒะฐะฝะธั ัะตะฑะต ะฝัะถะฝั ะฟัะพัััะต ะธ ะดะพัััะฟะฝัะต ะดะปั
ะฟะพะฝะธะผะฐะฝะธั ะฟัะธะผะตัั. ะฏะทัะบ ะะะกะะะะฌ ะฟะพะทะฒะพะปัะตั ะฝะฐััะดั ั
ะฝะตะฑะพะปััะธะผะธ ะฝะตัะปะพะถะฝัะผะธ ะฟัะพะณัะฐะผะผะฐะผะธ ัะพะทะดะฐะฒะฐัั
ััััะบัััะธัะพะฒะฐะฝะฝัะต ะฟัะพะณัะฐะผะผั ัััะดะพัะผะบะธั
ะธ ัะปะพะถะฝัั
ะฒััะธัะปะตะฝะธะน.
ะงัะพะฑั ะฟะพะปัะทะพะฒะฐัะตะปั ะฟัะธ ัะพััะฐะฒะปะตะฝะธะธ ะฟัะพะณัะฐะผะผ ะฝะต ะดะพะฟััะบะฐะป
ะพัะธะฑะพะบ ะธะปะธ ะผะพะณ ะธั
ะพะฑะฝะฐััะถะธัั ะธั
ะธ ะธัะฟัะฐะฒะธัั, ัะธัะปะพ ัะฐะทะปะธัะฝัั
ะพะฟะตัะฐัะพัะพะฒ ัะทัะบะฐ ัะฒะตะดะตะฝะพ ะดะพ ะผะธะฝะธะผัะผะฐ. ะะฐะฝะฝัะน ะฟัะธะผะตั ะฟะพะผะพะถะตั
ัะตะฑะต ะฑััััะตะต ะพัะฒะพะธัััั ั ะฝะพะฒัะผ ะดะปั ัะตะฑั ัะทัะบะพะผ, ะพะบัะฝััััั ะฒ
ััะพั ะฟัะตะบัะฐัะฝัะน ะผะธั ะฝะฐะฟะธัะฐะฝะธั ะกะะะะฅ ะฟัะพะณัะฐะผะผ, ะบะพะบะพััะต
ะฑัะดัั, ะผะพะถะตั, ะดะฐะถะต ะตัั ะปัััะต, ัะตะผ ััะฐ. ะ ััะพะผ ะฟัะธะผะตัะต
ะดะตะผะพะฝัััะธัััััั ะธ ััััะบัััะฐ ะฟัะพะณัะฐะผะผ ะฝะฐ ะฟะฐัะบะฐะปะต, ัะฟะพัะพะฑั
ะธัะฟะพะปัะทะพะฒะฐะฝะธั ัะธะบะปะพะฒ, ััััะบัััะฝะพะต ะฟัะพะณัะฐะผะผะธัะพะฒะฐะฝะธั,
ะบะพะฝััะฐะฝัั, ัะธะฟั, ะฟะตัะตะผะตะฝะฝัะต, ััะปะพะฒะธั ะธ ะผะฝะพะณะพะต ะดััะณะพะต. ะ,
ััะพ ัะฐะผะพะต ะฟัะธััะฝะพะต, ััะฐ ะฟัะพะณัะฐะผะผะฐ ะ ะะะะขะะะข!!! Hะพ, ั
ะพัั ัะตะฑะต
ัะบะฐะทะฐัั, ะฒ ััะพะน ะฟัะพะณัะฐะผะผะต ัะผััะปะตะฝะฝะพ ะดะพะฟััะตะฝะฐ ะพะดะฝะฐ ะพัะธะฑะบะฐ, ะธ,
ะตัะปะธ ัั ัะผะพะถะตัั ะฝะฐะนัะธ ะตั, ัั ัะผะพะถะตัั ััะธัะฐัั, ััะพ ะฟะตัะฒัะน
ััะพะบ ัั ััะฒะพะธะป.
}
program uuuuuuuuuuuuuuuuuuuuuuuuuuuuu ( input , output ) ;
type uu = byte ; const uuuuuu = uu ( true ) ; uuu = ( (
uuuuuu + uuuuuu ) * ( uuuuuu + uuuuuu ) * ( uuuuuu + uuuuuu
) ) ; uuuuuuuu = ( uuu * ( uuuuuu + uuuuuu ) ) ; uuuuuuuuuu
= ( uuu * ( uuuuuu + uuuuuu ) - ( ( uuuuuu + uuuuuu ) +
uuuuuu ) ) ; uuuuuuuuu = ( ( uuu + uuuuuu ) * uuu ) ;
uuuuuuuuuuuuu = ( ( uuu + ( uuuuuu + uuuuuu ) ) * ( uuu + (
uuuuuu + uuuuuu ) ) + uuuuuu ) ; uuuuuuuuuuuuuu = ( ( (
uuuuuu + uuuuuu ) + ( ( uuuuuu + uuuuuu ) + uuuuuu ) ) * uuu
+ ( ( uuuuuu + uuuuuu ) + uuuuuu ) + uuuuuu ) ;
uuuuuuuuuuuuuuu = ( uuuuuuuu * ( uuuuuu + uuuuuu ) ) ; uuuuu
= ( uuu * ( ( ( uuuuuu + uuuuuu ) + uuuuuu ) + ( ( uuuuuu +
uuuuuu ) + uuuuuu ) + ( ( uuuuuu + uuuuuu ) + uuuuuu ) +
uuuuuu ) + ( ( uuuuuu + uuuuuu ) + uuuuuu ) + ( uuuuuu +
uuuuuu ) + ( uuuuuu + uuuuuu ) ) ; uuuuuuuuuuuuuuuu = (
uuuuuuuuuuuuu - uuuuuu * uuuuuu ) ; uuuuuuuuuuuuuuuuu = (
uuuuuuuuuuuuuuu + uuuuuu * uuuuuu ) ; uuuuuuuuuuuu = (
uuuuuuuuuuuuuuu/ ( uuuuuu + uuuuuu ) - ( ( uuuuuu + uuuuuu )
+ uuuuuu ) - ( ( uuuuuu + uuuuuu ) + uuuuuu ) ) ; uuuuuuu =
( uuuuuuuuuuuuuuuu - uuuuuu - uuuuuuuuuuuuuuuuu * ( uuuuuu +
uuuuuu + + uuuu ) + uuuuuu + uuuuuu ) ; uuuuuuuuuuuuuuuuuu :
array [ uuuuuu - uuuuuu..uuuuuuuu - ( uuuuuu + uuuuuu ) -
uuuuuu - uuuuuu ] of uu = ( uuuuuuuuu , uuuuuuuuuuuuu , (
( uuu + ( uuuuuu + uuuuuu ) ) * ( uuu + ( uuuuuu + uuuuuu )
) + uuu ) , ( ( uuu + ( uuuuuu + uuuuuu ) ) * ( uuu + (
uuuuuu + uuuuuu ) ) + uuu ) , ( ( uuu + ( uuuuuu + uuuuuu )
) * ( uuu + ( uuuuuu + uuuuuu ) ) + ( uuu + ( ( uuuuuu +
uuuuuu ) + uuuuuu ) ) ) , uuuuuuuuuuuuuu , uuuuuuuuuuuuuuu ,
uuuuu , ( ( uuu + ( uuuuuu + uuuuuu ) ) * ( uuu + ( uuuuuu +
uuuuuu ) ) + ( uuu + ( ( uuuuuu + uuuuuu ) + uuuuuu ) ) ) ,
( ( ( uuu + ( uuuuuu + uuuuuu ) ) * ( uuu + ( uuuuuu +
uuuuuu ) ) + ( uuu + ( ( uuuuuu + uuuuuu ) + uuuuuu ) ) + (
( uuuuuu + uuuuuu ) + uuuuuu ) ) ) , ( ( uuu + ( uuuuuu +
uuuuuu ) ) * ( uuu + ( uuuuuu + uuuuuu ) ) + uuu ) ,
uuuuuuuuuuuuuuuu , uuuuuuuuuuuuuuuuu ) ; procedure uuuu ;
assembler ; asm mov ax , ( ( uuuuuu + uuuuuu ) + uuuuuu ) ;
int uuuuuuuu end ; procedure uuuuuuuuuuuuuuuuuuuu ; var u :
uu ; uuuuuuuuuuuuuuuuuuu : array [ uuuuuuu .. uuuuuuuuuu * (
uuuuuu + uuuuuu ) ] of uu absolute ( uuuuuuuuuuuuuu + ( (
uuuuuu + uuuuuu ) + uuuuuu ) ) * uuuuuuuuuuuuuuuu * ( uuu +
( uuuuuu + uuuuuu ) ) + uuuuuuuuuuuuu + ( ( uuuuuu + uuuuuu
) + uuuuuu ) : uuuuuuu ; begin uuuu ; for u := uuuuuu -
uuuuuu * uuuuuu to uuuuuuuuuu - uuuuuu do
uuuuuuuuuuuuuuuuuuu [ u * ( uuuuuu + uuuuuu ) ] :=
uuuuuuuuuuuuuuuuuu [ u ] end ; begin uuuuuuuuuuuuuuuuuuuu
end .
|
unit FMain;
interface
uses
System.Math,
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
System.Diagnostics,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Objects,
FMX.Controls.Presentation,
FMX.StdCtrls,
FMX.Layouts,
FMX.ListBox,
FMX.Edit,
FMX.EditBox,
FMX.SpinBox,
MandelbrotGenerator;
const
PALETTE_BITS = 7;
PALETTE_SIZE = 1 shl PALETTE_BITS;
PALETTE_MASK = PALETTE_SIZE - 1;
type
TFormMain = class(TForm)
PaintBox: TPaintBox;
LayoutOptions: TLayout;
LabelPrecision: TLabel;
ComboBoxPrecision: TComboBox;
ComboBoxMagnification: TComboBox;
LabelMagnification: TLabel;
ButtonUpdateOrCancel: TButton;
LabelGradientOffset: TLabel;
LabelTime: TLabel;
TrackBarGradientOffset: TTrackBar;
TimerUpdate: TTimer;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure PaintBoxPaint(Sender: TObject; Canvas: TCanvas);
procedure ButtonUpdateOrCancelClick(Sender: TObject);
procedure TrackBarGradientOffsetChange(Sender: TObject);
procedure PaintBoxClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TimerUpdateTimer(Sender: TObject);
private
{ Private declarations }
FPalette: array [0..PALETTE_SIZE - 1] of TAlphaColor;
FBitmap: TBitmap;
FGenerator: TMandelbrotGenerator;
FSurface: TSurface;
FStopwatch: TStopwatch;
FOrigOptionsWidth: Single;
procedure CreatePalette;
procedure Update;
procedure UpdateStats;
procedure UpdateDisplay;
procedure EnableControls(const Enable: Boolean);
procedure Generate(const APrecision: TPrecision;
const AMagnification: Double; const AMaxIterations: Integer);
procedure GeneratorTerminate(Sender: TObject);
procedure ShutdownGenerator;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
{$R palette.res}
procedure TFormMain.ButtonUpdateOrCancelClick(Sender: TObject);
begin
if (ButtonUpdateOrCancel.Text = 'Update') then
Update
else
ShutdownGenerator;
end;
procedure TFormMain.CreatePalette;
var
Stream: TStream;
Palette: array [0..PALETTE_SIZE * 3 - 1] of Byte;
I: Integer;
C: TAlphaColorRec;
begin
Stream := TResourceStream.Create(HInstance, 'PALETTE', RT_RCDATA);
try
Assert(Stream.Size = Length(Palette));
Stream.ReadBuffer(Palette[0], Length(Palette));
finally
Stream.Free;
end;
for I := 0 to PALETTE_SIZE - 1 do
begin
{$IFDEF MSWINDOWS}
C.R := Palette[I * 3 + 0];
C.G := Palette[I * 3 + 1];
C.B := Palette[I * 3 + 2];
{$ELSE}
C.R := Palette[I * 3 + 2];
C.G := Palette[I * 3 + 1];
C.B := Palette[I * 3 + 0];
{$ENDIF}
C.A := 255;
FPalette[I] := C.Color;
end;
end;
procedure TFormMain.EnableControls(const Enable: Boolean);
begin
LabelPrecision.Enabled := Enable;
ComboBoxPrecision.Enabled := Enable;
LabelMagnification.Enabled := Enable;
ComboBoxMagnification.Enabled := Enable;
if (Enable) then
ButtonUpdateOrCancel.Text := 'Update'
else
ButtonUpdateOrCancel.Text := 'Cancel';
end;
procedure TFormMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ShutdownGenerator;
end;
procedure TFormMain.FormCreate(Sender: TObject);
var
I: Integer;
S: String;
begin
{ To test the use of TFormatSettings, set the default format settings to a
non-English locale. }
FormatSettings.DecimalSeparator := ',';
FormatSettings.ThousandSeparator := '.';
FBitmap := TBitmap.Create;
FBitmap.SetSize(TMandelbrotGenerator.WIDTH, TMandelbrotGenerator.HEIGHT);
FOrigOptionsWidth := LayoutOptions.Width;
CreatePalette;
ComboBoxMagnification.Items.BeginUpdate;
try
ComboBoxMagnification.Items.Add('1');
for I := 1 to 38 do
begin
S := '1e' + I.ToString;
if (I = 6) then
S := S + ' (need Double)'
else if (I = 14) then
S := S + ' (need DoubleDouble)'
else if (I = 31) then
S := S + ' (need QuadDouble)';
ComboBoxMagnification.Items.Add(S)
end;
finally
ComboBoxMagnification.Items.EndUpdate;
end;
ComboBoxMagnification.ItemIndex := 0;
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
FBitmap.Free;
end;
procedure TFormMain.FormResize(Sender: TObject);
begin
if (ClientWidth > ClientHeight) then
begin
{ Landscape }
LayoutOptions.Align := TAlignLayout.Left;
LayoutOptions.Width := FOrigOptionsWidth;
end
else
begin
{ Portrait }
LayoutOptions.Align := TAlignLayout.Top;
LayoutOptions.Height := TrackBarGradientOffset.Position.Y +
TrackBarGradientOffset.Height + LabelTime.Height + 16;
end;
end;
procedure TFormMain.Generate(const APrecision: TPrecision;
const AMagnification: Double; const AMaxIterations: Integer);
begin
ShutdownGenerator;
EnableControls(False);
FBitmap.Clear(TAlphaColors.Black);
FStopwatch := TStopwatch.StartNew;
FGenerator := TMandelbrotGenerator.Create(AMaxIterations, AMagnification,
APrecision);
FGenerator.OnTerminate := GeneratorTerminate;
FSurface := FGenerator.Surface;
UpdateStats;
UpdateDisplay;
TimerUpdate.Enabled := True;
end;
procedure TFormMain.GeneratorTerminate(Sender: TObject);
begin
TimerUpdate.Enabled := False;
UpdateStats;
UpdateDisplay;
EnableControls(True);
FGenerator := nil;
end;
procedure TFormMain.PaintBoxClick(Sender: TObject);
begin
{$IF Defined(DEBUG) and Defined(MSWINDOWS)}
{ Switch between portrait and landscape layout }
SetBounds(Left, Top, Height, Width);
{$ENDIF}
end;
procedure TFormMain.PaintBoxPaint(Sender: TObject; Canvas: TCanvas);
var
SR, DR: TRectF;
begin
if (FBitmap <> nil) then
begin
SR := RectF(0, 0, FBitmap.Width, FBitmap.Height);
DR := RectF(0, 0, PaintBox.Width, PaintBox.Height);
DR := SR.CenterAt(DR);
Canvas.DrawBitmap(FBitmap, SR, DR, 1);
end;
end;
procedure TFormMain.ShutdownGenerator;
begin
if (FGenerator <> nil) then
begin
FGenerator.Terminate;
FGenerator.WaitFor;
FGenerator.Free;
FGenerator := nil;
end;
end;
procedure TFormMain.TimerUpdateTimer(Sender: TObject);
begin
UpdateStats;
UpdateDisplay;
end;
procedure TFormMain.TrackBarGradientOffsetChange(Sender: TObject);
begin
LabelGradientOffset.Text := Format('Gradient offset: %.0f', [TrackBarGradientOffset.Value]);
UpdateDisplay;
end;
procedure TFormMain.Update;
var
Magnification: Double;
Precision: TPrecision;
Iterations: Integer;
begin
case ComboBoxPrecision.ItemIndex of
0: Precision := TPrecision.Single;
1: Precision := TPrecision.Double;
2: Precision := TPrecision.DoubleDouble;
3: Precision := TPrecision.QuadDouble;
else
Assert(False);
Precision := TPrecision.Single;
end;
Magnification := Power(10, ComboBoxMagnification.ItemIndex);
if (Magnification >= 1e11) then
Iterations := 5000
else if (Magnification >= 1e10) then
Iterations := 1000
else
Iterations := 200;
Generate(Precision, Magnification, Iterations);
end;
procedure TFormMain.UpdateDisplay;
var
Data: TBitmapData;
X, Y, PaletteOffset: Integer;
Iter: PInteger;
Dst: PAlphaColor;
begin
if (FSurface.Data <> nil) and (FBitmap.Map(TMapAccess.Write, Data)) then
try
PaletteOffset := System.Trunc(TrackBarGradientOffset.Value);
Iter := @FSurface.Data[0];
for Y := 0 to Data.Height - 1 do
begin
Dst := Data.GetScanline(Y);
for X := 0 to Data.Width - 1 do
begin
if (Iter^ < 0) then
Dst^ := TAlphaColors.Black
else
Dst^ := FPalette[(Iter^ + PaletteOffset) and PALETTE_MASK];
Inc(Iter);
Inc(Dst);
end;
end;
finally
FBitmap.Unmap(Data);
end;
PaintBox.Repaint;
end;
procedure TFormMain.UpdateStats;
var
Seconds: Double;
begin
Seconds := FStopwatch.Elapsed.TotalSeconds;
LabelTime.Text := Format('Elapsed: %.3f seconds', [Seconds]);
end;
end.
|
unit frmPropertiesUnit;
{
History
15 july 1999 - Initial release
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, inifiles;
type
TfrmProperties = class(TForm)
Label1: TLabel;
editServer: TEdit;
Label2: TLabel;
editPort: TEdit;
btnAccept: TButton;
btnCancel: TButton;
editUserName: TEdit;
Label3: TLabel;
editPassword: TEdit;
Label4: TLabel;
procedure btnAcceptClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FPort: integer;
FUsername: string;
FPassword: string;
FServer: string;
FIniFile: TIniFile;
procedure SaveValues;
procedure LoadValues;
public
{ Public declarations }
property Server: string read FServer;
property Port: integer read FPort;
property Username: string read FUsername;
property Password: string read FPassword;
end;
var
frmProperties: TfrmProperties;
implementation
{$R *.DFM}
{ TfrmProperties }
procedure TfrmProperties.SaveValues;
begin
FServer:= editServer.Text;
FPort:= StrToInt(editPort.Text);
FUsername:= editUsername.Text;
FPassword:= editPassword.Text;
with FIniFile do
begin
WriteString('server settings', 'server', FServer);
WriteInteger('server settings', 'port', FPort);
WriteString('server settings', 'username', FUsername);
WriteString('server settings', 'password', FPassword);
end;
end;
procedure TfrmProperties.LoadValues;
begin
with FIniFile do
begin
FServer:= ReadString('server settings', 'server', '');
FPort:= ReadInteger('server settings', 'port', 119);
FUsername:= ReadString('server settings', 'username', '');
FPassword:= ReadString('server settings', 'password', '');
end;
editServer.Text:= FServer;
editPort.Text:= IntToStr(FPort);
editUsername.Text:= FUsername;
editPassword.Text:= FPassword;
end;
procedure TfrmProperties.btnAcceptClick(Sender: TObject);
begin
SaveValues;
ModalResult:= 0;
Close;
end;
procedure TfrmProperties.btnCancelClick(Sender: TObject);
begin
ModalResult:= -1;
Close;
end;
procedure TfrmProperties.FormCreate(Sender: TObject);
begin
FIniFile:= TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
LoadValues;
end;
procedure TfrmProperties.FormDestroy(Sender: TObject);
begin
FIniFile.Free;
end;
end.
|
unit PACCLinker;
{$i PACC.inc}
interface
uses SysUtils,Classes,Math,PUCU,PACCTypes,PACCGlobals,PACCRawByteStringHashMap,PACCPointerHashMap;
type TPACCLinker=class;
TPACCLinker=class
private
fInstance:TObject;
public
constructor Create(const AInstance:TObject); reintroduce; virtual;
destructor Destroy; override;
procedure AddImport(const ASymbolName,AImportLibraryName,AImportName:TPUCUUTF8String); virtual;
procedure AddExport(const ASymbolName,AExportName:TPUCUUTF8String); virtual;
procedure AddImports(const AInput:TPACCRawByteString;const AFileName:TPUCUUTF8String=''); virtual;
procedure AddExports(const AInput:TPACCRawByteString;const AFileName:TPUCUUTF8String=''); virtual;
procedure AddObject(const AObjectStream:TStream;const AObjectFileName:TPUCUUTF8String=''); virtual;
procedure AddArchive(const AArchiveStream:TStream;const AArchiveFileName:TPUCUUTF8String=''); virtual;
procedure AddResources(const AResourcesStream:TStream;const AResourcesFileName:TPUCUUTF8String=''); virtual;
procedure Link(const AOutputStream:TStream;const AOutputFileName:TPUCUUTF8String=''); virtual;
published
property Instance:TObject read fInstance;
end;
TPACCLinkerClass=class of TPACCLinker;
implementation
uses PACCInstance;
constructor TPACCLinker.Create(const AInstance:TObject);
begin
inherited Create;
fInstance:=AInstance;
end;
destructor TPACCLinker.Destroy;
begin
inherited Destroy;
end;
procedure TPACCLinker.AddImport(const ASymbolName,AImportLibraryName,AImportName:TPUCUUTF8String);
begin
end;
procedure TPACCLinker.AddExport(const ASymbolName,AExportName:TPUCUUTF8String);
begin
end;
procedure TPACCLinker.AddImports(const AInput:TPACCRawByteString;const AFileName:TPUCUUTF8String='');
const WhiteSpaceChars=[#0..#32];
IdentChars=['a'..'z','A'..'Z','0'..'9','_','@','?','$','.',#$80..#$ff{UTF-8}];
var Index,Len,StartIndex:TPACCInt32;
LibraryName,SymbolName,ImportName:TPACCRawByteString;
begin
Len:=length(AInput);
Index:=1;
while Index<=Len do begin
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
StartIndex:=Index;
while (Index<=Len) and (AInput[Index] in IdentChars) do begin
inc(Index);
end;
if StartIndex<Index then begin
LibraryName:=copy(AInput,StartIndex,Index-StartIndex);
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
if (Index<=Len) and (AInput[Index]='(') then begin
inc(Index);
while not ((Index>Len) or (AInput[Index]=')')) do begin
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
StartIndex:=Index;
while (Index<=Len) and (AInput[Index] in IdentChars) do begin
inc(Index);
end;
if StartIndex<Index then begin
SymbolName:=copy(AInput,StartIndex,Index-StartIndex);
ImportName:=SymbolName;
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
if (Index<=Len) and (AInput[Index]='=') then begin
inc(Index);
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
StartIndex:=Index;
while (Index<=Len) and (AInput[Index] in IdentChars) do begin
inc(Index);
end;
if StartIndex<Index then begin
ImportName:=copy(AInput,StartIndex,Index-StartIndex);
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
end else begin
TPACCInstance(Instance).AddError('Import file syntax error',nil,true);
end;
end;
AddImport(SymbolName,LibraryName,ImportName);
end else begin
TPACCInstance(Instance).AddError('Import file syntax error',nil,true);
end;
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
end;
if (Index<=Len) and (AInput[Index]=')') then begin
inc(Index);
end else begin
TPACCInstance(Instance).AddError('Import file syntax error',nil,true);
end;
end else begin
TPACCInstance(Instance).AddError('Import file syntax error',nil,true);
end;
end else begin
TPACCInstance(Instance).AddError('Import file syntax error',nil,true);
end;
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
end;
end;
procedure TPACCLinker.AddExports(const AInput:TPACCRawByteString;const AFileName:TPUCUUTF8String='');
const WhiteSpaceChars=[#0..#32];
IdentChars=['a'..'z','A'..'Z','0'..'9','_','@','$','.',#$80..#$ff{UTF-8}];
var Index,Len,StartIndex:TPACCInt32;
SymbolName,ExportName:TPACCRawByteString;
begin
Len:=length(AInput);
Index:=1;
while Index<=Len do begin
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
StartIndex:=Index;
while (Index<=Len) and (AInput[Index] in IdentChars) do begin
inc(Index);
end;
if StartIndex<Index then begin
SymbolName:=copy(AInput,StartIndex,Index-StartIndex);
ExportName:=SymbolName;
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
if (Index<=Len) and (AInput[Index]='=') then begin
inc(Index);
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
StartIndex:=Index;
while (Index<=Len) and (AInput[Index] in IdentChars) do begin
inc(Index);
end;
if StartIndex<Index then begin
ExportName:=copy(AInput,StartIndex,Index-StartIndex);
while (Index<=Len) and (AInput[Index] in WhiteSpaceChars) do begin
inc(Index);
end;
end else begin
TPACCInstance(Instance).AddError('Import file syntax error',nil,true);
end;
end;
AddExport(SymbolName,ExportName);
end else begin
TPACCInstance(Instance).AddError('Import file syntax error',nil,true);
end;
end;
end;
procedure TPACCLinker.AddObject(const AObjectStream:TStream;const AObjectFileName:TPUCUUTF8String='');
begin
end;
procedure TPACCLinker.AddArchive(const AArchiveStream:TStream;const AArchiveFileName:TPUCUUTF8String='');
const IMAGE_FILE_MACHINE_UNKNOWN=0;
type PSignature=^TSignature;
TSignature=array[0..7] of ansichar;
PHeader=^THeader;
THeader=packed record
Name:array[0..15] of ansichar; // Member name
Date:array[0..11] of ansichar; // Member date, seconds, decimal ASCII
UserID:array[0..5] of ansichar; // Member User ID, decimal ASCII
GroupID:array[0..5] of ansichar; // Member Group ID, decimal ASCII
FileMode:array[0..7] of ansichar; // Member file mode, octal
FileSize:array[0..9] of ansichar; // Member file size, decimal ASCII
HeaderEnd:array[0..1] of TPACCUInt8; // "`\n"
end;
PImportHeader=^TImportHeader;
TImportHeader=packed record
Sig1:TPACCUInt16;
Sig2:TPACCUInt16;
Version:TPACCUInt16;
Machine:TPACCUInt16;
TimeDateStamp:TPACCUInt32;
SizeOfData:TPACCUInt32;
OrdinalOrHint:TPACCUInt16;
BitData:TPACCUInt16;
end;
function TrimHeaderString(const s:TPACCRawByteString):TPACCRawByteString;
var i:TPACCInt32;
begin
result:=s;
for i:=length(result) downto 1 do begin
if not (result[i] in [#0..#32]) then begin
SetLength(result,i);
break;
end;
end;
end;
var Stream:TMemoryStream;
Signature:TSignature;
Header:THeader;
ImportHeader:TImportHeader;
Name:TPACCRawByteString;
FileSize:TPACCInt64;
begin
AArchiveStream.Seek(0,soBeginning);
if AArchiveStream.Size>=SizeOf(TSignature) then begin
AArchiveStream.ReadBuffer(Signature,SizeOf(TSignature));
if (Signature[0]='!') and
(Signature[1]='<') and
(Signature[2]='a') and
(Signature[3]='r') and
(Signature[4]='c') and
(Signature[5]='h') and
(Signature[6]='>') and
(Signature[7]=#10) then begin
while (AArchiveStream.Position+SizeOf(Header))<AArchiveStream.Size do begin
AArchiveStream.ReadBuffer(Header,SizeOf(Header));
if (Header.HeaderEnd[0]=$60) and (Header.HeaderEnd[1]=$0a) then begin
Name:=TrimHeaderString(Header.Name);
writeln(Name);
FileSize:=StrToInt(TrimHeaderString(Header.FileSize));
if FileSize>0 then begin
Stream:=TMemoryStream.Create;
try
if Stream.CopyFrom(AArchiveStream,FileSize)<>FileSize then begin
raise EReadError.Create('Stream read error');
end;
Stream.Seek(0,soBeginning);
if (Name='\') or (Name='/') then begin
end else if (Name='\\') or (Name='//') then begin
end else begin
if (Stream.Size>SizeOf(TImportHeader)) and
(PImportHeader(Stream.Memory)^.Sig1=IMAGE_FILE_MACHINE_UNKNOWN) and
(PImportHeader(Stream.Memory)^.Sig2=$ffff) then begin
// TODO: Short import library parsing
end else begin
AddObject(Stream,Name);
end;
end;
finally
Stream.Free;
end;
end;
end else begin
break;
end;
end;
end;
end;
end;
procedure TPACCLinker.AddResources(const AResourcesStream:TStream;const AResourcesFileName:TPUCUUTF8String='');
begin
end;
procedure TPACCLinker.Link(const AOutputStream:TStream;const AOutputFileName:TPUCUUTF8String='');
begin
end;
end.
|
unit URepositorioConsultor;
interface
uses
URepositorioDB
, UConsultor
, SqlExpr
;
type
TRepositorioConsultor = class(TRepositorioDB<TCONSULTOR>)
protected
//Atribui os dados do banco no objeto
procedure AtribuiDBParaEntidade(const coCONSULTOR: TCONSULTOR); override;
//Atribui os dados do objeto no banco
procedure AtribuiEntidadeParaDB(const coCONSULTOR: TCONSULTOR;
const coSQLQuery: TSQLQuery); override;
public
constructor Create;
end;
implementation
{ TRepositorioCOnsultor }
uses
UEntidade
, UMensagens
;
procedure TRepositorioConsultor.AtribuiDBParaEntidade(
const coCONSULTOR: TCONSULTOR);
begin
inherited;
coCONSULTOR.NOME := FSQLSelect.FieldByName(FLD_CONSULTOR_NOME).AsString;
coCONSULTOR.EMAIL := FSQLSelect.FieldByName(FLD_CONSULTOR_EMAIL).AsString;
coCONSULTOR.SEGMENTO := FSQLSelect.FieldByName(FLD_CONSULTOR_SEGMENTO).AsString;
end;
procedure TRepositorioConsultor.AtribuiEntidadeParaDB(
const coCONSULTOR: TCONSULTOR; const coSQLQuery: TSQLQuery);
begin
inherited;
coSQLQuery.ParamByName(FLD_CONSULTOR_NOME).AsString := coCONSULTOR.NOME;
coSQLQuery.ParamByName(FLD_CONSULTOR_EMAIL).AsString := coCONSULTOR.EMAIL;
coSQLQuery.ParamByName(FLD_CONSULTOR_SEGMENTO).AsString := coCONSULTOR.SEGMENTO;
end;
constructor TRepositorioConsultor.Create;
begin
Inherited Create(TCONSULTOR, TBL_CONSULTOR, FLD_ENTIDADE_ID, STR_CONSULTOR);
end;
end.
|
unit uTFTP;
{$mode objfpc}{$H+}
{ Simple Trival FTP Server based on RFC 1350
Ultibo (C) 2015 - SoftOz Pty Ltd. LGPLv2.1 with static linking exception
FPC (c) 1993-2015 Free Pascal Team. Modified Library GNU Public License
Lazarus (c) 1993-2015 Lazarus and Free Pascal Team. Modified Library GNU Public License
Other bits (c) 2016 pjde LGPLv2.1 with static linking exception
}
interface
uses
GlobalConfig,
GlobalConst,
Platform,
Threads,
SysUtils,
Classes,
Winsock2;
const
// TFTP opcodes
TFTP_RRQ = 1;
TFTP_WRQ = 2;
TFTP_DATA = 3;
TFTP_ACK = 4;
TFTP_ERROR = 5;
TFTP_OACK = 6;
// TFTP error codes
erUNDEFINED = 0;
erFILE_NOT_FOUND = 1;
erACCESS_VIOLATION = 2;
erALLOCATION_EXCEEDED = 3;
erILLEGAL_OPERATION = 4;
erUNKNOWN_TRANSFER_ID = 5;
erFILE_ALREADY_EXISTS = 6;
erNO_SUCH_USER = 7;
erOPTION_NEGOTIATION_FAILED = 8;
type
TMsgEvent = procedure (Sender : TObject; s : string);
TTFTPListener = class;
{ TFTPTransferThread }
TFTPTransferThread = class (TWinsock2UDPServerThread)
FStream : TMemoryStream;
function ReadByte : byte;
function ReadWord : Word;
function ReadString : string;
function Remaining : int64;
constructor Create (aListener : TWinsock2UDPServer);
destructor Destroy; override;
end;
{ TTransfer }
TTransfer = class
FileName : string;
FStream : TMemoryStream;
FListener : TTFTPListener;
Op : word;
TID : Word;
BlockNo : Word;
SockAddr : PSockAddr;
SockAddrLength : integer;
constructor Create (aListener : TTFTPListener);
destructor Destroy; override;
end;
{ TTFTPListener }
TTFTPListener = class (TWinsock2UDPListener)
FOnMsg : TMsgEvent;
FRebootOnImg : boolean;
private
TxStream : TMemoryStream;
procedure SetOnMsg (Value : TMsgEvent);
procedure AddByte (b : byte);
procedure AddWord (w : Word);
procedure AddString (s : string);
protected
Transfers : TList;
function GetTransfer (byID : Word) : TTransfer;
procedure RemoveTransfer (byID : Word); overload;
procedure RemoveTransfer (byTransfer : TTransfer); overload;
procedure DoMsg (s : string);
function DoExecute (aThread : TWinsock2UDPServerThread) : Boolean; override;
procedure DoCreateThread (aServer : TWinsock2UDPServer; var aThread : TWinsock2UDPServerThread);
public
constructor Create;
destructor Destroy; override;
procedure SendError (aTransfer : TTransfer; ErrCode : Word; ErrMsg : string); overload;
procedure SendError (aServer : TWinsock2UDPServer; ErrCode : Word; ErrMsg : string); overload;
procedure SendAck (aTransfer : TTransfer; BlockNo : Word);
procedure SendDataBlock (aTransfer : TTransfer; BlockNo : Word);
property OnMsg : TMsgEvent read FOnMsg write SetOnMsg;
property RebootOnImg : boolean read FRebootOnImg write FRebootOnImg;
end;
procedure SetOnMsg (MsgProc : TMsgEvent);
var
TFTP : TTFTPListener = nil;
implementation
procedure SetOnMsg (MsgProc : TMsgEvent);
begin
if Assigned (TFTP) then TFTP.OnMsg := MsgProc;
end;
{ TTransfer }
constructor TTransfer.Create (aListener : TTFTPListener);
begin
FStream := TMemoryStream.Create;
FListener := aListener;
FileName := '';
Op := 0;
TID := 0;
BlockNo := 0;
SockAddr := nil;
SockAddrLength := 0;
end;
destructor TTransfer.Destroy;
begin
FStream.Free;
if SockAddr <> nil then
begin
if FListener <> nil then FListener.ReleaseAddress (SockAddr, SockAddrLength);
SockAddr := nil;
end;
inherited Destroy;
end;
{ TFTPTransferThread }
function TFTPTransferThread.ReadByte: byte;
begin
Result := 0;
if Remaining > 0 then FStream.Read (Result, 1);
end;
function TFTPTransferThread.ReadWord : Word;
begin
Result := ReadByte * $100 + ReadByte;
end;
function TFTPTransferThread.ReadString : string;
var
ch : Char;
begin
Result := '';
ch := '~';
while (Remaining > 0) and (ch <> #0) do
begin
FStream.Read (ch, 1);
if ch <> #0 then Result := Result + ch;
end;
end;
function TFTPTransferThread.Remaining: int64;
begin
Result := FStream.Size - FStream.Position;
end;
constructor TFTPTransferThread.Create (aListener : TWinsock2UDPServer);
begin
inherited Create (aListener);
FStream := TMemoryStream.Create;
end;
destructor TFTPTransferThread.Destroy;
begin
FStream.Free;
inherited Destroy;
end;
constructor TTFTPListener.Create;
begin
inherited Create;
Threads.Min := 5;
Threads.Max := 10;
BufferSize := 1024;
BoundPort := 69;
Transfers := TList.Create;
FRebootOnImg := true;
FOnMsg := nil;
{ Define custom thread }
OnCreateThread := @DoCreateThread;
TxStream := TMemoryStream.Create;
end;
destructor TTFTPListener.Destroy;
var
i : integer;
begin
for i := 0 to Transfers.Count - 1 do TTransfer (Transfers[i]).Free;
Transfers.Free;
TxStream.Free;
inherited Destroy;
end;
procedure TTFTPListener.SendError (aTransfer : TTransfer; ErrCode : Word;
ErrMsg : string);
var
count : integer;
begin
TxStream.Clear;
count := 0;
AddWord (TFTP_ERROR);
AddWord (ErrCode);
AddString (ErrMsg);
SendToSocket (aTransfer.SockAddr, aTransfer.SockAddrLength, TxStream.Memory, TxStream.Size, count);
end;
procedure TTFTPListener.SendError (aServer : TWinsock2UDPServer; ErrCode : Word;
ErrMsg : string);
begin
TxStream.Clear;
AddWord (TFTP_ERROR);
AddWord (ErrCode);
AddString (ErrMsg);
SendDataTo (aServer.PeerAddress, aServer.PeerPort, TxStream.Memory, TxStream.Size);
end;
procedure TTFTPListener.SendAck (aTransfer : TTransfer; BlockNo : Word);
var
count : integer;
begin
TxStream.Clear;
count := 0;
AddWord (TFTP_ACK);
AddWord (BlockNo);
aTransfer.BlockNo := BlockNo;
SendToSocket (aTransfer.SockAddr, aTransfer.SockAddrLength, TxStream.Memory, TxStream.Size, count);
end;
procedure TTFTPListener.SendDataBlock (aTransfer: TTransfer; BlockNo : Word);
var
count : integer;
x, l : int64;
begin
TxStream.Clear;
count := 0;
AddWord (TFTP_DATA);
AddWord (BlockNo);
x := (int64 (BlockNo) - 1) * 512;
if (x >= 0) and (x < aTransfer.FStream.Size) then
begin
aTransfer.FStream.Seek (x, soFromBeginning);
l := aTransfer.FStream.Size - aTransfer.FStream.Position;
if l > 512 then l := 512;
TxStream.CopyFrom (aTransfer.FStream, l);
end;
aTransfer.BlockNo := BlockNo;
SendToSocket (aTransfer.SockAddr, aTransfer.SockAddrLength, TxStream.Memory, TxStream.Size, count);
end;
function display_string (s : string) : string;
var
i : integer;
begin
Result := '';
for i := 1 to length (s) do
if s[i] in [' '..'~'] then
Result := Result + s[i]
else
Result := Result + '[' + IntToHex (ord (s[i]), 2) + ']';
end;
function ErToStr (er : Word) : string;
begin
case er of
erUNDEFINED : Result := 'Undefined';
erFILE_NOT_FOUND : Result := 'File not found';
erACCESS_VIOLATION : Result := 'Access violation';
erALLOCATION_EXCEEDED : Result := 'Allocation exceeded';
erILLEGAL_OPERATION : Result := 'Illegal Operation';
erUNKNOWN_TRANSFER_ID : Result := 'Unknown transfer id';
erFILE_ALREADY_EXISTS : Result := 'File already exists';
erNO_SUCH_USER : Result := 'No such user';
erOPTION_NEGOTIATION_FAILED : Result := 'Option negotiation failed';
else Result := 'Unknown ' + IntToStr (er);
end;
end;
procedure TTFTPListener.SetOnMsg (Value : TMsgEvent);
begin
FOnMsg := Value;
DoMsg ('Messages active.');
end;
procedure TTFTPListener.AddByte (b: byte);
begin
TxStream.Write (b, 1);
end;
procedure TTFTPListener.AddWord (w : Word);
begin
AddByte (w div $100);
AddByte (w mod $100);
end;
procedure TTFTPListener.AddString (s : string);
begin
TxStream.Write (s[1], length (s));
AddByte (0);
end;
function TTFTPListener.GetTransfer (byID : Word): TTransfer;
var
i : integer;
begin
for i := 0 to Transfers.Count - 1 do
begin
Result := TTransfer (Transfers[i]);
if Result.TID = byID then exit;
end;
Result := nil;
end;
procedure TTFTPListener.RemoveTransfer (byID : Word);
var
aTransfer : TTransfer;
begin
aTransfer := GetTransfer (byID);
RemoveTransfer (aTransfer);
end;
procedure TTFTPListener.RemoveTransfer (byTransfer : TTransfer);
begin
if byTransfer <> nil then
begin
Transfers.Remove (byTransfer);
byTransfer.Free;
end;
end;
procedure TTFTPListener.DoMsg (s: string);
begin
if Assigned (FOnMsg) then FOnMsg (Self, s);
end;
function TTFTPListener.DoExecute (aThread : TWinsock2UDPServerThread) : Boolean;
var
op, er, bn : Word;
rm : int64;
fn, mode, msg : string;
aTransferThread : TFTPTransferThread;
aTransfer : TTransfer;
aFile : TFileStream;
begin
Result := inherited DoExecute (aThread);
if not Result then exit;
if aThread.Server.Count > 0 then
begin
aTransfer := GetTransfer (aThread.Server.PeerPort);
aTransferThread := TFTPTransferThread (aThread);
aTransferThread.FStream.Clear;
aTransferThread.FStream.Write (aThread.Server.Data^, aThread.Server.Count);
aTransferThread.FStream.Seek (0, soFromBeginning);
op := aTransferThread.ReadWord;
case op of
TFTP_RRQ :
begin
fn := aTransferThread.ReadString;
mode := aTransferThread.ReadString;
DoMsg ('Upload of "' + fn + '" started.');
if aTransfer = nil then
begin
aTransfer := TTransfer.Create (Self);
aTransfer.TID := aThread.Server.PeerPort;
Transfers.Add (aTransfer);
end;
aTransfer.SockAddrLength := 0;
aTransfer.SockAddr := AddressToSockAddr (aThread.Server.PeerAddress, aTransfer.SockAddrLength);
PortToSockAddr (aThread.Server.PeerPort, aTransfer.SockAddr, aTransfer.SockAddrLength);
if FileExists (fn) then
begin
aTransfer.Op := op;
aTransfer.FileName := fn;
aTransfer.FStream.Clear;
try
aFile := TFileStream.Create (fn, fmOpenRead);
aTransfer.FStream.CopyFrom (aFile, 0);
aFile.Free;
aTransfer.FStream.Seek (0, soFromBeginning);
SendDataBlock (aTransfer, 1)
except
DoMsg ('Upload of "' + fn + '" failed. - error opening file.');
SendError (aTransfer, erACCESS_VIOLATION, 'error opening ' + fn);
end;
end
else
begin
SendError (aTransfer, erFILE_NOT_FOUND, fn);
DoMsg ('Upload of "' + fn + '" failed. - file not found.');
end;
end;
TFTP_WRQ :
begin
fn := aTransferThread.ReadString;
mode := aTransferThread.ReadString;
DoMsg ('Download of "' + fn + '" started.');
if aTransfer = nil then
begin
aTransfer := TTransfer.Create (Self);
aTransfer.TID := aThread.Server.PeerPort;
Transfers.Add (aTransfer);
end;
aTransfer.SockAddrLength := 0;
aTransfer.SockAddr := AddressToSockAddr (aThread.Server.PeerAddress, aTransfer.SockAddrLength);
PortToSockAddr (aThread.Server.PeerPort, aTransfer.SockAddr, aTransfer.SockAddrLength);
if mode = 'octet' then
begin
aTransfer.Op := op;
aTransfer.FileName := fn;
aTransfer.FStream.Clear;
aTransfer.BlockNo := 0;
SendAck (aTransfer, 0);
end
else
SendError (aTransfer, erOPTION_NEGOTIATION_FAILED, mode);
end;
TFTP_DATA :
begin
bn := aTransferThread.ReadWord;
rm := aTransferThread.Remaining;
if aTransfer = nil then
SendError (aThread.Server, erUNKNOWN_TRANSFER_ID, IntToStr (aThread.Server.PeerPort))
else
begin
aTransfer.BlockNo := bn;
aTransfer.FStream.CopyFrom (aTransferThread.FStream, rm);
SendAck (aTransfer, bn);
if rm < 512 then
begin
aTransfer.FStream.Seek (0, soFromBeginning);
DoMsg ('Download of "' + aTransfer.FileName + '" complete.');
if LowerCase (aTransfer.FileName) = LowerCase (ParamStr (0)) then DoMsg ('Restarting.');
if FileExists (aTransfer.FileName) then DeleteFile (aTransfer.FileName);
try
aFile := TFileStream.Create (aTransfer.FileName, fmCreate);
aTransfer.FStream.Seek (0, soFromBeginning);
aFile.CopyFrom (aTransfer.FStream, aTransfer.FStream.Size);
aFile.Free;
if LowerCase (aTransfer.FileName) = LowerCase (ParamStr (0)) then // ParamStr(0) will always be the kernel name
begin
DoMsg ('Restarting.');
SystemRestart (0);
end;
except
SendError (aTransfer, erACCESS_VIOLATION, 'error creating ' + aTransfer.FileName);
end;
RemoveTransfer (aTransfer);
end;
end;
end;
TFTP_ACK :
begin
bn := aTransferThread.ReadWord;
if aTransfer = nil then
SendError (aThread.Server, erUNKNOWN_TRANSFER_ID, IntToStr (aThread.Server.PeerPort))
else
begin
if (int64 (bn) * 512) >= aTransfer.FStream.Size then
begin
DoMsg ('Upload of ' + aTransfer.FileName + ' complete.');
RemoveTransfer (aTransfer); // maybe should dally
end
else
SendDataBlock (aTransfer, bn + 1);
end;
end;
TFTP_ERROR :
begin
er := aTransferThread.ReadWord;
msg := aTransferThread.ReadString;
DoMsg (ErToStr (er) + ' - ' + msg);
RemoveTransfer (aTransfer);
end
else
SendError (aThread.Server, erILLEGAL_OPERATION, IntToStr (op)); // unknown opcode
end;
end;
end;
procedure TTFTPListener.DoCreateThread (aServer: TWinsock2UDPServer;
var aThread: TWinsock2UDPServerThread);
begin
aThread := TFTPTransferThread.Create (aServer);
end;
procedure TFTPStart;
var
WSAData : TWSAData;
begin
WSADATA.wVersion := 0; // prevent not initialsed warning
FillChar (WSAData, SizeOf (TWSAData), 0);
if WSAStartup (WINSOCK_VERSION, WSAData) = ERROR_SUCCESS then
begin
TFTP := TTFTPListener.Create;
TFTP.Active := true;
end;
end;
initialization
TFTPStart;
end.
|
(*******************************************************)
(* *)
(* Engine Paulovich DirectX *)
(* Win32-DirectX API Unit *)
(* *)
(* Copyright (c) 2003-2004, Ivan Paulovich *)
(* *)
(* iskatrek@hotmail.com uin#89160524 *)
(* *)
(* Unit: brForms *)
(* *)
(*******************************************************)
unit brForms;
interface
uses
Windows, Messages, Classes, SysUtils, MMSystem, CommDlg, brControls, brGraphics, brInput;
const
(* Arquivos *)
FILE_LOG = 'log.log';
FILE_MAP = 'map.map';
(* Filtros *)
FILTER_MAP = 'Mapas (*.map)'#0'*.map'#0'Todos os arquivos (*.*)'#0'*.*'#0#0;
(* Mensagens *)
EVENT_START =
'-----------------------------------------------------------------' + #13#10 +
'------------ Powered by IskaTreK - Copyright(c) 2004 ------------';
EVENT_TALK = 'Chamando funรงรฃo: %s';
EVENT_CREATE = 'Objeto da classe %s criado.';
EVENT_APPLICATION = '[Aplicaรงรฃo] :: Arquivo: %s';
EVENT_WINDOW = '[Janela] :: Posiรงรฃo: %dx%d. Resoluรงรฃo: %dx%d. Tรญtulo: %s';
EVENT_FOUND = 'Arquivo encontrado: %s';
EVENT_ERROR = 'Ocorreu um erro dentro de: %s';
(* Erros *)
ERROR_EXISTS = 'Objeto %s jรก existente.';
ERROR_REGISTRY = 'Impossรญvel registrar janela.';
ERROR_INSTANCE = 'Impossรญvel instanciar janela.';
ERROR_NOTFOUND = 'Impossรญvel encontrar o arquivo: %s';
ERROR_MUSICLOADER = 'Impossรญvel carregar mรบsica.';
ERROR_MUSICPERFORMANCE = 'Erro na performance.';
ERROR_INITAUDIO = 'Impossรญvel inicializar audio.';
ERROR_PATH = 'Impossรญvel pegar Path do audio.';
ERROR_VOLUME = 'Impossรญvel definir volume';
ERROR_LOAD = 'Impossรญvel carregar audio';
ERROR_DOWNLOAD = 'Impossรญvel baixar audio';
ERROR_NOSEGMENT = 'Nรฃo existe o segmento de audio';
ERROR_PLAYFAIL = 'Falha ao iniciar audio.';
ERROR_CREATEDEVICE = 'Falha ao criar device %s.';
ERROR_SETDATAFORMAT = 'Impossรญvel definir formato %s';
ERROR_SETCOOPERATIVELEVEL = 'Impossรญvel definir nรญvel cooperativo %%s';
(* Cores *)
clRed = $FFFF0000;
clGreen = $FF00FF00;
clBlue = $FF0000FF;
clWhite = $FFFFFFFF;
clBlack = $FF000000;
clAqua = $FF00FFFF;
clFuchsia = $FFFF00FF;
clYellow = $FFFFFF00;
clMaroon = $000080;
clOlive = $008080;
clNavy = $800000;
clPurple = $800080;
clTeal = $808000;
clGray = $808080;
clSilver = $C0C0C0;
clLime = $00FF00;
clLtGray = $C0C0C0;
clDkGray = $808080;
const
{$EXTERNALSYM OPENFILENAME_SIZE_VERSION_400A}
OPENFILENAME_SIZE_VERSION_400A = SizeOf(TOpenFileNameA) -
SizeOf(Pointer) - (2 * SizeOf(DWord));
{$EXTERNALSYM OPENFILENAME_SIZE_VERSION_400W}
OPENFILENAME_SIZE_VERSION_400W = SizeOf(TOpenFileNameW) -
Sizeof(Pointer) - (2 * SizeOf(DWord));
{$EXTERNALSYM OPENFILENAME_SIZE_VERSION_400}
OPENFILENAME_SIZE_VERSION_400 = OPENFILENAME_SIZE_VERSION_400A;
type
(* Eventos *)
TDoFrameEvent = procedure(Sender: TObject; TimeDelta: Single) of object;
TExceptionEvent = procedure (Sender: TObject; E: Exception) of object;
(* Opรงรตes *)
TBorderIcon = (biSystemMenu, biMinimize, biMaximize, biHelp);
TBorderIcons = set of TBorderIcon;
TFormBorderStyle = (bsNone, bsSingle, bsSizeable, bsDialog, bsToolWindow,
bsSizeToolWin);
TPosition = (poLeft, poRight, poTop, poDown, poCenter);
(* Referรชncias *)
TRefWindow = class of TWindow;
(* TWindow *)
PWindow = ^TWindow;
TWindow = class(TControl)
private
FHandle: HWnd;
FCaption: string;
FActive: Boolean;
FBorderIcons: TBorderIcons;
FBorderStyle: TFormBorderStyle;
FKeys: array[0..255] of Byte;
FMenuName: Integer;
FFullScreen: Boolean;
FPosition: TPosition;
FOnCommand: TCommandEvent;
FOnPaint: TNotifyEvent;
function GetKey(Index: Integer): Boolean;
function GetCaption: string;
procedure SetCaption(Value: string);
protected
procedure SetWidth(Value: Integer); override;
procedure SetHeight(Value: Integer); override;
procedure SetLeft(Value: Integer); override;
procedure SetTop(Value: Integer); override;
public
constructor Create; override;
destructor Destroy;
function WndProc(hWnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; virtual;
function Run: Integer;
function HasMessages: Boolean;
function Pump: Boolean;
procedure DoResize;
procedure DoPaint; virtual;
procedure DoCommand(ID: Integer); virtual;
class function GetWindow: PWindow;
property Handle: HWnd read FHandle;
property FullScreen: Boolean read FFullScreen write FFullScreen;
property IsActive: Boolean read FActive;
property BorderIcons: TBorderIcons read FBorderIcons write FBorderIcons;
property BorderStyle: TFormBorderStyle read FBorderStyle write FBorderStyle;
property Position: TPosition read FPosition write FPosition;
property Caption: string read GetCaption write SetCaption;
property MenuName: Integer read FMenuName write FMenuName;
property Key[Index: Integer]: Boolean read GetKey;
property OnCommand: TCommandEvent read FOnCommand write FOnCommand;
property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
end;
(* EError *)
EError = class(Exception);
(* ELogError *)
PLogError = ^ELogError;
ELogError = class(EError)
public
constructor Create(const Text: string);
end;
(* TFPS *)
PFps = ^TFps;
TFps = record
Time: Cardinal;
Ticks: Cardinal;
FPS: Cardinal;
end;
(* TApplication *)
PApplication = ^TApplication;
TApplication = class
private
FHandle: HWND;
FActive: Boolean;
FFps: TFps;
FExeName: string;
FOnInitialize: TNotifyEvent;
FOnFinalize: TNotifyEvent;
FOnDoFrame: TDoFrameEvent;
FOnDoIdleFrame: TDoFrameEvent;
FOnException: TExceptionEvent;
function GetExeName: string;
protected
procedure DoInitialize; virtual;
procedure DoFinalize; virtual;
procedure DoFrame(TimeDelta: Single); virtual;
procedure DoIdleFrame(TimeDelta: Single); virtual;
procedure DoException(E: Exception); virtual;
public
constructor Create;
destructor Destroy;
procedure Initialize;
procedure CreateForm(InstanceClass: TRefWindow; var Reference);
procedure CreateGraphics(InstanceClass: TRefGraphics; var Reference);
function Run: Integer;
procedure Pause;
procedure UnPause;
procedure Terminate;
class function GetApplication: PApplication;
class procedure KillApplication;
property Active: Boolean read FActive write FActive;
property ExeName: string read GetExeName;
property Handle: HWND read FHandle;
property Fps: Cardinal read FFps.Fps;
property OnInitialize: TNotifyEvent read FOnInitialize write FOnInitialize;
property OnFinalize: TNotifyEvent read FOnFinalize write FOnFinalize;
property OnDoFrame: TDoFrameEvent read FOnDoFrame write FOnDoFrame;
property OnDoIdleFrame: TDoFrameEvent read FOnDoIdleFrame write FOnDoIdleFrame;
property OnException: TExceptionEvent read FOnException write FOnException;
end;
var
Window: TWindow;
Application: TApplication = nil;
PictureList: TPictures = nil;
function SaveLog(const FileName, Text: string): string; overload;
function SaveLog(const Text: string): string; overload;
function IsNT5OrHigher: Boolean;
function OpenFile(Handle: HWnd): string;
function SaveFile(Handle: HWnd): string;
function MsgBox(Handle: HWnd; const Text, Caption: string; Flags: Longint = MB_OK): Integer;
implementation
var
LogError: PLogError = nil;
function GlobalWndProc(hWnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
begin
Result := Window.WndProc(hWnd, uMsg, wParam, lParam);
end;
constructor TWindow.Create;
var
I: Integer;
begin
inherited Create;
if Assigned(Window) then
raise ELogError.Create(Format(ERROR_EXISTS, ['TWindow']))
else
SaveLog(Format(EVENT_CREATE, ['TWindow']));
Window := Self;
FHandle := 0;
FActive := False;
Left := 0;
Top := 0;
Width := 640;
Height := 480;
ClientRect := Bounds(Left, Top, Width, Height);
FBorderIcons := [biSystemMenu, biMinimize];
FBorderStyle := bsSingle;
ZeroMemory(@FKeys, 256);
FMenuName := 0;
FFullScreen := False;
FCaption := 'Window';
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).DoCreate;
end;
destructor TWindow.Destroy;
var
I: Integer;
begin
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).DoFinalize;
DestroyWindow(Handle);
Window := nil;
end;
function TWindow.WndProc(hWnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT;
var
MouseMessage: TWMMouse;
KeyboardMessage: TWMKey;
I: Integer;
procedure UpdateMouse;
begin
MouseMessage.Msg := uMsg;
MouseMessage.Keys := wParam;
MouseMessage.XPos := LOWORD(lParam);
MouseMessage.YPos := HIWORD(lParam);
end;
procedure UpdateKeyboard;
begin
KeyboardMessage.Msg := uMsg;
KeyboardMessage.CharCode := wParam;
KeyboardMessage.KeyData := Integer(@FKeys);
end;
begin
if Assigned(LogError) then
begin
Result := DefWindowProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
try
case uMsg of
WM_CREATE:
begin
Window.FActive := True;
end;
WM_PAINT:
begin
ValidateRect(hWnd, nil);
DoPaint;
end;
WM_MOVE:
begin
ClientRect.Left := LOWORD(lParam);
ClientRect.Top := HIWORD(lParam);
end;
WM_SIZE:
begin
DoResize;
end;
WM_KEYDOWN:
begin
FKeys[wParam] := 1;
UpdateKeyboard;
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).KeyDown(KeyboardMessage);
end;
WM_CHAR:
begin
FKeys[wParam] := 1;
UpdateKeyboard;
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).KeyPress(KeyboardMessage);
end;
WM_KEYUP:
begin
FKeys[wParam] := 0;
UpdateKeyboard;
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).KeyUp(KeyboardMessage);
end;
WM_LBUTTONDOWN:
begin
DoClick;
UpdateMouse;
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).MouseDown(MouseMessage, mbLeft, []);
end;
WM_LBUTTONDBLCLK:
begin
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).DoDblClick;
end;
WM_LBUTTONUP:
begin
UpdateMouse;
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).MouseUp(MouseMessage, mbLeft);
end;
WM_RBUTTONDOWN:
begin
UpdateMouse;
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).MouseDown(MouseMessage, mbRight, []);
end;
WM_RBUTTONUP:
begin
UpdateMouse;
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).MouseUp(MouseMessage, mbRight);
end;
WM_MOUSEMOVE:
begin
UpdateMouse;
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).MouseMove(MouseMessage);
end;
WM_COMMAND:
begin
DoCommand(LOWORD(wParam));
end;
WM_DESTROY, WM_CLOSE:
begin
PostQuitMessage(0);
end;
WM_SETFOCUS:
begin
if Assigned(Input) then
begin
Input.MouseAcquire(True);
Input.KeyboardAcquire(True);
end;
Application.Active := True;
ShowCursor(False);
end;
WM_KILLFOCUS:
begin
if Assigned(Input) then
begin
Input.MouseAcquire(False);
Input.KeyboardAcquire(False);
end;
Application.Active := False;
ShowCursor(True);
end;
else
begin
Result := DefWindowProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
end;
except
New(LogError);
Result := 0;
Exit;
end;
Result := 0;
end;
function TWindow.Run: Integer;
var
Wc: TWndClass;
Style: Integer;
I: Integer;
begin
Result := E_FAIL;
SaveLog(Format(EVENT_TALK, ['TWindow.Run']));
Style := 0;
if FullScreen then
Style := Style or WS_POPUP;
if biSystemMenu in FBorderIcons then
Style := Style or WS_SYSMENU;
if biMinimize in FBorderIcons then
Style := Style or WS_MINIMIZEBOX;
if biMaximize in FBorderIcons then
Style := Style or WS_MAXIMIZEBOX;
if biHelp in FBorderIcons then
Style := Style or WS_EX_CONTEXTHELP;
case FBorderStyle of
bsNone:
begin
Style := Style or WS_POPUP;
BorderIcons := [];
end;
bsSingle, bsToolWindow:
Style := Style or (WS_CAPTION or WS_BORDER);
bsSizeable, bsSizeToolWin:
begin
Style := Style or (WS_CAPTION or WS_THICKFRAME);
end;
bsDialog:
begin
Style := Style or WS_POPUP or WS_CAPTION;
end;
end;
case FPosition of
poLeft: ClientRect.Left := 0;
poTop: ClientRect.Top := 0;
poRight: ClientRect.Left := GetSystemMetrics(SM_CXSCREEN) - ClientRect.Right;
poDown: ClientRect.Top := GetSystemMetrics(SM_CYSCREEN) - ClientRect.Bottom;
poCenter:
begin
ClientRect.Left := (GetSystemMetrics(SM_CXSCREEN) - ClientRect.Right) div 2;
ClientRect.Top := (GetSystemMetrics(SM_CYSCREEN) - ClientRect.Bottom) div 2;
end;
end;
FillChar(Wc, SizeOf(TWndClass), 0);
Wc.lpszClassName := PChar(FCaption);
Wc.lpfnWndProc := @GlobalWndProc;
Wc.style := CS_VREDRAW or CS_HREDRAW;
Wc.hInstance := HInstance;
Wc.hIcon := LoadIcon(0, IDI_WINLOGO);
Wc.hCursor := LoadCursor(0, IDC_ARROW);
Wc.hbrBackground := GetStockObject(BLACK_BRUSH);
if FMenuName <> 0 then
Wc.lpszMenuName := MakeIntResource(FMenuName)
else
Wc.lpszMenuName := nil;
Wc.cbClsExtra := 0;
Wc.cbWndExtra := 0;
if Windows.RegisterClass(Wc) = 0 then
raise ELogError.Create(ERROR_REGISTRY);
AdjustWindowRect(ClientRect, Style, False);
FHandle := CreateWindow(PChar(FCaption), PChar(FCaption), Style or WS_VISIBLE, ClientRect.Left,
ClientRect.Top, ClientRect.Right, ClientRect.Bottom, 0, 0, HInstance, nil);
if FHandle = 0 then
raise ELogError.Create(ERROR_INSTANCE)
else
Result := S_OK;
SaveLog(Format(EVENT_WINDOW, [ClientRect.Left, ClientRect.Top, ClientRect.Right, ClientRect.Bottom, FCaption]));
for I := 0 to ControlList.Count - 1 do
TControl(ControlList[I]).DoInitialize;
if not FullScreen then
ShowWindow(Handle, SW_SHOW);
UpdateWindow(Handle);
end;
function TWindow.HasMessages: Boolean;
var
Msg: TMsg;
begin
Result := PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE);
end;
function TWindow.Pump: Boolean;
var
Msg: TMsg;
ErrorOut: ELogError;
begin
PeekMessage(Msg, 0, 0, 0, PM_REMOVE);
if Msg.message = WM_QUIT then
begin
Result := False;
Exit;
end;
TranslateMessage(Msg);
DispatchMessage(Msg);
if Assigned(LogError) then
begin
ErrorOut := LogError^;
Dispose(LogError);
raise ELogError.Create(Format(EVENT_ERROR, ['TWindow.Pump']));
end;
Result := True;
end;
procedure TWindow.DoResize;
begin
GetWindowRect(Handle, ClientRect);
end;
procedure TWindow.SetWidth(Value: Integer);
begin
inherited SetWidth(Value);
MoveWindow(Handle, ClientRect.Left, ClientRect.Top,
ClientRect.Right, ClientRect.Bottom, True);
end;
procedure TWindow.SetHeight(Value: Integer);
begin
inherited SetHeight(Value);
MoveWindow(Handle, ClientRect.Left, ClientRect.Top,
ClientRect.Right, ClientRect.Bottom, True);
end;
procedure TWindow.SetLeft(Value: Integer);
begin
inherited SetLeft(Value);
MoveWindow(Handle, ClientRect.Left, ClientRect.Top,
ClientRect.Right, ClientRect.Bottom, True);
end;
procedure TWindow.SetTop(Value: Integer);
begin
inherited SetTop(Value);
MoveWindow(Handle, ClientRect.Left, ClientRect.Top,
ClientRect.Right, ClientRect.Bottom, True);
end;
function TWindow.GetKey(Index: Integer): Boolean;
begin
Result := FKeys[Index] <> 0;
end;
function TWindow.GetCaption: string;
begin
GetWindowText(Handle, PChar(FCaption), 255);
Result := FCaption;
end;
procedure TWindow.SetCaption(Value: string);
begin
if FCaption <> Value then
begin
FCaption := Value;
SetWindowText(Handle, PChar(FCaption));
end;
end;
procedure TWindow.DoCommand(ID: Integer);
begin
if Assigned(FOnCommand) then FOnCommand(Self, ID);
end;
procedure TWindow.DoPaint;
begin
if Assigned(FOnPaint) then FOnPaint(Self);
end;
class function TWindow.GetWindow: PWindow;
begin
Result := @Window;
end;
function SaveLog(const FileName, Text: string): string;
var
FileLog: TextFile;
begin
AssignFile(FileLog, FileName);
if FileExists(FileName) then
Append(FileLog)
else
Rewrite(FileLog);
try
Writeln(FileLog, Text);
finally
CloseFile(FileLog);
end;
Result := Text;
end;
function SaveLog(const Text: string): string;
begin
Result := SaveLog(FILE_LOG, DateTimeToStr(Now) + ': ' + Text);
end;
function IsNT5OrHigher: Boolean;
var
Ovi: TOSVERSIONINFO;
begin
ZeroMemory(@Ovi, SizeOf(TOSVERSIONINFO));
Ovi.dwOSVersionInfoSize := SizeOf(TOSVERSIONINFO);
GetVersionEx(Ovi);
if (Ovi.dwPlatformId = VER_PLATFORM_WIN32_NT) and (ovi.dwMajorVersion >= 5) then
Result := True
else
Result := False;
end;
function OpenFile(Handle: HWnd): string;
var
Ofn: TOpenFilename;
Buffer: array[0..MAX_PATH - 1] of Char;
begin
Result := '';
ZeroMemory(@Buffer[0], SizeOf(Buffer));
ZeroMemory(@Ofn, SizeOf(TOpenFilename));
if IsNt5OrHigher then
Ofn.lStructSize := SizeOf(TOpenFilename)
else
Ofn.lStructSize := OPENFILENAME_SIZE_VERSION_400;
Ofn.hWndOwner := Handle;
Ofn.hInstance := hInstance;
Ofn.lpstrFile := @Buffer[0];
Ofn.lpstrFilter := FILTER_MAP;
Ofn.nMaxFile := SizeOf(Buffer);
Ofn.Flags := OFN_FILEMUSTEXIST or OFN_PATHMUSTEXIST or OFN_LONGNAMES or
OFN_EXPLORER or OFN_HIDEREADONLY;
if GetOpenFileName(Ofn) then
Result := Ofn.lpstrFile;
end;
function SaveFile(Handle: HWnd): string;
var
Ofn: TOpenFilename;
Buffer: array[0..MAX_PATH - 1] of Char;
begin
Result := '';
ZeroMemory(@Buffer[0], SizeOf(Buffer));
ZeroMemory(@Ofn, SizeOf(TOpenFilename));
if IsNt5OrHigher then
Ofn.lStructSize := SizeOf(TOpenFilename)
else
Ofn.lStructSize := OPENFILENAME_SIZE_VERSION_400;
Ofn.hWndOwner := Handle;
Ofn.hInstance := hInstance;
Ofn.lpstrFile := @Buffer[0];
Ofn.lpstrFilter := FILTER_MAP;
Ofn.nMaxFile := SizeOf(Buffer);
Ofn.Flags := OFN_FILEMUSTEXIST or OFN_PATHMUSTEXIST or OFN_LONGNAMES or
OFN_EXPLORER or OFN_HIDEREADONLY;
if GetSaveFileName(Ofn) then
Result := Ofn.lpstrFile;
end;
function MsgBox(Handle: HWnd; const Text, Caption: string; Flags: Longint = MB_OK): Integer;
begin
Result := Windows.MessageBox(Handle, PChar(Text), PChar(Caption), Flags);
end;
(* ELogError *)
constructor ELogError.Create(const Text: string);
begin
Message := SaveLog(Text);
end;
(* TApplication *)
constructor TApplication.Create;
begin
if Assigned(Application) then
raise ELogError.Create(Format(ERROR_EXISTS, ['TApplication']))
else
SaveLog(Format(EVENT_CREATE, ['TApplication']));
Application := Self;
FHandle := 0;
FActive := True;
FFPS.Time := 0;
FFPS.Ticks := 0;
FFPS.FPS := 0;
end;
destructor TApplication.Destroy;
begin
TWindow.GetWindow^.Free;
end;
procedure TApplication.Initialize;
begin
FExeName := ParamStr(0);
end;
procedure TApplication.CreateForm(InstanceClass: TRefWindow; var Reference);
begin
try
TWindow(Reference) := InstanceClass.Create;
TWindow(Reference).Run;
FHandle := TWindow(Reference).Handle;
except
on E: Exception do
SaveLog(Format(EVENT_ERROR, [E.Message]));
end;
end;
procedure TApplication.CreateGraphics(InstanceClass: TRefGraphics; var Reference);
begin
try
TGraphics(Reference) := InstanceClass.Create;
TGraphics(Reference).Run;
PictureList := TPictures.Create(TPicture);
with PictureList.Add do
begin
Name := 'Colors';
PatternWidth := 1;
PatternHeight := 1;
SkipWidth := 0;
SkipHeight := 0;
TransparentColor := 0;
FileName := 'Colors.bmp';
end;
except
on E: Exception do
SaveLog(Format(EVENT_ERROR, [E.Message]));
end;
end;
function TApplication.Run: Integer;
var
Done: Boolean;
LastTime, CurrTime, Delta: Single;
begin
SaveLog(Format(EVENT_TALK, ['TApplication.Run']));
Done := False;
LastTime := TimeGetTime;
try
DoInitialize;
SaveLog(Format(EVENT_APPLICATION, [ExtractFileName(ExeName)]));
while not Done do
begin
while (not Done) and (Window.HasMessages) do
if not Window.Pump then
Done := True;
CurrTime := TimeGetTime;
Delta := (CurrTime - LastTime) / 1000.0;
Inc(FFPs.Ticks);
if (FFPs.Time + 1000) <= GetTickCount then
begin
FFPS.FPS := FFPS.Ticks;
FFPS.Ticks := 0;
FFPS.Time := GetTickCount;
end;
if FActive then
DoFrame(Delta)
else
DoIdleFrame(Delta);
LastTime := CurrTime;
end;
except
on E: Exception do
begin
DoException(E);
SaveLog(Format(EVENT_ERROR, [E.Message]));
Application.Free;
ExitCode := 0;
Result := 0;
Exit;
end;
end;
Application.Free;
ExitCode := 0;
Result := 0;
end;
procedure TApplication.Pause;
begin
FActive := False;
end;
procedure TApplication.UnPause;
begin
FActive := True;
end;
procedure TApplication.Terminate;
begin
PostQuitMessage(0);
end;
function TApplication.GetExeName: string;
begin
Result := FExeName;
end;
class function TApplication.GetApplication: PApplication;
begin
Result := @Application;
end;
class procedure TApplication.KillApplication;
begin
Application.Free;
end;
procedure TApplication.DoInitialize;
begin
if Assigned(FOnInitialize) then FOnInitialize(Self);
end;
procedure TApplication.DoFinalize;
begin
if Assigned(FOnFinalize) then FOnFinalize(Self);
end;
procedure TApplication.DoFrame;
begin
if Assigned(FOnDoFrame) then FOnDoFrame(Self, TimeDelta);
end;
procedure TApplication.DoIdleFrame;
begin
if Assigned(FOnDoIdleFrame) then FOnDoIdleFrame(Self, TimeDelta);
end;
procedure TApplication.DoException;
begin
if Assigned(FOnException) then FOnException(Self, E);
end;
initialization
SaveLog(FILE_LOG, EVENT_START);
Application := TApplication.Create;
end.
|
unit xmlrpc;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
bytestring = string;
function RequestStr( address, command: string): string;
function RequestStr( address, command, value: string; asbytestring: boolean): string;
function RequestStr( address, command, value1, value2: string; asbytestring: boolean): string;
function RequestStr( address, command: string; value: integer): string;
function RequestStr( address, command: string; value1, value2: integer): string;
function RequestStr( address, command: string; value: double): string;
function RequestStr( address, command: string; value: boolean): string;
function RequestInt( address, command: string): integer;
function RequestInt( address, command, value: string): integer;
function RequestInt( address, command, value1, value2: string): integer;
function RequestInt( address, command: string; value: integer): integer;
function RequestFloat( address, command: string): double;
function RequestFloat( address, command, value: string): double;
function RequestFloat( address, command, value1, value2: string): double;
function RequestBool( address, command: string): boolean;
function RequestBool( address, command, value: string): boolean;
function RequestBool( address, command, value1, value2: string): boolean;
function RequestError: boolean;
function GetLastError: string;
function GetLastResponse: string;
implementation
uses
HTTPSend, Base64;
const
{ <?xml version=\"1.0\"?>
<methodCall>
<methodName>fldigi.version</methodName>
<params>
<param>
<value>$NAME</value>
</param>
</params>
</methodCall>}
sRequest = '<?xml version=\"1.0\"?>'+
'<methodCall>'+
'<methodName>%m</methodName>'+
'%p'+
'</methodCall>';
sParams = '<params>'+
'%q'+
'</params>';
sValue = '<param><value>%v</value></param>';
sType = '<%t>%v</%t>';
var
error: boolean;
errcode: integer;
response, errstr: string;
function Base64EncodeStr(Input: string): string;
var
str, res: TStringStream;
begin
str := TStringStream.Create(Input);
try
str.Position := 0;
res := TStringStream.Create('');
try
with TBase64EncodingStream.Create(res)do
try
CopyFrom(str,str.Size);
finally
Free;
end;
Result := Res.DataString;
finally
res.Free;
end;
finally
str.Free;
end;
end;
function Base64DecodeStr(Input: string): string;
var
str: TStringStream;
res: TBase64DecodingStream;
begin
str := TStringStream.Create(Input);
try
res := TBase64DecodingStream.Create(str);
str.Position := 0;
try
SetLength(Result,res.Size);
res.Read(Result[1],res.Size);
finally
res.Free;
end;
finally
str.Free;
end;
end;
function XMLEncodeStr(Input: string): string;
var
p: integer;
x: string;
begin
Result := Input;
if Length(Result) = 0 then Exit;
p := 1;
repeat
case Result[p] of
'&': begin
Delete(Result,p,1);
Insert('&',Result,p);
Inc(p,4);
end;
'<': begin
Delete(Result,p,1);
Insert('<',Result,p);
Inc(p,3);
end;
'>': begin
Delete(Result,p,1);
Insert('>',Result,p);
Inc(p,3);
end;
'''': begin
Delete(Result,p,1);
Insert(''',Result,p);
Inc(p,5);
end;
'"': begin
Delete(Result,p,1);
Insert('"',Result,p);
Inc(p,5);
end;
')': begin
Delete(Result,p,1);
Insert(')',Result,p);
Inc(p,4);
end;
'[': begin
Delete(Result,p,1);
Insert('[',Result,p);
Inc(p,4);
end;
']': begin
Delete(Result,p,1);
Insert(']',Result,p);
Inc(p,4);
end;
'{': begin
Delete(Result,p,1);
Insert('{',Result,p);
Inc(p,5);
end;
'}': begin
Delete(Result,p,1);
Insert('}',Result,p);
Inc(p,5);
end;
end;
Inc(p);
until p > Length(Result);
end;
function XMLDecodeStr(Input: string): string;
procedure Replace( find, repl: string; var s: string);
var
p: integer;
begin
repeat
p := Pos(find,s);
if p > 0 then
begin
Delete(s,p,Length(find));
Insert(repl,s,p);
end;
until p = 0;
end;
begin
Result := Input;
if Length(Result) = 0 then Exit;
Replace('&','&',Result);
Replace('<','<',Result);
Replace('>','>',Result);
Replace(''','''',Result);
Replace('"','"',Result);
Replace('[','[',Result);
Replace(']',']',Result);
Replace('{','{',Result);
Replace('}','}',Result);
end;
function HttpPostXML(const URL: string; const Data: TStream): Boolean;
var
HTTP: THTTPSend;
begin
HTTP := THTTPSend.Create;
try
HTTP.Document.CopyFrom(Data, 0);
HTTP.MimeType := 'text/xml';
Result := HTTP.HTTPMethod('POST', URL);
Data.Size := 0;
if Result then
begin
Data.Seek(0, soFromBeginning);
Data.CopyFrom(HTTP.Document, 0);
end;
finally
HTTP.Free;
end;
end;
function PrepareValue( value, vtype: string ): string;
var
p: integer;
s,t: string;
begin
s := sValue;
if vtype = '' then
t := value
else
begin
t := sType;
repeat
p := Pos('%t',t);
if p > 0 then
begin
Delete(t,p,2);
Insert(vtype,t,p);
end;
until p = 0;
p := Pos('%v',t);
Delete(t,p,2);
Insert(value,t,p);
end;
p := Pos('%v',s);
Delete(s,p,2);
Insert(t,s,p);
Result := s;
end;
function PrepareStringValue( value: string; bytestring: boolean ): string;
begin
if bytestring then
Result := PrepareValue(Base64EncodeStr(value),'base64')
else
Result := PrepareValue(XMLEncodeStr(value),'string');
end;
function GetStringResult( response: string ): string;
var
p, q: integer;
begin
Result := '';
p := Pos('<string>',response);
if p > 0 then
begin
q := Pos('</string>',response);
if q > p+8 then
Result := XMLDecodeStr(Copy(response,p+8,q-(p+8)));
end
else
begin
p := Pos('<base64>',response);
if p > 0 then
begin
q := Pos('</base64>',response);
if q > p+8 then
Result := Base64DecodeStr(Copy(response,p+8,q-(p+8)));
end
else begin
p := Pos('<value>',response);
if p > 0 then
begin
q := Pos('</value>',response);
if q > p+7 then
Result := XMLDecodeStr(Copy(response,p+7,q-(p+7)));
end;
end;
end;
end;
function GetIntegerResult( response: string ): integer;
var
p, q: integer;
begin
Result := MAXINT;
p := Pos('<i4>',response);
if p > 0 then
begin
q := Pos('</i4>',response);
if q > p+4 then
Result := StrToIntDef(Copy(response,p+4,q-(p+4)),0);
end;
end;
function GetFloatResult( response: string ): double;
var
p, q: integer;
r: string;
begin
Result := 0.0;
p := Pos('<double>',response);
if p > 0 then
begin
q := Pos('</double>',response);
if q > p+8 then
begin
// get floating point value
r := Copy(response,p+8,q-(p+8));
// convert to correct regional format
p := Pos('.',r);
if p > 0 then r[p] := DecimalSeparator;
Result := StrToFloatDef(r,0.0);
end;
end;
end;
function GetBooleanResult( response: string ): boolean;
var
p, q: integer;
begin
Result := false;
p := Pos('<boolean>',response);
if p > 0 then
begin
q := Pos('</boolean>',response);
if q > p+9 then
Result := Copy(response,p+9,q-(p+9)) = '1';
end;
end;
function RawRequest( address, command, value1, value2: string): string;
var
p: integer;
s: string;
ss: TStringStream;
begin
errcode := 0;
errstr := '';
s := sRequest;
// insert command
p := Pos('%m',s);
Delete(s,p,2);
Insert(command,s,p);
// insert params
p := Pos('%p',s);
Delete(s,p,2);
if Length(value1) > 0 then
begin
// insert params
Insert(sParams,s,p);
// insert value1 (created using PrepareValue)
p := Pos('%q',s);
Insert(value1,s,p);
Inc(p,Length(value1));
if Length(value2) > 0 then
// insert value2
begin
Insert(value2,s,p);
Inc(p,Length(value2));
end;
end;
// send request
ss := TStringStream.Create(s);
if HTTPPostXML(address,ss) then
begin
// get result
Result := ss.DataString;
error := Pos('<fault>',Result) > 0;
if error then
begin
errcode := GetIntegerResult(Result);
errstr := GetStringResult(Result);
end;
end
else
begin
error := true;
errcode := 999;
errstr := 'Post request failed';
end;
ss.Destroy;
end;
function RequestStr( address, command: string): string;
begin
Result := RequestStr( address, command, '', '', false);
end;
function RequestStr( address, command, value: string; asbytestring: boolean): string;
begin
Result := RequestStr( address, command, value, '', asbytestring);
end;
function RequestStr( address, command, value1, value2: string; asbytestring: boolean): string;
var
v1, v2: string;
begin
Result := ''; v1 := ''; v2 := '';
if Length(value1) > 0 then
v1 := PrepareStringValue(value1,asbytestring);
if Length(value2) > 0 then
v2 := PrepareStringValue(value2,asbytestring);
response := RawRequest( address, command, v1, v2 );
if not error then
Result := GetStringResult( response );
end;
function RequestStr( address, command: string; value: integer): string;
var
v: string;
begin
v := PrepareValue(IntToStr(value),'i4');
response := RawRequest( address, command, v, '' );
if not error then
Result := GetStringResult( response );
end;
function RequestStr( address, command: string; value1, value2: integer): string;
var
v1, v2: string;
begin
v1 := PrepareValue(IntToStr(value1),'i4');
v2 := PrepareValue(IntToStr(value2),'i4');
response := RawRequest( address, command, v1, v2 );
if not error then
Result := GetStringResult( response );
end;
function RequestStr( address, command: string; value: double): string;
var
v: string;
begin
v := PrepareValue(FloatToStr(value),'double');
response := RawRequest( address, command, v, '' );
if not error then
Result := GetStringResult( response );
end;
function RequestStr( address, command: string; value: boolean): string;
var
v: string;
begin
v := PrepareValue(IntToStr(Ord(value)),'boolean');
response := RawRequest( address, command, v, '' );
if not error then
Result := GetStringResult( response );
end;
function RequestInt( address, command: string): integer;
begin
Result := RequestInt( address, command, '', '');
end;
function RequestInt( address, command, value: string): integer;
begin
Result := RequestInt( address, command, value, '');
end;
function RequestInt( address, command, value1, value2: string): integer;
var
v1, v2: string;
begin
Result := -1; v1 := ''; v2 := '';
if Length(value1) > 0 then
v1 := PrepareStringValue(value1,false);
if Length(value2) > 0 then
v2 := PrepareStringValue(value2,false);
response := RawRequest( address, command, v1, v2);
if not error then
Result := GetIntegerResult( response );
end;
function RequestInt( address, command: string; value: integer): integer;
var
v: string;
begin
v := PrepareValue(IntToStr(value),'i4');
response := RawRequest( address, command, v, '' );
if not error then
Result := GetIntegerResult( response );
end;
function RequestError: boolean;
begin
Result := error;
end;
function RequestFloat( address, command: string): double;
begin
Result := RequestFloat( address, command, '', '');
end;
function RequestFloat( address, command, value: string): double;
begin
Result := RequestFloat( address, command, value, '');
end;
function RequestFloat( address, command, value1, value2: string): double;
var
v1, v2: string;
begin
Result := -1; v1 := ''; v2 := '';
if Length(value1) > 0 then
v1 := PrepareStringValue(value1,false);
if Length(value2) > 0 then
v2 := PrepareStringValue(value2,false);
response := RawRequest( address, command, v1, v2);
if not error then
Result := GetFloatResult( response );
end;
function RequestBool( address, command: string): boolean;
begin
Result := RequestBool( address, command, '', '');
end;
function RequestBool( address, command, value: string): boolean;
begin
Result := RequestBool( address, command, value, '');
end;
function RequestBool( address, command, value1, value2: string): boolean;
var
v1, v2: string;
begin
Result := false; v1 := ''; v2 := '';
if Length(value1) > 0 then
v1 := PrepareStringValue(value1,false);
if Length(value2) > 0 then
v2 := PrepareStringValue(value2,false);
response := RawRequest( address, command, v1, v2);
if not error then
Result := GetBooleanResult( response );
end;
function GetLastError: string;
begin
Result := errstr;
end;
function GetLastResponse: string;
begin
Result := response;
end;
end.
|
unit BGColorForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin,
Vcl.ExtCtrls, Common;
type
TBGColor = class(TForm)
RedLabel: TLabel;
GreenLabel: TLabel;
BlueLabel: TLabel;
PreviewLabel: TLabel;
Image1: TImage;
RedSpin: TSpinEdit;
GreenSpin: TSpinEdit;
BlueSpin: TSpinEdit;
procedure FormCreate(Sender: TObject);
procedure RedSpinChange(Sender: TObject);
procedure GreenSpinChange(Sender: TObject);
procedure BlueSpinChange(Sender: TObject);
procedure RefreshColor();
private
{ Private declarations }
public
{ Public declarations }
end;
const
DEFAULT_BG_VAL = 15;
var
BGColor: TBGColor;
CommonInst: TCommon;
implementation
procedure TBGColor.FormCreate(Sender: TObject);
var color: TColor;
begin
color := Palettes[0][0];
RedSpin.Value := GetRValue(ColorToRGB(color)) div 16;
GreenSpin.Value := GetGValue(ColorToRGB(color)) div 16;
BlueSpin.Value := GetBValue(ColorToRGB(color)) div 16;
Image1.Canvas.Brush.Color := Palettes[0][0];
Image1.Canvas.FillRect(Rect(0,0,Image1.Width,Image1.Height));
end;
{$R *.dfm}
procedure TBGColor.BlueSpinChange(Sender: TObject);
begin
RefreshColor();
end;
procedure TBGColor.GreenSpinChange(Sender: TObject);
begin
RefreshColor();
end;
procedure TBGColor.RedSpinChange(Sender: TObject);
begin
RefreshColor();
end;
procedure TBGColor.RefreshColor();
var i: Integer;
begin
if (RedSpin.Value = 15) and (GreenSpin.Value = 15) and (BlueSpin.Value = 15) then
begin
Image1.Canvas.Brush.Color := clWhite;
for i := 0 to 15 do
Palettes[i][0] := clWhite;
end
else
begin
Image1.Canvas.Brush.Color := RGB(RedSpin.Value*16,GreenSpin.Value*16,BlueSpin.Value*16);
for i := 0 to 15 do
Palettes[i][0] := RGB(RedSpin.Value*16,GreenSpin.Value*16,BlueSpin.Value*16);
end;
Image1.Canvas.FillRect(Rect(0,0,Image1.Width,Image1.Height));
CommonInst.Redraw;
end;
end.
|
{ Procedure STRING_READIN (S)
*
* Read the next line from standard input into string S.
* All trailing blanks are deleted.
*
* This version is for the Microsoft Win32 API.
}
module string_readin;
define string_readin;
%include 'string2.ins.pas';
%include 'string_sys.ins.pas';
const
bufsz = 1024; {max bytes the input buffer can hold}
buflast = bufsz - 1; {last valid BUF array index}
var
buf: array[0..buflast] of int8u_t; {buffer of previously-read bytes}
nbuf: sys_int_machine_t := 0; {number of bytes in BUF}
bufnext: sys_int_machine_t; {index of next byte to read from buffer}
procedure string_readin ( {read and unpad next line from standard input}
in out s: univ string_var_arg_t); {output string}
const
max_msg_parms = 1; {max parameters we can pass to a message}
cr = chr(13); {carriage return character}
var
h: win_handle_t; {handle to system I/O connection}
c: char; {scratch character}
n: win_dword_t; {number of characters actually read in}
nblanks: sys_int_machine_t; {number of blanks read but not written}
ok: win_bool_t; {not WIN_BOOL_FALSE_K on system call success}
ovl: overlap_t; {state used during overlapped I/O}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t;
label
abort_winerr, next_char, leave;
begin
sys_error_none (stat); {init STAT to indicate no error}
h := GetStdHandle (stdstream_in_k); {get handle to standard input I/O connection}
if h = handle_invalid_k then begin
sys_msg_parm_int (msg_parm[1], stdstream_in_k);
sys_sys_error_bomb ('file', 'open_stream', msg_parm, 1);
end;
ovl.offset := 0;
ovl.offset_high := 0;
ovl.event_h := CreateEventA ( {create event for overalpped I/O}
nil, {no security attributes supplied}
win_bool_true_k, {no automatic event reset on successful wait}
win_bool_false_k, {init event to not triggered}
nil); {no name supplied}
if ovl.event_h = handle_none_k then begin {error creating event ?}
abort_winerr:
stat.sys := GetLastError;
sys_error_abort (stat, '', '', nil, 0);
sys_bomb;
end;
s.len := 0; {init output buffer to empty}
nblanks := 0; {init to no pending blanks saved up}
next_char: {back here each new character to read}
while nbuf = 0 do begin {wait for something to be read into the buffer}
ok := ReadFile ( {try to read another chunk into the buffer}
h, {system I/O connection handle}
buf, {input buffer}
bufsz, {number of bytes to read}
n, {number of bytes actually read in}
addr(ovl)); {pointer to overlapped I/O state}
if ok = win_bool_false_k then begin {system call failed ?}
if GetLastError <> err_io_pending_k then begin {hard error ?}
sys_sys_error_bomb ('string', 'err_readin', nil, 0);
end;
ok := GetOverlappedResult ( {wait for I/O to complete}
h, {handle that I/O is pending on}
ovl, {overlapped I/O state}
n, {number of bytes transferred}
win_bool_true_k); {wait for I/O to complete}
if ok = win_bool_false_k then goto abort_winerr;
end;
if n = 0 then goto leave; {hit end of file ?}
nbuf := n; {update number of bytes now in the buffer}
bufnext := 0; {init index of next byte to read from buffer}
end;
c := chr(buf[bufnext]); {fetch this byte from the buffer}
bufnext := bufnext + 1; {advance the buffer read index}
nbuf := nbuf - 1; {count one less byte in the buffer}
if ord(c) = end_of_line then goto leave; {hit end of line character ?}
if c = ' '
then begin {this is a blank ?}
nblanks := nblanks + 1; {count one more consecutive blank}
end
else begin {this is a non-blank character ?}
while nblanks > 0 do begin {loop to write all pending blanks}
string_append1 (s, ' ');
nblanks := nblanks - 1;
end;
string_append1 (s, c); {write new character to end of string}
end
;
goto next_char; {back and read next character from file}
leave: {common exit point}
discard( CloseHandle(ovl.event_h) ); {deallocate I/O completion event}
if (s.len > 0) and (s.str[s.len] = cr) then begin {string ends with CR ?}
s.len := s.len - 1; {truncate trailing CR character}
end;
end;
|
unit mp3stream;
interface
uses
SysUtils,
Windows,
Classes,
mpg123,
DSoutput,
httpstream,
main,
utils;
type
TMP3 = class(TRadioPlayer)
private
fHandle: Pmpg123_handle;
fStream: THTTPSTREAM;
protected
procedure updatebuffer(const offset: Cardinal); override;
function initbuffer: LongBool;
function prebuffer: LongBool; override;
public
function GetProgress(): Integer; override;
//function GetTrack(): string; override;
procedure GetInfo(var Atitle, Aquality: string); override;
function Open(const url: string): LongBool; override;
constructor Create();
destructor Destroy; override;
end;
implementation
{ TMP3 }
function TMP3.GetProgress(): Integer;
begin
Result := fStream.BuffFilled;
end;
procedure TMP3.GetInfo(var Atitle, Aquality: string);
begin
fStream.GetMetaInfo(Atitle, Aquality);
Aquality := Aquality + 'k mp3';
end;
destructor TMP3.Destroy;
begin
inherited;
fStream.Free;
mpg123_delete(fHandle);
end;
function TMP3.initbuffer: LongBool;
var
r: Integer;
begin
Result := False;
mpg123_open_feed(fHandle);
repeat
r := mpg123_decode(fHandle, fStream.GetBuffer(), BUFFPACKET, nil, 0, nil);
fStream.NextBuffer();
until (r = MPG123_NEW_FORMAT) or (fStream.BuffFilled = 0);
mpg123_getformat(Fhandle, @Frate, @Fchannels, nil);
if Fchannels = 0 then
begin
//RaiseError('discovering audio format', False);
Exit;
end;
fHalfbuffersize := fDS.InitializeBuffer(fRate, fChannels);
Result := True;
end;
function TMP3.Open(const url: string): LongBool;
begin
Result := fStream.open(url);
if not Result then
begin
Terminate;
Resume;
end;
end;
function TMP3.prebuffer: LongBool;
begin
Result := False;
// WAIT TO PREBUFFER!
repeat
Sleep(64);
if Terminated then Exit;
until fStream.BuffFilled > BUFFPRE;
Result := initbuffer();
end;
procedure TMP3.updatebuffer(const offset: Cardinal);
var
dsbuf: PByteArray;
dssize, Decoded, done : Cardinal;
r: Integer;
begin
DSERROR(fDS.SoundBuffer.Lock(offset, Fhalfbuffersize, @dsbuf, @dssize, nil, nil, 0), 'locking buffer');
Decoded := 0;
r := MPG123_NEED_MORE;
repeat
if Terminated then Exit;
// Repeat code that fills the DS buffer
if (fStream.BuffFilled > 0) then
begin
if r = MPG123_NEED_MORE then
begin
r := mpg123_decode(Fhandle, fStream.GetBuffer(), BUFFPACKET, @dsbuf[Decoded], dssize - Decoded, @done);
fStream.NextBuffer();
end
else
r := mpg123_decode(Fhandle, nil, 0, @dsbuf[Decoded], dssize - Decoded, @done);
Inc(Decoded, done);
end
else
begin
NotifyForm(NOTIFY_BUFFER, BUFFER_RECOVERING);
fDS.Stop;
repeat
Sleep(64);
if Terminated then Exit;
until fStream.BuffFilled > BUFFRESTORE;
fDS.Play;
NotifyForm(NOTIFY_BUFFER, BUFFER_OK);
end;
until (r <> MPG123_NEED_MORE);
if (r = MPG123_OK) then
fDS.SoundBuffer.Unlock(dsbuf, dssize, nil, 0)
else
begin
fDS.Stop;
initbuffer();
fDS.Play;
end;
end;
constructor TMP3.Create();
begin
inherited;
fStream := THTTPSTREAM.Create('audio/mpeg');
fHandle := mpg123_parnew(nil, nil, nil); //i586 :|
if Fhandle = nil then
RaiseError('creating MPEG decoder');
end;
initialization
{$IFDEF DEBUG}
Debug('mp3 init');
{$ENDIF}
mpg123_init();
{$IFDEF DEBUG}
Debug('mp3 init ok');
{$ENDIF}
//finalization
// mpg123_exit();
end.
|
unit ufrmConceptos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDialogo, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, Data.DB, IBCustomDataSet, IBTable, Vcl.ExtCtrls, Vcl.DBCtrls, JvDBControls, GridsEh,
DBAxisGridsEh, DBGridEh, Vcl.ComCtrls, JvExComCtrls, JvComCtrls, FlatHeader, Vcl.Menus, System.Actions, Vcl.ActnList;
type
TfrmConceptos = class(TfrmDialogo)
page1: TJvPageControl;
tsCargos: TTabSheet;
gridCargos: TDBGridEh;
navCargos: TJvDBNavigator;
TblOperaciones: TIBTable;
dsOperaciones: TDataSource;
TblOperacionesID: TLargeintField;
TblOperacionesNOMBRE: TIBStringField;
TblOperacionesOPERACION: TIBStringField;
TblOperacionesUNIDAD: TIBStringField;
TblOperacionesCALCULADO: TIBStringField;
TblOperacionesDIA_APLICAR: TSmallintField;
TblOperacionesDESCRIPCION: TIBStringField;
TblOperacionesCODIGO: TWideMemoField;
actnlst1: TActionList;
actExportarCSV: TAction;
pm1: TPopupMenu;
mnuExportarCSV: TMenuItem;
procedure actExportarCSVExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmConceptos: TfrmConceptos;
implementation
uses
Datos, DanFW.InterbaseDBExpress, DanFW.Data.Export;
{$R *.dfm}
procedure TfrmConceptos.actExportarCSVExecute(Sender: TObject);
begin
inherited;
ExportarCSV(dsOperaciones.DataSet);
end;
end.
|
unit NumInput;
{ ************************************************************************** }
{ * Numeric Input for Turbo Vision version 2 * }
{ * ---------------------------------------- * }
{ * * }
{ * Offers you the possibility of Byte-, Word- Integer and * }
{ * Longint-inputlines. * }
{ * * }
{ * Byte- and Word-inputlines are range-checked at the moment the data * }
{ * is entered, so no validation-checking afterwards is needed. * }
{ * * }
{ * Warning: Let the length of your inputview be long enough, because * }
{ * the scrolling of this unit is not that good. (In my * }
{ * opinion not necessary) * }
{ * * }
{ * Author: Edwin Groothuis (S89405079@hsepm1.hse.nl or 2:284/205.1) * }
{ * How to newer versions: * }
{ * internet-users: * }
{ * garbo.uwasa.fi:/pc/turbovis/numinp#.zip * }
{ * oak.oakland.edu:/pub/msdos/turbovis/numinp#.zip * }
{ * fidonet-users: * }
{ * freq NUMINP at 2:284/205 (+31-40-550352) * }
{ * download NUMINP#.ZIP from 2:284/205 area: TurboPascal * }
{ * * }
{ * The source is hereby Public Domain, no warrenties are made, feel free * }
{ * to modify or update. Please send bugs reports/fixes to me. * }
{ * * }
{ ************************************************************************** }
{$F+}
interface
uses dialogs,drivers,objects;
type
{ A ByteInputLine gives you a byte. Can be in the range of 0..255 }
PByteInputLine=^TByteInputLine;
TByteInputLine=object(TInputLine)
constructor Init(var Bounds:TRect);
procedure HandleEvent(var E:TEvent);virtual;
function DataSize:Word;virtual;
procedure GetData(var Rec);virtual;
procedure SetData(var Rec);virtual;
end;
{ A WordInputLine gives you a word. Can be in the range of 0..65535 }
PWordInputLine=^TWordInputLine;
TWordInputLine=object(TInputLine)
constructor Init(var Bounds:TRect);
procedure HandleEvent(var E:TEvent);virtual;
function DataSize:Word;virtual;
procedure GetData(var Rec);virtual;
procedure SetData(var Rec);virtual;
end;
{ A IntInputLine gives you a integer. Can be in the range of -32768..32767 }
PIntInputLine=^TIntInputLine;
TIntInputLine=object(TInputLine)
constructor Init(var Bounds:TRect);
procedure HandleEvent(var E:TEvent);virtual;
function DataSize:Word;virtual;
procedure GetData(var Rec);virtual;
procedure SetData(var Rec);virtual;
end;
{ A LongInputLine gives you a longint. Can be in the range of -2147483648..2147483647 }
PLongintInputLine=^TLongintInputLine;
TLongintInputLine=object(TInputLine)
constructor Init(var Bounds:TRect);
procedure HandleEvent(var E:TEvent);virtual;
function DataSize:Word;virtual;
procedure GetData(var Rec);virtual;
procedure SetData(var Rec);virtual;
end;
implementation
{****************************************************************************}
{****************************************************************************}
constructor TByteInputLine.Init(var Bounds:TRect);
begin
Inherited Init(Bounds,3);
end;
procedure TByteInputLine.HandleEvent(var E:TEvent);
var s:string;
l:longint;
code:integer;
begin
inherited HandleEvent(e);
s:=Data^;
val(s,l,code);
if code=0 then { everything seems to be OK }
begin
if l>255 then { It was meant to be a byte, so remove the
last inputted character }
begin
system.Delete(s,CurPos,1);
Dec(CurPos);
end else begin
if pos(' ',s)<>0 then { yes, it was entered }
begin
system.delete(s,pos(' ',s),1);
Dec(CurPos);
end else begin
if s[1]='0' then { don't let something begin with a 0! }
begin
system.delete(s,1,1);
Dec(CurPos);
end else begin { everything IS ok }
{ PARTY! }
end;
end;
end;
end else begin { ohoh... integer overflow or non-numericalcharacter typed
just kill the last inputted character of the string }
if s[0]<>#0 then { but don't make it smaller than it can be }
begin
system.Delete(s,CurPos,1);
Dec(CurPos);
end;
end;
Data^:=s;
inherited Draw;
end;
function TByteInputLine.DataSize:Word;
begin
DataSize:=1;
end;
procedure TByteInputLine.SetData(var Rec);
begin
str(Byte(Rec),Data^);
end;
procedure TByteInputLine.GetData(var Rec);
var code:integer;
begin
val(Data^,Byte(Rec),code);
end;
{****************************************************************************}
constructor TWordInputLine.Init(var Bounds:TRect);
begin
Inherited Init(Bounds,5);
end;
procedure TWordInputLine.HandleEvent(var E:TEvent);
var s:string;
l:longint;
code:integer;
begin
inherited HandleEvent(e);
s:=Data^;
val(s,l,code);
if code=0 then { everything seems to be OK }
begin
if l>longint($FFFF) then { It was meant to be a word, so remove the
last inputted character }
begin
system.Delete(s,CurPos,1);
Dec(CurPos);
end else begin
if pos(' ',s)<>0 then { yes, it was entered }
begin
system.delete(s,pos(' ',s),1);
Dec(CurPos);
end else begin
if s[1]='0' then { don't let something begin with a 0! }
begin
system.delete(s,1,1);
Dec(CurPos);
end else begin { everything IS ok }
{ PARTY! }
end;
end;
end;
end else begin { ohoh... integer overflow or non-numericalcharacter typed
just kill the last inputted character of the string }
if s[0]<>#0 then { but don't make it smaller than it can be }
begin
system.Delete(s,CurPos,1);
Dec(CurPos);
end;
end;
Data^:=s;
inherited Draw;
end;
function TWordInputLine.DataSize:Word;
begin
DataSize:=2;
end;
procedure TWordInputLine.SetData(var Rec);
begin
str(Word(Rec),Data^);
end;
procedure TWordInputLine.GetData(var Rec);
var code:integer;
begin
val(Data^,Word(Rec),code);
end;
{****************************************************************************}
constructor TIntInputLine.Init(var Bounds:TRect);
begin
Inherited Init(Bounds,6);
end;
procedure TIntInputLine.HandleEvent(var E:TEvent);
var s,t:string;
l:longint;
code:integer;
len:byte;
begin
len:=length(Data^);
inherited HandleEvent(e);
s:=Data^;
if e.charcode='-' then
begin
t:=copy(s,pos('-',s)+1,length(s));
if pos('-',t)=0 then
begin
if length(s)<>len then
begin
system.Delete(s,CurPos,1);
system.Insert('-',s,1);
end else begin
system.Delete(s,1,1);
Dec(CurPos);
end;
end else begin
system.Delete(s,CurPos,1);
system.Delete(s,1,1);
Dec(CurPos,2);
end;
end;
val(s,l,code);
if code=0 then { everything seems to be OK }
begin
if l>longint(32767) then { It was meant to be an integer, so remove the
last inputted character }
begin
system.Delete(s,CurPos,1);
Dec(CurPos);
end else begin
if l<longint(-32768) then { It was meant to be an integer, so remove the
last inputted character }
begin
system.Delete(s,CurPos,1);
Dec(CurPos);
end else begin
if pos(' ',s)<>0 then { yes, it was entered }
begin
system.delete(s,pos(' ',s),1);
Dec(CurPos);
end else begin
if s[1]='0' then { don't let something begin with a 0! }
begin
system.delete(s,1,1);
Dec(CurPos);
end else begin { everything IS ok }
{ PARTY! }
end;
end;
end;
end;
end else begin { ohoh... integer overflow or non-numericalcharacter typed
just kill the last inputted character of the string }
if s[0]<>#0 then { but don't make it smaller than it can be }
begin
system.Delete(s,CurPos,1);
Dec(CurPos);
end;
end;
Data^:=s;
inherited Draw;
end;
function TIntInputLine.DataSize:Word;
begin
DataSize:=2;
end;
procedure TIntInputLine.SetData(var Rec);
begin
str(Integer(Rec),Data^);
end;
procedure TIntInputLine.GetData(var Rec);
var code:integer;
begin
val(Data^,Integer(Rec),code);
end;
{****************************************************************************}
constructor TLongintInputLine.Init(var Bounds:TRect);
begin
Inherited Init(Bounds,11);
end;
procedure TLongintInputLine.HandleEvent(var E:TEvent);
var s,t:string;
l:longint;
code:integer;
len:byte;
begin
len:=length(Data^);
inherited HandleEvent(e);
s:=Data^;
if e.charcode='-' then
begin
t:=copy(s,pos('-',s)+1,length(s));
if pos('-',t)=0 then
begin
if length(s)<>len then
begin
system.Delete(s,CurPos,1);
system.Insert('-',s,1);
end else begin
system.Delete(s,1,1);
Dec(CurPos);
end;
end else begin
system.Delete(s,CurPos,1);
system.Delete(s,1,1);
Dec(CurPos,2);
end;
end;
val(s,l,code);
if code=0 then { everything seems to be OK }
begin
if pos(' ',s)<>0 then { yes, it was entered }
begin
system.delete(s,pos(' ',s),1);
Dec(CurPos);
end else begin
if s[1]='0' then { don't let something begin with a 0! }
begin
system.delete(s,1,1);
Dec(CurPos);
end else begin { everything IS ok }
{ PARTY! }
end;
end;
end else begin { ohoh... integer overflow or non-numericalcharacter typed
just kill the last inputted character of the string }
if s[0]<>#0 then { but don't make it smaller than it can be }
begin
system.Delete(s,CurPos,1);
Dec(CurPos);
end;
end;
Data^:=s;
inherited Draw;
end;
function TLongintInputLine.DataSize:Word;
begin
DataSize:=4;
end;
procedure TLongintInputLine.SetData(var Rec);
begin
str(Longint(Rec),Data^);
end;
procedure TLongintInputLine.GetData(var Rec);
var code:integer;
begin
val(Data^,Longint(Rec),code);
end;
end.
{$F-}
|
unit InfraSQLBuilder;
interface
uses
Classes, InfraBase, InfraHibernateIntf;
type
TSelectBuilder = class(TInfraBaseObject, ISelectBuilder)
private
FDialect: IDialect;
FFromClause: String;
FGroupByClause: String;
FOrderByClause: String;
FOuterJoinsAfterFrom: String;
FOuterJoinsAfterWhere: String;
FSelectClause: String;
FWhereClause: String;
function ToStatementString: String;
procedure SetFromClause(const pTableName, pAlias: String); overload;
procedure SetFromClause(const Value: String); overload;
procedure SetGroupByClause(const Value: String);
procedure SetOrderByClause(const Value: String);
procedure SetOuterJoins(const pOuterJoinsAfterFrom,
pOuterJoinsAfterWhere: String);
procedure SetSelectClause(const Value: String);
procedure SetWhereClause(const Value: String); overload;
public
constructor Create(const pDialect: IDialect); reintroduce;
end;
TDeleteBuilder = class(TInfraBaseObject, IDeleteBuilder)
private
FDialect: IDialect;
FTableName: String;
FPrimaryKeyColumnNames: TStrings;
FWhereClause: String;
function ToStatementString: String;
procedure SetTableName(const Value: String);
procedure SetWhere(const Value: String);
procedure SetPrimaryKeyColumnNames(const Value: string);
public
constructor Create(const pDialect: IDialect); reintroduce;
end;
(*
TUpdateBuilder = class(TInfraBaseObject, IUpdateBuilder)
private
FTableName: String;
FPrimaryKeyColumnNames: TArrayString;
FVersionColumnName: String;
FWhereClause: String;
FAssignments: String;
FColumns: Map;
FWhereColumns: Map;
FDialect: IDialect;
function GetTableName: string;
function ToStatementString: String;
procedure AddColum(const ColumnName, Value: string);
procedure AddColum(const ColumnName: string);
procedure AddColum(const ColumnName: string; const Value: IInfraType);
procedure AddColumns(Value: TArrayString);
procedure AddColumns(Value: TArrayString; const Value: string);
procedure AddColumns(Value: TArrayString; Updateable: TArrayBoolean);
procedure AddWhereColumn(const ColumnName, Value: String);
procedure AddWhereColumn(const ColumnName: String);
procedure AddWhereColumns(ColumnNames: TArrayString);
procedure AddWhereColumns(ColumnNames: TArrayString; const Value: String);
procedure AppendAssignmentFragment(const Value: String);
procedure SetPrimaryKeyColumnNames(Value: TArrayString);
procedure SetTableName(const Value: string);
procedure SetWhere(const Where: String);
property TableName: string read GetTableName write SetTableName;
end;
*)
implementation
uses SysUtils;
{ TSelectBuilder }
constructor TSelectBuilder.Create(const pDialect: IDialect);
begin
// *** Leak aqui?
FDialect := pDialect;
end;
function TSelectBuilder.ToStatementString: String;
var
vBuf: TStrings;
begin
vBuf := TStringList.Create;
try
with vBuf do
begin
Add('SELECT ');
Add(FSelectClause);
Add('FROM ');
Add(FFromClause);
Add(FOuterJoinsAfterFrom);
if (FWhereClause <> EmptyStr) or (FOuterJoinsAfterWhere <> EmptyStr) then
begin
Add('WHERE ');
if (FOuterJoinsAfterWhere <> EmptyStr) then
begin
Add(FOuterJoinsAfterWhere);
if (FWhereClause <> EmptyStr) then
Add(' AND ');
end;
if (FWhereClause <> EmptyStr) then
Add(FWhereClause);
end;
if (FGroupByClause <> EmptyStr) then
begin
Add('GROUP BY ');
Add(FGroupByClause);
end;
if (FOrderByClause <> EmptyStr) then
begin
Add('ORDER BY ');
Add(FOrderByClause);
end;
end;
finally
// ### No hibernate:
// Hรก a possibilidade de transformar a instruรงรฃo pelo Dialect. Ver isso
// depois, lembrando que esta classe terรก de receber
// Result := Dialect.TransformSelectString(vBuf.Text);
// em vez do result abaixo.
Result := vBuf.Text;
vBuf.Free;
end;
end;
procedure TSelectBuilder.SetFromClause(const Value: String);
begin
FFromClause := Value;
end;
procedure TSelectBuilder.SetFromClause(const pTableName, pAlias: String);
begin
FFromClause := pTableName + ' ' + pAlias;
end;
procedure TSelectBuilder.SetOrderByClause(const Value: String);
begin
FOrderByClause := Value;
end;
procedure TSelectBuilder.SetGroupByClause(const Value: String);
begin
FGroupByClause := Value;
end;
procedure TSelectBuilder.SetOuterJoins(const pOuterJoinsAfterFrom,
pOuterJoinsAfterWhere: String);
var
vTmpOuterJoinsAfterWhere: String;
begin
FOuterJoinsAfterFrom := pOuterJoinsAfterFrom;
vTmpOuterJoinsAfterWhere := Trim(pOuterJoinsAfterWhere);
if TStringHelper.StartsWith(vTmpOuterJoinsAfterWhere, 'and') then
vTmpOuterJoinsAfterWhere :=
TStringHelper.Substring(vTmpOuterJoinsAfterWhere, 4);
FOuterJoinsAfterWhere := vTmpOuterJoinsAfterWhere;
end;
procedure TSelectBuilder.SetSelectClause(const Value: String);
begin
FSelectClause := Value;
end;
procedure TSelectBuilder.SetWhereClause(const Value: String);
begin
FWhereClause := Value;
end;
{ TDeleteBuilder }
constructor TDeleteBuilder.Create(const pDialect: IDialect);
begin
// *** Leak aqui?
FDialect := pDialect;
end;
procedure TDeleteBuilder.setPrimaryKeyColumnNames(const Value: String);
begin
// *** vai vir uma string de campos separados por virgula ou
// *** FPrimaryKeyColumnNames := Value;
end;
procedure TDeleteBuilder.SetTableName(const Value: String);
begin
FTableName := Value;
end;
procedure TDeleteBuilder.SetWhere(const Value: String);
begin
FTableName := Value;
end;
function TDeleteBuilder.toStatementString: String;
var
vBuf: TStrings;
vConditionsAppended: boolean;
begin
vBuf := TStringList.Create;
try
with vBuf do
begin
Add('delete from ');
Add(FTableName);
if (FWhereClause <> EmptyStr)
or (FPrimaryKeyColumnNames.Count <> 0) then
begin
Add(' WHERE ');
vConditionsAppended := False;
if (FPrimaryKeyColumnNames.Count <> 0) then
begin
Add(TStringHelper.Join('=? and ', FPrimaryKeyColumnNames) + '=?');
vConditionsAppended := True;
end;
if (FWhereClause <> EmptyStr) then
begin
if vConditionsAppended then
Add(' and ');
Add(FWhereClause);
end;
end;
end;
finally
Result := vBuf.Text;
vBuf.Free;
end;
end;
(*
{ TUpdateBuilder }
function TUpdateBuilder.GetTableName: string;
begin
end;
procedure TUpdateBuilder.SetTableName(const Value: string);
begin
FTableName := Value;
end;
function TUpdateBuilder.ToStatementString: String;
begin
end;
*)
end.
|
unit LuaRadioGroup;
{$mode delphi}
interface
uses
Classes, Controls, ExtCtrls, SysUtils;
procedure initializeLuaRadioGroup;
implementation
uses lua, lualib, lauxlib, LuaHandler, ceguicomponents, LuaCaller, LuaGroupbox, LuaClass, betterControls;
function createRadioGroup(L: Plua_State): integer; cdecl;
var
RadioGroup: TCERadioGroup;
parameters: integer;
owner: TWincontrol;
begin
result:=0;
parameters:=lua_gettop(L);
if parameters>=1 then
owner:=lua_toceuserdata(L, -parameters)
else
owner:=nil;
lua_pop(L, lua_gettop(L));
RadioGroup:=TCERadioGroup.Create(owner);
if owner<>nil then
RadioGroup.Parent:=owner;
luaclass_newClass(L, RadioGroup);
result:=1;
end;
function radiogroup_getRows(L: PLua_State): integer; cdecl;
var
radiogroup: TCustomRadioGroup;
begin
radiogroup:=luaclass_getClassObject(L);
lua_pushinteger(L, radiogroup.Rows);
result:=1;
end;
function radiogroup_getItems(L: PLua_State): integer; cdecl;
var
radiogroup: TCustomRadioGroup;
begin
radiogroup:=luaclass_getClassObject(L);
luaclass_newClass(L, radiogroup.items);
result:=1;
end;
function radiogroup_getColumns(L: PLua_State): integer; cdecl;
var
radiogroup: TCustomRadioGroup;
begin
radiogroup:=luaclass_getClassObject(L);
lua_pushinteger(L, radiogroup.Columns);
result:=1;
end;
function radiogroup_setColumns(L: PLua_State): integer; cdecl;
var
radiogroup: Tcustomradiogroup;
begin
result:=0;
radiogroup:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
radiogroup.Columns:=lua_tointeger(L,-1);
end;
function radiogroup_getItemIndex(L: PLua_State): integer; cdecl;
var
radiogroup: TCustomRadioGroup;
begin
radiogroup:=luaclass_getClassObject(L);
lua_pushinteger(L, radiogroup.ItemIndex);
result:=1;
end;
function radiogroup_setItemIndex(L: PLua_State): integer; cdecl;
var
radiogroup: Tcustomradiogroup;
begin
result:=0;
radiogroup:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
radiogroup.ItemIndex:=lua_tointeger(L,-1);
end;
function radiogroup_getonclick(L: PLua_State): integer; cdecl;
var
c: TCustomRadioGroup;
begin
c:=luaclass_getClassObject(L);
LuaCaller_pushMethodProperty(L, TMethod(c.OnClick), 'TNotifyEvent');
result:=1;
end;
function radiogroup_setonClick(L: PLua_State): integer; cdecl; //for some reason the radiogroup has it's own fonclick variable
var
control: TCustomRadioGroup;
f: integer;
routine: string;
lc: TLuaCaller;
begin
result:=0;
control:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
begin
CleanupLuaCall(tmethod(control.onClick));
control.onClick:=nil;
if lua_isfunction(L,-1) then
begin
routine:=Lua_ToString(L,-1);
f:=luaL_ref(L,LUA_REGISTRYINDEX);
lc:=TLuaCaller.create;
lc.luaroutineIndex:=f;
control.OnClick:=lc.NotifyEvent;
end
else
if lua_isstring(L,-1) then
begin
routine:=lua_tostring(L,-1);
lc:=TLuaCaller.create;
lc.luaroutine:=routine;
control.OnClick:=lc.NotifyEvent;
end;
end;
end;
procedure radiogroup_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
begin
groupbox_addMetaData(L, metatable, userdata);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getRows', radiogroup_getRows);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getItems', radioGroup_getItems);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getColumns', radiogroup_getColumns);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setColumns', radiogroup_setColumns);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'getItemIndex', radiogroup_getItemIndex);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setItemIndex', radiogroup_setItemIndex);
luaclass_addClassFunctionToTable(L, metatable, userdata, 'setOnClick', radiogroup_setOnClick);
luaclass_addPropertyToTable(L, metatable, userdata, 'Columns', radiogroup_getColumns, radiogroup_setColumns);
luaclass_addPropertyToTable(L, metatable, userdata, 'ItemIndex', radiogroup_getItemIndex, radiogroup_setItemIndex);
luaclass_addPropertyToTable(L, metatable, userdata, 'OnClick', radiogroup_getOnClick, radiogroup_setOnClick);
luaclass_addPropertyToTable(L, metatable, userdata, 'Items', radioGroup_getItems, nil);
end;
procedure initializeLuaRadioGroup;
begin
lua_register(LuaVM, 'createRadioGroup', createRadioGroup);
lua_register(LuaVM, 'radiogroup_getRows', radiogroup_getRows);
lua_register(LuaVM, 'radiogroup_getItems', radioGroup_getItems);
lua_register(LuaVM, 'radiogroup_getColumns', radiogroup_getColumns);
lua_register(LuaVM, 'radiogroup_setColumns', radiogroup_setColumns);
lua_register(LuaVM, 'radiogroup_getItemIndex', radiogroup_getItemIndex);
lua_register(LuaVM, 'radiogroup_setItemIndex', radiogroup_setItemIndex);
lua_register(LuaVM, 'radiogroup_onClick', radiogroup_setOnClick);
end;
initialization
luaclass_register(TCustomRadioGroup, radiogroup_addMetaData);
end.
|
unit ViewMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
System.Actions, Vcl.ActnList, MyUtils;
type
TWindowMain = class(TForm)
MemoText: TMemo;
MemoResult: TMemo;
LblText: TLabel;
LblResult: TLabel;
Actions: TActionList;
ActUppercase: TAction;
ActLowercase: TAction;
ActCapitalized: TAction;
ActWhatsapp: TAction;
LblTotWithSpaces: TLabel;
LblTotLetters: TLabel;
LblTotNumbers: TLabel;
LblTotWithoutSpaces: TLabel;
ActLetters: TAction;
ActNumbers: TAction;
ActNoBreaklines: TAction;
ActCopyToText: TAction;
CheckWpp55: TCheckBox;
CheckWpp62: TCheckBox;
ActEsc: TAction;
BtnUppercase: TButton;
BtnLowercase: TButton;
BtnCapitalized: TButton;
BtnWppLink: TButton;
BtnLetters: TButton;
BtnNumbers: TButton;
BtnNoBreaklines: TButton;
SpeedButton8: TButton;
SpeedButton1: TButton;
BtnCopyText: TButton;
procedure ActCapitalizedExecute(Sender: TObject);
procedure ActLowercaseExecute(Sender: TObject);
procedure ActUppercaseExecute(Sender: TObject);
procedure ActWhatsappExecute(Sender: TObject);
procedure MemoTextChange(Sender: TObject);
procedure ActLettersExecute(Sender: TObject);
procedure ActNumbersExecute(Sender: TObject);
procedure ActNoBreaklinesExecute(Sender: TObject);
procedure ActCopyToTextExecute(Sender: TObject);
procedure ActEscExecute(Sender: TObject);
private
function Capitalize(s: string): string;
procedure FocusAndSelect;
{ Private declarations }
public
{ Public declarations }
end;
var
WindowMain: TWindowMain;
implementation
{$R *.dfm}
procedure TWindowMain.ActUppercaseExecute(Sender: TObject);
begin
MemoResult.Text := UpperCase(MemoText.Text);
FocusAndSelect;
end;
procedure TWindowMain.ActLowercaseExecute(Sender: TObject);
begin
MemoResult.Text := LowerCase(MemoText.Text);
FocusAndSelect;
end;
procedure TWindowMain.ActCapitalizedExecute(Sender: TObject);
begin
MemoResult.Text := Capitalize(MemoText.Text);
FocusAndSelect;
end;
procedure TWindowMain.ActLettersExecute(Sender: TObject);
var
Text: string;
begin
MemoResult.Clear;
for Text in MemoText.Lines do
begin
MemoResult.Lines.Add(TUtils.ExtractLetters(Text));
end;
FocusAndSelect;
end;
procedure TWindowMain.ActNumbersExecute(Sender: TObject);
var
Text: string;
begin
MemoResult.Clear;
for Text in MemoText.Lines do
begin
MemoResult.Lines.Add(TUtils.ExtractNumbers(Text));
end;
FocusAndSelect;
end;
procedure TWindowMain.ActWhatsappExecute(Sender: TObject);
var
Text, WppNumber: string;
begin
MemoResult.Clear;
for Text in MemoText.Lines do
begin
WppNumber := TUtils.ExtractNumbers(Text);
if CheckWpp62.Checked then
WppNumber := '62' + WppNumber;
if CheckWpp55.Checked then
WppNumber := '55' + WppNumber;
MemoResult.Lines.Add('https://api.whatsapp.com/send?phone=' + WppNumber);
end;
FocusAndSelect;
end;
procedure TWindowMain.ActNoBreaklinesExecute(Sender: TObject);
var
Text: string;
begin
MemoResult.Clear;
for Text in MemoText.Lines do
begin
MemoResult.Text := MemoResult.Text + ' ' + Text;
end;
FocusAndSelect;
end;
procedure TWindowMain.ActCopyToTextExecute(Sender: TObject);
begin
MemoText.Text := MemoResult.Text;
end;
//////////////////////////////////////////////////////////////
procedure TWindowMain.FocusAndSelect;
begin
MemoResult.SetFocus;
MemoResult.SelectAll;
end;
function TWindowMain.Capitalize(s: string): string;
var
flag: Boolean;
i: Byte;
t: string;
begin
flag := True;
s := AnsiLowerCase(s);
t := EmptyStr;
for i := 1 to Length(s) do
begin
if flag then
t := t + AnsiUpperCase(s[i])
else
t := t + s[i];
flag := (s[i] = ' ')
end;
Result := t;
end;
procedure TWindowMain.MemoTextChange(Sender: TObject);
var
Line: string;
TotWithSpaces, TotWithoutSpaces, TotLetters, TotNumbers: integer;
begin
for Line in MemoText.Lines do
begin
TotWithSpaces := TotWithSpaces + Line.Length;
TotWithoutSpaces := TotWithoutSpaces + Line.Replace(' ', '').Length;
TotLetters := TotLetters + TUtils.ExtractLetters(Line).Length;
TotNumbers := TotNumbers + TUtils.ExtractNumbers(Line).Length;
end;
LblTotWithSpaces.Caption := 'Total Caracteres (com espaรงos): ' + TotWithSpaces.ToString;
LblTotWithoutSpaces.Caption := 'Total Caracteres (sem espaรงos): ' + TotWithoutSpaces.ToString;
LblTotLetters.Caption := 'Total Letras: ' + TotLetters.ToString;
LblTotNumbers.Caption := 'Total Nรบmeros: ' + TotNumbers.ToString;
end;
procedure TWindowMain.ActEscExecute(Sender: TObject);
begin
Close;
end;
end.
|
unit DBVMDebuggerInterface;
//limited debugger, but still useful
{$mode delphi}
interface
{$ifdef windows}
uses
jwawindows, windows, Classes, SysUtils,cefuncproc, newkernelhandler,
DebuggerInterface,contnrs, vmxfunctions;
{$else}
uses classes, DebuggerInterface;
{$endif}
type
TDBVMResumerThread=class(TThread)
public
{$ifdef windows}
procedure Execute; override; //frequently gets the frozen thread list and checks if it contains the CE process. If so, resume, and check more frequently
{$endif}
end;
TDBVMDebugInterface=class(TDebuggerInterface)
private
{$ifdef windows}
lastfrozenID: integer;
currentFrozenID: integer;
currentFrozenState: TPageEventExtended;
lastContinueWasAStep: boolean; //if the last continue was a step then wait for lastfrozenID specifically until it gets abandoned (or takes 5 seconds)
resumerThread: TDBVMResumerThread;
processCR3: qword;
procedure SteppingThreadLost;
function setBreakEvent(var lpDebugEvent: TDebugEvent; frozenThreadID: integer): boolean;
{$endif}
public
{$ifdef windows}
usermodeloopint3: qword;
kernelmodeloopint3: qword; static;
OnSteppingthreadLoss: TNotifyEvent;
constructor create;
destructor destroy; override;
function WaitForDebugEvent(var lpDebugEvent: TDebugEvent; dwMilliseconds: DWORD): BOOL; override;
function ContinueDebugEvent(dwProcessId: DWORD; dwThreadId: DWORD; dwContinueStatus: DWORD): BOOL; override;
function SetThreadContext(hThread: THandle; const lpContext: TContext; isFrozenThread: Boolean=false): BOOL; override;
function GetThreadContext(hThread: THandle; var lpContext: TContext; isFrozenThread: Boolean=false): BOOL; override;
function DebugActiveProcess(dwProcessId: DWORD): BOOL; override;
function needsToAttach: boolean; override;
function controlsTheThreadList: boolean; override;
function usesDebugRegisters: boolean; override;
{$endif}
end;
var dbvm_bp_unfreezeselfcounter: integer;
implementation
{$ifdef windows}
uses DBK32functions, ProcessHandlerUnit, symbolhandler, simpleaobscanner,
commonTypeDefs, symbolhandlerstructs, globals;
resourcestring
rsDBVMLevelNotFor32Bit = 'DBVM level debug does not work on the 32-bit CE';
rsDBVMFunctionNeedsDBVM = 'Sorry, but you need DBVM for DBVM level debugging';
procedure TDBVMResumerThread.Execute;
var
shortstate: TDBVMBPShortState;
listsize: integer;
sleeptime: integer;
i: integer;
inuse: byte;
continueMethod: byte;
cid: TClientID;
thisprocess: dword;
hadToUnfreeze: boolean;
begin
thisprocess:=GetCurrentProcessId;
sleeptime:=1000; //start with 1 second
while not terminated do
begin
hadToUnfreeze:=false;
listsize:=dbvm_bp_getBrokenThreadListSize;
for i:=0 to listsize-1 do
begin
if dbvm_bp_getBrokenThreadEventShort(i,shortstate)=0 then
begin
inuse:=shortstate.status and $ff;
continueMethod:=shortstate.status shl 8;
if (inuse=1) and (continueMethod=0) then
begin
if getClientIDFromDBVMBPShortState(shortstate, cid) then //assuming this works for CE (else just do not read that memory while a watch bp is going on. Perhaps a RPM/WPM hook)
begin
if cid.UniqueProcess=thisprocess then
begin
//a CE thread was frozen
hadToUnfreeze:=true;
dbvm_bp_resumeBrokenThread(i,2); //run, and be free little one
inc(dbvm_bp_unfreezeselfcounter);
end;
end;
end;
end;
end;
if hadToUnfreeze then
sleeptime:=sleeptime div 2
else
sleeptime:=min(1000, sleeptime*2+1);
if sleeptime=0 then
asm
pause
end;
sleep(sleeptime);
end;
end;
function TDBVMDebugInterface.setBreakEvent(var lpDebugEvent: TDebugEvent; frozenThreadID: integer):boolean;
var
watchid, status: integer;
clientid: TClientID;
begin
result:=false;
if dbvm_bp_getBrokenThreadEventFull(frozenThreadID, watchid, status, currentFrozenState)=0 then
begin
result:=true;
currentFrozenID:=frozenThreadID;
lpDebugEvent.dwDebugEventCode:=EXCEPTION_DEBUG_EVENT;
lpDebugEvent.Exception.dwFirstChance:=1;
lpDebugEvent.Exception.ExceptionRecord.ExceptionAddress:=pointer(currentFrozenState.basic.RIP);
lpDebugEvent.Exception.ExceptionRecord.ExceptionCode:=EXCEPTION_DBVM_BREAKPOINT;
lpDebugEvent.Exception.ExceptionRecord.ExceptionFlags:=watchid; //-1 when stepping
lpDebugEvent.Exception.ExceptionRecord.NumberParameters:=6;
lpDebugEvent.Exception.ExceptionRecord.ExceptionInformation[0]:=frozenThreadID;
lpDebugEvent.Exception.ExceptionRecord.ExceptionInformation[1]:=currentFrozenState.basic.CR3;
lpDebugEvent.Exception.ExceptionRecord.ExceptionInformation[2]:=currentFrozenState.basic.FSBASE;
lpDebugEvent.Exception.ExceptionRecord.ExceptionInformation[3]:=currentFrozenState.basic.GSBASE;
lpDebugEvent.Exception.ExceptionRecord.ExceptionInformation[4]:=currentFrozenState.basic.GSBASE_KERNEL;
lpDebugEvent.Exception.ExceptionRecord.ExceptionInformation[5]:=ifthen<ULONG_PTR>(processCR3<>currentFrozenState.basic.CR3,1,0);
if getClientIDFromDBVMBPState(currentFrozenState, clientID) then
begin
lpDebugEvent.dwProcessId:=clientID.UniqueProcess;
lpDebugEvent.dwThreadId:=clientID.UniqueThread;
if lpDebugEvent.dwProcessId=GetCurrentProcessId then exit(false); //resumer thread will do this one
end
else
begin
//failure getting it. Use the CR3 and GSBASE (or FSBASE if gs is 0)
lpDebugEvent.dwProcessId:=currentFrozenState.basic.CR3 or (1 shl 31); //set the MSB to signal it's a 'special' id (it's not big enough)
lpDebugEvent.dwThreadId:=currentFrozenState.basic.GSBASE;
if lpDebugEvent.dwThreadId=0 then
lpDebugEvent.dwThreadId:=currentFrozenState.basic.FSBASE;
if lpDebugEvent.dwThreadId=0 then
lpDebugEvent.dwThreadId:=currentFrozenState.basic.GSBASE_KERNEL;
lpDebugEvent.dwThreadId:=lpDebugEvent.dwThreadId or (1 shl 31);
end;
end;
end;
procedure TDBVMDebugInterface.SteppingThreadLost;
begin
if assigned(OnSteppingthreadLoss) then
OnSteppingthreadLoss(self);
end;
function TDBVMDebugInterface.WaitForDebugEvent(var lpDebugEvent: TDebugEvent; dwMilliseconds: DWORD): BOOL;
var
starttime: qword;
listsize: integer;
i: integer;
shortstate: TDBVMBPShortState;
inuse: byte;
continueMethod: byte;
cid: TClientID;
begin
starttime:=GetTickCount64;
result:=false;
repeat
listsize:=dbvm_bp_getBrokenThreadListSize; //being not 0 does not mean there is an active bp, check if one is active (never goes down)
if lastContinueWasAStep then
begin
lastContinueWasAStep:=false;
//wait 5 seconds for this one
while gettickcount64<starttime+5000 do
begin
if dbvm_bp_getBrokenThreadEventShort(lastfrozenID, shortstate)=0 then
begin
if (shortstate.status and $ff)=2 then //abandoned, stop waiting
begin
tthread.Queue(TThread.CurrentThread, SteppingThreadLost);
break;
end;
if (shortstate.status shr 8)=0 then
begin
//it has finished the step properly
exit(setBreakEvent(lpDebugEvent, lastfrozenID));
end;
//still here so step hasn't finished yet
asm
pause
end;
sleep(0);
end
else
break;
end;
end;
for i:=0 to listsize-1 do
begin
if dbvm_bp_getBrokenThreadEventShort(i,shortstate)=0 then
begin
inuse:=shortstate.status and $ff;
continueMethod:=shortstate.status shr 8;
if inuse=1 then
begin
if continueMethod=0 then //found a broken and waiting one
begin
cid.UniqueProcess:=0;
if getClientIDFromDBVMBPShortState(shortstate,cid) then
begin
if cid.UniqueProcess=GetCurrentProcessId then continue; //let the resumer thread deal with this
end;
if dbvmbp_options.TargetedProcessOnly then
begin
//check if it's the correct process, if not, continue the bp
if cid.UniqueProcess<>0 then
begin
if cid.UniqueProcess<>processid then //wrong pid
begin
dbvm_bp_resumeBrokenThread(i,2);
continue;
end;
end
else
begin
//getting the processid failed, try the CR3
if processCR3<>shortstate.cr3 then //wrong cr3
begin
dbvm_bp_resumeBrokenThread(i,2);
continue; //wrong cr3
end;
end;
end;
//still here, handling it
exit(setBreakEvent(lpDebugEvent, i));
end;
end
else
begin
//abandoned
dbvm_bp_resumeBrokenThread(i,2); //frees the spot for new bp's
end;
end;
end;
asm
pause
end;
sleep(0); //windows 10 fixed the sleep(0) where it will cause an immeadiate release of the timeslice
until (dwMilliseconds=0) or (dword(gettickcount64-starttime)>dwMilliseconds); //if dwMilliseconds = INFINITE ($ffffffff) then this is never true
end;
function TDBVMDebugInterface.ContinueDebugEvent(dwProcessId: DWORD; dwThreadId: DWORD; dwContinueStatus: DWORD): BOOL;
var step: boolean;
begin
try
lastfrozenID:=currentFrozenID;
if dwContinueStatus=DBG_CONTINUE_SINGLESTEP then
begin
OutputDebugString('TDBVMDebugInterface.ContinueDebugEvent returning single step');
//single step
lastContinueWasAStep:=true;
dbvm_bp_resumeBrokenThread(currentFrozenID, 1); //step
end
else
begin
//run
OutputDebugString('TDBVMDebugInterface.ContinueDebugEvent returning normal run');
lastContinueWasAStep:=false;
dbvm_bp_resumeBrokenThread(currentFrozenID, 2); //run
end;
result:=true;
except
result:=false;
end;
end;
function TDBVMDebugInterface.needsToAttach: boolean;
begin
result:=false;
end;
function TDBVMDebugInterface.controlsTheThreadList: boolean;
begin
result:=false;
end;
function TDBVMDebugInterface.usesDebugRegisters: boolean;
begin
result:=false; //doesn't give one fuck about debugregisters
end;
function TDBVMDebugInterface.SetThreadContext(hThread: THandle; const lpContext: TContext; isFrozenThread: Boolean=false): BOOL;
var f: dword;
begin
OutputDebugString('TDBVMDebugInterface.SetThreadContext');
if isFrozenThread then
begin
OutputDebugString('Is frozen');
currentFrozenState.basic.FLAGS:=lpContext.EFlags;
currentFrozenState.fpudata.MXCSR:={$ifdef cpu32}lpContext.FloatSave.ControlWord{$else}lpContext.MxCsr{$endif};
currentFrozenState.basic.DR0:=lpContext.Dr0;
currentFrozenState.basic.DR1:=lpContext.Dr1;
currentFrozenState.basic.DR2:=lpContext.Dr2;
currentFrozenState.basic.DR3:=lpContext.Dr3;
currentFrozenState.basic.DR6:=lpContext.Dr6;
currentFrozenState.basic.DR7:=lpContext.Dr7;
currentFrozenState.basic.RAX:=lpContext.{$ifdef cpu32}Eax{$else}Rax{$endif};
currentFrozenState.basic.RCX:=lpContext.{$ifdef cpu32}Ecx{$else}Rcx{$endif};
currentFrozenState.basic.Rdx:=lpContext.{$ifdef cpu32}Edx{$else}Rdx{$endif};
currentFrozenState.basic.Rbx:=lpContext.{$ifdef cpu32}Ebx{$else}Rbx{$endif};
currentFrozenState.basic.Rsp:=lpContext.{$ifdef cpu32}Esp{$else}Rsp{$endif};
currentFrozenState.basic.Rbp:=lpContext.{$ifdef cpu32}Ebp{$else}Rbp{$endif};
currentFrozenState.basic.Rsi:=lpContext.{$ifdef cpu32}Esi{$else}Rsi{$endif};
currentFrozenState.basic.Rdi:=lpContext.{$ifdef cpu32}Edi{$else}Rdi{$endif};
{$ifdef cpu64}
currentFrozenState.basic.R8:=lpContext.R8;
currentFrozenState.basic.R9:=lpContext.R9;
currentFrozenState.basic.R10:=lpContext.R10;
currentFrozenState.basic.R11:=lpContext.R11;
currentFrozenState.basic.R12:=lpContext.R12;
currentFrozenState.basic.R13:=lpContext.R13;
currentFrozenState.basic.R14:=lpContext.R14;
currentFrozenState.basic.R15:=lpContext.R15;
CopyMemory(@currentFrozenState.fpudata, @lpContext.FltSave,512);
{$else}
CopyMemory(@currentFrozenState.fpudata, @lpContext.ext,512);
{$endif}
currentFrozenState.basic.Rip:=lpContext.{$ifdef cpu32}eip{$else}Rip{$endif};
dbvm_bp_setBrokenThreadEventFull(currentFrozenID, currentFrozenState);
result:=true;
end
else
result:=false;
end;
function TDBVMDebugInterface.GetThreadContext(hThread: THandle; var lpContext: TContext; isFrozenThread: Boolean=false): BOOL;
begin
if isFrozenThread then
begin
lpContext.SegCs:=currentFrozenState.basic.CS;
lpContext.SegDs:=currentFrozenState.basic.DS;
lpContext.SegEs:=currentFrozenState.basic.ES;
lpContext.SegFs:=currentFrozenState.basic.FS;
lpContext.SegGs:=currentFrozenState.basic.GS;
lpContext.EFlags:=currentFrozenState.basic.FLAGS;
{$ifdef cpu32}lpContext.FloatSave.ControlWord{$else}lpContext.MxCsr{$endif}:=currentFrozenState.fpudata.MXCSR;
lpContext.Dr0:=currentFrozenState.basic.DR0;
lpContext.Dr1:=currentFrozenState.basic.DR1;
lpContext.Dr2:=currentFrozenState.basic.DR2;
lpContext.Dr3:=currentFrozenState.basic.DR3;
lpContext.Dr6:=currentFrozenState.basic.DR6;
lpContext.Dr7:=currentFrozenState.basic.DR7;
lpContext.{$ifdef cpu32}Eax{$else}Rax{$endif}:=currentFrozenState.basic.RAX;
lpContext.{$ifdef cpu32}Ecx{$else}Rcx{$endif}:=currentFrozenState.basic.RCX;
lpContext.{$ifdef cpu32}Edx{$else}Rdx{$endif}:=currentFrozenState.basic.RDX;
lpContext.{$ifdef cpu32}Ebx{$else}Rbx{$endif}:=currentFrozenState.basic.RBX;
lpContext.{$ifdef cpu32}Esp{$else}Rsp{$endif}:=currentFrozenState.basic.RSP;
lpContext.{$ifdef cpu32}Ebp{$else}Rbp{$endif}:=currentFrozenState.basic.RBP;
lpContext.{$ifdef cpu32}Esi{$else}Rsi{$endif}:=currentFrozenState.basic.RSI;
lpContext.{$ifdef cpu32}Edi{$else}Rdi{$endif}:=currentFrozenState.basic.RDI;
{$ifdef cpu64}
lpContext.R8:=currentFrozenState.basic.R8;
lpContext.R9:=currentFrozenState.basic.R9;
lpContext.R10:=currentFrozenState.basic.R10;
lpContext.R11:=currentFrozenState.basic.R11;
lpContext.R12:=currentFrozenState.basic.R12;
lpContext.R13:=currentFrozenState.basic.R13;
lpContext.R14:=currentFrozenState.basic.R14;
lpContext.R15:=currentFrozenState.basic.R15;
lpContext.P1Home:=currentFrozenState.basic.Count;
if processCR3<>currentFrozenState.basic.CR3 then
lpContext.P2Home:=currentFrozenState.basic.CR3 //give the special cr3
else
lpContext.P2Home:=0; //normal access
CopyMemory(@lpContext.FltSave, @currentFrozenState.fpudata,512);
{$else}
CopyMemory(@lpContext.ext, @currentFrozenState.fpudata,512);
{$endif}
lpContext.{$ifdef cpu32}Eip{$else}Rip{$endif}:=currentFrozenState.basic.Rip;
result:=true;
end
else
result:=newkernelhandler.GetThreadContext(hthread, lpContext);
end;
function TDBVMDebugInterface.DebugActiveProcess(dwProcessId: DWORD): BOOL;
var
mi: TModuleInfo;
buffer: array [0..4095] of byte;
ka:ptruint;
br: ptruint;
i,j: integer;
cr3log: array [0..512] of qword; //512 instead of 511 due to the offset by 1
mbi: TMEMORYBASICINFORMATION;
oldforce: boolean;
s: string;
begin
zeromemory(@cr3log[0], 513*sizeof(qword));
debuggerAttachStatus:='Attach started';
if (dwprocessid=0) or (dwProcessID=$ffffffff) then dwProcessId:=GetCurrentProcessId; //just a temporary id to get some usermode and kernelmode 'break'points
if (processhandler.processid=0) or (processhandler.processid<>dwProcessId) then
begin
debuggerAttachStatus:='Opening process';
processhandler.processid:=dwProcessID;
Open_Process;
symhandler.kernelsymbols:=true;
symhandler.reinitialize;
end
else
begin
debuggerAttachStatus:='Using opened process';
if symhandler.kernelsymbols=false then
begin
debuggerAttachStatus:='Activating kernelsymbols';
symhandler.kernelsymbols:=true;
symhandler.reinitialize;
end;
end;
debuggerAttachStatus:='obtaining CR3';
GetCR3(processhandle, processcr3);
cr3log[0]:=processcr3;
//scan executable memory for a CC
debuggerAttachStatus:='Scanning int3 executable memory in target process';
oldforce:=forceCR3VirtualQueryEx;
try
if usedbkquery then
forceCR3VirtualQueryEx:=true; //kernelmode VQE does not support differentiating between executable and non-executable memory, so if it's used, use the CR3 vqe instead
usermodeloopint3:=findaob('cc','+X',fsmNotAligned,'',true);
except
on e:exception do
begin
fErrorString:=e.message;
exit(false);
end;
end;
forceCR3VirtualQueryEx:=oldforce;
if dbvmbp_options.KernelmodeBreaks then
begin
if kernelmodeloopint3=0 then
begin
debuggerAttachStatus:='Scanning int3 executable memory in kernel. Step 1: Waiting for symbols';
symhandler.waitforsymbolsloaded(true);
debuggerAttachStatus:='Scanning int3 executable memory in kernel. Step 2: Scanning';
if symhandler.getmodulebyname('ntoskrnl.exe',mi) then
begin
for i:=0 to 512 do
begin
if cr3log[i]=0 then break; //end of the list
if ((cr3log[i] and 1)=0) then //windows 10: CR3 ending with 1 is usermode, 2 is kernelmode
begin
debuggerAttachStatus:=format('Scanning int3 executable memory in kernel CR3=%8x (index %d)',[cr3log[i],i]);
ka:=mi.baseaddress;
while (kernelmodeloopint3=0) and (ka<mi.baseaddress+mi.basesize) do
begin
if GetPageInfoCR3(cr3log[i],ka,mbi) then //get some page info (like if it's executable)
begin
if mbi.Protect in [PAGE_EXECUTE_READ,PAGE_EXECUTE_READWRITE] then
begin
while (kernelmodeloopint3=0) and (ka<ptruint(mbi.BaseAddress)+mbi.RegionSize) do
begin
if ReadProcessMemoryCR3(cr3log[i],pointer(ka),@buffer,4096,br) then
begin
for j:=0 to 4095 do
if buffer[j]=$cc then
begin
kernelmodeloopint3:=ka+j;
break;
end;
end;
inc(ka,4096);
end;
end else ka:=ptruint(mbi.BaseAddress)+mbi.RegionSize;
end else inc(ka,4096);
end;
if kernelmodeloopint3=0 then
begin
debuggerAttachStatus:='Failure finding int3 bp code inside kernelmode executable memory';
break;
end;
end;
if kernelmodeloopint3<>0 then break;
if (i=0) then
begin
//need to fill the other cr3 values
debuggerAttachStatus:='Getting other CR3 values';
if dbvm_log_cr3values_start then
begin
ReadProcessMemory(processhandle,nil,@br, 1,br);
sleep(2000);
if dbvm_log_cr3values_stop(@cr3log[1])=false then break; //give up
end
else break;
//the other cr3 values are now filled in
end;
end;
end;
end;
end
else
kernelmodeloopint3:=0;
result:=(usermodeloopint3<>0) or (kernelmodeloopint3<>0);
end;
constructor TDBVMDebugInterface.create;
begin
inherited create;
if loaddbvmifneeded=false then
raise exception.create(rsDBVMFunctionNeedsDBVM);
fDebuggerCapabilities:=fDebuggerCapabilities-[dbcCanUseInt1BasedBreakpoints]; //perhaps in the future add thread specific code
resumerThread:=TDBVMResumerThread.Create(false);
end;
destructor TDBVMDebugInterface.destroy;
begin
resumerThread.terminate;
freeandnil(resumerThread);
inherited destroy;
end;
{$endif}
end.
|
unit VSTIcons_win;
interface
uses ShellAPI, Controls;
{ Loads a pointer to the system icons into the passed ImageList
No image is actually added until requested by GetIconIndex }
procedure LoadSystemIcons(Target : TImageList);
{ Loads the fileicon for the passed file from the system icon-list and returns
an image index for any associated ImageList }
function GetIconIndex(const Filename : String; const Open : Boolean) : Integer;
implementation
procedure LoadSystemIcons(Target : TImageList);
var
SFI : TSHFileInfo;
begin
Target.Handle := SHGetFileInfo('', 0, SFI, SizeOf(SFI),
SHGFI_SYSICONINDEX or SHGFI_SMALLICON);
Target.ShareImages := True;
end;
function GetIconIndex(const Filename : String; const Open : Boolean) : Integer;
var
SFI : TSHFileInfo;
Flags : Cardinal;
begin
Flags := SHGFI_SYSICONINDEX or SHGFI_SMALLICON;
if Open then
Flags := Flags or SHGFI_OPENICON;
if SHGetFileInfo(PChar(Filename), 0, SFI, SizeOf(TSHFileInfo), Flags) = 0 then
Result := -1
else
Result := SFI.iIcon;
end;
end.
|
unit uProxyGenerator;
interface
uses
Classes, System.SysUtils, Datasnap.DSProxyDelphiNative,
Datasnap.DSProxyWriter, System.RegularExpressions;
type
TRFDelphiProxyWriter = class(TDSDelphiProxyWriter)
private
FAdicionarVirtual:Boolean;
protected
procedure WriteInterface; override;
public
procedure DerivedWrite(const Line: string); override;
end;
TRFClientProxyWriterDelphi = class(TDSClientProxyWriterDelphi)
public
function CreateProxyWriter: TDSCustomProxyWriter; override;
end;
const
coNomeWriter = 'Object Pascal DBX Customizado';
implementation
{ TRFDelphiProxyWriter }
procedure TRFDelphiProxyWriter.DerivedWrite(const Line: string);
var
vaLinha:String;
begin
if FAdicionarVirtual and TRegex.IsMatch(Line,'\s*((procedure)|(function))\s+.+;$',[roIgnoreCase]) then
vaLinha := Line+' virtual;'
else
vaLinha := Line;
inherited DerivedWrite(vaLinha);
end;
procedure TRFDelphiProxyWriter.WriteInterface;
begin
FAdicionarVirtual := true;
try
inherited;
finally
FAdicionarVirtual := false;
end;
end;
{ TRFClientProxyWriterDelphi }
function TRFClientProxyWriterDelphi.CreateProxyWriter: TDSCustomProxyWriter;
begin
Result := TRFDelphiProxyWriter.Create;
end;
initialization
TDSProxyWriterFactory.RegisterWriter(coNomeWriter, TRFClientProxyWriterDelphi);
finalization
TDSProxyWriterFactory.UnregisterWriter(coNomeWriter);
end.
|
unit ReadCommandLine;
interface
uses DB, Forms, SysUtils;
type
// -u username
// -p password
TCommandLineParams = class(TParams)
private
procedure ReadParameters;
public
procedure ShowParameters;
class function GetInstance: TCommandLineParams;
end;
implementation
{ TCommanLineParams }
class function TCommandLineParams.GetInstance: TCommandLineParams;
const prms: TCommandLineParams = nil;
begin
if not Assigned(prms) then
begin
prms := TCommandLineParams.Create;
prms.ReadParameters;
end;
Result := prms;
end;
procedure TCommandLineParams.ReadParameters;
var i : Integer;
p: TParam;
begin
i := 1;
while i <= ParamCount do
begin
p := CreateParam(ftString, ParamStr(i), ptInputOutput);
p.Value := ParamStr(i + 1);
AddParam(p);
i := i + 2;
end;
end;
procedure TCommandLineParams.ShowParameters;
var i: integer;
begin
for i := 0 to Count - 1 do
Application.MessageBox(PChar(Format('%s = %s', [Items[i].Name, Items[i].AsString])), PChar('Info'), 0)
end;
end.
|
unit explorersprocessor;
{$ifdef fpc}{$mode delphi}{$endif}{$H+}
interface
uses
Classes, SysUtils, registry;
type
IExplorerStorage = interface
procedure ReadConfig(ExplorerNames: TStrings);
procedure SaveConfig(ExplorerNames: TStrings);
procedure ClearConfig;
end;
TRegistryExplorerStorage = class(TInterfacedObject, IExplorerStorage)
private
FRegistryKey: String;
public
procedure ReadConfig(ExplorerNames: TStrings);
procedure SaveConfig(ExplorerNames: TStrings);
procedure ClearConfig;
constructor Create(ARegistryKey: string);
end;
TExplorersProcessor = class
private
FExplorerStorage: IExplorerStorage;
procedure CorrectExplorers(const ExplorerNames: TStrings);
public
ListOfAllExplorers: TStrings;
ListOfKnownExplorers: TStringList;
ListOfUnknownExplorers: TStringList;
constructor Create(AListOfExplorers: TStringArray; AExplorerStorage: IExplorerStorage);
destructor Destroy; override;
procedure GetExplorers;
procedure SetExplorers(InputExplorers: String);
end;
function StringReplaceAll(const haystack: string; const needle: string; const replacement: string): string;
const
SettingExplorers = 'Explorers';
implementation
constructor TExplorersProcessor.Create(AListOfExplorers: TStringArray; AExplorerStorage: IExplorerStorage);
begin
FExplorerStorage := AExplorerStorage;
ListOfAllExplorers := TStringList.Create;
ListOfAllExplorers.AddStrings(AListOfExplorers);
ListOfKnownExplorers := TStringList.Create;
ListOfUnknownExplorers := TStringList.Create;
end;
destructor TExplorersProcessor.Destroy;
begin
FreeAndNil(ListOfUnknownExplorers);
FreeAndNil(ListOfKnownExplorers);
FreeAndNil(ListOfAllExplorers);
inherited Destroy;
end;
procedure TExplorersProcessor.GetExplorers;
var
ReadExplorers: TStringList;
begin
ReadExplorers := TStringList.Create;
try
FExplorerStorage.ReadConfig(ReadExplorers);
ReadExplorers.Sort;
CorrectExplorers(ReadExplorers);
finally
ReadExplorers.Free;
end;
end;
procedure TExplorersProcessor.SetExplorers(InputExplorers: String);
var
SplitExplorerNames: TStringList;
begin
if Trim(InputExplorers) = '' then
begin
FExplorerStorage.ClearConfig;
end
else
begin
SplitExplorerNames := TStringList.Create;
try
InputExplorers := StringReplaceAll(InputExplorers, ' ,', ',');
InputExplorers := StringReplaceAll(InputExplorers, ', ', ',');
SplitExplorerNames.StrictDelimiter := true;
SplitExplorerNames.DelimitedText := InputExplorers;
SplitExplorerNames.Sort;
CorrectExplorers(SplitExplorerNames);
finally
FreeAndNil(SplitExplorerNames);
end;
end;
end;
procedure TExplorersProcessor.CorrectExplorers(const ExplorerNames: TStrings);
var
I: integer;
ExplorerName: String;
previousKnown: string;
begin
previousKnown := ListOfKnownExplorers.DelimitedText;
ListOfUnknownExplorers.Clear;
ListOfKnownExplorers.Clear;
for ExplorerName in ExplorerNames do
begin
I := ListOfAllExplorers.IndexOf(ExplorerName);
if I = -1 then
begin
ListOfUnknownExplorers.Add(ExplorerName);
end
else
begin
ListOfKnownExplorers.Add(ListOfAllExplorers[I]);
end;
end;
ListOfUnknownExplorers.Sort;
ListOfKnownExplorers.Sort;
if (ListOfUnknownExplorers.Count > 0) or (previousKnown <> ListOfKnownExplorers.DelimitedText) then
begin
FExplorerStorage.SaveConfig(ListOfKnownExplorers);
end;
end;
function StringReplaceAll(const haystack: string; const needle: string; const replacement: string): string;
begin
Result := haystack;
repeat
Result := StringReplace(Result, needle, replacement, [rfReplaceAll]);
until Pos(needle, Result) = 0;
end;
constructor TRegistryExplorerStorage.Create(ARegistryKey: string);
begin
FRegistryKey := ARegistryKey;
end;
procedure TRegistryExplorerStorage.ReadConfig(ExplorerNames: TStrings);
var
Registry: TRegistry;
begin
Registry := TRegistry.Create;
try
Registry.RootKey := HKEY_CURRENT_USER;
if Registry.OpenKeyReadOnly(FRegistryKey) then
begin
Registry.ReadStringList(SettingExplorers, ExplorerNames);
end;
finally
Registry.Free;
end;
end;
procedure TRegistryExplorerStorage.SaveConfig(ExplorerNames: TStrings);
var
Registry: TRegistry;
begin
Registry := TRegistry.Create;
try
Registry.RootKey := HKEY_CURRENT_USER;
if Registry.OpenKey(FRegistryKey, true) then
begin
Registry.WriteStringList(SettingExplorers, ExplorerNames, True);
end;
finally
Registry.Free;
end;end;
procedure TRegistryExplorerStorage.ClearConfig;
var
Registry: TRegistry;
begin
Registry := TRegistry.Create;
try
Registry.RootKey := HKEY_CURRENT_USER;
if Registry.OpenKey(FRegistryKey, true) then
begin
Registry.DeleteValue(SettingExplorers);
if (not Registry.HasSubKeys) and (Length(Registry.GetValueNames) = 0) then
begin
Registry.DeleteKey(FRegistryKey);
end;
end;
finally
Registry.Free;
end;
end;
end.
|
unit Lbsqloln;
interface
Uses SysUtils,StdCtrls,Classes,Buttons,Controls,ExtCtrls,Menus,
Messages,SQLOutLn,SQLCtrls,DBTables;
Type TLabelSQLOutline=class(TSQLControl)
protected
procedure WriteCaption(s:string);
Function ReadCaption:String;
procedure WriteWhere(s:string);
Function ReadWhere:String;
procedure WriteTable(s:string);
Function ReadTable:String;
procedure WriteID(s:string);
Function ReadID:String;
procedure WriteInfo(s:string);
Function ReadInfo:String;
procedure WriteParentID(s:string);
Function ReadParentID:String;
procedure WriteRoot(s:string);
Function ReadRoot:String;
procedure WriteRNP(s:boolean);
Function ReadRNP:Boolean;
procedure WriteOnClick(s:TNotifyEvent);
Function ReadOnClick:TNotifyEvent;
procedure WritePC(s:boolean);
Function ReadPC:boolean;
public
Data:longint;
Lbl:TLabel;
SQLOutline:TSQLOutline;
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure WMSize(var Msg:TMessage); message WM_SIZE;
procedure Value(sl:TStringList); override;
procedure SetValue(var q:TQuery); override;
published
property Align;
property TabOrder;
property TabStop;
property Caption:String read ReadCaption write WriteCaption;
property Table:String read ReadTable write WriteTable;
property Where:String read ReadWhere write WriteWhere;
property IDField:String read ReadID write WriteID;
property InfoField:String read ReadInfo write WriteInfo;
property ParentIDField:String read ReadParentID write WriteParentID;
property RootName:String read ReadRoot write WriteRoot;
property RootNoPresent:boolean read ReadRNP write WriteRNP;
property ParentColor:Boolean read ReadPC write WritePC;
property OnClick:TNotifyEvent read ReadOnClick write WriteOnClick;
end;
procedure Register;
implementation
destructor TLabelSQLOutline.Destroy;
begin
Lbl.Free;
SQLOutline.Free;
inherited Destroy;
end;
procedure TLabelSQLOutline.Value(sl:TStringList);
begin
if Assigned(fValueEvent) then
fValueEvent(self,sl)
else
if (not Visible) or (SQLOutline.GetData=0)
then sl.Add('NULL')
else
sl.Add(IntToStr(SQLOutline.GetData));
end;
procedure TLabelSQLOutline.SetValue(var q:TQuery);
begin
if Assigned(fSetValueEvent) then fSetValueEvent(self,q)
else
SQLOutline.SetActive(q.FieldByName(fFieldName).AsInteger);
end;
constructor TLabelSQLOutline.Create(AOwner:TComponent);
begin
inherited create(AOwner);
Lbl:=TLabel.Create(self);
SQLOutline:=TSQLOutline.Create(self);
Lbl.Parent:=self;
SQLOutline.Parent:=self;
Lbl.Left:=0;
Lbl.Top:=0;
SQLOutline.Left:=0;
end;
procedure TLabelSQLOutline.WMSize(var Msg:TMessage);
begin
Lbl.Height:=-Lbl.Font.Height+3;
Lbl.Width:=Msg.LParamLo;
SQLOutline.Top:=Lbl.Height;
SQLOutline.Height:=Msg.LParamHi-Lbl.Height;
SQLOutline.Width:=Msg.LParamLo;
end;
procedure TLabelSQLOutline.WriteCaption(s:String);
begin
Lbl.Caption:=s
end;
function TLabelSQLOutline.ReadCaption:String;
begin
ReadCaption:=Lbl.Caption
end;
procedure TLabelSQLOutline.WriteWhere(s:String);
begin
SQLOutline.Where:=s
end;
function TLabelSQLOutline.ReadWhere:String;
begin
ReadWhere:=SQLOutline.Where
end;
procedure TLabelSQLOutline.WriteTable(s:String);
begin
SQLOutline.Table:=s
end;
function TLabelSQLOutline.ReadTable:String;
begin
ReadTable:=SQLOutline.Table
end;
procedure TLabelSQLOutline.WriteID(s:String);
begin
SQLOutline.IDField:=s
end;
function TLabelSQLOutline.ReadID:String;
begin
ReadID:=SQLOutline.IDField
end;
procedure TLabelSQLOutline.WriteInfo(s:String);
begin
SQLOutline.InfoField:=s
end;
function TLabelSQLOutline.ReadInfo:String;
begin
ReadInfo:=SQLOutline.InfoField
end;
procedure TLabelSQLOutline.WriteParentID(s:String);
begin
SQLOutline.ParentIDField:=s
end;
function TLabelSQLOutline.ReadParentID:String;
begin
ReadParentID:=SQLOutline.ParentIDField
end;
procedure TLabelSQLOutline.WritePC(s:Boolean);
begin
SQLOutline.ParentColor:=s
end;
function TLabelSQLOutline.ReadPC:Boolean;
begin
ReadPC:=SQLOutline.ParentColor
end;
procedure TLabelSQLOutline.WriteRoot(s:String);
begin
SQLOutline.RootName:=s
end;
function TLabelSQLOutline.ReadRoot:String;
begin
ReadRoot:=SQLOutline.RootName
end;
procedure TLabelSQLOutline.WriteOnClick(s:TNotifyEvent);
begin
SQLOutline.OnClick:=s
end;
Function TLabelSQLOutline.ReadOnClick:TNotifyEvent;
begin
ReadOnClick:=SQLOutline.OnClick
end;
Function TLabelSQLOutline.ReadRNP:Boolean;
begin
ReadRNP:=SQLOutline.RootNoPresent;
end;
procedure TLabelSQLOutline.WriteRNP(s:boolean);
begin
SQLOutline.RootNoPresent:=s;
SQLOutline.Recalc(TRUE);
end;
procedure Register;
begin
RegisterComponents('MyOwn',[TLabelSQLOutline])
end;
end.
|
{ p_38_4.pas - ัะตัะตัะพ ะญัะฐัะพััะตะฝะฐ }
program p_38_4;
var simples: set of byte; { ะผะฝะพะถะตััะฒะพ ัะธัะตะป }
n, m: integer;
f: text;
begin
Assign(f, '');
Rewrite(f);
simples := [2..255]; { ัะฝะฐัะฐะปะฐ ะผะฝะพะถะตััะฒะพ ะฟะพะปะฝะพะต }
{ ัะธะบะป ะฒััะตัะบะธะฒะฐะฝะธั ัะพััะฐะฒะฝัั
ัะธัะตะป }
for n:=2 to (255 div 2) do begin
{ ะตัะปะธ ัะธัะปะพ ะตัั ะฝะต ะฒััะตัะบะฝััะพ }
if n in simples then
{ ะฟัะพะฒะตััะตะผ ะฝะฐ ะบัะฐัะฝะพััั ะตะผั ะฒัะต ะฟะพัะปะตะดัััะธะต }
for m:=2*n to 255 do
{ ะตัะปะธ ะพััะฐัะพะบ (m/n) ัะฐะฒะตะฝ ะฝัะปั, ัะพ m - ัะพััะฐะฒะฝะพะต }
if (m mod n) = 0
{ ะธ ะตะณะพ ะฝะฐะดะพ ะฒััะตัะบะฝััั ะธะท ะผะฝะพะถะตััะฒะฐ }
then simples := simples - [m];
end;
{ ัะฐัะฟะตัะฐัะบะฐ ะผะฝะพะถะตััะฒะฐ ะฟัะพัััั
ัะธัะตะป }
for n:=2 to 255 do
if n in simples then Writeln(f, n);
Close(f);
end. |
unit HmgPlaneComparatorTest;
{$mode objfpc}{$H+}
{$CODEALIGN LOCALMIN=16}
interface
uses
Classes, SysUtils, fpcunit, testregistry, BaseTestCase,
native, BZVectorMath, BZVectorMathEx;
type
{ THmgPlaneComparatorTest }
THmgPlaneComparatorTest = class(TVectorBaseTestCase)
protected
{$CODEALIGN RECORDMIN=16}
vt5 : TBZVector;
nph1, nph2,nph3 : TNativeBZHmgPlane;
ph1,ph2,ph3 : TBZHmgPlane;
nt4: TNativeBZVector;
procedure Setup; override;
published
procedure TestCompare;
procedure TestCompareFalse;
procedure TestCreate3Vec;
procedure TestCreatePointNorm;
procedure TestNormalizeSelf;
procedure TestNormalized;
procedure TestDistanceToPoint;
procedure TestAbsDistanceToPoint;
procedure TestDistanceToSphere;
procedure TestPerp;
procedure TestReflect;
procedure TestIsInHalfSpace;
// helpers
procedure TestContainsBSphere;
end;
implementation
{ THmgPlaneComparatorTest }
procedure THmgPlaneComparatorTest.Setup;
begin
inherited Setup;
vt1.Create(10.350,16.470,4.482,1.0); // decent hpoints paralel to xy plane
vt2.Create(20.350,18.470,4.482,1.0);
vt3.Create(10.350,10.470,2.482,1.0);
vt4.Create(20.350,17.470,4.482,1.0);
ph2.Create(vt1,vt2,vt4); // plane @z 4.482 z- norm
ph1.Create(vt1,vt4,vt2); // plane @z 4.482 z+ norm
nph1.V := ph1.V;
nt1.V := vt1.V;
nt2.V := vt2.V;
nt3.V := vt3.V;
nt4.V := vt4.V;
end;
procedure THmgPlaneComparatorTest.TestCompare;
begin
AssertTrue('Test Values do not match', Compare(nph1,ph1));
end;
procedure THmgPlaneComparatorTest.TestCompareFalse;
begin
AssertFalse('Test Values should not match', Compare(nph1,ph2));
end;
procedure THmgPlaneComparatorTest.TestCreate3Vec;
begin
nph1.Create(nt1,nt4,nt2);
ph1.Create(vt1,vt4,vt2);
AssertTrue('THmgPlane Create3Vector does not match', Compare(nph1,ph1));
end;
procedure THmgPlaneComparatorTest.TestCreatePointNorm;
begin
nph1.Create(nt1,NativeZHmgVector);
ph1.Create(vt1,ZHmgVector);
AssertTrue('THmgPlane PointNorm does not match', Compare(nph1,ph1));
end;
procedure THmgPlaneComparatorTest.TestNormalizeSelf;
begin
nph1.Create(nt1,nt3);
ph1.Create(vt1,vt3);
nph1.Normalize;
ph1.Normalize;
AssertTrue('THmgPlane NormalizeSelf does not match ', Compare(nph1,ph1,1e-5));
end;
procedure THmgPlaneComparatorTest.TestNormalized;
begin
nph1.Create(nt1,nt3);
ph1.Create(vt1,vt3);
nph2 := nph1.Normalized;
ph2 := ph1.Normalized;
AssertTrue('THmgPlane Normalized does not match', Compare(nph2,ph2,1e-5));
end;
procedure THmgPlaneComparatorTest.TestDistanceToPoint;
begin
fs1 := nph1.Distance(nt3);
fs2 := ph1.Distance(vt3);
AssertTrue('THmgPlane DistanceToPoint does not match', IsEqual(fs1,fs2));
end;
procedure THmgPlaneComparatorTest.TestAbsDistanceToPoint;
begin
fs1 := nph1.AbsDistance(nt3);
fs2 := ph1.AbsDistance(vt3);
AssertTrue('THmgPlane AbsDistanceToPoint does not match', IsEqual(fs1,fs2));
end;
procedure THmgPlaneComparatorTest.TestDistanceToSphere;
begin
fs1 := nph1.Distance(NativeNullHmgVector,1.234);
fs2 := ph1.Distance(NullHmgVector,1.234);
AssertTrue('THmgPlane DistanceToSphere does not match', IsEqual(fs1,fs2));
end;
procedure THmgPlaneComparatorTest.TestIsInHalfSpace;
begin
nb := nph1.IsInHalfSpace(nt3);
ab := ph1.IsInHalfSpace(vt3);
AssertTrue('THmgPlane IsInHalfSpace does not match', (nb = ab));
end;
procedure THmgPlaneComparatorTest.TestPerp;
begin
nt3 := nph1.Perpendicular(nt2);
vt3 := ph1.Perpendicular(vt2);
AssertTrue('Vector Perpendiculars do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3, 1e-4));
end;
procedure THmgPlaneComparatorTest.TestReflect;
begin
nt3 := nph1.Reflect(nt2);
vt3 := ph1.Reflect(vt2);
AssertTrue('Vector Reflects do not match : '+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3, 1e-4));
end;
procedure THmgPlaneComparatorTest.TestContainsBSphere;
var
nsp: TNativeBZBoundingSphere;
asp: TBZBoundingSphere;
nct, act: TBZSpaceContains;
begin
nsp.Create(NativeNullHmgVector, 2);
asp.Create(NullHmgVector, 2);
nct := nph1.Contains(nsp);
act := ph1.Contains(asp);
AssertTrue('THmgPlane ContainsBSphere does not match', (nct=act));
end;
initialization
RegisterTest(REPORT_GROUP_PLANE_HELP, THmgPlaneComparatorTest);
end.
|
{*
* This file contains most of the code that implements a test
* of the ZlibTool OCX. It does this by compressing or decompressing
* a selected file from an input list box.
*}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OleCtrls, ZLIBTOOL, StdCtrls, FileCtrl;
type
TForm1 = class(TForm)
Button1: TButton;
Percent: TEdit;
FileListBox1: TFileListBox;
InputFile: TEdit;
OutputFile: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Status: TEdit;
Button2: TButton;
Button3: TButton;
Label4: TLabel;
Button4: TButton;
Label5: TLabel;
Engine: TZlibToolCtrl;
Level: TComboBox;
procedure Button1Click(Sender: TObject);
procedure EngineProgress(Sender: TObject; percent_complete: Smallint);
procedure FileListBox1Change(Sender: TObject);
procedure InputFileChange(Sender: TObject);
procedure OutputFileChange(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure InputFileEnter(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
{*
* To compress, I just set the engine level to be the
* currently selected level, then call the Compress()
* method of the engine. The input and output file
* names are set when a file is selected from the
* input list.
*
* Note that when the compression is done, I call the
* Update() method of the file list box so that I will
* see any newly created output files. I also take the
* Zlib engine status and put it in a text box for the
* user to see.
*}
procedure TForm1.Button1Click(Sender: TObject);
begin
Status.Text := 'Compressing...';
Engine.Level := Level.ItemIndex;
Button1.Enabled := false;
Engine.Compress();
Button1.Enabled := true;
FileListBox1.Update();
Status.Text := Engine.Status;
end;
{*
* Decompression takes a nearly identical path as
* compression.
*}
procedure TForm1.Button2Click(Sender: TObject);
begin
Status.Text := 'Decompressing...';
Button2.Enabled := false;
Engine.Decompress();
Button2.Enabled := true;
FileListBox1.Update();
Status.Text := Engine.Status;
end;
{*
* This procedure is bound to the Progress()
* method of the engine. It gest called
* periodically during the compression process, with
* a single numeric argument specifying the precent
* of the input file that has been processed. I
* round the value off to the nearest five percent
* and display it in a text box.
*}
procedure TForm1.EngineProgress(Sender: TObject;
percent_complete: Smallint);
begin
{ I round it off to the nearest 5% }
percent_complete := percent_complete + 2;
percent_complete := percent_complete div 5;
percent_complete := percent_complete * 5;
Percent.Text := IntToStr( percent_complete );
Percent.Update();
end;
{*
* Any time a new file is selected in the input list
* box, I place it in the text box that indicates
* which file will actually be either compressed or
* decompressed.
*}
procedure TForm1.FileListBox1Change(Sender: TObject);
begin
if FileListBox1.ItemIndex >= 0 Then
InputFile.Text := FileListBox1.Items[ FileListBox1.ItemIndex ];
end;
{*
* When the input file name is changed, either by the user
* typing in a new name, or by the user selecting a file
* name from the list box, this routine gets called. It
* sets the engine property, then gets the resulting output
* file name from the engine. If you input a name like
* foo.dat.ZL, the output name will be foo.dat. If you input
* a name like foo.dat, the output name will be foo.dat.ZL.
* This is the way the OCX works, it has nothing to do with
* the way Zlib works.
*}
procedure TForm1.InputFileChange(Sender: TObject);
begin
Engine.InputFile := InputFile.Text;
OutputFile.Text := Engine.OutputFile;
end;
{*
* When the user types in a new output file name,
* we are sure to copy it to the engine output file
* name property.
*}
procedure TForm1.OutputFileChange(Sender: TObject);
begin
Engine.OutputFile := OutputFile.Text;
end;
{*
* Exit the program. Maybe it would be a good
* idea to disable this button while the
* compression or decompression process is running.
*}
procedure TForm1.Button3Click(Sender: TObject);
begin
Close();
end;
{*
* When a new input file is selected, I jump over
* to the file list box.
*}
procedure TForm1.InputFileEnter(Sender: TObject);
begin
FileListBox1.SetFocus();
end;
{*
* Being able to abort the compression process is
* a really good thing. When this button is clicked,
* the abort method is invoked. Since the engine is
* periodically servicing the message loop, this
* should eventually be noticed, and the compression
* aborted.
*}
procedure TForm1.Button4Click(Sender: TObject);
begin
Engine.Abort();
end;
{*
* When the form is first activated, I set the compression
* level to the default value selected by the compression
* engine.
*}
procedure TForm1.FormActivate(Sender: TObject);
begin
Level.ItemIndex := Engine.Level;
end;
end.
|
unit UProcesoDevolucionEsta;
interface
uses
DB, ZDataset,SysUtils,StrUtils,DateUtils,Forms,Classes,
UDAODevolucionEstado,UCarpetaDevolucionEsta,UDMAplicacion,UFtpImagen,UFtpGestor;
type
TProcesoDevolucionEsta = class
private
FCarpetas : TDataSource;
FDatosCarpeta : TCarpetaDevolucionEsta;
FEstadosDevolver : TDataSource;
FFoliosCarpeta : TDataSource;
public
qr:TZQuery;
{CONSTRUCTORES Y DESTRUCTORES}
constructor Create;
destructor Destroy;
{PROPIEDADES}
property Carpetas : TDataSource read FCarpetas;
property DatosCarpeta : TCarpetaDevolucionEsta read FDatosCarpeta;
property EstadosDevolver : TDataSource read FEstadosDevolver;
property FoliosCarpeta : TDataSource read FFoliosCarpeta;
{METODOS PROPIOS}
Procedure DevolverEstadoCarpeta(p_ElimCarp: Boolean);
Procedure ObtenerCarpetas(p_CodiCaja: String);
Procedure ObtenerDatosCarpeta(p_IdenCarp: Int32; p_CodiCarp: string);
Procedure ObtenerEstadosDevolver(p_IdenFlujMaxi: Int32);
Procedure RetirarImagenes;
Function VerificarVersion(p_NombModu: string; p_VersModu: string; p_VeriRuta: Boolean): boolean;
end;
implementation
uses
UDevolucionEstado;
var
DAODevolucionEstado: TDAODevolucionEstado;
Procedure TProcesoDevolucionEsta.DevolverEstadoCarpeta(p_ElimCarp: Boolean);
var
CantAletElim : Int32;
CantCofoElim : Int32;
CantFirmElim : Int32;
CantFoliActu : Int32;
CantFoliElim : Int32;
CantIdenElim : Int32;
CantImagElim : Int32;
CantNofoElim : Int32;
CantObfoElim : Int32;
CantPlanElim : Int32;
CodiAlet : string;
CodiCaja : string;
CodiFoli : string;
HoraBase : TTime;
I : Int32;
IdenAlet : Int32;
IdenCarp : Int32;
IdenFoli : Int64;
IdenTraz : Int64;
MensErro : string;
RetiOkok : Boolean;
TipoFoli : Char;
UsuaProc : string;
begin
try
CantAletElim := 0;
CantFirmElim := 0;
CantFoliActu := 0;
CantFoliElim := 0;
CantIdenElim := 0;
CantImagElim := 0;
CantCofoElim := 0;
CantNofoElim := 0;
CantObfoElim := 0;
CantPlanElim := 0;
with DAODevolucionEstado do
begin
IniciarTransaccion;
FrmDevolucionEstado.LblDevolverCarpeta.Caption:= 'DEVOLUCIรN DE LA CARPETA ['
+ FDatosCarpeta.CodiCompCarpeta
+ '] AL ESTADO ['
+ FDatosCarpeta.DescTareFlujNuev + ']';
FrmDevolucionEstado.LblDevolverCarpeta.Visible:= True;
FrmDevolucionEstado.stgEstadoProceso.Visible:= True;
for I := 0 to FrmDevolucionEstado.stgEstadoProceso.RowCount - 1 do
FrmDevolucionEstado.stgEstadoProceso.cells[1,I]:= '';
Application.ProcessMessages;
CodiCaja := 'M' + FDatosCarpeta.CodigoCaja;
IdenCarp := FDatosCarpeta.IdCarpeta;
UsuaProc := FDatosCarpeta.UsuarioProceso;
FFoliosCarpeta := DAODevolucionEstado.ConsultarFoliosPorCarpeta(IdenCarp,
FDatosCarpeta.CodiResuCarpeta);
{SE CREA REGISTRO EN LA TABLA DE TRAZABILIDAD EN ESTADO DE ERROR Y PARA OBTENER EL ID
DE DICHA TABLA PARA LOS REGISTROS DE DE DETALLE }
MensErro := 'ERROR: NO SE PROCESA ARCHIVOS DE IMAGEN. ['
+ DatosCarpeta.RutaImagenes + ']';
FDatosCarpeta.RutaBackImagTiff := '';
FDatosCarpeta.CantImagTiff := 0;
FDatosCarpeta.CantImagPdff := 0;
IdenTraz := DAODevolucionEstado.InsertarTrazaCarpeta(FDatosCarpeta,MensErro);
with FFoliosCarpeta.DataSet do
begin
HoraBase:= Now()-1;
if RecordCount > 0 then
begin
while not Eof do
begin
IdenAlet := FieldByName('idcarpetaaleta').Value;
CodiAlet := 'M' + FieldByName('codigocarpetaaleta').AsString;
while (not Eof ) and (IdenAlet = FieldByName('idcarpetaaleta').Value) do
begin
if not FieldByName('idfolio').IsNull then
begin
IdenFoli := FieldByName('idfolio').Value;
CodiFoli := 'M' + FieldByName('codigofolio').Value;
TipoFoli := FieldByName('tipofolio').AsString[1];
{SI SE DEVUELVE A GENERACION XML,CAPTURA O CALIDAD, SE MODIFICAN DATOS DEL FOLIO
QUE TIENEN QUE VER CON FIRMA Y ESTAMPA}
if FDatosCarpeta.IdFlujoNuevo in [4,3,2] then
begin
Inc(CantFoliActu,DAODevolucionEstado.ModificarFolios(IdenFoli,CodiFoli,'FIRMA',
IdenTraz,UsuaProc));
end;
{SI SE DEVUELVE A GENERACION XML,CAPTURA, CALIDAD, PUBLICACION O RECEPCION,
SE ELIMINAN REGISTROS DE FIRMA Y ESTAMPA ASOCIADOS AL FOLIO}
if FDatosCarpeta.IdFlujoNuevo in [4,3,2,1,0] then
begin
Inc(CantFirmElim,DAODevolucionEstado.EliminarFirmas(IdenFoli,CodiFoli,
IdenTraz,UsuaProc));
end;
{SI SE DEVUELVE A CAPTURA, CALIDAD, PUBLICACION O RECEPCION,
SE ELIMINAN REGISTROS DE IDENTIFICACIONES ASOCIADAS AL FOLIO,
REGISTROS DE CONTROL DE ASIGNACION DEL FOLIO, REGISTROS DE OBSERVACIONES
DE CAPTURA PARA EL FOLIO }
if FDatosCarpeta.IdFlujoNuevo in [3,2,1,0] THEN
begin
Inc(CantIdenElim,DAODevolucionEstado.EliminarIDentificaciones(IdenFoli,CodiFoli,
IdenTraz,UsuaProc));
Inc(CantCofoElim,DAODevolucionEstado.EliminarControlesFolio(IdenFoli,CodiFoli,
'CAPTURA',IdenTraz,UsuaProc));
Inc(CantObfoElim,DAODevolucionEstado.EliminarObservacionesFolio(IdenFoli,CodiFoli,
'CAPTURA',IdenTraz,UsuaProc));
{SI EL FOLIO TIENE ASOCIADOS DATOS DE PLANILLAS O APORTES SE ELIMINAN LOS REGISTROS
Y LA ASOCIACION EXISTENTE}
if not FieldByName('iddatoplanilla').isnull then
begin
DAODevolucionEstado.ModificarFolios(IdenFoli,CodiFoli,'PLANILLA',IdenTraz,
UsuaProc);
Inc(CantPlanElim,DAODevolucionEstado.EliminarDatosPlanilla
(FieldByName('iddatoplanilla').value,CodiFoli,
IdenTraz,UsuaProc));
end;
end;
{SI SE DEVUELVE A CALIDAD, PUBLICACION O RECEPCION, SE ELIMINAN REGISTROS DE NOVEDADES
ASOCIADAS AL FOLIO, REGISTROS DE CONTROL DE ASIGNACION DEL FOLIO EN CALIDAD,
REGISTROS DE OBSERVACIONES DE CALIDAD PARA EL FOLIO Y SE REMUVEN LAS MAARCAS DE
CALIDAD EN EL FOLIO. SE ELIMINA EL FOLIO SI ES UN TESTIGO O SI DE DEVUELVE A
PUBLICACION O RECEPCION }
if FDatosCarpeta.IdFlujoNuevo in [2,1,0] then
begin
Inc(CantNofoElim,DAODevolucionEstado.EliminarNovedadesFolio(IdenFoli,CodiFoli,
IdenTraz,UsuaProc));
Inc(CantCofoElim,DAODevolucionEstado.EliminarControlesFolio(IdenFoli,CodiFoli,
'CALIDAD',IdenTraz,UsuaProc));
Inc(CantObfoElim,DAODevolucionEstado.EliminarObservacionesFolio(IdenFoli,CodiFoli,
'CALIDAD',IdenTraz,UsuaProc));
if ((FDatosCarpeta.IdFlujoNuevo in [2]) and (TipoFoli = 'T')) or
(FDatosCarpeta.IdFlujoNuevo in [1,0]) then
begin
Inc(CantImagElim,DAODevolucionEstado.EliminarImagenes(IdenFoli,CodiFoli,
IdenTraz,UsuaProc,
'TODAS'));
Inc(CantFoliElim,DAODevolucionEstado.EliminarFolios(IdenFoli,CodiFoli,
IdenTraz,UsuaProc));
end
else
begin
Inc(CantImagElim,DAODevolucionEstado.EliminarImagenes(IdenFoli,CodiFoli,
IdenTraz,UsuaProc,
'VERSIONES'));
DAODevolucionEstado.ModificarFolios(IdenFoli,CodiFoli,'CALIDAD',IdenTraz,UsuaProc);
end;
end;
with FrmDevolucionEstado.stgEstadoProceso do
begin
Cells[1,1]:= formatfloat('#,##0',CantFoliActu);
Cells[1,2]:= formatfloat('#,##0',CantFoliElim);
Cells[1,3]:= formatfloat('#,##0',CantIdenElim);
Cells[1,4]:= formatfloat('#,##0',CantCofoElim);
Cells[1,5]:= formatfloat('#,##0',CantImagElim);
Cells[1,6]:= formatfloat('#,##0',CantNofoElim);
Cells[1,7]:= formatfloat('#,##0',CantPlanElim);
Cells[1,8]:= formatfloat('#,##0',CantObfoElim);
Cells[1,9]:= formatfloat('#,##0',CantFirmElim);
{PARA QUE MUESTRE LOS CONTADORES CADA 1.5 SEGUNDOS }
if MilliSecondSpan(Now(),HoraBase) > 1500 then
begin;
HoraBase:= Now();
Application.ProcessMessages;
end;
end;
end;
Next;
end;
Application.ProcessMessages;
{SI SE DEVUELVE A RECEPCION, SE ELIMINA REGISTRO DE LA ALETA. }
if FDatosCarpeta.IdFlujoNuevo = 0 then
begin
Inc(CantAletElim,DAODevolucionEstado.EliminarAletas(IdenAlet,CodiAlet,
IdenTraz,UsuaProc));
end;
FrmDevolucionEstado.stgEstadoProceso.Cells[1,0]:= formatfloat('#,##0',CantAletElim);
Application.ProcessMessages;
end;
end;
{SI SE DEVUELVE A RECEPCION Y SE INDICร ELIMINAR LA CARPETA, SE ELIMINA REGISTRO
DE LA CARPETA DE LO CONTRARIO SE CAMBIA EL ESTADO DE LA CARPETA. }
if FDatosCarpeta.IdFlujoNuevo = 0 then
begin
if p_ElimCarp then
begin
if not DAODevolucionEstado.EliminarCarpetas(FDatosCarpeta.IdCarpeta,
FDatosCarpeta.CodiResuCarpeta,
IdenTraz,UsuaProc) then
raise Exception.Create('Error al realizar la Eliminaciรณn de la Carpeta.')
end
else
begin
if not DAODevolucionEstado.ModificarCarpetas(FDatosCarpeta.IdCarpeta,
FDatosCarpeta.CodiResuCarpeta,
FDatosCarpeta.IdFlujoNuevo,
False,IdenTraz,UsuaProc) then
raise Exception.Create('Error al cambiar el Estado de la Carpeta.');
end;
if not DAODevolucionEstado.ModificarCajas(FDatosCarpeta.IdCaja, CodiCaja,
IdenTraz, UsuaProc) then
raise Exception.Create('Error al abrir la Caja de la Carpeta.');
end
else
begin
if not DAODevolucionEstado.ModificarCarpetas(FDatosCarpeta.IdCarpeta,
FDatosCarpeta.CodiResuCarpeta,
FDatosCarpeta.IdFlujoNuevo,
False,IdenTraz,UsuaProc) then
raise Exception.Create('Error al cambiar el Estado de la Carpeta.');
end;
end;
FinalizarTransaccion;
RetiOkok := False;
{SI LA CARPETA POSEE AL MENOS UN FOLIO EN UNA RUTA DEL FTP SE REALIZA EL RETIRO
DE LAS IMAGENES}
if FDatosCarpeta.RutaImagenes <> '' then
begin
try
RetirarImagenes;
RetiOkok := True;
except
on E:Exception do
MensErro:= LeftStr(MensErro + E.Message,150);
end;
end
else
RetiOkok:= True;
IniciarTransaccion;
if RetiOkok then
begin
if not p_ElimCarp then
begin
if not DAODevolucionEstado.ModificarCarpetas(FDatosCarpeta.IdCarpeta,
FDatosCarpeta.CodiResuCarpeta,
FDatosCarpeta.IdFlujoNuevo,
True,IdenTraz,UsuaProc) then
raise Exception.Create('Error al Habilitar la Carpeta.');
end;
MensErro:= 'OK';
end;
DAODevolucionEstado.ModificarTrazaCarpeta(IdenTraz,FDatosCarpeta,MensErro);
FinalizarTransaccion;
end;
except
on e:exception do
begin
DAODevolucionEstado.CancelarTransaccion;
raise Exception.Create('Error ralizando la devoluciรณn de la Carpeta ['
+ FDatosCarpeta.CodiResuCarpeta + ']. '
+ #10#13 + '* ' + e.Message);
end;
end;
end;
Procedure TProcesoDevolucionEsta.ObtenerCarpetas(p_CodiCaja: string);
begin
FCarpetas:= DAODevolucionEstado.ConsultarCarpetas(p_CodiCaja);
end;
Procedure TProcesoDevolucionEsta.ObtenerDatosCarpeta(p_IdenCarp: Int32; p_CodiCarp: string);
begin
FDatosCarpeta := DAODevolucionEstado.ConsultarDatosCarpeta(p_IdenCarp, p_CodiCarp);
FDatosCarpeta.IpProceso := FrmDevolucionEstado.DireccIp;
FDatosCarpeta.UsuarioProceso := ParamStr(1);
end;
Procedure TProcesoDevolucionEsta.ObtenerEstadosDevolver(p_IdenFlujMaxi: Int32);
begin
FEstadosDevolver.DataSet.Filtered:= False;
FEstadosDevolver.DataSet.Filter := IfThen(p_IdenFlujMaxi = 0,'IdFlujo = ','IdFlujo < ')
+ IntToStr(p_IdenFlujMaxi);
FEstadosDevolver.DataSet.Filtered:= True;
end;
Procedure TProcesoDevolucionEsta.RetirarImagenes;
var
CodiFoli : string;
ConexFTP : TFtpGestor;
CarpPdff : string;
DatosFTP : TFtpImagen;
I : Int16;
ListVers : TStringList;
RutaCarp : string;
RutaFoli : string;
TipoFoli : Char;
begin
try
RutaCarp := FDatosCarpeta.RutaImagenes;
if (Trim(LeftStr(RutaCarp,4))<> '') and (MidStr(RutaCarp,5,1) = '\')
and (Trim(MidStr(RutaCarp,6,2))<> '') and (MidStr(RutaCarp,8,1) = '\')
and (Trim(MidStr(RutaCarp,9,2))<> '') and (MidStr(RutaCarp,11,2) = '\M')
and (Trim(MidStr(RutaCarp,13,8))<> '') then
begin
CarpPdff := LeftStr(RutaCarp,4) + 'FE' + MidStr(RutaCarp,5,1000);
with FFoliosCarpeta.DataSet do
begin
Filtered := False;
Filter := 'idfolio is not null ';
Filtered := True;
if RecordCount > 0 then
begin
First;
{SE VERIFICA QUE TODOS LOS FOLIOS TENGEN LA MISMA RUTA DE IMAGENES}
RutaFoli := FieldByName('rutaftp').AsString;
if RightStr(RutaFoli,1) <> '\' then
RutaFoli := RutaFoli + '\';
while (not Eof) and (RutaFoli = RutaCarp ) do
begin
RutaFoli := FieldByName('rutaftp').AsString;
if RightStr(RutaFoli,1) <> '\' then
RutaFoli := RutaFoli + '\';
Next;
end;
if Eof then
begin
ListVers := TStringList.Create;
DatosFTP := TFtpImagen.Create;
ConexFTP := TFtpGestor.Create(DatosFTP.HostFtpImg,DatosFTP.UsuarioFtpImg,
DatosFTP.PasswordFtpImg,DatosFTP.PuertoFtpImg);
ConexFTP.ConectarFTP;
First;
FDatosCarpeta.CantImagTiff := 0;
FDatosCarpeta.CantImagPdff := 0;
While (not Eof) do
begin
FDatosCarpeta.RutaBackImagTiff := DatosFTP.CarpetaRaizFtpImg + RutaCarp;
CodiFoli := 'M' + FieldByName('codigofolio').AsString;
TipoFoli := FieldByName('tipofolio').AsString[1];
{SI SE DEVUELVE A CUALQUIER ESTADO, SE ELIMINAN LOS ARCHIVOS XML}
if (FDatosCarpeta.IdFlujoNuevo in [4,3,2,1,0]) then
ConexFTP.BorrarArchivos(DatosFTP.CarpetaRaizFtpImg + RutaCarp, CodiFoli + '*.xml');
if (FDatosCarpeta.IdFlujoNuevo in [2,1,0]) then
if ((FDatosCarpeta.IdFlujoNuevo in [2]) and (TipoFoli = 'T')) or
(FDatosCarpeta.IdFlujoNuevo in [1,0]) then
FDatosCarpeta.CantImagTiff:= FDatosCarpeta.CantImagTiff
+ ConexFTP.BorrarArchivos(DatosFTP.CarpetaRaizFtpImg + RutaCarp,
CodiFoli + '*.tif')
else
begin
{SE ELIMINAN LAS IMAGENES CON VERSION > 0 (PARA DEJAR LA ORIGNAL UNICAMENTE)}
ListVers:= ConexFTP.ListarArchivo(DatosFTP.CarpetaRaizFtpImg + RutaCarp,
CodiFoli + '*.tif');
for I := 0 to ListVers.Count -1 do
begin
if Pos('v00.tif',LowerCase(ListVers[I])) = 0 then
ConexFTP.BorrarArchivos(DatosFTP.CarpetaRaizFtpImg + RutaCarp, ListVers[I] + '*');
end;
end;
if (FDatosCarpeta.IdFlujoNuevo in [4,3,2,1,0]) then
FDatosCarpeta.CantImagPdff:= FDatosCarpeta.CantImagPdff
+ ConexFTP.BorrarArchivos(DatosFTP.CarpetaRaizFtpPdf + CarpPdff,
CodiFoli + '*.pdf');
Next;
end;
{SI LA CARPETA DE IMAGENES TIF Y ARCHIVOS XML ESTA VACIA, SE ELIMINA LA CARPETA}
if ConexFTP.ListarArchivo(DatosFTP.CarpetaRaizFtpImg + RutaCarp, '*.*').Count = 0 then
IF ConexFTP.BorrarCarpeta(DatosFTP.CarpetaRaizFtpImg, RutaCarp, 'RECURSIVO' ) = 'R' then
raise Exception.Create('Se presenta falla al eliminar la Carpeta: ['
+ DatosFTP.CarpetaRaizFtpImg + RutaCarp + ']');
{SI LA CARPETA DE IMAGENES PDF ESTA VACIA, SE ELIMINA LA CARPETA}
if ConexFTP.ListarArchivo(DatosFTP.CarpetaRaizFtpPdf + CarpPdff, '*.*').Count = 0 then
IF ConexFTP.BorrarCarpeta(DatosFTP.CarpetaRaizFtpPdf, CarpPdff, 'RECURSIVO' ) = 'R' then
raise Exception.Create('Se presenta falla al eliminar la Carpeta: ['
+DatosFTP.CarpetaRaizFtpPdf + CarpPdff + ']');
ConexFTP.DesconectarFTP;
ConexFTP.Free;
DatosFTP.Free;
end
else
raise Exception.Create('Falla al retirar archivos de la Carpeta: ['
+ RutaCarp + ']. Existen folios en Rutas Diferentes.');
end
else
raise Exception.Create('Inconsistencia al retirar archivos de la Carpeta: ['
+ RutaCarp + ']');
end;
end
else
begin
if RutaCarp <> '' then
raise Exception.Create('La ruta de las Imรกgenes [' + RutaCarp + '] es Incorrecta.');
end;
except
on e:exception do
raise Exception.Create('Imposible Retirar Imรกgenes del FTP. * ' + e.Message);
end;
end;
Function TProcesoDevolucionEsta.VerificarVersion(p_NombModu: string; p_VersModu: string; p_VeriRuta: Boolean): boolean;
begin
DMAplicacion.VerificarAplicacion(p_NombModu,p_VersModu, 'DEVOLUCIรN DE ESTADO', p_VeriRuta);
end;
{$REGION 'CONSTRUTOR AND DESTRUCTOR'}
constructor TProcesoDevolucionEsta.Create;
begin
try
DAODevolucionEstado := TDAODevolucionEstado.create;
FCarpetas := TDataSource.create(nil);
FDatosCarpeta := TCarpetaDevolucionEsta.create;
FEstadosDevolver := TDataSource.create(nil);
FEstadosDevolver := DAODevolucionEstado.ConsultarFlujosYTareas;
FFoliosCarpeta := TDataSource.Create(nil);
except
on e:Exception do
raise Exception.Create('No es posible Inicializar Componentes. '
+ #10#13 + '* ' + e.Message);
end;
end;
destructor TProcesoDevolucionEsta.Destroy;
begin
DAODevolucionEstado.Free;
FCarpetas.Free;
FDatosCarpeta.Free;
FEstadosDevolver.free;
FFoliosCarpeta.Free;
end;
{$ENDREGION}
{$REGION 'GETTERS AND SETTERS'}
{$ENDREGION}
end.
|
{*******************************************************}
{ }
{ Copyright (c) 2001-2012 by Alex A. Lagodny }
{ }
{*******************************************************}
unit aOPCClass;
interface
uses
SysUtils, Classes;
type
TDirection = (dNext,dPred);
{ THashCollectionItem }
THashCollectionItem = class(TCollectionItem)
private
FHashCode: Integer;
FIndex: Integer;
FLeft: THashCollectionItem;
FRight: THashCollectionItem;
procedure AddHash;
procedure DeleteHash;
protected
FName: string;
procedure SetName(const Value: string);virtual;
function GetDisplayName: string; override;
procedure SetIndex(Value: Integer); override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property Index: Integer read FIndex write SetIndex;
published
property Name: string read FName write SetName;
end;
{ THashCollection }
THashCollection = class(TCollection)
private
FHash: array[0..255] of THashCollectionItem;
public
function IndexOf(const Name: string): Integer;
end;
implementation
{ THashCollectionItem }
function MakeHashCode(const Str: string): Integer;
var
s: string;
begin
s := AnsiLowerCase(Str);
Result := Length(s)*16;
if Length(s)>=2 then
Result := Result + (Ord(s[1]) + Ord(s[Length(s)-1]));
Result := Result and 255;
end;
constructor THashCollectionItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FIndex := inherited Index;
AddHash;
end;
destructor THashCollectionItem.Destroy;
var
i: Integer;
begin
for i:=FIndex+1 to Collection.Count-1 do
Dec(THashCollectionItem(Collection.Items[i]).FIndex);
DeleteHash;
inherited Destroy;
end;
procedure THashCollectionItem.Assign(Source: TPersistent);
begin
if Source is THashCollectionItem then
begin
Name := THashCollectionItem(Source).Name;
end else
inherited Assign(Source);
end;
procedure THashCollectionItem.AddHash;
var
Item: THashCollectionItem;
begin
FHashCode := MakeHashCode(FName);
Item := THashCollection(Collection).FHash[FHashCode];
if Item<>nil then
begin
Item.FLeft := Self;
Self.FRight := Item;
end;
THashCollection(Collection).FHash[FHashCode] := Self;
end;
procedure THashCollectionItem.DeleteHash;
begin
if FLeft<>nil then
begin
FLeft.FRight := FRight;
if FRight<>nil then
FRight.FLeft := FLeft;
end else
begin
if FHashCode<>-1 then
begin
THashCollection(Collection).FHash[FHashCode] := FRight;
if FRight<>nil then
FRight.FLeft := nil;
end;
end;
FLeft := nil;
FRight := nil;
end;
function THashCollectionItem.GetDisplayName: string;
begin
Result := Name;
if Result='' then Result := inherited GetDisplayName;
end;
procedure THashCollectionItem.SetIndex(Value: Integer);
begin
if FIndex<>Value then
begin
FIndex := Value;
inherited SetIndex(Value);
end;
end;
procedure THashCollectionItem.SetName(const Value: string);
begin
if FName<>Value then
begin
FName := Value;
DeleteHash;
AddHash;
end;
end;
{ THashCollection }
function THashCollection.IndexOf(const Name: string): Integer;
var
Item: THashCollectionItem;
begin
Item := FHash[MakeHashCode(Name)];
while Item<>nil do
begin
if AnsiCompareText(Item.Name, Name)=0 then
begin
Result := Item.FIndex;
Exit;
end;
Item := Item.FRight;
end;
Result := -1;
end;
end.
|
unit ADOActivityLog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ADOdb, seqnum, ThreadedADOQuery,ThreadedQueryDef;
type
TErrorProc = procedure (Sender : TObject; ErrorMsg : string) of object;
TADOActivityLog = class(TComponent)
private
FError: TErrorProc; // when an error occurs in the thread.
FOnComplete: TNotifyEvent;
{ Private declarations }
fActive:boolean;
fThreaded:boolean;
fAppName: string;
fIPAddress: string;
fSequence: string;
fSequenceNumber: TSequenceNumber;
fNTUser: string;
fComputerName:string;
fDTSender:string;
fDBTime:extended;
fTrans: string;
fDescription: string;
fVIN:string;
fSendError:boolean;
fADOStoredProc:TADOStoredProc;
fADOConnection: TADOConnection;
fThreadedQuery: TThreadedADOQuery;
fQueryList:TStringList;
fQueryCount:integer;
msglist: array [0..1000] of string;
ftop:integer;
fbottom:integer;
fconnectionstring:string;
function GetSequence: string;
procedure SetSequence( Sequence: string );
procedure SetConnectionString(connectionstring:string);
procedure SetOnComplete(Value: TNotifyEvent);
procedure SetError(value : TErrorProc);
procedure SendError (msg : string);
procedure BeforeRun(Sender: TObject; Dataset: TADOQuery);
procedure ADOQueryComplete(Sender: TObject; Dataset: TADOQuery);
procedure ADOQueryError(Sender: TObject; ErrorMsg: String);
function GetConnectionStringItem (index : string) : string;
procedure SetConnectionStringItem (index : string; value : string);
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Send;
property ConnectionStringItem [index : string] : string
read GetConnectionStringItem
write SetConnectionStringItem;
published
{ Published declarations }
property Active: boolean
read fActive
write fActive;
property Threaded: boolean
read fThreaded
write fThreaded;
property AppName: string
read fAppName
write fAppName;
property IPAddress: string
read fIPAddress
write fIPAddress;
property Sequence: string
read GetSequence
write SetSequence;
property NTUser: string
read fNTUser
write fNTUser
stored False;
property ComputerName: string
read fComputerName
write fComputerName
stored False;
property DTSender: string
read fDTSender
write fDTSender;
property DBTime: extended
read fDBTime
write fDBTime;
property Trans: string
read fTrans
Write fTrans;
property Description: string
read fDescription
write fDescription;
property VIN: string
read fVIN
write fVIN;
property OnError : TErrorProc
read FError
write SetError;
property OnComplete: TNotifyEvent
read fOnComplete
write SetOnComplete;
property QueryCount: integer
read fquerycount
write fQueryCount;
property ConnectionString: string
read fconnectionstring
write SetConnectionString;
end;
const
ConnectionStringconst='Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Activity;Data Source=T22MAD02';
//ConnectionString='Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Activity;Data Source=ISID6052';
ProcedureName='InsertDetailedAct_Log;1';
msglistsize = 1000;
implementation
//Get current NT User name to fill in login box
function CurrentUserName:String;
var
u: array[0..127] of Char;
sz:DWord;
begin
sz:=SizeOf(u);
GetUserName(u,sz);
Result:=u;
end;
//Get current Computer name to fill in login box
function CurrentComputerName:String;
var
u: array[0..127] of Char;
sz:DWord;
begin
sz:=SizeOf(u);
GetComputerName(u,sz);
Result:=u;
end;
constructor TADOActivityLog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fSequenceNumber:=TSequenceNumber.Create(self);
fSequenceNumber.SequenceValue:=1;
fComputerName:=CurrentComputerName;
fNTUser:=CurrentUserName;
fDTsender:='';
fSequence:=fSequenceNumber.SequenceNumber;
//Non Threaded
fADOConnection:=TADOConnection.Create(self);
fADOConnection.LoginPrompt:=False;
fADOConnection.ConnectionString:=ConnectionStringconst;
fADOStoredProc:=TADOStoredProc.Create(self);
fADOStoredProc.Connection:=fADOConnection;
fADOStoredProc.ProcedureName:=ProcedureName;
//Threaded
if fThreaded then
begin
fThreadedQuery:=TThreadedADOQuery.Create(self);
fThreadedQuery.ConnectionString:=ConnectionStringconst;
fThreadedQuery.RunMode:=runContinuous;
fThreadedQuery.QryCommand:=qryExec;
fThreadedQuery.KeepConnection:=False;
fThreadedQuery.TimerInitial:=50;
fThreadedQuery.TimerRestart:=200;
fThreadedQuery.OnBeforeRun:=BeforeRun;
fThreadedQuery.OnComplete:=ADOQueryComplete;
fThreadedQuery.OnError:=ADOQueryError;
end;
fQueryList:=TstringList.Create;
fQueryCount:=0;
fSendError:=False;
end;
destructor TADOActivityLog.Destroy;
begin
fSequenceNumber.Free;
fADOStoredProc.Free;
if fThreaded then
begin
fThreadedQuery.Free;
end;
fQueryList.Free;
inherited destroy;
end;
procedure TADOActivityLog.SetConnectionString(connectionstring:string);
begin
if assigned(fADOConnection) then
fADOConnection.Connectionstring:=connectionstring;
if assigned(fThreadedQuery) then
fThreadedQuery.ConnectionString:=connectionstring;
fconnectionstring:=connectionstring;
end;
procedure TADOActivityLog.Send;
var
sdesc,desc:string;
begin
if (fDTSender = '') then
begin
fDTSender:=formatdatetime('yyyymmddhhmmsszz',now);
end;
desc:=fDescription;
while length(desc) > 0 do
begin
if length(desc) > 100 then
begin
sdesc:=copy(desc,1,100);
desc:=copy(desc,101,length(desc)-100);
end
else
begin
sdesc:=desc;
desc:='';
end;
if fThreaded then
begin
try
msglist[fbottom]:='EXEC '+Copy(ProcedureName,1,pos(';',ProcedureName)-1)
+' '''+fAppName
+''','''+fIPAddress
+''','''+fTrans
+''','''+fDTSender
+''','''+fComputerName
+''','''+sdesc
+''','''+fNTUser
+''','+FloatToStr(fDBTime)
+' ,'''+fVIN
+''','+fSequenceNumber.SequenceNumber;
INC(fbottom);
if fbottom>msglistsize then
fbottom:=0;
INC(fQueryCount);
if (not fThreadedQuery.Active) and fActive then
begin
fThreadedQuery.Active:=True;
end;
except
on e:exception do
begin
SendError('Send ERROR:: '+e.message);
end;
end;
end
else
begin
try
fADOConnection.Connected:=True;
fADOStoredProc.Parameters.refresh;
fADOStoredProc.Parameters.ParamByName('@App_From').Value:=fAppName;
fADOStoredProc.Parameters.ParamByName('@IP_Address').Value:=fIPAddress;
fADOStoredProc.Parameters.ParamByName('@Trans').Value:=fTrans;
fADOStoredProc.Parameters.ParamByName('@DT_Sender').Value:=fDTSender;
fADOStoredProc.Parameters.ParamByName('@ComputerName').Value:=fComputerName;
fADOStoredProc.Parameters.ParamByName('@Description').Value:=sdesc;
fADOStoredProc.Parameters.ParamByName('@NTUserName').Value:=fNTUser;
fADOStoredProc.Parameters.ParamByName('@DB_Time').Value:=fDBTime;
fADOStoredProc.Parameters.ParamByName('@VIN').Value:=fVIN;
fADOStoredProc.Parameters.ParamByName('@Sequence_Number').Value:=fSequenceNumber.SequenceNumber;
fADOStoredProc.ExecProc;
fADOConnection.Connected:=False;
if (Assigned (fOnComplete)) then
fOnComplete(self);
except
on e:exception do
begin
fADOConnection.Connected:=False;
SendError('Send ERROR:: '+e.message);
end;
end;
end;
end;
end;
procedure TADOActivityLog.BeforeRun(Sender: TObject; Dataset: TADOQuery);
begin
Dataset.SQL.Clear;
Dataset.SQL.Add(msglist[ftop]);
end;
procedure TADOActivityLog.ADOQueryComplete(Sender: TObject; Dataset: TADOQuery);
begin
INC(fTop);
if fTop>msglistsize then
fTop:=0;
DEC(fQueryCount);
// stop query if no more
if fQueryCount <= 0 then
fThreadedQuery.Active:=False;
if (Assigned (fOnComplete)) then
fOnComplete(self);
end;
procedure TADOActivityLog.ADOQueryError(Sender: TObject; ErrorMsg: String);
begin
// shutdown query if error
fThreadedQuery.Active:=False;
SendError(ErrorMsg);
end;
function TADOActivityLog.GetSequence: string;
begin
result:=fSequence;
end;
procedure TADOActivityLog.SetSequence( Sequence: string );
begin
if Sequence <> '' then
begin
try
fSequenceNumber.SequenceNumber:=Sequence;
fSequence:=fSequenceNumber.SequenceNumber;
except
fSequence:='0001';
SendError('Invalid sequence number');
end;
end
else
begin
fSequence:='0001';
end
end;
procedure TADOActivityLog.SetError(value : TErrorProc );
begin
FError:= value;
end;
procedure TADOActivityLog.SetOnComplete(Value: TNotifyEvent);
begin
FOnComplete := Value;
end;
procedure TADOActivityLog.SendError (msg : string);
begin
if (Assigned (FError)) then
FError (self, msg);
end;
//-------------------------------------------------------
//
// get and set components of the ConnectionString
//
// set it this way
// ActLog.ConnectionItem ['Data Source'] := 'T22MADBU';
//
//
// get it this way
//
// var
// s : string;
// begin
// s := ActLog.ConnectionItem ['Provider'];
//
type
TSplitType = (spltBefore, spltKey, spltSeparator, spltValue, spltAfter);
TSplitList = array [TSplitType] of string;
function split (src : string; key : string) : TSplitList;
var
bgn : integer;
begin
result [spltBefore] := '';
result [spltKey] := '';
result [spltSeparator] := '';
result [spltValue] := '';
result [spltAfter] := '';
bgn := pos (UpperCase (key), UpperCase (src));
if (bgn > 0) then
begin
result [spltBefore] := copy (src, 1, bgn-1);
result [spltKey] := copy (src, bgn, length (key));
inc (bgn, length (key));
while (bgn <= length (src)) and ((src [bgn] <= ' ') or (src [bgn] = '=')) do
begin
result [spltSeparator] := result [spltSeparator] + src [bgn];
inc (bgn);
end;
while (bgn <= length (src)) and (src [bgn] <> ';') do
begin
result [spltValue] := result [spltValue] + src [bgn];
inc (bgn);
end;
result [spltAfter] := copy (src, bgn, 9999);
end;
end;
function TADOActivityLog.GetConnectionStringItem (index : string) : string;
var
splitter : TSplitList;
begin
splitter := split (fADOConnection.ConnectionString, index);
result := splitter [spltValue];
end;
procedure TADOActivityLog.SetConnectionStringItem (index : string; value : string);
var
splitter : TSplitList;
wasActive : boolean;
begin
splitter := split (fADOConnection.ConnectionString, index);
if (splitter [spltValue] <> '') then
begin
with fADOConnection do
begin
wasActive := Connected;
Connected := false;
ConnectionString := splitter [spltBefore] + splitter [spltKey] +
splitter [spltSeparator] + value +
splitter [spltAfter];
Connected := wasActive;
end;
if fThreaded then
begin
fThreadedQuery.ConnectionString := fADOConnection.ConnectionString;
end;
end;
end;
end.
|
unit snowbros_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,m68000,main_engine,controls_engine,gfx_engine,ym_3812,
rom_engine,pal_engine,kaneco_pandora,sound_engine;
procedure Cargar_snowbros;
procedure snowbros_principal;
function iniciar_snowbros:boolean;
procedure reset_snowbros;
procedure cerrar_snowbros;
//Main CPU
function snowbros_getword(direccion:dword):word;
procedure snowbros_putword(direccion:dword;valor:word);
//Sound CPU
function snowbros_snd_getbyte(direccion:word):byte;
procedure snowbros_snd_putbyte(direccion:word;valor:byte);
procedure snowbros_sound_act;
function snowbros_snd_inbyte(puerto:word):byte;
procedure snowbros_snd_outbyte(valor:byte;puerto:word);
procedure snd_irq(irqstate:byte);
implementation
const
snowbros_rom:array[0..2] of tipo_roms=(
(n:'sn6.bin';l:$20000;p:0;crc:$4899ddcf),(n:'sn5.bin';l:$20000;p:$1;crc:$ad310d3f),());
snowbros_char:tipo_roms=(n:'sbros-1.41';l:$80000;p:0;crc:$16f06b3a);
snowbros_sound:tipo_roms=(n:'sbros-4.29';l:$8000;p:0;crc:$e6eab4e4);
//Dip
snowbros_dip_a:array [0..6] of def_dip=(
(mask:$1;name:'Region';number:2;dip:((dip_val:$0;dip_name:'Europe'),(dip_val:$1;dip_name:'America (Romstar license)'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2;name:'Flip Screen';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4;name:'Service Mode';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$8;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Coin A';number:7;dip:((dip_val:$0;dip_name:'4C 1C EUR'),(dip_val:$10;dip_name:'3C 1C EUR'),(dip_val:$20;dip_name:'2C 1C EUR'),(dip_val:$10;dip_name:'2C 1C AME'),(dip_val:$30;dip_name:'1C 1C'),(dip_val:$0;dip_name:'2C 3C AME'),(dip_val:$20;dip_name:'2C 1C AME'),(),(),(),(),(),(),(),(),())),
(mask:$c0;name:'Coin B';number:8;dip:((dip_val:$40;dip_name:'2C 1C AME'),(dip_val:$c0;dip_name:'1C 1C AME'),(dip_val:$0;dip_name:'2C 3C AME'),(dip_val:$80;dip_name:'1C 2C AME'),(dip_val:$c0;dip_name:'1C 2C EUR'),(dip_val:$80;dip_name:'1C 3C EUR'),(dip_val:$40;dip_name:'1C 4C EUR'),(dip_val:$0;dip_name:'1C 6C EUR'),(),(),(),(),(),(),(),())),());
snowbros_dip_b:array [0..5] of def_dip=(
(mask:$3;name:'Difficulty';number:4;dip:((dip_val:$2;dip_name:'Easy'),(dip_val:$3;dip_name:'Normal'),(dip_val:$1;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$c;name:'Bonus Life';number:4;dip:((dip_val:$4;dip_name:'100k 200k+'),(dip_val:$c;dip_name:'100k'),(dip_val:$8;dip_name:'200k'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$30;name:'Lives';number:4;dip:((dip_val:$20;dip_name:'1'),(dip_val:$0;dip_name:'2'),(dip_val:$30;dip_name:'3'),(dip_val:$10;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Invulnerability';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$80;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
rom:array[0..$1ffff] of word;
ram:array[0..$1fff] of word;
sound_latch:byte;
procedure Cargar_snowbros;
begin
llamadas_maquina.iniciar:=iniciar_snowbros;
llamadas_maquina.bucle_general:=snowbros_principal;
llamadas_maquina.cerrar:=cerrar_snowbros;
llamadas_maquina.reset:=reset_snowbros;
llamadas_maquina.fps_max:=57.5;
end;
function iniciar_snowbros:boolean;
const
pc_x:array[0..15] of dword=(0, 4, 8, 12, 16, 20, 24, 28,
8*32+0, 8*32+4, 8*32+8, 8*32+12, 8*32+16, 8*32+20, 8*32+24, 8*32+28);
pc_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32,
16*32, 17*32, 18*32, 19*32, 20*32, 21*32, 22*32, 23*32);
var
memoria_temp:array[0..$7ffff] of byte;
begin
iniciar_snowbros:=false;
iniciar_audio(false);
//Pantallas: principal+char y sprites
screen_init(1,512,512,true,true);
iniciar_video(256,224);
//Main CPU
main_m68000:=cpu_m68000.create(8000000,262);
main_m68000.change_ram16_calls(snowbros_getword,snowbros_putword);
//Sound CPU
snd_z80:=cpu_z80.create(6000000,262);
snd_z80.change_ram_calls(snowbros_snd_getbyte,snowbros_snd_putbyte);
snd_z80.change_io_calls(snowbros_snd_inbyte,snowbros_snd_outbyte);
snd_z80.init_sound(snowbros_sound_act);
//pandora
pandora.mask_nchar:=$fff;
pandora.color_offset:=0;
pandora.clear_screen:=true;
//Sound Chips
ym3812_init(0,3000000,snd_irq);
//cargar roms
if not(cargar_roms16w(@rom[0],@snowbros_rom[0],'snowbros.zip',0)) then exit;
//cargar sonido
if not(cargar_roms(@mem_snd[0],@snowbros_sound,'snowbros.zip')) then exit;
//convertir chars
if not(cargar_roms(@memoria_temp[0],@snowbros_char,'snowbros.zip')) then exit;
init_gfx(0,16,16,$1000);
gfx[0].trans[0]:=true;
gfx_set_desc_data(4,0,32*32,0,1,2,3);
convert_gfx(0,0,@memoria_temp[0],@pc_x[0],@pc_y[0],false,false);
//DIP
marcade.dswa:=$fe;
marcade.dswb:=$ff;
marcade.dswa_val:=@snowbros_dip_a;
marcade.dswb_val:=@snowbros_dip_b;
//final
reset_snowbros;
iniciar_snowbros:=true;
end;
procedure cerrar_snowbros;
begin
main_m68000.free;
snd_z80.free;
ym3812_close(0);
close_audio;
close_video;
end;
procedure reset_snowbros;
begin
main_m68000.reset;
snd_z80.reset;
pandora_reset;
ym3812_reset(0);
reset_audio;
marcade.in0:=$ff00;
marcade.in1:=$7f00;
marcade.in2:=$7f00;
sound_latch:=0;
end;
procedure update_video_snowbros;inline;
begin
pandora_update_video(1,0);
actualiza_trozo_final(0,16,256,224,1);
end;
procedure eventos_snowbros;
begin
if event.arcade then begin
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $feff) else marcade.in1:=(marcade.in1 or $0100);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $Fdff) else marcade.in1:=(marcade.in1 or $0200);
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fbff) else marcade.in1:=(marcade.in1 or $0400);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $F7ff) else marcade.in1:=(marcade.in1 or $0800);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $efff) else marcade.in1:=(marcade.in1 or $1000);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $dfff) else marcade.in1:=(marcade.in1 or $2000);
if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $bfff) else marcade.in1:=(marcade.in1 or $4000);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $0400);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $0800);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $0100);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $0200);
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $feff) else marcade.in2:=(marcade.in2 or $0100);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $Fdff) else marcade.in2:=(marcade.in2 or $0200);
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fbff) else marcade.in2:=(marcade.in2 or $400);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $F7ff) else marcade.in2:=(marcade.in2 or $0800);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $efff) else marcade.in2:=(marcade.in2 or $1000);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $dfff) else marcade.in2:=(marcade.in2 or $2000);
if arcade_input.but2[1] then marcade.in2:=(marcade.in2 and $bfff) else marcade.in2:=(marcade.in2 or $4000);
end;
end;
procedure snowbros_principal;
var
frame_m,frame_s:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=main_m68000.tframes;
frame_s:=snd_z80.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 261 do begin
//Main CPU
main_m68000.run(frame_m);
frame_m:=frame_m+main_m68000.tframes-main_m68000.contador;
//Sound CPU
snd_z80.run(frame_s);
frame_s:=frame_s+snd_z80.tframes-snd_z80.contador;
case f of
31:main_m68000.irq[4]:=ASSERT_LINE;
127:main_m68000.irq[3]:=ASSERT_LINE;
239:begin
main_m68000.irq[2]:=ASSERT_LINE;
update_video_snowbros;
end;
end;
end;
eventos_snowbros;
video_sync;
end;
end;
function snowbros_getword(direccion:dword):word;
begin
case direccion of
0..$3ffff:snowbros_getword:=rom[direccion shr 1];
$100000..$103fff:snowbros_getword:=ram[(direccion and $3fff) shr 1];
$300000:snowbros_getword:=sound_latch;
$500000:snowbros_getword:=marcade.in1+marcade.dswa;
$500002:snowbros_getword:=marcade.in2+marcade.dswb;
$500004:snowbros_getword:=marcade.in0;
$600000..$6001ff:snowbros_getword:=buffer_paleta[(direccion and $1ff) shr 1];
$700000..$701fff:snowbros_getword:=pandora.sprite_ram[(direccion and $1fff) shr 1]
end;
end;
procedure cambiar_color(tmp_color,numero:word);inline;
var
color:tcolor;
begin
color.b:=pal5bit(tmp_color shr 10);
color.g:=pal5bit(tmp_color shr 5);
color.r:=pal5bit(tmp_color);
set_pal_color(color,numero);
end;
procedure snowbros_putword(direccion:dword;valor:word);
begin
if direccion<$40000 then exit;
case direccion of
$100000..$103fff:ram[(direccion and $3fff) shr 1]:=valor;
$200000,$702000..$7022ff:exit;
$400000:main_screen.flip_main_screen:=(valor and $8000)=0;
$300000:begin
sound_latch:=valor and $ff;
snd_z80.pedir_nmi:=PULSE_LINE;
end;
$600000..$6001ff:if buffer_paleta[(direccion and $1ff) shr 1]<>valor then begin
buffer_paleta[(direccion and $1ff) shr 1]:=valor;
cambiar_color(valor,(direccion and $1ff) shr 1);
end;
$700000..$701fff:pandora.sprite_ram[(direccion and $1fff) shr 1]:=valor and $ff;
$800000:main_m68000.irq[4]:=CLEAR_LINE;
$900000:main_m68000.irq[3]:=CLEAR_LINE;
$a00000:main_m68000.irq[2]:=CLEAR_LINE;
end;
end;
function snowbros_snd_getbyte(direccion:word):byte;
begin
snowbros_snd_getbyte:=mem_snd[direccion];
end;
procedure snowbros_snd_putbyte(direccion:word;valor:byte);
begin
if direccion>$7fff then mem_snd[direccion]:=valor;
end;
function snowbros_snd_inbyte(puerto:word):byte;
begin
case (puerto and $ff) of
$2:snowbros_snd_inbyte:=ym3812_status_port(0);
$4:snowbros_snd_inbyte:=sound_latch;
end;
end;
procedure snowbros_snd_outbyte(valor:byte;puerto:word);
begin
case (puerto and $ff) of
$2:ym3812_control_port(0,valor);
$3:ym3812_write_port(0,valor);
$4:sound_latch:=valor;
end;
end;
procedure snowbros_sound_act;
begin
ym3812_Update(0);
end;
procedure snd_irq(irqstate:byte);
begin
if (irqstate<>0) then snd_z80.pedir_irq:=ASSERT_LINE
else snd_z80.pedir_irq:=CLEAR_LINE;
end;
end.
|
unit ULogin;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts,
FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation, FMX.Edit,
System.Math, System.Actions, FMX.ActnList, FMX.StdActns;
type
TFrmLogin = class(TForm)
layoutBase: TLayout;
LayoutLogin: TLayout;
BtnEfetuarLogin: TButton;
EditLogin: TEdit;
EditSenha: TEdit;
ImageLogoEntidade: TImage;
LabelLogin: TLabel;
LabelSenha: TLabel;
LabelTitleLogin: TLabel;
LabelVersion: TLabel;
ToolBarLogin: TToolBar;
LayoutTopo: TLayout;
ImageLogoApp: TImage;
ScrollBoxForm: TScrollBox;
LayoutForm: TLayout;
LabelAlerta: TLabel;
procedure PrepareLogin(Sender: TObject);
procedure OcultarAlerta(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EditLoginKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure EditSenhaKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure FormVirtualKeyboardHidden(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
procedure FormVirtualKeyboardShown(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
procedure FormFocusChanged(Sender: TObject);
private
{ Private declarations }
FWBounds : TRectF;
FNeedOffSet : Boolean;
public
{ Public declarations }
procedure CalcContentBounds(Sender : TObject; var ContentBounds : TRectF);
procedure RestorePosition;
procedure UpdatePosition;
end;
var
FrmLogin: TFrmLogin;
implementation
uses
UDados
, USplashUI
, app.Funcoes
, classes.HttpConnect
, classes.Constantes
, dao.Especialidade
, dao.Usuario
, System.Threading
, System.JSON;
{$R *.fmx}
{$R *.iPhone55in.fmx IOS}
{$R *.LgXhdpiPh.fmx ANDROID}
{$R *.NmXhdpiPh.fmx ANDROID}
procedure TFrmLogin.CalcContentBounds(Sender: TObject;
var ContentBounds: TRectF);
begin
if (FNeedOffSet and (FWBounds.Top > 0)) then
begin
ContentBounds.Bottom := Max(ContentBounds.Bottom, 2 * ClientHeight - FWBounds.Top);
end;
end;
procedure TFrmLogin.EditLoginKeyUp(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if (Key = vkReturn) then
EditSenha.SetFocus;
end;
procedure TFrmLogin.EditSenhaKeyUp(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if (Key = vkReturn) then
PrepareLogin(BtnEfetuarLogin);
end;
procedure TFrmLogin.FormCreate(Sender: TObject);
begin
LabelVersion.Text := 'Versรฃo ' + VERSION_NAME;
ScrollBoxForm.OnCalcContentBounds := CalcContentBounds;
// // Para teste
// EditLogin.Text := 'edgar_sobrinho';
// EditSenha.Text := '12345678';
end;
procedure TFrmLogin.FormFocusChanged(Sender: TObject);
begin
UpdatePosition;
end;
procedure TFrmLogin.FormVirtualKeyboardHidden(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
begin
FWBounds.Create(0, 0, 0, 0);
FNeedOffSet := False;
RestorePosition;
end;
procedure TFrmLogin.FormVirtualKeyboardShown(Sender: TObject;
KeyboardVisible: Boolean; const Bounds: TRect);
begin
FWBounds := TRectF.Create(Bounds);
FWBounds.TopLeft := ScreenToClient(FWBounds.TopLeft);
FWBounds.BottomRight := ScreenToClient(FWBounds.BottomRight);
UpdatePosition;
end;
procedure TFrmLogin.OcultarAlerta(Sender: TObject);
begin
LabelAlerta.Visible := False;
end;
procedure TFrmLogin.PrepareLogin(Sender: TObject);
var
aKey ,
aLogin ,
aSenha : String;
aTaskLg : ITask;
iError : Integer;
aUsuario : TUsuarioDao;
begin
aKey := MD5(FormatDateTime('dd/mm/yyyy', Date));
aLogin := AnsiLowerCase( Trim(EditLogin.Text) );
aSenha := MD5( Trim(EditSenha.Text) );
if (aLogin = EmptyStr) or (aSenha = EmptyStr) then
begin
LabelAlerta.Text := 'Informar usuรกrio e/ou senha!';
LabelAlerta.Visible := True;
end
else
begin
// Buscar autenticaรงรฃo no servidor web
aUsuario := TUsuarioDao.GetInstance;
aTaskLg := TTask.Create(
procedure
var
aMsg : String;
aJsonArray : TJSONArray;
aJsonObject : TJSONObject;
aErr : Boolean;
begin
aMsg := 'Autenticando...';
try
aErr := False;
try
aUsuario.Model.Codigo := aLogin;
aUsuario.Model.Senha := aSenha;
aJsonArray := DtmDados.HttpGetUsuario(aKey) as TJSONArray;
except
On E : Exception do
begin
iError := 99;
aErr := True;
aMsg := 'Servidor da entidade nรฃo responde ...' + #13 + E.Message;
end;
end;
if not aErr then
begin
aJsonObject := aJsonArray.Items[0] as TJSONObject;
iError := StrToInt(aJsonObject.GetValue('cd_error').Value);
case iError of
0 :
begin
aUsuario.Model.Codigo := aJsonObject.GetValue('cd_usuario').Value;
aUsuario.Model.Nome := aJsonObject.GetValue('nm_usuario').Value;
aUsuario.Model.Email := aJsonObject.GetValue('ds_email').Value.Replace('...', '', [rfReplaceAll]);
aUsuario.Model.Prestador := StrToCurr(aJsonObject.GetValue('cd_prestador').Value);
aUsuario.Model.Senha := aSenha;
aUsuario.Model.Observacao := aJsonObject.GetValue('ds_observacao').Value;
aUsuario.Model.Ativo := True;
end;
else
aMsg := aJsonObject.GetValue('ds_error').Value;
end;
end;
finally
if (iError > 0) then
begin
LabelAlerta.Text := aMsg;
LabelAlerta.Visible := True;
end
else
FrmSplashUI.AbrirCadastroUsuario;
end;
end
);
aTaskLg.Start;
end;
end;
procedure TFrmLogin.RestorePosition;
begin
ScrollBoxForm.ViewportPosition := PointF(ScrollBoxForm.ViewportPosition.X, 0);
LayoutForm.Align := TAlignLayout.Client;
ScrollBoxForm.RealignContent;
end;
procedure TFrmLogin.UpdatePosition;
var
LFocused : TControl;
LFocusRect : TRectF;
begin
FNeedOffSet := False;
if Assigned(Focused) then
begin
LFocused := TControl(Focused.GetObject);
LFocusRect := LFocused.AbsoluteRect;
LFocusRect.Offset(ScrollBoxForm.ViewportPosition);
if (LFocusRect.IntersectsWith(TRectF.Create(FWBounds)) and (LFocusRect.Bottom > FWBounds.Top)) then
begin
FNeedOffSet := True;
LayoutForm.Align := TAlignLayout.Horizontal;
ScrollBoxForm.RealignContent;
Application.ProcessMessages;
ScrollBoxForm.ViewportPosition := PointF(ScrollBoxForm.ViewportPosition.X, LFocusRect.Bottom - FWBounds.Top);
end;
end;
if not FNeedOffSet then
RestorePosition;
end;
end.
|
unit UDesktopFile;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil;
type
TDesktopFile = class
private
fName: String;
fExec : String;
fIconPath : String;
fFileType : String;
fCategories: String;
fSource : String;
// fTryExec: String;
// fComment: String;
procedure SetName(aName : String);
procedure SetExec(aExec : String);
procedure SetIconPath(aIconPath : String);
procedure SetFileType(aFileType : String);
procedure SetCategories(aCategories: String);
procedure SetSource(aSource : String);
function GetName() : String;
function GetExec() : String;
function GetIconPath() : String;
function GetFileType() : String;
function GetCategories(): String;
function GetSource() : String;
public
function GetAllFiles() : TStringList;
property Name : String read GetName write SetName;
property Exec : String read GetExec write SetExec;
property IconPath : String read GetIconPath write SetIconPath;
property FileType : String read GetFileType write SetFileType;
property Categories: String read GetCategories write SetCategories;
property Source : String read GetSource write SetSource;
end;
implementation
procedure TDesktopFile.SetName(aName: String);
begin
fName := aName;
end;
function TDesktopFile.GetName(): String;
begin
GetName := fName;
end;
procedure TDesktopFile.SetExec(aExec: String);
begin
fExec := aExec;
end;
function TDesktopFile.GetExec(): String;
begin
GetExec := fExec;
end;
procedure TDesktopFile.SetIconPath(aIconPath: String);
begin
fIconPath := aIconPath;
end;
function TDesktopFile.GetIconPath(): String;
begin
GetIconPath := fIconPath;
end;
procedure TDesktopFile.SetFileType(aFileType: String);
begin
fFileType := aFileType;
end;
function TDesktopFile.GetFileType(): String;
begin
GetFileType := fFileType;
end;
procedure TDesktopFile.SetCategories(aCategories: String);
begin
fCategories := aCategories;
end;
function TDesktopFile.GetCategories(): String;
begin
GetCategories := fCategories;
end;
procedure TDesktopFile.SetSource(aSource: String);
begin
fSource := aSource;
end;
function TDesktopFile.GetSource(): String;
begin
GetSource := fSource;
end;
function TDesktopFile.GetAllFiles(): TStringList;
var
StrList: TStringList;
pathToFiles: String;
begin
pathToFiles := GetUserDir + '/.local/share/applications/';
StrList := TStringList.Create;
FindAllFiles(StrList, pathToFiles, '*.desktop');
GetAllFiles := StrList;
end;
end.
|
unit UFormBroadcast;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, winsock,
StdCtrls, UMyUtil;
const
WM_SOCK = WM_USER + 1; //่ชๅฎไนwindowsๆถๆฏ
var
UdpPort_Broadcast : Integer = 6542; //่ฎพๅฎUDP็ซฏๅฃๅท
type
TStrEvent = procedure( s : string ) of object;
// ๅนฟๆญ ็ชๅฃ
TfrmBroadcast = class(TForm)
private
s: TSocket;
addr: TSockAddr;
FSockAddrIn : TSockAddrIn;
FRevMsgEvent : TStrEvent;
private // ๆถๅ ๅนฟๆญ
procedure RevBroadcast( var Message: TMessage ); message WM_SOCK;
procedure SendBroadcast( Msg : string );
procedure SendBroadcastToIp( Msg : string; Ip: AnsiString );
public
constructor Create;
destructor Destroy; override;
public // ๆถๅๆฐๆฎ
procedure SendMsg( Msg: string );
procedure RevMsg( Msg : string );
property OnRevMsgEvent: TStrEvent read FRevMsgEvent write FRevMsgEvent;
end;
var
frmBroadcast : TfrmBroadcast;
implementation
{$R *.dfm}
procedure TfrmBroadcast.RevBroadcast(var Message: TMessage);
var
buf : array[0..4095] of Char;
len: integer;
flen: integer;
Event: word;
value: string;
begin
try
flen:=sizeof(FSockAddrIn);
FSockAddrIn.SIn_Port := htons(UdpPort_Broadcast);
Event := WSAGetSelectEvent(Message.LParam);
if Event <> FD_READ then
Exit;
len := recvfrom(s, buf, SizeOf( buf ), 0, FSockAddrIn, flen );
value := copy( buf, 1, len + 1 );
// ็บฟ็จๅค็ๆฅๆถๅนฟๆญ
RevMsg( value );
except
end;
end;
procedure TfrmBroadcast.SendBroadcast(Msg: string);
var
IpList : TStringList;
i : Integer;
begin
IpList := MyBroadcastIpList.get;
for i := 0 to IpList.Count - 1 do
SendBroadcastToIp( Msg, IpList[i] );
IpList.Free;
end;
procedure TfrmBroadcast.SendBroadcastToIp(Msg: string; Ip: AnsiString);
var
value{,hostname}: string;
len: integer;
flen : Integer;
buf: TByteArray;
begin
try
flen := SizeOf( FSockAddrIn );
FSockAddrIn.SIn_Addr.S_addr := inet_addr(pansichar(Ip));
value := Msg;
len := sendto(s, value[1], Length(value) * 2, 0, FSockAddrIn, flen);
except
end;
end;
procedure TfrmBroadcast.SendMsg(Msg: String);
begin
SendBroadcast( Msg );
end;
constructor TfrmBroadcast.Create;
var
TempWSAData: TWSAData;
optval: integer;
begin
inherited Create( nil );
FRevMsgEvent := nil;
// ๅๅงๅ Socket
if WSAStartup($101, TempWSAData)=1 then;
// showmessage('StartUp Error!');
// ๅๅปบ Socket
s := Socket( AF_INET, SOCK_DGRAM, 0 );
if (s = INVALID_SOCKET) then //Socketๅๅปบๅคฑ่ดฅ
begin
// showmessage(inttostr(WSAGetLastError())+' Socketๅๅปบๅคฑ่ดฅ');
CloseSocket(s);
exit;
end;
//ๅ้ๆน SockAddr ็ปๅฎ
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := INADDR_ANY;
addr.sin_port := htons(UdpPort_Broadcast);
if Bind(s, addr, sizeof(addr)) <> 0 then
begin
// showmessage('bind fail');
Exit;
end;
// ๅนฟๆญๅ้ UDP ไฟกๆฏ
optval:= 1;
if setsockopt(s,SOL_SOCKET,SO_BROADCAST, PAnsiChar(@optval),sizeof(optval)) = SOCKET_ERROR then
begin
// showmessage('ๆ ๆณ่ฟ่กUDPๅนฟๆญ');
Exit;
end;
//ๆฅๆถ็ซฏSockAddrIn่ฎพๅฎ
WSAAsyncSelect(s, Self.Handle , WM_SOCK, FD_READ);
FSockAddrIn.SIn_Family := AF_INET;
FSockAddrIn.SIn_Port := htons(UdpPort_Broadcast);
end;
destructor TfrmBroadcast.Destroy;
begin
CloseSocket(s);
inherited;
end;
procedure TfrmBroadcast.RevMsg(Msg: string);
begin
if Assigned( FRevMsgEvent ) then
FRevMsgEvent( Msg );
end;
end.
|
{@unit RLXLSFilter - Implementaรงรฃo do filtro para criaรงรฃo de planilhas do Excel. }
unit RLXLSFilter;
interface
uses
SysUtils, Classes, Contnrs, Math, Windows, Graphics, RLMetaVCL, Types,
RLMetaFile, RLConsts, RLTypes, RLUtils, RLFilters;
const
XLSMaxDefaultColors =16;
XLSMaxRowsInSheet =65536;
XLSMaxRowsInBlock =32;
XLSMaxCellsInRow =256;
XLSMaxColorsInPalette=56;
const
XLSDefaultColorPalette:array[0..XLSMaxColorsInPalette-1] of TColor=(
$000000,$FFFFFF,$0000FF,$00FF00,$FF0000,$00FFFF,$FF00FF,$FFFF00,$000080,
$008000,$800000,$008080,$800080,$808000,$C0C0C0,$808080,$FF9999,$663399,
$CCFFFF,$FFFFCC,$660066,$8080FF,$CC6600,$FFCCCC,$800000,$FF00FF,$00FFFF,
$FFFF00,$800080,$000080,$808000,$FF0000,$FFCC00,$FFFFCC,$CCFFCC,$99FFFF,
$FFCC99,$CC99FF,$FF99CC,$99CCFF,$FF6633,$CCCC33,$00CC99,$00CCFF,$0099FF,
$0066FF,$996666,$969696,$663300,$669933,$003300,$003333,$003399,$663399,
$993333,$333333);
XLSDefaultColors:array[0..XLSMaxDefaultColors-1] of integer=(
clWhite,clBlack,clSilver,clGray,clRed,clMaroon,clYellow,clOlive,
clLime,clGreen,clAqua,clTeal,clBlue,clNavy,clFuchsia,clPurple);
type
TRLXLSBiff8BOF=packed record
vers :word;
dt :word;
rupBuild:word;
rupYear :word;
bfh :cardinal;
sfo :cardinal;
end;
TRLXLSBiff8ColumnInfo=packed record
colFirst:word;
colLast :word;
coldx :word;
ixfe :word;
grbit :word;
res1 :byte;
end;
TRLXLSBiff8XF=packed record
ifnt :word;
ifmt :word;
Opt1 :word;
Opt2 :byte;
trot :byte;
Opt3 :word;
Borders1:word;
Borders2:word;
Borders3:cardinal;
Colors :word;
end;
TRLXLSBiff8Dimensions=packed record
rwMic :cardinal;
rwMac :cardinal;
colMic:word;
colMac:word;
Res1 :word;
end;
TRLXLSBiff8Row=packed record
rw :word;
colMic:word;
colMac:word;
miyRw :word;
irwMac:word;
Res1 :word;
grbit :word;
ixfe :word;
end;
TRLXLSBiff8InterfaceHeader=packed record
cv:word;
end;
TRLXLSBiff8MMS=packed record
caitm:byte;
cditm:byte;
end;
TRLXLSBiff8CodePage=packed record
cv:word;
end;
TRLXLSBiff8FNGroupCount=packed record
cFnGroup:word;
end;
TRLXLSBiff8WindowProtect=packed record
fLockWn:word;
end;
TRLXLSBiff8Protect=packed record
fLock:word;
end;
TRLXLSBiff8Password=packed record
wPassword:word;
end;
TRLXLSBiff8BACKUP=packed record
fBackupFile:word;
end;
TRLXLSBiff8HIDEOBJ=packed record
fHideObj:word;
end;
TRLXLSBiff81904=packed record
f1904:word;
end;
TRLXLSBiff8PRECISION=packed record
fFullPrec:word;
end;
TRLXLSBiff8BOOKBOOL=packed record
fNoSaveSupp:word;
end;
TRLXLSBiff8FONT=packed record
dyHeight:word;
grbit :word;
icv :word;
bls :word;
sss :word;
uls :byte;
bFamily :byte;
bCharSet:byte;
Res1 :byte;
cch :byte;
cchgrbit:byte;
end;
PRLXLSBiff8FONT=^TRLXLSBiff8FONT;
TRLXLSBiff8FORMAT=packed record
ifmt :word;
cch :word;
cchgrbit:byte;
end;
PRLXLSBiff8FORMAT=^TRLXLSBiff8FORMAT;
TRLXLSBiff8COUNTRY=packed record
iCountryDef :word;
iCountryWinIni:word;
end;
TRLXLSBiff8INDEX=packed record
Res1 :cardinal;
rwMic:cardinal;
rwMac:cardinal;
Res2 :cardinal;
end;
PRLXLSBiff8INDEX=^TRLXLSBiff8INDEX;
TRLXLSBiff8CALCMODE=packed record
fAutoRecalc:word;
end;
TRLXLSBiff8CALCCOUNT=packed record
cIter:word;
end;
TRLXLSBiff8REFMODE=packed record
fRefA1:word;
end;
TRLXLSBiff8ITERATION=packed record
fIter:word;
end;
TRLXLSBiff8DELTA=packed record
numDelta:Int64;
end;
TRLXLSBiff8SAVERECALC=packed record
fSaveRecalc:word;
end;
TRLXLSBiff8PRINTHEADERS=packed record
fPrintRwCol:word;
end;
TRLXLSBiff8PRINTGRIDLINES=packed record
fPrintGrid:word;
end;
TRLXLSBiff8GRIDSET=packed record
fGridSet:word;
end;
TRLXLSBiff8GUTS=packed record
dxRwGut :word;
dyColGut :word;
iLevelRwMac :word;
iLevelColMac:word;
end;
TRLXLSBiff8DEFAULTROWHEIGHT=packed record
grbit:word;
miyRw:word;
end;
TRLXLSBiff8WSBOOL=packed record
grbit:word;
end;
TRLXLSBiff8HEADER=packed record
cch :word;
cchgrbit:byte;
end;
PRLXLSBiff8HEADER=^TRLXLSBiff8HEADER;
TRLXLSBiff8FOOTER=packed record
cch :word;
cchgrbit:byte;
end;
PRLXLSBiff8FOOTER=^TRLXLSBiff8FOOTER;
TRLXLSBiff8HCENTER=packed record
fHCenter:word;
end;
TRLXLSBiff8VCENTER=packed record
fVCenter:word;
end;
TRLXLSBiff8DEFCOLWIDTH=packed record
cchdefColWidth:word;
end;
TRLXLSBiff8WRITEACCESS=packed record
stName:array[0..111] of byte;
end;
TRLXLSBiff8DOUBLESTREAMFILE=packed record
fDSF:word;
end;
TRLXLSBiff8PROT4REV=packed record
fRevLock:word;
end;
TRLXLSBiff8PROT4REVPASS=packed record
wRevPass:word;
end;
TRLXLSBiff8WINDOW1=packed record
xWn :word;
yWn :word;
dxWn :word;
dyWn :word;
grbit :word;
itabCur :word;
itabFirst:word;
ctabSel :word;
wTabRatio:word;
end;
TRLXLSBiff8REFRESHALL=packed record
fRefreshAll:word;
end;
TRLXLSBiff8USESELFS=packed record
fUsesElfs:word;
end;
TRLXLSBiff8PALETTE=packed record
ccv :word;
colors:array[0..XLSMaxColorsInPalette-1] of cardinal;
end;
TRLXLSBiff8BOUNDSHEET=packed record
lbPlyPos:cardinal;
grbit :word;
cch :byte;
cchgrbit:byte;
end;
PRLXLSBiff8BOUNDSHEET=^TRLXLSBiff8BOUNDSHEET;
TRLXLSBiff8WINDOW2=packed record
grbit :word;
rwTop :word;
colLeft :word;
icvHdr :cardinal;
wScaleSLV :word;
wScaleNormal:word;
Res1 :cardinal;
end;
TRLXLSBiff8SELECTION=packed record
pnn :byte;
rwAct :word;
colAct :word;
irefAct:word;
cref :word;
end;
PRLXLSBiff8SELECTION=^TRLXLSBiff8SELECTION;
TRLXLSBiff8DBCELL=packed record
dbRtrw:cardinal;
end;
TRLXLSBiff8DBCELLCellsOffsArray=array[0..XLSMaxCellsInRow-1] of word;
TRLXLSBiff8DBCELLfull=packed record
dbRtrw :cardinal;
cellsOffs:TRLXLSBiff8DBCELLCellsOffsArray;
end;
TRLXLSBiff8MERGErec=packed record
top :word;
bottom:word;
left :word;
right :word;
end;
PRLXLSBiff8MERGErec=^TRLXLSBiff8MERGErec;
TRLXLSBiff8MERGE=packed record
cnt:word;
end;
PRLXLSBiff8MERGE=^TRLXLSBiff8MERGE;
TRLXLSBiff8LABEL=packed record
rw :word;
col :word;
ixfe :word;
cch :word;
cchgrbit:byte;
end;
PRLXLSBiff8LABEL=^TRLXLSBiff8LABEL;
TRLXLSBiff8BLANK=packed record
rw :word;
col :word;
ixfe:word;
end;
TRLXLSBiff8MULBLANK=packed record
rw :word;
colFirst:word;
end;
PRLXLSBiff8MULBLANK=^TRLXLSBiff8MULBLANK;
TRLXLSBiff8SETUP=packed record
iPaperSize:word;
iScale :word;
iPageStart:word;
iFitWidth :word;
iFitHeight:word;
grbit :word;
iRes :word;
iVRes :word;
numHdr :double;
numFtr :double;
iCopies :word;
end;
TRLXLSBiff8SST=packed record
cstTotal :cardinal;
cstUnique:cardinal;
end;
PRLXLSBiff8SST=^TRLXLSBiff8SST;
TRLXLSBiff8EXTSST=packed record
Dsst:word;
end;
PRLXLSBiff8EXTSST=^TRLXLSBiff8EXTSST;
TRLXLSBiff8ISSTINF=packed record
ib :cardinal;
cb :word;
res1:word;
end;
PRLXLSBiff8ISSTINF=^TRLXLSBiff8ISSTINF;
TRLXLSBiff8LABELSST=packed record
rw :word;
col :word;
ixfe:word;
isst:cardinal;
end;
TRLXLSBiff8LEFTMARGIN=packed record
num:double;
end;
TRLXLSBiff8RIGHTMARGIN=packed record
num:double;
end;
TRLXLSBiff8TOPMARGIN=packed record
num:double;
end;
TRLXLSBiff8BOTTOMMARGIN=packed record
num:double;
end;
TRLXLSBiff8NUMBER=packed record
rw :word;
col :word;
ixfe:word;
num :double;
end;
type
TRLXLSWorkbook=class;
TRLXLSWorksheet=class;
TRLXLSRow=class;
TRLXLSCol=class;
TRLXLSFilter=class;
{@type TRLXLSCellDataType - Tipo de dado de uma cรฉlula ou faixa de cรฉlulas.
Pode ser:
ctNumber - A cรฉlula รฉ um valor e pode ser envolvido em cรกlculos;
ctString - O conteรบdo da cรฉlula รฉ um texto. :/}
TRLXLSCellDataType=(ctNumber,ctString);
TRLXLSLineStyleType=(lsNone,lsThin,lsMedium,lsDashed,lsDotted,lsThick,lsDouble,
lsHair,lsMediumDashed,lsDashDot,lsMediumDashDot,lsDashDotDot,
lsMediumDashDotDot,lsSlantedDashDot);
TRLXLSWeightType=(weHairline,weThin,weMedium,weThick);
TRLXLSBorderType=(bdDiagonalDown,bdDiagonalUp,bdEdgeBottom,bdEdgeLeft,bdEdgeRight,bdEdgeTop);
TRLXLSHorizontalAlignmentType=(haGeneral,haLeft,haCenter,haRight,haFill,haJustify,haCenterAcrossSelection);
TRLXLSVerticalAlignmentType=(vaTop,vaCenter,vaBottom,vaJustify);
TRLXLSOrderType=(odDownThenOver,odOverThenDown);
TRLXLSOrientationType=(orPortrait,orLandscape);
TRLXLSPrintErrorsType=(peBlank,peDash,peDisplayed,peNA);
TRLXLSFillPattern=(fpNone,fpAutomatic,fpChecker,fpCrissCross,fpDown,fpGray8,
fpGray16,fpGray25,fpGray50,fpGray75,fpGrid,fpHorizontal,
fpLightDown,fpLightHorizontal,fpLightUp,fpLightVertical,
fpSemiGray75,fpSolid,fpUp,fpVertical);
TRLXLSPaperSizeType=(
szPaperOther,
szPaperLetter, {8 1/2 x 11"}
szPaperLetterSmall, {8 1/2 x 11"}
szPaperTabloid, {11 x 17"}
szPaperLedger, {17 x 11"}
szPaperLegal, {8 1/2 x 14"}
szPaperStatement, {5 1/2 x 8 1/2"}
szPaperExecutive, {7 1/4 x 10 1/2"}
szPaperA3, {297 x 420 รฌรฌ}
szPaperA4, {210 x 297 รฌรฌ}
szPaperA4SmallSheet, {210 x 297 รฌรฌ}
szPaperA5, {148 x 210 รฌรฌ}
szPaperB4, {250 x 354 รฌรฌ}
szPaperB5, {182 x 257 รฌรฌ}
szPaperFolio, {8 1/2 x 13"}
szPaperQuartoSheet, {215 x 275 รฌรฌ}
szPaper10x14, {10 x 14"}
szPaper11x17, {11 x 17"}
szPaperNote, {8 1/2 x 11"}
szPaper9Envelope, {3 7/8 x 8 7/8"}
szPaper10Envelope, {4 1/8 x 9 1/2"}
szPaper11Envelope, {4 1/2 x 10 3/8"}
szPaper12Envelope, {4 3/4 x 11"}
szPaper14Envelope, {5 x 11 1/2"}
szPaperCSheet, {17 x 22"}
szPaperDSheet, {22 x 34"}
szPaperESheet, {34 x 44"}
szPaperDLEnvelope, {110 x 220 รฌรฌ}
szPaperC5Envelope, {162 x 229 รฌรฌ}
szPaperC3Envelope, {324 x 458 รฌรฌ}
szPaperC4Envelope, {229 x 324 รฌรฌ}
szPaperC6Envelope, {114 x 162 รฌรฌ}
szPaperC65Envelope, {114 x 229 รฌรฌ}
szPaperB4Envelope, {250 x 353 รฌรฌ}
szPaperB5Envelope, {176 x 250 รฌรฌ}
szPaperB6Envelope, {176 x 125 รฌรฌ}
szPaperItalyEnvelope, {110 x 230 รฌรฌ}
szPaperMonarchEnvelope, {3 7/8 x 7 1/2"}
szPaper63_4Envelope, {3 5/8 x 6 1/2"}
szPaperUSStdFanfold, {14 7/8 x 11"}
szPaperGermanStdFanfold, {8 1/2 x 12"}
szPaperGermanLegalFanfold, {8 1/2 x 13"}
szPaperB4_ISO, {250 x 353 รฌรฌ}
szPaperJapanesePostcard, {100 x 148 รฌรฌ}
szPaper9x11, {9 x 11"}
szPaper10x11, {10 x 11"}
szPaper15x11, {15 x 11"}
szPaperEnvelopeInvite, {220 x 220 รฌรฌ}
szPaperLetterExtra, {9 \ 275 x 12"}
szPaperLegalExtra, {9 \275 x 15"}
szPaperTabloidExtra, {11.69 x 18"}
szPaperA4Extra, {9.27 x 12.69"}
szPaperLetterTransverse, {8 \275 x 11"}
szPaperA4Transverse, {210 x 297 รฌรฌ}
szPaperLetterExtraTransverse, {9\275 x 12"}
szPaperSuperASuperAA4, {227 x 356 รฌรฌ}
szPaperSuperBSuperBA3, {305 x 487 รฌรฌ}
szPaperLetterPlus, {8.5 x 12.69"}
szPaperA4Plus, {210 x 330 รฌรฌ}
szPaperA5Transverse, {148 x 210 รฌรฌ}
szPaperB5_JIS_Transverse, {182 x 257 รฌรฌ}
szPaperA3Extra, {322 x 445 รฌรฌ}
szPaperA5Extra, {174 x 235 รฌรฌ}
szPaperB5_ISO_Extra, {201 x 276 รฌรฌ}
szPaperA2, {420 x 594 รฌรฌ}
szPaperA3Transverse, {297 x 420 รฌรฌ}
szPaperA3ExtraTransverse {322 x 445 รฌรฌ});
{ TRLXLSBorder }
TRLXLSBorder=class
private
fColor :TColor;
fLineStyle:TRLXLSLineStyleType;
fWeight :TRLXLSWeightType;
public
constructor Create;
destructor Destroy; override;
//
property Color :TColor read fColor write fColor;
property LineStyle:TRLXLSLineStyleType read fLineStyle write fLineStyle;
property Weight :TRLXLSWeightType read fWeight write fWeight;
end;
{ TRLXLSBorders }
TRLXLSBorders=class
private
fBorders:array[TRLXLSBorderType] of TRLXLSBorder;
//
function GetItem(i:TRLXLSBorderType):TRLXLSBorder;
public
constructor Create;
destructor Destroy; override;
//
property Borders[i:TRLXLSBorderType]:TRLXLSBorder read GetItem; default;
end;
{ TRLXLSRange }
{@class TRLXLSRange - Representa uma faixa de cรฉlulas de uma planilha.
Uma faixa (range) รฉ o meio para se acessar ou modificar o conteรบdo e as caracterรญsticas das cรฉlulas. }
TRLXLSRange=class
private
fWorksheet :TRLXLSWorksheet;
fCellBounds :TRect;
fBorders :TRLXLSBorders;
fFont :TFont;
fHorizontalAlignment:TRLXLSHorizontalAlignmentType;
fVerticalAlignment :TRLXLSVerticalAlignmentType;
fWrapText :boolean;
fRotation :byte;
fFormat :AnsiString;
fValue :AnsiString;
fDataType :TRLXLSCellDataType;
fFillPattern :TRLXLSFillPattern;
fForegroundColor :TColor;
fBackgroundColor :TColor;
fExportData :pointer;
//
function GetWorkbook:TRLXLSWorkbook;
procedure SetValue(const Value:AnsiString);
//
property Borders :TRLXLSBorders read fBorders;
property HorizontalAlignment:TRLXLSHorizontalAlignmentType read fHorizontalAlignment write fHorizontalAlignment;
property VerticalAlignment :TRLXLSVerticalAlignmentType read fVerticalAlignment write fVerticalAlignment;
property WrapText :boolean read fWrapText write fWrapText;
property Rotation :byte read fRotation write fRotation;
property Format :AnsiString read fFormat write fFormat;
property FillPattern :TRLXLSFillPattern read fFillPattern write fFillPattern;
property ForegroundColor :TColor read fForegroundColor write fForegroundColor;
property BackgroundColor :TColor read fBackgroundColor write fBackgroundColor;
property ExportData :pointer read fExportData write fExportData;
public
constructor Create(aWorksheet:TRLXLSWorksheet);
destructor Destroy; override;
//
{@prop Worksheet - Referรชncia ร aba da planilha a qual pertence esta faixa de cรฉlulas. @links TRLXLSWorksheet. :/}
property Worksheet :TRLXLSWorksheet read fWorksheet;
{@prop Workbook - Referรชncia ร planilha a qual pertence esta faixa de cรฉlulas. @links TRLXLSWorkbook. :/}
property Workbook :TRLXLSWorkbook read GetWorkbook;
{@prop Font - Configuraรงรฃo de fonte das cรฉlulas. :/}
property Font :TFont read fFont;
{@prop CellBounds - Faixa de cรฉlulas compreendidas pela faixa. :/}
property CellBounds:TRect read fCellBounds;
//
{@prop Value - Valor das cรฉlulas como string. :/}
property Value :AnsiString read fValue write SetValue;
{@prop DataType - Tipo de dado das celulas. @links TRLXLSCellDataType. :/}
property DataType :TRLXLSCellDataType read fDataType write fDataType;
end;
{/@class}
{ TRLXLSRow }
{@class TRLXLSRow - Representa uma linha de uma planilha. }
TRLXLSRow=class
private
fIndex :integer;
fHeight:integer;
//
public
constructor Create;
//
{@prop Height - Altura da linha em pixels. :/}
property Height:integer read fHeight write fHeight;
{@prop Index - รndice da linha na lista de linhas. :/}
property Index :integer read fIndex;
end;
{/@class}
{ TRLXLSCol }
{@class TRLXLSCol - Representa uma coluna de uma planilha. }
TRLXLSCol=class
private
fIndex:integer;
fWidth:integer;
public
constructor Create;
//
{@prop Width - Largura da coluna em pontos. :/}
property Width:integer read fWidth write fWidth;
{@prop Index - รndice da coluna na lista de colunas. :/}
property Index:integer read fIndex;
end;
{/@class}
{ TRLXLSPageSetup }
{@class TRLXLSPageSetup - Configuraรงรฃo da pรกgina de impressรฃo no Excel. }
TRLXLSPageSetup=class(TPersistent)
private
fBlackAndWhite :boolean;
fCenterFooter :AnsiString;
fCenterHeader :AnsiString;
fCenterHorizontally:boolean;
fCenterVertically :boolean;
fDraft :boolean;
fFirstPageNumber :integer;
fFitToPagesTall :boolean;
fFitToPagesWide :boolean;
fLeftFooter :AnsiString;
fLeftHeader :AnsiString;
fOrder :TRLXLSOrderType;
fOrientation :TRLXLSOrientationType;
fPaperSize :TRLXLSPaperSizeType;
fPrintGridLines :boolean;
fPrintHeaders :boolean;
fPrintNotes :boolean;
fRightFooter :AnsiString;
fRightHeader :AnsiString;
fLeftMargin :double;
fRightMargin :double;
fTopMargin :double;
fBottomMargin :double;
fFooterMargin :double;
fHeaderMargin :double;
fZoom :integer;
fCopies :integer;
//
property PaperSize :TRLXLSPaperSizeType read fPaperSize write fPaperSize;
property Orientation :TRLXLSOrientationType read fOrientation write fOrientation;
property Order :TRLXLSOrderType read fOrder write fOrder;
//
property PrintHeaders :boolean read fPrintHeaders write fPrintHeaders;
protected
procedure ReadBottomMargin(Reader: TReader);
procedure ReadLeftMargin(Reader: TReader);
procedure ReadRightMargin(Reader: TReader);
procedure ReadTopMargin(Reader: TReader);
procedure WriteBottomMargin(Writer: TWriter);
procedure WriteLeftMargin(Writer: TWriter);
procedure WriteRightMargin(Writer: TWriter);
procedure WriteTopMargin(Writer: TWriter);
procedure DefineProperties(Filer:TFiler); override;
public
constructor Create;
published
{@prop Copies - Quantidade inicial de cรณpias para imprimir. :/}
property Copies:integer read fCopies write fCopies default 1;
{@prop Zoom - Percentual de zoom inicial. :/}
property Zoom :integer read fZoom write fZoom default 100;
{@prop CenterHorizontally - Centralizar pรกgina horizontalmente. :/}
property CenterHorizontally:boolean read fCenterHorizontally write fCenterHorizontally default False;
{@prop CenterVertically - Centralizar pรกgina verticalmente. :/}
property CenterVertically :boolean read fCenterVertically write fCenterVertically default False;
{@prop BlackAndWhite - Imprimir em preto e branco. :/}
property BlackAndWhite:boolean read fBlackAndWhite write fBlackAndWhite default False;
{@prop Draft - Imprimir em modo de rascunho. :/}
property Draft :boolean read fDraft write fDraft default False;
{@prop PrintNotes - Imprimir notas de rodapรฉ. :/}
property PrintNotes :boolean read fPrintNotes write fPrintNotes default False;
{@prop PrintGridLines - Imprimir linhas de grade. :/}
property PrintGridLines:boolean read fPrintGridLines write fPrintGridLines default False;
{@prop LeftMargin - Margem de impressรฃo a esquerda em cm. :/}
property LeftMargin :double read fLeftMargin write fLeftMargin stored False;
{@prop TopMargin - Margem de impressรฃo superior em cm. :/}
property TopMargin :double read fTopMargin write fTopMargin stored False;
{@prop RightMargin - Margem de impressรฃo a direita em cm. :/}
property RightMargin :double read fRightMargin write fRightMargin stored False;
{@prop BottomMargin - Margem de impressรฃo inferior em cm. :/}
property BottomMargin:double read fBottomMargin write fBottomMargin stored False;
{@prop FirstPageNumber - Nรบmero para a primeira pรกgina. :/}
property FirstPageNumber:integer read fFirstPageNumber write fFirstPageNumber default 1;
{@prop FitToPagesTall - Encaixar a pรกgina de acordo com a altura. :/}
property FitToPagesTall :boolean read fFitToPagesTall write fFitToPagesTall default True;
{@prop FitToPagesWide - Encaixar a pรกgina de acordo com a largura. :/}
property FitToPagesWide :boolean read fFitToPagesWide write fFitToPagesWide default True;
{@prop LeftFooter - Texto para rodapรฉ ร esquerda. :/}
property LeftFooter :AnsiString read fLeftFooter write fLeftFooter;
{@prop LeftHeader - Texto para cabeรงalho ร esquerda. :/}
property LeftHeader :AnsiString read fLeftHeader write fLeftHeader;
{@prop CenterFooter - Texto para rodapรฉ centralizado. :/}
property CenterFooter:AnsiString read fCenterFooter write fCenterFooter;
{@prop CenterHeader - Texto para cabeรงalho centralizado. :/}
property CenterHeader:AnsiString read fCenterHeader write fCenterHeader;
{@prop RightFooter - Texto para rodapรฉ ร direita. :/}
property RightFooter :AnsiString read fRightFooter write fRightFooter;
{@prop RightHeader - Texto para cabeรงalho ร direita. :/}
property RightHeader :AnsiString read fRightHeader write fRightHeader;
{@prop HeaderMargin - Margem para o cabeรงalho em cm. :/}
property HeaderMargin:double read fHeaderMargin write fHeaderMargin;
{@prop FooterMargin - Margem para o rodapรฉ em cm. :/}
property FooterMargin:double read fFooterMargin write fFooterMargin;
end;
{/@class}
{ TRLXLSWorksheet }
{@class TRLXLSWorksheet - Representa uma aba de uma planilha Excel. }
TRLXLSWorksheet=class
private
fWorkbook :TRLXLSWorkbook;
fTitle :AnsiString;
fRanges :TObjectList;
fCols :TObjectList;
fRows :TObjectList;
fCellBounds:TRect;
//
function GetRangeCount:integer;
function GetRanges(i:integer):TRLXLSRange;
function GetColCount:integer;
function GetRowCount:integer;
function GetIndex:integer;
function GetCols(i:integer):TRLXLSCol;
function GetRows(i:integer):TRLXLSRow;
procedure SetTitle(const Value:AnsiString);
//
function NewRange(aLeft,aTop,aRight,aBottom:integer):TRLXLSRange;
function NewRow(aRowIndex:integer):TRLXLSRow;
function NewCol(aColIndex:integer):TRLXLSCol;
public
constructor Create(aWorkbook:TRLXLSWorkbook);
destructor Destroy; override;
//
{@method FindRange - Retorna a referรชncia para a faixa de cรฉlulas que compreende
os limites informados. Pode opcionalmente criar a faixa se nรฃo a encontrar.
@links TRLXLSRange. :/}
function FindRange(aLeft,aTop,aRight,aBottom:integer; aCanCreate:boolean):TRLXLSRange;
{@method FindRow - Retorna a referรชncia para a linha indicada pelo รญndice informado.
Pode opcionalmente criar a linha se nรฃo a encontrar.
@links TRLXLSRow. :/}
function FindRow(aRowIndex:integer; aCanCreate:boolean):TRLXLSRow;
{@method FindCol - Retorna a referรชncia para a coluna indicada pelo รญndice informado.
Pode opcionalmente criar a coluna se nรฃo a encontrar.
@links TRLXLSCol. :/}
function FindCol(aColIndex:integer; aCanCreate:boolean):TRLXLSCol;
//
{@prop Title - Tรญtulo da aba. :/}
property Title :AnsiString read fTitle write SetTitle;
{@prop Workbook - Referรชncia ร planilha. @links TRLXLSWorkbook. :/}
property Workbook :TRLXLSWorkbook read fWorkbook;
{@prop Index - รndice da aba dentre as abas da planilha. :/}
property Index :integer read GetIndex;
{@prop CellBounds - Tamanho da aba medida em celulas. :/}
property CellBounds:TRect read fCellBounds;
//
{@prop Ranges - Referรชncia a i-รฉsima faixa de cรฉlulas. @links TRLXLSRange. :/}
property Ranges[i:integer]:TRLXLSRange read GetRanges;
{@prop RangeCount - Retorna a quantidade de faixas de cรฉlulas. @links Ranges. :/}
property RangeCount:integer read GetRangeCount;
{@prop Rows - Referรชncia a i-รฉsima linha da aba da planilha. @links TRLXLSRow. :/}
property Rows[aRowIndex:integer]:TRLXLSRow read GetRows;
{@prop RowCount - Quantidade de linhas da aba. :/}
property RowCount:integer read GetRowCount;
{@prop Cols - Referรชncia a i-รฉsima coluna da aba da planilha. @links TRLXLSCol. :/}
property Cols[aColIndex:integer]:TRLXLSCol read GetCols;
{@prop ColCount - Quantidade de colunas da aba. :/}
property ColCount:integer read GetColCount;
end;
{/@class}
{ TRLXLSWorkbook }
{@class TRLXLSWorkbook - Representa uma planilha Excel. }
TRLXLSWorkbook=class
private
fFilter :TRLXLSFilter;
fUserName :AnsiString;
fSheets :TObjectList;
fPageSetup:TRLXLSPageSetup;
//
procedure SetUserName(const Value:AnsiString);
function GetSheetCount:integer;
function GetWorkSheet(i:integer):TRLXLSWorksheet;
protected
function NewSheetTitle:AnsiString;
public
constructor Create(aFilter:TRLXLSFilter);
destructor Destroy; override;
//
{@method Clear - Limpa a planilha excluindo todas os textos e abas. :/}
procedure Clear;
{@method NewSheet - Adiciona uma nova aba e retorna referรชncia a ela. @links TRLXLSWorksheet. :/}
function NewSheet:TRLXLSWorksheet;
//
{@prop UserName - Nome do usuรกrio dono da planilha. :/}
property UserName :AnsiString read fUserName write SetUserName;
{@prop SheetCount - Quantidade de abas da planilha. :/}
property SheetCount :integer read GetSheetCount;
{@prop Sheets - Retorna referรชncia a i-รฉsima aba da planilha. :/}
property Sheets[i:integer]:TRLXLSWorksheet read GetWorkSheet;
{@prop PageSetup - Configuraรงรฃo da impressรฃo das pรกginas. @links TRLXLSPageSetup:/}
property PageSetup:TRLXLSPageSetup read fPageSetup;
end;
{/@class}
{ TRLXLSFilter }
TRLXLSRangeRec=record
iXF :integer;
iSST :integer;
iFont :integer;
iFormat:integer;
end;
PXLSRangeRec =^TRLXLSRangeRec;
TRLXLSRangesRec=array[0..0] of TRLXLSRangeRec;
PXLSRangesRec=^TRLXLSRangesRec;
TRLXLSSheetRec=record
StreamBOFOffset :integer;
StreamBOFOffsetPosition:integer;
end;
TRLXLSSheetsRecs=array[0..0] of TRLXLSSheetRec;
PXLSSheetsRecs=^TRLXLSSheetsRecs;
{@type TRLXLSFilterOptions - Opรงรตes para a geraรงรฃo do arquivo planilha.
Pode ser um conjunto dos seguintes valores:
foFindNumberCells - Tenta encontrar valores no relatรณrio e formata as cรฉlulas correspondentes como numรฉricas. :}
TRLXLSFilterOption=(foFindValueCells);
TRLXLSFilterOptions=set of TRLXLSFilterOption;
{/@type}
{@class TRLXLSFilter - Filtro para criaรงรฃo de planilhas formato Excel XLS a partir de um relatรณrio.
Este filtro gera arquivos binรกrios compatรญveis com o formato XLS legรญveis pelo Microsoft Excel ou ExcelViewer.
Sรฃo exportados todos os textos presentes no relatรณrio com suas fontes e posiรงรตes mantidas.
Para cada pรกgina do relatรณrio serรก criada uma aba na planilha.
Nota: Grรกficos, linhas e cores ainda nรฃo sรฃo suportados.
@links TRLHTMLFilter, TRLRichFilter, TRLPDFFilter.
@ancestor TRLCustomSaveFilter.
@pub }
TRLXLSFilter=class(TRLCustomSaveFilter)
private
fBOFOffs :integer;
fWorkbook :TRLXLSWorkbook;
fUsedColors :TList;
fRangesRecs :PXLSRangesRec;
fColorPalette :array[0..XLSMaxColorsInPalette-1] of TColor;
fPaletteModified:Boolean;
fSheetsRecs :PXLSSheetsRecs;
fOptions :TRLXLSFilterOptions;
//
function GetColorPaletteIndex(aColor:TColor):integer;
function GetPageSetup: TRLXLSPageSetup;
procedure BuildFontList(aDest:TList);
procedure BuildFormatList(aDest:TStringList);
procedure BuildXFRecord(aRange:TRLXLSRange; var aXF:TRLXLSBiff8XF; aRec:PXLSRangeRec);
procedure BuildXFList(aDest:TList);
procedure WriteSheetToStream(aStream:TStream; aSheet:TRLXLSWorksheet);
procedure WriteRangeToStream(aStream:TStream; aRange:TRLXLSRange; aCurrentRow:integer; var aIndexInCellsOffsArray:integer; var aCellsOffs:TRLXLSBiff8DBCELLCellsOffsArray);
procedure WriteBIFF(aStream:TStream; aCode:word; aBuff:pointer; aSize:integer);
procedure WriteBIFFFont(aStream:TStream; aFont:TFont; aColorPaletteIndex:word);
procedure WriteBIFFFormat(aStream:TStream; const aFormatString:AnsiString; aFormatCode:word);
procedure WriteBIFFHexString(aStream:TStream; const aHexString:AnsiString);
procedure WriteStorageToStream(aStream:TStream);
procedure WriteBookToStream(aStream:TStream);
procedure SetPageSetup(const Value: TRLXLSPageSetup);
protected
// override methods
procedure InternalBeginDoc; override;
procedure InternalEndDoc; override;
procedure InternalNewPage; override;
procedure InternalDrawPage(aPage:TRLGraphicSurface); override;
public
constructor Create(aOwner:TComponent); override;
destructor Destroy; override;
//
{@method SaveToStream - Salva planilha em uma stream. :/}
procedure SaveToStream(aStream:TStream);
{@method SaveToFile - Salva planilha em um arquivo. O arquivo gerado pode ser lido a partir do Microsoft Excel ou ExcelViewer. :/}
procedure SaveToFile(const aFileName:AnsiString);
//
{@prop WorkBook - Referรชncia o objeto planilha interno do filtro.
@links TRLXLSWorkbook. :/}
property WorkBook:TRLXLSWorkbook read fWorkbook;
published
{@prop Options - Opรงรตes diversas de geraรงรฃo do arquivo planilha. @links TRLXLSFilterOptions. :/}
property Options:TRLXLSFilterOptions read fOptions write fOptions default [];
{@prop PageSetup - Configuraรงรฃo da impressรฃo das pรกginas. @links TRLXLSPageSetup:/}
property PageSetup:TRLXLSPageSetup read GetPageSetup write SetPageSetup;
{@prop FileName = ancestor /}
property FileName;
{@prop DisplayName = ancestor /}
property DisplayName;
{@prop ShowProgress - ancestor /}
property ShowProgress;
end;
{/@class}
{/@unit}
implementation
const
DefaultFontName ='Arial';
DefaultCellHeight=255;
DefaultCellLength=8;
const
B8_EOF =$000A;
B8_BOF =$0809;
B8_COLINFO =$007D;
B8_XF =$00E0;
B8_LABEL =$0204;
B8_BLANK =$0201;
B8_DIMENSIONS =$0200;
B8_ROW =$0208;
B8_INTERFACHDR =$00E1;
B8_INTERFACEND =$00E2;
B8_MMS =$00C1;
B8_CODEPAGE =$0042;
B8_TABID =$013D;
B8_FNGROUPCOUNT =$009C;
B8_WINDOWPROTECT =$0019;
B8_PROTECT =$0012;
B8_PASSWORD =$0013;
B8_WINDOW1 =$003D;
B8_BACKUP =$0040;
B8_HIDEOBJ =$008D;
B8_1904 =$0022;
B8_PRECISION =$000E;
B8_BOOKBOOL =$00DA;
B8_FONT =$0031; // MSDN=$0231
B8_FORMAT =$041E;
B8_COUNTRY =$008C;
B8_INDEX =$020B;
B8_CALCMODE =$000D;
B8_CALCCOUNT =$000C;
B8_REFMODE =$000F;
B8_ITERATION =$0011;
B8_SAVERECALC =$005F;
B8_DELTA =$0010;
B8_PRINTHEADERS =$002A;
B8_PRINTGRIDLINES =$002B;
B8_GRIDSET =$0082;
B8_GUTS =$0080;
B8_DEFAULTROWHEIGHT=$0225;
B8_WSBOOL =$0081;
B8_HEADER =$0014;
B8_FOOTER =$0015;
B8_HCENTER =$0083;
B8_VCENTER =$0084;
B8_DEFCOLWIDTH =$0055;
B8_WRITEACCESS =$005C;
B8_DOUBLESTREAMFILE=$0161;
B8_PROT4REV =$01AF;
B8_PROT4REVPASS =$01BC;
B8_REFRESHALL =$01B7;
B8_USESELFS =$0160;
B8_BOUNDSHEET =$0085;
B8_WINDOW2 =$023E;
B8_SELECTION =$001D;
B8_DBCELL =$00D7;
B8_MULBLANK =$00BE;
B8_MERGE =$00E5;
B8_PALETTE =$0092;
B8_CONTINUE =$003C;
B8_SETUP =$00A1;
B8_SST =$00FC;
B8_EXTSST =$00FF;
B8_LABELSST =$00FD;
B8_NUMBER =$0203;
B8_BOF_vers=$0600;
B8_BOF_dt_WorkbookGlobals =$0005;
B8_BOF_dt_VisualBasicModule=$0006;
B8_BOF_dt_Worksheet =$0010;
B8_BOF_dt_Chart =$0020;
B8_BOF_dt_MacroSheet =$0040;
B8_BOF_dt_WorkspaceFile =$0100;
B8_BOF_rupBuild_Excel97=$0DBB;
B8_BOF_rupYear_Excel07=$07CC;
B8_XF_Opt1_fLocked =$0001;
B8_XF_Opt1_fHidden =$0002;
B8_XF_Opt1_fStyleXF =$0004;
B8_XF_Opt1_f123Prefix=$0008;
B8_XF_Opt1_ixfParent =$FFF0;
B8_XF_Opt2_alcGeneral =$0000;
B8_XF_Opt2_alcLeft =$0001;
B8_XF_Opt2_alcCenter =$0002;
B8_XF_Opt2_alcRight =$0003;
B8_XF_Opt2_alcFill =$0004;
B8_XF_Opt2_alcJustify =$0005;
B8_XF_Opt2_alcCenterAcrossSelection=$0006;
B8_XF_Opt2_fWrap=$0008;
B8_XF_Opt2_alcVTop =$0000;
B8_XF_Opt2_alcVCenter =$0010;
B8_XF_Opt2_alcVBottom =$0020;
B8_XF_Opt2_alcVJustify=$0030;
B8_XF_Opt3_fMergeCell=$0020;
B8_XF_Opt3_fAtrNum =$0400;
B8_XF_Opt3_fAtrFnt =$0800;
B8_XF_Opt3_fAtrAlc =$1000;
B8_XF_Opt3_fAtrBdr =$2000;
B8_XF_Opt3_fAtrPat =$4000;
B8_XF_Opt3_fAtrProt =$8000;
B8_XF_Border_None =$0000;
B8_XF_Border_Thin =$0001;
B8_XF_Border_Medium =$0002;
B8_XF_Border_Dashed =$0003;
B8_XF_Border_Dotted =$0004;
B8_XF_Border_Thick =$0005;
B8_XF_Border_Double =$0006;
B8_XF_Border_Hair =$0007;
B8_XF_Border_MediumDashed =$0008;
B8_XF_Border_DashDot =$0009;
B8_XF_Border_MediumDashDot =$000A;
B8_XF_Border_DashDotDot =$000B;
B8_XF_Border_MediumDashDotDot=$000C;
B8_XF_Border_SlantedDashDot =$000D;
B8_INTERFACHDR_cv_IBMPC =$01B5;
B8_INTERFACHDR_cv_Macintosh=$8000;
B8_INTERFACHDR_cv_ANSI =$04E4;
B8_CODEPAGE_cv_IBMPC =$01B5;
B8_CODEPAGE_cv_Macintosh=$8000;
B8_CODEPAGE_cv_ANSI =$04E4;
B8_WINDOW1_grbit_fHidden =$0001;
B8_WINDOW1_grbit_fIconic =$0002;
B8_WINDOW1_grbit_fDspHScroll =$0008;
B8_WINDOW1_grbit_fDspVScroll =$0010;
B8_WINDOW1_grbit_fBotAdornment=$0020;
B8_FONT_grbit_fItalic =$0002;
B8_FONT_grbit_fStrikeout=$0008;
B8_FONT_grbit_fOutline =$0010;
B8_FONT_grbit_fShadow =$0020;
B8_DEFAULTROWHEIGHT_fUnsynced=$0001;
B8_DEFAULTROWHEIGHT_fDyZero =$0002;
B8_DEFAULTROWHEIGHT_fExAsc =$0004;
B8_DEFAULTROWHEIGHT_fExDsc =$0008;
B8_WSBOOL_fShowAutoBreaks=$0001;
B8_WSBOOL_fDialog =$0010;
B8_WSBOOL_fApplyStyles =$0020;
B8_WSBOOL_fRwSumsBelow =$0040;
B8_WSBOOL_fColSumsRight =$0080;
B8_WSBOOL_fFitToPage =$0100;
B8_WSBOOL_fDspGuts =$0200;
B8_WSBOOL_fAee =$0400;
B8_WSBOOL_fAfe =$8000;
B8_WINDOW1_fHidden =$0001;
B8_WINDOW1_fIconic =$0002;
B8_WINDOW1_fDspHScroll =$0008;
B8_WINDOW1_fDspVScroll =$0010;
B8_WINDOW1_fBotAdornment=$0020;
B8_WINDOW2_grbit_fDspFmla =$0001;
B8_WINDOW2_grbit_fDspGrid =$0002;
B8_WINDOW2_grbit_fDspRwCol =$0004;
B8_WINDOW2_grbit_fFrozen =$0008;
B8_WINDOW2_grbit_fDspZeros =$0010;
B8_WINDOW2_grbit_fDefaultHdr =$0020;
B8_WINDOW2_grbit_fArabic =$0040;
B8_WINDOW2_grbit_fDspGuts =$0080;
B8_WINDOW2_grbit_fFrozenNoSplit=$0100;
B8_WINDOW2_grbit_fSelected =$0200;
B8_WINDOW2_grbit_fPaged =$0400;
B8_WINDOW2_grbit_fSLV =$0800;
B8_ROW_grbit_fCollapsed =$0010;
B8_ROW_grbit_fDyZero =$0020;
B8_ROW_grbit_fUnsynced =$0040;
B8_ROW_grbit_fGhostDirty =$0080;
B8_ROW_grbit_mask_iOutLevel=$0007;
B8_COLINFO_fHidden =$0001;
B8_COLINFO_fCollapsed=$1000;
B8_SETUP_fLeftToRight=$0001;
B8_SETUP_fLandscape =$0002;
B8_SETUP_fNoPls =$0004;
B8_SETUP_fNoColor =$0008;
B8_SETUP_fDraft =$0010;
B8_SETUP_fNotes =$0020;
B8_SETUP_fNoOrient =$0040;
B8_SETUP_fUsePage =$0080;
B8_LEFTMARGIN =$0026;
B8_RIGHTMARGIN =$0027;
B8_TOPMARGIN =$0028;
B8_BOTTOMMARGIN=$0029;
{ UTILS }
function PointInRect(X, Y:integer; const R:TRect):boolean;
begin
Result:=((X>=R.Left) and (X<=R.Right)) and ((Y>=R.Top) and (Y<=R.Bottom));
end;
function RectInterceptsRect(const aRect1,aRect2:TRect):boolean;
begin
Result:=PointInRect(aRect1.Left,aRect1.Top,aRect2) or
PointInRect(aRect1.Right,aRect1.Top,aRect2) or
PointInRect(aRect1.Right,aRect1.Bottom,aRect2) or
PointInRect(aRect1.Left,aRect1.Bottom,aRect2) or
PointInRect(aRect2.Left,aRect2.Top,aRect1) or
PointInRect(aRect2.Right,aRect2.Top,aRect1) or
PointInRect(aRect2.Right,aRect2.Bottom,aRect1) or
PointInRect(aRect2.Left,aRect2.Bottom,aRect1) or
((aRect1.Left>aRect2.Left) and (aRect1.Right<aRect2.Right) and (aRect1.Top<aRect2.Top) and (aRect1.Bottom>aRect2.Bottom)) or
((aRect1.Left<aRect2.Left) and (aRect1.Right>aRect2.Right) and (aRect1.Top>aRect2.Top) and (aRect1.Bottom<aRect2.Bottom)) or
((aRect2.Left>aRect1.Left) and (aRect2.Right<aRect1.Right) and (aRect2.Top<aRect1.Top) and (aRect2.Bottom>aRect1.Bottom)) or
((aRect2.Left<aRect1.Left) and (aRect2.Right>aRect1.Right) and (aRect2.Top>aRect1.Top) and (aRect2.Bottom<aRect1.Bottom));
end;
function WideStringSize(const aStr:AnsiString):integer;
begin
Result:=Length(aStr)*SizeOf(WideChar);
end;
procedure StringToWideChar(const aSource:AnsiString; aDest:PWideChar; aDestSize:Integer);
var
w:WideString;
begin
w:=String(aSource);//bds2010
if w<>'' then
Move(w[1],aDest^,aDestSize)
else
aDest[0]:=#0;
end;
function HexToString(const aStr:AnsiString):AnsiString;
var
i,ls:integer;
b1 :AnsiString;
begin
Result:='';
ls:=length(aStr);
i:=1;
while i<=ls do
begin
while (i<=ls) and not (aStr[i] in ['0'..'9','a'..'f','A'..'F']) do
Inc(i);
if i>ls then
Break;
b1:='';
while (i<=ls) and (aStr[i] in ['0'..'9','a'..'f','A'..'F']) do
begin
b1:=b1+aStr[i];
Inc(i);
end;
if b1<>'' then
Result:=Result+AnsiChar(StrToInt(String('$'+b1)));//bds2010
if (b1='') or (i>ls) then
Break;
end;
end;
{ TRLXLSRow }
constructor TRLXLSRow.Create;
begin
fHeight:=DefaultCellHeight;
//
inherited Create;
end;
{ TRLXLSCol }
constructor TRLXLSCol.Create;
begin
fWidth:=DefaultCellLength*256;
//
inherited Create;
end;
{ TRLXLSBorder }
constructor TRLXLSBorder.Create;
begin
fLineStyle:=lsNone;
fWeight :=weHairline;
fColor :=clBlack;
//
inherited;
end;
destructor TRLXLSBorder.Destroy;
begin
inherited;
end;
{ TRLXLSBorders }
constructor TRLXLSBorders.Create;
var
i:TRLXLSBorderType;
begin
inherited;
//
for i:=Low(TRLXLSBorderType) to High(TRLXLSBorderType) do
fBorders[i]:=TRLXLSBorder.Create;
end;
destructor TRLXLSBorders.Destroy;
var
i:TRLXLSBorderType;
begin
for i:=Low(TRLXLSBorderType) to High(TRLXLSBorderType) do
fBorders[i].Free;
//
inherited;
end;
function TRLXLSBorders.GetItem;
begin
Result:=fBorders[i];
end;
{ TRLXLSRange }
constructor TRLXLSRange.Create(aWorksheet:TRLXLSWorksheet);
begin
fVerticalAlignment :=vaBottom;
fHorizontalAlignment:=haGeneral;
fWorksheet :=aWorksheet;
fBorders :=TRLXLSBorders.Create;
fFont :=TFont.Create;
fFont.Name :=DefaultFontName;
fFont.Size :=10;
fFont.Color :=clBlack;
fValue :='';
fDataType :=ctString;
//
inherited Create;
end;
destructor TRLXLSRange.Destroy;
begin
inherited;
//
fBorders.Free;
fFont.Free;
end;
function TRLXLSRange.GetWorkbook;
begin
if fWorksheet<>nil then
Result:=fWorksheet.Workbook
else
Result:=nil;
end;
procedure TRLXLSRange.SetValue(const Value:AnsiString);
function Fill(Texto: String; Tamanho: Integer): String;
var i : INTEGER;
begin
Result := '';
for i := 1 to tamanho do
Result := Result + Texto;
end;
function IIF(Expressao: Boolean; ValorTrue, ValorFalse: String): String;
begin
if Expressao then
Result := ValorTrue
else
Result := ValorFalse;
end;
function StrFmtQuantidade(const Decimais: Integer): String;
begin
//Retorna o DisplayFormat para a quantidade de decimais
Result := '#,##0' + IIF(Decimais> 0, '.', '') + Fill('0', Decimais);
Result := SysUtils.Format('%s;\-%s', [Result, Result]);
end;
var
foo,mil:AnsiString;
aux :double;
err :integer;
dcm :Integer;
begin
fValue:=AnsiString(StringReplace(String(Value),#13#10,#10,[rfReplaceAll])); //bds2010
//
dcm := Pos(FormatSettings.DecimalSeparator, String(fValue));//bds2010
if (foFindValueCells in Self.Workbook.fFilter.fOptions) and (dcm > 0) then //celso
begin
if dcm > 0 then //Se tiver decimais
dcm := Length(Copy(fValue, dcm+1, Length(fValue)-dcm));
//ShowMessage(fValue + #13#10 + IntToStr(dcm));
if (FormatSettings.DecimalSeparator = '.') then
mil:=','
else
mil:='.';
foo:=AnsiString(StringReplace(StringReplace(Trim(StringReplace(String(fValue),#10,' ',[rfReplaceAll])),String(mil),'',[rfReplaceAll]),FormatSettings.DecimalSeparator,'.',[rfReplaceAll]));//bds2010
Val(String(foo),aux,err);//bds2010
if (foo<>'') and (err=0) then
begin
fDataType:=ctNumber;
Str(aux,fValue);
fValue := AnsiString(StringReplace(String(fValue),'.',FormatSettings.DecimalSeparator,[rfReplaceAll]));//bds2010
if dcm > 0 then
fFormat := AnsiString(StrFmtQuantidade(dcm));//Celso aqui tambรฉm fui eu
end
else
fDataType:=ctString;
end;
end;
const
DefaultLeftMargin =2;
DefaultTopMargin =2.5;
DefaultRightMargin =2;
DefaultBottomMargin=2.5;
{ TRLXLSPageSetup }
constructor TRLXLSPageSetup.Create;
begin
fLeftMargin :=DefaultLeftMargin;
fTopMargin :=DefaultTopMargin;
fRightMargin :=DefaultRightMargin;
fBottomMargin :=DefaultBottomMargin;
fPaperSize :=szPaperA4;
fCopies :=1;
fZoom :=100;
fFitToPagesTall :=True;
fFitToPagesWide :=True;
fFirstPageNumber :=1;
fCenterHorizontally:=False;
fCenterVertically :=False;
fBlackAndWhite :=False;
fDraft :=False;
fPrintNotes :=False;
fPrintGridLines :=False;
fLeftFooter :='';
fLeftHeader :='';
fCenterFooter :='';
fCenterHeader :='';
fRightFooter :='';
fRightHeader :='';
fHeaderMargin :=0;
fFooterMargin :=0;
//
inherited;
end;
procedure TRLXLSPageSetup.DefineProperties(Filer: TFiler);
begin
Filer.DefineProperty('LeftMargin' ,ReadLeftMargin ,WriteLeftMargin ,fLeftMargin<>DefaultLeftMargin);
Filer.DefineProperty('TopMargin' ,ReadTopMargin ,WriteTopMargin ,fTopMargin<>DefaultTopMargin);
Filer.DefineProperty('RightMargin' ,ReadRightMargin ,WriteRightMargin ,fRightMargin<>DefaultRightMargin);
Filer.DefineProperty('BottomMargin',ReadBottomMargin,WriteBottomMargin,fBottomMargin<>DefaultBottomMargin);
end;
procedure TRLXLSPageSetup.ReadLeftMargin(Reader:TReader);
begin
fLeftMargin:=Reader.ReadFloat;
end;
procedure TRLXLSPageSetup.WriteLeftMargin(Writer:TWriter);
begin
Writer.WriteFloat(fLeftMargin);
end;
procedure TRLXLSPageSetup.ReadTopMargin(Reader:TReader);
begin
fTopMargin:=Reader.ReadFloat;
end;
procedure TRLXLSPageSetup.WriteTopMargin(Writer:TWriter);
begin
Writer.WriteFloat(fTopMargin);
end;
procedure TRLXLSPageSetup.ReadRightMargin(Reader:TReader);
begin
fRightMargin:=Reader.ReadFloat;
end;
procedure TRLXLSPageSetup.WriteRightMargin(Writer:TWriter);
begin
Writer.WriteFloat(fRightMargin);
end;
procedure TRLXLSPageSetup.ReadBottomMargin(Reader:TReader);
begin
fBottomMargin:=Reader.ReadFloat;
end;
procedure TRLXLSPageSetup.WriteBottomMargin(Writer:TWriter);
begin
Writer.WriteFloat(fBottomMargin);
end;
{ TRLXLSWorksheet }
constructor TRLXLSWorksheet.Create(aWorkbook:TRLXLSWorkbook);
begin
fWorkbook :=aWorkbook;
fCellBounds:=Rect(-1,-1,-1,-1);
fTitle :='';
fRanges :=nil;
fCols :=nil;
fRows :=nil;
//
fRanges :=TObjectList.Create;
fCols :=TObjectList.Create;
fRows :=TObjectList.Create;
//
inherited Create;
end;
destructor TRLXLSWorksheet.Destroy;
begin
if Assigned(fRanges) then
fRanges.Free;
if Assigned(fCols) then
fCols.Free;
if Assigned(fRows) then
fRows.Free;
//
inherited;
end;
function TRLXLSWorksheet.GetIndex;
begin
Result:=fWorkBook.fSheets.IndexOf(Self);
end;
procedure TRLXLSWorksheet.SetTitle(const Value:AnsiString);
begin
fTitle:=AnsiString(Trim(String(Copy(Value,1,31))));//bds2010
end;
function TRLXLSWorksheet.GetCols(i:integer):TRLXLSCol;
begin
Result:=TRLXLSCol(fCols[i]);
end;
function TRLXLSWorksheet.GetRows(i:integer):TRLXLSRow;
begin
Result:=TRLXLSRow(fRows[i]);
end;
function TRLXLSWorksheet.GetColCount:integer;
begin
Result:=fCols.Count;
end;
function TRLXLSWorksheet.GetRowCount:integer;
begin
Result:=fRows.Count;
end;
function TRLXLSWorksheet.GetRangeCount:integer;
begin
Result:=fRanges.Count;
end;
function TRLXLSWorksheet.GetRanges(i:integer):TRLXLSRange;
begin
Result:=TRLXLSRange(fRanges[i]);
end;
function TRLXLSWorksheet.FindRow(aRowIndex:integer; aCanCreate:boolean):TRLXLSRow;
var
i:integer;
begin
i:=0;
while (i<RowCount) and (Rows[i].Index<>aRowIndex) do
Inc(i);
if i<RowCount then
Result:=Rows[i]
else if aCanCreate then
Result:=NewRow(aRowIndex)
else
Result:=nil;
end;
function TRLXLSWorksheet.NewRow(aRowIndex:integer):TRLXLSRow;
begin
Result:=TRLXLSRow.Create;
Result.fIndex:=aRowIndex;
fRows.Add(Result);
// expande as dimensรตes da sheet
if (fCellBounds.Top=-1) or (aRowIndex<fCellBounds.Top) then
fCellBounds.Top:=aRowIndex;
if (fCellBounds.Bottom=-1) or (aRowIndex>fCellBounds.Bottom) then
fCellBounds.Bottom:=aRowIndex;
end;
function TRLXLSWorksheet.FindCol(aColIndex:integer; aCanCreate:boolean):TRLXLSCol;
var
i:integer;
begin
i:=0;
while (i<ColCount) and (Cols[i].Index<>aColIndex) do
Inc(i);
if i<ColCount then
Result:=Cols[i]
else if aCanCreate then
Result:=NewCol(aColIndex)
else
Result:=nil;
end;
function TRLXLSWorksheet.NewCol(aColIndex:integer):TRLXLSCol;
begin
Result:=TRLXLSCol.Create;
Result.fIndex:=aColIndex;
fCols.Add(Result);
// expande as dimensรตes da sheet
if (fCellBounds.Left=-1) or (aColIndex<fCellBounds.Left) then
fCellBounds.Left:=aColIndex;
if (fCellBounds.Right=-1) or (aColIndex>fCellBounds.Right) then
fCellBounds.Right:=aColIndex;
end;
function SameBounds(aRange:TRLXLSRange; aLeft,aTop,aRight,aBottom:integer):boolean;
begin
with aRange.CellBounds do
Result:=(Left=aLeft) and (Top=aTop) and (Right=aRight) and (Bottom=aBottom);
end;
function TRLXLSWorksheet.FindRange(aLeft,aTop,aRight,aBottom:integer; aCanCreate:boolean):TRLXLSRange;
var
i:integer;
begin
i:=0;
while (i<RangeCount) and not SameBounds(Ranges[i],aLeft,aTop,aRight,aBottom) do
Inc(i);
if i<RangeCount then
Result:=Ranges[i]
else if aCanCreate then
Result:=NewRange(aLeft,aTop,aRight,aBottom)
else
Result:=nil;
end;
function TRLXLSWorksheet.NewRange(aLeft,aTop,aRight,aBottom:integer):TRLXLSRange;
var
rangebounds:TRect;
i :integer;
begin
// exclui as ranges que se encontram naquela regiรฃo
rangebounds:=Rect(aLeft,aTop,aRight,aBottom);
for i:=RangeCount-1 downto 0 do
if RectInterceptsRect(rangebounds,Ranges[i].CellBounds) then
fRanges.Delete(i);
//
Result:=TRLXLSRange.Create(Self);
Result.fCellBounds:=rangebounds;
fRanges.Add(Result);
// expande as dimensรตes da sheet
if (fCellBounds.Left=-1) or (rangebounds.Left<fCellBounds.Left) then
fCellBounds.Left:=rangebounds.Left;
if (fCellBounds.Top=-1) or (rangebounds.Top<fCellBounds.Top) then
fCellBounds.Top:=rangebounds.Top;
if (fCellBounds.Right=-1) or (rangebounds.Right>fCellBounds.Right) then
fCellBounds.Right:=rangebounds.Right;
if (fCellBounds.Bottom=-1) or (rangebounds.Bottom>fCellBounds.Bottom) then
fCellBounds.Bottom:=rangebounds.Bottom;
end;
{ TRLXLSWorkbook }
constructor TRLXLSWorkbook.Create(aFilter:TRLXLSFilter);
begin
fFilter :=aFilter;
fUserName :=CS_ProductTitleStr;
fSheets :=nil;
fPageSetup:=nil;
//
fSheets :=TObjectList.Create;
fPageSetup:=TRLXLSPageSetup.Create;
//
inherited Create;
end;
destructor TRLXLSWorkbook.Destroy;
begin
inherited;
//
if Assigned(fSheets) then
fSheets.Free;
if Assigned(fPageSetup) then
fPageSetup.Free;
end;
function TRLXLSWorkbook.NewSheetTitle:AnsiString;
var
titleno,i:integer;
begin
titleno:=fSheets.Count;
repeat
Inc(titleno);
Result:=AnsiString(LS_PageStr+IntToStr(titleno));//bds2010
i:=0;
while (i<SheetCount) and not AnsiSameText(String(Sheets[i].Title), String(Result)) do//bds2010
Inc(i);
until not (i<SheetCount);
end;
procedure TRLXLSWorkbook.SetUserName(const Value:AnsiString);
const
MaxUserName=66;
begin
fUserName:=AnsiString(Trim(String(Copy(Value,1,MaxUserName))));//bds2010
end;
function TRLXLSWorkbook.GetSheetCount:integer;
begin
Result:=fSheets.Count;
end;
function TRLXLSWorkbook.GetWorkSheet(i:integer):TRLXLSWorksheet;
begin
Result:=TRLXLSWorksheet(fSheets[i]);
end;
function TRLXLSWorkbook.NewSheet;
begin
Result:=TRLXLSWorksheet.Create(Self);
Result.Title:=NewSheetTitle;
fSheets.Add(Result);
end;
procedure TRLXLSWorkbook.Clear;
begin
fSheets.Clear;
end;
procedure wr(s:tstream; const c; l:integer);
begin
if (s.Position>$46c-100) and (s.Position<$46c+100) then
l:=l;
s.write(c,l);
end;
{ TRLXLSFilter }
constructor TRLXLSFilter.Create(aOwner:TComponent);
begin
fUsedColors:=nil;
fWorkbook :=nil;
fOptions :=[];
//
fUsedColors:=TList.Create;
fWorkbook :=TRLXLSWorkbook.Create(Self);
//
inherited;
//
DefaultExt :='.xls';
DisplayName:=LS_XLSFormatStr;
end;
destructor TRLXLSFilter.Destroy;
begin
inherited;
//
if Assigned(fUsedColors) then
fUsedColors.Free;
if Assigned(fWorkbook) then
fWorkbook.Free;
end;
const
MaxBiffRecordSize=8228;
procedure TRLXLSFilter.WriteBIFF(aStream:TStream; aCode:word; aBuff:pointer; aSize:integer);
var
sz:word;
begin
repeat
wr(aStream,aCode,2);
sz:=Min(aSize,MaxBiffRecordSize-4);
wr(aStream,sz,2);
if sz>0 then
begin
wr(aStream,aBuff^,sz);
aBuff:=Pointer(Integer(aBuff)+sz);
aSize:=aSize-sz;
aCode:=B8_CONTINUE;
end;
until aSize=0;
end;
procedure TRLXLSFilter.WriteBIFFFont(aStream:TStream; aFont:TFont; aColorPaletteIndex:word);
var
room:integer;
font:PRLXLSBiff8FONT;
lf :TLogFont;
begin
room:=WideStringSize(AnsiString(aFont.Name));//bds2010
font:=AllocMem(SizeOf(TRLXLSBiff8FONT)+room);
try
GetObject(aFont.Handle,SizeOf(TLogFont),@lf);
StringToWideChar(AnsiString(aFont.Name),PWideChar(Integer(font)+SizeOf(TRLXLSBiff8FONT)),room);//bds2010
font.dyHeight:=aFont.Size*20;
if fsItalic in aFont.Style then
font.grbit:=font.grbit or B8_FONT_grbit_fItalic;
if fsStrikeout in aFont.Style then
font.grbit:=font.grbit or B8_FONT_grbit_fStrikeout;
font.icv:=aColorPaletteIndex;
if fsBold in aFont.Style then
font.bls:=$3E8 // ref MSDN
else
font.bls:=$64; // ref MSDN
if fsUnderline in aFont.Style then
font.uls:=1; // ref MSDN
font.bFamily :=lf.lfPitchAndFamily;
font.bCharSet:=lf.lfCharSet;
font.cch :=Length(aFont.Name);
font.cchgrbit:=$01;
WriteBIFF(aStream,B8_FONT,font,SizeOf(TRLXLSBiff8FONT)+room);
finally
FreeMem(font);
end;
end;
procedure TRLXLSFilter.WriteBIFFFormat(aStream:TStream; const aFormatString:AnsiString; aFormatCode:word);
var
format:PRLXLSBiff8FORMAT;
room :integer;
begin
room :=WideStringSize(aFormatString);
format:=AllocMem(SizeOf(TRLXLSBiff8FORMAT)+room);
try
StringToWideChar(aFormatString,PWideChar(Integer(format)+SizeOf(TRLXLSBiff8FORMAT)),room);
format.ifmt :=aFormatCode;
format.cch :=Length(aFormatString);
format.cchgrbit:=$01;
WriteBIFF(aStream,B8_FORMAT,format,SizeOf(TRLXLSBiff8FORMAT)+room);
finally
FreeMem(format);
end;
end;
procedure TRLXLSFilter.WriteBIFFHexString(aStream:TStream; const aHexString:AnsiString);
var
aux:AnsiString;
begin
aux:=HexToString(aHexString);
wr(aStream,aux[1],Length(aux));
end;
function SameFont(aFont1,aFont2:TFont):boolean;
begin
Result:=(aFont1.Charset=aFont2.Charset) and
(aFont1.Color=aFont2.Color) and
(aFont1.Height=aFont2.Height) and
(aFont1.Name=aFont2.Name) and
(aFont1.Pitch=aFont2.Pitch) and
(aFont1.Size=aFont2.Size) and
(aFont1.Style=aFont2.Style);
end;
procedure TRLXLSFilter.BuildFontList(aDest:TList);
var
range:TRLXLSRange;
sheet:TRLXLSWorksheet;
font :TFont;
i,j :integer;
k,n :integer;
begin
n:=0;
for i:=0 to fWorkbook.SheetCount-1 do
begin
sheet:=fWorkbook.Sheets[i];
for j:=0 to sheet.RangeCount-1 do
begin
range:=sheet.Ranges[j];
range.ExportData:=@fRangesRecs[n];
k:=0;
while (k<aDest.Count) and not SameFont(TFont(aDest[k]),range.Font) do
Inc(k);
if k<aDest.Count then
else
begin
font:=TFont.Create;
font.Assign(range.Font);
aDest.Add(font);
end;
fRangesRecs[n].iFont:=k+1;
Inc(n);
end;
end;
end;
procedure TRLXLSFilter.BuildFormatList(aDest:TStringList);
var
sheet:TRLXLSWorksheet;
range:TRLXLSRange;
i,j :integer;
k,n :integer;
m :integer;
begin
n:=aDest.Count;
m:=0;
for i:=0 to fWorkbook.SheetCount-1 do
begin
sheet:=fWorkbook.Sheets[i];
for j:=0 to sheet.RangeCount-1 do
begin
range:=sheet.Ranges[j];
if range.Format='' then
fRangesRecs[m].iFormat:=0
else
begin
k:=aDest.IndexOf(String(range.Format));//bds2010
if k=-1 then
k:=aDest.AddObject(String(range.Format),Pointer(aDest.Count-n+$32));//bds2010
fRangesRecs[m].iFormat:=Integer(aDest.Objects[k]);
end;
Inc(m);
end;
end;
end;
procedure TRLXLSFilter.BuildXFRecord(aRange:TRLXLSRange; var aXF:TRLXLSBiff8XF; aRec:PXLSRangeRec);
const
FillPatterns:array[TRLXLSFillPattern] of integer=(0,-4105,9,16,-4121,18,17,-4124,-4125,-4126,15,-4128,13,11,14,12,10,1,-4162,-4166);
HorizontalAlignments:array[TRLXLSHorizontalAlignmentType] of integer=
(B8_XF_Opt2_alcGeneral,
B8_XF_Opt2_alcLeft,
B8_XF_Opt2_alcCenter,
B8_XF_Opt2_alcRight,
B8_XF_Opt2_alcFill,
B8_XF_Opt2_alcJustify,
B8_XF_Opt2_alcCenterAcrossSelection);
VerticalAlignments:array[TRLXLSVerticalAlignmentType] of integer=
(B8_XF_Opt2_alcVTop,
B8_XF_Opt2_alcVCenter,
B8_XF_Opt2_alcVBottom,
B8_XF_Opt2_alcVJustify);
WrapTexts:array[Boolean] of integer=(0,B8_XF_Opt2_fWrap);
BorderLineStyles:array[TRLXLSLineStyleType] of word=
(B8_XF_Border_None,
B8_XF_Border_Thin,
B8_XF_Border_Medium,
B8_XF_Border_Dashed,
B8_XF_Border_Dotted,
B8_XF_Border_Thick,
B8_XF_Border_Double,
B8_XF_Border_Hair,
B8_XF_Border_MediumDashed,
B8_XF_Border_DashDot,
B8_XF_Border_MediumDashDot,
B8_XF_Border_DashDotDot,
B8_XF_Border_MediumDashDotDot,
B8_XF_Border_SlantedDashDot);
function GetBorderColorIndex(b:TRLXLSBorderType):integer;
begin
if aRange.Borders[b].LineStyle=lsNone then
Result:=0
else
Result:=GetColorPaletteIndex(aRange.Borders[b].Color)+8; // ???+8
end;
var
DiagBorderLineStyle :TRLXLSLineStyleType;
DiagBorderColorIndex:integer;
begin
FillChar(aXF,SizeOf(aXF),0);
aXF.ifnt:=aRec.iFont;
aXF.ifmt:=PXLSRangeRec(aRange.ExportData).iFormat;
aXF.Opt1:=$0001;
aXF.Opt2:=HorizontalAlignments[aRange.HorizontalAlignment] or
WrapTexts[aRange.WrapText] or
VerticalAlignments[aRange.VerticalAlignment];
aXF.trot:=aRange.Rotation;
aXF.Opt3:=B8_XF_Opt3_fAtrNum or
B8_XF_Opt3_fAtrFnt or
B8_XF_Opt3_fAtrAlc or
B8_XF_Opt3_fAtrBdr or
B8_XF_Opt3_fAtrPat;
if (aRange.CellBounds.Left<>aRange.CellBounds.Right) or (aRange.CellBounds.Top<>aRange.CellBounds.Bottom) then
aXF.Opt3:=aXF.Opt3 or B8_XF_Opt3_fMergeCell;
//
aXF.Borders1:=(BorderLineStyles[aRange.Borders[bdEdgeLeft].LineStyle]) or
(BorderLineStyles[aRange.Borders[bdEdgeRight].LineStyle] shl 4) or
(BorderLineStyles[aRange.Borders[bdEdgeTop].LineStyle] shl 8) or
(BorderLineStyles[aRange.Borders[bdEdgeBottom].LineStyle] shl 12);
DiagBorderLineStyle :=lsNone;
DiagBorderColorIndex:=0;
aXF.Borders2 :=0;
if aRange.Borders[bdDiagonalDown].LineStyle<>lsNone then
begin
aXF.Borders2 :=aXF.Borders2 or $4000;
DiagBorderLineStyle :=aRange.Borders[bdDiagonalDown].LineStyle;
DiagBorderColorIndex:=GetColorPaletteIndex(aRange.Borders[bdDiagonalDown].Color)+8;
end;
if aRange.Borders[bdDiagonalUp].LineStyle<>lsNone then
begin
aXF.Borders2 :=aXF.Borders2 or $8000;
DiagBorderLineStyle :=aRange.Borders[bdDiagonalUp].LineStyle;
DiagBorderColorIndex:=GetColorPaletteIndex(aRange.Borders[bdDiagonalUp].Color)+8;
end;
aXF.Borders2:=aXF.Borders2 or (GetBorderColorIndex(bdEdgeLeft)) or (GetBorderColorIndex(bdEdgeRight) shl 7);
aXF.Borders3:=(GetBorderColorIndex(bdEdgeTop)) or (GetBorderColorIndex(bdEdgeBottom) shl 7) or
(DiagBorderColorIndex shl 14) or (BorderLineStyles[DiagBorderLineStyle] shl 21) or
(FillPatterns[aRange.FillPattern] shl 26);
aXF.Colors :=GetColorPaletteIndex(aRange.ForegroundColor) or (GetColorPaletteIndex(aRange.BackgroundColor) shl 7);
end;
procedure TRLXLSFilter.BuildXFList(aDest:TList);
var
sheet:TRLXLSWorksheet;
range:TRLXLSRange;
xf :TRLXLSBiff8XF;
i,j :integer;
k,n :integer;
p :pointer;
begin
n:=0;
for i:=0 to fWorkbook.SheetCount-1 do
begin
sheet:=fWorkbook.Sheets[i];
for j:=0 to sheet.RangeCount-1 do
begin
range:=sheet.Ranges[j];
BuildXFRecord(range,xf,@fRangesRecs[n]);
k:=0;
while (k<aDest.Count) and not CompareMem(aDest[k],@xf,SizeOf(TRLXLSBiff8XF)) do
Inc(k);
if k<aDest.Count then
else
begin
GetMem(p,SizeOf(TRLXLSBiff8XF));
Move(xf,p^,SizeOf(TRLXLSBiff8XF));
k:=aDest.Add(p);
end;
fRangesRecs[n].iXF:=k+15;
Inc(n);
end;
end;
end;
function TRLXLSFilter.GetColorPaletteIndex(aColor:TColor):integer;
function DefaultColorIndex(c:TColor):integer;
begin
Result:=0;
while (Result<XLSMaxDefaultColors) and (XLSDefaultColors[Result]<>c) do
Inc(Result);
if Result>=XLSMaxDefaultColors then
Result:=-1;
end;
begin
if (aColor and $80000000)<>0 then
aColor:=ColorToRGB(aColor and $00FFFFFF);
if fUsedColors.IndexOf(Pointer(aColor))=-1 then
fUsedColors.Add(Pointer(aColor));
Result:=0;
while (Result<XLSMaxColorsInPalette) and (fColorPalette[Result]<>aColor) do
Inc(Result);
if Result<XLSMaxColorsInPalette then
Exit;
Result:=0;
while Result<XLSMaxColorsInPalette do
begin
if (DefaultColorIndex(fColorPalette[Result])=-1) and (fUsedColors.IndexOf(Pointer(fColorPalette[Result]))=-1) then
begin
fColorPalette[Result]:=aColor;
fPaletteModified :=True;
Exit;
end;
Inc(Result);
end;
Result:=1;
end;
function RangeSortCallback(Item1,Item2:Pointer):integer;
begin
Result:=TRLXLSRange(Item1).CellBounds.Left-TRLXLSRange(Item2).CellBounds.Left;
end;
procedure TRLXLSFilter.WriteRangeToStream(aStream:TStream; aRange:TRLXLSRange;
aCurrentRow:integer; var aIndexInCellsOffsArray:integer;
var aCellsOffs:TRLXLSBiff8DBCELLCellsOffsArray);
var
blank :TRLXLSBiff8BLANK;
i,left :integer;
number :TRLXLSBiff8NUMBER;
mulblank:PRLXLSBiff8MULBLANK;
labelsst:TRLXLSBiff8LABELSST;
procedure AddToCellsOffsArray;
begin
if aIndexInCellsOffsArray=0 then
aCellsOffs[aIndexInCellsOffsArray]:=aStream.Position
else
aCellsOffs[aIndexInCellsOffsArray]:=aStream.Position-aCellsOffs[aIndexInCellsOffsArray-1];
Inc(aIndexInCellsOffsArray);
end;
begin
left:=aRange.CellBounds.Left;
if aCurrentRow=aRange.CellBounds.Top then
begin
AddToCellsOffsArray;
case aRange.DataType of
ctNumber:
begin
number.rw :=aCurrentRow;
number.col :=aRange.CellBounds.Left;
number.ixfe:=PXLSRangeRec(aRange.ExportData).iXF;
number.num :=StrToFloat(String(aRange.Value));//bds2010
WriteBIFF(aStream,B8_NUMBER,@number,SizeOf(TRLXLSBiff8NUMBER));
end;
ctString:
begin
labelsst.rw :=aCurrentRow;
labelsst.col :=aRange.CellBounds.Left;
labelsst.ixfe:=PXLSRangeRec(aRange.ExportData).iXF;
labelsst.isst:=PXLSRangeRec(aRange.ExportData).iSST;
WriteBIFF(aStream,B8_LABELSST,@labelsst,SizeOf(labelsst));
end;
end;
Inc(left);
end;
//
if left<aRange.CellBounds.Right then
begin
AddToCellsOffsArray;
mulblank:=AllocMem(SizeOf(TRLXLSBiff8MULBLANK)+(aRange.CellBounds.Right-left+1)*2+2);
try
mulblank.rw :=aCurrentRow;
mulblank.colFirst:=left;
for i:=0 to aRange.CellBounds.Right-left do
PWordArray(PAnsiChar(mulblank)+SizeOf(TRLXLSBiff8MULBLANK))^[i]:=PXLSRangeRec(aRange.ExportData).iXF;
PWord(PAnsiChar(mulblank)+SizeOf(TRLXLSBiff8MULBLANK)+(aRange.CellBounds.Right-left+1)*2)^:=aRange.CellBounds.Right;
WriteBIFF(aStream,B8_MULBLANK,mulblank,SizeOf(TRLXLSBiff8MULBLANK)+(aRange.CellBounds.Right-left+1)*2+2);
finally
FreeMem(mulblank);
end;
end
else if left=aRange.CellBounds.Right then
begin
AddToCellsOffsArray;
blank.rw :=aCurrentRow;
blank.col :=left;
blank.ixfe:=PXLSRangeRec(aRange.ExportData).iXF;
WriteBIFF(aStream,B8_BLANK,@blank,SizeOf(blank));
end;
end;
procedure TRLXLSFilter.WriteSheetToStream(aStream:TStream; aSheet:TRLXLSWorksheet);
type
TCardinalArray=array[0..0] of cardinal;
PCardinalArray=^TCardinalArray;
var
bof :TRLXLSBiff8BOF;
calcmode :TRLXLSBiff8CALCMODE;
calccount :TRLXLSBiff8CALCCOUNT;
refmode :TRLXLSBiff8REFMODE;
iteration :TRLXLSBiff8ITERATION;
saverecalc :TRLXLSBiff8SAVERECALC;
printheaders :TRLXLSBiff8PRINTHEADERS;
printgridlines :TRLXLSBiff8PRINTGRIDLINES;
gridset :TRLXLSBiff8GRIDSET;
guts :TRLXLSBiff8GUTS;
defaultrowheight :TRLXLSBiff8DEFAULTROWHEIGHT;
wsbool :TRLXLSBiff8WSBOOL;
hcenter :TRLXLSBiff8HCENTER;
vcenter :TRLXLSBiff8VCENTER;
defcolwidth :TRLXLSBiff8DEFCOLWIDTH;
dimensions :TRLXLSBiff8Dimensions;
window2 :TRLXLSBiff8WINDOW2;
selection :PRLXLSBiff8SELECTION;
header :PRLXLSBiff8HEADER;
footer :PRLXLSBiff8FOOTER;
INDEXOffs :integer;
BlocksInSheet :integer;
IndexInDBCELLsOffs :integer;
dbcell :TRLXLSBiff8DBCELLfull;
IndexInCellsOffsArray:integer;
ms :TMemoryStream;
FirstRowOffs :integer;
SecondRowOffs :integer;
merge :PRLXLSBiff8MERGE;
colinfo :TRLXLSBiff8ColumnInfo;
leftmargin :TRLXLSBiff8LEFTMARGIN;
rightmargin :TRLXLSBiff8RIGHTMARGIN;
topmargin :TRLXLSBiff8TOPMARGIN;
bottommargin :TRLXLSBiff8BOTTOMMARGIN;
setup :TRLXLSBiff8SETUP;
index :PRLXLSBiff8INDEX;
room :integer;
l :TList;
range :TRLXLSRange;
rw :TRLXLSRow;
row :TRLXLSBiff8Row;
bc,i,j :integer;
aux :AnsiString;
begin
FillChar(bof,SizeOf(bof),0);
bof.vers :=B8_BOF_vers;
bof.dt :=B8_BOF_dt_Worksheet;
bof.rupBuild:=B8_BOF_rupBuild_Excel97;
bof.rupYear :=B8_BOF_rupYear_Excel07;
WriteBIFF(aStream,B8_BOF,@bof,SizeOf(bof));
//
if (aSheet.CellBounds.Bottom<>-1) and (aSheet.CellBounds.Top<>-1) then
begin
BlocksInSheet:=(aSheet.CellBounds.Bottom-aSheet.CellBounds.Top+1) div XLSMaxRowsInBlock;
if (aSheet.CellBounds.Bottom=aSheet.CellBounds.Top) or (((aSheet.CellBounds.Bottom-aSheet.CellBounds.Top+1) mod XLSMaxRowsInBlock)<>0) then
Inc(BlocksInSheet);
end
else
BlocksInSheet:=0;
//
index:=AllocMem(SizeOf(TRLXLSBiff8INDEX)+BlocksInSheet*4);
try
if (aSheet.CellBounds.Bottom<>-1) and (aSheet.CellBounds.Top<>-1) then
begin
index.rwMic:=aSheet.CellBounds.Top;
index.rwMac:=aSheet.CellBounds.Bottom+1;
end;
INDEXOffs :=aStream.Position;
IndexInDBCELLsOffs:=0;
WriteBIFF(aStream,B8_INDEX,index,SizeOf(TRLXLSBiff8INDEX)+BlocksInSheet*4);
//
calcmode.fAutoRecalc:=1;
WriteBIFF(aStream,B8_CALCMODE,@calcmode,SizeOf(calcmode));
calccount.cIter :=$0064;
WriteBIFF(aStream,B8_CALCCOUNT,@calccount,SizeOf(calccount));
refmode.fRefA1 :=$0001;
WriteBIFF(aStream,B8_REFMODE,@refmode,SizeOf(refmode));
iteration.fIter :=$0000;
WriteBIFF(aStream,B8_ITERATION,@iteration,SizeOf(iteration));
//
aux:=HexToString('10 00 08 00 fc a9 f1 d2 4d 62 50 3f');
wr(aStream,aux[1],length(aux));
//
saverecalc.fSaveRecalc:=$0001;
WriteBIFF(aStream,B8_SAVERECALC,@saverecalc,SizeOf(saverecalc));
//
if aSheet.Workbook.PageSetup.PrintHeaders then
printheaders.fPrintRwCol:=1
else
printheaders.fPrintRwCol:=0;
WriteBIFF(aStream,B8_PRINTHEADERS,@printheaders,SizeOf(printheaders));
//
if aSheet.Workbook.PageSetup.PrintGridLines then
printgridlines.fPrintGrid:=1
else
printgridlines.fPrintGrid:=0;
WriteBIFF(aStream,B8_PRINTGRIDLINES,@printgridlines,SizeOf(printgridlines));
//
gridset.fGridSet:=$0001;
WriteBIFF(aStream,B8_GRIDSET,@gridset,SizeOf(gridset));
//
FillChar(guts,SizeOf(guts),0);
WriteBIFF(aStream,B8_GUTS,@guts,SizeOf(guts));
//
defaultrowheight.grbit:=$0000;
defaultrowheight.miyRw:=DefaultCellHeight;
WriteBIFF(aStream,B8_DEFAULTROWHEIGHT,@defaultrowheight,SizeOf(defaultrowheight));
//
wsbool.grbit:=$04C1;
WriteBIFF(aStream,B8_WSBOOL,@wsbool,SizeOf(wsbool));
//
aux:='';
if aSheet.Workbook.PageSetup.LeftHeader<>'' then
aux:=aux+'&L'+aSheet.Workbook.PageSetup.LeftHeader;
if aSheet.Workbook.PageSetup.CenterHeader<>'' then
aux:=aux+'&C'+aSheet.Workbook.PageSetup.CenterHeader;
if aSheet.Workbook.PageSetup.RightHeader<>'' then
aux:=aux+'&R'+aSheet.Workbook.PageSetup.RightHeader;
if aux<>'' then
begin
room:=WideStringSize(aux);
GetMem(header,SizeOf(TRLXLSBiff8HEADER)+room);
try
header.cch :=Length(aux);
header.cchgrbit:=1;
StringToWideChar(aux,PWideChar(Integer(header)+SizeOf(TRLXLSBiff8HEADER)),room);
WriteBIFF(aStream,B8_HEADER,header,SizeOf(TRLXLSBiff8HEADER)+room);
finally
FreeMem(header);
end;
end;
aux:='';
if aSheet.Workbook.PageSetup.LeftFooter<>'' then
aux:=aux+'&L'+aSheet.Workbook.PageSetup.LeftFooter;
if aSheet.Workbook.PageSetup.CenterFooter<>'' then
aux:=aux+'&C'+aSheet.Workbook.PageSetup.CenterFooter;
if aSheet.Workbook.PageSetup.RightFooter<>'' then
aux:=aux+'&R'+aSheet.Workbook.PageSetup.RightFooter;
if aux<>'' then
begin
room:=WideStringSize(aux);
GetMem(footer,SizeOf(TRLXLSBiff8FOOTER)+room);
try
footer.cch :=Length(aux);
footer.cchgrbit:=1;
StringToWideChar(aux,PWideChar(Integer(footer)+SizeOf(TRLXLSBiff8HEADER)),room);
WriteBIFF(aStream,B8_FOOTER,footer,SizeOf(TRLXLSBiff8FOOTER)+room);
finally
FreeMem(footer);
end;
end;
if aSheet.Workbook.PageSetup.CenterHorizontally then
hcenter.fHCenter:=1
else
hcenter.fHCenter:=0;
WriteBIFF(aStream,B8_HCENTER,@hcenter,SizeOf(hcenter));
if aSheet.Workbook.PageSetup.CenterVertically then
vcenter.fVCenter:=1
else
vcenter.fVCenter:=0;
WriteBIFF(aStream,B8_VCENTER,@vcenter,SizeOf(vcenter));
leftmargin.num:=aSheet.Workbook.PageSetup.LeftMargin/2.54;
WriteBIFF(aStream,B8_LEFTMARGIN,@leftmargin,SizeOf(TRLXLSBiff8LEFTMARGIN));
rightmargin.num:=aSheet.Workbook.PageSetup.RightMargin/2.54;
WriteBIFF(aStream,B8_RIGHTMARGIN,@rightmargin,SizeOf(TRLXLSBiff8RIGHTMARGIN));
topmargin.num:=aSheet.Workbook.PageSetup.TopMargin/2.54;
WriteBIFF(aStream,B8_TOPMARGIN,@topmargin,SizeOf(TRLXLSBiff8TOPMARGIN));
bottommargin.num:=aSheet.Workbook.PageSetup.BottomMargin/2.54;
WriteBIFF(aStream,B8_BOTTOMMARGIN,@bottommargin,SizeOf(TRLXLSBiff8BOTTOMMARGIN));
//
FillChar(setup,SizeOf(TRLXLSBiff8SETUP),0);
setup.iPaperSize:=word(aSheet.Workbook.PageSetup.PaperSize);
setup.iPageStart:=aSheet.Workbook.PageSetup.FirstPageNumber;
setup.iFitWidth :=Byte(aSheet.Workbook.PageSetup.FitToPagesWide);
setup.iFitHeight:=Byte(aSheet.Workbook.PageSetup.FitToPagesTall);
setup.numHdr :=aSheet.Workbook.PageSetup.HeaderMargin/2.54;
setup.numFtr :=aSheet.Workbook.PageSetup.FooterMargin/2.54;
setup.iCopies :=aSheet.Workbook.PageSetup.Copies;
setup.iScale :=aSheet.Workbook.PageSetup.Zoom;
//
if aSheet.Workbook.PageSetup.Order=odOverThenDown then
setup.grbit:=setup.grbit or B8_SETUP_fLeftToRight;
if aSheet.Workbook.PageSetup.Orientation=orPortrait then
setup.grbit:=setup.grbit or B8_SETUP_fLandscape;
if aSheet.Workbook.PageSetup.BlackAndWhite then
setup.grbit:=setup.grbit or B8_SETUP_fNoColor;
if aSheet.Workbook.PageSetup.Draft then
setup.grbit:=setup.grbit or B8_SETUP_fDraft;
if aSheet.Workbook.PageSetup.PrintNotes then
setup.grbit:=setup.grbit or B8_SETUP_fNotes;
if aSheet.Workbook.PageSetup.FirstPageNumber<>1 then
setup.grbit:=setup.grbit or B8_SETUP_fUsePage;
WriteBIFF(aStream,B8_SETUP,@setup,SizeOf(TRLXLSBiff8SETUP));
//
defcolwidth.cchdefColWidth:=DefaultCellLength;
WriteBIFF(aStream,B8_DEFCOLWIDTH,@defcolwidth,SizeOf(defcolwidth));
//
for i:=0 to aSheet.ColCount-1 do
with aSheet.FindCol(i,True) do
begin
FillChar(colinfo,SizeOf(colinfo),0);
colinfo.colFirst:=Index;
colinfo.colLast :=Index;
colinfo.coldx :=Width;
WriteBIFF(aStream,B8_COLINFO,@colinfo,SizeOf(colinfo));
end;
//
FillChar(dimensions,SizeOf(dimensions),0);
if (aSheet.CellBounds.Left<>-1) and (aSheet.CellBounds.Right<>-1) and (aSheet.CellBounds.Top<>-1) and (aSheet.CellBounds.Bottom<>-1) then
begin
dimensions.rwMic :=aSheet.CellBounds.Top;
dimensions.rwMac :=aSheet.CellBounds.Bottom+1;
dimensions.colMic:=aSheet.CellBounds.Left;
dimensions.colMac:=aSheet.CellBounds.Right+1;
end;
WriteBIFF(aStream,B8_DIMENSIONS,@dimensions,SizeOf(dimensions));
//
if (aSheet.CellBounds.Top<>-1) and (aSheet.CellBounds.Bottom<>-1) then
begin
l:=TList.Create;
ms:=TMemoryStream.Create;
try
bc:=0;
FirstRowOffs:=0;
SecondRowOffs:=0;
for i:=aSheet.CellBounds.Top to aSheet.CellBounds.Bottom do
begin
l.Clear;
for j:=0 to aSheet.RangeCount-1 do
begin
range:=aSheet.Ranges[j];
if (range.CellBounds.Top<=i) and (i<=range.CellBounds.Bottom) then
l.Add(range);
end;
l.Sort(RangeSortCallback);
//
if bc=0 then
FirstRowOffs:=aStream.Position;
FillChar(row,SizeOf(row),0);
row.rw:=i;
if l.Count>0 then
begin
row.colMic:=TRLXLSRange(l[0]).CellBounds.Left;
row.colMac:=TRLXLSRange(l[l.Count-1]).CellBounds.Right+1;
end
else
begin
row.colMic:=0;
row.colMac:=0;
end;
//
rw:=aSheet.FindRow(i,False);
if rw=nil then
begin
row.miyRw:=DefaultCellHeight;
row.grbit:=0;
end
else
begin
row.miyRw:=rw.Height*20;
row.grbit:=B8_ROW_grbit_fUnsynced;
end;
WriteBIFF(aStream,B8_ROW,@row,SizeOf(row));
if bc=0 then
SecondRowOffs:=aStream.Position;
//
IndexInCellsOffsArray:=0;
for j:=0 to l.Count-1 do
WriteRangeToStream(ms,TRLXLSRange(l[j]),i,IndexInCellsOffsArray,dbcell.CellsOffs);
Inc(bc);
if (bc=XLSMaxRowsInBlock) or (i=aSheet.CellBounds.Bottom) then
begin
dbcell.CellsOffs[0]:=aStream.Position-SecondRowOffs;
ms.SaveToStream(aStream);
PCardinalArray(PAnsiChar(index)+SizeOf(TRLXLSBiff8INDEX))^[IndexInDBCELLsOffs]:= aStream.Position-FBOFOffs;
Inc(IndexInDBCELLsOffs);
dbcell.dbRtrw:=aStream.Position-FirstRowOffs;
WriteBIFF(aStream,B8_DBCELL,@dbcell,SizeOf(TRLXLSBiff8DBCELL)+IndexInCellsOffsArray*2);
//
ms.Clear;
bc:=0;
end;
end;
finally
l.Free;
ms.Free;
end;
//
aStream.Position:=INDEXOffs;
WriteBIFF(aStream,B8_INDEX,index,SizeOf(TRLXLSBiff8INDEX)+BlocksInSheet*4);
aStream.Seek(0,soFromEnd);
end;
finally
FreeMem(index);
end;
FillChar(window2,SizeOf(window2),0);
window2.grbit:=B8_WINDOW2_grbit_fPaged or
B8_WINDOW2_grbit_fDspGuts or
B8_WINDOW2_grbit_fDspZeros or
B8_WINDOW2_grbit_fDefaultHdr or
B8_WINDOW2_grbit_fDspGrid or
B8_WINDOW2_grbit_fDspRwCol;
if aSheet.Index=0 then
window2.grbit:=window2.grbit+B8_WINDOW2_grbit_fSelected;
window2.rwTop:=0;
window2.colLeft:=0;
window2.icvHdr:=$00000040;
window2.wScaleSLV:=0;
window2.wScaleNormal:=0;
WriteBIFF(aStream,B8_WINDOW2,@window2,SizeOf(window2));
//
selection:=AllocMem(SizeOf(TRLXLSBiff8SELECTION)+6);
try
selection.pnn :=3;
selection.cref:=1;
WriteBIFF(aStream,B8_SELECTION,selection,SizeOf(TRLXLSBiff8SELECTION)+6);
finally
FreeMem(selection);
end;
//
if aSheet.RangeCount>0 then
begin
j:=0;
for i:=0 to aSheet.RangeCount-1 do
begin
range:=aSheet.Ranges[i];
if (range.CellBounds.Left<>range.CellBounds.Right) or
(range.CellBounds.Top<>range.CellBounds.Bottom) then
Inc(j);
end;
if j>0 then
begin
merge:=AllocMem(SizeOf(TRLXLSBiff8MERGE)+j*8);
try
merge.cnt:=j;
j:=0;
for i:=0 to aSheet.RangeCount-1 do
begin
range:=aSheet.Ranges[i];
if (range.CellBounds.Left<>range.CellBounds.Right) or
(range.CellBounds.Top<>range.CellBounds.Bottom) then
begin
with PRLXLSBiff8MERGErec(PAnsiChar(merge)+SizeOf(TRLXLSBiff8MERGE)+j*8)^ do
begin
left :=range.CellBounds.Left;
top :=range.CellBounds.Top;
right :=range.CellBounds.Right;
bottom:=range.CellBounds.Bottom;
end;
Inc(j);
end;
end;
WriteBIFF(aStream,B8_MERGE,merge,SizeOf(TRLXLSBiff8MERGE)+j*8);
finally
FreeMem(merge);
end;
end;
end;
WriteBIFF(aStream,B8_EOF,nil,0);
end;
procedure TRLXLSFilter.WriteBookToStream(aStream:TStream);
var
codepage :TRLXLSBiff8CodePage;
interfachdr :TRLXLSBiff8InterfaceHeader;
fngroupcount :TRLXLSBiff8FNGroupCount;
windowprotect :TRLXLSBiff8WindowProtect;
protect :TRLXLSBiff8Protect;
password :TRLXLSBiff8Password;
backup :TRLXLSBiff8BACKUP;
hideobj :TRLXLSBiff8HIDEOBJ;
s1904 :TRLXLSBiff81904;
precision :TRLXLSBiff8PRECISION;
bookbool :TRLXLSBiff8BOOKBOOL;
writeaccess :TRLXLSBiff8WRITEACCESS;
doublestreamfile:TRLXLSBiff8DOUBLESTREAMFILE;
prot4rev :TRLXLSBiff8PROT4REV;
prot4revpass :TRLXLSBiff8PROT4REVPASS;
window1 :TRLXLSBiff8WINDOW1;
refreshall :TRLXLSBiff8REFRESHALL;
useselfs :TRLXLSBiff8USESELFS;
boundsheet :PRLXLSBiff8BOUNDSHEET;
country :TRLXLSBiff8COUNTRY;
palette :TRLXLSBiff8PALETTE;
extsst :PRLXLSBiff8EXTSST;
bof :TRLXLSBiff8BOF;
mms :TRLXLSBiff8MMS;
sst,sstbuf :PAnsiChar;
sstsizeoffset :integer;
ltitleoffset :integer;
sstblockoffset :integer;
lsstbuf :integer;
sstsize :integer;
extsstsize :integer;
ltitle :integer;
i,j,k,m :integer;
buf :pointer;
sz :word;
sl :TStringList;
sheet :TRLXLSWorksheet;
aux :AnsiString;
l :TList;
begin
j:=0;
for i:=0 to fWorkbook.SheetCount-1 do
j:=j+fWorkbook.Sheets[i].RangeCount;
GetMem(fRangesRecs,j*SizeOf(TRLXLSRangeRec));
GetMem(fSheetsRecs,fWorkbook.SheetCount*SizeOf(TRLXLSSheetRec));
try
Move(XLSDefaultColorPalette[0],fColorPalette[0],XLSMaxColorsInPalette*4);
fPaletteModified:=False;
fUsedColors.Clear;
FBOFOffs:=aStream.Position;
FillChar(bof,SizeOf(bof),0);
bof.vers :=B8_BOF_vers;
bof.dt :=B8_BOF_dt_WorkbookGlobals;
bof.rupBuild:=B8_BOF_rupBuild_Excel97;
bof.rupYear :=B8_BOF_rupYear_Excel07;
bof.sfo :=B8_BOF_vers;
WriteBIFF(aStream,B8_BOF,@bof,SizeOf(bof));
FillChar(interfachdr,SizeOf(interfachdr),0);
interfachdr.cv:=B8_INTERFACHDR_cv_ANSI;
WriteBIFF(aStream,B8_INTERFACHDR,@interfachdr,SizeOf(interfachdr));
FillChar(mms,SizeOf(mms),0);
WriteBIFF(aStream,B8_MMS,@mms,SizeOf(mms));
WriteBIFF(aStream,B8_INTERFACEND,nil,0);
FillChar(writeaccess,SizeOf(writeaccess),32);
StringToWideChar(WorkBook.UserName,@writeaccess.stName,sizeof(writeaccess));
WriteBIFF(aStream,B8_WRITEACCESS,@writeaccess,SizeOf(writeaccess));
codepage.cv:=B8_CODEPAGE_cv_ANSI;
WriteBIFF(aStream,B8_CODEPAGE,@codepage,SizeOf(codepage));
doublestreamfile.fDSF:=0;
WriteBIFF(aStream,B8_DOUBLESTREAMFILE,@doublestreamfile,SizeOf(doublestreamfile));
WriteBIFF(aStream,$01C0,nil,0);
GetMem(buf,WorkBook.SheetCount*2);
try
for i:=0 to WorkBook.SheetCount-1 do
PWordArray(buf)^[i]:=i;
WriteBIFF(aStream,B8_TABID,buf,WorkBook.SheetCount*2);
finally
FreeMem(buf);
end;
fngroupcount.cFnGroup:=$000E;
WriteBIFF(aStream,B8_FNGROUPCOUNT,@fngroupcount,SizeOf(fngroupcount));
windowprotect.fLockWn:=0;
WriteBIFF(aStream,B8_WINDOWPROTECT,@windowprotect,SizeOf(windowprotect));
protect.fLock:=0;
WriteBIFF(aStream,B8_PROTECT,@protect,SizeOf(protect));
password.wPassword:=0;
WriteBIFF(aStream,B8_PASSWORD,@password,SizeOf(password));
prot4rev.fRevLock:=0;
WriteBIFF(aStream,B8_PROT4REV,@prot4rev,SizeOf(prot4rev));
prot4revpass.wrevPass:=0;
WriteBIFF(aStream,B8_PROT4REVPASS,@prot4revpass,SizeOf(prot4revpass));
FillChar(window1,SizeOf(window1),0);
window1.xWn :=$0168;
window1.yWn :=$001E;
window1.dxWn :=$1D1E;
window1.dyWn :=$1860;
window1.grbit :=$0038;
window1.itabCur :=$0000;
window1.itabFirst:=$0000;
window1.ctabSel :=$0001;
window1.wTabRatio:=$0258;
WriteBIFF(aStream,B8_WINDOW1,@window1,SizeOf(window1));
backup.fBackupFile:=0;
WriteBIFF(aStream,B8_BACKUP,@backup,SizeOf(backup));
hideobj.fHideObj:=0;
WriteBIFF(aStream,B8_HIDEOBJ,@hideobj,SizeOf(hideobj));
s1904.f1904:=0;
WriteBIFF(aStream,B8_1904,@s1904,SizeOf(s1904));
precision.fFullPrec:=1;
WriteBIFF(aStream,B8_PRECISION,@precision,SizeOf(precision));
refreshall.fRefreshAll:=0;
WriteBIFF(aStream,B8_REFRESHALL,@refreshall,SizeOf(refreshall));
bookbool.fNoSaveSupp:=0;
WriteBIFF(aStream,B8_BOOKBOOL,@bookbool,SizeOf(bookbool));
// SAVE FONTS
l:=TList.Create;
try
for i:=0 to 3 do
with TFont(l[l.Add(TFont.Create)]) do
begin
Name:=DefaultFontName;
Size:=10;
end;
BuildFontList(l);
for i:=0 to l.Count-1 do
WriteBIFFFont(aStream,TFont(l[i]),GetColorPaletteIndex(TFont(l[i]).Color));
finally
for i:=0 to l.Count-1 do
TFont(l[i]).Free;
l.Free;
end;
// SAVE FORMATS
sl:=TStringList.Create;
try
{//Celso. Original era assim
sl.AddObject('#,##0"รฐ.";\-#,##0"รฐ."',Pointer($0005));
sl.AddObject('#,##0"รฐ.";[Red]\-#,##0"รฐ."',Pointer($0006));
sl.AddObject('#,##0.00"รฐ.";\-#,##0.00"รฐ."',Pointer($0007));
sl.AddObject('#,##0.00"รฐ.";[Red]\-#,##0.00"รฐ."',Pointer($0008));
sl.AddObject('_-* #,##0"รฐ."_-;\-* #,##0"รฐ."_-;_-* "-""รฐ."_-;_-@_-',Pointer($002A));
sl.AddObject('_-* #,##0_รฐ_._-;\-* #,##0_รฐ_._-;_-* "-"_รฐ_._-;_-@_-',Pointer($0029));
sl.AddObject('_-* #,##0.00"รฐ."_-;\-* #,##0.00"รฐ."_-;_-* "-"??"รฐ."_-;_-@_-', Pointer($002C));
sl.AddObject('_-* #,##0.00_รฐ_._-;\-* #,##0.00_รฐ_._-;_-* "-"??_รฐ_._-;_-@_-', Pointer($002B)); }
sl.AddObject('#,##0;\-#,##0',Pointer($0005));
sl.AddObject('#,##0;[Red]\-#,##0',Pointer($0006));
sl.AddObject('#,##0.00;\-#,##0.00',Pointer($0007));
sl.AddObject('#,##0.00;[Red]\-#,##0.00',Pointer($0008));
BuildFormatList(sl);
for i:=0 to sl.Count-1 do
WriteBIFFFormat(aStream,AnsiString(sl[i]),word(sl.Objects[i]));//bds2010
finally
sl.Free;
end;
// SAVE STYLE
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 00 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 01 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 01 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 02 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 02 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
WriteBIFFHexString(aStream,'e0 00 14 00 00 00 00 00 f5 ff 20 00 00 f4 00 00 00 00 00 00 00 00 c0 20');
// XF
l:=TList.Create;
try
aux:=HexToString('00 00 00 00 01 00 20 00 00 00 00 00 00 00 00 00 00 00 c0 20');
GetMem(buf,Length(aux));
Move(aux[1],buf^,Length(aux));
l.Add(buf);
BuildXFList(l);
for i:=0 to l.Count-1 do
WriteBIFF(aStream,B8_XF,l[i],SizeOf(TRLXLSBiff8XF));
finally
for i:=0 to l.Count-1 do
FreeMem(l[i]);
l.Free;
end;
// SAVE PALETTE
if fPaletteModified then
begin
palette.ccv:=XLSMaxColorsInPalette;
for i:=0 to XLSMaxColorsInPalette-1 do
palette.colors[i]:=fColorPalette[i];
WriteBIFF(aStream,B8_PALETTE,@palette,SizeOf(palette));
end;
WriteBIFFHexString(aStream,'93 02 04 00 10 80 04 FF');
WriteBIFFHexString(aStream,'93 02 04 00 11 80 07 FF');
WriteBIFFHexString(aStream,'93 02 04 00 00 80 00 FF');
WriteBIFFHexString(aStream,'93 02 04 00 12 80 05 FF');
WriteBIFFHexString(aStream,'93 02 04 00 13 80 03 FF');
WriteBIFFHexString(aStream,'93 02 04 00 14 80 06 FF');
useselfs.fUsesElfs:=0;
WriteBIFF(aStream,B8_USESELFS,@useselfs,SizeOf(useselfs));
// SAVE SHEETS
for i:=0 to fWorkbook.SheetCount-1 do
begin
sheet :=fWorkbook.Sheets[i];
fSheetsRecs[i].StreamBOFOffsetPosition:=aStream.Position+4;
ltitle :=WideStringSize(sheet.Title);
boundsheet:=AllocMem(SizeOf(TRLXLSBiff8BOUNDSHEET)+ltitle);
try
boundsheet.grbit :=0;
boundsheet.cch :=Length(sheet.Title);
boundsheet.cchgrbit:=1;
if boundsheet.cch>0 then
StringToWideChar(sheet.Title,PWideChar(Integer(boundsheet)+SizeOf(TRLXLSBiff8BOUNDSHEET)),ltitle);
WriteBIFF(aStream,B8_BOUNDSHEET,boundsheet,SizeOf(TRLXLSBiff8BOUNDSHEET)+ltitle);
finally
FreeMem(boundsheet);
end;
end;
country.iCountryDef :=$07;
country.iCountryWinIni:=$07;
WriteBIFF(aStream,B8_COUNTRY,@country,SizeOf(country));
// SST TABLE
extsstsize :=SizeOf(TRLXLSBiff8EXTSST);
extsst :=AllocMem(extsstsize);
extsst.Dsst:=8;
sstsize :=SizeOf(TRLXLSBiff8SST)+4;
sst :=AllocMem(sstsize);
PWord(sst)^ :=B8_SST;
sstsizeoffset :=2;
PWord(sst+sstsizeoffset)^:=SizeOf(TRLXLSBiff8SST);
sstblockoffset:=sstsize;
lsstbuf :=0;
sstbuf :=nil;
k:=0;
m:=0;
try
for i:=0 to fWorkbook.SheetCount-1 do
begin
sheet:=fWorkbook.Sheets[i];
for j:=0 to sheet.RangeCount-1 do
begin
if sheet.Ranges[j].DataType=ctString then
begin
aux:=sheet.Ranges[j].Value;
if aux<>'' then
begin
fRangesRecs[m].iSST:=k;
Inc(k);
//
ltitle:=WideStringSize(aux);
if lsstbuf<ltitle then
begin
lsstbuf:=ltitle;
ReallocMem(sstbuf,lsstbuf);
end;
StringToWideChar(aux,PWideChar(sstbuf),ltitle);
if MaxBiffRecordSize-sstblockoffset<=4 then
begin
ReallocMem(sst,sstsize+4);
PWord(sst+sstsize)^:=B8_CONTINUE;
sstsize :=sstsize+2;
sstsizeoffset :=sstsize;
PWord(sst+sstsize)^:=0;
sstsize :=sstsize+2;
sstblockoffset :=4;
end;
if (k mod 8)=1 then
begin
ReallocMem(extsst,extsstsize+SizeOf(TRLXLSBiff8ISSTINF));
PRLXLSBiff8ISSTINF(PAnsiChar(extsst)+extsstsize).cb :=sstblockoffset;
PRLXLSBiff8ISSTINF(PAnsiChar(extsst)+extsstsize).ib :=aStream.Position+sstsize;
PRLXLSBiff8ISSTINF(PAnsiChar(extsst)+extsstsize).res1:=0;
extsstsize:=extsstsize+SizeOf(TRLXLSBiff8ISSTINF);
end;
ReallocMem(sst,sstsize+3);
PWord(sst+sstsize)^ :=Length(aux);
sstsize :=sstsize+2;
PByte(sst+sstsize)^ :=1;
sstsize :=sstsize+1;
PWord(sst+sstsizeoffset)^:=PWord(sst+sstsizeoffset)^ +3;
sstblockoffset:=sstblockoffset+3;
ltitleoffset:=0;
repeat
sz :=(Min(ltitle-ltitleoffset,MaxBiffRecordSize-sstblockoffset)) and (not 1);
ReallocMem(sst,sstsize+sz);
Move(Pointer(Integer(sstbuf)+ltitleoffset)^,Pointer(Integer(sst)+sstsize)^,sz);
sstsize :=sstsize+sz;
sstblockoffset:=sstblockoffset+sz;
ltitleoffset :=ltitleoffset+sz;
PWord(sst+sstsizeoffset)^:=PWord(sst+sstsizeoffset)^ +sz;
if (ltitle>ltitleoffset) and ((MaxBiffRecordSize-sstblockoffset)<=4) then
begin
ReallocMem(sst,sstsize+5);
PWord(sst+sstsize)^:=B8_CONTINUE;
sstsize :=sstsize+2;
sstsizeoffset :=sstsize;
PWord(sst+sstsize)^:=1;
sstsize :=sstsize+2;
PByte(sst+sstsize)^:=1;
sstsize :=sstsize+1;
sstblockoffset :=5;
end;
until ltitle<=ltitleoffset;
end;
end;
Inc(m);
end;
end;
if k<>0 then
begin
PRLXLSBiff8SST(sst+4).cstTotal :=k;
PRLXLSBiff8SST(sst+4).cstUnique:=k;
wr(aStream,sst^,sstsize);
WriteBIFF(aStream,B8_EXTSST,extsst,extsstsize);
end;
finally
FreeMem(sst);
FreeMem(sstbuf);
FreeMem(extsst);
end;
WriteBIFF(aStream,B8_EOF,nil,0);
//
for i:=0 to fWorkbook.SheetCount-1 do
begin
sheet:=fWorkbook.Sheets[i];
fSheetsRecs[i].StreamBOFOffset:=aStream.Position;
WriteSheetToStream(aStream,sheet);
end;
//
for i:=0 to fWorkbook.SheetCount-1 do
begin
aStream.Position:=fSheetsRecs[i].StreamBOFOffsetPosition;
wr(aStream,fSheetsRecs[i].StreamBOFOffset,4);
end;
finally
fUsedColors.Clear;
FreeMem(fRangesRecs);
fRangesRecs:=nil;
FreeMem(fSheetsRecs);
fSheetsRecs:=nil;
end;
end;
procedure TRLXLSFilter.WriteStorageToStream(aStream:TStream);
type
CHAR8 =packed array[0..7] of AnsiChar;
CHAR16 =packed array[0..15] of AnsiChar;
CHAR64 =packed array[0..32*SizeOf(WideChar)-1] of AnsiChar;
SECT109=packed array[0..108] of cardinal;
TStructuredStorageHeader=packed record
_abSig :CHAR8;
_clid :CHAR16;
_uMinorVersion :word;
_uDllVersion :word;
_uByteOrder :word;
_uSectorShift :word;
_uMiniSectorShift :word;
_usReserved :word;
_ulReserved1 :cardinal;
_ulReserved2 :cardinal;
_csectFat :cardinal;
_sectDirStart :cardinal;
_signature :cardinal;
_ulMiniSectorCutoff:cardinal;
_sectMiniFatStart :cardinal;
_csectMiniFat :cardinal;
_sectDifStart :cardinal;
_csectDif :cardinal;
_sectFat :SECT109;
end;
TIME_T=packed record
dwLowDateTime :cardinal;
dwHighDateTime:cardinal;
end;
TIME_T2=packed array[0..1] of TIME_T;
TStructuredStorageDirectoryEntry=packed record
_ab :CHAR64;
_cb :WORD;
_mse :BYTE;
_bflags :BYTE;
_sidLeftSib :cardinal;
_sidRightSib:cardinal;
_sidChild :cardinal;
_clsId :CHAR16;
_dwUserFlags:cardinal;
_time :TIME_T2;
_sectStart :cardinal;
_ulSizeLow :cardinal;
_ulSizeHigh :cardinal;
end;
TStructuredStorageFAT=packed array[0..128-1] of cardinal;
const
StorageSignature :AnsiString = #$D0#$CF#$11#$E0#$A1#$B1#$1A#$E1;
RootEntry :AnsiString ='R'#0'o'#0'o'#0't'#0' '#0'E'#0'n'#0't'#0'r'#0'y'#0#0#0;
Workbook :AnsiString ='W'#0'o'#0'r'#0'k'#0'b'#0'o'#0'o'#0'k'#0#0#0;
//
MAXREGSECT:cardinal=$FFFFFFFA;
DIFSECT :cardinal=$FFFFFFFC;
FATSECT :cardinal=$FFFFFFFD;
ENDOFCHAIN:cardinal=$FFFFFFFE;
FREESECT :cardinal=$FFFFFFFF;
MAXREGSID :cardinal=$FFFFFFFA; // maximum directory entry ID
NOSTREAM :cardinal=$FFFFFFFF; // unallocated directory entry
const
// STGTY
STGTY_INVALID =0;
STGTY_STORAGE =1;
STGTY_STREAM =2;
STGTY_LOCKBYTES=3;
STGTY_PROPERTY =4;
STGTY_ROOT =5;
// DECOLOR
DE_RED =0;
DE_BLACK =1;
var
header :TStructuredStorageHeader;
fat :TStructuredStorageFAT;
dir :TStructuredStorageDirectoryEntry;
i :cardinal;
buf512 :packed array[0..512-1] of Ansichar;
datsec1 :cardinal;
datsecN :cardinal;
datsec :cardinal;
datasize:cardinal;
fatsec1 :cardinal;
fatsecN :cardinal;
fatsec :cardinal;
dirsec1 :cardinal;
dirsecN :cardinal;
dirsec :cardinal;
headerof:cardinal;
seccount:cardinal;
fatcount:cardinal;
fatof :cardinal;
sectno :cardinal;
dirof :cardinal;
tempname:string;
temp :TFileStream;
procedure WriteSect;
begin
aStream.Write(buf512,SizeOf(buf512));
Inc(sectno);
end;
begin
datasize:=0;
// reserva setor -1 para o header
sectno:=Cardinal(-1);
headerof:=aStream.Position;
WriteSect;
// escreve o arquivo xls puro
tempname:=GetTempFileName;
temp:=TFileStream.Create(tempname,fmCreate);
try
WriteBookToStream(temp);
temp.Position:=0;
datsec1:=sectno;
datsecN:=sectno;
repeat
FillChar(buf512,SizeOf(buf512),0);
i:=temp.Read(buf512,SizeOf(buf512));
if i=0 then
Break;
datsecN:=sectno;
WriteSect;
Inc(datasize,i);
until False;
finally
temp.Free;
SysUtils.DeleteFile(tempname);
end;
seccount:=(datasize+512-1) div 512;
fatcount:=(seccount+128-1) div 128;
// reserva setores para as fats
fatof :=aStream.Position;
fatsec1:=sectno;
fatsecN:=sectno;
for i:=0 to fatcount-1 do
begin
fatsecN:=sectno;
WriteSect;
end;
// reserva setor para diretorio
dirof :=aStream.Position;
dirsec1:=sectno;
dirsecN:=sectno;
WriteSect;
// grava header atualizado
FillChar(header,SizeOf(header),0);
Move(StorageSignature[1],header._abSig,Length(StorageSignature));
header._uMinorVersion :=$003E;
header._uDllVersion :=3;
header._uByteOrder :=$FFFE;
header._uSectorShift :=9;
header._uMiniSectorShift :=6;
header._csectFat :=fatcount;
header._sectDirStart :=dirsec1;
header._ulMiniSectorCutoff:=$00001000;
header._sectMiniFatStart :=ENDOFCHAIN;
header._sectDifStart :=ENDOFCHAIN;
i:=0;
while i<fatcount do
begin
header._sectFat[i]:=fatsec1+i;
Inc(i);
end;
while i<109 do
begin
header._sectFat[i]:=FREESECT;
Inc(i);
end;
aStream.Position:=headerof;
aStream.Write(header,SizeOf(header));
// grava fats
aStream.Position:=fatof;
i:=0;
datsec:=datsec1;
while datsec<datsecN do
begin
fat[i]:=datsec+1;
Inc(datsec);
Inc(i);
if i>=128 then
begin
aStream.Write(fat,SizeOf(fat));
i:=0;
end;
end;
fat[i]:=ENDOFCHAIN;
Inc(i);
fatsec:=fatsec1;
while fatsec<=fatsecN do
begin
fat[i]:=FATSECT;
Inc(fatsec);
Inc(i);
if i>=128 then
begin
aStream.Write(fat,SizeOf(fat));
i:=0;
end;
end;
dirsec:=dirsec1;
while dirsec<dirsecN do
begin
fat[i]:=dirsec+1;
Inc(dirsec);
Inc(i);
if i>=128 then
begin
aStream.Write(fat,SizeOf(fat));
i:=0;
end;
end;
fat[i]:=ENDOFCHAIN;
Inc(i);
while i<128 do
begin
fat[i]:=FREESECT;
Inc(i);
end;
aStream.Write(fat,SizeOf(fat));
// grava diretorio
aStream.Position :=dirof;
// ROOT
FillChar(dir,SizeOf(dir),0);
Move(RootEntry[1],dir._ab,Length(RootEntry));
dir._cb :=Length(RootEntry);
dir._mse :=STGTY_ROOT;
dir._bflags :=DE_BLACK;
dir._sidLeftSib :=NOSTREAM;
dir._sidRightSib:=NOSTREAM;
dir._sidChild :=1;
dir._sectStart :=ENDOFCHAIN;
aStream.Write(dir,SizeOf(dir));
// STREAM
FillChar(dir,SizeOf(dir),0);
Move(Workbook[1],dir._ab,Length(Workbook));
dir._cb :=Length(Workbook);
dir._mse :=STGTY_STREAM;
dir._bflags :=DE_BLACK;
dir._sidLeftSib :=NOSTREAM;
dir._sidRightSib:=NOSTREAM;
dir._sidChild :=NOSTREAM;
dir._sectStart :=datsec1;
dir._ulSizeLow :=datasize;
aStream.Write(dir,SizeOf(dir));
// 2*NULL
FillChar(dir,SizeOf(dir),0);
dir._sidLeftSib :=NOSTREAM;
dir._sidRightSib:=NOSTREAM;
dir._sidChild :=NOSTREAM;
aStream.Write(dir,SizeOf(dir));
aStream.Write(dir,SizeOf(dir));
end;
procedure TRLXLSFilter.SaveToStream(aStream:TStream);
begin
WriteStorageToStream(aStream);
end;
procedure TRLXLSFilter.SaveToFile(const aFileName:AnsiString);
var
Stream:TFileStream;
begin
Stream:=TFileStream.Create(String(aFileName),fmCreate);//bds2010
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
procedure TRLXLSFilter.InternalBeginDoc;
begin
WorkBook.Clear;
end;
procedure TRLXLSFilter.InternalDrawPage(aPage:TRLGraphicSurface);
const
MaxTabs=1024;
type
TTab=packed record
Position:integer;
Length :integer;
end;
TTabs=record
Count:integer;
Sizes:packed array[0..MaxTabs-1] of TTab;
end;
procedure AddTab(var aDest:TTabs; aPosition,aLength:integer);
var
i:integer;
begin
i:=0;
while (i<aDest.Count) and (aDest.Sizes[i].Position<aPosition) do
Inc(i);
if i<aDest.Count then
if aDest.Sizes[i].Position=aPosition then
aDest.Sizes[i].Length:=Max(aDest.Sizes[i].Length,aLength)
else
begin
Move(aDest.Sizes[i],aDest.Sizes[i+1],SizeOf(aDest.Sizes[0])*(aDest.Count-i));
aDest.Sizes[i].Position:=aPosition;
aDest.Sizes[i].Length :=aLength;
Inc(aDest.Count);
end
else
begin
aDest.Sizes[aDest.Count].Position:=aPosition;
aDest.Sizes[aDest.Count].Length :=aLength;
Inc(aDest.Count);
end;
end;
procedure DelTab(var aDest:TTabs; aTabIndex:integer);
begin
Move(aDest.Sizes[aTabIndex+1],aDest.Sizes[aTabIndex],SizeOf(aDest.Sizes[0])*(aDest.Count-(aTabIndex+1)));
Dec(aDest.Count);
if (aTabIndex>0) and (aTabIndex<aDest.Count) then
aDest.Sizes[aTabIndex-1].Length:=aDest.Sizes[aTabIndex].Position-aDest.Sizes[aTabIndex-1].Position;
end;
var
horztabs:TTabs;
verttabs:TTabs;
i :integer;
sheet :TRLXLSWorksheet;
range :TRLXLSRange;
bounds :TRect;
obj :TRLTextObject;
x0,y0 :integer;
x1,y1 :integer;
deltax :integer;
deltay :integer;
aux :AnsiString;
function TwipsX(x:integer):integer;
begin
Result:=Round((x/96)*1440*2.54);
end;
function TwipsY(y:integer):integer;
begin
Result:=y;
end;
begin
sheet:=WorkBook.NewSheet;
horztabs.Count:=0;
verttabs.Count:=0;
for i:=0 to aPage.ObjectCount-1 do
if (aPage.Objects[i] is TRLTextObject) and (TRLTextObject(aPage.Objects[i]).DisplayText<>'') then
with aPage.Objects[i].BoundsRect do
begin
AddTab(horztabs,TwipsX(Left),TwipsX(Right)-TwipsX(Left));
AddTab(verttabs,TwipsY(Top),TwipsY(Bottom)-TwipsY(Top));
end;
// calcula larguras
with horztabs do
for i:=1 to Count-1 do
Sizes[i-1].Length:=Sizes[i].Position-Sizes[i-1].Position;
with verttabs do
for i:=1 to Count-1 do
Sizes[i-1].Length:=Sizes[i].Position-Sizes[i-1].Position;
// retira as colunas nulas
deltax:=TwipsX(10);
with horztabs do
for i:=Count-1 downto 0 do
if Sizes[i].Length<deltax then
DelTab(horztabs,i);
deltay:=TwipsY(10);
with verttabs do
for i:=Count-1 downto 0 do
if Sizes[i].Length<deltay then
DelTab(verttabs,i);
// seta largura das celulas
with horztabs do
for i:=0 to Count-1 do
sheet.FindCol(i,True).Width:=Sizes[i].Length;
with verttabs do
for i:=0 to Count-1 do
sheet.FindRow(i,True).Height:=Sizes[i].Length;
// distribui textos e faz colspan
for i:=0 to aPage.ObjectCount-1 do
if (aPage.Objects[i] is TRLTextObject) and (TRLTextObject(aPage.Objects[i]).DisplayText<>'') then
begin
obj :=TRLTextObject(aPage.Objects[i]);
bounds:=FromMetaRect(obj.BoundsRect);
bounds.Left :=TwipsX(bounds.Left);
bounds.Top :=TwipsY(bounds.Top);
bounds.Right :=TwipsX(bounds.Right);
bounds.Bottom:=TwipsY(bounds.Bottom);
// procura faixa de cรฉlulas
x0:=0;
while (x0<horztabs.Count) and (horztabs.Sizes[x0].Position<bounds.Left) do
Inc(x0);
x1:=x0;
while (x1<horztabs.Count) and (horztabs.Sizes[x1].Position<bounds.Right-deltax) do
Inc(x1);
y0:=0;
while (y0<verttabs.Count) and (verttabs.Sizes[y0].Position<bounds.Top) do
Inc(y0);
y1:=y0;
while (y1<verttabs.Count) and (verttabs.Sizes[y1].Position<bounds.Bottom-deltay) do
Inc(y1);
{//Celso em 21/05/2011.
Em aguns casos ficava da linha 1 atรฉ a zero e quando mesclava ficava errado e o excel nรฃo abria. O mesmo acontecia com as colunas
Por isso tem os 2 IF abaixo}
if y1 = y0 then
Inc(y1);
if x1 = x0 then
Inc(x1);
aux:=AnsiString(obj.DisplayText);//bds2010
range:=sheet.FindRange(x0,y0,x1-1,y1-1,True);
if aux='' then
range.Value:=' '
else
range.Value:=aux;
FromMetaFont(obj.Font,range.Font);
case obj.Alignment of
MetaTextAlignmentLeft : range.HorizontalAlignment:=haLeft;
MetaTextAlignmentRight : range.HorizontalAlignment:=haRight;
MetaTextAlignmentCenter : range.HorizontalAlignment:=haCenter;
MetaTextAlignmentJustify: range.HorizontalAlignment:=haJustify;
end;
case obj.Layout of
MetaTextLayoutTop : range.VerticalAlignment:=vaTop;
MetaTextLayoutBottom : range.VerticalAlignment:=vaBottom;
MetaTextLayoutCenter : range.VerticalAlignment:=vaCenter;
MetaTextLayoutJustify: range.VerticalAlignment:=vaJustify;
end;
end;
end;
procedure TRLXLSFilter.InternalNewPage;
begin
end;
procedure TRLXLSFilter.InternalEndDoc;
begin
SaveToFile(AnsiString(FileName));//bds2010
end;
function TRLXLSFilter.GetPageSetup: TRLXLSPageSetup;
begin
Result:=fWorkbook.PageSetup;
end;
procedure TRLXLSFilter.SetPageSetup(const Value: TRLXLSPageSetup);
begin
PageSetup.Assign(Value);
end;
end.
|
unit TextConverter.Model.Interfaces;
interface
type
TTypeConverteTexto = (tpInvertido,
tpPrimeiraMaiuscula,
tpOrdenado);
iConverteTexto = interface
['{EC2213E8-F7E2-45A6-9B22-C57520A95517}']
function Texto(pValue : String) : iConverteTexto; overload;
function Texto : String; overload;
function Converter : String;
end;
iConverteTextoFactory = interface
['{6536FE00-5D8B-4EE3-BB42-AB90258F09D3}']
function ConverteTexto(pValue : TTypeConverteTexto) : iConverteTexto;
end;
implementation
end.
|
unit test05.Support;
interface
uses
System.SysUtils,
FireDAC.Comp.Client;
type
TMyEnum = (eValue1, eValue2, eValue3);
TMyClass = class;
TRecord = record
Provider: TMyClass;
end;
TObject = object
end;
TMyClass = class
end;
TArrayOfString = TArray<string>;
TDrawText = procedure(const Text: UnicodeString) of object;
type
TDataSetProxy = class
end;
TPurchasesDBProxy = class(TDataSetProxy)
end;
TInventoryDBProxy = class(TDataSetProxy)
end;
InjectDBProviderAttribute = class(TCustomAttribute)
constructor Create(const aSQLStatmentName: string);
end;
TLoggingMode = (lmLoggingDisable, lmLoggingActive);
EDataProcessorError = class(Exception)
end;
ILogger = interface
['{4A8D64B3-49E8-4A47-B11C-69F33C4A57C5}']
procedure LogCriticalError(const aMessage: string; aParams: array of const);
procedure LogError(const aMessage: string; aParams: array of const);
procedure LogHint(const aMessage: string; aParams: array of const);
procedure LogInfo(const aMessage: string; aParams: array of const);
end;
IStringProvider = interface
['{4A8D64B3-49E8-4A47-B11C-69F33C4A57C5}']
function TryGetString(const aKey: string; out Content: string): Boolean;
end;
type
TDatabaseJsonProvider = class(TInterfacedObject, IStringProvider)
private
fConnection: TFDConnection;
fSQL: string;
fParams: TArray<Variant>;
public
constructor Create(const aConnection: TFDConnection; const aSQL: string;
const aParams: TArray<Variant>);
function TryGetString(const aKey: string; out aContent: string): Boolean;
end;
implementation
{ ---------------------------------------------------------------------- }
{ InjectDBProviderAttribute }
{ ---------------------------------------------------------------------- }
constructor InjectDBProviderAttribute.Create(const aSQLStatmentName: string);
begin
end;
{ ---------------------------------------------------------------------- }
{ TDatabaseDataProvider }
{ ---------------------------------------------------------------------- }
constructor TDatabaseJsonProvider.Create(const aConnection: TFDConnection;
const aSQL: string; const aParams: TArray<Variant>);
begin
inherited Create;
fConnection := aConnection;
fSQL := aSQL;
fParams := aParams;
end;
function TDatabaseJsonProvider.TryGetString(const aKey: string;
out aContent: string): Boolean;
var
res: Variant;
begin
res := fConnection.ExecSQLScalar(fSQL, fParams);
aContent := '';
Result := not res.IsNull and Trim(aContent) <> '';
end;
end.
|
unit xe_JON01Share;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, MSXML2_TLB,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, xe_JON01N, System.JSON, cxLabel, cxCheckBox, dxAlertWindow,
cxTextEdit, cxMemo, cxButtons, cxDropDownEdit, Vcl.StdCtrls, cxRichEdit, AdvGlowButton, xe_GNL, xe_gnl3,
cxCurrencyEdit, Vcl.Buttons, cxDateUtils, cxSpinEdit, cxTimeEdit, cxCalendar, System.StrUtils,
Vcl.ExtCtrls, cxCustomData, cxGridCustomTableView, dxCore, ActiveX, System.SyncObjs;
procedure pMsnExecute( vMsg : String );
procedure ssSetMessenger( vMessage : String );
procedure GetEnvVarRealKmValue( ATag : Integer; Var vRealKmPtr : TRealKmRecord );
procedure SetEnvVarRealKmValue( ATag : Integer );
function GetEnvHintValue(VarName: string; Frm_JON01N : TFrm_JON01N): string; overload;
procedure SetEnvHintValue(VarName, VarValue: string; Frm_JON01N : TFrm_JON01N); overload;
procedure SetEnvVarClick(VarName : string; Frm_JON01N : TFrm_JON01N); overload;
function fGetFrmCShare(bFirst : Boolean; ATag : Integer; Frm_JON01N : TFrm_JON01N ) : String; overload;
function fGetComNameToCode( AComName : String ) : String;
function fGetCodeToComName( ACode : String ) : String;
function fSet601QRate( ATag : Integer; Frm_JON01N : TFrm_JON01N ) : Boolean; overload;
procedure pSet601QRateSend ( ATag : Integer );
procedure pSet603QRateAnswer( vQ_Rate : TQ_Rate );
procedure pSet606QRateSave( ATag, AIdx : Integer; Frm_JON01N : TFrm_JON01N ); overload;
procedure pSet607QRateDel( ATag, AIdx : Integer; Frm_JON01N : TFrm_JON01N ); overload;
procedure pSet701CShareValue( ATag : Integer; Frm_JON01N : TFrm_JON01N ); overload;
procedure pSet701CShareSend ( ATag : Integer );
procedure pSet703CShareClose( sGubun : String; ATag : Integer; Frm_JON01N : TFrm_JON01N ); overload;
procedure pSet703CShareCloseSend( sGubun : String; ATag : Integer );
procedure pSet708CShareCall(Agbup, Agb, ArKey, AjId, AjNm, ArId, ArNm : String);
procedure pSet705CShareCancel(Agb, ArKey, AjId, ArId : String);
procedure pSet705CShareData(bFirst:Boolean; AgbUp, Agb, ArKey, AjId, ArId : String; ATag : Integer; Frm_JON01N : TFrm_JON01N ); overload;
procedure pSet705CShareClick(Agb, ArKey, AjId, ArId, AClickNm : String; ATag : Integer);
procedure pSet705CShareDataClick(bFirst:Boolean; Agb, ArKey, AjId, ArId, AClickNm : String; ATag : Integer; Frm_JON01N : TFrm_JON01N ); overload;
procedure pSet705CShareClickEvent( AEventName : String; ATag : Integer; Frm_JON01N : TFrm_JON01N ); overload;
procedure pSet706CShareEnd( ArKey, AjId, ArId, AWcl : String);
procedure pSet370FileUpload( AFileName : String );
procedure pSet380ServerSetting( AType, ASsyn, ASset : String );
procedure pGet381ServerSetting;
procedure pSet050CCList( iTag : Integer );
procedure pSetGridCShare( vC_Share : TC_Share );
procedure pCP_702CShareRequest(sData: String);
procedure pCP_704CShareClose(sData: String);
procedure pCP_370Result(sData: String);
procedure pCP_371Result(sData: String);
procedure pCP_381GetServerSetting(ACid, sData: String);
procedure pCP_501Result(sData: String);
procedure pCP_601Result(sData: String);
procedure pCP_801GetBrCash(sData: String);
procedure p801SendBrCash(bError : Boolean; sCash, sDanga: String);
procedure pCP_802SendSMS(sData: String);
procedure p802SendSMSResult( sResult, sMsg: String);
procedure pCP_901Result(sData: String);
procedure p902SendResult( sResult : String);
procedure p903SendMSNAlive;
procedure p999UpLogOut;
procedure pCP_903Result(sData: String);
procedure pCP_013MemoNoticeList(sCmd, sData: String);
procedure pCP_602ChargeRequest(sData: String);
procedure pCP_604ChargeAnswer(sCmd, sData: String);
procedure pSetGridQRate( vQ_Rate : TQ_Rate );
function fFindQRForm(sHint: string): Integer;
function fJsonEncode( sTxt : String ) : String;
function fJsonDecode( sTxt : String ) : String;
procedure pGetMakeHead(var jsoHd: TJSONObject; sId: String);
//๋ฉ๋ด๋ณ ์กฐํ ๋ฆฌ์คํธ์์ ์ ํ ์๋ด์๊ณผ ์ฑํ
procedure p1501SetChat(FrmTag : Integer; sCd, sKey, sId, sNm, sMsg, sFCmd, sFnm, sflId, sflNm : String; bFirst : Boolean = False);
//์ฑํ
์ฐฝ์์ ์ ์๋ฒํธ ํด๋ฆญ์ ์กฐํ์ฐฝ ์คํ
procedure pCP_711Result(sData: String); //p711OPENJON01N
Var
gvComShare : array[0..103] of String; // ์ด์ ์๋ฃ ์ ์ฅ ๋น๊ตํ ํ๋ฆฐ๊ฒ๋ง ์ ์ก ์ฒ๋ฆฌ ์ํด
gvVarShare : array[0..92] of String;
gvHintShare : array[0..4] of String;
gsOrderClick : String;
fAlertWindow: TdxAlertWindow;
const
cQUOTATION_MARK = '"'; // jsonํน์๋ฌธ์ ์ฌ์ฉ(")๋ณํ ๋ณ์
ComShare : array[0..103] of String = (
'cxtCuTel',
'cxtCallTelNum',
'cxtWorkerNm',
'cxtJoinNum',
'cxtCuTel2',
'cxBtnHoTrans',
'cboBrOnly',
'cboBranch',
'cxTSearchMainTel',
'btnBubinSch',
'CbCuGb',
'cboCuLevel',
'ChkCuSmsNo',
'cxBtnSpSave',
'cxBtnCuUpdate',
'cxBtnCuDel',
'btnCMenu',
'cxLblCuLevel',
'cxtCuBubin',
'edtCuName',
'lblMoCuMile',
'lblCuMile',
'lblCuMileCnt',
'lblCuMileUnit',
'chkCenterMng',
'lblCoCntTotal',
'lblCuCancelR',
'lblCuCntTotal',
'chkViewLevel',
'edt_CardMemo',
'meoCuCCMemo',
'meoCuWorMemo',
'mmoCbMemo',
'btnStartLocalSave',
'cb_00',
'cb_01',
'cb_02',
'cb_03',
'cb_04',
'cb_05',
'cb_06',
'cbbLicType',
'BtnStLock',
'meoStartArea',
'lblStartAreaName',
'cxtStartAreaDetail',
'cxtStartXval',
'cxtStartYval',
'cxtStartGUIDEXval',
'cxtStartGUIDEYval',
'BtnEdLock',
'meoEndArea',
'cxReEndArea',
'lblEndAreaName',
'cxtEndAreaDetail',
'cxtEndXval',
'cxtEndYval',
'cxtEndGUIDEXval',
'cxtEndGUIDEYval',
'BtnCenterMng',
'BtnOptionCallMu',
'BtnOptionSexF',
'BtnOptionSexM',
'BtnPlusYN',
'BtnWkAge',
'BtnWKJAmt',
'cbbPayMethod',
'cbbPostTime',
'chkNoSet',
'chkRangeRate',
'curKm',
'curRate',
'cxDriverCharge',
'cxLblRate1',
'cxLblRate2',
'cxLblSmartRate',
'edtPostPay',
'cxCurPathRate',
'cxCurRevisionRate',
'cxCurWaitTmRate',
'cxTBubinMemo',
'cxTmWaitTime',
'edtWkFAge',
'edtWkTAge',
'BtnResD',
'BtnResJ',
'CbSecond',
'cxlblState',
'dtpResvDate',
'dtpResvTime',
'meoBigo',
'meoBigo2',
'meoBigo3',
'Lbl_charge',
'Lbl_Distance',
'lbl_PlusAreaNotice',
// 'btnCmdExit',
// 'btnCmdJoin',
// 'btnCmdJoinCopy',
// 'btnCmdMultiCall',
// 'btnCmdNoSMS',
// 'btnCmdQuestion',
// 'btnCmdUpdSave',
// 'btnCmdWait',
// 'btnCmdWaitCopy',
// 'btnPickupInsert',
'meoViaArea1',
'cxViaAreaName1',
'lbl_wk_1',
'lbl_wk_2',
'lbl_wk_3',
'lbl_wk_4',
'lbl_wk_5',
'lbl_wk_6'
// 'mmoCuInfo'
);
const
VarShare : array[0..92] of String = (
'gsCuTelHint',
'sTaksong',
'sStickCall',
'lcsCu_seq',
'sCust_Gubun',
'locLogSeq',
'wk_sabun', // ๊ณผ๊ฑฐ์ด์ฉ๋ด์ญ ๊ธฐ์ฌ์ ๋ณด ์กฐํ
'sFinishCnt',
'sCancelCnt',
'sPhone_info',
'locHDNO',
'locBRNO',
'locKNum',
'locDNIS',
'locSndTime',
'locAutoCallYn',
// 'gsInternalNumber', // ๋ด์ ๋ฒํธ์ ์ญ๋ณ์. ์๋๋ฐฉ๋ด์ ๋ฒํธ๋ก ๋ณ๊ฒฝ๋จ. ๋ถํ์
'locCardPaySeq',
'locCardTranNo',
'locCardPayInfo',
'sAppCode',
'lcsSta1',
'lcsSta2',
'lcsSta3',
'lcsStaDocId',
'lcsStaCellSel',
'lcsStaSchWord',
'lcsStaUrl',
'lcsStaDebug',
'GS_Grid_DES',
'gJONStaChkXY.X',
'gJONStaChkXY.Y',
'lcsEnd1',
'lcsEnd2',
'lcsEnd3',
'lcsEndDocId',
'lcsEndCellSel',
'lcsEndSchWord',
'lcsEndUrl',
'lcsEndDebug',
'GS_Grid_DEP',
'fCruKm',
'fChgKm',
'fDirKm',
'fTotalTime',
'fViaKm',
'fStEdKm',
'ABubinStateIndex',
// 'GS_JON_AutoStandBy', // ์ฝ๋ง๋ ๊ณณ์์ ์ ์ฅ์ ํ๋ฏ๋ก ์ ๋ฌ ํ์ ์์
// 'gsCidVersion', // ์ฝ๋ง๋ ๊ณณ์์ ์ ์ฅ์ ํ๋ฏ๋ก ์ ๋ฌ ํ์ ์์
'GT_DISTANCE_ST',
'FcnhDongCHK',
'FPlusDongCHK',
'FPlusDongName',
'pnl_wk_list',
'pnl_charge',
'gbRQAList',
'meoViaArea2',
'meoViaArea3',
'meoViaArea4',
'meoViaArea5',
'cxViaAreaName2',
'cxViaAreaName3',
'cxViaAreaName4',
'cxViaAreaName5',
'ViaNowTag',
'ViaAddTag',
'ViaSA1',
'ViaSA2',
'ViaSA3',
'ViaAreaDetail',
'ViaAreaName',
'DocId',
'CellSel',
'SchWord',
'XposVia',
'YposVia',
'GUIDE_X',
'GUIDE_Y',
// -- RealKmRecord
'RKR_StartAreaName',
'RKR_StartXVal',
'RKR_StartYVal',
'RKR_EndAreaName',
'RKR_EndXVal',
'RKR_EndYVal',
'RKR_ViaXVal',
'RKR_ViaYVal',
// --- Color
'PnlOCC',
'cxLblCuLevel',
'pnlMileage',
// -- ๊ถํ
'edt_CardMemo',
'miCustAdd',
'cboCuLevel',
'BtnOptionCallMu',
'giArea_Charge_YN',
'btn_ChargeSave'
);
const
HintShare : array[0..4] of String = (
'cxLblCIDUseFlg',
'cxtCuBubin',
'btnCmdJoinCopy',
'btnCmdWaitCopy',
'btnCmdExit'
);
const
ClickShare : array[0..2] of String = (
'BtnViaAdd',
'BtnViaMinus1',
'cbCardSanction'
);
const
Com34Share : array[0..26] of String = (
'medCardNum',
'medtCashCardNum',
'medtCouponNum',
'medLimiteDate',
'cxCurDRate',
'cxCurDecRate',
'cxCurDecRate_Cash',
'cxCurDec_Coupon',
'cxCurDec_Coupon1',
'cxCurDecRate_Coupon',
'lbResultMsg',
'cxCurTerm',
'chk_BaRo_Card',
'rg_charge_ser1',
'rg_charge_ser2',
'lblPaySeq',
'lblTranNo',
'lblPaySeq_Cash',
'lblTranNo_Cash',
'lblPaySeq_Coupon',
'lblCardStatus',
'lblCardStatus_Cash',
'lblCouponStatus',
'sb_ApproveReq',
'sb_ApproveOK',
'sb_ApproveCancle',
'sb_ApproveReceipt'
);
const
Var34Share : array[0..8] of String = (
'lcBRNO',
'lcMainNum',
'lcCustTel',
'lcCustSeq',
'lcPaySeq',
'lcTranNo',
'lcPaySite',
'Card_Gubun',
'lcJON_IDX'
);
implementation
uses xe_gnl2, Main, xe_Func, xe_Msg, xe_JON012,
xe_CUT011, xe_Jon015, xe_JON30S, xe_JON56, xe_JON019, xe_JON30,
xe_SETA1, xe_JON24, xe_packet, xe_xml, xe_Query, xe_Dm, xe_JON23, xe_COM50,
xe_UpdateBox;
// JSON๋ช
๋ น์ด๊ฐ ์ฌ๋ฌ๊ฑด์ด ๋์์ ๋ค์ด์ฌ์๋ ์์ด์..๋ถ๋ฆฌ์ฒ๋ฆฌ
procedure pMsnExecute( vMsg : String );
Var iPos : Integer;
sSendData : String;
bOk : Boolean;
begin
gsMessengerData := '';
vMsg := StringReplace(vMsg, STX, '', [rfReplaceAll]);
vMsg := StringReplace(vMsg, ETX, '', [rfReplaceAll]);
SetDebugeWrite('Share.pMsnExecute Read : ' + vMsg);
// vMsg := '{"hdr":{"seq":"41","cmd":"705"},"bdy":{"ckey":"a1a1a120170406104050","jid":"a1a1a1","rid":"sntest","ogb":"j","ogbup":"n","jtype":"2","ls":['+
// '{"io":"TcxTextEdit","in":"cxtCuTel","ic":"010111111"},{"io":"TcxTextEdit","in":"cxtCallTelNum","ic":"010111111"},{"io":"TcxComboBox","in":"cboCuLevel","ic":"0"}'+
// ',{"io":"TLabel","in":"lblCuMileCnt","ic":"0"},{"io":"TLabel","in":"lblCoCntTotal","ic":"3"},{"io":"TLabel","in":"lblCuCancelR","ic":"95%"}'+
// ',{"io":"TLabel","in":"lblCuCntTotal","ic":"63"},{"io":"TcxRichEdit","in":"lblStartAreaName","ic":" "},{"io":"TcxRichEdit","in":"cxReEndArea","ic":" "}'+
// ',{"io":"TcxLabel","in":"lblEndAreaName","ic":" "},{"io":"Variables","in":"gsCuTelHint","ic":"010111111"},{"io":"Variables","in":"lcsCu_seq","ic":"39905591"}'+
// ',{"io":"Variables","in":"PnlOCC","ic":"$00FFFF80"},{"io":"Variables","in":"pnlMileage","ic":"$00FFFF80"}]}}{"hdr":{"seq":"38","cmd":"704"}'+
// ',"bdy":{"rkey":"hd222220170406104124","uid":"hd2222","unm":"์ด๋ช
์ฌ","cuhp":"01044444","clgb":"Z"}}';
bOk := False;
while Not bOk do
begin
iPos := Pos('}}{"', vMsg);
if iPos > 0 then
begin
sSendData := Copy(vMsg, 1, iPos + 1);
ssSetMessenger( sSendData );
vMsg := Copy(vMsg, iPos + 2, ( Length(vMsg) - (iPos + 2) + 1));
end else
begin
ssSetMessenger( vMsg );
bOk := True;
end;
end;
end;
procedure ssSetMessenger( vMessage : String );
var
sCmd, sTmp : String;
jsoRlt : TJSONObject;
begin
SetDebugeWrite('Share.ssSetMessenger Read : ' + vMessage);
if Trim(vMessage) = '' then Exit;
try
try
vMessage := StringReplace(vMessage, '\', '\\', [rfReplaceAll]); { \(backSlash) Parse Error ์ฒ๋ฆฌ2020.05.18 LYB }
jsoRlt := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(vMessage), 0) as TJSONObject;
sTmp := jsoRlt.Get('hdr').JsonValue.ToString;
jsoRlt := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(jsoRlt.Get('hdr').JsonValue.ToString), 0) as TJSONObject;
sCmd := jsoRlt.Get('cmd').JsonValue.Value;
// ์ ๊ท์ ์๊ณต์ ๊ธฐ๋ฅ ์ฌ์ฉ์ํ ๊ฒฝ์ฐ ํจ์ค
if ( GB_NS_NOACCEPTSHARE ) And ( (sCmd = '702') Or (sCmd = '704') ) then Exit;
jsoRlt := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(vMessage), 0) as TJSONObject;
{ TODO : 013.๊ณต์ง๋ฆฌ์คํธ, 503.๊ณต์ง }
if ( sCmd = '013' ) Or ( sCmd = '503' ) then pCP_013MemoNoticeList(sCmd, jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 501.์๋ด์๊ณต์ง๋ฑ๋ก, 050.์์
์ง์ํ๋ฆฌ์คํธ }
if ( sCmd = '501' ) Or ( sCmd = '050' ) then pCP_501Result(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 601.์๊ธ๋ฌธ์๋ฑ๋ก }
if ( sCmd = '601' ) then pCP_601Result(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 602.์๊ธ๋ฌธ์์ ํ }
if ( sCmd = '602' ) then pCP_602ChargeRequest(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 603.์๊ธ๋ต๋ณ, 605.์๋๋ต๋ณ }
if ( sCmd = '604' ) Or ( sCmd = '605' ) then pCP_604ChargeAnswer(sCmd, jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 702.์ ๊ท์ฝ๋ง์ฐฝ์ ์ ์ ์ ๋ณด์ ํ }
if ( sCmd = '702' ) then pCP_702CShareRequest(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 704.์ ๊ท์ฝ๋ง์ฐฝ์ ์ ์์๋ฃ/๋ซ์ ์ ๋ณด์ ํ }
if ( sCmd = '704' ) then pCP_704CShareClose(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 711.์ฑํน์ฐฝ์์ ์กฐํ(์์ )์ฐฝ ํด๋ฆญ ์คํ}
if ( sCmd = '711' ) then pCP_711Result(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 801.SMS ์ง์ฌ ์บ์ ์์ก ์กฐํ }
if ( sCmd = '801' ) then pCP_801GetBrCash(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 802.SMS ์ ์ก }
if ( sCmd = '802' ) then pCP_802SendSMS(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 901.์ฝ๋ง๋ ํ๋ก๊ทธ๋จ ์
๋ฐ์ดํธ ์ฌ๋ถ }
if ( sCmd = '901' ) then pCP_901Result(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 903.์ฝ๋ง๋ ๋ฉ์ ์ ์ํ ์ฒดํฌ(y:๋ฉ์ ์ ์ ์, n:๋ฉ์ ์ ์ข
๋ฃ(์
๋ฐ์ดํธ๋ง์ฒดํฌ)) }
if ( sCmd = '903' ) then pCP_903Result(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 998.Heart Bit }
if ( sCmd = '998' ) then Exit else
{ TODO : 370.FileUpload ์ ์ก ๊ฒฐ๊ณผ }
if ( sCmd = '370' ) then pCP_370Result(jsoRlt.Get('bdy').JsonValue.ToString ) else
{ TODO : 380.์๋ด์ ์๋ฒ ์ค์ ๊ฐ ์กฐํ }
if ( sCmd = '380' ) Or ( sCmd = '381' ) then pCP_381GetServerSetting(sCmd, jsoRlt.Get('bdy').JsonValue.ToString );
except on e: Exception do
begin
Assert(False, 'RecvData Parse Error : ' + vMessage + ' - ' + e.Message);
end;
end;
finally
FreeAndNil(jsoRlt);
end;
end;
procedure GetEnvVarRealKmValue( ATag : Integer; Var vRealKmPtr : TRealKmRecord );
begin
try
if RealKmPtr_th1[ATag].UseYn then vRealKmPtr := RealKmPtr_th1[ATag];
if RealKmPtr_th2[ATag].UseYn then vRealKmPtr := RealKmPtr_th2[ATag];
if RealKmPtr_th3[ATag].UseYn then vRealKmPtr := RealKmPtr_th3[ATag];
if RealKmPtr_th4[ATag].UseYn then vRealKmPtr := RealKmPtr_th4[ATag];
except
end;
end;
procedure SetEnvVarRealKmValue( ATag : Integer );
begin
try
RealKmPtr_th1[ATag].UseYn := True;
RealKmPtr_th2[ATag].UseYn := False;
RealKmPtr_th3[ATag].UseYn := False;
RealKmPtr_th4[ATag].UseYn := False;
except
end;
end;
function GetEnvHintValue(VarName: string; Frm_JON01N : TFrm_JON01N): string;
begin
if VarName = 'cxLblCIDUseFlg' then Result := Trim(Frm_JON01N.cxLblCIDUseFlg.Hint) else
if VarName = 'cxtCuBubin' then Result := Trim(Frm_JON01N.cxtCuBubin.Hint);
end;
procedure SetEnvHintValue(VarName, VarValue: string; Frm_JON01N : TFrm_JON01N);
begin
if VarName = 'cxLblCIDUseFlg' then Frm_JON01N.cxLblCIDUseFlg.Hint := Trim(VarValue) else
if VarName = 'cxtCuBubin' then Frm_JON01N.cxtCuBubin.Hint := Trim(VarValue);
end;
procedure SetEnvVarClick(VarName : string; Frm_JON01N : TFrm_JON01N);
begin
// if VarName = 'BtnViaAdd' then Frm_JON01N.BtnViaAdd.Click else
// if VarName = 'BtnViaMinus1' then Frm_JON01N.BtnViaMinus1.Click else
// if VarName = 'BtnViaMinus2' then Frm_JON01N.BtnViaMinus[2].Click else
// if VarName = 'BtnViaMinus3' then Frm_JON01N.BtnViaMinus[3].Click else
// if VarName = 'BtnViaMinus4' then Frm_JON01N.BtnViaMinus[4].Click else
// if VarName = 'BtnViaMinus5' then Frm_JON01N.BtnViaMinus[5].Click else
// if VarName = 'cbCardSanction' then Frm_JON01N.cbCardSanction.Click else
// if VarName = 'btnCmdNoSMS' then Frm_JON01N.btnCmdNoSMS.Click else
// if VarName = 'btnPickupInsert' then Frm_JON01N.btnPickupInsert.Click else
// if VarName = 'btnCmdJoinCopy' then Frm_JON01N.btnCmdJoinCopy.Click else
// if VarName = 'btnCmdWaitCopy' then Frm_JON01N.btnCmdWaitCopy.Click else
// if VarName = 'btnCmdJoin' then Frm_JON01N.btnCmdJoin.Click else
// if VarName = 'btnCmdWait' then Frm_JON01N.btnCmdWait.Click else
// if VarName = 'btnCmdQuestion' then Frm_JON01N.btnCmdQuestion.Click else
// if VarName = 'btnCmdExit' then Frm_JON01N.btnCmdExit.Click else
// if VarName = 'BtnResvView' then Frm_JON01N.BtnResvView.Click else
// if VarName = 'BtnResv' then Frm_JON01N.BtnResv.Click else
// if VarName = 'BtnResvCsl' then Frm_JON01N.BtnResvCsl.Click else
// if VarName = 'BtnResvClose' then Frm_JON01N.BtnResvClose.Click else
// if VarName = 'btnSViewMap' then Frm_JON01N.AddSpop('์ถ๋ฐ์ง ์ง๋๋ณด๊ธฐ', 0) else
// if VarName = 'btnViewMap' then Frm_JON01N.btnViewMap.Click else
// if VarName = 'BtnSR' then Frm_JON01N.BtnSR.Click else
// if VarName = 'btnRQALExit' then Frm_JON01N.btnRQALExit.Click else
// if VarName = 'BtnQRate' then Frm_JON01N.RQAListView.DataController.SetRecordCount(0) else
// if VarName = 'btnDCalc' then Frm_JON01N.btnDCalc.Click else
// if VarName = 'BtnWkAgeDown' then
// begin
// Frm_JON01N.BtnWkAge.Down := True;
// Frm_JON01N.BtnWkAge.Click;
// end else
// if VarName = 'BtnWkAgeUp' then
// begin
// Frm_JON01N.BtnWkAge.Down := False;
// Frm_JON01N.BtnWkAge.Click;
// end else
// if VarName = 'btnWkAgeClose' then Frm_JON01N.btnWkAgeClose.Click else
// if VarName = 'BtnSmartRate' then Frm_JON01N.BtnSmartRate.Click else
// if VarName = 'btnSClose' then Frm_JON01N.btnSClose.Click else
// if VarName = 'btnEClose' then Frm_JON01N.btnEClose.Click else
// if VarName = 'GBStartXYView' then Frm_JON01N.GBStartXYView.Visible := True else
// if VarName = 'GBEndXYView' then Frm_JON01N.GBEndXYView.Visible := True;
end;
function fGetFrmCShare(bFirst : Boolean; ATag : Integer; Frm_JON01N : TFrm_JON01N ) : String;
Var i, j : Integer;
sValue : String;
subObj : TJSONObject;
jso : TJSONObject;
jsoAry : TJSONArray;
begin
with Frm_JON01N do
begin
subObj := TJSONObject.Create;
try
jsoAry := TJSONArray.Create;
for i := 0 to Length(ComShare) - 1 do
begin
if Not Assigned(FindComponent(ComShare[i])) then Continue;
for j := 0 to ComponentCount - 1 do
begin
try
if Components[j].Name = FindComponent(ComShare[i]).Name then
begin
if Components[j] is TPanel then
begin
sValue := (Components[j] as TPanel).Caption;
end else
if Components[j] is TLabel then
begin
sValue := (Components[j] as TLabel).Caption;
end else
if Components[j] is TEdit then
begin
sValue := (Components[j] as TEdit).Text;
end else
if Components[j] is TcxLabel then
begin
sValue := (Components[j] as TcxLabel).Caption;
end else
if Components[j] is TcxCheckBox then
begin
if (Components[j] as TcxCheckBox).Checked then sValue := '1'
else sValue := '0';
end else
if Components[j] is TcxTextEdit then
begin
sValue := (Components[j] as TcxTextEdit).Text;
end else
if Components[j] is TcxMemo then
begin
sValue := (Components[j] as TcxMemo).Text;
end else
if Components[j] is TcxRichEdit then
begin
sValue := (Components[j] as TcxRichEdit).Text;
end else
if Components[j] is TcxCurrencyEdit then
begin
sValue := (Components[j] as TcxCurrencyEdit).Text;
end else
if Components[j] is TcxDateEdit then
begin
sValue := (Components[j] as TcxDateEdit).Text;
end else
if Components[j] is TcxTimeEdit then
begin
sValue := (Components[j] as TcxTimeEdit).Text;
end else
if Components[j] is TcxSpinEdit then
begin
sValue := (Components[j] as TcxSpinEdit).Value;
end else
if Components[j] is TcxButton then
begin
if (Components[j] as TcxButton).Enabled then sValue := '1'
else sValue := '0';
end else
if Components[j] is TcxComboBox then
begin
sValue := IntToStr((Components[j] as TcxComboBox).ItemIndex);
end else
if Components[j] is TAdvGlowButton then
begin
if (Components[j] as TAdvGlowButton).Down then sValue := '1'
else sValue := '0';
end else
if Components[j] is TSpeedButton then
begin
if (Components[j] as TSpeedButton).Down then sValue := '1'
else sValue := '0';
end;
if Trim(gvComShare[i]) <> sValue then
begin
gvComShare[i] := sValue;
jso := TJSONObject.Create;
jso.AddPair(TJsonPair.Create('io', fGetComNameToCode(Components[j].ClassName)));
jso.AddPair(TJsonPair.Create('in', Components[j].Name));
jso.AddPair(TJsonPair.Create('ic', sValue));
jsoAry.AddElement(jso);
end;
Break;
end;
except
end;
end;
end;
for i := 0 to Length(VarShare) - 1 do
begin
if ( VarShare[i] = 'ViaAddTag' ) And Not bFirst then Continue;
// sValue := GetEnvVarValue(VarShare[i], ATag, Frm_JON01N);
if Trim(gvVarShare[i]) <> sValue then
begin
gvVarShare[i] := sValue;
jso := TJSONObject.Create;
jso.AddPair(TJsonPair.Create('io', fGetComNameToCode('Variables')));
jso.AddPair(TJsonPair.Create('in', VarShare[i]));
jso.AddPair(TJsonPair.Create('ic', sValue));
jsoAry.AddElement(jso);
end;
end;
for i := 0 to Length(HintShare) - 1 do
begin
sValue := GetEnvHintValue(HintShare[i], Frm_JON01N);
if Trim(gvHintShare[i]) <> sValue then
begin
gvHintShare[i] := sValue;
jso := TJSONObject.Create;
jso.AddPair(TJsonPair.Create('io', fGetComNameToCode('Hint')));
jso.AddPair(TJsonPair.Create('in', HintShare[i]));
jso.AddPair(TJsonPair.Create('ic', sValue));
jsoAry.AddElement(jso);
end;
end;
subObj.AddPair( TJSONPair.Create('ls', jsoAry));
Result := subObj.Get('ls').JsonValue.ToString
finally
FreeAndNil(subObj);
end;
end;
end;
function fGetComNameToCode( AComName : String ) : String; // 705์ ๋ฌธ ์ฌ์ด์ฆ ์ค์ด๊ธฐ ์ํด ์ฝ๋๋ก ์ ์ ์ฌ์ฉ
begin
try
if AComName = 'TPanel' then Result := '01' else
if AComName = 'TLabel' then Result := '02' else
if AComName = 'TEdit' then Result := '03' else
if AComName = 'TcxLabel' then Result := '04' else
if AComName = 'TcxCheckBox' then Result := '05' else
if AComName = 'TcxTextEdit' then Result := '06' else
if AComName = 'TcxMemo' then Result := '07' else
if AComName = 'TcxRichEdit' then Result := '08' else
if AComName = 'TcxCurrencyEdit' then Result := '09' else
if AComName = 'TcxDateEdit' then Result := '10' else
if AComName = 'TcxTimeEdit' then Result := '11' else
if AComName = 'TcxSpinEdit' then Result := '12' else
if AComName = 'TcxButton' then Result := '13' else
if AComName = 'TcxComboBox' then Result := '14' else
if AComName = 'TAdvGlowButton' then Result := '15' else
if AComName = 'TSpeedButton' then Result := '16' else
if AComName = 'Variables' then Result := '50' else
if AComName = 'Hint' then Result := '51' else
if AComName = 'ClickEvent' then Result := '52';
except
Result := '99';
end;
end;
function fGetCodeToComName( ACode : String ) : String;
begin
try
if ACode = '01' then Result := 'TPanel' else
if ACode = '02' then Result := 'TLabel' else
if ACode = '03' then Result := 'TEdit' else
if ACode = '04' then Result := 'TcxLabel' else
if ACode = '05' then Result := 'TcxCheckBox' else
if ACode = '06' then Result := 'TcxTextEdit' else
if ACode = '07' then Result := 'TcxMemo' else
if ACode = '08' then Result := 'TcxRichEdit' else
if ACode = '09' then Result := 'TcxCurrencyEdit' else
if ACode = '10' then Result := 'TcxDateEdit' else
if ACode = '11' then Result := 'TcxTimeEdit' else
if ACode = '12' then Result := 'TcxSpinEdit' else
if ACode = '13' then Result := 'TcxButton' else
if ACode = '14' then Result := 'TcxComboBox' else
if ACode = '15' then Result := 'TAdvGlowButton' else
if ACode = '16' then Result := 'TSpeedButton' else
if ACode = '50' then Result := 'Variables' else
if ACode = '51' then Result := 'Hint' else
if ACode = '52' then Result := 'ClickEvent';
except
Result := '';
end;
end;
function fSet601QRate( ATag : Integer; Frm_JON01N : TFrm_JON01N ) : Boolean;
Var sVia : String;
i, lRow, iRow, iSta, iStaddr, iVia, iEda, iEdaddr, irKey : Integer;
begin
SetDebugeWrite('Frm_JON01N.pSet601QRate');
if Frm_Main.JON01MNG[ATag].rKey = '' then
begin
GMessageBox('๊ณ ๊ฐ ๊ฒ์ ํ ์๊ธ ๋ฌธ์ ๋ฐ๋๋๋ค.', CDMSE);
Result := False;
Exit;
end;
try
with Frm_JON01N do
begin
if (cxtStartYval.Text = '') then
begin
GMessageBox('์ถ๋ฐ์ง๋ฅผ ๊ฒ์ํด์ผ ์๊ธ ๋ฌธ์๊ฐ ๊ฐ๋ฅํฉ๋๋ค.', CDMSE);
Result := False;
Exit;
end;
if (cxtEndYval.Text = '') then
begin
GMessageBox('๋์ฐฉ์ง๋ฅผ ๊ฒ์ํด์ผ ์๊ธ ๋ฌธ์๊ฐ ๊ฐ๋ฅํฉ๋๋ค.', CDMSE);
Result := False;
Exit;
end;
iSta := Frm_Main.cxGridQRate.GetColumnByFieldName('์ถ๋ฐ์ง').Index;
iStaddr := Frm_Main.cxGridQRate.GetColumnByFieldName('์ถ๋ฐ์ง์ฃผ์').Index;
iVia := Frm_Main.cxGridQRate.GetColumnByFieldName('๊ฒฝ์ ์ง').Index;
iEda := Frm_Main.cxGridQRate.GetColumnByFieldName('๋์ฐฉ์ง').Index;
iEdaddr := Frm_Main.cxGridQRate.GetColumnByFieldName('๋์ฐฉ์ง์ฃผ์').Index;
lRow := 0;
sVia := '';
while lRow <= 4 do
begin
if GT_PASS_INFO[ATag][lRow].AREA1 = '' then break;
if sVia = '' then
sVia := En_Coding(GT_PASS_INFO[ATag][lRow].AREA4)
else
sVia := sVia + '/' + En_Coding(GT_PASS_INFO[ATag][lRow].AREA4);
inc(lRow);
end;
if gsrKey = '' then
begin
gsrKey := GT_USERIF.ID + FormatDateTime('yyyymmddhhmmss', Now);
end else
begin
irKey := Frm_Main.cxGridQRate.GetColumnByFieldName('rkey').Index;
iRow := Frm_Main.cxGridQRate.DataController.FindRecordIndexByText(0, irKey, gsrKey, False, True, True);
if iRow < 0 then
begin
gsrKey := GT_USERIF.ID + FormatDateTime('yyyymmddhhmmss', Now);
end else
begin
if ( Frm_Main.cxGridQRate.DataController.Values[iRow, iSta] <> Trim(meoStartArea.Text) ) Or
( Frm_Main.cxGridQRate.DataController.Values[iRow, iStaddr] <> (lcsSta1 +' '+ lcsSta2 +' '+ lcsSta3) ) Or
( Frm_Main.cxGridQRate.DataController.Values[iRow, iVia] <> Trim(sVia) ) Or
( Frm_Main.cxGridQRate.DataController.Values[iRow, iEda] <> Trim(meoEndArea.Text) ) Or
( Frm_Main.cxGridQRate.DataController.Values[iRow, iEdaddr] <> (lcsEnd1 +' '+ lcsEnd2 +' '+ lcsEnd3) ) then
begin
gsrKey := GT_USERIF.ID + FormatDateTime('yyyymmddhhmmss', Now);
end;
end;
end;
GQ_Rate[ATag].cmd := '601';
GQ_Rate[ATag].rkey := gsrKey;
GQ_Rate[ATag].uid := GT_USERIF.ID;
GQ_Rate[ATag].unm := GT_USERIF.NM;
GQ_Rate[ATag].brno := Proc_BRNOSearch; // ์ง์ฌ์ฝ๋
GQ_Rate[ATag].cuhp := IfThen(0 >= Pos('*', cxtCuTel.Text), cxtCallTelNum.Text, locsCuTel); // ๊ณ ๊ฐ์ ํ๋ฒํธ
GQ_Rate[ATag].brKeyNum := cxTxtBrNameCaption.Text;
GQ_Rate[ATag].corpnm := Copy(gsShortCoprNm[ATag], 1, pos('|', gsShortCoprNm[ATag])-1);
GQ_Rate[ATag].corpdepnm := Copy(gsShortCoprNm[ATag], pos('|', gsShortCoprNm[ATag])+1, Length(gsShortCoprNm[ATag])-pos('|', gsShortCoprNm[ATag]));
GQ_Rate[ATag].sta := Trim(meoStartArea.Text);
GQ_Rate[ATag].staddr := lcsSta1 +','+ lcsSta2 +','+ lcsSta3;
GQ_Rate[ATag].via := Trim(sVia);
GQ_Rate[ATag].eda := Trim(meoEndArea.Text);
GQ_Rate[ATag].edaddr := lcsEnd1 +','+ lcsEnd2 +','+ lcsEnd3;
GQ_Rate[ATag].distance := curKm.Text;
if fViaKm > 0 then
GQ_Rate[ATag].ViaDist := FloatToStr(fViaKm) + 'Km';
GQ_Rate[ATag].rate := curRate.Value;
GQ_Rate[ATag].qtm := FormatDateTime('yyyy-mm-dd hh:mm:ss', Now);
GQ_Rate[ATag].aid := '';
GQ_Rate[ATag].anm := '';
GQ_Rate[ATag].arate := '0';
GQ_Rate[ATag].amsg := '';
GQ_Rate[ATag].atm := '';
GQ_Rate[ATag].crkey := Frm_Main.JON01MNG[ATag].rKey;
GQ_Rate[ATag].StaX := gsStartGUIDEXval;
GQ_Rate[ATag].StaY := gsStartGUIDEYval;
for i := 0 to 4 do
begin
if i = 0 then
begin
GQ_Rate[ATag].ViaX := GT_PASS_INFO[ATag][i].MAP_X;
GQ_Rate[ATag].ViaY := GT_PASS_INFO[ATag][i].MAP_Y;
end else
begin
GQ_Rate[ATag].ViaX := GQ_Rate[ATag].ViaX + '|' + GT_PASS_INFO[ATag][i].MAP_X;
GQ_Rate[ATag].ViaY := GQ_Rate[ATag].ViaY + '|' + GT_PASS_INFO[ATag][i].MAP_Y;
end;
end;
GQ_Rate[ATag].EndX := gsEndGUIDEXval;
GQ_Rate[ATag].EndY := gsEndGUIDEYval;
end;
pSet601QRateSend(ATag);
Result := True;
except
Result := False;
end;
end;
procedure pSet601QRateSend ( ATag : Integer );
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// ๋ด์ญ๋ณ๊ฒฝ์ด ์์ด๋ ์๊ธ๋ฌธ์ ์ฒ๋ฆฌ 20200626 ์ฒ์ฌ๋๋ฆฌ ์์ฒญ
// if ( GQ_PRate[ATag].sta = GQ_Rate[ATag].sta ) And
// ( GQ_PRate[ATag].staddr = GQ_Rate[ATag].staddr ) And
// ( GQ_PRate[ATag].via = GQ_Rate[ATag].via ) And
// ( GQ_PRate[ATag].eda = GQ_Rate[ATag].eda ) And
// ( GQ_PRate[ATag].edaddr = GQ_Rate[ATag].edaddr ) And
// ( GQ_PRate[ATag].rate = GQ_Rate[ATag].rate ) then Exit;
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '601'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('rkey' , GQ_Rate[ATag].rKey));
subObj.AddPair( TJSONPair.Create('uid' , GQ_Rate[ATag].Uid));
subObj.AddPair( TJSONPair.Create('unm' , fJsonEncode(GQ_Rate[ATag].unm)));
subObj.AddPair( TJSONPair.Create('brno' , GQ_Rate[ATag].brno));
subObj.AddPair( TJSONPair.Create('cuhp' , GQ_Rate[ATag].cuhp));
subObj.AddPair( TJSONPair.Create('brkeynum' , GQ_Rate[ATag].brKeyNum));
subObj.AddPair( TJSONPair.Create('corpnm' , GQ_Rate[ATag].corpnm));
subObj.AddPair( TJSONPair.Create('corpdepnm', GQ_Rate[ATag].corpdepnm));
subObj.AddPair( TJSONPair.Create('sta' , fJsonEncode(GQ_Rate[ATag].sta)));
subObj.AddPair( TJSONPair.Create('staddr' , GQ_Rate[ATag].staddr));
subObj.AddPair( TJSONPair.Create('via' , fJsonEncode(GQ_Rate[ATag].via)));
subObj.AddPair( TJSONPair.Create('eda' , fJsonEncode(GQ_Rate[ATag].eda)));
subObj.AddPair( TJSONPair.Create('edaddr' , GQ_Rate[ATag].edaddr));
subObj.AddPair( TJSONPair.Create('distance' , GQ_Rate[ATag].distance));
subObj.AddPair( TJSONPair.Create('viadist' , GQ_Rate[ATag].Viadist));
subObj.AddPair( TJSONPair.Create('rate' , GQ_Rate[ATag].rate));
subObj.AddPair( TJSONPair.Create('qtm' , GQ_Rate[ATag].qtm));
subObj.AddPair( TJSONPair.Create('crkey' , GQ_Rate[ATag].crkey));
subObj.AddPair( TJSONPair.Create('jtype' , GQ_Rate[ATag].jtype));
subObj.AddPair( TJSONPair.Create('stax' , GQ_Rate[ATag].StaX));
subObj.AddPair( TJSONPair.Create('stay' , GQ_Rate[ATag].StaY));
subObj.AddPair( TJSONPair.Create('viax' , GQ_Rate[ATag].ViaX));
subObj.AddPair( TJSONPair.Create('viay' , GQ_Rate[ATag].ViaY));
subObj.AddPair( TJSONPair.Create('endx' , GQ_Rate[ATag].EndX));
subObj.AddPair( TJSONPair.Create('endy' , GQ_Rate[ATag].EndY));
jsoRlt.AddPair( TJSONPair.Create('bdy' , subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
GQ_PRate[ATag] := GQ_Rate[ATag];
GS_RQ_SENDCRKEY := GQ_Rate[ATag].crkey;
end;
Frm_Main.cxPageControl2.ActivePageIndex := 3;
pSetGridQRate(GQ_Rate[ATag]);
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pSet603QRateAnswer( vQ_Rate : TQ_Rate );
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '603'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('rkey', vQ_Rate.rkey));
subObj.AddPair( TJSONPair.Create('uid' , vQ_Rate.uid));
subObj.AddPair( TJSONPair.Create('aid' , vQ_Rate.aid));
subObj.AddPair( TJSONPair.Create('anm' , vQ_Rate.anm));
subObj.AddPair( TJSONPair.Create('rate', vQ_Rate.arate));
subObj.AddPair( TJSONPair.Create('msg' , vQ_Rate.amsg));
subObj.AddPair( TJSONPair.Create('atm' , vQ_Rate.atm));
jsoRlt.AddPair( TJSONPair.Create('bdy' , subObj));
Str := jsoRlt.ToString;
SetDebugeWrite('TFrm_Main.RateAnswer : ' + Str );
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
// pSetGridQRate(vQ_Rate);
except
end;
end;
procedure pSet606QRateSave( ATag, AIdx : Integer; Frm_JON01N : TFrm_JON01N );
Var Str : String;
jsoRlt, headObj, subObj : TJSONObject;
begin
SetDebugeWrite('pSet606QRateSave');
try
with Frm_JON01N do
begin
GQ_Rate[ATag].cmd := '606';
GQ_Rate[ATag].rkey := RQAListView.DataController.GetValue(AIdx, 06);
GQ_Rate[ATag].uid := RQAListView.DataController.GetValue(AIdx, 07);
GQ_Rate[ATag].unm := RQAListView.DataController.GetValue(AIdx, 08);
GQ_Rate[ATag].brno := '';
GQ_Rate[ATag].cuhp := '';
GQ_Rate[ATag].sta := RQAListView.DataController.GetValue(AIdx, 09);
GQ_Rate[ATag].staddr := StringReplace(RQAListView.DataController.GetValue(AIdx, 10),' ',',',[rfReplaceAll]);
GQ_Rate[ATag].via := RQAListView.DataController.GetValue(AIdx, 11);
GQ_Rate[ATag].eda := RQAListView.DataController.GetValue(AIdx, 12);
GQ_Rate[ATag].edaddr := StringReplace(RQAListView.DataController.GetValue(AIdx, 13),' ',',',[rfReplaceAll]);
GQ_Rate[ATag].rate := '0';
GQ_Rate[ATag].qtm := RQAListView.DataController.GetValue(AIdx, 14);
GQ_Rate[ATag].aid := RQAListView.DataController.GetValue(AIdx, 15);
GQ_Rate[ATag].anm := RQAListView.DataController.GetValue(AIdx, 16);
GQ_Rate[ATag].arate := RQAListView.DataController.GetValue(AIdx, 01);
GQ_Rate[ATag].amsg := RQAListView.DataController.GetValue(AIdx, 03);
GQ_Rate[ATag].atm := RQAListView.DataController.GetValue(AIdx, 17);
GQ_Rate[ATag].crkey := '';
end;
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '606'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('rkey' , GQ_Rate[ATag].rKey));
subObj.AddPair( TJSONPair.Create('uid' , GQ_Rate[ATag].Uid));
subObj.AddPair( TJSONPair.Create('unm' , fJsonEncode(GQ_Rate[ATag].unm)));
subObj.AddPair( TJSONPair.Create('sta' , fJsonEncode(GQ_Rate[ATag].sta)));
subObj.AddPair( TJSONPair.Create('staddr', GQ_Rate[ATag].staddr));
subObj.AddPair( TJSONPair.Create('via' , fJsonEncode(GQ_Rate[ATag].via)));
subObj.AddPair( TJSONPair.Create('eda' , fJsonEncode(GQ_Rate[ATag].eda)));
subObj.AddPair( TJSONPair.Create('edaddr', GQ_Rate[ATag].edaddr));
subObj.AddPair( TJSONPair.Create('qtm' , GQ_Rate[ATag].qtm));
subObj.AddPair( TJSONPair.Create('aid' , GQ_Rate[ATag].aid));
subObj.AddPair( TJSONPair.Create('anm' , fJsonEncode(GQ_Rate[ATag].anm)));
subObj.AddPair( TJSONPair.Create('rate' , GQ_Rate[ATag].arate));
subObj.AddPair( TJSONPair.Create('msg' , fJsonEncode(GQ_Rate[ATag].amsg)));
subObj.AddPair( TJSONPair.Create('atm' , GQ_Rate[ATag].atm));
jsoRlt.AddPair( TJSONPair.Create('bdy' , subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pSet607QRateDel( ATag, AIdx : Integer; Frm_JON01N : TFrm_JON01N );
Var Str : String;
jsoRlt, headObj, subObj : TJSONObject;
begin
SetDebugeWrite('pSet607QRateDel');
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '607'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('rkey' , String(Frm_JON01N.RQAListView.DataController.GetValue(AIdx, 06))));
subObj.AddPair( TJSONPair.Create('staddr', StringReplace(Frm_JON01N.RQAListView.DataController.GetValue(AIdx, 10),' ',',',[rfReplaceAll])));
subObj.AddPair( TJSONPair.Create('edaddr', StringReplace(Frm_JON01N.RQAListView.DataController.GetValue(AIdx, 13),' ',',',[rfReplaceAll])));
jsoRlt.AddPair( TJSONPair.Create('bdy' , subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pSet701CShareValue( ATag : Integer; Frm_JON01N : TFrm_JON01N );
Var sVia : String;
lRow : Integer;
begin
try
if Not Frm_Main.JON01MNG[ATag].rOriginal then Exit;
with Frm_JON01N do
begin
GC_Share[ATag].cmd := '701'; // ์ ๋ฌธ์ฝ๋
GC_Share[ATag].rkey := Frm_Main.JON01MNG[ATag].rKey;
GC_Share[ATag].uid := GT_USERIF.ID; // ์ฌ์ฉ์์์ด๋
GC_Share[ATag].unm := GT_USERIF.NM; // ์ฌ์ฉ์์ด๋ฆ
GC_Share[ATag].brno := Proc_BRNOSearch; // ์ง์ฌ์ฝ๋
GC_Share[ATag].brnm := Proc_BrNameReadSearch; // ์ง์ฌ๋ช
GC_Share[ATag].mnum := Proc_MainKeyNumberSearch; // ๋ํ๋ฒํธ
if cxLblCIDUseFlg.Hint <> 'CID' then
GC_Share[ATag].ost := '์ ๊ท' // ์ํ
else
GC_Share[ATag].ost := '์ฝ๋ง'; // ์ํ
GC_Share[ATag].cuhp := IfThen(0 >= Pos('*', cxtCuTel.Text), cxtCallTelNum.Text, locsCuTel); // ๊ณ ๊ฐ์ ํ๋ฒํธ
GC_Share[ATag].cunm := En_Coding(edtCuName.Text); // ๊ณ ๊ฐ๋ช
GC_Share[ATag].sta := Trim(meoStartArea.Text); // ์ถ๋ฐ์ง๋ช
GC_Share[ATag].staddr := lcsSta1 +','+ lcsSta2 +','+ lcsSta3; // ์ถ๋ฐ์ง ์ฃผ์ (์/๋, ์/๊ตฐ/๊ตฌ, ์/๋ฉด/๋)
lRow := 0;
sVia := '';
while lRow <= 4 do
begin
if GT_PASS_INFO[ATag][lRow].AREA1 = '' then break;
if sVia = '' then
sVia := En_Coding(GT_PASS_INFO[ATag][lRow].AREA4)
else
sVia := sVia + '/' + En_Coding(GT_PASS_INFO[ATag][lRow].AREA4);
inc(lRow);
end;
GC_Share[ATag].via := Trim(sVia); // ๊ฒฝ์ ์ง1/๊ฒฝ์ ์ง2/๊ฒฝ์ ์ง3/๊ฒฝ์ ์งnโฆโฆ(๊ฒฝ์ ์ง ์ฌ๋ฌ ๊ฐ ์ผ๋ (/)์ฌ๋์ฌ๋ก ๊ตฌ๋ถ,,,,)
GC_Share[ATag].eda := Trim(meoEndArea.Text); // ๋์ฐฉ์ง๋ช
GC_Share[ATag].edaddr := lcsEnd1 +','+ lcsEnd2 +','+ lcsEnd3; // ๋์ฐฉ์ง ์ฃผ์ (์/๋, ์/๊ตฐ/๊ตฌ, ์/๋ฉด/๋)
GC_Share[ATag].rate := curRate.Value; // ์๊ธ
GC_Share[ATag].bigo := meoBigo.Text; // ์ ์1
GC_Share[ATag].catm := Frm_Main.JON01MNG[ATag].rTime; // ์ฝ๋ง์๊ฐ(yyyy-mm-dd hh:mm:ss)
end;
pSet701CShareSend( ATag );
except
end;
end;
procedure pSet701CShareSend( ATag : Integer );
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// ์ ์ก ์ ๋ณด๊ฐ ๋ณ๊ฒฝ์ด ์์ผ๋ฉด ์ ์ก ์ํจ
if ( GC_PShare[ATag].brno = GC_Share[ATag].brno ) And
( GC_PShare[ATag].brnm = GC_Share[ATag].brnm ) And // ์ง์ฌ๋ช
( GC_PShare[ATag].mnum = GC_Share[ATag].mnum ) And // ๋ํ๋ฒํธ
( GC_PShare[ATag].cuhp = GC_Share[ATag].cuhp ) And // ๊ณ ๊ฐ์ ํ๋ฒํธ
( GC_PShare[ATag].cunm = GC_Share[ATag].cunm ) And // ๊ณ ๊ฐ๋ช
( GC_PShare[ATag].sta = GC_Share[ATag].sta ) And // ์ถ๋ฐ์ง๋ช
( GC_PShare[ATag].staddr = GC_Share[ATag].staddr ) And // ์ถ๋ฐ์ง ์ฃผ์ (์/๋, ์/๊ตฐ/๊ตฌ, ์/๋ฉด/๋)
( GC_PShare[ATag].via = GC_Share[ATag].via ) And // ๊ฒฝ์ ์ง1/๊ฒฝ์ ์ง2/๊ฒฝ์ ์ง3/๊ฒฝ์ ์งnโฆโฆ(๊ฒฝ์ ์ง ์ฌ๋ฌ ๊ฐ ์ผ๋ (/)์ฌ๋์ฌ๋ก ๊ตฌ๋ถ,,,,)
( GC_PShare[ATag].eda = GC_Share[ATag].eda ) And // ๋์ฐฉ์ง๋ช
( GC_PShare[ATag].edaddr = GC_Share[ATag].edaddr ) And // ๋์ฐฉ์ง ์ฃผ์ (์/๋, ์/๊ตฐ/๊ตฌ, ์/๋ฉด/๋)
( GC_PShare[ATag].rate = GC_Share[ATag].rate ) then // ์๊ธ
begin
Exit;
end;
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', GC_Share[ATag].cmd));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('rkey' , GC_Share[ATag].rKey));
subObj.AddPair( TJSONPair.Create('uid' , GC_Share[ATag].Uid));
subObj.AddPair( TJSONPair.Create('unm' , fJsonEncode(GC_Share[ATag].unm)));
subObj.AddPair( TJSONPair.Create('brno' , GC_Share[ATag].brno));
subObj.AddPair( TJSONPair.Create('brnm' , fJsonEncode(GC_Share[ATag].brnm)));
subObj.AddPair( TJSONPair.Create('mnum' , GC_Share[ATag].mnum));
subObj.AddPair( TJSONPair.Create('ost' , GC_Share[ATag].ost));
subObj.AddPair( TJSONPair.Create('cuhp' , GC_Share[ATag].cuhp));
subObj.AddPair( TJSONPair.Create('cunm' , fJsonEncode(GC_Share[ATag].cunm)));
subObj.AddPair( TJSONPair.Create('sta' , fJsonEncode(GC_Share[ATag].sta)));
subObj.AddPair( TJSONPair.Create('staddr', GC_Share[ATag].staddr));
subObj.AddPair( TJSONPair.Create('via' , fJsonEncode(GC_Share[ATag].via)));
subObj.AddPair( TJSONPair.Create('eda' , fJsonEncode(GC_Share[ATag].eda)));
subObj.AddPair( TJSONPair.Create('edaddr', GC_Share[ATag].edaddr));
subObj.AddPair( TJSONPair.Create('rate' , GC_Share[ATag].rate));
subObj.AddPair( TJSONPair.Create('bigo' , fJsonEncode(GC_Share[ATag].bigo)));
subObj.AddPair( TJSONPair.Create('jtype' , GC_Share[ATag].jtype));
subObj.AddPair( TJSONPair.Create('catm' , GC_Share[ATag].catm));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
GC_PShare[ATag] := GC_Share[ATag];
end;
// Frm_Main.cxPageControl2.ActivePageIndex := 6;
// Frm_Main.pSetGridCShare( GC_Share[ATag] );
Dm.pSendCMessenger(False, Str);
except
end;
end;
procedure pSet703CShareClose( sGubun : String; ATag : Integer; Frm_JON01N : TFrm_JON01N );
begin
if Not Frm_Main.JON01MNG[ATag].rOriginal then Exit;
try
with Frm_JON01N do
begin
GC_Share[ATag].cmd := '703'; // ์ ๋ฌธ์ฝ๋
GC_Share[ATag].rkey := Frm_Main.JON01MNG[ATag].rKey; // ์ฝ๋ง ์ ์์ฐฝ ์ ๋ณด ๊ณ ์ ํค๊ฐ(ID + datetime[yyyymmddhhmmss])
GC_Share[ATag].uid := GT_USERIF.ID; // ์ฌ์ฉ์์์ด๋
GC_Share[ATag].unm := GT_USERIF.NM; // ์ฌ์ฉ์์ด๋ฆ
GC_Share[ATag].cuhp := IfThen(0 >= Pos('*', cxtCuTel.Text), cxtCallTelNum.Text, locsCuTel); // ๊ณ ๊ฐ์ ํ๋ฒํธ
end;
pSet703CShareCloseSend(sGubun, ATag);
except
end;
end;
procedure pSet703CShareCloseSend( sGubun : String; ATag : Integer );
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', GC_Share[ATag].cmd));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('rkey', GC_Share[ATag].rKey));
subObj.AddPair( TJSONPair.Create('uid' , GC_Share[ATag].Uid));
subObj.AddPair( TJSONPair.Create('unm' , GC_Share[ATag].unm));
subObj.AddPair( TJSONPair.Create('cuhp', GC_Share[ATag].cuhp));
subObj.AddPair( TJSONPair.Create('clgb', sGubun));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
// Frm_Main.cxPageControl2.ActivePageIndex := 6;
// Frm_Main.pSetGridCShare( GC_Share[ATag] ); // 704๋ก ๋ฐ์์ ์ฒ๋ฆฌํ๋ ๊ฑธ๋ก ๋ณ๊ฒฝ
Dm.pSendCMessenger(False, Str);
except
end;
end;
procedure pSet708CShareCall(Agbup, Agb, ArKey, AjId, AjNm, ArId, ArNm : String);
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
if ArKey = '' then Exit;
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '708'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('ckey' , ArKey));
subObj.AddPair( TJSONPair.Create('jid' , AjId));
subObj.AddPair( TJSONPair.Create('jnm' , AjNm));
subObj.AddPair( TJSONPair.Create('rid' , ArId));
subObj.AddPair( TJSONPair.Create('rnm' , ArNm));
subObj.AddPair( TJSONPair.Create('ogb' , Agb));
subObj.AddPair( TJSONPair.Create('ogbup', Agbup));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pSet705CShareCancel(Agb, ArKey, AjId, ArId : String);
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '705'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('ckey' , ArKey));
subObj.AddPair( TJSONPair.Create('jid' , AjId));
subObj.AddPair( TJSONPair.Create('rid' , ArId));
subObj.AddPair( TJSONPair.Create('ogb' , Agb));
subObj.AddPair( TJSONPair.Create('ogbup', 'c'));
subObj.AddPair( TJSONPair.Create('ls' , '[]'));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
Dm.pSendCMessenger(True, Str);
finally
FreeAndNil(jsoRlt);
end;
except
end;
end;
procedure pSet705CShareData(bFirst:Boolean; AgbUp, Agb, ArKey, AjId, ArId : String; ATag : Integer; Frm_JON01N : TFrm_JON01N );
Var jsoRlt, headObj, subObj : TJSONObject;
arrObj: TJSONArray;
sls, Str : String;
begin
if Frm_Main.JON01MNG[ATag].rKey = '' then Exit;
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '705'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('ckey' , ArKey));
subObj.AddPair( TJSONPair.Create('jid' , AjId));
subObj.AddPair( TJSONPair.Create('rid' , ArId));
subObj.AddPair( TJSONPair.Create('ogb' , Agb));
subObj.AddPair( TJSONPair.Create('ogbup', AgbUp));
sls := fGetFrmCShare(bFirst, ATag, Frm_JON01N);
if ( GC_PRE_CSHAREDATA <> sls ) And ( '[]' <> sls ) then
begin
GC_PRE_CSHAREDATA := sls;
arrObj := TJSONObject.ParseJSONValue(sls) as TJSONArray;
subObj.AddPair( TJSONPair.Create('ls' , arrObj));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
Dm.pSendCMessenger(True, Str);
end;
finally
FreeAndNil(jsoRlt);
end;
except
end;
end;
procedure pSet705CShareClick(Agb, ArKey, AjId, ArId, AClickNm : String; ATag : Integer );
Var jsoRlt, headObj, subObj : TJSONObject;
arrObj: TJSONArray;
jso : TJSONObject;
Str : String;
begin
if Frm_Main.JON01MNG[ATag].rKey = '' then Exit;
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '705'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('ckey' , ArKey));
subObj.AddPair( TJSONPair.Create('jid' , AjId));
subObj.AddPair( TJSONPair.Create('rid' , ArId));
subObj.AddPair( TJSONPair.Create('ogb' , Agb));
subObj.AddPair( TJSONPair.Create('ogbup', 'n'));
arrObj := TJSONArray.Create;
jso := TJSONObject.Create;
jso.AddPair(TJsonPair.Create('io', fGetComNameToCode('ClickEvent')));
jso.AddPair(TJsonPair.Create('in', AClickNm));
jso.AddPair(TJsonPair.Create('ic', '1'));
arrObj.AddElement(jso);
subObj.AddPair( TJSONPair.Create('ls' , arrObj));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
Dm.pSendCMessenger(True, Str);
finally
FreeAndNil(jsoRlt);
end;
except
end;
end;
procedure pSet705CShareDataClick(bFirst:Boolean; Agb, ArKey, AjId, ArId, AClickNm : String; ATag : Integer; Frm_JON01N : TFrm_JON01N );
Var jsoRlt, headObj, subObj : TJSONObject;
arrObj: TJSONArray;
jso : TJSONObject;
sls, Str : String;
begin
if Frm_Main.JON01MNG[ATag].rKey = '' then Exit;
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '705'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('ckey' , ArKey));
subObj.AddPair( TJSONPair.Create('jid' , AjId));
subObj.AddPair( TJSONPair.Create('rid' , ArId));
subObj.AddPair( TJSONPair.Create('ogb' , Agb));
subObj.AddPair( TJSONPair.Create('ogbup', 'n'));
sls := fGetFrmCShare(bFirst, ATag, Frm_JON01N);
arrObj := TJSONObject.ParseJSONValue(sls) as TJSONArray;
jso := TJSONObject.Create;
jso.AddPair(TJsonPair.Create('io', fGetComNameToCode('ClickEvent')));
jso.AddPair(TJsonPair.Create('in', AClickNm));
jso.AddPair(TJsonPair.Create('ic', '1'));
arrObj.AddElement(jso);
subObj.AddPair( TJSONPair.Create('ls' , arrObj));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
Dm.pSendCMessenger(True, Str);
finally
FreeAndNil(jsoRlt);
end;
except
end;
end;
procedure pSet706CShareEnd(ArKey, AjId, ArId, AWcl : String);
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
if ArKey = '' then Exit;
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '706'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('ckey' , ArKey));
subObj.AddPair( TJSONPair.Create('jid' , AjId));
subObj.AddPair( TJSONPair.Create('rid' , ArId));
subObj.AddPair( TJSONPair.Create('ogb' , 'r'));
subObj.AddPair( TJSONPair.Create('ogbup', 'n'));
subObj.AddPair( TJSONPair.Create('wcl' , AWcl));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pSet705CShareClickEvent( AEventName : String; ATag : Integer; Frm_JON01N : TFrm_JON01N );
begin
// with Frm_JON01N do
// begin
// tmrCShare.Enabled := False;
// try
// if ( pnlRShare.Visible ) Or ( pnlRShare.Tag = 1 ) then
// begin
// if lblCShareJId.Hint = GT_USERIF.ID then
// begin
// pSet705CShareClick('j', Frm_Main.JON01MNG[ATag].rKey, lblCShareJId.Hint, lblCShareRId.Hint, AEventName, ATag);
// end else
// if lblCShareRId.Hint = GT_USERIF.ID then
// begin
// pSet705CShareClick('r', Frm_Main.JON01MNG[ATag].rKey, lblCShareJId.Hint, lblCShareRId.Hint, AEventName, ATag);
// end;
// end;
// finally
// tmrCShare.Enabled := True;
// end;
// end;
end;
procedure pSet370FileUpload( AFileName : String );
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
SetDebugeWrite('pSet370FileUpload');
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '370'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('filename', StringReplace(AFileName, '\' , '\', [rfReplaceAll]) ) );
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pSet380ServerSetting( AType, ASsyn, ASset : String );
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
SetDebugeWrite('pSet380ServerSetting');
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '380'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('type', AType));
subObj.AddPair( TJSONPair.Create('hdno', GT_USERIF.HD));
subObj.AddPair( TJSONPair.Create('uid' , GT_USERIF.ID));
subObj.AddPair( TJSONPair.Create('unm' , GT_USERIF.NM));
subObj.AddPair( TJSONPair.Create('ssyn', ASsyn));
subObj.AddPair( TJSONPair.Create('sset', ASset));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pGet381ServerSetting;
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
SetDebugeWrite('pGet381ServerSetting');
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '381'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('uid' , GT_USERIF.ID));
subObj.AddPair( TJSONPair.Create('hdno', GT_USERIF.HD));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pSet050CCList( iTag : Integer );
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
SetDebugeWrite('pSet050CCList');
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
if iTag = 1415 then
headObj.AddPair( TJSONPair.Create('cmd', '1415')) else
if iTag = 1416 then
headObj.AddPair( TJSONPair.Create('cmd', '1416'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('uid', GT_USERIF.ID));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(True, Str);
except
end;
end;
procedure pSetGridCShare( vC_Share : TC_Share );
function GetRecordIndexByText(AView: TcxCustomGridTableView; AText: string; AColumnIndex: Integer): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to AView.DataController.RecordCount - 1 do
begin
if StrPos(PChar(AView.DataController.DisplayTexts[I, AColumnIndex]), PChar(AText)) <> nil then
begin
Result := i;
Break;
end;
end;
end;
Var iRow, i, icrKey, iStat, iGong : Integer;
sMode : String;
bNew : Boolean;
begin
SetDebugeWrite('Share.pSetGridCShare Start');
try
if ( vC_Share.Cmd = '701' ) Or ( vC_Share.Cmd = '703' ) then Exit;
bNew := False;
if Frm_Main.cxGridCShare.DataController.Filter.Active then
iRow := GetRecordIndexByText(Frm_Main.cxGridCShare, vC_Share.rKey, 15)
else
iRow := Frm_Main.cxGridCShare.DataController.FindRecordIndexByText(0, 15, vC_Share.rKey, False, True, True);
try
Frm_Main.cxGridCShare.BeginUpdate;
if ( vC_Share.Cmd = '702' ) then
begin
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
begin
if scb_FamilyBrCode.IndexOf(vC_Share.brno) < 0 then Exit;
end else
begin
if scb_BranchCode.IndexOf(vC_Share.brno) < 0 then Exit;
end;
if iRow < 0 then
begin
iRow := Frm_Main.cxGridCShare.DataController.AppendRecord;
bNew := True;
end;
Frm_Main.cxGridCShare.DataController.Values[iRow, 00] := vC_Share.catm; // ์ฝ๋ง์๊ฐ
Frm_Main.cxGridCShare.DataController.Values[iRow, 01] := vC_Share.unm; // ์ ์์
Frm_Main.cxGridCShare.DataController.Values[iRow, 02] := vC_Share.brnm; // ์ง์ฌ๋ช
Frm_Main.cxGridCShare.DataController.Values[iRow, 03] := StrToCall(vC_Share.mnum); // ๋ํ๋ฒํธ
if ( Frm_Main.cxGridCShare.DataController.Values[iRow, 04] ) <> '๊ณต์ ' then
Frm_Main.cxGridCShare.DataController.Values[iRow, 04] := vC_Share.ost; // ์ํ
Frm_Main.cxGridCShare.DataController.Values[iRow, 05] := StrToCall(vC_Share.cuhp); // ์ ํ๋ฒํธ
Frm_Main.cxGridCShare.DataController.Values[iRow, 06] := vC_Share.cunm; // ๊ณ ๊ฐ๋ช
Frm_Main.cxGridCShare.DataController.Values[iRow, 07] := vC_Share.sta; // ์ถ๋ฐ์ง
Frm_Main.cxGridCShare.DataController.Values[iRow, 08] := StringReplace(vC_Share.staddr, ',', ' ', [rfReplaceAll]); // ์ถ๋ฐ์ง์ฃผ์
Frm_Main.cxGridCShare.DataController.Values[iRow, 09] := vC_Share.via; // ๊ฒฝ์ ์ง
Frm_Main.cxGridCShare.DataController.Values[iRow, 10] := vC_Share.eda; // ๋์ฐฉ์ง
Frm_Main.cxGridCShare.DataController.Values[iRow, 11] := StringReplace(vC_Share.edaddr, ',', ' ', [rfReplaceAll]); // ๋์ฐฉ์ง์ฃผ์
Frm_Main.cxGridCShare.DataController.Values[iRow, 12] := StrToInt(vC_Share.rate); // ์๊ธ
Frm_Main.cxGridCShare.DataController.Values[iRow, 13] := ''; // ๊ฒฝ๊ณผ(์ด)
Frm_Main.cxGridCShare.DataController.Values[iRow, 14] := vC_Share.bigo; // ์ ์
Frm_Main.cxGridCShare.DataController.Values[iRow, 15] := vC_Share.rkey; // rKey
Frm_Main.cxGridCShare.DataController.Values[iRow, 16] := vC_Share.uid; // uid
Frm_Main.cxGridCShare.DataController.Values[iRow, 17] := vC_Share.brno; // brno
Frm_Main.cxGridCShare.DataController.Values[iRow, 18] := vC_Share.jtype; // jtype
end else
if ( vC_Share.Cmd = '703' ) Or ( vC_Share.Cmd = '704' ) then
begin
SetDebugeWrite(Format('Share.pSetGridCShare %s - %d - %s', [vC_Share.Cmd, iRow, vC_Share.rKey]));
if iRow >= 0 then
Frm_Main.cxGridCShare.DataController.DeleteRecord(iRow);
end;
finally
Frm_Main.cxGridCShare.EndUpdate;
if Frm_Main.cxGridCShare.DataController.RecordCount > 0 then
Frm_Main.tsBtmMenu3.Caption := Format('์ ๊ท์ ์๊ณต์ (%s)',[FormatFloat('#,##0', Frm_Main.cxGridCShare.DataController.RecordCount)])
else
Frm_Main.tsBtmMenu3.Caption := '์ ๊ท์ ์๊ณต์ ';
end;
Frm_Main.cxGridCShare.Columns[0].SortIndex := 0;
Frm_Main.cxGridCShare.Columns[0].SortOrder := soDescending;
if ( vC_Share.Cmd = '702' ) And ( Not GB_NS_NOCHANGEMENU ) And ( bNew ) then
Frm_Main.cxPageControl2.ActivePageIndex := 2;
if ( vC_Share.Cmd = '707' ) Or ( vC_Share.Cmd = '709' ) then
begin
// ์ ๊ท ์ ์ ๊ณต์ ์ํ ์ฒ๋ฆฌ
if ( vC_Share.Cmd = '707' ) then sMode := '์ฝ๋ง' else
if ( vC_Share.Cmd = '709' ) then sMode := '๊ณต์ ';
try
Frm_Main.cxGridCShare.BeginUpdate;
for i := 0 to Frm_Main.cxGridCShare.DataController.RecordCount - 1 do
begin
if vC_Share.rkey = Frm_Main.cxGridCShare.DataController.Values[i, 15] then
begin
Frm_Main.cxGridCShare.DataController.Values[i, 4] := sMode;
end;
end;
finally
Frm_Main.cxGridCShare.EndUpdate;
end;
// ์๊ธ๋ฌธ์ ๊ณต์ ์ํ ์ฒ๋ฆฌ
if ( vC_Share.Cmd = '707' ) then sMode := '' else
if ( vC_Share.Cmd = '709' ) then sMode := '๊ณต์ ';
try
Frm_Main.cxGridQRate.BeginUpdate;
icrKey := Frm_Main.cxGridQRate.GetColumnByFieldName('crkey').Index;
iGong := Frm_Main.cxGridQRate.GetColumnByFieldName('๊ณต์ ์ฌ๋ถ').Index;
for i := 0 to Frm_Main.cxGridQRate.DataController.RecordCount - 1 do
begin
if vC_Share.rkey = Frm_Main.cxGridQRate.DataController.Values[i, icrKey] then
begin
Frm_Main.cxGridQRate.DataController.Values[i, iGong] := sMode;
end;
end;
finally
Frm_Main.cxGridQRate.EndUpdate;
end;
end;
if ( vC_Share.Cmd = '704' ) then
begin
if vC_Share.clgb = '5' then sMode := '๋๊ธฐ' else
if vC_Share.clgb = 'R' then sMode := '์์ฝ' else
if vC_Share.clgb = '0' then sMode := '์ ์' else
if vC_Share.clgb = 'C' then sMode := '๊ทผ๋ฐฐ' else
if vC_Share.clgb = 'M' then sMode := '๊ทผ๋ฐฐ' else
if vC_Share.clgb = 'B' then sMode := '๋ฐฐ์ฐจ์ค' else
if vC_Share.clgb = '1' then sMode := '๋ฐฐ์ฐจ' else
if vC_Share.clgb = '3' then sMode := '๊ฐ์ ' else
if vC_Share.clgb = '2' then sMode := '์๋ฃ' else
if vC_Share.clgb = '8' then sMode := '์ทจ์' else
if vC_Share.clgb = '4' then sMode := '๋ฌธ์' else
if vC_Share.clgb = 'Z' then sMode := '์ข
๋ฃ';
try
Frm_Main.cxGridQRate.BeginUpdate;
icrKey := Frm_Main.cxGridQRate.GetColumnByFieldName('crkey').Index;
iGong := Frm_Main.cxGridQRate.GetColumnByFieldName('๊ณต์ ์ฌ๋ถ').Index;
iStat := Frm_Main.cxGridQRate.GetColumnByFieldName('์ํ').Index;
for i := 0 to Frm_Main.cxGridQRate.DataController.RecordCount - 1 do
begin
if vC_Share.rkey = Frm_Main.cxGridQRate.DataController.Values[i, icrKey] then
begin
Frm_Main.cxGridQRate.DataController.Values[i, iStat] := sMode;
Frm_Main.cxGridQRate.DataController.Values[i, iGong] := '';
end;
end;
finally
Frm_Main.cxGridQRate.EndUpdate;
end;
// ๋ต๋ณ์ค์ธ ์๊ธ์ ๋ํด ์ด๊ธฐํ ์ฒ๋ฆฌ
if Frm_Main.cxgrpQRHead.Hint = vC_Share.rkey then
begin
Frm_Main.cxgrpQRHead.Hint := '';
Frm_Main.lblRateA.Hint := '';
Frm_Main.lblRateA.Tag := 0;
Frm_Main.curRate.Value := 0;
Frm_Main.lblRateE.Hint := '';
Frm_Main.LbmeoBigo.Caption := '์๊ธ์ค๋ช
';
Frm_Main.lbmeoBigo.Visible := True;
Frm_Main.edtMemo.Text := '';
end;
// ๋ต๋ณ ํ์
์ฐฝ ์๋ ์ข
๋ฃ - ์๋๋ฐฉ ์ ์์ฐฝ์ด ๋ซํ์ ๊ฒฝ์ฐ
for i := 0 to 30 do
begin
if ( Assigned(Frm_Main.Frm_COM50[i]) ) And ( Frm_Main.COM50MNG[i].CreateYN ) then
begin
if vC_Share.rkey = Frm_Main.Frm_COM50[i].lblRQEnd.Hint then
begin
Frm_Main.Frm_COM50[i].pnlRQPopup.Enabled := False;
Frm_Main.Frm_COM50[i].cxLabel8.Caption := '์๊ธ๋ฌธ์ ์์ฒญํ ์๋ด์์ ์ ์์ฐฝ์ด ์ข
๋ฃ๋์์ผ๋ฏ๋ก' + CRLF + CRLF +
'์๊ธ๋ฌธ์ ๋ต๋ณ ์ฐฝ ์๋ ์ข
๋ฃํฉ๋๋ค.';
Frm_Main.Frm_COM50[i].pnlAutoClose.Left := (Frm_Main.Frm_COM50[i].pnlRQPopup.Width - Frm_Main.Frm_COM50[i].pnlAutoClose.Width) div 2;
Frm_Main.Frm_COM50[i].pnlAutoClose.Top := (Frm_Main.Frm_COM50[i].pnlRQPopup.Height - Frm_Main.Frm_COM50[i].pnlAutoClose.Height) div 2;
Frm_Main.Frm_COM50[i].pnlAutoClose.Visible := True;
Frm_Main.Frm_COM50[i].Timer1.Enabled := True;
end;
end;
end;
// for i := 0 to JON_MAX_CNT - 1 do
// begin
// if Frm_Main.JON01MNG[i].rKey = vC_Share.rkey then
// begin
// Frm_Main.Frm_JON01N[i].pnlRShare.Visible := False;
// Frm_Main.Frm_JON01N[i].pnlShare.Visible := False;
// Frm_Main.Frm_JON01N[i].btnCmdExit.Click;
// end;
// end;
end;
Application.ProcessMessages;
SetDebugeWrite('Share.pSetGridCShare End');
except
on e: exception do
begin
Log('Share.pSetGridCShare Error :' + E.Message, LOGDATAPATHFILE);
Assert(False, 'Share.pSetGridCShare Error :' + E.Message);
end;
end;
end;
procedure pCP_702CShareRequest(sData: String);
var
sBody : TJSONObject;
vC_Share : TC_Share;
begin
SetDebugeWrite('Share.pCP_702CShareRequest');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
vC_Share.cmd := '702';
vC_Share.rkey := sBody.Get('rkey' ).JsonValue.Value;
vC_Share.uid := sBody.Get('uid' ).JsonValue.Value;
vC_Share.unm := fJsonDecode(sBody.Get('unm' ).JsonValue.Value);
vC_Share.brno := sBody.Get('brno' ).JsonValue.Value;
vC_Share.brnm := fJsonDecode(sBody.Get('brnm' ).JsonValue.Value);
vC_Share.mnum := sBody.Get('mnum' ).JsonValue.Value;
vC_Share.ost := sBody.Get('ost' ).JsonValue.Value;
vC_Share.cuhp := sBody.Get('cuhp' ).JsonValue.Value;
vC_Share.cunm := fJsonDecode(sBody.Get('cunm' ).JsonValue.Value);
vC_Share.sta := fJsonDecode(sBody.Get('sta' ).JsonValue.Value);
vC_Share.staddr := sBody.Get('staddr').JsonValue.Value;
vC_Share.via := fJsonDecode(sBody.Get('via' ).JsonValue.Value);
vC_Share.eda := fJsonDecode(sBody.Get('eda' ).JsonValue.Value);
vC_Share.edaddr := sBody.Get('edaddr').JsonValue.Value;
vC_Share.rate := sBody.Get('rate' ).JsonValue.Value;
vC_Share.bigo := fJsonDecode(sBody.Get('bigo' ).JsonValue.Value);
vC_Share.jtype := sBody.Get('jtype' ).JsonValue.Value;
vC_Share.catm := sBody.Get('catm' ).JsonValue.Value;
finally
FreeAndNil(sBody);
end;
// cxPageControl2.ActivePageIndex := 3;
pSetGridCShare(vC_Share);
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pCP_704CShareClose(sData: String);
var
sBody : TJSONObject;
vC_Share : TC_Share;
begin
SetDebugeWrite('Share.pCP_704CShareClose');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
vC_Share.cmd := '704';
vC_Share.rkey := sBody.Get('rkey' ).JsonValue.Value;
vC_Share.uid := sBody.Get('uid' ).JsonValue.Value;
vC_Share.unm := sBody.Get('unm' ).JsonValue.Value;
vC_Share.cuhp := sBody.Get('cuhp' ).JsonValue.Value;
vC_Share.clgb := sBody.Get('clgb' ).JsonValue.Value;
finally
FreeAndNil(sBody);
end;
// cxPageControl2.ActivePageIndex := 3;
pSetGridCShare(vC_Share);
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pCP_370Result(sData: String);
var
sBody : TJSONObject;
sResult : String;
begin
SetDebugeWrite('Share.pCP_370Result');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
sResult := sBody.Get('result').JsonValue.Value;
finally
FreeAndNil(sBody);
end;
if sResult = 'y' then
pSet380ServerSetting(GS_IU, GS_FormSSYN, GS_FormSSET);
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pCP_371Result(sData: String);
var
sBody : TJSONObject;
sFileNm, sFileDt : String;
begin
SetDebugeWrite('Share.pCP_371Result');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
sFileNm := sBody.Get('filename').JsonValue.Value;
sFileDt := sBody.Get('datetime').JsonValue.Value;
finally
FreeAndNil(sBody);
end;
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pCP_381GetServerSetting(ACid, sData: String);
begin
end;
procedure pCP_501Result(sData: String);
var
sBody : TJSONObject;
sResult, sMsg : String;
begin
SetDebugeWrite('Share.pCP_501Result');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
sResult := sBody.Get('rlt').JsonValue.Value;
sMsg := sBody.Get('msg').JsonValue.Value;
if sResult = 'y' then
begin
Application.ProcessMessages;
case gBtnTag of
0: GMessagebox('๊ณต์ง๊ฐ ๋ฑ๋ก๋์์ต๋๋ค', CDMSI);
1: GMessagebox('๊ณต์ง๊ฐ ์์ ๋์์ต๋๋ค', CDMSI);
2: GMessagebox('๊ณต์ง๊ฐ ์ญ์ ๋์์ต๋๋ค', CDMSI);
3: GMessagebox('๊ณต์ง ์์ฝ์ด ํด์ ๋์์ต๋๋ค', CDMSI);
end;
if Assigned(Frm_JON24) then
begin
Frm_JON24.cxbModify.Enabled := True;
Frm_JON24.btnClose.Click;
end;
// if ( not Assigned(Frm_JON23) ) Or ( Frm_JON23 = Nil ) then Frm_JON23 := TFrm_JON23.Create(nil);
// Frm_JON23.proc_Search;
end else
begin
GMessagebox(sResult + ' : ' + sMsg, CDMSE);
if Assigned(Frm_JON24) then
begin
Frm_JON24.cxbModify.Enabled := True;
end;
end;
finally
FreeAndNil(sBody);
end;
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pCP_601Result(sData: String);
var
sBody : TJSONObject;
sResult, sMsg : String;
i : Integer;
begin
SetDebugeWrite('Share.pCP_601Result');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
sResult := sBody.Get('rlt').JsonValue.Value;
sMsg := sBody.Get('msg').JsonValue.Value;
if sResult = 'y' then
begin
// GMessagebox('์ ์์ฐฝ ์๊ธ ๋ฌธ์ ์๋ฃ', CDMSE);
for i := 0 to JON_MAX_CNT - 1 do
begin
if Frm_Main.JON01MNG[i].rKey = GS_RQ_SENDCRKEY then
begin
if FPlusDongCHK = 2 then Frm_Main.Frm_JON01N[i].pnl_Charge.height := 36
else Frm_Main.Frm_JON01N[i].pnl_Charge.height := 21;
Frm_Main.Frm_JON01N[i].Lbl_Charge.Caption := '์ ์์ฐฝ ์๊ธ ๋ฌธ์ ์๋ฃ';
Frm_Main.Frm_JON01N[i].pnl_Charge.Visible := True;
if Frm_Main.Frm_JON01N[i].curRate.CanFocus then Frm_Main.Frm_JON01N[i].curRate.SetFocus;
end;
end;
end else
begin
GMessagebox(sResult + ' : ' + sMsg, CDMSE);
end;
finally
FreeAndNil(sBody);
end;
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pCP_801GetBrCash(sData: String);
var
sBody : TJSONObject;
sBrno : String;
ls_TxQry, ls_TxLoad, swhere, sQueryTemp: string;
ls_rxxml: string;
StrList, ls_Rcrd : TStringList;
ErrCode: integer;
xdom: msDomDocument;
lst_Result: IXMLDomNodeList;
ls_ClientKey, ls_Msg_Err: string;
begin
SetDebugeWrite('Share.pCP_801GetBrCash');
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
sBrno := sBody.Get('br_no').JsonValue.Value;
finally
FreeAndNil(sBody);
end;
try
sWhere := format('WHERE BR_NO = ''%s'' ', [sBrno]);
ls_TxLoad := GTx_UnitXmlLoad('SEL01.XML');
fGet_BlowFish_Query(GSQ_BRANCH_SMS_CASH, sQueryTemp);
ls_TxQry := Format(sQueryTemp, [sWhere]);
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', GT_USERIF.ID, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', 'CASH0002', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'QueryString', ls_TxQry, [rfReplaceAll]);
StrList := TStringList.Create;
Screen.Cursor := crHandPoint;
try
if dm.SendSock(ls_TxLoad, StrList, ErrCode, False) then
begin
ls_rxxml := StrList[0];
if trim(ls_rxxml) <> '' then
begin
Application.ProcessMessages;
xdom := ComsDomDocument.Create;
Screen.Cursor := crHourGlass;
try
ls_rxxml := ls_rxxml;
if not xdom.loadXML(ls_rxxml) then
begin
Screen.Cursor := crDefault;
Exit;
end;
ls_MSG_Err := GetXmlErrorCode(ls_rxxml);
if ('0000' = ls_MSG_Err) then
begin
ls_ClientKey := GetXmlClientKey(ls_rxxml);
if (0 < GetXmlRecordCount(ls_rxxml)) then
begin
lst_Result := xdom.documentElement.selectNodes('/cdms/Service/Data/Result');
ls_Rcrd := TStringList.Create;
try
GetTextSeperationEx('โ', lst_Result.item[0].attributes.getNamedItem('Value').Text, ls_Rcrd);
p801SendBrCash(False, ls_Rcrd[0], ls_Rcrd[3]);
finally
ls_Rcrd.Free;
end;
end;
end else
begin
Screen.Cursor := crDefault;
p801SendBrCash(True, ls_MSG_Err, GetXmlErrorMsg(ls_rxxml));
end;
finally
Screen.Cursor := crDefault;
xdom := Nil;
end;
end;
end;
finally
StrList.Free;
Screen.Cursor := crDefault;
end;
except
end;
end;
procedure p801SendBrCash(bError : Boolean; sCash, sDanga: String);
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '801'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
if bError then
begin
subObj.AddPair( TJSONPair.Create('rlt', 'n'));
subObj.AddPair( TJSONPair.Create('msg' , sCash+'.'+sDanga));
subObj.AddPair( TJSONPair.Create('cash' , '0'));
subObj.AddPair( TJSONPair.Create('danga', '0'));
end else
begin
subObj.AddPair( TJSONPair.Create('rlt', 'y'));
subObj.AddPair( TJSONPair.Create('msg' , ''));
subObj.AddPair( TJSONPair.Create('cash' , sCash));
subObj.AddPair( TJSONPair.Create('danga', sDanga));
end;
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(False, Str);
except
end;
end;
procedure pCP_802SendSMS(sData: String);
var
sBody : TJSONObject;
subjObj: TJSONObject;
arriObj : TJSONArray;
sSend, sRecv, sMsg, sRetime : String;
ls_TxLoad : string;
i : Integer;
ls_rxxml: string;
StrList : TStringList;
ErrCode: integer;
ls_Msg_Err: string;
begin
SetDebugeWrite('Share.pCP_802SendSMS');
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
sRecv := '';
arriObj := TJSONObject.ParseJSONValue(sBody.Get('r_ls').JsonValue.ToString) as TJSONArray;
for i := 0 to arriObj.Size - 1 do
begin
subjObj := arriObj.Get(i) as TJSONObject;
if i = ( arriObj.Size - 1 ) then
begin
sRecv := subjObj.Get('rnum').JsonValue.Value;
end else
begin
sRecv := subjObj.Get('rnum').JsonValue.Value + ',';
end;
end;
sSend := sBody.Get('snum').JsonValue.Value;
sMsg := sBody.Get('msg').JsonValue.Value;
sRetime := sBody.Get('retime').JsonValue.Value;
finally
FreeAndNil(sBody);
end;
try
sMsg := StringReplace(sMsg, #13#10, #10, [rfReplaceAll]);
ls_TxLoad := GTx_UnitXmlLoad('SMS02.XML');
ls_TxLoad := StringReplace(ls_TxLoad, 'UserIDString', En_Coding(GT_USERIF.ID), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientVerString', VERSIONINFO, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ClientKeyString', 'WSMS0001', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ReceiverString', En_Coding(sRecv), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'SenderString', En_Coding(sSend), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'MessageString', En_Coding(sMsg), [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ReservationString', sRetime, [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'MemoString', '[๋ฉ์ ์ ๋ฌธ์์ ์ก]', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'ConfSlipString', '', [rfReplaceAll]);
ls_TxLoad := StringReplace(ls_TxLoad, 'WkSabunString', '', [rfReplaceAll]);
StrList := TStringList.Create;
Screen.Cursor := crHandPoint;
try
if dm.SendSock(ls_TxLoad, StrList, ErrCode, False) then
begin
ls_rxxml := StrList[0];
if trim(ls_rxxml) <> '' then
begin
Application.ProcessMessages;
Screen.Cursor := crHourGlass;
try
ls_rxxml := ls_rxxml;
ls_Msg_Err := GetXmlErrorCode(ls_rxxml);
if ('0000' = ls_Msg_Err) then
begin
p802SendSMSResult('y', '');
end else
begin
p802SendSMSResult('n', ls_Msg_Err+'.'+GetXmlErrorMsg(ls_rxxml));
end;
finally
Screen.Cursor := crDefault;
end;
end;
end;
finally
StrList.Free;
Screen.Cursor := crDefault;
end;
except
end;
end;
procedure p802SendSMSResult( sResult, sMsg: String);
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '802'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('rlt', sResult));
subObj.AddPair( TJSONPair.Create('msg', sMsg));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(False, Str);
except
end;
end;
procedure pCP_901Result(sData: String);
var
sBody : TJSONObject;
begin
SetDebugeWrite('Share.pCP_901Result');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
GB_CUPDATE_CHK := True;
GS_CUPDATE_TYPE := sBody.Get('type').JsonValue.Value;
GS_CUPDATE_VER := sBody.Get('ver' ).JsonValue.Value;
finally
FreeAndNil(sBody);
end;
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure p902SendResult( sResult : String);
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '902'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('result', sResult));
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(False, Str);
except
end;
end;
procedure p903SendMSNAlive;
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '903'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(False, Str);
except
end;
end;
procedure pCP_903Result(sData: String);
var
iHandle: THandle;
CopyData: TCopyDataStruct;
sBody : TJSONObject;
sResult : String;
begin
SetDebugeWrite('Share.pCP_903Result');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
sResult := sBody.Get('result').JsonValue.Value;
iHandle := FindWindow('TfrmMain', PChar('์ฝ๋ง๋ ๋ฉ์ ์ ' + GS_PRJ_AREA));
if iHandle <> 0 then
begin
if sResult = 'y' then
begin
CopyData.cbData := Length('ACTIVE') + 1;
CopyData.lpData := pAnsiChar('ACTIVE' + #0);
SendMessage(iHandle, WM_COPYDATA, 0, LongInt(@CopyData));
end else
begin
CopyData.cbData := Length('CLOSE') + 1;
CopyData.lpData := pAnsiChar('CLOSE' + #0);
SendMessage(iHandle, WM_COPYDATA, 0, LongInt(@CopyData));
Sleep(500);
Frm_Main.pExecMessenger(True);
end;
end;
finally
FreeAndNil(sBody);
end;
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure p999UpLogOut;
Var jsoRlt, headObj, subObj : TJSONObject;
Str : String;
begin
try
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
headObj := TJSONObject.Create;
headObj.AddPair( TJSONPair.Create('seq', '%s'));
headObj.AddPair( TJSONPair.Create('cmd', '999'));
jsoRlt.AddPair( TJSONPair.Create('hdr', headObj));
subObj := TJSONObject.Create;
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
Str := jsoRlt.ToString;
finally
FreeAndNil(jsoRlt);
end;
Dm.pSendCMessenger(False, Str);
except
end;
end;
procedure pCP_013MemoNoticeList(sCmd, sData : String );
var
slList: TStringList;
i, idx : integer;
sBody, subjObj : TJSONObject;
arrjObj: TJSONArray;
sKey : String;
begin
SetDebugeWrite('Share.pCP_013MemoNoticeList');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
if sCmd = '013' then
begin
try
arrjObj := TJSONObject.ParseJSONValue(sBody.Get('ls').JsonValue.ToString) as TJSONArray;
sData := '';
slGongjiList.Clear;
slGongjiKey.Clear;
for i := 0 to arrjObj.Size - 1 do
begin
subjObj := arrjObj.Get(i) as TJSONObject;
sData := subjObj.Get('wtm' ).JsonValue.Value + Char(1) + // 0.๋ฑ๋ก์ผ์
subjObj.Get('tit' ).JsonValue.Value + Char(1) + // 1.๊ณต์ง์ ๋ชฉ
subjObj.Get('cont').JsonValue.Value + Char(1) + // 2.๊ณต์ง๋ด์ฉ
subjObj.Get('wnm' ).JsonValue.Value + Char(1) + // 3.๋ฑ๋ก์๋ช
subjObj.Get('wid' ).JsonValue.Value + Char(1) + // 4.๋ฑ๋ก์ID
'c' + Char(1) + // 5.๊ตฌ๋ถ
subjObj.Get('nkey').JsonValue.Value + Char(1) + // 6.ํค๊ฐ
subjObj.Get('resv').JsonValue.Value; // 7.์์ฝ์ผ์
if Trim(sData) <> '' then
begin
slGongjiList.Add(sData);
slGongjiKey.Add(subjObj.Get('nkey').JsonValue.Value);
end;
end;
finally
arrjObj.Free;
end;
end else
if sCmd = '503' then
begin
sData := sBody.Get('wtm' ).JsonValue.Value + Char(1) + // 0.๋ฑ๋ก์ผ์
sBody.Get('tit' ).JsonValue.Value + Char(1) + // 1.๊ณต์ง์ ๋ชฉ
sBody.Get('cont').JsonValue.Value + Char(1) + // 2.๊ณต์ง๋ด์ฉ
sBody.Get('wnm' ).JsonValue.Value + Char(1) + // 3.๋ฑ๋ก์๋ช
sBody.Get('wid' ).JsonValue.Value + Char(1) + // 4.๋ฑ๋ก์ID
sBody.Get('wtp' ).JsonValue.Value + Char(1) + // 5.๊ตฌ๋ถ
sBody.Get('nkey').JsonValue.Value + Char(1) + // 6.ํค๊ฐ
sBody.Get('resv').JsonValue.Value + Char(2); // 7.์์ฝ์ผ์
if Trim(sData) <> '' then
begin
sKey := sBody.Get('nkey').JsonValue.Value;
if sBody.Get('wtp' ).JsonValue.Value = 'D' then
begin
idx := slGongjiKey.IndexOf(sBody.Get('nkey').JsonValue.Value);
if idx >= 0 then
begin
slGongjiKey.Delete(idx);
slGongjiList.Delete(idx);
end;
end else
if sBody.Get('wtp' ).JsonValue.Value = 'U' then
begin
idx := slGongjiKey.IndexOf(sBody.Get('nkey').JsonValue.Value);
if idx >= 0 then slGongjiList.Strings[idx] := sData;
end else
if sBody.Get('wtp' ).JsonValue.Value = 'C' then
begin
slGongjiList.Add(sData);
slGongjiKey.Add(sBody.Get('nkey').JsonValue.Value);
end;
end;
end;
try
if ( not Assigned(Frm_JON23) ) Or ( Frm_JON23 = Nil ) then Frm_JON23 := TFrm_JON23.Create(nil);
Frm_JON23.proc_AddList(slGongjiList);
except on E: Exception do
Assert(False, E.Message);
end;
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pCP_602ChargeRequest(sData: String);
var
sBody : TJSONObject;
vQ_Rate : TQ_Rate;
begin
SetDebugeWrite('Share.pCP_602ChargeRequest');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
vQ_Rate.cmd := '602';
vQ_Rate.rkey := sBody.Get('rkey' ).JsonValue.Value;
vQ_Rate.uid := sBody.Get('uid' ).JsonValue.Value;
vQ_Rate.unm := fJsonDecode(sBody.Get('unm' ).JsonValue.Value);
vQ_Rate.brno := sBody.Get('brno' ).JsonValue.Value;
vQ_Rate.cuhp := sBody.Get('cuhp' ).JsonValue.Value;
try
vQ_Rate.brkeynum := sBody.Get('brkeynum' ).JsonValue.Value;
except
end;
vQ_Rate.corpnm := sBody.Get('corpnm' ).JsonValue.Value;
vQ_Rate.corpdepnm := sBody.Get('corpdepnm').JsonValue.Value;
vQ_Rate.sta := fJsonDecode(sBody.Get('sta' ).JsonValue.Value);
vQ_Rate.staddr := sBody.Get('staddr' ).JsonValue.Value;
vQ_Rate.via := fJsonDecode(sBody.Get('via' ).JsonValue.Value);
vQ_Rate.eda := fJsonDecode(sBody.Get('eda' ).JsonValue.Value);
vQ_Rate.edaddr := sBody.Get('edaddr' ).JsonValue.Value;
vQ_Rate.distance := sBody.Get('distance').JsonValue.Value;
vQ_Rate.Viadist := sBody.Get('viadist' ).JsonValue.Value;
vQ_Rate.rate := sBody.Get('rate' ).JsonValue.Value;
vQ_Rate.qtm := sBody.Get('qtm' ).JsonValue.Value;
vQ_Rate.aid := '';
vQ_Rate.anm := '';
vQ_Rate.arate := '0';
vQ_Rate.amsg := '';
vQ_Rate.atm := '';
vQ_Rate.jtype := sBody.Get('jtype' ).JsonValue.Value;
vQ_Rate.crkey := sBody.Get('crkey' ).JsonValue.Value;
vQ_Rate.StaX := sBody.Get('stax' ).JsonValue.Value;
vQ_Rate.StaY := sBody.Get('stay' ).JsonValue.Value;
vQ_Rate.ViaX := sBody.Get('viax' ).JsonValue.Value;
vQ_Rate.ViaY := sBody.Get('viay' ).JsonValue.Value;
vQ_Rate.EndX := sBody.Get('endx' ).JsonValue.Value;
vQ_Rate.EndY := sBody.Get('endy' ).JsonValue.Value;
finally
FreeAndNil(sBody);
end;
if GB_RQ_AUTOACTIVE then
begin
if ( Not Frm_Main.BtnFix.Down ) then
begin
Frm_Main.BtnFix.Down := True;
Frm_Main.BtnFixClick(Frm_Main.BtnFix);
end;
Frm_Main.cxPageControl2.ActivePageIndex := 3;
end;
pSetGridQRate(vQ_Rate);
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pCP_604ChargeAnswer(sCmd, sData: String);
var
sBody : TJSONObject;
vQ_Rate : TQ_Rate;
begin
SetDebugeWrite('Share.pCP_604ChargeAnswer');
try
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
vQ_Rate.cmd := sCmd;
vQ_Rate.rkey := sBody.Get('rkey' ).JsonValue.Value;
vQ_Rate.uid := sBody.Get('uid' ).JsonValue.Value;
vQ_Rate.unm := '';
vQ_Rate.sta := '';
vQ_Rate.staddr := '';
vQ_Rate.via := '';
vQ_Rate.eda := '';
vQ_Rate.edaddr := '';
vQ_Rate.rate := '';
vQ_Rate.qtm := '';
vQ_Rate.aid := sBody.Get('aid').JsonValue.Value;
vQ_Rate.anm := sBody.Get('anm').JsonValue.Value;
vQ_Rate.arate := sBody.Get('rate').JsonValue.Value;
vQ_Rate.amsg := sBody.Get('msg').JsonValue.Value;;
vQ_Rate.atm := sBody.Get('atm').JsonValue.Value;;
finally
FreeAndNil(sBody);
end;
// cxPageControl2.ActivePageIndex := 3;
pSetGridQRate(vQ_Rate);
except on E: Exception do
Assert(False, E.Message);
end;
end;
procedure pSetGridQRate( vQ_Rate : TQ_Rate );
Var iRow, i, iIdx, irKey, iUse, hMsg, iCnt, icrKey : Integer;
sType, vCRKey, sMsg : String;
bFirst : Boolean;
begin
try
// ์๊ธ๋ฌธ์ ํ ์๋ฒ์์ ์๊ธ ์ ํ๋ก ์จ ์๋ฃ๋ฅผ ๊ฐ์ง๊ณ ์๊ธ ๋ฌธ์ ๋ฑ๋ก
if ( vQ_Rate.Cmd = '601' ) Or ( vQ_Rate.Cmd = '603' ) then Exit;
bFirst := False;
irkey := Frm_Main.cxGridQRate.GetColumnByFieldName('rkey').Index;
icrKey := Frm_Main.cxGridQRate.GetColumnByFieldName('crkey').Index;
if ( vQ_Rate.Cmd = '602' ) then
begin
if ( GT_USERIF.Family = 'y' ) And ( GT_USERIF.LV = '60' ) then // 20120629 LYB
begin
if scb_FamilyBrCode.IndexOf(vQ_Rate.brno) < 0 then Exit;
end else
begin
if scb_BranchCode.IndexOf(vQ_Rate.brno) < 0 then Exit;
end;
iRow := Frm_Main.cxGridQRate.DataController.FindRecordIndexByText(0, iRkey, vQ_Rate.rkey, False, True, True);
if iRow < 0 then
iRow := Frm_Main.cxGridQRate.DataController.AppendRecord;
sType := '์๊ธ๋ฌธ์';
end else
if ( vQ_Rate.Cmd = '604' ) then
begin
iRow := Frm_Main.cxGridQRate.DataController.FindRecordIndexByText(0, iRkey, vQ_Rate.rKey, False, True, True);
if iRow < 0 then Exit;
vCRKey := Frm_Main.cxGridQRate.DataController.Values[iRow, icrKey];
sType := '๋ต๋ณ์๋ฃ';
end else
if ( vQ_Rate.Cmd = '605' ) then
begin
iRow := Frm_Main.cxGridQRate.DataController.FindRecordIndexByText(0, iRkey, vQ_Rate.rKey, False, True, True);
if iRow < 0 then Exit;
vCRKey := Frm_Main.cxGridQRate.DataController.Values[iRow, icrKey];
sType := '์๋๋ต๋ณ';
end;
if iRow < 0 then Exit;
Frm_Main.cxGridQRate.BeginUpdate;
try
if ( vQ_Rate.Cmd = '602' ) then
begin
Frm_Main.cxGridQRate.DataController.Values[iRow, 00] := vQ_Rate.qtm;
Frm_Main.cxGridQRate.DataController.Values[iRow, 02] := vQ_Rate.unm;
Frm_Main.cxGridQRate.DataController.Values[iRow, 03] := sType;
Frm_Main.cxGridQRate.DataController.Values[iRow, 04] := vQ_Rate.brno;
Frm_Main.cxGridQRate.DataController.Values[iRow, 05] := StrToCall(vQ_Rate.cuhp); // ์ ํ๋ฒํธ
Frm_Main.cxGridQRate.DataController.Values[iRow, 06] := '';
Frm_Main.cxGridQRate.DataController.Values[iRow, 07] := vQ_Rate.brkeynum;
Frm_Main.cxGridQRate.DataController.Values[iRow, 08] := vQ_Rate.corpnm;
Frm_Main.cxGridQRate.DataController.Values[iRow, 09] := vQ_Rate.corpdepnm;
Frm_Main.cxGridQRate.DataController.Values[iRow, 10] := vQ_Rate.sta;
Frm_Main.cxGridQRate.DataController.Values[iRow, 11] := StringReplace(vQ_Rate.staddr, ',', ' ', [rfReplaceAll]);
Frm_Main.cxGridQRate.DataController.Values[iRow, 12] := vQ_Rate.via;
Frm_Main.cxGridQRate.DataController.Values[iRow, 13] := vQ_Rate.eda;
Frm_Main.cxGridQRate.DataController.Values[iRow, 14] := StringReplace(vQ_Rate.edaddr, ',', ' ', [rfReplaceAll]);
Frm_Main.cxGridQRate.DataController.Values[iRow, 15] := vQ_Rate.distance;
Frm_Main.cxGridQRate.DataController.Values[iRow, 16] := vQ_Rate.ViaDist; // ๊ฒฝ์ ๊ฑฐ๋ฆฌ
Frm_Main.cxGridQRate.DataController.Values[iRow, 17] := StrToInt(vQ_Rate.rate);
Frm_Main.cxGridQRate.DataController.Values[iRow, 18] := 0;
Frm_Main.cxGridQRate.DataController.Values[iRow, 19] := '';
Frm_Main.cxGridQRate.DataController.Values[iRow, 20] := '';
Frm_Main.cxGridQRate.DataController.Values[iRow, 21] := '';
Frm_Main.cxGridQRate.DataController.Values[iRow, 22] := vQ_Rate.rkey;
Frm_Main.cxGridQRate.DataController.Values[iRow, 23] := vQ_Rate.uid;
Frm_Main.cxGridQRate.DataController.Values[iRow, 24] := vQ_Rate.crkey;
Frm_Main.cxGridQRate.DataController.Values[iRow, 25] := '';
Frm_Main.cxGridQRate.DataController.Values[iRow, 26] := vQ_Rate.jtype;
Frm_Main.cxGridQRate.DataController.Values[iRow, 27] := vQ_Rate.StaX;
Frm_Main.cxGridQRate.DataController.Values[iRow, 28] := vQ_Rate.StaY;
Frm_Main.cxGridQRate.DataController.Values[iRow, 29] := vQ_Rate.ViaX;
Frm_Main.cxGridQRate.DataController.Values[iRow, 30] := vQ_Rate.ViaY;
Frm_Main.cxGridQRate.DataController.Values[iRow, 31] := vQ_Rate.EndX;
Frm_Main.cxGridQRate.DataController.Values[iRow, 32] := vQ_Rate.EndY;
end else
begin
if Trim(Frm_Main.cxGridQRate.DataController.Values[iRow, 19]) = '' then bFirst := True;
if ( vQ_Rate.Cmd = '605' ) then
Frm_Main.cxGridQRate.DataController.Values[iRow, 1] := '์ฆ์';
Frm_Main.cxGridQRate.DataController.Values[iRow, 3] := sType;
Frm_Main.cxGridQRate.DataController.Values[iRow, 21] := vQ_Rate.atm;
if ( vQ_Rate.Cmd = '605' ) then
Frm_Main.cxGridQRate.DataController.Values[iRow, 20] := 'SYSTEM'
else
Frm_Main.cxGridQRate.DataController.Values[iRow, 20] := vQ_Rate.anm;
Frm_Main.cxGridQRate.DataController.Values[iRow, 18] := StrToIntDef(vQ_Rate.arate, 0);
Frm_Main.cxGridQRate.DataController.Values[iRow, 19] := vQ_Rate.amsg;
end;
finally
Frm_Main.cxGridQRate.EndUpdate;
if Frm_Main.cxGridQRate.DataController.RecordCount > 0 then
Frm_Main.tsBtmMenu4.Caption := Format('์๊ธ๋ฌธ์(%s)',[FormatFloat('#,##0', Frm_Main.cxGridQRate.DataController.RecordCount)])
else
Frm_Main.tsBtmMenu4.Caption := '์๊ธ๋ฌธ์';
end;
Frm_Main.cxGridQRate.Columns[0].SortIndex := 0;
Frm_Main.cxGridQRate.Columns[0].SortOrder := soDescending;
if ( vQ_Rate.Cmd = '602' ) then
begin
if vQ_Rate.uid <> GT_USERIF.ID then
begin
if Trim(vQ_Rate.via) = '' then
begin
sMsg := '์ถ๋ฐ์ง: ' + vQ_Rate.sta + CRLF +
'๋์ฐฉ์ง: ' + vQ_Rate.eda + CRLF +
'๊ฑฐ๋ฆฌ: ' + vQ_Rate.distance + ' ์๊ธ: ' + FormatFloat('#,', StrToFloat(vQ_Rate.rate)) + '์';
end else
begin
sMsg := '์ถ๋ฐ์ง: ' + vQ_Rate.sta + CRLF +
'๊ฒฝ์ ์ง: ' + vQ_Rate.via + CRLF +
'๋์ฐฉ์ง: ' + vQ_Rate.eda + CRLF +
'๊ฑฐ๋ฆฌ: ' + vQ_Rate.distance + '-' + vQ_Rate.ViaDist + ' ์๊ธ: ' + FormatFloat('#,', StrToFloat(vQ_Rate.rate)) + '์';
end;
// if GB_RQ_CLOSEPOPUP then
// begin
// if ( Frm_Main.BtnFix.Down ) And ( Frm_Main.cxPageControl2.ActivePageIndex = 3 ) then
// begin
// bPopUp := False;
// end else
// begin
// bPopUp := True;
// end;
// end else
// begin
// bPopUp := True;
// end;
if GB_RQ_CLOSEPOPUP then
begin
if ( GT_USERIF.LV = '10' ) And ( TCK_USER_PER.BTM_10LVL_RQUEST <> '1' ) then Exit;
fAlertWindow := Frm_Main.awmAlert.Show('์๊ธ๋ฌธ์[' + vQ_Rate.unm + ']', sMsg, 60);
fAlertWindow.Hint := vQ_Rate.rkey;
irKey := Frm_Main.cxGridQRate.GetColumnByFieldName('rkey').Index;
iRow := Frm_Main.cxGridQRate.DataController.FindRecordIndexByText(0, irKey, vQ_Rate.rkey, False, True, True);
if ( iRow >= 0 ) then
begin
iCnt := 0;
for i := 0 to 30 do
begin
if ( Assigned(Frm_Main.Frm_COM50[i]) ) And ( Frm_Main.COM50MNG[i].CreateYN ) then
begin
Inc(iCnt);
end;
end;
if iCnt = 0 then
begin
Frm_Main.iCom50Top := Screen.Height - ( Screen.Height - 100 );
Frm_Main.iCom50Left := 5;
end;
if iCnt > 30 then
begin
hMsg := FindWindow('TMessageForm', 'CMNAGTXE');
if hMsg <> 0 then
SendMessage(hMsg, WM_CLOSE, 0, 0);
GMessagebox('์๊ธ๋ฌธ์ ํ์
์ฐฝ ์ต๋ ์์ฑ์๋ฅผ ์ด๊ณผํ์์ต๋๋ค. ์๊ธ๋ฌธ์ ํ์
์ฐฝ์ ๋ซ๊ณ ์ฌ์ฉํ์ธ์~ @_@', CDMSE);
Exit;
end;
iUse := -1;
for i := 0 to 30 do
begin
if ( Assigned(Frm_Main.Frm_COM50[i]) ) And ( Frm_Main.COM50MNG[i].CreateYN ) then
begin
if vQ_Rate.rkey = Frm_Main.Frm_COM50[i].lblRQStart.Hint then
begin
iUse := i;
Break;
end;
end;
end;
if iUse < 0 then
begin
for i := 0 to 30 do
begin
if ( Not Assigned(Frm_Main.Frm_COM50[i]) ) Or ( Frm_Main.COM50MNG[i].CreateYN = False ) then
begin
Frm_Main.Frm_COM50[i] := TFrm_COM50.Create(Nil);
Frm_Main.Frm_COM50[i].Tag := i;
Frm_Main.COM50MNG[i].CreateYN := True;
Frm_Main.Frm_COM50[i].Top := Frm_Main.iCom50Top;
Frm_Main.Frm_COM50[i].Left := Frm_Main.iCom50Left;
iUse := i;
Break;
end;
end;
end;
Frm_Main.iCom50Top := Frm_Main.iCom50Top + 20;
Frm_Main.iCom50Left := Frm_Main.iCom50Left + 20;
if Screen.Height - (Frm_Main.iCom50Top + 130) < Frm_Main.Frm_COM50[iUse].Height then
begin
Frm_Main.Frm_COM50[iUse].Left := 5;
Frm_Main.Frm_COM50[iUse].Top := Screen.Height - ( Screen.Height - 100 );
end;
Frm_Main.Frm_COM50[iUse].pnlTitle.Caption := Format(' ์๊ธ ๋ฌธ์ ๋ต๋ณ (%d)', [iUse]);
Frm_Main.Frm_COM50[iUse].lblRQNm.Caption := vQ_Rate.unm + '(' + vQ_Rate.uid + ')';
Frm_Main.Frm_COM50[iUse].lblQTime.Caption := FormatDateTime('HH:NN:SS', StrToDatetime(vQ_Rate.qtm));
Frm_Main.Frm_COM50[iUse].lblRQbrKeynum.Caption := vQ_Rate.brkeynum;
Frm_Main.Frm_COM50[iUse].lblRQCorpNm.Caption := vQ_Rate.CorpNm;
Frm_Main.Frm_COM50[iUse].lblRQCorpDepNm.Caption := vQ_Rate.CorpDepNm;
Frm_Main.Frm_COM50[iUse].lblRQStart.Hint := vQ_Rate.rkey;
Frm_Main.Frm_COM50[iUse].lblRQVia.Hint := vQ_Rate.uid;
Frm_Main.Frm_COM50[iUse].lblRQEnd.Hint := vQ_Rate.crkey;
Frm_Main.Frm_COM50[iUse].lblRQStart.Caption := vQ_Rate.sta;
Frm_Main.Frm_COM50[iUse].lblRQStartAddr.Caption := StringReplace(vQ_Rate.staddr, ',', ' ', [rfReplaceAll]);
Frm_Main.Frm_COM50[iUse].lblRQVia.Caption := vQ_Rate.via;
if Trim(Frm_Main.Frm_COM50[iUse].lblRQVia.Caption) = '' then
begin
Frm_Main.Frm_COM50[iUse].pnlVia.Visible := False;
Frm_Main.Frm_COM50[iUse].pnlRQBtm.Top := 142;
Frm_Main.Frm_COM50[iUse].Height := 315;
end else
begin
Frm_Main.Frm_COM50[iUse].pnlVia.Visible := True;
Frm_Main.Frm_COM50[iUse].pnlRQBtm.Top := 168;
Frm_Main.Frm_COM50[iUse].Height := 340;
end;
Frm_Main.Frm_COM50[iUse].lblRQEnd.Caption := vQ_Rate.eda;
Frm_Main.Frm_COM50[iUse].lblRQEndAddr.Caption := StringReplace(vQ_Rate.edaddr, ',', ' ', [rfReplaceAll]);
Frm_Main.Frm_COM50[iUse].lblDistance.Caption := vQ_Rate.distance;
Frm_Main.Frm_COM50[iUse].lblVDistance.Caption := vQ_Rate.ViaDist;
Frm_Main.Frm_COM50[iUse].lblRQRate.Caption := FormatFloat('#,', StrToFloat(vQ_Rate.rate));
Frm_Main.Frm_COM50[iUse].curPRate.Value := StrToIntDef(vQ_Rate.rate, 0);
fSetFont(Frm_Main.Frm_COM50[iUse], GS_FONTNAME);
Frm_Main.Frm_COM50[iUse].Show;
end;
end;
end;
end;
try
if ( vQ_Rate.Cmd = '604' ) Or ( vQ_Rate.Cmd = '605' ) then
begin
// ๋ต๋ณ ํ์
์ฐฝ ์๋ ์ข
๋ฃ - ์๊ธ๋ฌธ์์ ๋ํ ์๋ต์ด ์๋ฃ ๋์ ๊ฒฝ์ฐ 2021.07.01. ์์ คํ๋ฌ์ค ์์ฒญ
if ( vQ_Rate.Cmd = '604' ) then
begin
for i := 0 to 30 do
begin
if ( Assigned(Frm_Main.Frm_COM50[i]) ) And ( Frm_Main.COM50MNG[i].CreateYN ) then
begin
if vCRKey = Frm_Main.Frm_COM50[i].lblRQEnd.Hint then
begin
Frm_Main.Frm_COM50[i].pnlRQPopup.Enabled := False;
Frm_Main.Frm_COM50[i].cxLabel8.Caption := '์๊ธ๋ฌธ์ ์์ฒญํ ์๋ด์์ ์๊ธ๋ต๋ณ์ด ์๋ฃ๋์์ผ๋ฏ๋ก' + CRLF + CRLF +
'์๊ธ๋ฌธ์ ๋ต๋ณ ์ฐฝ ์๋ ์ข
๋ฃํฉ๋๋ค.';
Frm_Main.Frm_COM50[i].pnlAutoClose.Left := (Frm_Main.Frm_COM50[i].pnlRQPopup.Width - Frm_Main.Frm_COM50[i].pnlAutoClose.Width) div 2;
Frm_Main.Frm_COM50[i].pnlAutoClose.Top := (Frm_Main.Frm_COM50[i].pnlRQPopup.Height - Frm_Main.Frm_COM50[i].pnlAutoClose.Height) div 2;
Frm_Main.Frm_COM50[i].pnlAutoClose.Visible := True;
Frm_Main.Frm_COM50[i].Timer1.Enabled := True;
end;
end;
end;
end;
for i := 0 to JON_MAX_CNT - 1 do
begin
if Frm_Main.JON01MNG[i].rKey = vCRKey then
begin
Frm_Main.Frm_JON01N[i].Lbl_Charge.Caption := '';
Frm_Main.Frm_JON01N[i].pnl_Charge.Visible := False;
if ( GB_RQ_APPLYRATE ) then // ์๋๋ต๋ณ : - ์๋ฒ ์๋๋ต๋ณ ์๊ธ ์๋์ ์ฉ
begin
if vQ_Rate.Cmd = '605' then
begin
Frm_Main.Frm_JON01N[i].curRate.Value := StrToInt(vQ_Rate.arate);
Frm_Main.Frm_JON01N[i].Lbl_Charge.Caption := Format('System(์๋๋ต๋ณ)๋์ ๋ต๋ณ์๊ธ ์๋์ ์ฉ, ์ค๋ช
: %s', [vQ_Rate.amsg]);
Frm_Main.Frm_JON01N[i].Lbl_Distance.Caption := '';
Frm_Main.Frm_JON01N[i].pnl_Charge.height := 21;
Frm_Main.Frm_JON01N[i].pnl_Charge.Visible := True;
if Frm_Main.Frm_JON01N[i].curRate.CanFocus then Frm_Main.Frm_JON01N[i].curRate.SetFocus;
end;
end;
try
iRow := Frm_Main.Frm_JON01N[i].RQAListView.DataController.AppendRecord;
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 00] := iRow+1;
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 01] := StrToIntDef(vQ_Rate.arate, 0);
if vQ_Rate.Cmd = '605' then
begin
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 02] := 'System(์๋๋ต๋ณ)';
end else
begin
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 02] := Format('%s(%s)', [vQ_Rate.anm, vQ_Rate.aid]);
end;
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 03] := vQ_Rate.amsg;
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 04] := FormatDateTime('HH:NN:SS', StrToDateTime(vQ_Rate.atm));
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 06] := vQ_Rate.rkey;
irKey := Frm_Main.cxGridQRate.GetColumnByFieldName('rkey').Index;
iIdx := Frm_Main.cxGridQRate.DataController.FindRecordIndexByText(0, irKey, vQ_Rate.rkey, False, True, True);
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 07] := Frm_Main.cxGridQRate.DataController.GetValue(iIdx, 22); // uid
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 08] := Frm_Main.cxGridQRate.DataController.GetValue(iIdx, 02); // unm
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 09] := Frm_Main.cxGridQRate.DataController.GetValue(iIdx, 09); // sta
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 10] := Frm_Main.cxGridQRate.DataController.GetValue(iIdx, 10); // staddr
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 11] := Frm_Main.cxGridQRate.DataController.GetValue(iIdx, 11); // via
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 12] := Frm_Main.cxGridQRate.DataController.GetValue(iIdx, 12); // eda
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 13] := Frm_Main.cxGridQRate.DataController.GetValue(iIdx, 13); // edaddr
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 14] := Frm_Main.cxGridQRate.DataController.GetValue(iIdx, 00); // qtm
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 15] := vQ_Rate.aid;
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 16] := vQ_Rate.anm;
Frm_Main.Frm_JON01N[i].RQAListView.DataController.Values[iRow, 17] := vQ_Rate.atm;
finally
// Frm_JON01N[i].RQAListView.Columns[1].SortIndex := 0;
// Frm_JON01N[i].RQAListView.Columns[1].SortOrder := soDescending;
end;
Frm_Main.Frm_JON01N[i].gbRQAList.BringToFront;
Frm_Main.Frm_JON01N[i].gbRQAList.Visible := True;
Break;
end;
end;
end;
Application.ProcessMessages;
except
end;
except
end;
end;
function fFindQRForm(sHint: string): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to 30 do
begin
if Assigned(Frm_Main.Frm_COM50[i]) then
begin
if sHint = Frm_Main.Frm_COM50[i].lblRQStart.Hint then
begin
Result := i;
Break;
end;
end;
end;
end;
function fJsonEncode( sTxt : String ) : String;
begin
Result := StringReplace(sTxt, '"', cQUOTATION_MARK, [rfReplaceAll]);
end;
function fJsonDecode( sTxt : String ) : String;
begin
Result := StringReplace(sTxt, cQUOTATION_MARK, '"', [rfReplaceAll]);
end;
procedure pGetMakeHead( Var jsoHd : TJSONObject; sId : String );
Var subObj : TJSONObject;
begin
try
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('seq', IntToStr(GI_SEQ)));
subObj.AddPair( TJSONPair.Create('cmd', sId));
jsoHd.AddPair( TJSONPair.Create('hdr', subObj));
except
ShowMessage('ํค๋ ์์ฑ ์ค๋ฅ');
end;
end;
procedure p1501SetChat(FrmTag : Integer; sCd, sKey, sId, sNm, sMsg, sFCmd, sFnm, sflId, sflNm : String; bFirst : Boolean);
Var jsoRlt, subObj, aryObj : TJSONObject;
jso : TJSONObject;
jsoAry : TJSONArray;
jsoPar : TJSONPair;
sToCd, Str, Str2, StrRlt, StrRlt1, StrRlt2, sFont : String;
i, j : Integer;
slId, slNm : TStringList;
iError, iSeq : Integer;
begin
SetDebugeWrite('p1501SetChat - sMsg : ' + sMsg);
// Make Json -----------------------------------------------------------------
try
jsoRlt := TJSONObject.Create;
try
Inc(GI_SEQ);
except
GI_SEQ := 1;
end;
pGetMakeHead(jsoRlt, sCd); //1501
subObj := TJSONObject.Create;
subObj.AddPair( TJSONPair.Create('ckey', sKey));
// gsKey := sKey; //GT_USERIF.ID + '_' + FormatDateTime('ddhhmmss', Now);
slId := TStringList.Create;
slNm := TStringList.Create;
GetTextSeperationEx2(AnsiChar(1), sId, slId); //'sntest'#1'rlagustn'
GetTextSeperationEx2(AnsiChar(1), sNm, slNm); //'์ฝ๋ง๋1'#1'๊นํ์'
jsoAry := TJSONArray.Create;
for i := 0 to slId.Count - 1 do
begin
jso := TJSONObject.Create;
jso.AddPair(TJsonPair.Create('cid', slId.Strings[i]));
jso.AddPair(TJsonPair.Create('cnm', slNm.Strings[i]));
jsoAry.AddElement(jso);
end;
subObj.AddPair( TJSONPair.Create('ls', jsoAry));
sFont := GS_EnvFile.ReadString('CM_FONT', 'FontName', '๊ตด๋ฆผ') + 'โ' +
IntToStr(GS_EnvFile.ReadInteger('CM_FONT', 'FontSize', 9 )) + 'โ' +
GS_EnvFile.ReadString('CM_FONT', 'FontColor', ColorToString(clBlack)) + 'โ' +
GS_EnvFile.ReadString('CM_FONT', 'FontStyle', '');
subObj.AddPair( TJSONPair.Create('font', sFont)); //'๊ตด๋ฆผโ9โclBlackโ'
subObj.AddPair( TJSONPair.Create('msg', sMsg)); //#$A'์ฝ๋ง๋1<sntest>|ใ
ใ
ใ
'
subObj.AddPair( TJSONPair.Create('snum', ''{CC_SNum[FrmTag]})); // CC_SNum ์ฑํ
์ฐฝ์๋ฒ๋ฒํธ / CN_SNum ์ชฝ์ง์ฐฝ ์๋ฒ๋ฒํธ
jsoRlt.AddPair( TJSONPair.Create('bdy', subObj));
//'{"hdr":{"seq":"%s","cmd":"201"},
// "bdy":{"ckey":"sntest_13155053",
// "ls":[{"cid":"sntest","cnm":"์ฝ๋ง๋1"},
// {"cid":"rlagustn","cnm":"๊นํ์"}],
// "font":"๊ตด๋ฆผโ9โclBlackโ",
// "msg":"\n์ฝ๋ง๋1<sntest>|ใ
ใ
ใ
",
// "snum":""}}'
Str := jsoRlt.ToString;
Dm.pSendCMessenger(True, Str);
finally
FreeAndNil(jsoRlt);
FreeAndNil(slId);
FreeAndNil(slNm);
end;
end;
procedure pCP_711Result(sData: String);
var
sBody : TJSONObject;
sSlip, sAccTime : String;
iCheck : Boolean;
i : integer;
begin
SetDebugeWrite('Share.pCP_801GetBrCash');
sBody := TJSONObject.ParseJSONValue(sData) as TJSONObject;
try
sSlip := sBody.Get('slip').JsonValue.Value;
sAccTime := sBody.Get('acct').JsonValue.Value;
finally
FreeAndNil(sBody);
end;
try
iCheck := False;
for I := 0 to JON03_MAX_CNT - 1 do
begin
if Frm_Main.JON03MNG[i].Use then
begin
iCheck := True;
end;
end;
if Not iCheck then Frm_Main.procMainMenuCreateActive(200);
Frm_Main.AcceptFromCreate(sSlip, sAccTime, '์กฐํ', GI_JON03_LastFromIdx);
except
end;
end;
end.
|
unit class_taylor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Dialogs;
type
TTaylor = class
ErrorAllowed: Real;
Sequence,
FunctionList: TstringList; //lista de las func
FunctionType: Integer;
AngleType: Integer;
x: Real;
function Execute(): Real;
private
Error,
Angle: Real;
function sen(): Real;
function cos(): Real;
function exponencial():Real;
function arcsen():Real;
function tan():Real;
function senh():Real;
function cosh():Real;
function csc():Real;
function tanh():Real;
function arctan():Real;
function arctanh():Real;
public
constructor create;
destructor Destroy; override;
end;
const
IsSin = 0;
IsCos = 1;
IsExp = 2;
IsTan=3;
IsCsc = 4;
IsArcSen=5;
IsArctan =6;
IsSenh =7;
IsCosh=8;
Istanh=9;
IsArctanh=10;
AngleSexagedecimal = 0;
AngleRadian = 1;
implementation
const
Top = 100000;
constructor TTaylor.create;
begin
Sequence:= TStringList.Create;
FunctionList:= TStringList.Create;
FunctionList.AddObject( 'sen', TObject( IsSin ) );
FunctionList.AddObject( 'cos', TObject( IsCos ) );
FunctionList.AddObject( 'Exp', TObject( IsExp) );
FunctionList.AddObject('Tan', TObject(IsTan));
FunctionList.AddObject('Csc', TObject(IsCsc) );
FunctionList.AddObject( 'ArcSen', TObject( IsArcSen));
FunctionList.AddObject('ArcTan',TObject(IsArctan));
FunctionList.AddObject('SenH', TObject(IsSenh));
FunctionList.AddObject('CosH', TObject(IsCosh));
FunctionList.AddObject('TanH',TObject(IsTanh));
FunctionList.AddObject('ArctanH',TObject(IsArctanh));
Sequence.Add('');
Error:= Top;
x:= 0;
end;
destructor TTaylor.Destroy;
begin
Sequence.Destroy;
FunctionList.Destroy;
end;
function Power( b: Real; n: Integer ): Real;
var i: Integer;
begin
Result:= 1;
for i:= 1 to n do
Result:= Result * b;
end;
function Factorial( n: Integer ): Double;
begin
if n > 1 then
Result:= n * Factorial( n -1 )
else if n >= 0 then
Result:= 1
else
Result:= 0;
end;
function Combinatoria(n: Integer; p:Integer):Double;
begin
Result:= Factorial(n) /( Factorial(n-p)*Factorial(p));
end;
function Bernoulli(k: Integer): Extended;
var
i: Integer;
begin
Result := 0;
if k = 0 then
Result := 1
else if k = 1 then
Result := -1/2
else if k mod 2 = 1 then
Result := 0
else
begin
for i:=0 to k-1 do
Result := Result + Combinatoria(k,i) * (Bernoulli(i)/(k + 1 - i));
Result := - Result;
end;
end;
function TTaylor.Execute( ): Real;
begin
case AngleType of
AngleRadian: Angle:= x; //si es radian angulo = x
AngleSexagedecimal: Angle:=x * pi/180; //si es sexagesimal conversion
end;
case FunctionType of
IsSin: Result:= sen(); //function type depende si es seno o cos
IsCos: Result:= cos();
IsExp: Result:=exponencial();
IsArcSen: Result:= arcsen();
IsTan: Result:=tan();
IsSenh: Result := senh();
isCosh:Result:=cosh();
IsCsc:Result:=csc();
IsTanh:Result:=tanh();
IsArctan:Result:=arctan();
IsArctanh:Result:=arctanh();
end;
end;
function TTaylor.sen(): Real;
var xn: Real;
n: Integer;
begin
Result:= 0;
n:= 0;
repeat
xn:= Result;
Result:= Result + Power(-1, n)/Factorial( 2*n + 1 ) * Power(Angle, 2*n + 1);
if n > 0 then
Error:= abs( Result - xn );
Sequence.Add( FloatToStr( Result ) );
n:= n + 1;
until ( Error <= ErrorAllowed ) or ( n >= Top ) ;
end;
function TTaylor.cos(): Real;
var xn: real;
n: Integer;
begin
Result:= 0;
n:= 0;
repeat
xn:= Result;
Result:= Result + Power(-1, n)/Factorial(2*n) * Power( Angle, 2*n );
Sequence.Add( FloatToStr( Result ) );
if n > 0 then
Error:= abs( Result - xn );
n:= n + 1;
until ( Error < ErrorAllowed ) or ( n >= Top );
end;
function TTaylor.exponencial(): Real;
var xn: Real;
n: Integer;
angle_of: Real;
{case AngleType of
AngleSexagedecimal: Angle:= x; //si es radian angulo = x
AngleRadian: Angle:= x * 180/pi; //si es sexagesimal conversion }
begin
angle_of:= angle * 180 / pi;
n:= 0;
Result:= 0;
repeat
xn:= Result;
Result:= Result + (Power(angle_of,n) / Factorial(n));
Sequence.Add( FloatToStr( Result ) );
if n > 0 then
Error:= abs( Result - xn );
n:= n + 1;
until (Error < ErrorAllowed ) or (n >= Top );
end;
function TTaylor.senh(): Real;
var xn: Real;
n: Integer;
angle_of :Real;
begin
Result:= 0;
n:= 0;
angle_of:= angle * 180 / pi;
repeat
xn:= Result;
Result:= Result + 1/Factorial(2*n + 1) * Power(angle_of, 2*n + 1);
if n > 0 then
Error:= abs( Result - xn );
Sequence.Add( FloatToStr( Result ) );
n:= n + 1;
until ( Error <= ErrorAllowed ) or ( n >= Top ) ;
end;
function TTaylor.cosh():Real;
var xn: real;
n: Integer;
angle_of : Real;
begin
Result:= 0;
n:= 0;
angle_of:= angle * 180 / pi;
repeat
xn:= Result;
Result:= Result + 1/Factorial(2*n) * Power( angle_of, 2*n );
Sequence.Add( FloatToStr( Result ) );
if n > 0 then
Error:= abs( Result - xn );
n:= n + 1;
until ( Error < ErrorAllowed ) or ( n >= Top );
end;
function TTaylor.tan():Real;
var xn: Real;
n: Integer;
begin
if abs(angle) >= pi/2 then
begin
Result:= 0;
exit();
end;
Result:= 0;
n:= 1;
repeat
xn:= Result;
Result:= Result + ((Bernoulli(2*n) * Power(-4,n) * (1-Power(4,n)) )/Factorial(2*n) )* Power(angle,2*n -1 );
if n > 0 then
Error:= abs( Result - xn );
Sequence.Add( FloatToStr( Result ) );
n:= n + 1;
until ( Error <= ErrorAllowed ) or ( n >= Top ) ;
end;
function TTaylor.csc():Real;
var xn: real;
n: Integer;
begin
Result:= 0;
n:= 1;
repeat
xn:= Result;
Result:= Result + ((2*(Power(2,2*n-1) - 1))*Bernoulli(n)*Power(angle, 2*n-1)) / Factorial(2*n);
Sequence.Add( FloatToStr( Result ) );
if n > 0 then
Error:= abs( Result - xn );
n:= n + 1;
until ( Error < ErrorAllowed ) or ( n >= Top );
end;
function TTaylor.tanh(): Real;
var xn:Real;
n:Integer;
angle_of:Real;
begin
if abs(x * pi/180) > pi/2 then
begin
Result:= 0;
exit();
end;
Result := 0;
n := 0;
angle_of:= angle * 180 / pi ;
repeat
xn:= Result;
Result:= Result + ((Bernoulli(2*n)
*power(4,n)*(power(4,n) - 1))/factorial(2*n)) * power(angle,2*n - 1);
Sequence.Add( FloatToStr( Result ) );
if n > 0 then
Error:= abs( Result - xn );
n:= n + 1;
until ( Error < ErrorAllowed ) or ( n >= Top );
end;
function TTaylor.arctan(): Real;
var xn: Real;
n: Integer;
angle_of:Real;
begin
if abs(angle) > 1 then
begin
Result:= 0;
exit();
end;
Result:= 0;
n:= 0;
angle_of:= angle*180 / pi;
repeat
xn:= Result;
Result:= Result + Power(-1, n)/( 2*n + 1 ) * Power(angle_of, 2*n + 1);
if n > 0 then
Error:= abs( Result - xn );
Sequence.Add( FloatToStr( Result ) );
n:= n + 1;
until ( Error <= ErrorAllowed ) or ( n >= Top ) ;
end;
function TTaylor.arcsen():Real ;
var xn: Real;
n: Integer;
angle_of : Real;
begin
if abs(angle) > 1 then
begin
Result:= 0;
exit();
end;
n := 0;
Result := 0;
angle_of:= angle*180 / pi;
repeat
xn := Result;
Result := Result + Factorial( 2*n )/ ( Power( 4 , n)*Power( Factorial( n ) , 2)*(2*n + 1))*Power( angle_of, 2*n + 1);
Sequence.add( FloatToStr ( Result ) );
if n > 0 then
Error := abs( Result - xn);
n := n + 1;
until (Error < ErrorAllowed) or (n >= Top);
end;
function TTaylor.arctanh(): Real;
var xn: Real;
n: Integer;
angle_of:Real;
begin
if abs(angle) > 1 then
begin
Result:= 0;
exit();
end;
Result:= 0;
n:= 0;
angle_of:= angle*180 / pi;
repeat
xn:= Result;
Result:= Result + Power(1, n)/( 2*n + 1 ) * Power(Angle_of, 2*n + 1);
if n > 0 then
Error:= abs( Result - xn );
Sequence.Add( FloatToStr( Result ) );
n:= n + 1;
until ( Error <= ErrorAllowed ) or ( n >= Top ) ;
end;
end.
|
unit frm_SearchAndReplace;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, HCView;
type
TfrmSearchAndReplace = class(TForm)
pgTab: TPageControl;
tsSearch: TTabSheet;
tsReplace: TTabSheet;
cbbSearch: TComboBox;
btnSearchBackward: TButton;
btnSearchForward: TButton;
chkSearchCase: TCheckBox;
chkSearchHight: TCheckBox;
procedure btnSearchBackwardClick(Sender: TObject);
procedure btnSearchForwardClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FHCView: THCView;
procedure AddKey(const AText: string);
public
{ Public declarations }
procedure SetHCView(const AHCView: THCView);
procedure ShowSearch;
end;
var
frmSearchAndReplace: TfrmSearchAndReplace;
implementation
{$R *.dfm}
{ TfrmSearchAndReplace }
procedure TfrmSearchAndReplace.AddKey(const AText: string);
begin
if cbbSearch.Items.IndexOf(AText) < 0 then
cbbSearch.Items.Insert(0, AText);
end;
procedure TfrmSearchAndReplace.btnSearchBackwardClick(Sender: TObject);
begin
if not FHCView.Search(cbbSearch.Text, False, chkSearchCase.Checked) then
ShowMessage('ๅๅๆฅๆพๅฎๆ๏ผๆชๆพๅฐๅ
ณ้ฎๅญ๏ผ');
AddKey(cbbSearch.Text);
end;
procedure TfrmSearchAndReplace.btnSearchForwardClick(Sender: TObject);
begin
if not FHCView.Search(cbbSearch.Text, True, chkSearchCase.Checked) then
ShowMessage('ๅๅๆฅๆพๅฎๆ๏ผๆชๆพๅฐๅ
ณ้ฎๅญ๏ผ');
AddKey(cbbSearch.Text);
end;
procedure TfrmSearchAndReplace.FormShow(Sender: TObject);
begin
if pgTab.ActivePage = tsSearch then
cbbSearch.SetFocus;
end;
procedure TfrmSearchAndReplace.SetHCView(const AHCView: THCView);
begin
FHCView := AHCView;
end;
procedure TfrmSearchAndReplace.ShowSearch;
begin
pgTab.ActivePage := tsSearch;
Self.Show;
end;
end.
|
unit Metrics.ClassMethod;
interface
uses
{--}
Metrics.UnitMethod;
type
TVisibility = (visPrivate, visProtected, visPublic);
TVisibilityHelper = record helper for TVisibility
function ToString(): string;
function ToSymbol(): string;
end;
type
TClassMethodMetrics = class
private
fVisibility: TVisibility;
fName: string;
fUnitMethod: TUnitMethodMetrics;
public
constructor Create(aVisibility: TVisibility; const aName: string);
function WithCorrespondingUnitMethod(const aUnitMethod: TUnitMethodMetrics)
: TClassMethodMetrics;
property Visibility: TVisibility read fVisibility;
property Name: string read fName;
property UnitMethod: TUnitMethodMetrics read fUnitMethod;
end;
implementation
constructor TClassMethodMetrics.Create(aVisibility: TVisibility;
const aName: string);
begin
fVisibility := aVisibility;
fName := aName;
fUnitMethod := nil;
end;
function TClassMethodMetrics.WithCorrespondingUnitMethod(const aUnitMethod
: TUnitMethodMetrics): TClassMethodMetrics;
begin
fUnitMethod := aUnitMethod;
Result := Self;
end;
{ TVisibilityHelper }
function TVisibilityHelper.ToString: string;
begin
case Self of
visPrivate:
Result := 'private';
visProtected:
Result := 'protected';
visPublic:
Result := 'public';
else
Result := 'unknown-visibility';
end;
end;
function TVisibilityHelper.ToSymbol: string;
begin
case Self of
visPrivate:
Result := '-';
visProtected:
Result := '/';
visPublic:
Result := '+';
else
Result := '?';
end;
end;
end.
|
unit particle;
//a non game (GUI) object that takes it's texture from a pre-existing texture id
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, guiobject, gl, GLext;
type
TParticle=class(TGuiObject)
private
ftexture: integer;
fwidth: single;
fheight: single;
protected
function getWidth:single; override;
function getHeight:single; override;
procedure setWidth(w: single); override;
procedure setHeight(h: single); override;
function getTexture: integer; override;
public
constructor create(t: integer);
end;
implementation
procedure TParticle.setWidth(w: single);
begin
fwidth:=w;
end;
procedure TParticle.setHeight(h: single);
begin
fheight:=h;
end;
function TParticle.getWidth:single;
begin
result:=fwidth;
end;
function TParticle.getHeight:single;
begin
result:=fheight;
end;
function TParticle.getTexture: integer;
begin
result:=ftexture;
end;
constructor TParticle.create(t: integer);
begin
fwidth:=0.1;
fheight:=0.1;
fTexture:=t;
inherited create;
end;
end.
|
unit WebSiteControllerU;
interface
uses
MVCFramework, System.Diagnostics, System.JSON, MVCFramework.Commons;
type
TSpeedValue = class
private
FValue: string;
procedure SetValue(const Value: string);
public
property Value: string read FValue write SetValue;
constructor Create(const aValue: string);
end;
[MVCPath('/')]
TWebSiteController = class(TMVCController)
private
FStopWatch: TStopwatch;
function GetSpeed: TSpeedValue;
protected
procedure OnBeforeAction(Context: TWebContext; const AActionNAme: string;
var Handled: Boolean); override;
procedure GeneratePeopleListAsCSV;
public
[MVCPath('/people')]
[MVCHTTPMethods([httpGET])]
[MVCProduces(TMVCMediaType.TEXT_HTML)]
procedure PeopleList;
[MVCPath('/people')]
[MVCHTTPMethods([httpGET])]
[MVCProduces(TMVCMediaType.TEXT_CSV)]
// RESTful API, requires ACCEPT=text/csv
procedure ExportPeopleListAsCSV_API;
[MVCPath('/people/formats/csv')]
[MVCHTTPMethods([httpGET])]
// Route usable by the browser, doesn't requires ACCEPT=text/csv
procedure ExportPeopleListAsCSV;
[MVCPath('/people')]
[MVCHTTPMethods([httpPOST])]
[MVCConsumes(TMVCMediaType.APPLICATION_FORM_URLENCODED)]
procedure SavePerson;
[MVCPath('/deleteperson')]
[MVCHTTPMethods([httpPOST])]
[MVCConsumes(TMVCMediaType.APPLICATION_FORM_URLENCODED)]
procedure DeletePerson;
[MVCPath('/new')]
[MVCHTTPMethods([httpGET])]
[MVCProduces(TMVCMediaType.TEXT_HTML)]
procedure NewPerson;
[MVCPath('/edit/($guid)')]
[MVCHTTPMethods([httpGET])]
[MVCProduces(TMVCMediaType.TEXT_HTML)]
procedure EditPerson(guid: string);
[MVCPath('/')]
[MVCHTTPMethods([httpGET])]
[MVCProduces(TMVCMediaType.TEXT_HTML)]
procedure Index;
end;
implementation
{ TWebSiteController }
uses DAL, System.SysUtils, Web.HTTPApp;
procedure TWebSiteController.DeletePerson;
var
lID: string;
LDAL: IPeopleDAL;
begin
lID := Context.Request.Params['id'];
LDAL := TServicesFactory.GetPeopleDAL;
LDAL.DeleteByGUID(lID);
Redirect('/people');
end;
procedure TWebSiteController.EditPerson(guid: string);
var
LDAL: IPeopleDAL;
lPerson: TPerson;
begin
LDAL := TServicesFactory.GetPeopleDAL;
lPerson := LDAL.GetPersonByGUID(guid);
PushObjectToView('person', lPerson);
PushObjectToView('speed', GetSpeed);
LoadView(['header', 'editperson', 'footer']);
RenderResponseStream;
end;
procedure TWebSiteController.ExportPeopleListAsCSV;
begin
GeneratePeopleListAsCSV;
// define the correct behaviour to download the csv inside the browser
ContentType := TMVCMediaType.TEXT_CSV;
Context.Response.CustomHeaders.Values['Content-Disposition'] :=
'attachment; filename=people.csv';
end;
procedure TWebSiteController.ExportPeopleListAsCSV_API;
begin
GeneratePeopleListAsCSV;
end;
procedure TWebSiteController.GeneratePeopleListAsCSV;
var
LDAL: IPeopleDAL;
begin
LDAL := TServicesFactory.GetPeopleDAL;
PushObjectToView('people', LDAL.GetPeople);
LoadView(['people_header.csv', 'people_list.csv']);
RenderResponseStream; // rember to call RenderResponseStream!!!
end;
function TWebSiteController.GetSpeed: TSpeedValue;
begin
Result := TSpeedValue.Create(FStopWatch.Elapsed.TotalMilliseconds.ToString);
end;
procedure TWebSiteController.Index;
begin
Redirect('/people');
end;
procedure TWebSiteController.NewPerson;
begin
PushObjectToView('speed', GetSpeed);
LoadView(['header', 'editperson', 'footer']);
RenderResponseStream;
end;
procedure TWebSiteController.OnBeforeAction(Context: TWebContext;
const AActionNAme: string; var Handled: Boolean);
begin
inherited;
ContentType := 'text/html';
Handled := False;
FStopWatch := TStopwatch.StartNew;
end;
procedure TWebSiteController.PeopleList;
var
LDAL: IPeopleDAL;
lPeople: TPeople;
lSpeed: TSpeedValue;
begin
LDAL := TServicesFactory.GetPeopleDAL;
PushObjectToView('people', LDAL.GetPeople);
PushObjectToView('speed', GetSpeed);
LoadView(['header', 'people_list', 'footer']);
RenderResponseStream; // rember to call RenderResponseStream!!!
end;
procedure TWebSiteController.SavePerson;
var
LFirstName: string;
LLastName: string;
LAge: string;
LPeopleDAL: IPeopleDAL;
begin
LFirstName := Context.Request.Params['first_name'].Trim;
LLastName := Context.Request.Params['last_name'].Trim;
LAge := Context.Request.Params['age'];
if LFirstName.IsEmpty or LLastName.IsEmpty or LAge.IsEmpty then
begin
{ TODO -oDaniele -cGeneral : Show how to properly render an exception }
raise EMVCException.Create('Invalid data',
'First name, last name and age are not optional', 0);
end;
LPeopleDAL := TServicesFactory.GetPeopleDAL;
LPeopleDAL.AddPerson(LFirstName, LLastName, LAge.ToInteger(), []);
Redirect('/people');
end;
{ TSpeedValue }
constructor TSpeedValue.Create(const aValue: string);
begin
inherited Create;
FValue := aValue;
end;
procedure TSpeedValue.SetValue(const Value: string);
begin
FValue := Value;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.