text stringlengths 14 6.51M |
|---|
unit UFrmWorkerInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
uFrmGrid, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
dxSkinsCore, dxSkinsDefaultPainters, cxStyles, dxSkinscxPCPainter,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
dxSkinsdxBarPainter, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, ActnList, dxBar, DBClient, cxClasses, ExtCtrls,
cxGridLevel, cxGridCustomView, cxGrid, cxImageComboBox, cxNavigator,
cxDataControllerConditionalFormattingRulesManagerDialog;
type
TFrmWorkerInfo = class(TFrmGrid)
ClmnWorkerID: TcxGridDBColumn;
ClmnWorkerName: TcxGridDBColumn;
ClmnWorkerClass: TcxGridDBColumn;
ClmnBeginTime: TcxGridDBColumn;
ClmnEndTime: TcxGridDBColumn;
cxgrdbclmnIsStop: TcxGridDBColumn;
actInitPass: TAction;
btnInitPass: TdxBarButton;
procedure FormShow(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actNewExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure grdbtblvwDataDblClick(Sender: TObject);
procedure grdbtblvwDataKeyPress(Sender: TObject; var Key: Char);
procedure FormDestroy(Sender: TObject);
procedure actInitPassExecute(Sender: TObject);
procedure actlst1Update(Action: TBasicAction; var Handled: Boolean);
private
FClassList: TStrings;
function IsAdmin: Boolean;
procedure QueryWorkerInfo(ALocate: Boolean = False; AValue: string = '');
function GetWorkerClass(AList: TStrings): Boolean;
procedure DoShowWorkerInfoEdit(AAction: string);
public
end;
var
FrmWorkerInfo: TFrmWorkerInfo;
implementation
uses UMsgBox, HJYForms, UFrmWorkerInfoEdit, uSysObj, UHJYDataRecord,
uPubFunLib, uConst, HJYCryptors;
{$R *.dfm}
function TFrmWorkerInfo.IsAdmin: Boolean;
var
lClassID: string;
begin
lClassID := CdsData.FindField('WorkerID').AsString;
Result := SameText(lClassID, 'admin');
end;
procedure TFrmWorkerInfo.QueryWorkerInfo(ALocate: Boolean; AValue: string);
var
lStrSql: string;
begin
lStrSql := 'select a.*, b.ClassName from WorkerInfo a ' +
' inner join WorkerClass b on b.Guid=a.ClassGuid ' +
' where (a.IsDelete=0 or a.IsDelete is null) order by a.WorkerID';
if not DBAccess.ReadDataSet(lStrSql, CdsData) then
begin
ShowMsg('获取用户信息失败!');
Exit;
end;
if ALocate and (AValue <> '') then
if cdsData.Active and not cdsData.IsEmpty then
cdsData.Locate('WorkerID', AValue, [loCaseInsensitive]);
end;
function TFrmWorkerInfo.GetWorkerClass(AList: TStrings): Boolean;
var
lStrSql: string;
tmpCds: TClientDataSet;
begin
tmpCds := TClientDataSet.Create(nil);
try
lStrSql := 'select Guid, ClassName from WorkerClass ' +
' where (IsDelete=0 or IsDelete is null) order by ClassID';
Result := DBAccess.ReadDataSet(lStrSql, tmpCds);
if not Result then Exit;
AList.Clear;
UHJYDataRecord.FillList(tmpCds, 'ClassName', AList);
tmpCds.Close;
finally
FreeAndNil(tmpCds);
end;
end;
procedure TFrmWorkerInfo.actDeleteExecute(Sender: TObject);
const
DelWorkerClassSQL = 'update WorkerInfo set IsDelete=1, DeleteMan=''%s'', ' +
' DeleteTime=%s, EditTime=%s where Guid=''%s''';
var
lWorkerGuid, lStrSql: string;
begin
if CdsData.Active and not CdsData.IsEmpty then
begin
if IsAdmin then
begin
ShowMsg('“系统管理员”不允许删除!');
Exit;
end;
if not ShowConfirm('您确定要删除当前选择的角色信息吗?') then
Exit;
lWorkerGuid := CdsData.FindField('Guid').AsString;
lStrSql := Format(DelWorkerClassSQL, [Sys.WorkerInfo.WorkerID,
Sys.DateStr, Sys.DateStr, lWorkerGuid]);
if not DBAccess.ExecuteSQL(lStrSql) then
begin
ShowMsg('用户信息删除失败,请重新操作!');
Exit;
end;
QueryWorkerInfo;
end;
end;
procedure TFrmWorkerInfo.actEditExecute(Sender: TObject);
begin
if CdsData.Active and not CdsData.IsEmpty then
begin
if IsAdmin then
begin
ShowMsg('“系统管理员”不允许修改!');
Exit;
end;
DoShowWorkerInfoEdit('Edit');
end;
end;
procedure TFrmWorkerInfo.actInitPassExecute(Sender: TObject);
const
cInitPassSQL = 'update WorkerInfo set WorkerPass=''%s'', '+
' EditTime=%s, SyncState=0 where Guid=''%s''';
var
lStrSql: string;
lWorkerGuid: string;
begin
inherited;
if DataSetIsEmpty(cdsData) then
Exit;
if not ShowConfirm('您确定要初始化当前选择用户密码吗?') then
Exit;
lWorkerGuid := cdsData.FindField('Guid').AsString;
lStrSql := Format(cInitPassSQL, [MD5(cDefWorkerPass), Sys.DateStr, lWorkerGuid]);
if not DBAccess.ExecuteSQL(lStrSql) then
begin
ShowMsg('初始化密码失败!');
Exit;
end;
ShowMsg('初始化密码成功!' + #10#13 + '初始化后密码为“' + cDefWorkerPass + '”!');
end;
procedure TFrmWorkerInfo.actlst1Update(Action: TBasicAction; var Handled: Boolean);
begin
inherited;
actInitPass.Enabled := not DataSetIsEmpty(cdsData);
end;
procedure TFrmWorkerInfo.actNewExecute(Sender: TObject);
begin
if not CdsData.Active then
Exit;
DoShowWorkerInfoEdit('Append');
end;
procedure TFrmWorkerInfo.actRefreshExecute(Sender: TObject);
begin
QueryWorkerInfo;
end;
procedure TFrmWorkerInfo.DoShowWorkerInfoEdit(AAction: string);
begin
if not Assigned(FClassList) then
begin
FClassList := TStringList.Create;
if not GetWorkerClass(FClassList) then
begin
ShowMsg('获取角色信息失败!');
Exit;
end;
end;
FrmWorkerInfoEdit := TFrmWorkerInfoEdit.Create(nil);
try
FrmWorkerInfoEdit.OperAction := AAction;
FrmWorkerInfoEdit.cbbWorkerClass.Properties.Items.AddStrings(FClassList);
if AAction = 'Append' then
begin
FrmWorkerInfoEdit.cbbIsStop.ItemIndex := 0;
FrmWorkerInfoEdit.OnRefreshAfterPost := Self.QueryWorkerInfo;
end
else
begin
with FrmWorkerInfoEdit, CdsData do
begin
edtWorkerGuid.Text := FindField('Guid').AsString;
edtWorkerID.Text := FindField('WorkerID').AsString;
edtWorkerName.Text := FindField('WorkerName').AsString;
cbbWorkerClass.ItemIndex := GetDataRecordIndex(FClassList, 'Guid',
FindField('ClassGuid').AsString);
edtBeginTime.Date := FindField('BeginTime').AsDateTime;
edtEndTime.Date := FindField('EndTime').AsDateTime;
cbbIsStop.ItemIndex := FindField('IsStop').AsInteger;
end;
end;
if FrmWorkerInfoEdit.ShowModal = mrOk then
QueryWorkerInfo(True, Trim(FrmWorkerInfoEdit.edtWorkerID.Text));
finally
FreeAndNil(FrmWorkerInfoEdit);
end;
end;
procedure TFrmWorkerInfo.FormDestroy(Sender: TObject);
begin
if Assigned(FClassList) then
begin
ClearList(FClassList);
FreeAndNil(FClassList);
end;
inherited;
end;
procedure TFrmWorkerInfo.FormShow(Sender: TObject);
begin
inherited;
QueryWorkerInfo;
end;
procedure TFrmWorkerInfo.grdbtblvwDataDblClick(Sender: TObject);
begin
inherited;
actEditExecute(nil);
end;
procedure TFrmWorkerInfo.grdbtblvwDataKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if Key = #13 then
actEditExecute(nil);
end;
initialization
HJYFormManager.RegisterForm(TFrmWorkerInfo);
end.
|
{
ID: a_zaky01
PROG: fence4
LANG: PASCAL
}
const
ep=0.0000001;
type
point=record
x,y:extended;
end;
segment=record
p1,p2:point;
end;
var
n,i,j,count:longint;
pob,t1,t2,temp:point;
s1,s2:segment;
leg1,leg2:segment;
valid,in1,in2:boolean;
poly:array[1..200] of point;
seg:array[1..200] of segment;
seen:array[1..200] of boolean;
fin,fout:text;
{distance between two points}
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;
{length of a segment}
function length(s:segment):extended;
begin
length:=distance(s.p1,s.p2);
end;
{the z component of cross product of two vectors}
function cross(point1,point2:point):extended;
begin
cross:=point1.x*point2.y-point1.y*point2.x;
end;
{checks whether two points lies on the same side of a line or not}
function sameside(point1,point2:point; s:segment):boolean;
var
temp,temp1,temp2:point;
z1,z2:extended;
begin
with temp do
begin
x:=s.p2.x-s.p1.x;
y:=s.p2.y-s.p1.y;
end;
with temp1 do
begin
x:=point1.x-s.p1.x;
y:=point1.y-s.p1.y;
end;
with temp2 do
begin
x:=point2.x-s.p1.x;
y:=point2.y-s.p1.y;
end;
z1:=cross(temp,temp1);
z2:=cross(temp,temp2);
if z1*z2>0 then sameside:=true
else sameside:=false;
end;
{checks whether a point lies on a line or not}
function online(p:point; l:segment):boolean;
begin
online:=false;
with l do
if abs((p1.y-p.y)*(p2.x-p.x)-(p2.y-p.y)*(p1.x-p.x))<ep then online:=true;
end;
{checks whether a point lies on a segment or not}
function onsegment(p:point; s:segment):boolean;
begin
onsegment:=false;
if online(p,s) then
if abs(distance(p,s.p1)+distance(p,s.p2)-distance(s.p1,s.p2))<ep then onsegment:=true;
end;
{check whether two segments intersect each other or not}
function intersect(s1,s2:segment):boolean;
begin
intersect:=false;
if not sameside(s1.p1,s1.p2,s2) and not sameside(s2.p1,s2.p2,s1) then intersect:=true;
if onsegment(s1.p1,s2) or onsegment(s1.p2,s2) or onsegment(s2.p1,s1) or onsegment(s2.p2,s1) then intersect:=true
else if online(s1.p1,s2) and online(s1.p2,s2) then intersect:=false;
end;
{find the intersection point of two lines}
function intersectpoint(s1,s2:segment):point;
var
a1,a2,b1,b2,c1,c2,i:extended;
begin
if (s1.p1.y-s1.p2.y)*(s2.p1.x-s2.p2.x)=(s2.p1.y-s2.p2.y)*(s1.p1.x-s1.p2.x) then
with intersectpoint do
begin
x:=-50000.0;
y:=-50000.0;
end
else
begin
a1:=s1.p2.x-s1.p1.x;
b1:=s2.p1.x-s2.p2.x;
c1:=s2.p1.x-s1.p1.x;
a2:=s1.p2.y-s1.p1.y;
b2:=s2.p1.y-s2.p2.y;
c2:=s2.p1.y-s1.p1.y;
i:=(c1*b2-c2*b1)/(a1*b2-a2*b1);
with intersectpoint do
begin
x:=s1.p1.x+a1*i;
y:=s1.p1.y+a2*i;
end;
end;
end;
{checks wheter a point lies inside a triangle or not}
function intriangle(p,t1,t2,t3:point):boolean;
var
temp:point;
s1,s2,s3:segment;
begin
intriangle:=true;
with temp do
begin
x:=(t1.x+t2.x+t3.x)/3;
y:=(t1.y+t2.y+t3.y)/3;
end;
with s1 do
begin
p1:=t2;
p2:=t3;
end;
with s2 do
begin
p1:=t1;
p2:=t3;
end;
with s3 do
begin
p1:=t1;
p2:=t2;
end;
if not sameside(p,temp,s1) or not sameside(p,temp,s2) or not sameside(p,temp,s3) then intriangle:=false;
end;
begin
assign(fin,'fence4.in');
assign(fout,'fence4.out');
reset(fin);
rewrite(fout);
readln(fin,n);
readln(fin,pob.x,pob.y);
for i:=1 to n do
with poly[i] do readln(fin,x,y);
for i:=2 to n do
with seg[i] do
begin
p1:=poly[i-1];
p2:=poly[i];
end;
with seg[1] do
begin
p1:=poly[n];
p2:=poly[1];
end;
valid:=true;
for i:=1 to n do
if online(poly[(i mod n)+1],seg[i]) and (distance(poly[(i mod n)+1],poly[((i-2+n) mod n)+1])<length(seg[i])+length(seg[(i mod n)+1])) then
begin
valid:=false;
break;
end;
if valid then
for i:=1 to n do
if valid then
for j:=1 to n do
if i<>j then
if ((j<>(i mod n)+1) and (j<>((i-2+n) mod n)+1) and intersect(seg[i],seg[j])) or ((j<>(i mod n)+1) and onsegment(poly[i],seg[j])) then
begin
valid:=false;
break;
end;
if not valid then writeln(fout,'NOFENCE')
else
begin
fillchar(seen,sizeof(seen),true);
count:=n;
for i:=1 to n do
begin
t1:=poly[((i-2+n) mod n)+1];
t2:=poly[i];
with leg1 do
begin
p1:=pob;
p2:=t1;
end;
with leg2 do
begin
p1:=pob;
p2:=t2;
end;
for j:=1 to n do
if seen[i] then
if i<>j then
begin
in1:=intersect(seg[j],leg1);
in2:=intersect(seg[j],leg2);
if in1 then
begin
if intriangle(seg[j].p1,pob,t1,t2) then
begin
leg1.p2:=seg[j].p1;
t1:=intersectpoint(leg1,seg[i]);
leg1.p2:=t1;
end;
if intriangle(seg[j].p2,pob,t1,t2) then
begin
leg1.p2:=seg[j].p2;
t1:=intersectpoint(leg1,seg[i]);
leg1.p2:=t1;
end;
end;
if in2 then
begin
if intriangle(seg[j].p1,pob,t1,t2) then
begin
leg2.p2:=seg[j].p1;
t2:=intersectpoint(leg2,seg[i]);
leg2.p2:=t2;
end;
if intriangle(seg[j].p2,pob,t1,t2) then
begin
leg2.p2:=seg[j].p2;
t2:=intersectpoint(leg2,seg[i]);
leg2.p2:=t2;
end;
end;
if (in1 and in2) or ((abs(t1.x-t2.x)<ep) and (abs(t1.y-t2.y)<ep)) then
begin
seen[i]:=false;
dec(count);
break;
end;
end;
end;
writeln(fout,count);
for i:=2 to n-1 do
if seen[i] then writeln(fout,seg[i].p1.x:0:0,' ',seg[i].p1.y:0:0,' ',seg[i].p2.x:0:0,' ',seg[i].p2.y:0:0);
if seen[1] then writeln(fout,seg[1].p2.x:0:0,' ',seg[1].p2.y:0:0,' ',seg[1].p1.x:0:0,' ',seg[1].p1.y:0:0);
if seen[n] then writeln(fout,seg[n].p1.x:0:0,' ',seg[n].p1.y:0:0,' ',seg[n].p2.x:0:0,' ',seg[n].p2.y:0:0);
end;
close(fin);
close(fout);
end.
|
unit acProgressBar;
{$I sDefs.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, sCommonData, sConst, ExtCtrls;
type
{$IFNDEF D2009}
TProgressBarStyle = (pbstNormal, pbstMarquee);
{$ENDIF}
TsProgressBar = class(TProgressBar)
{$IFNDEF NOTFORHELP}
private
FOldCount : integer;
Timer : TTimer;
FCommonData: TsCommonData;
FProgressSkin: TsSkinSection;
FMarqPos : integer;
FMarqSize : integer;
FMarqStep : integer;
FOrient : integer;
{$IFNDEF D2009}
FSavedPosition: Integer;
FStyle: TProgressBarStyle;
FMarqueeInterval: Integer;
{$ENDIF}
procedure PrepareCache;
function ProgressRect : TRect;
function ItemSize : TSize;
function ClRect : TRect;
procedure SetProgressSkin(const Value: TsSkinSection);
{$IFNDEF D2009}
procedure SetStyle(const Value: TProgressBarStyle);
procedure SetMarqueeInterval(const Value: Integer);
{$ENDIF}
procedure TimerAction(Sender : TObject);
public
procedure Paint(DC : hdc);
constructor Create(AOwner: TComponent); override;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
destructor Destroy; override;
procedure AfterConstruction; override;
procedure Loaded; override;
procedure WndProc (var Message: TMessage); override;
published
{$ENDIF}
property ProgressSkin : TsSkinSection read FProgressSkin write SetProgressSkin;
property SkinData : TsCommonData read FCommonData write FCommonData;
{$IFNDEF D2009}
property Style: TProgressBarStyle read FStyle write SetStyle default pbstNormal;
property MarqueeInterval: Integer read FMarqueeInterval write SetMarqueeInterval default 10;
{$ENDIF}
end;
implementation
uses sMessages, sVclUtils, sGraphUtils, acntUtils, sAlphaGraph, sSkinProps, CommCtrl{$IFDEF DELPHI7UP}, Themes{$ENDIF};
const
iNdent = 2;
{ TsProgressBar }
procedure TsProgressBar.AfterConstruction;
begin
inherited;
FCommonData.Loaded;
end;
function TsProgressBar.ClRect: TRect;
begin
Result := Rect(0, 0, Width, Height);
InflateRect(Result, -1, -1);
end;
constructor TsProgressBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMarqSize := 40;
FMarqStep := 8;//6;
FOldCount := -1;
{$IFNDEF D2009}
FMarqueeInterval := 10;
FStyle := pbstNormal;
{$ENDIF}
FCommonData := TsCommonData.Create(Self, False);
FCommonData.COC := COC_TsGauge;
ControlStyle := ControlStyle + [csOpaque];
Timer := TTimer.Create(Self);
Timer.Enabled := False;
Timer.Interval := 30;
Timer.OnTimer := TimerAction;
FOrient := 1;
end;
destructor TsProgressBar.Destroy;
begin
FreeAndNil(FCommonData);
FreeAndNil(Timer);
inherited Destroy;
end;
function TsProgressBar.ItemSize: TSize;
const
prop = 0.66;
begin
if Style = pbstMarquee then begin
if Orientation = pbVertical then begin
Result.cx := WidthOf(clRect) - BorderWidth * 2;
Result.cy := 9;
end
else begin
Result.cy := HeightOf(clRect) - BorderWidth * 2;
Result.cx := 9;
end;
end
else begin
if Orientation = pbVertical then begin
Result.cx := WidthOf(clRect) - BorderWidth * 2;
if Smooth then Result.cy := ProgressRect.Bottom else Result.cy := Round(Result.cx * prop) - Indent;
end
else begin
Result.cy := HeightOf(clRect) - BorderWidth * 2;
if Smooth then Result.cx := ProgressRect.Right else Result.cx := Round(Result.cy * prop) - Indent;
end;
end
end;
procedure TsProgressBar.Loaded;
begin
inherited;
FCommonData.Loaded;
if not (csDesigning in ComponentState) and (Style = pbstMarquee) and not Timer.Enabled then Timer.Enabled := True;
end;
procedure TsProgressBar.Paint;
var
NewDC, SavedDC : hdc;
begin
if (Width < 1) or (Height < 1) then Exit;
if DC = 0 then NewDC := GetWindowDC(Handle) else NewDC := DC;
SavedDC := SaveDC(NewDC);
try
FCommonData.Updating := FCommonData.Updating;
if not FCommonData.Updating then begin
FCommonData.BGChanged := FCommonData.BGChanged or FCommonData.HalfVisible or GetBoolMsg(Parent, AC_GETHALFVISIBLE);
FCommonData.HalfVisible := not RectInRect(Parent.ClientRect, BoundsRect);
if FCommonData.BGChanged then PrepareCache;
if FCommonData.FCacheBmp <> nil then begin
UpdateCorners(FCommonData, 0);
CopyWinControlCache(Self, FCommonData, Rect(0, 0, 0, 0), Rect(0, 0, Width, Height), NewDC, True);
sVCLUtils.PaintControls(NewDC, Self, True, Point(0, 0));
end;
end;
finally
RestoreDC(NewDC, SavedDC);
if DC = 0 then ReleaseDC(Handle, NewDC);
end;
end;
procedure TsProgressBar.PrepareCache;
var
si, i, d, c, value, w, h : integer;
s : string;
ci : TCacheInfo;
Bmp : TBitmap;
prRect : TRect;
iSize : TSize;
begin
if (Style <> pbstMarquee) and not Smooth then begin
if (FCommonData.FCacheBmp <> nil) and (FCommonData.FCacheBmp.Width = Width) and (FCommonData.FCacheBmp.Height = Height) then begin
iSize := ItemSize;
if Orientation = pbHorizontal then begin
w := WidthOf(clRect) - iNdent;
c := w div (iSize.cx + iNdent);
end
else begin
h := HeightOf(clRect) - iNdent;
c := h div (iSize.cy + iNdent);
end;
if (c > 1) and (Max <> 0) and (Position <> 0) then value := Round(c / (Max - Min) * (Position - Min)) else value := 0;
if (value = FOldCount) and ((Position - Min) <> Max) then Exit else FOldCount := value;
end;
end;
InitCacheBmp(FCommonData);
PaintItem(FCommonData, GetParentCache(FCommonData), True, 0, Rect(0, 0, width, Height), Point(Left, Top), FCommonData.FCacheBMP, False);
if Max <= Min then Exit;
if (ProgressSkin <> '') then s := ProgressSkin else begin
if Orientation = pbVertical then s := s_ProgressV else s := s_ProgressH;
end;
si := FCommonData.SkinManager.GetSkinIndex(s);
ci := MakeCacheInfo(FCommonData.FCacheBmp);
prRect := ProgressRect;
if (prRect.Right <= prRect.Left) or (prRect.Bottom <= prRect.Top) then Exit;
iSize := ItemSize;
if (iSize.cx < 2) or (iSize.cy < 2) then Exit;
Bmp := CreateBmp32(iSize.cx, iSize.cy);
if Style = pbstMarquee then begin
d := 1;
if Orientation = pbHorizontal then for i := 0 to 4 do begin
c := prRect.Left + i * (iSize.cx + d);
if c > Width then c := c - Width;
PaintItem(si, s, ci, True, 0, Rect(0, 0, Bmp.Width, Bmp.Height), Point(c, prRect.Top), BMP, FCommonData.SkinManager);
BitBlt(FCommonData.FCacheBmp.Canvas.Handle, c, prRect.Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end
else for i := 0 to 4 do begin
c := prRect.Bottom - i * (iSize.cy + d) - iSize.cy;
if c < 0 then c := Height + c;
PaintItem(si, s, ci, True, 0, Rect(0, 0, Bmp.Width, Bmp.Height), Point(prRect.Left, c), BMP, FCommonData.SkinManager);
BitBlt(FCommonData.FCacheBmp.Canvas.Handle, prRect.Left, c, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
end
else begin
if Orientation = pbHorizontal then begin
if Smooth then begin
Bmp.Width := WidthOf(prRect);
PaintItem(si, s, ci, True, 0, Rect(0, 0, Bmp.Width, Bmp.Height), Point(prRect.Left, prRect.Top), BMP, FCommonData.SkinManager);
BitBlt(FCommonData.FCacheBmp.Canvas.Handle, prRect.Left, prRect.Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end
else if (Max <> 0) and (Position <> 0) then begin
w := WidthOf(clRect) - iNdent;
c := w div (iSize.cx + iNdent);
if c > 1 then begin
d := (w - c * iSize.cx) div (c - 1);
value := Round(c / (Max - Min) * (Position - Min));
for i := 0 to value - 1 do begin
PaintItem(si, s, ci, True, 0, Rect(0, 0, Bmp.Width, Bmp.Height), Point(prRect.Left + i * (iSize.cx + d), prRect.Top), BMP, FCommonData.SkinManager);
BitBlt(FCommonData.FCacheBmp.Canvas.Handle, prRect.Left + i * (iSize.cx + d), prRect.Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
if (Value > 0) and (Position = Max) and (w - (Value - 1) * (iSize.cx + d) - iSize.cx > 3) then begin
Bmp.Width := w - (Value - 1) * (iSize.cx + d) - iSize.cx;
PaintItem(si, s, ci, True, 0, Rect(0, 0, Bmp.Width, Bmp.Height), Point(prRect.Left + Value * (iSize.cx + d), prRect.Top), BMP, FCommonData.SkinManager);
BitBlt(FCommonData.FCacheBmp.Canvas.Handle, prRect.Left + (Value * (iSize.cx + d)), prRect.Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
end;
end;
end
else begin
if Smooth then begin
Bmp.Height := HeightOf(prRect);
PaintItem(si, s, ci, True, 0, Rect(0, 0, Bmp.Width, Bmp.Height), Point(prRect.Left, prRect.Top), BMP, FCommonData.SkinManager);
BitBlt(FCommonData.FCacheBmp.Canvas.Handle, prRect.Left, prRect.Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end
else if (Max <> 0) and (Position <> 0) then begin
h := HeightOf(clRect) - iNdent;
c := h div (iSize.cy + iNdent);
if c > 1 then begin
d := (h - c * iSize.cy) div (c - 1);
value := Round(c / (Max - Min) * (Position - Min));
for i := 0 to value - 1 do begin
PaintItem(si, s, ci, True, 0, Rect(0, 0, Bmp.Width, Bmp.Height), Point(prRect.Left, prRect.Bottom - i * (iSize.cy + d) - iSize.cy), BMP, FCommonData.SkinManager);
BitBlt(FCommonData.FCacheBmp.Canvas.Handle, prRect.Left, prRect.Bottom - i * (iSize.cy + d) - iSize.cy, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
if (Value > 0) and (Position = Max) and (h - (Value - 1) * (iSize.cy + d) - iSize.cy > 3) then begin
Bmp.Height := HeightOf(clRect) - Value * (iSize.cy + d);
PaintItem(si, s, ci, True, 0, Rect(0, 0, Bmp.Width, Bmp.Height), Point(prRect.Left, prRect.Top), BMP, FCommonData.SkinManager);
BitBlt(FCommonData.FCacheBmp.Canvas.Handle, prRect.Left, prRect.Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
end;
end;
end;
end;
FreeAndNil(Bmp);
end;
function TsProgressBar.ProgressRect: TRect;
begin
Result := clRect;
InflateRect(Result, -BorderWidth, -BorderWidth);
if Style = pbstMarquee then begin
if Orientation = pbVertical then begin
Result.Bottom := Height - FMarqPos;
Result.Top := Result.Bottom - FMarqSize;
end
else begin
Result.Left := Result.Left + FMarqPos;
Result.Right := Result.Left + FMarqSize;
end;
end
else if Max <> Min then begin
if Orientation = pbVertical then begin
Result.Top := Result.Bottom - Round(((Height - 2 * Result.Left) / (Max - Min)) * (Position - Min));
if Position = Max
then Result.Top := Result.Left
else Result.Top := Result.Bottom - Round(((Height - 2 * Result.Left) / (Max - Min)) * (Position - Min));
end
else begin
if Position = Max
then Result.Right := Width - Result.Left
else Result.Right := Round(((Width - 2 * Result.Left) / (Max - Min)) * (Position - Min));
end;
end;
end;
procedure TsProgressBar.SetProgressSkin(const Value: TsSkinSection);
begin
if FProgressSkin <> Value then begin
FProgressSkin := Value;
FCommonData.Invalidate;
end;
end;
{$IFNDEF D2009}
procedure TsProgressBar.SetMarqueeInterval(const Value: Integer);
{$IFDEF DELPHI7UP}
var
MarqueeEnabled: Boolean;
{$ENDIF}
begin
FMarqueeInterval := Value;
{$IFNDEF D2009}
{$IFDEF DELPHI7UP}
if (FStyle = pbstMarquee) and ThemeServices.ThemesEnabled and CheckWin32Version(5, 1) and HandleAllocated then begin
MarqueeEnabled := FStyle = pbstMarquee;
SendMessage(Handle, WM_USER + 10{PBM_SETMARQUEE}, WPARAM(MarqueeEnabled), LPARAM(FMarqueeInterval));
if Timer <> nil then Timer.Interval := FMarqueeInterval;
end;
{$ENDIF}
{$ENDIF}
end;
procedure TsProgressBar.SetStyle(const Value: TProgressBarStyle);
{$IFDEF DELPHI7UP}
var
MarqueeEnabled: Boolean;
{$ENDIF}
begin
if FStyle <> Value then begin
FStyle := Value;
if FStyle = pbstMarquee then begin
FSavedPosition := Position;
DoubleBuffered := False;
end;
Timer.Enabled := SkinData.Skinned and (FStyle = pbstMarquee);
{$IFDEF DELPHI7UP}
if ThemeServices.ThemesEnabled and CheckWin32Version(5, 1) and HandleAllocated then begin
MarqueeEnabled := FStyle = pbstMarquee;
SendMessage(Handle, WM_USER + 10{PBM_SETMARQUEE}, WPARAM(THandle(MarqueeEnabled)), LPARAM(FMarqueeInterval));
end;
{$ENDIF}
RecreateWnd;
if FStyle = pbstNormal then Position := FSavedPosition;
end;
end;
{$ENDIF}
procedure TsProgressBar.WndProc(var Message: TMessage);
var
PS : TPaintStruct;
begin
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_CTRLHANDLED : begin Message.Result := 1; Exit end; // AlphaSkins supported
AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end;
AC_REMOVESKIN : if LongWord(Message.LParam) = LongWord(SkinData.SkinManager) then begin
if Style = pbstMarquee then Timer.Enabled := False;
CommonWndProc(Message, FCommonData);
RedrawWindow(Handle, nil, 0, RDW_ERASE or RDW_INVALIDATE or RDW_FRAME or RDW_UPDATENOW);
Exit
end;
AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
Repaint;
FOldCount := -1;
Exit
end;
AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
if not (csDesigning in ComponentState) and (Style = pbstMarquee) then Timer.Enabled := True;
FOldCount := -1;
exit
end;
AC_ENDPARENTUPDATE : if FCommonData.Updating then begin
FCommonData.Updating := False;
Repaint; Exit
end;
AC_GETBG : begin
PacBGInfo(Message.LParam)^.Offset := Point(0, 0);
PacBGInfo(Message.LParam).Bmp := FCommonData.FCacheBmp;
PacBGInfo(Message.LParam)^.BgType := btCache;
Exit;
end;
end;
if Assigned(FCommonData) and ControlIsReady(Self) and FCommonData.Skinned then begin
case Message.Msg of
PBM_SETPOS : begin
if Style = pbstMarquee then Perform(WM_SETREDRAW, 0, 0);
inherited;
if Style = pbstMarquee then Perform(WM_SETREDRAW, 1, 0);
Exit
end;
WM_PRINT : begin
SkinData.Updating := False;
Paint(TWMPaint(Message).DC);
Exit;
end;
WM_PAINT : begin
BeginPaint(Handle, PS);
Paint(TWMPaint(Message).DC);
EndPaint(Handle, PS);
Message.Result := 0;
Exit;
end;
WM_SIZE, WM_MOVE, WM_WINDOWPOSCHANGED : FOldCount := -1;
WM_NCPAINT : begin
Message.Result := 0;
Exit;
end;
WM_ERASEBKGND : begin
Message.Result := 1;
Exit;
end;
end;
CommonWndProc(Message, FCommonData);
end;
inherited;
end;
procedure TsProgressBar.CreateParams(var Params: TCreateParams);
begin
inherited;
{$IFNDEF D2009}
{$IFDEF DELPHI7UP}
if (FStyle = pbstMarquee) and ThemeServices.ThemesEnabled and CheckWin32Version(5, 1)
then Params.Style := Params.Style or 8{PBS_MARQUEE};
{$ENDIF}
{$ENDIF}
end;
procedure TsProgressBar.CreateWnd;
begin
inherited;
{$IFDEF DELPHI7UP}
{$IFNDEF D2009}
if ThemeServices.ThemesEnabled and CheckWin32Version(5, 1) and HandleAllocated then begin
SendMessage(Handle, WM_USER + 10{PBM_SETMARQUEE}, WPARAM(THandle(FStyle = pbstMarquee)), LPARAM(FMarqueeInterval));
if Timer <> nil then Timer.Interval := FMarqueeInterval;
end;
{$ENDIF}
{$ENDIF}
end;
procedure TsProgressBar.TimerAction(Sender: TObject);
var
DC : hdc;
begin
if SkinData.Skinned then begin
if Visible then begin
PrepareCache;
DC := GetWindowDC(Handle);
BitBlt(DC, 0, 0, Width, Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY);
ReleaseDC(Handle, DC);
inc(FMarqPos, FOrient * FMarqStep);
{$IFDEF D2009}
if State = pbsError then begin
if (FMarqPos >= Width - FMarqSize - BorderWidth - FMarqStep) or (FMarqPos <= BorderWidth) then FOrient := -1 * FOrient;
end
else
{$ENDIF}
if (FMarqPos >= Width - FMarqStep) then FMarqPos := 0;
end;
end
else Timer.Enabled := False;
end;
end.
|
//------------------------------------------------------------------------------
//
// Voxelizer
// Copyright (C) 2021 by Jim Valavanis
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
// DESCRIPTION:
// Export model to voxelbuffer
//
//------------------------------------------------------------------------------
// Site : https://sourceforge.net/projects/voxelizer/
//------------------------------------------------------------------------------
unit vxl_voxelexport;
interface
uses
Windows,
Classes,
SysUtils,
Graphics,
vxl_voxels,
models,
vxl_voxelizer;
procedure DT_CreateVoxelFromModel(const t: model_t; const vox: voxelbuffer_p;
const voxsize: integer; const modeltex: TBitmap);
implementation
uses
vxl_defs;
procedure DT_CreateVoxelFacesFromModel(const mVertCount, mFaceCount: integer;
const mVert: array of fvec5_t; const mFace: array of ivec3_t;
const scale: single; const vox: voxelbuffer_p;
const voxsize: integer; const tex: TBitmap; const opaque: boolean);
var
tri: meshtriangle_t;
i: integer;
ofs: integer;
procedure _make_vertex(const r, g: integer);
begin
tri[g].x := mVert[r].x * scale + ofs;
tri[g].y := voxsize - 1.0 - mVert[r].y * scale;
tri[g].z := voxsize - 1.0 - mVert[r].z * scale - ofs;
tri[g].u := mVert[r].u;
tri[g].v := mVert[r].v;
end;
begin
ofs := voxsize div 2;
for i := 0 to mFaceCount - 1 do
begin
_make_vertex(mFace[i].x, 0);
_make_vertex(mFace[i].y, 1);
_make_vertex(mFace[i].z, 2);
DT_VoxelizeTri(@tri, tex, vox, voxsize, opaque);
end;
end;
procedure DT_CreateVoxelFromModel(const t: model_t; const vox: voxelbuffer_p;
const voxsize: integer; const modeltex: TBitmap);
var
xmin, xmax, ymin, ymax, zmin, zmax: single;
i: integer;
scale: single;
begin
if t.mVertCount = 0 then
Exit;
xmin := t.mVert[0].x;
xmax := t.mVert[0].x;
ymin := t.mVert[0].y;
ymax := t.mVert[0].y;
zmin := t.mVert[0].z;
zmax := t.mVert[0].z;
for i := 1 to t.mVertCount - 1 do
begin
if xmin > t.mVert[i].x then
xmin := t.mVert[i].x
else if xmax < t.mVert[i].x then
xmax := t.mVert[i].x;
if ymin > t.mVert[i].y then
ymin := t.mVert[i].y
else if ymax < t.mVert[i].y then
ymax := t.mVert[i].y;
if zmin > t.mVert[i].z then
zmin := t.mVert[i].z
else if zmax < t.mVert[i].z then
zmax := t.mVert[i].z;
end;
ZeroMemory(vox, SizeOf(voxelbuffer_t));
scale := abs(xmin);
if abs(xmax) > scale then
scale := abs(xmax);
if abs(ymin) > scale then
scale := abs(ymin);
if abs(ymax) > scale then
scale := abs(ymax);
if abs(zmin) > scale then
scale := abs(zmin);
if abs(zmax) > scale then
scale := abs(zmax);
scale := 2 * scale;
scale := 2 * t.maxcoord;
{ scale := xmax - xmin;
if ymax - ymin > scale then
scale := ymax - ymin;
if zmax - zmin > scale then
scale := zmax - zmin;}
scale := (voxsize - 1) / scale;
DT_CreateVoxelFacesFromModel(t.mVertCount, t.mFaceCount, t.mVert, t.mFace,
scale, vox, voxsize, modeltex, true);
end;
end.
|
unit Services.SmartPoint;
// DICA:
// https://www.youtube.com/watch?v=H2iDz8q-E6o
interface
type
TSmartPointer<T : class, constructor> = record
strict private
FClasse : T;
FFreeTheClasse : IInterface;
function GetClasse : T;
public
class operator Implicit(smart : TSmartPointer<T>) : T;
class operator Implicit(Value : T) : TSmartPointer<T>;
constructor Create(Value : T);
property Classe : T read GetClasse;
end;
TFreeTheClasse = class(TInterfacedObject)
private
FObjectToFree : TObject;
public
constructor Create(anObjectToFree : TObject);
destructor Destroy; override;
end;
implementation
{ TSmartPointer<T> }
constructor TSmartPointer<T>.Create(Value: T);
begin
FClasse := Value;
FFreeTheClasse := TFreeTheClasse.Create(FClasse);
end;
function TSmartPointer<T>.GetClasse: T;
begin
if not Assigned(FFreeTheClasse) then
Self := TSmartPointer<T>.Create(T.Create);
Result := FClasse;
end;
class operator TSmartPointer<T>.Implicit(Value: T): TSmartPointer<T>;
begin
Result := TSmartPointer<T>.Create(Value);
end;
class operator TSmartPointer<T>.Implicit(smart: TSmartPointer<T>): T;
begin
Result := smart.Classe;
end;
{ TFreeTheClasse }
constructor TFreeTheClasse.Create(anObjectToFree: TObject);
begin
FObjectToFree := anObjectToFree;
end;
destructor TFreeTheClasse.Destroy;
begin
FObjectToFree.DisposeOf;
inherited;
end;
end.
|
//
// Name: ThreadedActivityLog.pas
// Desc: This component will write to the activity log using the threaded query componenet
// Set the login params property and then set active to connect to the SQL log. To send
// a log message set the trans and desciption properties and then call send.
//
// Author: David Verespey
//
// Revision History:
//
// 06/25/97 Start Program
//
//
unit ThreadedActivityLog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ThreadedBDEQuery,
seqnum, DB, DBTables,ThreadedQueryDef;
type
TErrorProc = procedure (Sender : TObject; ErrorMsg : string) of object;
TThreadedActivityLog = class(TComponent)
private
{ Private declarations }
fSendList: TStringList; //list of current messages to send
fQuery:TThreadedBDEQuery;
fAppName: string;
fIPAddress: string;
fSequence: string;
fSequenceNumber: TSequenceNumber;
fVIN: string;
fTrans: string;
fDescription: string;
fAlias: string;
//fTable: string;
fParams: TStringList;
fSendError:boolean;
fActive:boolean;
protected
{ Protected declarations }
FError: TErrorProc; // when an error occurs in the thread.
FOnComplete: TNotifyEvent;
// property get and set
function GetActive: boolean;
procedure SetActive(Active: boolean);
function GetAppName: string;
procedure SetAppName(AppName: string);
function GetSequence: string;
procedure SetSequence( Sequence: string );
function GetVIN: string;
procedure SetVIN(VIN: string);
function GetTrans: string;
procedure SetTrans(Trans: string);
function GetDescription: string;
procedure SetDescription(Description: string);
function GetAlias: string;
procedure SetAlias(alias: string);
function GetLoginParams: TStringList;
procedure SetLoginParams(params: TstringList);
procedure SetOnComplete(Value: TNotifyEvent);
function GetSendCount: integer;
// notify events
procedure SetError(value : TErrorProc);
// handle callbacks from threaded query
procedure QueryComplete(Sender: TObject; Dataset: TDataSet);
procedure QueryError(Sender: TObject; ErrorMsg: string);
procedure AfterRun(Sender:TObject; Query:TQuery);
// internal
procedure SendError (msg : string);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Send;
published
property Active: boolean
read GetActive
write SetActive;
property AppName: string
read GetAppName
write SetAppName;
property IPAddress: string
read fIPAddress
write fIPAddress;
property Sequence: string
read GetSequence
write SetSequence;
property VIN: string
read GetVIN
write SetVIN;
property TransCode: string
read GetTrans
Write SetTrans;
property Description: string
read GetDescription
write Setdescription;
property AliasName: string
read GetAlias
write SetAlias;
property LoginParams : TStringList
read GetLoginParams
write SetLoginParams;
property OnError : TErrorProc
read FError
write SetError;
property OnComplete: TNotifyEvent
read fOnComplete
write SetOnComplete;
property SendCount : integer
read GetSendCount;
end;
implementation
constructor TThreadedActivityLog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fParams:=TStringList.Create;
fSendList:=TStringList.Create;
fSequenceNumber:=TSequenceNumber.Create(self);
fSendError:=False;
end;
destructor TThreadedActivityLog.Destroy;
begin
fParams.Free;
fSendList.Free;
fsequenceNumber.Free;
inherited destroy;
end;
procedure TThreadedActivityLog.Send;
const
sqlCommand = 'Insert into dbo.Act_Log ' +
'(App_From,IP_Address,Trans,DT_Sender,VIN,Description,Sequence_Number) ' +
'VALUES ( ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', ''%s'', %s)';
var
ssQuery : string;
ssDesc : string;
begin
// format the message
try
repeat
if length(fDescription)>100 then
begin
ssDesc:=copy(fDescription,1,100);
fdescription:=copy(fDescription,101,length(fDescription)-100);
end
else
begin
ssDesc:=fDescription;
fDescription:='';
end;
ssQuery := format (sqlCommand,[fAppName, fIPAddress,
fTrans, formatdatetime('yyyymmddhhmmss00',now),fVIN,ssDesc,fsequence]);
if assigned(fQuery) and (fSendList.Count = 0) and (not fSendError) and (fActive) then
begin
fQuery.SQL.Clear;
fQuery.SQL.Add (ssQuery);
fQuery.Exec;
end
else
fSendList.Add(ssQuery);
until Length(fDescription) >= 0;
except
on e:exception do
begin
SendError('Act Send:: '+e.message);
end;
end;
end;
procedure TThreadedActivityLog.AfterRun(Sender:TObject; Query:TQuery);
var
I:integer;
begin
try
// reset timer if there are any other messages in out cue then send next
// and start timer again. If not then leave it off.
fSendError:=False;
if (fSendList.Count > 0) and (not fSendError) and (fActive) then
begin
fQuery.SQL.Clear;
if fSendList.Count > 1 then
begin
for i:=0 to fSendList.Count-1 do
begin
fQuery.SQL.Add(fSendList[0]);
fSendList.Delete(0);
end;
end
else
begin
fQuery.SQL.Add(fSendList[0]);
fSendList.Delete(0);
end;
fQuery.Exec;
end;
// complete event
if (Assigned (fOnComplete)) then
fOnComplete(self);
except
on e:exception do
begin
SendError('Act Comp:: '+e.message);
end;
end;
end;
procedure TThreadedActivityLog.QueryComplete(Sender: TObject; Dataset: TDataSet);
begin
{try
// reset timer if there are any other messages in out cue then send next
// and start timer again. If not then leave it off.
fSendError:=False;
fQuery.SQL.Clear;
if (fSendList.Count > 0) and (not fSendError) and (fActive) then
begin
fQuery.SQL.Add(fSendList[0]);
fSendList.Delete(0);
fQuery.Exec;
end;
// complete event
if (Assigned (fOnComplete)) then
fOnComplete(self);
except
on e:exception do
begin
SendError('Act Comp:: '+e.message);
end;
end;}
end;
procedure TThreadedActivityLog.QueryError(Sender: TObject; ErrorMsg: string);
begin
fSendError:=True;
SendError(ErrorMsg);
end;
function TThreadedActivityLog.GetSendCount: integer;
begin
result:=fSendlist.Count;
end;
function TThreadedActivityLog.GetActive: boolean;
begin
result:=fActive;
end;
procedure TThreadedActivityLog.SetActive(Active: boolean);
begin
fActive:=Active;
if not Active then
begin
if assigned(fQuery) then
begin
while (fSendList.Count > 0) or (fQuery.IsRunning) do
begin
Application.ProcessMessages;
sleep(0);
end;
fQuery.Free;
fSendError:=False;
end;
end
else
begin
fQuery:=TThreadedBDEQuery.Create(self);
//Set login and other info
fQuery.KeepConnection:=false;
fQuery.qryCommand:=qryExec;
fQuery.RunMode:=runOneShot;
fQuery.DriverName:='';
fQuery.AliasName:=fAlias;
fQuery.LoginParams.Assign(fParams);
//point to the callbacks
fQuery.OnComplete:=QueryComplete;
fQuery.OnError:=QueryError;
fQuery.OnAfterRun:=AfterRun;
if fSendList.Count > 0 then
begin
fQuery.SQL.Add(fSendList[0]);
fSendList.Delete(0);
fQuery.Exec;
end;
end;
end;
function TThreadedActivityLog.GetAppName: string;
begin
result:=fAppName;
end;
procedure TThreadedActivityLog.SetAppName(AppName: string);
begin
fAppName:=AppName;
end;
function TThreadedActivityLog.GetSequence: string;
begin
result:=fSequence;
end;
procedure TThreadedActivityLog.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;
function TThreadedActivityLog.GetVIN: string;
begin
result:=fVIN;
end;
procedure TThreadedActivityLog.SetVIN(VIN: string);
begin
fVIN:=VIN;
end;
function TThreadedActivityLog.GetTrans: string;
begin
result:=fTrans;
end;
procedure TThreadedActivityLog.SetTrans(Trans: string);
begin
fTrans:=Trans;
end;
function TThreadedActivityLog.GetDescription: string;
begin
result:=fdescription;
end;
procedure TThreadedActivityLog.SetDescription(Description: string);
begin
if length(description) < 100 then
fDescription:=description
else
begin
fDescription:=copy(description,1,100);
end;
end;
function TThreadedActivityLog.GetAlias: string;
begin
result:=fAlias;
end;
procedure TThreadedActivityLog.SetAlias(alias: string);
begin
fAlias:=alias;
end;
function TThreadedActivityLog.GetLoginParams: TStringList;
begin
result:=fParams;
end;
procedure TThreadedActivityLog.SetLoginParams(params: TstringList);
begin
fParams.Assign (params);
end;
procedure TThreadedActivityLog.SetError(value : TErrorProc );
begin
FError:= value;
end;
procedure TThreadedActivityLog.SendError (msg : string);
begin
if (Assigned (FError)) then
FError (self, msg);
end;
procedure TThreadedActivityLog.SetOnComplete(Value: TNotifyEvent);
begin
FOnComplete := Value;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ScktComp;
type
TForm1 = class(TForm)
ServerSocket1: TServerSocket;
LabeledEdit1: TLabeledEdit;
CheckBox1: TCheckBox;
ListBox1: TListBox;
procedure CheckBox1Click(Sender: TObject);
procedure ServerSocket1ClientConnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1ClientDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
private
procedure AddItem(s: string);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.AddItem(s: string);
begin
ListBox1.Items.Add(s);
ListBox1.ItemIndex := ListBox1.Items.Count-1;
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
if CheckBox1.Checked = false then
begin
ServerSocket1.Close;
AddItem('szerver leállítva');
Abort;
end;
try
ServerSocket1.Port := StrToInt(LabeledEdit1.Text);
except
on e:exception do
begin
Application.MessageBox('Hiba: számot adj meg portnak!','',mb_ok);
Abort;
end;
end;
ServerSocket1.Open;
AddItem('szerver elindítva: ' + ServerSocket1.Socket.LocalHost + ' (' + ServerSocket1.Socket.LocalAddress + ')');
end;
procedure TForm1.ServerSocket1ClientConnect(Sender: TObject; Socket: TCustomWinSocket);
begin
AddItem('kliens csatlakozott: ' + Socket.RemoteHost + ' (' + Socket.RemoteAddress + ')');
end;
procedure TForm1.ServerSocket1ClientDisconnect(Sender: TObject; Socket: TCustomWinSocket);
begin
AddItem('kliens lecsatlakozott: ' + Socket.RemoteHost + ' (' + Socket.RemoteAddress + ')');
end;
procedure TForm1.ServerSocket1ClientRead(Sender: TObject; Socket: TCustomWinSocket);
var msg: string;
i: integer;
begin
msg := Socket.ReceiveText;
for i := 0 to ServerSocket1.Socket.ActiveConnections-1 do
ServerSocket1.Socket.Connections[i].SendText(msg);
end;
end.
|
unit Json.Intercept.Data;
interface
uses
Dialogs,
Rest.Json,
System.Json,
REST.JsonReflect,
System.DateUtils,
system.SysUtils,
System.Rtti;
type
TFormatSettingsBR = class
public
class function fs:TFormatSettings;
end;
TSuppressZeroDateInterceptor = class(TJSONInterceptor)
public
function StringConverter(Data: TObject; Field: string): string; override;
procedure StringReverter(Data: TObject; Field: string; Arg: string); override;
end;
SuppressZeroAttribute = class(JsonReflectAttribute)
public
constructor Create;
end;
implementation
{ TSuppressZeroDateInterceptor }
function TSuppressZeroDateInterceptor.StringConverter(Data: TObject;
Field: string): string;
var
ctx: TRTTIContext;
date: TDateTime;
begin
showmessage('StringConverter');
date := ctx.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<TDateTime>;
if date = 0 then begin
result := EmptyStr;
end
else begin
//result := DateToISO8601(date, True);
result := DateTimeToStr(date,TFormatSettingsBR.fs);
end;
end;
procedure TSuppressZeroDateInterceptor.StringReverter(Data: TObject; Field, Arg: string);
var
ctx: TRTTIContext;
date: TDateTime;
begin
showmessage('StringReverter');
if Arg.IsEmpty then
date := 0
else
date := StrToDateTimeDef(Arg,0, TFormatSettingsBR.fs);
ctx.GetType(Data.ClassType).GetField(Field).SetValue(Data, date);
end;
{ SuppressZeroAttribute }
constructor SuppressZeroAttribute.Create;
begin
inherited Create(ctString, rtString, TSuppressZeroDateInterceptor);
end;
{ TFormatSettingsBR }
class function TFormatSettingsBR.fs: TFormatSettings;
begin
result := TFormatSettings.Create;
result.DateSeparator := '-';
result.ShortDateFormat := 'yyyy-MM-dd';
result.TimeSeparator := ':';
result.ShortTimeFormat := 'hh:mm';
result.LongTimeFormat := 'hh:mm:ss';
end;
end.
|
unit U_BaseControl;
interface
uses
System.Classes, FireDAC.Comp.Client, FireDAC.Dapt, FireDAC.Stan.Async,
System.SysUtils;
type
TBaseControl = class(TComponent)
private
{ private declarations }
FQuery: TFDQuery;
function GetQuery: TFDQuery;
protected
{ protected declarations }
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetLastID: Int64;
property Query: TFDQuery read GetQuery;
end;
implementation
{ TBaseControl }
uses U_Conexao;
constructor TBaseControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FQuery := TFDQuery.Create(Self);
FQuery.Connection := TConexao.GetInstance.Conexao;
end;
destructor TBaseControl.Destroy;
begin
FQuery.Free;
inherited;
end;
function TBaseControl.GetLastID: Int64;
begin
Result := Int64(TConexao.GetInstance.Conexao.GetLastAutoGenValue(''));
end;
function TBaseControl.GetQuery: TFDQuery;
begin
Result := FQuery;
end;
end.
|
{ NIM/NAMA : 16518305/QURRATA A'YUNI
TANGGAL : RABU, 24 APRIL 2019
DEKSRIPSI : Menginput tinggi dan mengolah inputannya}
Program tinggi;
{ KAMUS}
const
NMin = 1;
NMax = 100;
var
i, hitung, hitung150, hitung170 : integer; {indeks -_-}
T : array [NMin..NMax] of integer; {memori untuk input}
N : integer; {indeks efektif}
x, jumlah : integer; {nilai yang akan dibaca}
rata : real;
{ ALGORITMA }
function IsWithinRange (X, min, max : integer) : boolean;
{ Menghasilkan true jika min <= X <= max, menghasilkan false jika tidak }
begin
if (X>=min) and (X<=max) then
IsWithinRange := true
else
IsWithinRange := false
end;
begin
{mengisi array}
i := NMin;
read(x);
if (x<>-999) then
begin
while (x<>-999) and (i<=NMax) do
begin
T[i] := x;
i := i+1;
read(x);
end;
N := i-1;
{menghitung array yang valid}
hitung := 0;
jumlah := 0;
for i:=1 to N do
begin
if ((IsWithinRange (T[i],100,300)) = true) then
begin
hitung := hitung+1;
jumlah := jumlah+T[i];
end;
end;
{hitung <= 150}
hitung150 := 0;
for i:=1 to N do
begin
if ((IsWithinRange (T[i],100,150)) = true) then
begin
hitung150 := hitung150+1;
end;
end;
{hitung >= 170}
hitung170 := 0;
for i:=1 to N do
begin
if ((IsWithinRange (T[i],170,300)) = true) then
begin
hitung170 := hitung170+1;
end;
end;
{tampilan menu}
if (hitung=0) then
begin
writeln ('Data kosong');
end else
begin
writeln(hitung);
writeln(hitung150);
writeln(hitung170);
rata := jumlah/hitung; {rata-rata}
writeln(round(rata));
end
end else
begin
writeln ('Data kosong');
end
end.
|
unit ArrayVal;
////////////////////////////////////////////////////////////////////////////////
//
// Author: Jaap Baak
// https://github.com/transportmodelling/Utils
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
interface
////////////////////////////////////////////////////////////////////////////////
Uses
SysUtils;
Type
TArrayView<T> = record
// Record that provides access to the array values, but prevents the array from being changed.
private
FValues: TArray<T>;
Function GetValues(Index: Integer): T; inline;
public
Constructor Create(Values: TArray<T>);
Function Length: Integer; inline;
public
Property Values[Index: Integer]: T read GetValues; default;
end;
TArrayValues<T> = record
// Record that provides access to the array values, but prevents the array from being resized.
private
FValues: TArray<T>;
Function GetValues(Index: Integer): T; inline;
Procedure SetValues(Index: Integer; Value: T); inline;
public
Constructor Create(Values: TArray<T>);
Function Length: Integer; inline;
public
Property Values[Index: Integer]: T read GetValues write SetValues; default;
end;
TStringArrayView = TArrayView<String>;
TIntArrayView = TArrayView<Integer>;
TFloat64ArrayView = TArrayView<Float64>;
TFloat32ArrayView = TArrayView<Float32>;
TStringArrayValues = TArrayValues<String>;
TIntArrayValues = TArrayValues<Integer>;
TFloat64ArrayValues = TArrayValues<Float64>;
TFloat32ArrayValues = TArrayValues<Float32>;
////////////////////////////////////////////////////////////////////////////////
implementation
////////////////////////////////////////////////////////////////////////////////
Constructor TArrayView<T>.Create(Values: TArray<T>);
begin
FValues := Values;
end;
Function TArrayView<T>.GetValues(Index: Integer): T;
begin
Result := FValues[Index];
end;
Function TArrayView<T>.Length: Integer;
begin
Result := System.Length(FValues);
end;
////////////////////////////////////////////////////////////////////////////////
Constructor TArrayValues<T>.Create(Values: TArray<T>);
begin
FValues := Values;
end;
Function TArrayValues<T>.GetValues(Index: Integer): T;
begin
Result := FValues[Index];
end;
Procedure TArrayValues<T>.SetValues(Index: Integer; Value: T);
begin
FValues[Index] := Value;
end;
Function TArrayValues<T>.Length: Integer;
begin
Result := System.Length(FValues);
end;
end.
|
unit TextEditor.Caret;
interface
uses
System.Classes, System.Types, TextEditor.Caret.MultiEdit, TextEditor.Caret.NonBlinking, TextEditor.Caret.Offsets,
TextEditor.Caret.Styles, TextEditor.Types;
type
TTextEditorCaret = class(TPersistent)
strict private
FMultiEdit: TTextEditorCaretMultiEdit;
FNonBlinking: TTextEditorCaretNonBlinking;
FOffsets: TTextEditorCaretOffsets;
FOnChange: TNotifyEvent;
FOptions: TTextEditorCaretOptions;
FStyles: TTextEditorCaretStyles;
FVisible: Boolean;
procedure DoChange(const ASender: TObject);
procedure SetMultiEdit(const AValue: TTextEditorCaretMultiEdit);
procedure SetNonBlinking(const AValue: TTextEditorCaretNonBlinking);
procedure SetOffsets(const AValue: TTextEditorCaretOffsets);
procedure SetOnChange(const AValue: TNotifyEvent);
procedure SetOptions(const AValue: TTextEditorCaretOptions);
procedure SetStyles(const AValue: TTextEditorCaretStyles);
procedure SetVisible(const AValue: Boolean);
public
constructor Create;
destructor Destroy; override;
procedure Assign(ASource: TPersistent); override;
procedure SetOption(const AOption: TTextEditorCaretOption; const AEnabled: Boolean);
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
published
property MultiEdit: TTextEditorCaretMultiEdit read FMultiEdit write SetMultiEdit;
property NonBlinking: TTextEditorCaretNonBlinking read FNonBlinking write SetNonBlinking;
property Offsets: TTextEditorCaretOffsets read FOffsets write SetOffsets;
property Options: TTextEditorCaretOptions read FOptions write SetOptions;
property Styles: TTextEditorCaretStyles read FStyles write SetStyles;
property Visible: Boolean read FVisible write SetVisible default True;
end;
implementation
constructor TTextEditorCaret.Create;
begin
inherited;
FMultiEdit := TTextEditorCaretMultiEdit.Create;
FNonBlinking := TTextEditorCaretNonBlinking.Create;
FOffsets := TTextEditorCaretOffsets.Create;
FStyles := TTextEditorCaretStyles.Create;
FVisible := True;
end;
destructor TTextEditorCaret.Destroy;
begin
FMultiEdit.Free;
FNonBlinking.Free;
FOffsets.Free;
FStyles.Free;
inherited;
end;
procedure TTextEditorCaret.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorCaret) then
with ASource as TTextEditorCaret do
begin
Self.FStyles.Assign(FStyles);
Self.FMultiEdit.Assign(FMultiEdit);
Self.FNonBlinking.Assign(FNonBlinking);
Self.FOffsets.Assign(FOffsets);
Self.FOptions := FOptions;
Self.FVisible := FVisible;
Self.DoChange(Self);
end
else
inherited Assign(ASource);
end;
procedure TTextEditorCaret.SetOnChange(const AValue: TNotifyEvent);
begin
FOnChange := AValue;
FOffsets.OnChange := AValue;
FStyles.OnChange := AValue;
FMultiEdit.OnChange := AValue;
FNonBlinking.OnChange := AValue;
end;
procedure TTextEditorCaret.DoChange(const ASender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(ASender);
end;
procedure TTextEditorCaret.SetStyles(const AValue: TTextEditorCaretStyles);
begin
FStyles.Assign(AValue);
end;
procedure TTextEditorCaret.SetMultiEdit(const AValue: TTextEditorCaretMultiEdit);
begin
FMultiEdit.Assign(AValue);
end;
procedure TTextEditorCaret.SetNonBlinking(const AValue: TTextEditorCaretNonBlinking);
begin
FNonBlinking.Assign(AValue);
end;
procedure TTextEditorCaret.SetVisible(const AValue: Boolean);
begin
if FVisible <> AValue then
begin
FVisible := AValue;
DoChange(Self);
end;
end;
procedure TTextEditorCaret.SetOffsets(const AValue: TTextEditorCaretOffsets);
begin
FOffsets.Assign(AValue);
end;
procedure TTextEditorCaret.SetOption(const AOption: TTextEditorCaretOption; const AEnabled: Boolean);
begin
if AEnabled then
Include(FOptions, AOption)
else
Exclude(FOptions, AOption);
end;
procedure TTextEditorCaret.SetOptions(const AValue: TTextEditorCaretOptions);
begin
if FOptions <> AValue then
begin
FOptions := AValue;
DoChange(Self);
end;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Unit para armazenas as constantes do sistema
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (T2Ti.COM)
@version 2.0
******************************************************************************* }
unit Constantes;
interface
const
// Formatter
ftCnpj = '##.###.###/####-##;0;_';
ftCpf = '###.###.###-##;0;_';
ftCep = '##.###-####;0;_';
ftTelefone = '(##)####-####;0;_';
ftInteiroComSeparador = '###,###,###';
ftInteiroSemSeparador = '#########';
ftFloatComSeparador = '###,###,##0.00';
ftFloatSemSeparador = '0.00';
ftZerosAEsquerda = '000000';
ftZeroInvisivel = '#';
type
TConstantes = class
const
QUANTIDADE_POR_PAGINA = 50;
{$WRITEABLECONST ON}
DECIMAIS_QUANTIDADE: Integer = 2;
DECIMAIS_VALOR: Integer = 2;
{$WRITEABLECONST OFF}
TagBotao: array [Boolean] of Integer = (0, 1);
TagPopupMenu: array [Boolean] of Integer = (0, 1);
// Módulos
MODULO_SEGURANCA = 'Segurança';
MODULO_CADASTROS = 'Cadastros';
MODULO_GED = 'GED - Gestão Eletrônica de Documentos';
MODULO_VENDAS = 'Vendas';
MODULO_CONTRATOS = 'Gestão de Contratos';
MODULO_NFE = 'Nota Fiscal Eletrônica - NFe';
MODULO_ESTOQUE = 'Controle de Estoque';
MODULO_PATRIMONIO = 'Controle Patrimonial';
MODULO_FINANCEIRO = 'Controle Financeiro';
MODULO_CONTAS_PAGAR = 'Contas a Pagar';
MODULO_CONTAS_RECEBER = 'Contas a Receber';
MODULO_COMPRAS = 'Gestão de Compras';
MODULO_FLUXO_CAIXA = 'Fluxo de Caixa';
MODULO_ORCAMENTO = 'Controle de Orçamentos';
MODULO_PONTO_ELETRONICO = 'Ponto Eletrônico';
MODULO_FOLHA_PAGAMENTO = 'Folha de Pagamento';
MODULO_CONTABILIDADE = 'Contabilidade';
MODULO_CONCILIACAO_CONTABIL = 'Conciliação Contábil';
MODULO_ESCRITA_FISCAL = 'Escrita Fiscal';
MODULO_SPED = 'Sped Contábil e Fiscal';
MODULO_ADMINISTRATIVO = 'Administrativo';
MODULO_SUPORTE = 'Suporte';
MODULO_BALCAO = 'Balcão';
MODULO_PCP = 'PCP';
end;
implementation
end.
|
unit Work.Table.Storage.Kind;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections, Vcl.Grids,
TableDraw, SQLLang, SQLiteTable3, Work.DB;
type
TTableProductKind = class;
TItemProdKind = class
private
FModifed:Boolean;
FOwner:TTableProductKind;
FEmpty:Boolean;
public
ID:Integer;
Name:string;
Comment:string;
property Modifed:Boolean read FModifed write FModifed;
property Empty:Boolean read FEmpty write FEmpty;
procedure Update;
procedure GetBack;
constructor Create(AOwner:TTableProductKind);
end;
TTableProductKind = class(TTableData<TItemProdKind>)
const TableName = 'ProductKind';
const fnID = 'pkID';
const fnName = 'pkName';
const fnComment = 'pkComment';
private
FDB:TDatabaseCore;
FOrderBy: string;
FOrderByDESC:Boolean;
public
procedure Load;
procedure Save;
procedure GetBack(Index:Integer); overload;
procedure GetBack(Item:TItemProdKind); overload;
procedure Update(Index:Integer); overload;
procedure Update(Item:TItemProdKind); overload;
procedure Delete(Item:TItemProdKind); overload;
procedure Delete(Index:Integer); overload;
function GetNextOrderNumber:Integer;
procedure Clear; override;
property LoadOrderBy:string read FOrderBy write FOrderBy;
property LoadOrderByDESC:Boolean read FOrderByDESC write FOrderByDESC;
constructor Create(ADB:TDatabaseCore); overload;
property DatabaseCore:TDatabaseCore read FDB write FDB;
end;
implementation
{ TTableProductKind }
procedure TTableProductKind.Clear;
var i:Integer;
begin
for i:= 0 to Count-1 do Items[i].Free;
inherited;
end;
constructor TTableProductKind.Create(ADB:TDatabaseCore);
begin
inherited Create;
FOrderBy:=fnName;
FOrderByDESC:=False;
FDB:=ADB;
if not FDB.SQL.TableExists(TableName) then
with SQL.CreateTable(TableName) do
begin
AddField(fnID, ftInteger, True, True);
AddField(fnName, ftString);
AddField(fnComment, ftString);
FDB.SQL.ExecSQL(GetSQL);
EndCreate;
end;
end;
procedure TTableProductKind.Delete(Item: TItemProdKind);
begin
with SQL.Delete(TableName) do
begin
WhereFieldEqual(fnID, Item.ID);
FDB.SQL.ExecSQL(GetSQL);
EndCreate;
end;
end;
procedure TTableProductKind.Delete(Index: Integer);
begin
Delete(Items[Index]);
inherited;
end;
procedure TTableProductKind.GetBack(Item: TItemProdKind);
var RTable:TSQLiteTable;
begin
with SQL.Select(TableName) do
begin
AddField(fnName);
AddField(fnComment);
WhereFieldEqual(fnID, Item.ID);
RTable:=FDB.SQL.GetTable(GetSQL);
if RTable.Count > 0 then
begin
Item.Name:=RTable.FieldAsString(0);
Item.Comment:=RTable.FieldAsString(1);
Item.Modifed:=False;
Item.Empty:=False;
end;
RTable.Free;
EndCreate;
end;
end;
function TTableProductKind.GetNextOrderNumber: Integer;
begin
Result:=FDB.GetNextVal('ORDERS');
end;
procedure TTableProductKind.Load;
var RTable:TSQLiteTable;
Item:TItemProdKind;
begin
BeginUpdate;
Clear;
try
with SQL.Select(TableName) do
begin
AddField(fnID);
AddField(fnName);
AddField(fnComment);
OrderBy(FOrderBy, FOrderByDESC);
RTable:=FDB.SQL.GetTable(GetSQL);
while not RTable.EOF do
begin
Item:=TItemProdKind.Create(Self);
Item.ID:=RTable.FieldAsInteger(0);
Item.Name:=RTable.FieldAsString(1);
Item.Comment:=RTable.FieldAsString(2);
Item.Modifed:=False;
Item.Empty:=False;
Add(Item);
RTable.Next;
end;
RTable.Free;
EndCreate;
end;
finally
EndUpdate;
end;
end;
procedure TTableProductKind.GetBack(Index: Integer);
begin
GetBack(Items[Index]);
end;
procedure TTableProductKind.Save;
var i:Integer;
begin
for i:= 0 to Count-1 do if Items[i].Modifed then Update(i);
end;
procedure TTableProductKind.Update(Item: TItemProdKind);
var Res:Integer;
begin
with SQL.Select(TableName) do
begin
AddField(fnID);
WhereFieldEqual(fnID, Item.ID);
Res:=FDB.SQL.GetTableValue(GetSQL);
EndCreate;
end;
if Res < 0 then
begin
with SQL.InsertInto(TableName) do
begin
AddValue(fnName, Item.Name);
AddValue(fnComment, Item.Comment);
FDB.SQL.ExecSQL(GetSQL);
Item.ID:=FDB.SQL.GetLastInsertRowID;
EndCreate;
end;
end
else
begin
with SQL.Update(TableName) do
begin
AddValue(fnName, Item.Name);
AddValue(fnComment, Item.Comment);
WhereFieldEqual(fnID, Item.ID);
FDB.SQL.ExecSQL(GetSQL);
EndCreate;
end;
end;
Item.Modifed:=False;
Item.Empty:=False;
end;
procedure TTableProductKind.Update(Index: Integer);
begin
Update(Items[Index]);
end;
{ TItemProdKind }
constructor TItemProdKind.Create(AOwner:TTableProductKind);
begin
inherited Create;
FModifed:=True;
FEmpty:=True;
FOwner:=AOwner;
end;
procedure TItemProdKind.GetBack;
begin
FOwner.GetBack(Self);
end;
procedure TItemProdKind.Update;
begin
FOwner.Update(Self);
end;
end.
|
Unit QSort;
interface
Type
_Compare = Function(Var A, B) : Boolean;{ QuickSort Calls This }
{ --------------------------------------------------------------- }
{ QuickSort Algorithm by C.A.R. Hoare. Non-Recursive adaptation }
{ from "ALGORITHMS + DATA STRUCTURES = ProgramS" by Niklaus Wirth }
{ Prentice-Hall, 1976. Generalized For unTyped arguments. }
{ --------------------------------------------------------------- }
Procedure QuickSort(V : Pointer; { To Array of Records }
Cnt : Word; { Record Count }
Len : Word; { Record Length }
ALessB : _Compare); { Compare Function }
{ =================================================================== }
implementation
{
> Can you show me any version of thew quick sort that you may have? I've
> never seen it and never used it before. I always used an insertion sort
> For anything that I was doing.
Here is one (long) non-recursive version, quite fast.
}
{ --------------------------------------------------------------- }
Procedure QuickSort(V : Pointer; { To Array of Records }
Cnt : Word; { Record Count }
Len : Word; { Record Length }
ALessB : _Compare); { Compare Function }
Type
SortRec = Record
Lt, Rt : Integer
end;
SortStak = Array [0..100] of SortRec;
Var
StkT,
StkM,
Ki, Kj,
M : Word;
Rt, Lt,
I, J : Integer;
Ps : ^SortStak;
Pw, Px : Pointer;
Procedure Push(Left, Right : Integer);
begin
Ps^[StkT].Lt := Left;
Ps^[StkT].Rt := Right;
Inc(StkT);
end;
Procedure Pop(Var Left, Right : Integer);
begin
Dec(StkT);
Left := Ps^[StkT].Lt;
Right := Ps^[StkT].Rt;
end;
begin {QSort}
if (Cnt > 1) and (V <> Nil) Then
begin
StkT := Cnt - 1; { Record Count - 1 }
Lt := 1; { Safety Valve }
{ We need a stack of Log2(n-1) entries plus 1 spare For safety }
Repeat
StkT := StkT SHR 1;
Inc(Lt);
Until StkT = 0; { 1+Log2(n-1) }
StkM := Lt * SizeOf(SortRec) + Len + Len; { Stack Size + 2 Records }
GetMem(Ps, StkM); { Allocate Memory }
if Ps = Nil Then
RunError(215); { Catastrophic Error }
Pw := @Ps^[Lt]; { Swap Area Pointer }
{$IFDEF USE32}
Px := Ptr( Ofs(Pw^) + Len );
{$ELSE}
Px := Ptr(Seg(Pw^), Ofs(Pw^) + Len); { Hold Area Pointer }
{$ENDIF}
Lt := 0;
Rt := Cnt - 1; { Initial Partition }
Push(Lt, Rt); { Push Entire Table }
While StkT > 0 Do
begin { QuickSort Main Loop }
Pop(Lt, Rt); { Get Next Partition }
Repeat
I := Lt; J := Rt; { Set Work Pointers }
{ Save Record at Partition Mid-Point in Hold Area }
M := (LongInt(Lt) + Rt) div 2;
{$IFDEF USE32}
Move( Ptr( Ofs(V^) + M * Len)^, Px^, Len );
{$ELSE}
Move(Ptr(Seg(V^), Ofs(V^) + M * Len)^, Px^, Len);
{$ENDIF}
{ Get Useful Offsets to speed loops }
Ki := I * Len + Ofs(V^);
Kj := J * Len + Ofs(V^);
Repeat
{ Find Left-Most Entry >= Mid-Point Entry }
{$IFDEF USE32}
while ALessB(Ptr(Ki)^, Px^) Do
{$ELSE}
While ALessB(Ptr(Seg(V^), Ki)^, Px^) Do
{$ENDIF}
begin
Inc(Ki, Len);
Inc(I)
end;
{ Find Right-Most Entry <= Mid-Point Entry }
{$IFDEF USE32}
while ALessB(Px^, Ptr(Kj)^) Do
{$ELSE}
While ALessB(Px^, Ptr(Seg(V^), Kj)^) Do
{$ENDIF}
begin
Dec(Kj, Len);
Dec(J)
end;
{ if I > J, the partition has been exhausted }
if I <= J Then
begin
if I < J Then { we have two Records to exchange }
begin
{$IFDEF USE32}
Move(Ptr(ki)^, Pw^, Len);
Move(Ptr(Kj)^, Ptr(Ki)^, Len);
Move(Pw^, Ptr(Kj)^, Len);
{$ELSE}
Move(Ptr(Seg(V^), Ki)^, Pw^, Len);
Move(Ptr(Seg(V^), Kj)^, Ptr(Seg(V^), Ki)^, Len);
Move(Pw^, Ptr(Seg(V^), Kj)^, Len);
{$ENDIF}
end;
Inc(I);
Dec(J);
Inc(Ki, Len);
Dec(Kj, Len);
end; { if I <= J }
Until I > J; { Until All Swaps Done }
{ We now have two partitions. At left are all Records }
{ < X, and at right are all Records > X. The larger }
{ partition is stacked and we re-partition the residue }
{ Until time to pop a deferred partition. }
if (J - Lt) < (Rt - I) Then { Right-Most Partition is Larger }
begin
if I < Rt Then
Push(I, Rt); { Stack Right Side }
Rt := J; { Resume With Left }
end
else { Left-Most Partition is Larger }
begin
if Lt < J Then
Push(Lt, J); { Stack Left Side }
Lt := I; { Resume With Right }
end;
Until Lt >= Rt; { QuickSort is now Complete }
end;
FreeMem(Ps, StkM); { Free Stack and Work Areas }
end;
end; {QSort}
end.
|
{
QuickChange v2.5
Created by matortheeternal
*Documentation*
This script will allow you to execute any number of functions on selected
records to modify, add, or delete elements at specific locations. The
functions this script offers are listed below:
-ElementAssign: Adds an element to a list of elements. E.g. the "Conditions"
section of a COBJ record or the "Factions" section of an NPC record.
Specify the location of the list and the value of the element. You can
add one multiple-valued element per script run.
-Add: Adds an element or group at the specified location. Use this for
elements that aren't in a list.
-Remove: Removes an element, either from a list or just the element itself.
Enter an index if you want to remove an element from a list, else leave
the index input blank.
-Replace: Replaces an element. Doesn't work with lists. Enter the
location of the element you want to look at, the value you want to find,
and the value you want to replace the found value with.
-Formula: Applies a formula to an integer element. Enter the location
of the element you want to look at, and the formula you want to apply to it.
Supported operators: + for addition, - for subtraction, * for multiplication,
/ for division, and ^ for power. You need a space before and after each
operator except for the power operator ^. Parenthesis are supported, and I
recommend you use them as much as possible. x is the variable for the
starting value. So you can do stuff like:
2 * x + 50
x^2 - 1
((3 * x) + x)/2
((5 * x)/2) - x
Everything explodes if the expression ever involves negative numbers, so I
recommend you avoid them.
-Restore: Restores values on an override record to those found on the master record,
or a lower override record.
-TemplateRestore: Restores values to those found on a template record on armor records
with a TNAM and weapons with a CNAM field. Enter the location for the element
you want to restore, and the rest is done for you.
-Copy: Copies an element to all selected records. You can use one Copy function
per script execution (until I fix this).
-Import: Imports values from a csv file exported with QuickDisplay onto matching records.
-ArrayImport: Imports values from an array text document exported with QuickDisplay onto
the selected records at the selected path. This allows you to set multiple values stored
at a single path simultaneously. E.g. Keywords, Factions, Head Parts, Conditions, etc.
In TES5Edit there are two kinds of values, Native Values and Edit Values.
Edit values are the ones you see when you look at a record in TES5Edit, while
native values are the ones that are stored internally. This script uses edit values.
}
unit userscript;
uses mteFunctions;
const
vs = 'v2.5';
sFunctions = 'Add'#13'ElementAssign'#13'Remove'#13'Replace'#13'Formula'#13'Restore'#13'TemplateRestore'#13'Copy'#13'Import'#13'ArrayImport';
formuladebug = false; // set formuladebug to true to debug the formula function
var
badfile, processed: boolean;
slFunctions, slInput, slImport, slImportValues, slImportPaths, slArray: TStringList;
sFiles: string;
frm: TForm;
sb: TScrollBox;
lbl01: TLabel;
pnlBottom: TPanel;
btnPlus, btnMinus, btnOk, btnCancel: TButton;
lstEntries: TList;
//=========================================================================
// ClearPanel: Frees components in the panel, excluding the base combobox
procedure ClearPanel(Sender: TObject);
var
pnl: TPanel;
i: integer;
begin
pnl := TComboBox(Sender).GetParentComponent;
for i := pnl.ControlCount - 1 downto 1 do
pnl.Controls[i].Free;
end;
//=========================================================================
// CreatePathEdit: Makes a path TEdit component at index
function CreatePathEdit(Sender: TObject): TObject;
var
ed: TEdit;
pnl: TPanel;
begin
// create entry inside of panel
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
ed := TEdit.Create(frm);
ed.Parent := pnl;
ed.Left := 116;
ed.Top := 8;
ed.Width := 150;
ed.Text := '<Path>';
Result := ed;
end;
//=========================================================================
// CreateAddEntry: Makes an entry for the Add function
procedure CreateAddEntry(Sender: TObject);
var
ed: TEdit;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
CreatePathEdit(Sender);
// create value edit
ed := TEdit.Create(frm);
ed.Parent := pnl;
ed.Left := 274;
ed.Top := 8;
ed.Width := 100;
ed.Text := '<Value>';
end;
//=========================================================================
// CreateElementAssignEntry: Makes an entry for the ElementAssign function
procedure CreateElementAssignEntry(Sender: TObject);
var
ed: TEdit;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
CreatePathEdit(Sender);
// create value edit
ed := TEdit.Create(frm);
ed.Parent := pnl;
ed.Left := 274;
ed.Top := 8;
ed.Width := 100;
ed.Text := '<Value>';
end;
//=========================================================================
// CreateRemoveEntry: Makes an entry for the Remove function
procedure CreateRemoveEntry(Sender: TObject);
var
ed: TEdit;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
CreatePathEdit(Sender);
// create index edit
ed := TEdit.Create(frm);
ed.Parent := pnl;
ed.Left := 274;
ed.Top := 8;
ed.Width := 50;
ed.Text := '<Index>';
end;
//=========================================================================
// CreateReplaceEntry: Makes an entry for the Replace function
procedure CreateReplaceEntry(Sender: TObject);
var
ed1, ed2: TEdit;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
CreatePathEdit(Sender);
// create find edit
ed1 := TEdit.Create(frm);
ed1.Parent := pnl;
ed1.Left := 274;
ed1.Top := 8;
ed1.Width := 100;
ed1.Text := '<Find>';
// create replace edit
ed2 := TEdit.Create(frm);
ed2.Parent := pnl;
ed2.Left := ed1.Left + ed1.Width + 8;
ed2.Top := ed1.Top;
ed2.Width := 100;
ed2.Text := '<Replace>';
end;
//=========================================================================
// CreateRestoreEntry: Makes an entry for the Restore function
procedure CreateRestoreEntry(Sender: TObject);
var
cb: TComboBox;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
CreatePathEdit(Sender);
// create files combobox
cb := TComboBox.Create(frm);
cb.Parent := pnl;
cb.Left := 274;
cb.Top := 8;
cb.Width := 150;
cb.Autocomplete := True;
cb.Style := csDropDown;
cb.Sorted := False;
cb.AutoDropDown := True;
cb.Items.Text := sFiles;
cb.ItemIndex := 0;
end;
//=========================================================================
// CreateTemplateRestoreEntry: Makes an entry for the TemplateRestore function
procedure CreateTemplateRestoreEntry(Sender: TObject);
var
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
CreatePathEdit(Sender);
end;
//=========================================================================
// CreateImportEntry: Makes an entry for the Import function
procedure CreateImportEntry(Sender: TObject);
var
ed: TEdit;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create import edit
ed := TEdit.Create(frm);
ed.Parent := pnl;
ed.Left := 116;
ed.Top := 8;
ed.Width := 450;
ed.Text := ProgramPath + 'Edit Scripts\Exported.csv';
end;
//=========================================================================
// CreateImportEntry: Makes an entry for the Import function
procedure CreateArrayImportEntry(Sender: TObject);
var
ed: TEdit;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
CreatePathEdit(Sender);
// create import edit
ed := TEdit.Create(frm);
ed.Parent := pnl;
ed.Left := 274;
ed.Top := 8;
ed.Width := 300;
ed.Text := ProgramPath + 'Edit Scripts\';
end;
//=========================================================================
// CreateFormulaEntry: Makes an entry for the Formula function
procedure CreateFormulaEntry(Sender: TObject);
var
ed: TEdit;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create path edit
CreatePathEdit(Sender);
// create Formula edit
ed := TEdit.Create(frm);
ed.Parent := pnl;
ed.Left := 274;
ed.Top := 8;
ed.Width := 150;
ed.Text := '<Formula>';
end;
//=========================================================================
// LoadGroups: Loads record groups from a file into a TComboBox
procedure LoadGroups(Sender: TObject);
var
fn, sGroups: string;
f, g: IInterface;
i: integer;
pnl: TPanel;
begin
pnl := TComboBox(Sender).GetParentComponent;
// clear groups, records, and exit if invalid file specified
if TComboBox(Sender).ItemIndex = -1 then begin
TComboBox(pnl.Controls[2]).Items.Text := '';
TComboBox(pnl.Controls[3]).Items.Text := '';
exit;
end;
// find file
fn := TComboBox(Sender).Text;
for i := 0 to FileCount - 1 do begin
if (fn = GetFileName(FileByLoadOrder(i))) then begin
f := FileByLoadOrder(i);
Break;
end;
end;
// if file found, load groups
if Assigned(f) then begin
sGroups := '';
for i := 0 to ElementCount(f) - 1 do begin
g := ElementByIndex(f, i);
if Signature(g) = 'TES4' then Continue;
if not (sGroups = '') then sGroups := sGroups + #13 + GroupSignature(g)
else sGroups := GroupSignature(g);
end;
TComboBox(pnl.Controls[2]).Items.Text := sGroups;
TComboBox(pnl.Controls[2]).ItemIndex := 0;
end;
end;
//=========================================================================
// ProcessElementsIn: Processes elements in a file or group
procedure ProcessElementsIn(g: IInterface; lst: TStringList);
var
r: IInterface;
s: string;
i: integer;
begin
for i := 0 to ElementCount(g) - 1 do begin
r := ElementByIndex(g, i);
if (Pos('GRUP Cell', Name(r)) = 1) then Continue;
if (Pos('GRUP Exterior Cell', Name(r)) = 1) then begin
ProcessElementsIn(r, lst);
Continue;
end;
if (Signature(r) = 'GRUP') then
ProcessElementsIn(r, lst)
else if (Signature(r) = 'CELL') then
lst.AddObject(Name(r), TObject(r))
else begin
lst.AddObject(geev(r, 'EDID'), r);
end;
end;
end;
//=========================================================================
// LoadRecords: Loads records from group into combobox
procedure LoadRecords(Sender: TObject);
var
f, g: IInterface;
fn: string;
i, j: integer;
pnl: TPanel;
slRecords: TStringList;
begin
pnl := TComboBox(Sender).GetParentComponent;
// we're using a stringlist so we can access the record later
slRecords := TStringList.Create;
// clear records
TComboBox(pnl.Controls[3]).Items.Clear;
//exit if invalid group specified
if TComboBox(Sender).ItemIndex = -1 then
exit;
// find file
fn := pnl.Controls[1].Text;
if TComboBox(Sender).ItemIndex > -1 then begin
for i := 0 to FileCount - 1 do begin
if (fn = GetFileName(FileByIndex(i))) then begin
f := FileByIndex(i);
Break;
end;
end;
// if file found, set records combobox content
if Assigned(f) then begin
g := GroupBySignature(f, TComboBox(Sender).Text);
ProcessElementsIn(g, slRecords);
for j := 0 to slRecords.Count - 1 do
TComboBox(pnl.Controls[3]).Items.AddObject(slRecords[j], slRecords.Objects[j]);
TComboBox(pnl.Controls[3]).ItemIndex := 0;
end;
end;
slRecords.Free;
end;
//=========================================================================
// CreateCopyEntry: Makes an entry for the Copy function
procedure CreateCopyEntry(Sender: TObject);
var
cb1, cb2, cb3: TComboBox;
ed1, ed2: TEdit;
ix: integer;
pnl: TPanel;
begin
// clear panel of previous entries and create entry inside of it
ClearPanel(Sender);
pnl := TComboBox(Sender).GetParentComponent;
// create Files combobox
cb1 := TComboBox.Create(frm);
cb1.Parent := pnl;
cb1.Left := 116;
cb1.Top := 8;
cb1.Width := 100;
cb1.Autocomplete := True;
cb1.Style := csDropDown;
cb1.Sorted := False;
cb1.AutoDropDown := True;
cb1.Items.Text := sFiles;
cb1.Text := '<File>';
cb1.OnSelect := LoadGroups;
// create groups combobox
cb2 := TComboBox.Create(frm);
cb2.Parent := pnl;
cb2.Left := cb1.Left + cb1.Width + 8;
cb2.Top := cb1.Top;
cb2.Width := 70;
cb2.Autocomplete := True;
cb2.Style := csDropDown;
cb2.Sorted := True;
cb2.AutoDropDown := True;
cb2.Text := '<Group>';
cb2.OnSelect := LoadRecords;
// create records combobox
cb3 := TComboBox.Create(frm);
cb3.Parent := pnl;
cb3.Left := cb2.Left + cb2.Width + 8;
cb3.Top := cb1.Top;
cb3.Width := 149;
cb3.Autocomplete := True;
cb3.Style := csDropDown;
cb3.Sorted := True;
cb3.AutoDropDown := True;
cb3.Text := '<Record>';
// create path edit
ed1 := TEdit.Create(frm);
ed1.Parent := pnl;
ed1.Left := cb3.Left + cb3.Width + 8;
ed1.Top := cb1.Top;
ed1.Width := 100;
ed1.Text := '<Path>';
end;
//=========================================================================
// AddEntry: Creates a new empty function entry
procedure AddEntry;
var
i: integer;
cb: TComboBox;
pnl: TPanel;
begin
// create panel
pnl := TPanel.Create(frm);
pnl.Parent := sb;
pnl.Width := 595;
pnl.Height := 30;
pnl.Top := 30*lstEntries.Count - sb.VertScrollBar.Position;
pnl.BevelOuter := bvNone;
// create combobox
cb := TComboBox.Create(frm);
cb.Parent := pnl;
cb.Left := 10;
cb.Top := 8;
cb.Width := 100;
cb.Style := csDropDownList;
cb.Items.Text := sFunctions;
cb.OnSelect := FunctionManager;
cb.ItemIndex := 0;
FunctionManager(cb);
lstEntries.Add(pnl);
end;
//=========================================================================
// RemoveEntry: Deletes the lowest function entry
procedure RemoveEntry;
var
pnl: TPanel;
i: integer;
begin
if lstEntries.Count > 1 then begin
pnl := TPanel(lstEntries[Pred(lstEntries.Count)]);
for i := pnl.ControlCount - 1 downto 0 do begin
pnl.Controls[i].Visible := false;
pnl.Controls[i].Free;
end;
lstEntries.Delete(Pred(lstEntries.Count));
pnl.Free;
end;
end;
//=========================================================================
// FunctionManager: Handles what entry to make when a function is chosen
procedure FunctionManager(Sender: TObject);
var
s, t: string;
n: integer;
ed: TEdit;
begin
s := TComboBox(Sender).Text;
if (s = 'Add') then CreateAddEntry(Sender)
else if (s = 'ElementAssign') then CreateElementAssignEntry(Sender)
else if (s = 'Remove') then CreateRemoveEntry(Sender)
else if (s = 'Replace') then CreateReplaceEntry(Sender)
else if (s = 'Formula') then CreateFormulaEntry(Sender)
else if (s = 'Restore') then CreateRestoreEntry(Sender)
else if (s = 'TemplateRestore') then CreateTemplateRestoreEntry(Sender)
else if (s = 'Copy') then CreateCopyEntry(Sender)
else if (s = 'Import') then CreateImportEntry(Sender)
else if (s = 'ArrayImport') then CreateArrayImportEntry(Sender);
end;
//=========================================================================
// OptionsForm: The main options form
procedure OptionsForm;
var
s, t: string;
obj: TObject;
i, j: integer;
pnl: TPanel;
cb: TComboBox;
begin
frm := TForm.Create(nil);
try
frm.Caption := 'QuickChange '+vs;
frm.Width := 625;
frm.Height := 350;
frm.Position := poScreenCenter;
frm.BorderStyle := bsDialog;
lbl01 := TLabel.Create(frm);
lbl01.Parent := frm;
lbl01.Top := 8;
lbl01.Left := 8;
lbl01.Width := 484;
lbl01.Height := 25;
lbl01.Caption := 'Choose the functions and function parameters you want to apply below:';
pnlBottom := TPanel.Create(frm);
pnlBottom.Parent := frm;
pnlBottom.BevelOuter := bvNone;
pnlBottom.Align := alBottom;
pnlBottom.Height := 80;
sb := TScrollBox.Create(frm);
sb.Parent := frm;
sb.Height := frm.Height - 150;
sb.Top := 35;
sb.Width := frm.Width - 5;
sb.Align := alNone;
btnPlus := TButton.Create(frm);
btnPlus.Parent := pnlBottom;
btnPlus.Caption := '+';
btnPlus.Width := 25;
btnPlus.Left := frm.Width - 2*btnPlus.Width - 20;
btnPlus.Top := 5;
btnPlus.OnClick := AddEntry;
btnMinus := TButton.Create(frm);
btnMinus.Parent := pnlBottom;
btnMinus.Caption := '-';
btnMinus.Width := btnPlus.Width;
btnMinus.Left := btnPlus.Left + btnPlus.Width + 5;
btnMinus.Top := btnPlus.Top;
btnMinus.OnClick := RemoveEntry;
btnOk := TButton.Create(frm);
btnOk.Parent := pnlBottom;
btnOk.Caption := 'OK';
btnOk.ModalResult := mrOk;
btnOk.Left := frm.Width div 2 - btnOk.Width - 8;
btnOk.Top := pnlBottom.Height - 40;
btnCancel := TButton.Create(frm);
btnCancel.Parent := pnlBottom;
btnCancel.Caption := 'Cancel';
btnCancel.ModalResult := mrCancel;
btnCancel.Left := btnOk.Left + btnOk.Width + 16;
btnCancel.Top := btnOk.Top;
// start with one entry
AddEntry;
if frm.ShowModal = mrOk then begin
for i := 0 to lstEntries.Count - 1 do begin
pnl := TPanel(lstEntries[i]);
slFunctions.Add(TComboBox(pnl.Controls[0]).Text);
s := '';
for j := 1 to pnl.ControlCount - 1 do begin
if pnl.Controls[j].InheritsFrom(TEdit) then
s := s + TEdit(pnl.Controls[j]).Text + ',';
if pnl.Controls[j].InheritsFrom(TComboBox) then
s := s + TComboBox(pnl.Controls[j]).Text + ',';
end;
if slFunctions[i] = 'Copy' then begin
cb := TComboBox(pnl.Controls[3]);
j := cb.Items.IndexOf(cb.Text);
slInput.AddObject(s, TObject(cb.Items.Objects[j]))
end
else
slInput.AddObject(s, TObject(nil));
end;
end;
finally
frm.Free;
end;
end;
//=========================================================================
// Resolve: For resolving a mathematical expression input as a string
function Resolve(input: string): string;
var
s1, s2, s3, s4, subinput: string;
c: integer;
r1: real;
begin
subinput := input;
// exponents first
While (Pos('^', subinput) > 0) do begin
// find end of expression
c := 1;
s1 := Copy(subinput, Pos('^', subinput) + 1, c);
if formuladebug then AddMessage('s1 = '+s1);
While Pos(' ', s1) = 0 do begin
Inc(c);
if Pos('^', subinput) + 1 + c > Length(subinput) then Break;
s1 := Copy(subinput, Pos('^', subinput) + 1, c);
if formuladebug then AddMessage('s1 = '+s1);
end;
// find beginning of expression
c := 1;
s2 := Copy(subinput, Pos('^', subinput) - c, c);
if formuladebug then AddMessage('s2 = '+s2);
While Pos(' ', s2) = 0 do begin
Inc(c);
if Pos('^', subinput) - c < 1 then Break;
s2 := Copy(subinput, Pos('^', subinput) - c, c);
if formuladebug then AddMessage('s2 = '+s2);
end;
r1 := exp(StrToInt(Trim(s1))*ln(StrToInt(Trim(s2))));
if formuladebug then AddMessage(FloatToStr(r1));
subinput := StringReplace(subinput, Trim(s2)+'^'+Trim(s1), FloatToStr(r1), nil);
if formuladebug then AddMessage(subinput);
end;
// multiplication and division
While ((Pos('*', subinput) > 0) or (Pos('/', subinput) > 0)) do begin
While (Pos('*', subinput) > Pos('/', subinput)) do begin
// fix overly spacious syntax
s1 := subinput;
if Pos(' *', s1) = Pos('*', s1) - 1 then
s1 := Copy(s1, 1, Pos(' *', s1) - 1) + Copy(s1, Pos(' *', s1) + 1, Length(s1));
if formuladebug then AddMessage('s1 = '+s1);
if Pos('* ', s1) = Pos('*', s1) then
s1 := Copy(s1, 1, Pos('* ', s1)) + Copy(s1, Pos('*', s1) + 2, Length(s1));
if formuladebug then AddMessage('s1 = '+s1);
// find end of expression
c := 1;
s2 := Copy(s1, Pos('*', s1) + 1, c);
if formuladebug then AddMessage('s2 = '+s2);
While Pos(' ', s2) = 0 do begin
Inc(c);
if Pos('*', s1) + c > Length(s1) then Break;
s2 := Copy(s1, Pos('*', s1) + 1, c);
if formuladebug then AddMessage('s2 = '+s2);
end;
// find beginning of expression
c := 1;
s3 := Copy(s1, Pos('*', s1) - c, c);
if formuladebug then AddMessage('s3 = '+s3);
While Pos(' ', s3) = 0 do begin
Inc(c);
if Pos('*', s1) - c < 1 then Break;
s3 := Copy(s1, Pos('*', s1) - c, c);
if formuladebug then AddMessage('s3 = '+s3);
end;
r1 := StrToInt(Trim(s3)) * StrToInt(Trim(s2));
if formuladebug then AddMessage(FloatToStr(r1));
subinput := StringReplace(s1, Trim(s3)+'*'+Trim(s2), FloatToStr(r1), nil);
if formuladebug then AddMessage(subinput);
end;
While (Pos('/', subinput) > Pos('*', subinput)) do begin
// fix overly spacious syntax
s1 := subinput;
if Pos(' /', s1) = Pos('/', s1) - 1 then
s1 := Copy(s1, 1, Pos(' /', s1) - 1) + Copy(s1, Pos(' /', s1) + 1, Length(s1));
if formuladebug then AddMessage('s1 = '+s1);
if Pos('/ ', s1) = Pos('/', s1) then
s1 := Copy(s1, 1, Pos('/ ', s1)) + Copy(s1, Pos('/', s1) + 2, Length(s1));
if formuladebug then AddMessage('s1 = '+s1);
// find end of expression
c := 1;
s2 := Copy(s1, Pos('/', s1) + 1, c);
if formuladebug then AddMessage('s2 = '+s2);
While Pos(' ', s2) = 0 do begin
Inc(c);
if Pos('/', s1) + c > Length(s1) then Break;
s2 := Copy(s1, Pos('/', s1) + 1, c);
if formuladebug then AddMessage('s2 = '+s2);
end;
// find beginning of expression
c := 1;
s3 := Copy(s1, Pos('/', s1) - c, c);
if formuladebug then AddMessage('s3 = '+s3);
While Pos(' ', s3) = 0 do begin
Inc(c);
if Pos('/', s1) - c < 1 then Break;
s3 := Copy(s1, Pos('/', s1) - c, c);
if formuladebug then AddMessage('s3 = '+s3);
end;
r1 := StrToInt(Trim(s3))/StrToInt(Trim(s2));
if formuladebug then AddMessage(FloatToStr(r1));
subinput := StringReplace(s1, Trim(s3)+'/'+Trim(s2), FloatToStr(r1), nil);
if formuladebug then AddMessage(subinput);
end;
end;
// addition and subtraction
While ((Pos('-', subinput) > 0) or (Pos('+', subinput) > 0)) do begin
While (Pos('+', subinput) > Pos('-', subinput)) do begin
// fix overly spacious syntax
s1 := subinput;
if Pos(' +', s1) = Pos('+', s1) - 1 then
s1 := Copy(s1, 1, Pos(' +', s1) - 1) + Copy(s1, Pos(' +', s1) + 1, Length(s1));
if formuladebug then AddMessage('s1 = '+s1);
if Pos('+ ', s1) = Pos('+', s1) then
s1 := Copy(s1, 1, Pos('+ ', s1)) + Copy(s1, Pos('+', s1) + 2, Length(s1));
if formuladebug then AddMessage('s1 = '+s1);
// find end of expression
c := 1;
s2 := Copy(s1, Pos('+', s1) + 1, c);
if formuladebug then AddMessage('s2 = '+s2);
While (Pos(' ', s2) = 0) do begin
Inc(c);
if Pos('+', s1) + c > Length(s1) then Break;
s2 := Copy(s1, Pos('+', s1) + 1, c);
if formuladebug then AddMessage('s2 = '+s2);
end;
// find beginning of expression
c := 1;
s3 := Copy(s1, Pos('+', s1) - c, c);
if formuladebug then AddMessage('s3 = '+s3);
While Pos(' ', s3) = 0 do begin
Inc(c);
if Pos('+', s1) - c < 1 then Break;
s3 := Copy(s1, Pos('+', s1) - c, c);
if formuladebug then AddMessage('s3 = '+s3);
end;
r1 := StrToInt(Trim(s3)) + StrToInt(Trim(s2));
if formuladebug then AddMessage(FloatToStr(r1));
subinput := StringReplace(s1, Trim(s3)+'+'+Trim(s2), FloatToStr(r1), nil);
if formuladebug then AddMessage(subinput);
end;
While (Pos('-', subinput) > Pos('+', subinput)) do begin
// fix overly spacious syntax
s1 := subinput;
if Pos(' -', s1) = Pos('-', s1) - 1 then
s1 := Copy(s1, 1, Pos(' -', s1) - 1) + Copy(s1, Pos(' -', s1) + 1, Length(s1));
if formuladebug then AddMessage('s1 = '+s1);
if Pos('- ', s1) = Pos('-', s1) then
s1 := Copy(s1, 1, Pos('- ', s1)) + Copy(s1, Pos('-', s1) + 2, Length(s1));
if formuladebug then AddMessage('s1 = '+s1);
// find end of expression
c := 1;
s2 := Copy(s1, Pos('-', s1) + 1, c);
if formuladebug then AddMessage('s2 = '+s2);
While Pos(' ', s2) = 0 do begin
Inc(c);
if Pos('-', s1) + c > Length(s1) then Break;
s2 := Copy(s1, Pos('-', s1) + 1, c);
if formuladebug then AddMessage('s2 = '+s2);
end;
// find beginning of expression
c := 1;
s3 := Copy(s1, Pos('-', s1) - c, c);
if formuladebug then AddMessage('s3 = '+s3);
While Pos(' ', s3) = 0 do begin
Inc(c);
if Pos('-', s1) - c < 1 then Break;
s3 := Copy(s1, Pos('-', s1) - c, c);
if formuladebug then AddMessage('s3 = '+s3);
end;
r1 := StrToInt(Trim(s3)) - StrToInt(Trim(s2));
if formuladebug then AddMessage(FloatToStr(r1));
subinput := StringReplace(s1, Trim(s3)+'-'+Trim(s2), FloatToStr(r1), nil);
if formuladebug then AddMessage(subinput);
end;
end;
Result := subinput;
end;
//=========================================================================
// Formula: Resolves a string input into single operations
function Formula(input: string): integer;
var
s1, s2, s3, s4: string;
begin
// find most internal calculation for first evaluation
s3 := input;
While ((Pos('(', s3) > 0) and (Pos(')', s3) > 0)) do begin
s1 := Copy(s3, 1, Pos(')', s3) - 1);
if FormulaDebug then AddMessage(s1);
While Pos('(', s1) > 0 do begin
s1 := Copy(s1, Pos('(', s1) + 1, Length(s1));
if FormulaDebug then AddMessage(s1);
end;
s2 := Resolve(s1);
s3 := StringReplace(s3, '('+s1+')', s2, nil);
if FormulaDebug then AddMessage(s3);
end;
s4 := Resolve(s3);
if formuladebug then AddMessage(s4);
Result := StrToInt(s4);
end;
//=========================================================================
// FindRecordsIn: Finds a record matching string
function FindRecordsIn(g: IInterface; s: string): IInterface;
var
i: integer;
r, res: IInterface;
begin
for i := 0 to ElementCount(g) - 1 do begin
r := ElementByIndex(g, i);
if (s = Name(r)) or (s = geev(r, 'EDID')) then begin
Result := r;
Break;
end;
if (s = geev(r, 'EDID')) then begin
Result := r;
Break;
end;
if (Pos('GRUP Exterior Cell', Name(r)) = 1) then begin
res := FindRecordsIn(r, s);
if Assigned(res) then Result := res;
Continue;
end;
if (Pos('GRUP Cell', Name(r)) = 1) then Continue;
if (Signature(r) = 'GRUP') then begin
res := FindRecordsIn(r, s);
if Assigned(res) then Result := res;
end;
end;
end;
//=========================================================================
// Initialize: Welcome messages, stringlist creation, and OptionsForm
function Initialize: integer;
var
i: integer;
begin
// welcome messages
AddMessage(#13#10#13#10);
AddMessage('----------------------------------------------------------');
AddMessage('QuickChange '+vs+': For fast element modification.');
AddMessage('----------------------------------------------------------');
// create lists
lstEntries := TList.Create;
slFunctions := TStringList.Create;
slInput := TStringList.Create;
slImport := TStringList.Create;
slImportValues := TStringList.Create;
slImportPaths := TStringList.Create;
slArray := TStringList.Create;
AddMessage('Created lists.');
// create sFiles list of files
for i := 0 to FileCount - 1 do begin
if not (sFiles = '') then sFiles := sFiles + #13 + GetFileName(FileByLoadOrder(i))
else sFiles := GetFileName(FileByLoadOrder(i));
end;
// create options form
OptionsForm;
// finished initializing
AddMessage(#13#10+'Applying functions...');
Result := 0;
end;
//=========================================================================
// Process: Make changes to selected records.
function Process(e: IInterface): integer;
var
s, edid, s1, s2, s3, s4, s5: string;
i, j, k, m: integer;
element, newelement, template, mRec, ovRec, f, r, g, ce: IInterface;
begin
// exit if no functions chosen
if slFunctions.Count = 0 then exit;
// exit if user is trying to modify bethesda master files
if (Pos(GetFileName(GetFile(e)), bethesdaFiles) > 0) then begin
badfile := true;
exit;
end;
// exit if record is header
if Signature(e) = 'TES4' then Exit;
// apply the functions specified by the user to the records selected by the user
edid := geev(e, 'EDID');
AddMessage(' Procesing record: '+edid);
processed := true;
for i := 0 to slFunctions.Count - 1 do begin
element := nil;
// Add function
if (slFunctions[i] = 'Add') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
s2 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 1) + 1, ItPos(',', slInput[i], 2) - 1);
AddMessage(s1);
newelement := Add(e, s1, True);
if Assigned(newelement) then begin
if (not (s2 = '')) and (not (s2 = '<Value>')) then begin
SetEditValue(newelement, s2);
AddMessage(' Created element at path: '+s1+' with value: '+s2+' on record: '+edid);
end
else
AddMessage(' Created element at path: '+s1+' on record: '+edid);
end
else
AddMessage(' !Failed to create element at path: '+s1+' on record: '+edid);
end;
// ElementAssign function
if (slFunctions[i] = 'ElementAssign') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
s2 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 1) + 1, ItPos(',', slInput[i], 2) - 1);
element := ElementByIP(e, s1);
if Assigned(element) then begin
newelement := ElementAssign(element, HighInteger, nil, False);
if (not (s2 = '')) and (not (s2 = '<Value>')) then begin
SetEditValue(newelement, s2);
AddMessage(' Assigned element at path: '+s1+' with value: '+s2+' on record: '+edid);
end;
end
else
AddMessage(' !Couldn''t find an element at path: '+s1+' on record: '+edid);
end;
// Remove function
if (slFunctions[i] = 'Remove') then begin
AddMessage('Remove');
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
AddMessage('s1 = '+s1);
s2 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 1) + 1, ItPos(',', slInput[i], 2) - 1);
AddMessage('s2 = '+s2);
element := ElementByIP(e, s1);
if Assigned(element) then begin
if (s2 = '') or (s2 = '<Index>') then begin
RemoveNode(element);
AddMessage(' Removed element at path: '+s1+' on record: '+edid);
end
else begin
RemoveNode(ElementByIndex(element, StrToInt(s2)));
AddMessage(' Removed element #'+s2+' at path: '+s1+' on record: '+edid);
end;
end
else
AddMessage(' !Couldn''t find an element at path: '+s1+' on record: '+edid);
end;
// Replace function
if (slFunctions[i] = 'Replace') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
s2 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 1) + 1, ItPos(',', slInput[i], 2) - 1);
s3 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 2) + 1, ItPos(',', slInput[i], 3) - 1);
s := nil;
s := geev(e, s1);
if (s = s2) or (s2 = '*') then begin
seev(e, s1, s3);
AddMessage(' '+s+' was replaced with '+s3+' on '+edid);
end;
if not Assigned(s) then AddMessage(' !Couldn''t find value at path: '+s1+' on '+edid)
end;
// Formula function
if (slFunctions[i] = 'Formula') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
s2 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 1) + 1, ItPos(',', slInput[i], 2) - 1);
if Assigned(geev(e, s1)) then begin
s := nil;
try
s := IntToStr(geev(e, s1));
except
on Exception do
AddMessage(' !Edit value of element at path: '+s1+' on record: '+edid+' is non-integer.');
end;
if Assigned(s) then begin
k := Formula(StringReplace(s2, 'x', s, [rfReplaceAll]));
AddMessage(' Applying formula: '+StringReplace(s2, 'x', s, [rfReplaceAll])+' = '+IntToStr(k));
seev(e, s1, k);
end;
end
else
AddMessage(' !Couldn''t find an element at path: '+s1+' on record: '+edid);
end;
// Restore function
if (slFunctions[i] = 'Restore') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
s2 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 1) + 1, ItPos(',', slInput[i], 2) - 1);
mRec := MasterOrSelf(e);
// skip if record is master (the function can only be run on override records)
if Equals(mRec, e) then begin
AddMessage(' Record is a base record, skipping.');
exit;
end;
// check if master record is the one user wanted to copy values from
if GetFileName(GetFile(mRec)) = s2 then begin
AddMessage(' Copying values from master record.');
if not (geev(e, s1) = '') then
AddMessage(' Value at path "'+s1+'" changed from "'+geev(e, s1)+'" to "'+geev(mRec, s1)+'"')
else
AddMessage(' Value at path "'+s1+'" restored.');
wbCopyElementToRecord(ElementByIP(mRec, s1), e, False, True);
end
else begin
// look for a lower override to copy values from
for j := 0 to OverrideCount(mRec) - 1 do begin
AddMessage(' Looking for override record...');
if GetFileName(GetFile(OverrideByIndex(mRec, j))) = s2 then begin
AddMessage(' Found override record.');
ovRec := OverrideByIndex(mRec, j);
Break;
end;
end;
if not (geev(e, s1) = '') then
AddMessage(' Value at path "'+s1+'" changed from "'+geev(e, s1)+'" to "'+geev(ovRec, s1)+'"')
else
AddMessage(' Value at path "'+s1+'" restored.');
wbCopyElementToRecord(ElementByIP(ovRec, s1), e, False, True);
end;
end;
// TemplateRestore function
if (slFunctions[i] = 'TemplateRestore') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
if Assigned(geev(e, s1)) then begin
if Signature(e) = 'ARMO' then begin
if Assigned(geev(e, 'TNAM')) then begin
template := LinksTo(ElementBySignature(e, 'TNAM'));
s := geev(e, s1);
seev(e, s1, geev(template, s1));
AddMessage(' Restored value on '+edid+' from '+s+' to '+geev(e, s1));
end
else AddMessage(' !TemplateRestore function can only be used on armors with a TNAM element or weapons with the CNAM element.');
end;
if Signature(e) = 'WEAP' then begin
if Assigned(geev(e, 'CNAM')) then begin
template := LinksTo(ElementBySignature(e, 'CNAM'));
s := geev(e, s1);
seev(e, s1, geev(template, s1));
AddMessage(' Restored value on '+edid+' from '+s+' to '+geev(e, s1));
end
else AddMessage(' !TemplateRestore function can only be used on armors with a TNAM element or weapons with the CNAM element.');
end;
end
else
AddMessage(' !Couldn''t find an element at path: '+s1+' on record: '+edid);
end;
// Copy function
if (slFunctions[i] = 'Copy') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
s2 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 1) + 1, ItPos(',', slInput[i], 2) - 1);
s3 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 2) + 1, ItPos(',', slInput[i], 3) - 1);
s4 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 3) + 1, ItPos(',', slInput[i], 4) - 1);
for j := 0 to FileCount - 1 do begin
s := GetFileName(FileByIndex(j));
if (s = s1) then f := FileByIndex(j);
end;
r := ObjectToElement(slInput.Objects[i]);
AddMessage(' Copying the element '+s4+' from the record '+ShortName(r));
ce := ElementByIP(r, s4);
if Assigned(ce) then begin
if (not (s5 = '')) and (not (s5 = '<Index>')) then begin
element := ElementByIP(e, s4);
try
m := StrToInt(s5);
except on Exception do
AddMessage(' !Failed to copy element, index was non-integer.');
Continue;
end;
newelement := ElementAssign(element, HighInteger, ElementByIndex(ce, m), False);
end
else wbCopyElementToRecord(ce, e, True, True);
end;
end;
// Import function
if (slFunctions[i] = 'Import') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
slImport.LoadFromFile(s1);
if slImportPaths.Count = 0 then
slImportPaths.Text := StringReplace(Copy(slImport[0], Pos(',', slImport[0]) + 1, Length(slImport[0])), ',', #13, [rfReplaceAll]);
for j := 0 to slImport.Count - 1 do begin
if Pos(IntToStr(FormID(e)), slImport[j]) = 1 then begin
slImportValues.Text := StringReplace(Copy(slImport[j], Pos(',', slImport[j]) + 1, Length(slImport[j])), ',', #13, [rfReplaceall]);
Break;
end;
end;
if slImportValues.Count > 0 then begin
for j := 0 to slImportPaths.Count - 1 do begin
if (Pos('<FileLink>', slImportValues[j]) = 0) and not (slImportValues[j] = geev(e, slImportPaths[j])) then begin
AddMessage(' Value at path '+slImportPaths[j]+' changed from '+geev(e, slImportPaths[j])+' to '+slImportValues[j]);
seev(e, slImportPaths[j], slImportValues[j]);
end
else if (Pos('<FileLink>', slImportValues[j]) = 1) then begin
s2 := StringReplace(slImportValues[j], '<FileLink>', '', [rfReplaceAll]);
slArray.LoadFromFile(ProgramPath + 'Edit Scripts\'+s2);
AddMessage(' Values at path '+slImportPaths[j]+' changed to those found in '+s2);
slev(e, slImportPaths[j], slArray);
slArray.Clear;
end;
end;
end;
slImportValues.Clear;
slImportPaths.Clear;
end;
// ArrayImport function
if (slFunctions[i] = 'ArrayImport') then begin
s1 := CopyFromTo(slInput[i], 1, ItPos(',', slInput[i], 1) - 1);
s2 := CopyFromTo(slInput[i], ItPos(',', slInput[i], 1) + 1, ItPos(',', slInput[i], 2) - 1);
slArray.LoadFromFile(s2);
if Pos('Record', slArray[0]) = 1 then begin
AddMessage(' Can''t import a standard QuickDisplay exported file to an array element.');
continue;
end;
AddMessage(' Values at path '+s1+' changed to those found in '+s2);
slev(e, s1, slArray);
slArray.Clear;
end;
end;
end;
//=========================================================================
// Finalize: Free lists, print finalization messages.
function Finalize: integer;
begin
// free data allocated for lists
lstEntries.Free;
slFunctions.Free;
slInput.Free;
slImport.Free;
slImportPaths.Free;
if not badfile then begin
// finalization messages
AddMessage(#13#10);
AddMessage('----------------------------------------------------------');
AddMessage('Script is done!');
end
else
AddMessage(#13#10+'You can''t change elements in Bethesda master files!');
if not badfile and not processed then AddMessage(#13#10+'No functions executed.');
AddMessage(#13#10#13#10);
Result := 0;
end;
end.
|
unit UBlog;
interface
uses UClientSuper, UPageSuper, UBlogView, UTypeDef, UxlWinControl, UxlExtClasses;
type
TBlogClient = class (TListClientSuper, ILangObserver, IOptionObserver)
private
FBlog: TBlogView;
procedure f_GetBlogItem (var o_item: TBlogItem; value: TPageSuper; b_virtual: boolean = false);
procedure f_OnPopulateBlogItem (index: integer; var o_item: TBlogItem);
procedure f_OnContextMenu (index: integer);
procedure f_OnDeleteItemDemand (Sender: TObject);
protected
function Items (index: integer): TPageSuper; override;
procedure Load (value: TPageSuper); override;
procedure UnLoad (); override;
public
constructor Create (WndParent: TxlWinContainer);
destructor Destroy (); override;
function Control (): TxlControl; override;
procedure Save (); override;
procedure OnPageEvent (pct: TPageEvent; id, id2: integer); override;
function CheckCommand (opr: word): boolean; override;
procedure ExecuteCommand (opr: word); override;
procedure LanguageChanged ();
procedure OptionChanged ();
end;
implementation
uses UxlDateTimeUtils, UxlList, UPageStore, UPageFactory, UGlobalObj, UxlcommDlgs, UxlStrUtils, ULangManager, UOptionManager, Resource;
constructor TBlogClient.Create (WndParent: TxlWinContainer);
begin
FBlog := TBlogView.Create (WndParent);
with FBlog do
begin
Items.OnPopulateItem := f_OnPopulateBlogItem;
Items.OnSelect := f_OnSelectItem;
MultiSelect := true;
OnItemDblClick := f_OnItemDblClick;
OnItemReturn := f_OnItemDblClick;
OnDeleteItemDemand := f_OnDeleteItemDemand;
OnContextMenu := f_OnContextMenu;
end;
LangMan.AddObserver (self);
OptionMan.AddObserver(self);
end;
destructor TBlogClient.Destroy ();
begin
LangMan.RemoveObserver (self);
OptionMan.RemoveObserver(self);
FBlog.free;
inherited;
end;
function TBlogClient.Control (): TxlControl;
begin
result := FBlog;
end;
function TBlogClient.Items (index: integer): TPageSuper;
begin
result := PageStore[FBlog.Items[index].data];
end;
procedure TBlogClient.f_GetBlogItem (var o_item: TBlogItem; value: TPageSuper; b_virtual: boolean = false);
begin
o_item.Data := value.id;
o_item.IsVirtual := b_virtual;
if not b_virtual then
with o_item do
begin
Title := value.GetColText (sr_Title);
DateTime := value.GetColText (sr_DateTime);
Text := SingleLineToMultiLine(value.GetColText (sr_Abstract));
end;
end;
procedure TBlogClient.f_OnPopulateBlogItem (index: integer; var o_item: TBlogItem);
begin
f_GetBlogItem (o_item, PageStore[o_item.data], false);
end;
procedure TBlogClient.f_OnContextMenu (index: integer);
var i_demand: cardinal;
begin
if index >= 0 then
i_demand := ListContext
else
i_demand := ListNoSelContext;
EventMan.EventNotify (e_ContextMenuDemand, i_demand);
end;
procedure TBlogClient.f_OnDeleteItemDemand (Sender: TObject);
begin
CommandMan.ExecuteCommand (m_delete);
end;
procedure TBlogClient.Load (value: TPageSuper);
var i: integer;
o_list: TxlIntList;
o_item: TBlogItem;
begin
if value = nil then exit;
inherited Load (value);
FBlog.Items.Clear;
o_list := TxlIntList.Create;
value.GetChildList (o_list);
for i := o_list.Low to o_list.High do
begin
f_GetBlogItem (o_item, PageStore[o_list[i]], true);
o_item.Selected := false;
FBlog.Items.Add (o_item);
end;
o_list.Free;
FBlog.Update;
end;
procedure TBlogClient.UnLoad ();
begin
FBlog.Items.Clear;
end;
procedure TBlogClient.Save ();
begin
end;
procedure TBlogClient.LanguageChanged ();
begin
Refresh;
end;
procedure TBlogClient.OptionChanged ();
begin
FBlog.Font := OptionMan.Options.BlogFont;
FBlog.Color := OptionMan.Options.BlogColor;
FBlog.TitleFont := OptionMan.Options.BlogTitleFont;
FBlog.TitleColor := OptionMan.Options.BlogTitleColor;
FBlog.TitleSelFont := OptionMan.Options.BlogSelTitleFont;
FBlog.TitleSelColor := OptionMan.Options.BlogSelTitleColor;
FBlog.Update;
end;
procedure TBlogClient.OnPageEvent (pct: TPageEvent; id, id2: integer);
var o_item: TBlogItem;
i: integer;
begin
case pct of
pctFieldModified:
begin
i := FBlog.Items.FindByData (id);
if i >= 0 then
begin
o_item := FBlog.Items[i];
f_GetBlogItem (o_item, PageStore[id], false);
FBlog.Items[i] := o_item;
FBlog.Redraw;
end;
end;
pctAddChild:
if id = FPage.id then
begin
f_GetBlogItem (o_item, PageStore[id2], true);
i := FPage.Childs.FindChild (id2);
if i <= FBlog.Items.High then
FBlog.Items.Insert (i, o_item)
else
FBlog.Items.Add (o_item);
FBlog.Items.SelIndex := i;
Fblog.Redraw;
FBlog.SetFocus;
end;
pctRemoveChild:
if id = FPage.id then
begin
i := FBlog.Items.FindByData (id2);
if i >= 0 then
begin
FBlog.Items.Delete (i);
FBlog.Redraw;
end;
end;
pctListProperty:
Refresh;
else
inherited OnPageEvent (pct, id, id2);
end
end;
function TBlogClient.CheckCommand (opr: word): boolean;
begin
case opr of
m_clear, m_selectall:
result := false; //FBlog.Items.Count > 0;
m_undo, m_redo, m_cut, m_copy, m_paste:
result := false;
m_delete:
if FPage = nil then
result := false
else if FPage.IsVirtualContainer then
result := CommandMan.CheckCommand (m_removeitem)
else
result := CommandMan.CheckCommand (m_deleteitem);
m_wordwrap, m_find, m_subsequentfind, m_highlightmatch, m_texttools, m_insertlink, m_insertcliptext, m_inserttemplate:
result := false;
else
result := true;
end;
end;
procedure TBlogClient.ExecuteCommand (opr: word);
begin
case opr of
m_delete, m_removeitem: CommandMan.ExecuteCommand (m_deleteitem);
end;
end;
end.
|
Program Variables;
Var
nombre: String;
Begin
WriteLn('Cual es tu nombre?');
ReadLn(nombre);
WriteLn('Hola ' + nombre + '!');
End.
|
program RemoteSwitch;
{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
uses
SysUtils, IPConnection, BrickletIndustrialQuadRelay;
type
TRemoteSwitch = class
private
ipcon: TIPConnection;
iqr: TBrickletIndustrialQuadRelay;
public
procedure Execute;
end;
const
HOST = 'localhost';
PORT = 4223;
UID = 'ctG'; { Change to your UID }
VALUE_A_ON = (1 shl 0) or (1 shl 2); { Pin 0 and 2 high }
VALUE_A_OFF = (1 shl 0) or (1 shl 3); { Pin 0 and 3 high }
VALUE_B_ON = (1 shl 1) or (1 shl 2); { Pin 1 and 2 high }
VALUE_B_OFF = (1 shl 1) or (1 shl 3); { Pin 1 and 3 high }
var
rs: TRemoteSwitch;
procedure TRemoteSwitch.Execute;
begin
{ Create IP connection }
ipcon := TIPConnection.Create;
{ Create device object }
iqr := TBrickletIndustrialQuadRelay.Create(UID, ipcon);
{ Connect to brickd }
ipcon.Connect(HOST, PORT);
{ Don't use device before ipcon is connected }
{ Set pins to high for 1.5 seconds }
iqr.SetMonoflop(VALUE_A_ON, 15, 1500);
end;
begin
rs := TRemoteSwitch.Create;
rs.Execute;
rs.Destroy;
end.
|
unit UnitRegistry;
interface
uses
Classes, SysUtils,
PascalParser;
type
TUnitRegistry = class (TObject)
private
FUnits: TStrings;
FUsesList: TStrings;
FIncludes: TStrings;
function GetUnitParser(UnitName: String): TPascalParser;
function FindUnitSource(UnitName: String): String;
protected
class procedure Initialize;
class procedure Shutdown;
property Units: TStrings read FUnits;
public
class function Instance: TUnitRegistry;
constructor Create;
destructor Destroy; override;
function IsUnitRegistered(UnitName: String): Boolean;
function RegisterUnit(UnitName, FileName: String; IncludedInProject: Boolean = False): TPascalParser;
procedure AddUsedUnit(UnitName, UsedUnit: String);
procedure GetProjectRegisteredUnitsNames(Units: TStrings);
procedure GetAllRegisteredUnitsNames(Units: TStrings);
procedure GetUnitUsesList(UnitName: String; UsesList: TStrings);
procedure GetUnitIncludes(UnitName: String; Includes: TStrings);
property UnitParser[UnitName: String]: TPascalParser read GetUnitParser;
end;
implementation
uses
Options,
SourceTreeWalker,
IncludeParser, CommentRemovalVisitor, WhitespaceRemovalVisitor;
{ TUnitRegistry }
{ Private declarations }
function TUnitRegistry.GetUnitParser(UnitName: String): TPascalParser;
var
UnitIndex: Integer;
FileName: String;
begin
Result := nil;
UnitName := UpperCase(UnitName);
UnitIndex := Units.IndexOf(UnitName);
if UnitIndex <> -1 then
Result := Units.Objects[UnitIndex] as TPascalParser
else
begin
FileName := FindUnitSource(UnitName);
if FileName <> '' then
Result := RegisterUnit(UnitName, FileName);
end;
end;
function TUnitRegistry.FindUnitSource(UnitName: String): String;
var
I: Integer;
Path: String;
begin
Result := '';
with TOptions.Instance do
for I := 0 to SearchPath.Count - 1 do
begin
if SearchPath[I] <> '' then
Path := IncludeTrailingPathDelimiter(SearchPath[I])
else
Path := '';
if FileExists(Path + UnitName + '.pas') then
begin
Result := Path + UnitName + '.pas';
Break;
end;
end;
end;
{ Protected declarations }
var
_Instance: TUnitRegistry = nil;
class procedure TUnitRegistry.Initialize;
begin
_Instance := TUnitRegistry.Create;
end;
class procedure TUnitRegistry.Shutdown;
begin
Assert(Assigned(_Instance), 'Error: TUnitRegistry instance not initialized');
FreeAndNil(_Instance);
end;
{ Public declarations }
class function TUnitRegistry.Instance: TUnitRegistry;
begin
Assert(Assigned(_Instance), 'Error: TUnitRegistry instance not initialized');
Result := _Instance;
end;
constructor TUnitRegistry.Create;
begin
Assert(not Assigned(_Instance), 'Error: TUnitRegistry is a singleton and can only be accessed using TUnitRegistry.Instance method');
inherited Create;
FUnits := TStringList.Create;
FUsesList := TStringList.Create;
FIncludes := TStringList.Create;
end;
destructor TUnitRegistry.Destroy;
var
I: Integer;
begin
for I := 0 to Units.Count - 1 do
Units.Objects[I].Free;
FreeAndNil(FUnits);
for I := 0 to FUsesList.Count - 1 do
FUsesList.Objects[I].Free;
FreeAndNil(FUsesList);
for I := 0 to FIncludes.Count - 1 do
FIncludes.Objects[I].Free;
FreeAndNil(FIncludes);
inherited Destroy;
end;
function TUnitRegistry.IsUnitRegistered(UnitName: String): Boolean;
begin
Result := Units.IndexOf(UnitName) <> -1;
end;
function TUnitRegistry.RegisterUnit(UnitName, FileName: String; IncludedInProject: Boolean = False): TPascalParser;
var
Source: TStrings;
UsesList: TStrings;
Includes: TStrings;
IncludeParser: TIncludeParser;
begin
UnitName := UpperCase(UnitName);
Assert(Units.IndexOf(UnitName) = -1, Format('Error: unit "%s" already registered', [UnitName]));
Assert(FileExists(FileName), Format('Error: file "%s" not found', [FileName]));
Result := TPascalParser.Create;
Result.PreserveWhiteSpaces := True;
Result.PreserveComments := True;
Source := TStringList.Create;
try
Source.LoadFromFile(FileName);
IncludeParser := TIncludeParser.Create;
try
IncludeParser.ParseIncludes(Source);
Includes := TStringList.Create;
Includes.Assign(IncludeParser.Includes);
FIncludes.AddObject(UnitName, Includes);
finally
IncludeParser.Free;
end;
Result.Parse(Source);
UsesList := TStringList.Create;
FUsesList.AddObject(UnitName, UsesList);
TSourceTreeWalker.Create.Walk(Result.Root, TCommentRemovalVisitor.Create);
TSourceTreeWalker.Create.Walk(Result.Root, TWhitespaceRemovalVisitor.Create);
finally
Source.Free;
end;
Result.Tag := Integer(IncludedInProject);
Units.AddObject(UnitName, Result);
end;
procedure TUnitRegistry.AddUsedUnit(UnitName, UsedUnit: String);
var
Index: Integer;
begin
Index := FUsesList.IndexOf(UnitName);
Assert(Index <> -1, 'Error: unit not registered!');
TStrings(FUsesList.Objects[Index]).Add(UsedUnit);
end;
procedure TUnitRegistry.GetProjectRegisteredUnitsNames(Units: TStrings);
var
I: Integer;
begin
Units.Clear;
for I := 0 to Self.Units.Count - 1 do
if TPascalParser(Self.Units.Objects[I]).Tag <> 0 then
Units.Add(Self.Units[I]);
end;
procedure TUnitRegistry.GetAllRegisteredUnitsNames(Units: TStrings);
begin
Units.Assign(Self.Units);
end;
procedure TUnitRegistry.GetUnitUsesList(UnitName: String; UsesList: TStrings);
begin
UsesList.Clear;
if FUsesList.IndexOf(UnitName) <> -1 then
UsesList.Assign(TStrings(FUsesList.Objects[FUsesList.IndexOf(UnitName)]));
end;
procedure TUnitRegistry.GetUnitIncludes(UnitName: String; Includes: TStrings);
begin
Includes.Clear;
if FIncludes.IndexOf(UnitName) <> -1 then
Includes.Assign(TStrings(FIncludes.Objects[FIncludes.IndexOf(UnitName)]));
end;
initialization
TUnitRegistry.Initialize;
finalization
TUnitRegistry.Shutdown;
end. |
unit UPageStore;
interface
uses UTypeDef, UPageSuper, UxlList, UxlClasses, UxlStack;
type
TPageRecord = record
id: integer;
ownerid: integer;
pagetype: TPageType;
length: integer;
value: widestring;
Page: TPageSuper;
end;
PPageRecord = ^TPageRecord;
TPageStore = class // single instance
private
FArray: TxlObjList;
FTemprList: TxlStrList;
FIdxFile, FDataFile: widestring;
FIdRecycler: TxlIntQueue;
function f_GetPageByINdex (index: integer): TPageSuper;
function f_DoCreateNewPage (i_id, i_ownerid: integer; pt: TPageType): TPageSuper;
function f_GetOffset (n: integer): integer;
function f_GetOwnerId (p: PPageRecord): integer; // ownerid 可能在运行过程中改变,故不能简单用record.ownerid代替
function f_InRecycler (p: PPageRecord): boolean;
function GetPageById (id: integer): TPageSuper;
procedure LoadIndex ();
public
constructor Create (const s_workspace: widestring);
destructor Destroy (); override;
procedure SaveIndex ();
function NewPage (ownerid: integer; pt: TPageType): integer; // return id
procedure DeletePage (id: integer);
function RetrieveText (id: integer; i_maxchar: integer = -1): widestring;
function SaveText (id: integer; const value: widestring): boolean; // return saved or not
function TextLength (id: integer): integer;
property Pages [id: integer]: TPageSuper read GetPageById; default;
function PageValid (id: integer): boolean;
procedure GetPageTypeList (o_list: TxlIntList);
procedure GetPageList (pt: TPageType; o_list: TxlIntList); // 若 pt = ptNone,则获取所有 CanSearch 的页面
function GetPageCount (pt: TPageType): integer;
function GetFirstPageId (pt: TPageType; var id: integer): boolean;
function GetPagePath (p: TPageSuper): widestring;
function FindPageByPath (const s_path: widestring; var p: TPageSuper): boolean;
end;
function PageStore (): TPageStore;
function Root (): TPageSuper;
const RootId = -1; RootParent = -2; // 为了便于导入 3.1 版的数据,RootId 须为 -1,以便 GroupRoot 为 0
implementation
uses Windows, UxlFunctions, UxlStrUtils, UxlIniFile, UxlFile, UxlMath, Resource, UGlobalObj, ULangManager, UPageFactory,
UxlDateTimeUtils, UVersionManager, UxlListSuper, UOptionManager;
var FPageStore: TPageStore;
procedure f_SplitStr (const s_source: widestring; var i: integer; var s: widestring);
var n: integer;
begin
n := FirstPos (#9, s_source);
i := StrToIntDef (LeftStr(s_source, n - 1));
s := MidStr(s_source, n + 1);
end;
function PageStore (): TPageStore;
begin
if FPageStore = nil then
FPageStore := TPageStore.Create ('minipad2');
result := FPageStore;
end;
function Root (): TPageSuper;
begin
result := PageStore[RootId];
end;
//----------------
constructor TPageStore.Create (const s_workspace: widestring);
begin
FArray := TxlObjList.Create (1000);
FArray.SortType := stByIndexNoDup;
FTemprlist := TxlStrList.create (25);
FTemprList.Separator := #9;
FIdRecycler := TxlIntQueue.Create;
FIdRecycler.Separator := ',';
FIdxFile := DataDir + s_workspace + '.idx';
FDataFile := DataDir + s_workspace + '.dat';
// CheckVersion (FIdxFile, FDataFile);
LoadIndex;
end;
destructor TPageStore.Destroy ();
var i: integer;
p: PPageRecord;
begin
FTemprList.Free;
FIdRecycler.free;
for i := FArray.Low to FArray.High do
begin
p := PPageRecord (FArray[i]);
p.Page.Free;
dispose (p);
end;
FArray.free;
inherited;
end;
procedure TPageStore.LoadIndex ();
var o_file: TxlMemoryTextFile;
s_line, s_version, s, s2, s3: widestring;
pt: integer;
p: PPageRecord;
begin
o_file := TxlMemoryTextFile.create (FIdxFile, fmRead, enUTF16LE);
if not o_file.EOF then o_file.ReadLn (s_version);
if not o_file.EOF then
begin
o_file.ReadLn (s);
FIdRecycler.Text := s;
end;
while not o_file.EOF do
begin
o_file.ReadLn (s_line);
new (p);
f_SplitStr (s_line, p^.id, s);
f_SplitStr (s, p^.ownerid, s2);
f_SplitStr (s2, pt, s3);
p^.PageType := TPageType(pt);
f_SplitStr (s3, p^.length, p^.value);
p^.page := nil;
FArray.AddByIndex (p^.id, p);
end;
o_file.free;
end;
procedure TPageStore.SaveIndex ();
var o_list: TxlStrList;
i: integer;
s_line: widestring;
p: PPageRecord;
o_file: TxlTextFile;
begin
o_list := TxlStrList.Create (FArray.Count + 2);
o_list.Add (Version);
o_list.Add (FIdRecycler.Text);
for i := FArray.Low to FArray.High do
begin
p := PPageRecord (FArray[i]);
s_line := IntToStr(p^.id) + #9 + IntToStr(f_GetOwnerId(p)) + #9 + IntToStr(Ord(p^.PageType)) + #9 + IntToStr(p^.Length) + #9;
if p^.Page <> nil then
begin
p^.Page.Save (FTemprList);
s_line := s_line + FTemprList.Text;
end
else
s_line := s_line + p^.Value;
o_list.Add (s_line);
end;
o_file := TxlTextFile.Create (FIdxFile, fmWrite, enUTF16LE, OptionMan.Options.EncryptDataFile);
o_file.WriteText (o_list.Text);
o_file.free;
// o_list.SaveToFile (FIdxFile); // 使用 TxlStrList 一次性 WriteText,比早期版本的逐行 WriteLn 要安全一些,尽管速度稍慢。这是为了防止由于某些因素文件只写了一半就意外中断。
o_list.free;
end;
function TPageStore.PageValid (id: integer): boolean;
begin
result := FArray.IndexValid (id);
end;
function TPageStore.GetPageById (id: integer): TPageSuper;
var i: integer;
begin
i := FArray.FindByIndex (id);
if i >= 0 then
result := f_GetPageByIndex (i)
else if id = RootId then
result := f_DoCreateNewPage (id, RootParent, ptRoot)
else
result := nil;
end;
function TPageStore.f_GetPageByINdex (index: integer): TPageSuper;
var p: PPageRecord;
begin
p := PPageRecord (FArray[index]);
if not assigned (p^.Page) then
begin
p^.Page := PageFactory.NewPage (p^.PageType, p^.id, p^.OwnerId);
FTemprList.Text := p^.value;
p^.Page.Load (FTemprList);
p^.value := '';
end;
result := p^.Page;
end;
function TPageStore.f_GetOwnerId (p: PPageRecord): integer;
begin
if p^.page <> nil then
result := p^.page.ownerid
else
result := p^.ownerid;
end;
procedure TPageStore.GetPageTypeList (o_list: TxlIntList);
var i, pt: integer;
begin
o_list.Clear;
for i := FArray.Low to FArray.High do
begin
pt := Ord (PPageRecord(FArray[i]).PageType);
if not o_list.itemExists (pt) then
o_list.AddByIndex (pt, pt);
end;
o_list.SortByIndex;
end;
function TPageStore.f_InRecycler (p: PPageRecord): boolean;
begin
result := false;
while p^.id <> RootId do
begin
p := PPageRecord (FArray.ItemsByINdex[f_GetOwnerId(p)]);
if p^.PageType = ptRecycleBin then
begin
result := true;
exit;
end;
end;
end;
procedure TPageStore.GetPageList (pt: TPageType; o_list: TxlIntList);
var i: integer;
p: PPageRecord;
b: boolean;
begin
o_list.Clear;
for i := FArray.Low to FArray.High do
begin
p := PPageRecord (FArray[i]);
b := (p^.PageType = pt) or ((pt = ptNone) and PageFactory.GetClass (p^.PageType).CanSearch);
if b and (not f_InRecycler(p)) then
o_list.Add (p^.id);
end;
end;
function TPageStore.GetPageCount (pt: TPageType): integer;
var i: integer;
p: PPageRecord;
begin
result := 0;
for i := FArray.Low to FArray.High do
begin
p := PPageRecord (FArray[i]);
if (p^.PageType = pt) and (not f_InRecycler(p)) then
inc (result);
end;
end;
function TPageStore.GetFirstPageId (pt: TPageType; var id: integer): boolean;
var i: integer;
p: PPageRecord;
begin
result := false;
for i := FArray.Low to FArray.High do
begin
p := PPageRecord (FArray[i]);
if p^.PageType = pt then
begin
id := p^.id;
result := true;
exit;
end;
end;
end;
function TPageStore.GetPagePath (p: TPageSuper): widestring;
var o_list: TxlStrList;
begin
o_list := TxlStrList.Create;
o_list.Separator := '\';
while p <> Root do
begin
o_list.InsertFirst (p.name);
p := p.Owner;
end;
result := o_list.Text;
o_list.free;
end;
function TPageStore.FindPageByPath (const s_path: widestring; var p: TPageSuper): boolean;
var i: integer;
begin
result := false;
for i := FArray.Low to FArray.High do
begin
p := f_GetPageByIndex (i);
if IsSameStr (GetPagePath(p), s_path) then
begin
result := true;
break;
end;
end;
end;
function TPageStore.NewPage (ownerid: integer; pt: TPageType): integer; // return id
begin
if PageFactory.GetClass (pt).SingleInstance and GetFirstPageId (pt, result) then exit;
if not FIdRecycler.Pop (result) then
result := FArray.GetNewIndex;
f_DoCreateNewPage (result, ownerid, pt);
end;
function TPageStore.f_DoCreateNewPage (i_id, i_ownerid: integer; pt: TPageType): TPageSuper;
var p: PPageRecord;
begin
new (p);
with p^ do
begin
id := i_id;
OwnerId := i_ownerid;
PageType := pt;
length := 0;
page := PageFactory.NewPage (pt, i_id, i_ownerid);
page.Initialize ();
end;
FArray.AddByIndex (i_id, p);
result := p^.page;
end;
procedure TPageStore.DeletePage (id: integer);
var i: integer;
p: PPageRecord;
begin
i := FArray.FindByIndex (id);
if i >= 0 then
begin
p := PPageRecord (FArray[i]);
SaveText (p^.id, '');
FIdRecycler.Push (p^.id);
FArray.Delete (i);
p^.page.free;
dispose (p);
end;
end;
//------------------
function TPageStore.f_GetOffset (n: integer): integer;
var i: integer;
begin
result := 0;
for i := 0 to n - 1 do
inc (result, PPageRecord(FArray[i])^.length);
end;
function TPageStore.RetrieveText (id: integer; i_maxchar: integer = -1): widestring;
var i_offset, n, i_len: integer;
o_file: TxlTextFile;
begin
result := '';
if (i_maxchar = 0) then exit;
n := FArray.FindByIndex (id);
if (n < 0) then exit;
i_len := PPageRecord(FArray[n])^.Length;
if i_len = 0 then exit;
i_offset := f_GetOffset (n);
try
o_file := TxlTextFile.create(FDataFile, fmRead, enUTF16LE);
if o_file.TextCount >= i_offset then
begin
o_file.CharIndex := i_Offset;
if InRange (i_maxchar, 1, i_len - 1) then
begin
o_file.ReadText (result, i_maxchar);
result := result + ' ...';
end
else
o_file.ReadText (result, i_len);
end;
finally
o_file.free;
end;
end;
function TPageStore.SaveText (id: integer; const value: widestring): boolean;
var o_file: TxlTextFile;
s1, s2: widestring;
i_offset, i_count, len1, pos2, len2, n: integer;
p: PPageRecord;
begin
result := false;
n := FArray.FindByIndex (id);
if n < 0 then exit;
p := PPageRecord (FArray[n]);
if (p^.Length = length(value)) and (RetrieveText (id) = value) then exit;
i_offset := f_GetOffset (n);
o_file := TxlTextFile.create (FDataFile, fmRead, enUTF16LE);
i_count := o_file.TextCount;
len1 := Min (i_offset, i_count);
pos2 := Min(i_offset + p^.Length, i_count);
len2 := i_count - pos2;
with o_file do
begin
readText (s1, len1);
CharIndex := pos2;
readText (s2, len2);
reset (fmWrite, enUTF16LE, OptionMan.Options.EncryptDataFile);
WriteText (s1);
writeText (value);
writeText (s2);
end;
o_file.free;
p^.length := length(value);
result := true;
SaveIndex;
end;
function TPageStore.TextLength (id: integer): integer;
var n: integer;
begin
result := 0;
n := FArray.FindByIndex (id);
if n >= 0 then
result := PPageRecord(FArray[n])^.Length;
end;
//------------------
initialization
finalization
FPageStore.free;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit fMasterDetails;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ComCtrls, ExtCtrls, StdCtrls, Buttons,
fMainLayers,
FireDAC.DatS, FireDAC.Stan.Intf,
FireDAC.Phys.Intf;
type
TfrmMasterDetails = class(TfrmMainLayers)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cbDBClick(Sender: TObject);
private
{ Private declarations }
FDatSManager: TFDDatSManager;
FTabCat: TFDDatSTable;
FTabProd: TFDDatSTable;
public
{ Public declarations }
end;
var
frmMasterDetails: TfrmMasterDetails;
implementation
uses
uDatSUtils;
{$R *.dfm}
procedure TfrmMasterDetails.FormCreate(Sender: TObject);
var
oCatPK, oProdPK: TFDDatSUniqueConstraint;
oProdFK: TFDDatSForeignKeyConstraint;
begin
inherited FormCreate(Sender);
// 1) create DatSManager object
FDatSManager := TFDDatSManager.Create;
// 2) create Categories table
FTabCat := FDatSManager.Tables.Add('Categories');
with FTabCat.Columns do begin
with Add('CategoryID', dtInt32) do begin
SourceID := 1;
AutoIncrement := True;
AllowDBNull := False;
end;
with Add('CategoryName', dtAnsiString) do begin
SourceID := 2;
Size := 15;
AllowDBNull := False;
end;
Add('Description', dtMemo).SourceID := 3;
Add('Picture', dtBlob).SourceID := 4;
end;
// 3) define Categories table primary key
oCatPK := FTabCat.Constraints.AddUK('CAT_PK', 'CategoryID', True);
// 4) create Products table
FTabProd := FDatSManager.Tables.Add('Products');
with FTabProd.Columns do begin
with Add('ProductID', dtInt32) do begin
SourceID := 1;
AutoIncrement := True;
AllowDBNull := False;
end;
with Add('ProductName', dtAnsiString) do begin
SourceID := 2;
Size := 40;
AllowDBNull := False;
end;
with Add('SupplierID', dtInt32) do begin
SourceID := 3;
AllowDBNull := False;
end;
Add('CategoryID', dtInt32).SourceID := 4;
with Add('QuantityPerUnit', dtAnsiString) do begin
SourceID := 5;
Size := 20;
end;
Add('UnitPrice', dtCurrency).SourceID := 6;
Add('UnitsInStock', dtInt16).SourceID := 7;
Add('UnitsOnOrder', dtInt16).SourceID := 8;
Add('ReorderLevel', dtInt16).SourceID := 9;
Add('Discontinued', dtBoolean).SourceID := 10;
end;
// 5) define Products table primary key
oProdPK := FTabProd.Constraints.AddUK('PROD_PK', 'ProductID', True);
// 6) define Products table foreign key
oProdFK := FTabProd.Constraints.AddFK('PROD_FK', 'Categories', 'CategoryID', 'CategoryID');
// 7) define relations based on FK and PK
FDatSManager.Relations.Add('CAT_PROD_REL', oCatPK, oProdFK);
end;
procedure TfrmMasterDetails.FormDestroy(Sender: TObject);
begin
FDatSManager.Free;
inherited FormDestroy(Sender);
end;
procedure TfrmMasterDetails.cbDBClick(Sender: TObject);
var
j: Integer;
myRow: TFDDatSRow;
childView: TFDDatSView;
procedure FetchTable(ATable: TFDDatSTable; const ATabName: String);
var
oCmdIntf: IFDPhysCommand;
begin
ATable.Clear;
FConnIntf.CreateCommand(oCmdIntf);
oCmdIntf.Prepare('select * from ' + ATabName);
oCmdIntf.Open;
oCmdIntf.Fetch(ATable, True);
end;
begin
inherited cbDBClick(Sender);
// 1) Fetch tables
FetchTable(FTabCat, '{id Categories}');
FetchTable(FTabProd, '{id Products}');
// 2) For each master Categories row
Console.Clear;
for j := 0 to FTabCat.Rows.Count - 1 do begin
myRow := FTabCat.Rows[j];
PrintRow(myRow, Console.Lines, '------ Parent Row' );
// 3) Get child rows view, specifing child table
childView := myRow.GetChildRows(FTabProd);
try
PrintRows(childView, Console.Lines, '------ Child Rows' );
finally
childView.Free;
end
end
end;
end.
|
unit UMainDataModule;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
Data.DB, FireDAC.Comp.Client, Data.Win.ADODB;
type
TMainDataModule = class(TDataModule)
MainADOConnection: TADOConnection;
ADODataSetDeleteGoods: TADODataSet;
DataSourceDeleteGoods: TDataSource;
ADOTableGoods: TADOTable;
DataSourceInsUpDelGoods: TDataSource;
ADOTableTypeGoods: TADOTable;
DataSourceTypeGoods: TDataSource;
DataSourcePoem: TDataSource;
ADOTableServices: TADOTable;
DataSourceServices: TDataSource;
ADOTableTypePoem: TADOTable;
DataSourceTypePoem: TDataSource;
ADOTablePictures: TADOTable;
DataSourcePictures: TDataSource;
ADOTablePicturesM: TADOTable;
DataSourcePicturesM: TDataSource;
ADOTableOrders: TADOTable;
DataSourceInsertOrders: TDataSource;
ADOTableGoodsOrders: TADOTable;
DataSourceGoodsOrders: TDataSource;
ADOTableArtWorks: TADOTable;
DataSourceArtWorks: TDataSource;
ADODataSetArtWorkId: TADODataSet;
DataSourceArtWorkId: TDataSource;
ADODataSetArtWorkIdID_AW: TIntegerField;
ADOQuerySetPrice: TADOQuery;
ADOQuerySetPricePrice_Sall: TFloatField;
ADOQuerySetPriceCOLUMN1: TIntegerField;
ADOTableGArch: TADOTable;
ADOTableGStand: TADOTable;
ADOTableGFlorist: TADOTable;
ADOTableGVase: TADOTable;
ADOTableGLamp: TADOTable;
ADOTableGFurniture: TADOTable;
ADOTableGBottom: TADOTable;
DataSourceGArch: TDataSource;
DataSourceGStand: TDataSource;
DataSourceGFlorist: TDataSource;
DataSourceGVase: TDataSource;
DataSourceGLamp: TDataSource;
DataSourceGFurniture: TDataSource;
DataSourceGBottom: TDataSource;
ADODataSetPrint: TADODataSet;
DataSourceSetPrint: TDataSource;
ADODataSetPrintID_Orders: TAutoIncField;
ADODataSetPrintFName: TStringField;
ADODataSetPrintMName: TStringField;
ADODataSetPrintLName: TStringField;
ADODataSetPrintPhone: TStringField;
ADODataSetPrintCAdress: TStringField;
ADODataSetPrintNotes: TStringField;
ADODataSetPrintOrder_Date: TDateTimeField;
ADODataSetPrintInstall_Date: TDateTimeField;
ADODataSetPrintTitle: TStringField;
ADODataSetPrintTitle_1: TStringField;
ADODataSetPrintTitle_2: TStringField;
ADODataSetPrintTitle_3: TStringField;
ADODataSetPrintTitle_4: TStringField;
ADODataSetPrintTitle_5: TStringField;
ADODataSetPrintTitle_6: TStringField;
ADODataSetPrintArtWorkID: TIntegerField;
ADODataSetPrintInitials: TStringField;
ADODataSetPrintDate_Birthd: TStringField;
ADODataSetPrintDate_Dead: TStringField;
ADODataSetPrintPhoto: TStringField;
ADODataSetPrintPict_Front: TStringField;
ADODataSetPrintPict_Back: TStringField;
ADODataSetPrintPoem_Front: TStringField;
ADODataSetPrintPoem_Back: TStringField;
ADODataSetPrintOther_Notes: TStringField;
ADODataSetPrintServiceList: TStringField;
ADODataSetPrintServicePrice: TFloatField;
ADODataSetPrintDeposit: TFloatField;
ADODataSetPrintDiscount: TIntegerField;
ADODataSetPrintPrice: TFloatField;
ADODataSetOrdersSelect: TADODataSet;
DataSourceOrderSelect: TDataSource;
ADODataSetOrdersSelectID_Orders: TAutoIncField;
ADODataSetOrdersSelectFName: TStringField;
ADODataSetOrdersSelectMName: TStringField;
ADODataSetOrdersSelectLName: TStringField;
ADODataSetOrdersSelectPhone: TStringField;
ADODataSetOrdersSelectCAdress: TStringField;
ADODataSetOrdersSelectNotes: TStringField;
ADODataSetOrdersSelectOrder_Date: TDateTimeField;
ADODataSetOrdersSelectInstall_Date: TDateTimeField;
ADODataSetOrdersSelectTitle: TStringField;
ADODataSetOrdersSelectTitle_1: TStringField;
ADODataSetOrdersSelectTitle_2: TStringField;
ADODataSetOrdersSelectTitle_3: TStringField;
ADODataSetOrdersSelectTitle_4: TStringField;
ADODataSetOrdersSelectTitle_5: TStringField;
ADODataSetOrdersSelectTitle_6: TStringField;
ADODataSetOrdersSelectArtWorkID: TIntegerField;
ADODataSetOrdersSelectInitials: TStringField;
ADODataSetOrdersSelectDate_Birthd: TStringField;
ADODataSetOrdersSelectDate_Dead: TStringField;
ADODataSetOrdersSelectPhoto: TStringField;
ADODataSetOrdersSelectPict_Front: TStringField;
ADODataSetOrdersSelectPict_Back: TStringField;
ADODataSetOrdersSelectPoem_Front: TStringField;
ADODataSetOrdersSelectPoem_Back: TStringField;
ADODataSetOrdersSelectOther_Notes: TStringField;
ADODataSetOrdersSelectServiceList: TStringField;
ADODataSetOrdersSelectServicePrice: TFloatField;
ADODataSetOrdersSelectDeposit: TFloatField;
ADODataSetOrdersSelectDiscount: TIntegerField;
ADODataSetOrdersSelectPrice: TFloatField;
ADOCommandDeleteGoods: TADOCommand;
ADOTablePicturesD: TADOTable;
DataSourcePicturesD: TDataSource;
ADODataSetPoem: TADODataSet;
ADODataSetPoemID_Poem: TAutoIncField;
ADODataSetPoemTypePoem: TStringField;
ADODataSetPoemPoem: TStringField;
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainDataModule: TMainDataModule;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
end.
|
{
Purpose: To quickly set the ESL flag on selected files that support it.
Must be used with -PseudoESL.
Usage: Start xEdit with the -PseudoESL command line argument. Select the plugins
you wish to check and flag for ESL. Click OK. Once loaded select the
files and apply this script. It will skip any files xEdit deems unsafe
to flag as ESL. Once done close xEdit and save plugins.
Games: Fallout 4 / Skyrim Special Edition
Author: Jonathan Ostrus
}
unit userscript;
// Set ExtraSpammy true if you want to be told about skipped files
const ExtraSpammy = false;
var SkipProcess : boolean;
function Initialize: integer;
begin
Result := 0;
// check for PseudoESL mode
if not wbIsPseudoESLMode then begin
AddMessage('xEdit must be started with the -PseudoESL argument in order to use this script.');
SkipProcess := true;
Result := 1;
exit;
end;
// process only file elements
try
ScriptProcessElements := [etFile];
except on Exception do
SkipProcess := true;
Result := 2;
end;
end;
// called for every record selected in xEdit
function Process(f: IInterface): integer;
var fs : string;
begin
Result := 0;
// Safety check. This should never happen.
// But quick ditch if there was a problem.
if SkipProcess then begin
Result := 1001;
exit;
end;
if (ElementType(f) = etMainRecord) then
exit;
fs := GetFileName(f);
if not CanBeESL(f) then begin
if ExtraSpammy then
AddMessage('warn - ' + fs + ' cannot be flagged as ESL.');
exit;
end;
if IsEditable(f) then begin
SetIsESL(f, true);
AddMessage(fs + ' is now processed.');
end
else
if ExtraSpammy then
AddMessage(fs + ' can be flagged ESL but is currently not editable.');
end;
end.
|
unit CRCoreTransferContentsViewFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, CommonFrame, ComCtrls, CoreTransfer, ToolWin, BaseObjects, StdCtrls,
Ex_Grid, Registrator, ImgList, ActnList, Menus;
type
TCoreTransferColumn = (ctpTransferType, ctpTransferringObject, ctpSource, ctpDest, ctpBoxCount, ctpBoxNumber);
TCoreTransferColumns = set of TCoreTransferColumn;
TfrmCoreTransferContentsView = class(TfrmCommonFrame)
tlbr: TToolBar;
gbxTransferTasks: TGroupBox;
grdCoreTransfers: TGridView;
actnlstCoreTransfers: TActionList;
actnAdd: TAction;
actnDelete: TAction;
actnSave: TAction;
imglstCoreTransfer: TImageList;
actnRefresh: TAction;
btnRemove: TToolButton;
btnSave: TToolButton;
btnREfresh: TToolButton;
btnAddMenu: TToolButton;
pmAdd: TPopupMenu;
N1: TMenuItem;
actnAddAllWellsString: TAction;
N2: TMenuItem;
pmDelete: TPopupMenu;
N3: TMenuItem;
actnDeleteByState: TAction;
actnDeleteByTransferType: TAction;
N4: TMenuItem;
N5: TMenuItem;
actnChangeTransferTypeForAll: TAction;
actnChangeSourcePlacement: TAction;
actnChangeTargetPlacement: TAction;
N6: TMenuItem;
N7: TMenuItem;
N8: TMenuItem;
N9: TMenuItem;
procedure grdCoreTransfersGetCellText(Sender: TObject; Cell: TGridCell; var Value: string);
procedure grdCoreTransfersEditCloseUp(Sender: TObject; Cell: TGridCell; ItemIndex: Integer; var Accept: Boolean);
procedure grdCoreTransfersSetEditText(Sender: TObject; Cell: TGridCell; var Value: string);
procedure grdCoreTransfersEditAcceptKey(Sender: TObject; Cell: TGridCell; Key: Char; var Accept: Boolean);
procedure actnAddExecute(Sender: TObject);
procedure actnAddUpdate(Sender: TObject);
procedure grdCoreTransfersCellAcceptCursor(Sender: TObject; Cell: TGridCell; var Accept: Boolean);
procedure grdCoreTransfersChange(Sender: TObject; Cell: TGridCell; Selected: Boolean);
procedure actnDeleteExecute(Sender: TObject);
procedure actnDeleteUpdate(Sender: TObject);
procedure actnSaveExecute(Sender: TObject);
procedure actnSaveUpdate(Sender: TObject);
procedure actnRefreshExecute(Sender: TObject);
procedure actnRefreshUpdate(Sender: TObject);
procedure actnAddAllWellsStringExecute(Sender: TObject);
procedure actnAddAllWellsStringUpdate(Sender: TObject);
procedure actnDeleteByStateExecute(Sender: TObject);
procedure actnDeleteByStateUpdate(Sender: TObject);
procedure actnDeleteByTransferTypeExecute(Sender: TObject);
procedure actnDeleteByTransferTypeUpdate(Sender: TObject);
procedure actnChangeTransferTypeForAllExecute(Sender: TObject);
procedure actnChangeTransferTypeForAllUpdate(Sender: TObject);
procedure actnChangeSourcePlacementExecute(Sender: TObject);
procedure actnChangeTargetPlacementExecute(Sender: TObject);
procedure actnChangeSourcePlacementUpdate(Sender: TObject);
procedure actnChangeTargetPlacementUpdate(Sender: TObject);
procedure grdCoreTransfersDrawCell(Sender: TObject; Cell: TGridCell;
var Rect: TRect; var DefaultDrawing: Boolean);
private
FCoreTransferColumns: TCoreTransferColumns;
FCoreTransferTypesVisibility: TCoreTransferTypesPresence;
FCoreTransferTasks: TCoreTransferTasks;
FTransferringObjects: TRegisteredIDObjects;
FCurrentTask: TCoreTransferTask;
FCoreTransferTaskWells: TRegisteredIDObjects;
FInternalCheckResult: Boolean;
procedure RefreshCoreTransferTasks;
function GetCoreTransfer: TCoreTransfer;
procedure SetCoreTransferColumns(const Value: TCoreTransferColumns);
function GetCanEdit: boolean;
function GetShowToolBar: boolean;
procedure SetCanEdit(const Value: boolean);
procedure SetShowToolbar(const Value: boolean);
function GetCoreTransferTasks: TCoreTransferTasks;
function GetTransferringObjects: TRegisteredIDObjects;
function GetCurrentTask: TCoreTransferTask;
procedure SetCurrentTask(const Value: TCoreTransferTask);
function GetCoreTransferTasksWells: TRegisteredIDObjects;
protected
procedure FillControls(ABaseObject: TIDObject); override;
procedure ClearControls; override;
procedure RegisterInspector; override;
procedure FillParentControls; override;
function InternalCheck: boolean; override;
public
{ Public declarations }
property CoreTransfer: TCoreTransfer read GetCoreTransfer;
property CoreTransferColumns: TCoreTransferColumns read FCoreTransferColumns write SetCoreTransferColumns;
property CoreTransferTypesVisibility: TCoreTransferTypesPresence read FCoreTransferTypesVisibility write FCoreTransferTypesVisibility;
property CoreTransferTasksWells: TRegisteredIDObjects read GetCoreTransferTasksWells;
property CoreTransferTasks: TCoreTransferTasks read GetCoreTransferTasks;
property TransferringObjects: TRegisteredIDObjects read GetTransferringObjects;
property CurrentTask: TCoreTransferTask read GetCurrentTask write SetCurrentTask;
property ShowToolbar: boolean read GetShowToolBar write SetShowToolbar;
property CanEdit: boolean read GetCanEdit write SetCanEdit;
procedure ClearCacheObjects;
constructor Create(AOwner: TComponent); override;
procedure Save(AObject: TIDObject = nil); override;
destructor Destroy; override;
end;
var
frmCoreTransferContentsView: TfrmCoreTransferContentsView;
implementation
uses
DateUtils, Facade, SlottingPlacement, StringUtils, SlottingWell,
CRSelectTransferStateForm, CRSelectPlacementForm, CommonProgressForm,
Well;
{$R *.dfm}
{ TfrmCoreTransferContentsView }
procedure TfrmCoreTransferContentsView.ClearControls;
begin
inherited;
ClearCacheObjects;
grdCoreTransfers.Rows.Count := 0;
end;
constructor TfrmCoreTransferContentsView.Create(AOwner: TComponent);
begin
inherited;
CoreTransferTypesVisibility := [cttvTransfer, cttvRepackaging, cttvDisposition];
end;
destructor TfrmCoreTransferContentsView.Destroy;
begin
ClearCacheObjects;
inherited;
end;
procedure TfrmCoreTransferContentsView.FillControls(ABaseObject: TIDObject);
begin
inherited;
ClearCacheObjects;
RefreshCoreTransferTasks;
CoreTransferColumns := [ctpTransferType, ctpTransferringObject, ctpSource, ctpDest, ctpBoxCount, ctpBoxNumber];
grdCoreTransfers.Rows.Count := CoreTransferTasks.Count;
grdCoreTransfers.Refresh;
end;
procedure TfrmCoreTransferContentsView.FillParentControls;
begin
inherited;
ClearCacheObjects;
end;
function TfrmCoreTransferContentsView.GetCoreTransfer: TCoreTransfer;
begin
Result := EditingObject as TCoreTransfer;
end;
procedure TfrmCoreTransferContentsView.RegisterInspector;
begin
inherited;
end;
procedure TfrmCoreTransferContentsView.Save(AObject: TIDObject);
var
i: integer;
ct: TCoreTransferTask;
begin
inherited;
for i := 0 to CoreTransferTasks.DeletedObjects.Count - 1 do
begin
ct := CoreTransfer.CoreTransferTasks.ItemsByID[CoreTransferTasks.DeletedObjects.Items[i].ID] as TCoreTransferTask;
if Assigned(ct) then
CoreTransfer.CoreTransferTasks.MarkDeleted(ct);
end;
for i := 0 to CoreTransferTasks.Count - 1 do
begin
ct := CoreTransfer.CoreTransferTasks.ItemsByID[CoreTransferTasks.Items[i].ID] as TCoreTransferTask;
if Assigned(ct) then
ct.Assign(CoreTransferTasks.Items[i]);
end;
for i := 0 to CoreTransferTasks.Count - 1 do
begin
ct := nil;
if CoreTransferTasks.Items[i].ID > 0 then
ct := CoreTransfer.CoreTransferTasks.ItemsByID[CoreTransferTasks.Items[i].ID] as TCoreTransferTask;
if not Assigned(ct) then
CoreTransfer.CoreTransferTasks.Add(CoreTransferTasks.Items[i], true, False);
end;
CoreTransfer.CoreTransferTasks.Update(nil);
FreeAndNil(FCoreTransferTasks);
RefreshCoreTransferTasks;
grdCoreTransfers.Refresh;
end;
procedure TfrmCoreTransferContentsView.grdCoreTransfersGetCellText(Sender: TObject; Cell: TGridCell; var Value: string);
begin
inherited;
if CoreTransferTasks.Count > Cell.Row then
with CoreTransferTasks.Items[Cell.Row] do
case Cell.Col of
// тип перемещения
0:
if Assigned(TransferType) then
Value := TransferType.List();
// скважина или св. разрез
1:
if Assigned(TransferringObject) then
Value := TransferringObject.List();
// откуда
2:
if Assigned(SourcePlacement) then
Value := SourcePlacement.List();
// куда
3:
if Assigned(TargetPlacement) then
Value := TargetPlacement.List();
// кол-во ящиков
4:
Value := IntToStr(BoxCount);
// номера ящиков
5:
Value := BoxNumbers;
end;
end;
procedure TfrmCoreTransferContentsView.SetCoreTransferColumns(const Value: TCoreTransferColumns);
begin
//if FCoreTransferColumns <> Value then
begin
FCoreTransferColumns := Value;
with grdCoreTransfers do
begin
Columns[0].Visible := ctpTransferType in FCoreTransferColumns;
TMainFacade.GetInstance.AllCoreTransferTypes.MakeList(Columns[0].PickList, True, True);
Columns[1].Visible := ctpTransferringObject in FCoreTransferColumns;
TransferringObjects.MakeList(Columns[1].PickList, True, True);
Columns[2].Visible := ctpSource in FCoreTransferColumns;
TMainFacade.GetInstance.CoreLibrary.OldMainPlacementPlainList.MakeList(Columns[2].PickList, True, True);
Columns[3].Visible := ctpDest in FCoreTransferColumns;
TMainFacade.GetInstance.CoreLibrary.NewPlacementPlainList.MakeList(Columns[3].PickList, True, True);
Columns[4].Visible := ctpBoxCount in FCoreTransferColumns;
Columns[5].Visible := ctpBoxNumber in FCoreTransferColumns;
end;
end;
end;
function TfrmCoreTransferContentsView.GetCanEdit: boolean;
begin
Result := grdCoreTransfers.AllowEdit;
end;
function TfrmCoreTransferContentsView.GetShowToolBar: boolean;
begin
Result := tlbr.Visible;
end;
procedure TfrmCoreTransferContentsView.SetCanEdit(const Value: boolean);
begin
grdCoreTransfers.AllowEdit := Value;
if not CanEdit then
ShowToolbar := false;
end;
procedure TfrmCoreTransferContentsView.SetShowToolbar(const Value: boolean);
begin
tlbr.Visible := Value;
end;
function TfrmCoreTransferContentsView.GetCoreTransferTasks: TCoreTransferTasks;
begin
if not Assigned(FCoreTransferTasks) then
begin
FCoreTransferTasks := TCoreTransferTasks.Create;
FCoreTransferTasks.OwnsObjects := true;
end;
Result := FCoreTransferTasks;
end;
procedure TfrmCoreTransferContentsView.grdCoreTransfersEditCloseUp(Sender: TObject; Cell: TGridCell; ItemIndex: Integer; var Accept: Boolean);
begin
inherited;
if ItemIndex > -1 then
case Cell.Col of
0:
CoreTransferTasks.Items[Cell.Row].TransferType := TMainFacade.GetInstance.AllCoreTransferTypes.Items[ItemIndex];
1:
begin
CoreTransferTasks.Items[Cell.Row].TransferringObject := TransferringObjects.Items[ItemIndex];
if TransferringObjects.Items[ItemIndex] is TSlottingWell then
begin
CoreTransferTasks.Items[Cell.Row].SourcePlacement := CoreTransferTasks.Items[Cell.Row].Well.SlottingPlacement.StatePartPlacement;
CoreTransferTasks.Items[Cell.Row].BoxCount := CoreTransferTasks.Items[Cell.Row].Well.Boxes.Count;
end;
end;
2:
CoreTransferTasks.Items[Cell.Row].SourcePlacement := TMainFacade.GetInstance.CoreLibrary.OldMainPlacementPlainList.Items[ItemIndex];
3:
CoreTransferTasks.Items[Cell.Row].TargetPlacement := TMainFacade.GetInstance.CoreLibrary.NewPlacementPlainList.Items[ItemIndex];
end;
grdCoreTransfers.Refresh;
InternalCheck;
end;
function TfrmCoreTransferContentsView.GetTransferringObjects: TRegisteredIDObjects;
begin
if not Assigned(FTransferringObjects) then
begin
FTransferringObjects := TRegisteredIDObjects.Create;
FTransferringObjects.OwnsObjects := False;
FTransferringObjects.AddObjects(CoreTransferTasksWells, false, false);
FTransferringObjects.AddObjects(TMainFacade.GetInstance.GeneralizedSections, false, false);
end;
Result := FTransferringObjects;
end;
procedure TfrmCoreTransferContentsView.grdCoreTransfersSetEditText(Sender: TObject; Cell: TGridCell; var Value: string);
begin
inherited;
case Cell.Col of
4:
CoreTransferTasks.Items[Cell.Row].BoxCount := StrToInt(Value);
5:
CoreTransferTasks.Items[Cell.Row].BoxNumbers := Value;
end;
InternalCheck;
grdCoreTransfers.Refresh;
end;
procedure TfrmCoreTransferContentsView.grdCoreTransfersEditAcceptKey(Sender: TObject; Cell: TGridCell; Key: Char; var Accept: Boolean);
begin
inherited;
Accept := true;
case Cell.Col of
4:
Accept := Key in NumberSet;
5:
Accept := Key in NumberSet + [',', '-']
end;
end;
procedure TfrmCoreTransferContentsView.actnAddExecute(Sender: TObject);
begin
inherited;
CurrentTask := CoreTransferTasks.Add as TCoreTransferTask;
InternalCheck;
grdCoreTransfers.Rows.Count := CoreTransferTasks.Count;
grdCoreTransfers.Refresh;
end;
function TfrmCoreTransferContentsView.GetCurrentTask: TCoreTransferTask;
begin
Result := FCurrentTask;
end;
procedure TfrmCoreTransferContentsView.SetCurrentTask(const Value: TCoreTransferTask);
begin
if FCurrentTask <> Value then
begin
FCurrentTask := Value;
if Assigned(FCurrentTask) then
grdCoreTransfers.Row := CoreTransferTasks.IndexOf(FCurrentTask);
end;
end;
procedure TfrmCoreTransferContentsView.actnAddUpdate(Sender: TObject);
begin
inherited;
actnAdd.Enabled := Assigned(CoreTransfer) and (not Assigned(CurrentTask) or (Assigned(CurrentTask) and CurrentTask.IsDataCompleted));
end;
procedure TfrmCoreTransferContentsView.grdCoreTransfersCellAcceptCursor(Sender: TObject; Cell: TGridCell; var Accept: Boolean);
begin
inherited;
Accept := true;
end;
procedure TfrmCoreTransferContentsView.grdCoreTransfersChange(Sender: TObject; Cell: TGridCell; Selected: Boolean);
begin
inherited;
if CoreTransferTasks.Count > Cell.Row then
CurrentTask := CoreTransferTasks.Items[Cell.Row]
else
CurrentTask := nil;
end;
procedure TfrmCoreTransferContentsView.actnDeleteExecute(Sender: TObject);
var
iRow: integer;
begin
inherited;
iRow := grdCoreTransfers.Row;
if CurrentTask.ID > 0 then
CoreTransferTasks.MarkDeleted(CurrentTask)
else
CoreTransferTasks.Remove(CurrentTask);
grdCoreTransfers.Rows.Count := CoreTransferTasks.Count;
grdCoreTransfers.Refresh;
if iRow < CoreTransferTasks.Count then
CurrentTask := CoreTransferTasks.Items[iRow]
else if CoreTransferTasks.Count > 0 then
begin
iRow := 0;
if CoreTransferTasks.Count > 0 then
CurrentTask := CoreTransferTasks.Items[iRow];
end;
InternalCheck;
end;
procedure TfrmCoreTransferContentsView.actnDeleteUpdate(Sender: TObject);
begin
inherited;
actnDelete.Enabled := Assigned(CurrentTask);
end;
procedure TfrmCoreTransferContentsView.actnSaveExecute(Sender: TObject);
begin
inherited;
Save;
end;
procedure TfrmCoreTransferContentsView.actnSaveUpdate(Sender: TObject);
begin
inherited;
actnSave.Enabled := Assigned(CoreTransfer) and FInternalCheckResult;
end;
procedure TfrmCoreTransferContentsView.actnRefreshExecute(Sender: TObject);
begin
inherited;
FillControls(EditingObject); // мзменения потеряются
end;
procedure TfrmCoreTransferContentsView.actnRefreshUpdate(Sender: TObject);
begin
inherited;
actnRefresh.Enabled := Assigned(CoreTransfer);
end;
procedure TfrmCoreTransferContentsView.actnAddAllWellsStringExecute(Sender: TObject);
var
i: integer;
ct: TCoreTransferTask;
w: TSlottingWell;
begin
inherited;
if not Assigned(frmSelectTransferStateDialog) then
frmSelectTransferStateDialog := TfrmSelectTransferStateDialog.Create(Self);
if frmSelectTransferStateDialog.ShowModal = mrOk then
begin
if not Assigned(frmProgress) then
frmProgress := TfrmProgress.Create(Self);
frmProgress.Min := 0;
frmProgress.Max := TransferringObjects.Count - 1;
frmProgress.Show;
for i := 0 to TransferringObjects.Count - 1 do
begin
if TransferringObjects.Items[i] is TSlottingWell then
begin
w := TransferringObjects.Items[i] as TSlottingWell;
if w.Slottings.Count > 0 then
begin
if not CoreTransferTasks.IsWellPresent(w) then
begin
ct := CoreTransferTasks.Add as TCoreTransferTask;
ct.TransferType := frmSelectTransferStateDialog.TransferType;
ct.TransferringObject := TransferringObjects.Items[i];
ct.SourcePlacement := w.SlottingPlacement.StatePartPlacement;
ct.BoxCount := w.SlottingPlacement.FinalBoxCount;
end;
end;
end;
frmProgress.StepIt;
end;
frmProgress.Close;
grdCoreTransfers.Rows.Count := CoreTransferTasks.Count;
grdCoreTransfers.Refresh;
InternalCheck;
end;
end;
procedure TfrmCoreTransferContentsView.actnAddAllWellsStringUpdate(Sender: TObject);
begin
inherited;
actnAddAllWellsString.Enabled := Assigned(CoreTransfer);
end;
procedure TfrmCoreTransferContentsView.actnDeleteByStateExecute(Sender: TObject);
var
i: integer;
begin
inherited;
for i := CoreTransferTasks.Count - 1 downto 0 do
if not CoreTransferTasks.Items[i].IsDataCompleted then
if CoreTransferTasks.Items[i].ID > 0 then
CoreTransferTasks.MarkDeleted(CoreTransferTasks.Items[i])
else
CoreTransferTasks.Remove(CoreTransferTasks.Items[i]);
grdCoreTransfers.Rows.Count := CoreTransferTasks.Count;
if CoreTransferTasks.Count > 0 then
CurrentTask := CoreTransferTasks.Items[0];
InternalCheck;
grdCoreTransfers.Refresh;
end;
procedure TfrmCoreTransferContentsView.actnDeleteByStateUpdate(Sender: TObject);
begin
inherited;
actnDeleteByState.Enabled := Assigned(CoreTransfer) and (CoreTransferTasks.Count > 0);
end;
procedure TfrmCoreTransferContentsView.actnDeleteByTransferTypeExecute(Sender: TObject);
var
i: integer;
begin
inherited;
if not Assigned(frmSelectTransferStateDialog) then
frmSelectTransferStateDialog := TfrmSelectTransferStateDialog.Create(Self);
if frmSelectTransferStateDialog.ShowModal = mrOk then
begin
for i := CoreTransferTasks.Count - 1 downto 0 do
begin
if CoreTransferTasks.Items[i].TransferType = frmSelectTransferStateDialog.TransferType then
if CoreTransferTasks.Items[i].ID > 0 then
CoreTransferTasks.MarkDeleted(CoreTransferTasks.Items[i])
else
CoreTransferTasks.Remove(CoreTransferTasks.Items[i]);
end;
grdCoreTransfers.Rows.Count := CoreTransferTasks.Count;
if CoreTransferTasks.Count > 0 then
CurrentTask := CoreTransferTasks.Items[0];
grdCoreTransfers.Refresh;
InternalCheck;
end;
end;
procedure TfrmCoreTransferContentsView.actnDeleteByTransferTypeUpdate(Sender: TObject);
begin
inherited;
actnDeleteByTransferType.Enabled := Assigned(CoreTransfer) and (CoreTransferTasks.Count > 0);
end;
procedure TfrmCoreTransferContentsView.actnChangeTransferTypeForAllExecute(Sender: TObject);
var
i: integer;
begin
inherited;
if not Assigned(frmSelectTransferStateDialog) then
frmSelectTransferStateDialog := TfrmSelectTransferStateDialog.Create(Self);
if frmSelectTransferStateDialog.ShowModal = mrOk then
begin
for i := 0 to CoreTransferTasks.Count - 1 do
CoreTransferTasks.Items[i].TransferType := frmSelectTransferStateDialog.TransferType;
end;
InternalCheck;
grdCoreTransfers.Refresh;
end;
procedure TfrmCoreTransferContentsView.actnChangeTransferTypeForAllUpdate(Sender: TObject);
begin
inherited;
actnChangeTransferTypeForAll.Enabled := Assigned(CoreTransfer) and (CoreTransferTasks.Count > 0);
end;
procedure TfrmCoreTransferContentsView.actnChangeSourcePlacementExecute(Sender: TObject);
var
i: integer;
begin
inherited;
if not Assigned(frmSelectPlacement) then
frmSelectPlacement := TfrmSelectPlacement.Create(Self);
frmSelectPlacement.UseNewPlacements := false;
if frmSelectPlacement.ShowModal = mrOk then
begin
if not frmSelectPlacement.FillOnlyEmpties then
for i := 0 to CoreTransferTasks.Count - 1 do
CoreTransferTasks.Items[i].SourcePlacement := frmSelectPlacement.PartPlacement
else
for i := 0 to CoreTransferTasks.Count - 1 do
if (CoreTransferTasks.Items[i].SourcePlacement = nil) or (not (Assigned(TMainFacade.GetInstance.CoreLibrary.OldPlacementPlainList.ItemsByID[CoreTransferTasks.Items[i].SourcePlacement.ID]))) then
CoreTransferTasks.Items[i].SourcePlacement := frmSelectPlacement.PartPlacement
end;
InternalCheck;
grdCoreTransfers.Refresh;
end;
procedure TfrmCoreTransferContentsView.actnChangeTargetPlacementExecute(Sender: TObject);
var
i: integer;
begin
inherited;
if not Assigned(frmSelectPlacement) then
frmSelectPlacement := TfrmSelectPlacement.Create(Self);
frmSelectPlacement.UseNewPlacements := true;
if frmSelectPlacement.ShowModal = mrOk then
begin
if not frmSelectPlacement.FillOnlyEmpties then
for i := 0 to CoreTransferTasks.Count - 1 do
CoreTransferTasks.Items[i].TargetPlacement := frmSelectPlacement.PartPlacement
else
for i := 0 to CoreTransferTasks.Count - 1 do
if (CoreTransferTasks.Items[i].TargetPlacement = nil) or (not (Assigned(TMainFacade.GetInstance.CoreLibrary.NewPlacementPlainList.ItemsByID[CoreTransferTasks.Items[i].TargetPlacement.ID]))) then
CoreTransferTasks.Items[i].TargetPlacement := frmSelectPlacement.PartPlacement
end;
InternalCheck;
grdCoreTransfers.Refresh;
end;
procedure TfrmCoreTransferContentsView.actnChangeSourcePlacementUpdate(Sender: TObject);
begin
inherited;
actnChangeSourcePlacement.Enabled := Assigned(CoreTransfer) and (CoreTransferTasks.Count > 0);
end;
procedure TfrmCoreTransferContentsView.actnChangeTargetPlacementUpdate(Sender: TObject);
begin
inherited;
actnChangeTargetPlacement.Enabled := Assigned(CoreTransfer) and (CoreTransferTasks.Count > 0);
end;
function TfrmCoreTransferContentsView.GetCoreTransferTasksWells: TRegisteredIDObjects;
begin
if not Assigned(FCoreTransferTaskWells) then
begin
FCoreTransferTaskWells := TSlottingWells.Create;
FCoreTransferTaskWells.OwnsObjects := true;
FCoreTransferTaskWells.AddObjects(TMainFacade.GetInstance.AllWells, True, false);
FCoreTransferTaskWells.AddObjects(CoreTransferTasks.Wells, True, true);
end;
Result := FCoreTransferTaskWells;
end;
procedure TfrmCoreTransferContentsView.ClearCacheObjects;
begin
try
FreeAndNil(FCoreTransferTasks);
except
end;
try
FreeAndNil(FTransferringObjects);
except
end;
try
FreeAndNil(FCoreTransferTaskWells);
except
end;
end;
procedure TfrmCoreTransferContentsView.RefreshCoreTransferTasks;
var i: integer;
begin
if Assigned(EditingObject) then
begin
for i := 0 to (EditingObject as TCoreTransfer).CoreTransferTasks.Count - 1 do
if (EditingObject as TCoreTransfer).CoreTransferTasks.Items[i].TransferType.CoreTransferTypePresence in CoreTransferTypesVisibility then
CoreTransferTasks.Add((EditingObject as TCoreTransfer).CoreTransferTasks.Items[i], True, True);
end;
end;
function TfrmCoreTransferContentsView.InternalCheck: boolean;
var i: integer;
begin
Result := true;
StatusBar.Panels.Items[0].Text := '';
for i := 0 to CoreTransferTasks.Count - 1 do
begin
result := Result and CoreTransferTasks.Items[i].IsDataCompleted;
if not result then
begin
StatusBar.Panels.Items[0].Text := 'Заполнение не завершено';
Break;
end;
end;
FInternalCheckResult := Result;
end;
procedure TfrmCoreTransferContentsView.grdCoreTransfersDrawCell(
Sender: TObject; Cell: TGridCell; var Rect: TRect;
var DefaultDrawing: Boolean);
var ctt: TCoreTransferTask;
s: string;
begin
inherited;
if Cell.Row < CoreTransferTasks.Count then
begin
ctt := CoreTransferTasks.Items[Cell.Row];
if ctt.IsDataCompleted then
DefaultDrawing := True
else
begin
DefaultDrawing := False;
grdCoreTransfers.Canvas.Brush.Color := clRed;
grdCoreTransfers.Canvas.FillRect(rect);
grdCoreTransfersGetCellText(Sender, Cell, s);
grdCoreTransfers.Canvas.TextOut(Rect.Left + 6, Rect.Top + 2, s);
end;
end;
end;
end.
|
unit ufrmMain;
interface
uses
Windows, Messages, SysUtils, StrUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ComCtrls, ImgList, ActnList, Registry;
type
TfrmMain = class(TForm)
Label1: TLabel;
edtKeywords: TEdit;
cbClasses: TCheckBox;
cbCurrUser: TCheckBox;
cbLocalMachine: TCheckBox;
cbAllUsers: TCheckBox;
cbConfig: TCheckBox;
btnSearch: TBitBtn;
btnExit: TBitBtn;
btnInfo: TBitBtn;
StatusBar: TStatusBar;
ActionList: TActionList;
actSearchRegistry: TAction;
ImageList: TImageList;
actInformation: TAction;
actExit: TAction;
actCancelSearch: TAction;
cbCheckNames: TCheckBox;
cbCheckValues: TCheckBox;
pbClasses: TProgressBar;
pbCurrUser: TProgressBar;
pbLocalMachine: TProgressBar;
pbAllUsers: TProgressBar;
pbConfig: TProgressBar;
procedure FormActivate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actCancelSearchExecute(Sender: TObject);
procedure actSearchRegistryExecute(Sender: TObject);
procedure actInformationExecute(Sender: TObject);
procedure actExitExecute(Sender: TObject);
private
FCurrRoot: string;
FCurrProgressBar: TProgressBar;
FKeyWordList: TStringList;
FCancelSearch: Boolean;
function NoSectionsChecked: Boolean;
procedure SearchRegistry;
procedure SearchRegPath(RootKey: HKEY; Path: string = '');
procedure SearchRegValues(Reg: TRegistry);
function KeywordFound(SearchStr: string): Boolean;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
ufrmRegFoundList;
procedure TfrmMain.FormCreate(Sender: TObject);
// create the list of keywords to be used throughout the program
begin
FKeyWordList := TStringList.Create;
end;
procedure TfrmMain.FormActivate(Sender: TObject);
begin
// why does this keep getting reset?
StatusBar.Font.Name := 'Arial Narrow';
StatusBar.Font.Style := [];
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
// free the memory for the keyword list
begin
FKeyWordList.Free;
end;
procedure TfrmMain.actExitExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.actInformationExecute(Sender: TObject);
// display the only help message in the program
begin
MessageDlg('This program searches through the Windows registry for the keywords ' +
'given and displays all entries found in a list. You can then, with ' +
'the click of a button, remove these entries from the registry. This ' +
'helps to clean things out after a program has been "uninstalled" but ' +
'leaves left-over settings you no longer need to keep.'#10#13#13 +
'DISCLAIMER: Modifying the system registry can render your system ' +
'unusable or may cause other unknown problems.'#10#13 +
'Use caution and ALWAYS make a backup.', mtInformation, [mbOK], 0);
end;
procedure TfrmMain.actSearchRegistryExecute(Sender: TObject);
// does some checking, then sets up the GUI for the actual registry check/clean process
var
i: Integer;
SaveStatusBarText: string;
begin
if Length(Trim(edtKeywords.Text)) = 0 then
MessageDlg('Please enter some keywords to search.', mtWarning, [mbOK], 0)
else if NoSectionsChecked then
MessageDlg('There is nothing to do because no registry sections have been checked.', mtWarning, [mbOK], 0)
else if (not cbCheckNames.Checked) and (not cbCheckValues.Checked) then
MessageDlg('There is nothing to do because neither "Check Key Names" nor "Check Key Values" are checked.', mtWarning, [mbOK], 0)
else begin
// the status bar doubles as progessive search display so the user knows how it's doing
SaveStatusBarText := StatusBar.SimpleText;
// initialize the cancel function
FCancelSearch := False;
// turn on the hourglass--this will take a while
Screen.Cursor := crHourGlass;
try
// disable all text edit fields, checkboxes, and buttons (except the cancel button)
for i := 0 to ComponentCount - 1 do
if (Components[i] is TWinControl) and ((Components[i] as TWincontrol).Tag <> 1) then
(Components[i] as TWinControl).Enabled := False;
// the Search button doubles as the cancel button
btnSearch.Glyph := nil;
btnSearch.Action := actCancelSearch;
// parse the keywords
FKeywordList.CommaText := Trim(edtKeywords.Text);
// all set--here's the meat!
SearchRegistry;
finally
// turn everything back on and restore normalcy
for i := 0 to ComponentCount - 1 do
if (Components[i] is TWinControl) and ((Components[i] as TWincontrol).Tag <> 1) then
(Components[i] as TWinControl).Enabled := True;
btnSearch.Glyph := nil;
btnSearch.Action := actSearchRegistry;
Screen.Cursor := crDefault;
StatusBar.SimpleText := SaveStatusBarText;
end;
end;
end;
procedure TfrmMain.actCancelSearchExecute(Sender: TObject);
// the cancel button was hit!!
begin
FCancelSearch := True;
end;
function TfrmMain.NoSectionsChecked: Boolean;
// return whether or not at least one of the registry sections is to be checked
begin
Result := (not cbClasses.Checked) and
(not cbCurrUser.Checked) and
(not cbLocalMachine.Checked) and
(not cbAllUsers.Checked) and
(not cbConfig.Checked);
end;
procedure TfrmMain.SearchRegistry;
// for each registry section to be checked, calls SearchRegPath
begin
pbClasses.Position := 0;
pbCurrUser.Position := 0;
pbLocalMachine.Position := 0;
pbAllUsers.Position := 0;
pbConfig.Position := 0;
frmRegFoundList := TfrmRegFoundList.Create(self);
try
if cbClasses.Checked and (not FCancelSearch) then begin
FCurrRoot := 'CLASSES_ROOT:';
FCurrProgressBar := pbClasses;
SearchRegPath(HKEY_CLASSES_ROOT);
end;
if cbCurrUser.Checked and (not FCancelSearch) then begin
FCurrRoot := 'CURRENT_USER:';
FCurrProgressBar := pbCurrUser;
SearchRegPath(HKEY_CURRENT_USER);
end;
if cbLocalMachine.Checked and (not FCancelSearch) then begin
FCurrRoot := 'LOCAL_MACHINE:';
FCurrProgressBar := pbLocalMachine;
SearchRegPath(HKEY_LOCAL_MACHINE);
end;
if cbAllUsers.Checked and (not FCancelSearch) then begin
FCurrRoot := 'USERS:';
FCurrProgressBar := pbAllUsers;
SearchRegPath(HKEY_USERS);
end;
if cbConfig.Checked and (not FCancelSearch) then begin
FCurrRoot := 'CURRENT_CONFIG:';
FCurrProgressBar := pbConfig;
SearchRegPath(HKEY_CURRENT_CONFIG);
end;
// found them all, now show them and let the user decide what to do
if FCancelSearch then
frmRegFoundList.lbEntriesFound.Items.Add('SEARCH CANCELED!');
frmRegFoundList.ShowModal;
finally
frmRegFoundList.Free;
end;
end;
procedure TfrmMain.SearchRegPath(RootKey: HKEY; Path: string = '');
// recursively searches all registry keys in the given path
var
s: string;
reg: TRegistry;
RegKeyList: TStringList;
i: Integer;
begin
reg := TRegistry.Create;
try
reg.RootKey := RootKey;
RegKeyList := TStringList.Create;
try
// open the registry key for the path given
reg.OpenKeyReadOnly(Path);
// get a list of all sub-keys
reg.GetKeyNames(RegKeyList);
// if path is blank, we're on the root path, so setup the progressbar
if Path = EmptyStr then
FCurrProgressBar.Max := RegKeyList.Count;
// here's where we traverse all keys in the current path
for i := 0 to RegKeyList.Count - 1 do begin
// display work in progress
if Path = EmptyStr then
FCurrProgressBar.StepIt;
s := FCurrRoot + Reg.CurrentPath + '\' + RegKeyList.Strings[i];
StatusBar.SimpleText := s;
// watch for cancel press and also update controls
Application.ProcessMessages;
// was cancel pressed?
if FCancelSearch then
Break;
// check registry keys
if cbCheckNames.Checked and KeywordFound(RegKeyList.Strings[i]) then
frmRegFoundList.lbEntriesFound.Items.Add(FCurrRoot + '\' + reg.CurrentPath + '\' + RegKeyList.Strings[i]);
// check registry string values
if cbCheckValues.Checked then
SearchRegValues(reg);
// traverse sub-keys
if Length(Trim(RegKeyList.Strings[i])) > 0 then
SearchRegPath(RootKey, Reg.CurrentPath + '\' + RegKeyList.Strings[i]);
end;
finally
reg.CloseKey;
RegKeyList.Free;
end;
finally
reg.Free;
end;
end;
function TfrmMain.KeywordFound(SearchStr: string): Boolean;
// searches the given string for an occurance of any of our keywords
var
i: Integer;
begin
Result := False;
for i := 0 to FKeywordList.Count - 1 do
if AnsiContainsText(SearchStr, FKeywordList.Strings[i]) then begin
Result := True;
Break;
end;
end;
procedure TfrmMain.SearchRegValues(Reg: TRegistry);
// searches through all values in the given registry key
var
i: Integer;
RegValueInfo: TRegDataInfo;
RegValueNames: TStringList;
s: string;
begin
RegValueNames := TStringList.Create;
try
reg.GetValueNames(RegValueNames);
for i := 0 to RegValueNames.Count - 1 do
if reg.GetDataInfo(RegValueNames.Strings[i], RegValueInfo) then
if (RegValueInfo.RegData = rdString) or (RegValueInfo.RegData = rdExpandString) then begin
s := reg.ReadString(RegValueNames.Strings[i]);
if KeywordFound(s) then
frmRegFoundList.lbEntriesFound.Items.Add(FCurrRoot + '\' + reg.CurrentPath + '\' +
RegValueNames.Strings[i] + ' "' + s + '"');
end;
finally
RegValueNames.Free;
end;
end;
end.
|
unit Csv;
interface
type
HCkCsv = Pointer;
HCkString = Pointer;
function CkCsv_Create: HCkCsv; stdcall;
procedure CkCsv_Dispose(handle: HCkCsv); stdcall;
function CkCsv_getAutoTrim(objHandle: HCkCsv): wordbool; stdcall;
procedure CkCsv_putAutoTrim(objHandle: HCkCsv; newPropVal: wordbool); stdcall;
function CkCsv_getCrlf(objHandle: HCkCsv): wordbool; stdcall;
procedure CkCsv_putCrlf(objHandle: HCkCsv; newPropVal: wordbool); stdcall;
procedure CkCsv_getDebugLogFilePath(objHandle: HCkCsv; outPropVal: HCkString); stdcall;
procedure CkCsv_putDebugLogFilePath(objHandle: HCkCsv; newPropVal: PWideChar); stdcall;
function CkCsv__debugLogFilePath(objHandle: HCkCsv): PWideChar; stdcall;
procedure CkCsv_getDelimiter(objHandle: HCkCsv; outPropVal: HCkString); stdcall;
procedure CkCsv_putDelimiter(objHandle: HCkCsv; newPropVal: PWideChar); stdcall;
function CkCsv__delimiter(objHandle: HCkCsv): PWideChar; stdcall;
function CkCsv_getEnableQuotes(objHandle: HCkCsv): wordbool; stdcall;
procedure CkCsv_putEnableQuotes(objHandle: HCkCsv; newPropVal: wordbool); stdcall;
function CkCsv_getEscapeBackslash(objHandle: HCkCsv): wordbool; stdcall;
procedure CkCsv_putEscapeBackslash(objHandle: HCkCsv; newPropVal: wordbool); stdcall;
function CkCsv_getHasColumnNames(objHandle: HCkCsv): wordbool; stdcall;
procedure CkCsv_putHasColumnNames(objHandle: HCkCsv; newPropVal: wordbool); stdcall;
procedure CkCsv_getLastErrorHtml(objHandle: HCkCsv; outPropVal: HCkString); stdcall;
function CkCsv__lastErrorHtml(objHandle: HCkCsv): PWideChar; stdcall;
procedure CkCsv_getLastErrorText(objHandle: HCkCsv; outPropVal: HCkString); stdcall;
function CkCsv__lastErrorText(objHandle: HCkCsv): PWideChar; stdcall;
procedure CkCsv_getLastErrorXml(objHandle: HCkCsv; outPropVal: HCkString); stdcall;
function CkCsv__lastErrorXml(objHandle: HCkCsv): PWideChar; stdcall;
function CkCsv_getLastMethodSuccess(objHandle: HCkCsv): wordbool; stdcall;
procedure CkCsv_putLastMethodSuccess(objHandle: HCkCsv; newPropVal: wordbool); stdcall;
function CkCsv_getNumColumns(objHandle: HCkCsv): Integer; stdcall;
function CkCsv_getNumRows(objHandle: HCkCsv): Integer; stdcall;
function CkCsv_getVerboseLogging(objHandle: HCkCsv): wordbool; stdcall;
procedure CkCsv_putVerboseLogging(objHandle: HCkCsv; newPropVal: wordbool); stdcall;
procedure CkCsv_getVersion(objHandle: HCkCsv; outPropVal: HCkString); stdcall;
function CkCsv__version(objHandle: HCkCsv): PWideChar; stdcall;
function CkCsv_DeleteColumn(objHandle: HCkCsv; index: Integer): wordbool; stdcall;
function CkCsv_DeleteColumnByName(objHandle: HCkCsv; columnName: PWideChar): wordbool; stdcall;
function CkCsv_DeleteRow(objHandle: HCkCsv; index: Integer): wordbool; stdcall;
function CkCsv_GetCell(objHandle: HCkCsv; row: Integer; col: Integer; outStr: HCkString): wordbool; stdcall;
function CkCsv__getCell(objHandle: HCkCsv; row: Integer; col: Integer): PWideChar; stdcall;
function CkCsv_GetCellByName(objHandle: HCkCsv; rowIndex: Integer; columnName: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkCsv__getCellByName(objHandle: HCkCsv; rowIndex: Integer; columnName: PWideChar): PWideChar; stdcall;
function CkCsv_GetColumnName(objHandle: HCkCsv; index: Integer; outStr: HCkString): wordbool; stdcall;
function CkCsv__getColumnName(objHandle: HCkCsv; index: Integer): PWideChar; stdcall;
function CkCsv_GetIndex(objHandle: HCkCsv; columnName: PWideChar): Integer; stdcall;
function CkCsv_GetNumCols(objHandle: HCkCsv; row: Integer): Integer; stdcall;
function CkCsv_LoadFile(objHandle: HCkCsv; path: PWideChar): wordbool; stdcall;
function CkCsv_LoadFile2(objHandle: HCkCsv; filename: PWideChar; charset: PWideChar): wordbool; stdcall;
function CkCsv_LoadFromString(objHandle: HCkCsv; csvData: PWideChar): wordbool; stdcall;
function CkCsv_RowMatches(objHandle: HCkCsv; rowIndex: Integer; matchPattern: PWideChar; caseSensitive: wordbool): wordbool; stdcall;
function CkCsv_SaveFile(objHandle: HCkCsv; path: PWideChar): wordbool; stdcall;
function CkCsv_SaveFile2(objHandle: HCkCsv; filename: PWideChar; charset: PWideChar): wordbool; stdcall;
function CkCsv_SaveLastError(objHandle: HCkCsv; path: PWideChar): wordbool; stdcall;
function CkCsv_SaveToString(objHandle: HCkCsv; outStr: HCkString): wordbool; stdcall;
function CkCsv__saveToString(objHandle: HCkCsv): PWideChar; stdcall;
function CkCsv_SetCell(objHandle: HCkCsv; row: Integer; col: Integer; content: PWideChar): wordbool; stdcall;
function CkCsv_SetCellByName(objHandle: HCkCsv; rowIndex: Integer; columnName: PWideChar; contentStr: PWideChar): wordbool; stdcall;
function CkCsv_SetColumnName(objHandle: HCkCsv; index: Integer; columnName: PWideChar): wordbool; stdcall;
function CkCsv_SortByColumn(objHandle: HCkCsv; columnName: PWideChar; ascending: wordbool; caseSensitive: wordbool): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkCsv_Create; external DLLName;
procedure CkCsv_Dispose; external DLLName;
function CkCsv_getAutoTrim; external DLLName;
procedure CkCsv_putAutoTrim; external DLLName;
function CkCsv_getCrlf; external DLLName;
procedure CkCsv_putCrlf; external DLLName;
procedure CkCsv_getDebugLogFilePath; external DLLName;
procedure CkCsv_putDebugLogFilePath; external DLLName;
function CkCsv__debugLogFilePath; external DLLName;
procedure CkCsv_getDelimiter; external DLLName;
procedure CkCsv_putDelimiter; external DLLName;
function CkCsv__delimiter; external DLLName;
function CkCsv_getEnableQuotes; external DLLName;
procedure CkCsv_putEnableQuotes; external DLLName;
function CkCsv_getEscapeBackslash; external DLLName;
procedure CkCsv_putEscapeBackslash; external DLLName;
function CkCsv_getHasColumnNames; external DLLName;
procedure CkCsv_putHasColumnNames; external DLLName;
procedure CkCsv_getLastErrorHtml; external DLLName;
function CkCsv__lastErrorHtml; external DLLName;
procedure CkCsv_getLastErrorText; external DLLName;
function CkCsv__lastErrorText; external DLLName;
procedure CkCsv_getLastErrorXml; external DLLName;
function CkCsv__lastErrorXml; external DLLName;
function CkCsv_getLastMethodSuccess; external DLLName;
procedure CkCsv_putLastMethodSuccess; external DLLName;
function CkCsv_getNumColumns; external DLLName;
function CkCsv_getNumRows; external DLLName;
function CkCsv_getVerboseLogging; external DLLName;
procedure CkCsv_putVerboseLogging; external DLLName;
procedure CkCsv_getVersion; external DLLName;
function CkCsv__version; external DLLName;
function CkCsv_DeleteColumn; external DLLName;
function CkCsv_DeleteColumnByName; external DLLName;
function CkCsv_DeleteRow; external DLLName;
function CkCsv_GetCell; external DLLName;
function CkCsv__getCell; external DLLName;
function CkCsv_GetCellByName; external DLLName;
function CkCsv__getCellByName; external DLLName;
function CkCsv_GetColumnName; external DLLName;
function CkCsv__getColumnName; external DLLName;
function CkCsv_GetIndex; external DLLName;
function CkCsv_GetNumCols; external DLLName;
function CkCsv_LoadFile; external DLLName;
function CkCsv_LoadFile2; external DLLName;
function CkCsv_LoadFromString; external DLLName;
function CkCsv_RowMatches; external DLLName;
function CkCsv_SaveFile; external DLLName;
function CkCsv_SaveFile2; external DLLName;
function CkCsv_SaveLastError; external DLLName;
function CkCsv_SaveToString; external DLLName;
function CkCsv__saveToString; external DLLName;
function CkCsv_SetCell; external DLLName;
function CkCsv_SetCellByName; external DLLName;
function CkCsv_SetColumnName; external DLLName;
function CkCsv_SortByColumn; external DLLName;
end.
|
(* NIM/Nama : 16515019/Stevanno Hero Leadervand*)
(* Nama file : ujam.pas *)
(* Topik : Prosedural Pascal *)
(* Tanggal : 6 April 2016 *)
(* Deskripsi : memeriksa jam valid, menuliskan, memeriksa masukan jam pertama lebih awal, menentukan durasi selisih 2 ja*)
unit ujam;
interface
type Jam = record
hh : integer; { bagian jam }
mm : integer; { bagian menit }
ss : integer; { bagian detik }
end;
var
J: Jam;
function IsJamValid (h, m, s : integer):boolean;
{ Menghasilkan true jika h, m, s dapat membentuk jam yang valid, sesuai definisi jam
di atas, dengan h sebagai bagian hh, m sebagai bagian mm, dan s sebagai bagian ss }
procedure TulisJam (J : Jam);
{ Menuliskan jam J ke layar dalam bentuk "J.hh:J.mm:J.ss" }
{ Tidak diawali, diselangi, atau diakhiri dengan karakter apa pun, termasuk spasi atau pun enter }
{ I.S.: J terdefinisi }
{ F.S.: J tercetak di layar dalam bentuk "hh:mm:ss" }
function IsJamLebihAwal (J1, J2 : Jam):boolean;
{ Menghasilkan true jika J1 lebih awal daripada J2 }
{ Menggunakan analisis kasus/kondisional }
function Durasi (J1, J2 : Jam):integer;
{ Menghasilkan durasi antara J1 dengan J2 dengan cara: jumlah detik J2 – jumlah detik J1 }
{ Untuk menghasilkan jumlah detik dari suatu jam <hh,mm,ss> dari jam <0,0,0>
gunakan rumus = hh * 3600 + mm * 60 + ss. }
{ Prekondisi : J1 lebih awal dari atau sama dengan J2 }
implementation
function IsJamValid (h, m, s : integer):boolean;
begin
if (h>=0) and (h<=23) and (m>=0) and (m<=59) and (s>=0) and (s<=59) then
begin
IsJamValid:=True;
end;
end;
procedure TulisJam (J : Jam);
begin
if (IsJamValid(J.hh,J.mm,J.ss)) then
begin
write(J.hh,':',J.mm,':',J.ss);
end;
end;
function IsJamLebihAwal (J1, J2 : Jam):boolean;
begin
if (J1.hh=J2.hh) and (J1.mm=J2.mm) and (J1.ss=J2.ss) then begin
IsJamLebihAwal:=False;
end else if (J1.hh>J2.hh) then begin
IsJamLebihAwal:=False;
end else if (J1.hh=J2.hh) and (J1.mm>J2.mm) then begin
IsJamLebihAwal:=False;
end else if (J1.hh=J2.hh) and (J1.mm=J2.mm) and (J1.ss>J2.ss) then begin
IsJamLebihAwal:=False;
end else
IsJamLebihAwal:=True;
end;
function Durasi (J1, J2 : Jam):integer;
begin
if (IsJamLebihAwal(J1,J2)) then begin
Durasi:=(J2.hh * 3600 + J2.mm * 60 + J2.ss)-(J1.hh * 3600 + J1.mm * 60 + J1.ss);
end;
end;
end.
|
unit VSETerrain;
interface
uses
AvL, avlUtils, avlMath, OpenGL, VSEOpenGLExt, oglExtensions, avlVectors,
VSEArrayBuffer, VSETexMan, SynTex, VSEVertexArrayUtils;
type
TTerrain=class(TObject)
private
function GetHeightMap(X, Y: Word): Byte;
protected
FTerrainData: PByteArray;
FVertexBuffer, FIndexBuffer: TArrayBuffer;
//Draw normals:
//FNormalsBuffer: TArrayBuffer;
FTexture: Cardinal;
FWidth, FHeight: Word;
FHScale, FVScale: Single;
public
constructor Create;
destructor Destroy; override;
procedure Load(const Tex: TSynTexRegister; TexSize: Integer; HScale, VScale: Single); //Load terrain from SynTex texture; Tex: SynTex texture; TexSize: texture size; HScale: horizontal scale; VScale: vertical scale
procedure Draw; //Draw terrain
function Altitude(X, Y: Single): Single; //Terrain altitude at (X, Y)
procedure Morph(X, Y, Width, Height: Word; Data: array of SmallInt); //Modify terrain; X, Y: coordinales of modified zone; Width, Height: size of modified zone; Data: height delta array
property Width: Word read FWidth; //Terrain width
property Height: Word read FHeight; //Terain height
property HeightMap[X, Y: Word]: Byte read GetHeightMap; //heightmap data
property Texture: Cardinal read FTexture write FTexture; //Terrain texture
end;
implementation
uses
VSECore;
constructor TTerrain.Create;
begin
inherited Create;
FVertexBuffer:=TArrayBuffer.Create;
FIndexBuffer:=TArrayBuffer.Create;
end;
destructor TTerrain.Destroy;
begin
if FTerrainData<>nil then FreeMem(FTerrainData, FWidth*FHeight);
FAN(FVertexBuffer);
FAN(FIndexBuffer);
inherited Destroy;
end;
procedure TTerrain.Load(const Tex: TSynTexRegister; TexSize: Integer; HScale, VScale: Single);
var
i, j: Cardinal;
VertexBuffer: array of TVertex;
IndexBuffer: array of Integer;
//Draw normals:
//NormBuf: array of TVector3D;
IndexLen: Cardinal;
begin
FHScale:=HScale;
FVScale:=VScale;
GetMem(FTerrainData, TexSize*TexSize);
for i:=0 to TexSize*TexSize-1 do
FTerrainData[i]:=Tex[i].R;
FWidth:=TexSize;
FHeight:=TexSize;
try
SetLength(VertexBuffer, FWidth*FHeight);
for i:=0 to FWidth*FHeight-1 do
begin
VertexBuffer[i].Vertex.X:=FHScale*(i mod FWidth);
VertexBuffer[i].Vertex.Z:=FHScale*(i div FWidth);
VertexBuffer[i].Vertex.Y:=FVScale*FTerrainData[i];
end;
IndexLen:=2*(FWidth*FHeight-FWidth+FHeight-1);
SetLength(IndexBuffer, IndexLen);
for j:=0 to FHeight-1 do
begin
for i:=0 to FWidth-1 do
begin
if j<FHeight-1 then
begin
IndexBuffer[2*(j*(FWidth+1)+i)]:=j*FWidth+i;
IndexBuffer[2*(j*(FWidth+1)+i)+1]:=(j+1)*FWidth+i;
end;
VectorClear(VertexBuffer[j*FWidth+i].Normal);
VertexBuffer[j*FWidth+i].TexCoord.X:=i/32;
VertexBuffer[j*FWidth+i].TexCoord.Y:=j/32;
end;
if j<FHeight-1 then
begin
IndexBuffer[2*(j*(FWidth+1)+FWidth)]:=(j+1)*FWidth+FWidth-1;
IndexBuffer[2*(j*(FWidth+1)+FWidth)+1]:=(j+1)*FWidth;
end;
end;
ComputeNormalsTrianglesStrip(VertexBuffer, IndexBuffer);
//Draw normals:
{SetLength(NormBuf, Length(VertexBuffer)*2);
for i:=0 to High(VertexBuffer) do
begin
NormBuf[2*i]:=VertexBuffer[i].Vertex;
NormBuf[2*i+1]:=VectorAdd(VertexBuffer[i].Vertex, VertexBuffer[i].Normal);
end;
FNormalsBuffer:=TArrayBuffer.Create;
FNormalsBuffer.SetData(@NormBuf[0], SizeOf(TVector3D)*Length(NormBuf));
Finalize(NormBuf);}
FVertexBuffer.SetData(@VertexBuffer[0], SizeOf(TVertex)*FWidth*FHeight);
FIndexBuffer.SetData(@IndexBuffer[0], IndexLen*SizeOf(Integer));
finally
Finalize(VertexBuffer);
Finalize(IndexBuffer);
end;
end;
procedure TTerrain.Draw;
procedure SetColor(Target: GLenum; Color: TColor);
var
C: TVector4D;
begin
C:=gleColorTo4f(Color or $FF000000);
glMaterialfv(GL_FRONT_AND_BACK, Target, @C);
end;
begin
glPushAttrib(GL_ENABLE_BIT or GL_TEXTURE_BIT);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
TexMan.Bind(FTexture);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
SetColor(GL_DIFFUSE, clWhite);
SetColor(GL_SPECULAR, clGray);
SetColor(GL_AMBIENT, $404040);
SetColor(GL_EMISSION, clBlack);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 10.0);
FVertexBuffer.Bind(GL_ARRAY_BUFFER_ARB);
FIndexBuffer.Bind(GL_ELEMENT_ARRAY_BUFFER_ARB);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glNormalPointer(GL_FLOAT, SizeOf(TVertex), IncPtr(FVertexBuffer.Data, SizeOf(TVector3D)));
glTexCoordPointer(2, GL_FLOAT, SizeOf(TVertex), IncPtr(FVertexBuffer.Data, 2*SizeOf(TVector3D)));
glVertexPointer(3, GL_FLOAT, SizeOf(TVertex), FVertexBuffer.Data);
glDrawElements(GL_TRIANGLE_STRIP, FIndexBuffer.Size div SizeOf(Integer), GL_UNSIGNED_INT, FIndexBuffer.Data);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
FVertexBuffer.Unbind;
FIndexBuffer.Unbind;
glPopAttrib;
end;
function TTerrain.Altitude(X, Y: Single): Single;
var
X0, X1, Y0, Y1: Integer;
H0, H1, H2, H3, AH1, AH2, WX, WY: Single;
begin
if X<0 then X:=0;
if Y<0 then Y:=0;
X:=X/FHScale;
Y:=Y/FHScale;
X0:=Floor(X);
Y0:=Floor(Y);
X1:=X0+1;
Y1:=Y0+1;
WX:=X-X0;
WY:=Y-Y0;
H0:=HeightMap[X0, Y0];
H1:=HeightMap[X0, Y1];
H2:=HeightMap[X1, Y0];
H3:=HeightMap[X1, Y1];
AH1:=(1-WY)*H0+WY*H1;
AH2:=(1-WY)*H2+WY*H3;
Result:=((1-WX)*AH1+WX*AH2)*FVScale;
end;
procedure TTerrain.Morph(X, Y, Width, Height: Word; Data: array of SmallInt);
begin
end;
function TTerrain.GetHeightMap(X, Y: Word): Byte;
begin
if X>=FWidth then X:=FWidth-1;
if Y>=FHeight then Y:=FHeight-1;
Result:=FTerrainData[Y*FWidth+X];
end;
end.
|
(******************************************************************************
* *
* MpuTools.pas *
* Contains helper functions for programming without the VCL *
* *
* Copyright (c) Michael Puff http://www.michael-puff.de *
* *
******************************************************************************)
(************************************************************************
* *
* COPYRIGHT NOTICE *
* *
* Copyright (c) 2001-2007, Michael Puff ["copyright holder(s)"] *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in *
* the documentation and/or other materials provided with the *
* distribution. *
* 3. The name(s) of the copyright holder(s) may not 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 *
* FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* REGENTS 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. *
* *
************************************************************************)
{$I CompilerSwitches.inc}
unit MpuTools;
interface
uses
Windows,
Messages,
ShlObj,
CommDlg,
commctrl,
ActiveX;
const
fmOpenRead = $0000;
fmOpenWrite = $0001;
fmOpenReadWrite = $0002;
fmShareCompat = $0000;
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyRead = $0030;
fmShareDenyNone = $0040;
const
CSIDL_FLAG_CREATE = $8000;
CSIDL_ADMINTOOLS = $0030;
CSIDL_ALTSTARTUP = $001D;
CSIDL_APPDATA = $001A;
CSIDL_BITBUCKET = $000A;
CSIDL_CDBURN_AREA = $003B;
CSIDL_COMMON_ADMINTOOLS = $002F;
CSIDL_COMMON_ALTSTARTUP = $001E;
CSIDL_COMMON_APPDATA = $0023;
CSIDL_COMMON_DESKTOPDIRECTORY = $0019;
CSIDL_COMMON_DOCUMENTS = $002E;
CSIDL_COMMON_FAVORITES = $001F;
CSIDL_COMMON_MUSIC = $0035;
CSIDL_COMMON_PICTURES = $0036;
CSIDL_COMMON_PROGRAMS = $0017;
CSIDL_COMMON_STARTMENU = $0016;
CSIDL_COMMON_STARTUP = $0018;
CSIDL_COMMON_TEMPLATES = $002D;
CSIDL_COMMON_VIDEO = $0037;
CSIDL_CONTROLS = $0003;
CSIDL_COOKIES = $0021;
CSIDL_DESKTOP = $0000;
CSIDL_DESKTOPDIRECTORY = $0010;
CSIDL_DRIVES = $0011;
CSIDL_FAVORITES = $0006;
CSIDL_FONTS = $0014;
CSIDL_HISTORY = $0022;
CSIDL_INTERNET = $0001;
CSIDL_INTERNET_CACHE = $0020;
CSIDL_LOCAL_APPDATA = $001C;
CSIDL_MYDOCUMENTS = $000C;
CSIDL_MYMUSIC = $000D;
CSIDL_MYPICTURES = $0027;
CSIDL_MYVIDEO = $000E;
CSIDL_NETHOOD = $0013;
CSIDL_NETWORK = $0012;
CSIDL_PERSONAL = $0005;
CSIDL_PRINTERS = $0004;
CSIDL_PRINTHOOD = $001B;
CSIDL_PROFILE = $0028;
CSIDL_PROFILES = $003E;
CSIDL_PROGRAM_FILES = $0026;
CSIDL_PROGRAM_FILES_COMMON = $002B;
CSIDL_PROGRAMS = $0002;
CSIDL_RECENT = $0008;
CSIDL_SENDTO = $0009;
CSIDL_STARTMENU = $000B;
CSIDL_STARTUP = $0007;
CSIDL_SYSTEM = $0025;
CSIDL_TEMPLATES = $0015;
CSIDL_WINDOWS = $0024;
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;
const
BIF_NEWDIALOGSTYLE = $0040;
const
TTS_BALLOON = $40;
var
hTooltip : Cardinal;
ti : TToolInfo;
{$IFDEF CONDITIONALEXPRESSIONS}
{$if CompilerVersion >= 20}
// Delphi 2009 oder höher
{$DEFINE TOSVERSIONINFOEX_DEFINED}
{$IFEND}
{$ENDIF}
{$IFNDEF TOSVERSIONINFOEX_DEFINED}
type
POSVersionInfoEx = ^TOSVersionInfoEx;
TOSVersionInfoEx = packed record
dwOSVersionInfoSize: DWORD;
dwMajorVersion: DWORD;
dwMinorVersion: DWORD;
dwBuildNumber: DWORD;
dwPlatformId: DWORD;
szCSDVersion: array[0..127] of AnsiChar;
wServicePackMajor: Word;
wServicePackMinor: Word;
wSuiteMask: Word;
wProductType: Byte;
wReserved: Byte;
end;
{$ENDIF} // TOSVERSIONINFOEX_DEFINED
const
VER_SERVER_NT = $80000000;
{$EXTERNALSYM VER_SERVER_NT}
VER_WORKSTATION_NT = $40000000;
{$EXTERNALSYM VER_WORKSTATION_NT}
VER_SUITE_SMALLBUSINESS = $00000001;
{$EXTERNALSYM VER_SUITE_SMALLBUSINESS}
VER_SUITE_ENTERPRISE = $00000002;
{$EXTERNALSYM VER_SUITE_ENTERPRISE}
VER_SUITE_BACKOFFICE = $00000004;
{$EXTERNALSYM VER_SUITE_BACKOFFICE}
VER_SUITE_COMMUNICATIONS = $00000008;
{$EXTERNALSYM VER_SUITE_COMMUNICATIONS}
VER_SUITE_TERMINAL = $00000010;
{$EXTERNALSYM VER_SUITE_TERMINAL}
VER_SUITE_SMALLBUSINESS_RESTRICTED = $00000020;
{$EXTERNALSYM VER_SUITE_SMALLBUSINESS_RESTRICTED}
VER_SUITE_EMBEDDEDNT = $00000040;
{$EXTERNALSYM VER_SUITE_EMBEDDEDNT}
VER_SUITE_DATACENTER = $00000080;
{$EXTERNALSYM VER_SUITE_DATACENTER}
VER_SUITE_SINGLEUSERTS = $00000100;
{$EXTERNALSYM VER_SUITE_SINGLEUSERTS}
VER_SUITE_PERSONAL = $00000200;
{$EXTERNALSYM VER_SUITE_PERSONAL}
VER_SUITE_BLADE = $00000400;
{$EXTERNALSYM VER_SUITE_BLADE}
VER_SUITE_EMBEDDED_RESTRICTED = $00000800;
{$EXTERNALSYM VER_SUITE_EMBEDDED_RESTRICTED}
VER_SUITE_SECURITY_APPLIANCE = $00001000;
{$EXTERNALSYM VER_SUITE_SECURITY_APPLIANCE}
const
VER_NT_WORKSTATION = $0000001;
{$EXTERNALSYM VER_NT_WORKSTATION}
VER_NT_DOMAIN_CONTROLLER = $0000002;
{$EXTERNALSYM VER_NT_DOMAIN_CONTROLLER}
VER_NT_SERVER = $0000003;
{$EXTERNALSYM VER_NT_SERVER}
function StrToInt(s: string): Int64;
function StrToFloat(s: string): Extended;
function IntToStr(Int: Int64): string;
function FloatToStr(Value: Extended; Width, Decimals: Integer): string;
function Format(fmt: string; params: array of const): string;
function FormatW(const S: WideString; const Args: array of const): WideString;
function UpperCase(const S: string): string;
function LowerCase(const S: string): string;
function Trim(const S: WideString): WideString;
function StrIComp(const Str1, Str2: PChar): Integer; assembler;
function AnsiStrComp(S1, S2: PChar): Integer;
function AnsiStrIComp(S1, S2: PChar): Integer;
function FileExists(const FileName: string): Boolean;
function DirectoryExists(const Directory: string): Boolean;
function ChangeFileExt(const szFilename, szNewExt: string): string;
function ExtractFilepath(s: string): string;
function ExtractFilepathW(s: WideString): WideString;
function ExtractFilename(s: string): string;
function ExtractFilenameW(s: WideString): WideString;
function HasBackslash(Dir: string): Boolean;
function DelBackSlash(Dir: string): string;
function ForceDirectories(Dir: string): Boolean;
function GetFileSize(Filename: String): Int64;
function FileCreate(const FileName: string): Integer;
function FileOpen(const FileName: string; Mode: LongWord): Integer;
procedure FileClose(Handle: Integer);
function FileRead(Handle: Integer; var Buffer; Count: LongWord): Integer;
function FileSeek(Handle, Offset, Origin: Integer): Integer;
function FileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer;
function GetFileVersion(const Filename: string): string;
function GetImageLinkTimeStamp(const FileName: string): DWORD;
function SysErrorMessage(ErrorCode: Integer): WideString;
procedure MyMessageBox(hWnd: HWND; caption, Text: WideString; IDIcon: DWORD);
procedure EnableControl(hParent: THandle; ID: DWORD; Enable: Boolean);
function LoadStr(ID: DWORD): string;
function LoadDLLStr(hDll: THandle; ID: DWORD): string;
function putbinrestohdd(binresname, path: string): Boolean;
function GetSystemFont: TLogFont;
function GetSystemFontName: WideString;
procedure ShowHelpText(hLib: THandle; wParam: WPARAM; lParam: LPARAM; hSB: HWND);
function CreateToolTips(hWnd: Cardinal; bBalloon: Boolean = False): Boolean;
procedure AddToolTip(hwnd, id: Cardinal; ti: PToolInfo; Text: string; Caption: string = ''; IDIcon: DWORD = 0);
procedure ProcessMessages(hWnd: DWORD);
function OpenFile(hParent: THandle; Filter: string): string;
function SaveFileAs(hParent: THandle; const Filter, Ext: string): string;
function GetFolder(hWnd: THandle; root: Integer; Caption: string; var Folder: string): DWORD;
function FindComputer(hWnd: THandle; Prompt: String; var Computer: String): boolean;
function FindDomain(hWnd: THandle; Prompt: String; var Domain: String): boolean;
function GetCurrUserName: string;
function GetCompName: string;
function IsAdmin: LongBool;
function GetWinDir(): string;
function GetSysDir(): string;
function GetShellFolder(CSIDL: integer): string;
function GetAppDir: string;
function IsNT5OrHigher: Boolean;
function GetOSVersionInfo(var Info: TOSVersionInfoEx): Boolean;
function GetOSVersionText: string;
function GetOSLanguageIDStr: string;
function GetOSLanguageStr: string;
function EnablePrivilege(const Privilege: string; fEnable: Boolean; out PreviousState: Boolean): DWORD;
function UnixTimeToDateString(i: PDWORD): string;
function UnixTimeToFileTime(t: LongWord): FILETIME;
function UnixTimeToTimeString(i: PDWORD): string;
function Min(x, y: Cardinal): Integer;
implementation
////////////////////////////////////////////////////////////////////////////////
//// SysUtils //////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Procedure : StrToInt
// Comment :
function StrToInt(s: string): Int64;
var
code : integer;
begin
val(s, result, code);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : StrToFloat
// Comment :
function StrToFloat(s: string): Extended;
var
code : integer;
begin
val(s, result, code);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : IntToStr
// Comment :
function IntToStr(Int: Int64): string;
begin
Str(Int, result);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FloatToStr
// Comment :
function FloatToStr(Value: Extended; Width, Decimals: Integer): string;
begin
Str(Value: Width: Decimals, result);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : Format
// Comment : Formats a string according to the formatdiscriptors
function Format(fmt: string; params: array of const): string;
var
pdw1, pdw2 : PDWORD;
i : integer;
pc : PCHAR;
begin
pdw1 := nil;
if length(params) > 0 then
GetMem(pdw1, length(params) * sizeof(Pointer));
pdw2 := pdw1;
for i := 0 to high(params) do
begin
pdw2^ := DWORD(PDWORD(@params[i])^);
inc(pdw2);
end;
GetMem(pc, 1024 - 1);
try
ZeroMemory(pc, 1024 - 1);
SetString(Result, pc, wvsprintf(pc, PCHAR(fmt), PCHAR(pdw1)));
except
Result := '';
end;
if (pdw1 <> nil) then
FreeMem(pdw1);
if (pc <> nil) then
FreeMem(pc);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : Format
// Comment : Formats a widestring according to the formatdiscriptors
function FormatW(const S: WideString; const Args: array of const): WideString;
var
StrBuffer2 : array[0..1023] of WideChar;
A : array[0..15] of LongWord;
i : Integer;
begin
for i := High(Args) downto 0 do
A[i] := Args[i].VInteger;
wvsprintfW(@StrBuffer2, PWideChar(S), @A);
Result := PWideChar(@StrBuffer2);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : UpperCase
// Author :
// Comment :
function UpperCase(const S: string): string;
var
Ch : Char;
L : Integer;
Source, Dest : PChar;
begin
L := Length(S);
SetLength(Result, L);
Source := Pointer(S);
Dest := Pointer(Result);
while L <> 0 do
begin
Ch := Source^;
if (Ch >= 'a') and (Ch <= 'z') then
Dec(Ch, 32);
Dest^ := Ch;
Inc(Source);
Inc(Dest);
Dec(L);
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : LowerCase
// Author :
// Comment :
function LowerCase(const S: string): string;
var
Ch : Char;
L : Integer;
Source, Dest : PChar;
begin
L := Length(S);
SetLength(Result, L);
Source := Pointer(S);
Dest := Pointer(Result);
while L <> 0 do
begin
Ch := Source^;
if (Ch >= 'A') and (Ch <= 'Z') then
Inc(Ch, 32);
Dest^ := Ch;
Inc(Source);
Inc(Dest);
Dec(L);
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : Trim
// Author :
// Comment :
function Trim(const S: WideString): WideString;
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;
////////////////////////////////////////////////////////////////////////////////
// Procedure : StrIComp
// Author :
// Comment :
function StrIComp(const Str1, Str2: PChar): Integer; assembler;
asm
PUSH EDI
PUSH ESI
MOV EDI,EDX
MOV ESI,EAX
MOV ECX,0FFFFFFFFH
XOR EAX,EAX
REPNE SCASB
NOT ECX
MOV EDI,EDX
XOR EDX,EDX
@@1: REPE CMPSB
JE @@4
MOV AL,[ESI-1]
CMP AL,'a'
JB @@2
CMP AL,'z'
JA @@2
SUB AL,20H
@@2: MOV DL,[EDI-1]
CMP DL,'a'
JB @@3
CMP DL,'z'
JA @@3
SUB DL,20H
@@3: SUB EAX,EDX
JE @@1
@@4: POP ESI
POP EDI
end;
////////////////////////////////////////////////////////////////////////////////
// AnsiStrComp
// AnsiStrComp compares S1 to S2, with case-sensitivity. The compare
// operation is controlled by the current user locale. The return value
// is the same as for CompareStr
//
function AnsiStrComp(S1, S2: PChar): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, 0, S1, -1, S2, -1) - 2;
end;
////////////////////////////////////////////////////////////////////////////////
//
// AnsiStrIComp
// AnsiStrIComp compares S1 to S2, without case-sensitivity. The compare
// operation is controlled by the current user locale. The return value
// is the same as for CompareStr.
//
function AnsiStrIComp(S1, S2: PChar): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, S1, -1,
S2, -1) - 2;
end;
////////////////////////////////////////////////////////////////////////////////
//// AppTools //////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Procedure : SysErrorMessage
// Comment : Returns last error as formated string
function SysErrorMessage(ErrorCode: Integer): WideString;
function MAKELANGID(usPrimaryLanguage, usSubLanguage: BYTE): WORD;
begin
Result := (usSubLanguage shl 10) or usPrimaryLanguage;
end;
var
MsgBuffer : array[0..2047] of WideChar;
len : Integer;
begin
len := FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
MsgBuffer, sizeof(MsgBuffer), nil);
if len > 0 then
begin
SetString(Result, MsgBuffer, len);
end
else
Result := '';
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : MyMessageBox
// Comment : Wrapper for MsgBoxParams
procedure MyMessageBox(hWnd: HWND; Caption, Text: WideString; IDIcon: DWORD);
var
MsgInfo : TMsgBoxParamsW;
begin
MsgInfo.cbSize := SizeOf(TMsgBoxParams);
MsgInfo.hwndOwner := hWnd;
MsgInfo.hInstance := GetWindowLong(hWnd, GWL_HINSTANCE);
MsgInfo.lpszText := @Text[1];
MsgInfo.lpszCaption := @Caption[1];
MsgInfo.dwStyle := MB_USERICON;
MsgInfo.lpszIcon := MAKEINTRESOURCEW(IDICON);
MessageBoxIndirectW(MsgInfo);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : EnableControl
// Author :
// Comment :
procedure EnableControl(hParent: THandle; ID: DWORD; Enable: Boolean);
var
hWnd : THandle;
begin
hWnd := GetFocus;
// jump to next control if control to disable has the focus
// otherwise we will get stuck and TAB won't work
if hWnd = GetDlgItem(hParent, ID) then
SendMessage(hParent, WM_NEXTDLGCTL, 0, 0);
EnableWindow(GetDlgItem(hParent, ID), Enable);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : LoadStr
// Comment : Loads a resource string
function LoadStr(ID: DWORD): string;
var
buffer : array[0..255] of Char;
begin
LoadString(hInstance, ID, buffer, 255);
result := string(buffer);
end;
////////////////////////////////////////////////////////////////////////////////
// LoadDLLStr
// Comment: Loads a StringResource from a DLL
function LoadDLLStr(hDll: THandle; ID: DWORD): string;
var
buffer : array[0..255] of Char;
begin
LoadString(hDll, ID, buffer, 255);
result := string(buffer);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ProcessMessages
// Comment : Replacement for ProcessMessages of TApplication
procedure ProcessMessages(hWnd: DWORD);
var
Msg : TMsg;
begin
while PeekMessage(Msg, hWnd, 0, 0, PM_REMOVE) do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetAppDir
// Author :
// Comment : uses ShlObj;
function GetAppDir: string;
var
pidl : PItemIdList;
FolderPath : string;
SystemFolder : Integer;
begin
SystemFolder := CSIDL_APPDATA;
if SUCCEEDED(SHGetSpecialFolderLocation(0, SystemFolder, pidl)) then
begin
SetLength(FolderPath, max_path);
if SHGetPathFromIDList(pidl, PChar(FolderPath)) then
begin
SetLength(FolderPath, length(PChar(FolderPath)) + 1);
end;
end;
Result := FolderPath;
end;
////////////////////////////////////////////////////////////////////////////////
//// UnixDateTimeTools /////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Procedure : UnixTimeToDateString
// Comment : Converts a Unixtimestamp to local systemtime
// and returns a formated date string
function UnixTimeToDateString(i: PDWORD): string;
var
umt : DWORD;
st : TSystemTime;
ft : TFileTime;
li : ULARGE_INTEGER;
buf : array[0..255] of char;
begin
result := '';
if i = nil then
exit;
umt := i^;
st.wYear := 1970;
st.wMonth := 1;
st.wDayOfWeek := 0;
st.wDay := 1;
st.wHour := 0;
st.wMinute := 0;
st.wSecond := 0;
st.wMilliseconds := 0;
SystemTimeToFileTime(st, ft);
li.QuadPart := (umt * 10000000) + ULARGE_INTEGER(ft).QuadPart;
ft.dwLowDateTime := li.LowPart;
ft.dwHighDateTime := li.HighPart;
FileTimeToSystemTime(ft, st);
ZeroMemory(@buf, sizeof(buf));
if (GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, @st, nil, buf,
sizeof(buf)) > 0) then
Result := string(buf);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : UnixTimeToTimeString
// Comment : Converts a Unixtimestamp to local systemtime
// and returns a formated time string
function UnixTimeToTimeString(i: PDWORD): string;
var
umt : int64;
st : SystemTime;
ft : FileTime;
li : ULARGE_INTEGER;
buf : array[0..255] of char;
begin
result := '';
if i = nil then
exit;
umt := i^;
st.wYear := 1970;
st.wMonth := 1;
st.wDayOfWeek := 0;
st.wDay := 1;
st.wHour := 0;
st.wMinute := 0;
st.wSecond := 0;
st.wMilliseconds := 0;
SystemTimeToFileTime(st, ft);
li.QuadPart := (umt * 10000000);
ft.dwLowDateTime := li.LowPart;
ft.dwHighDateTime := li.HighPart;
FileTimeToSystemTime(ft, st);
ZeroMemory(@buf, sizeof(buf));
if (GetTimeFormat(LOCALE_USER_DEFAULT, TIME_FORCE24HOURFORMAT, @st, nil, buf,
sizeof(buf)) > 0) then
Result := string(buf);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : UnixTimeToFileTime
// Comment : Converts a UnixTimeStamp to a FILETIME stamp
function UnixTimeToFileTime(t: LongWord): FILETIME;
var
ll : int64;
begin
ll := (Int64(t) * 10000000) + int64(116444736000000000);
result.dwLowDateTime := LongWord(ll);
result.dwHighDateTime := ll shr 32;
end;
////////////////////////////////////////////////////////////////////////////////
//// DialogTools ///////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Procedure : IsNT5OrHigher
// Author :
// Comment :
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;
////////////////////////////////////////////////////////////////////////////////
// Procedure : OpenFile
// Comment : returns the selected file including its path
function OpenFile(hParent: THandle; Filter: string): 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 := hParent;
ofn.hInstance := hInstance;
ofn.lpstrFile := @Buffer[0];
ofn.nMaxFile := sizeof(Buffer);
ofn.Flags := OFN_EXPLORER;
ofn.lpstrFilter := PChar(Filter + #0#0);
{ Datei-Öffnen-Dialog aufrufen }
if GetOpenFileName(ofn) then
result := ofn.lpstrFile;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : SaveFileAs
// Comment : returns the selected file including its path
function SaveFileAs(hParent: THandle; const Filter, Ext: string): 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 := hParent;
ofn.hInstance := hInstance;
ofn.lpstrFile := @Buffer[0];
ofn.lpstrFilter := PChar(Filter+ #0#0);
ofn.lpstrDefExt := PChar(Ext);
ofn.nMaxFile := sizeof(Buffer);
ofn.Flags := OFN_LONGNAMES;
{ Datei-Öffnen-Dialog aufrufen }
if GetSaveFileName(ofn) then
result := ofn.lpstrFile;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetFolder
// Author :
// Comment :
function GetFolder(hWnd: THandle; root: Integer; Caption: string; var Folder: string): DWORD;
var
bi : TBrowseInfo;
lpBuffer : PChar;
pidlPrograms,
pidlBrowse : PItemIDList;
begin
result := 0;
if (not SUCCEEDED(SHGetSpecialFolderLocation(GetActiveWindow, root, pidlPrograms))) then
begin
result := GetLastError;
exit;
end;
lpBuffer := GetMemory(MAX_PATH);
if Assigned(lpBuffer) then
begin
try
bi.hwndOwner := hWnd;
bi.pidlRoot := pidlPrograms;
bi.pszDisplayName := lpBuffer;
bi.lpszTitle := PChar(Caption);
bi.ulFlags := BIF_RETURNONLYFSDIRS;
bi.lpfn := nil;
bi.lParam := 0;
pidlBrowse := SHBrowseForFolder(bi);
if (pidlBrowse <> nil) then
if SHGetPathFromIDList(pidlBrowse, lpBuffer) then
Folder := string(lpBuffer);
finally
FreeMemory(lpBuffer);
end;
end
else
result := GetLastError;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FindComputer
// Author :
// Comment :
function FindComputer(hWnd: THandle; Prompt: String; var Computer: String): boolean;
const
BIF_NEWDIALOGSTYLE = $0040;
BIF_USENEWUI = BIF_NEWDIALOGSTYLE or BIF_EDITBOX;
BIF_BROWSEINCLUDEURLS = $0080;
BIF_UAHINT = $0100;
BIF_NONEWFOLDERBUTTON = $0200;
BIF_NOTRANSLATETARGETS = $0400;
BIF_SHAREABLE = $8000;
BFFM_IUNKNOWN = 5;
BFFM_SETOKTEXT = WM_USER + 105; // Unicode only
BFFM_SETEXPANDED = WM_USER + 106; // Unicode only
var
bi : TBrowseInfo;
ca : array[0..MAX_PATH] of char;
pidl, pidlSelected: PItemIDList;
m : IMalloc;
begin
if Failed(SHGetSpecialFolderLocation(hWnd, CSIDL_NETWORK, pidl)) then
begin
result := False;
exit;
end;
try
FillChar(bi, SizeOf(bi), 0);
with bi do
begin
hwndOwner := hWnd;
pidlRoot := pidl;
pszDisplayName := ca;
lpszTitle := PChar(Prompt);
ulFlags := BIF_BROWSEFORCOMPUTER;
end;
pidlSelected := SHBrowseForFolder(bi);
Result := Assigned(pidlSelected);
if Result then
Computer := '\\' + string(ca);
finally
if Succeeded(SHGetMalloc(m)) then
m.Free(pidl);
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FindDomain
// Comment :
function FindDomain(hWnd: THandle; Prompt: String; var Domain: String): boolean;
const
BIF_NEWDIALOGSTYLE = $0040;
BIF_USENEWUI = BIF_NEWDIALOGSTYLE or BIF_EDITBOX;
BIF_BROWSEINCLUDEURLS = $0080;
BIF_UAHINT = $0100;
BIF_NONEWFOLDERBUTTON = $0200;
BIF_NOTRANSLATETARGETS = $0400;
BIF_SHAREABLE = $8000;
BFFM_IUNKNOWN = 5;
BFFM_SETOKTEXT = WM_USER + 105; // Unicode only
BFFM_SETEXPANDED = WM_USER + 106; // Unicode only
var
bi : TBrowseInfo;
ca : array[0..MAX_PATH] of char;
pidl, pidlSelected: PItemIDList;
m : IMalloc;
begin
if Failed(SHGetSpecialFolderLocation(hWnd, CSIDL_NETWORK, pidl)) then
begin
result := False;
exit;
end;
try
FillChar(bi, SizeOf(bi), 0);
with bi do
begin
hwndOwner := hWnd;
pidlRoot := pidl;
pszDisplayName := ca;
lpszTitle := PChar(Prompt);
ulFlags := BIF_DONTGOBELOWDOMAIN;
end;
pidlSelected := SHBrowseForFolder(bi);
Result := Assigned(pidlSelected);
if Result then
Domain := string(ca);
finally
if Succeeded(SHGetMalloc(m)) then
m.Free(pidl);
end;
end;
////////////////////////////////////////////////////////////////////////////////
//// FileTools /////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Procedure : FileExists
// Comment : -
function FileExists(const FileName: string): Boolean;
var
Attr: Cardinal;
begin
Attr := GetFileAttributes(Pointer(Filename));
Result := (Attr <> $FFFFFFFF) and (Attr and FILE_ATTRIBUTE_DIRECTORY = 0);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : DirectoryExists
// Comment : -
function DirectoryExists(const Directory: string): Boolean;
var
Code: Cardinal;
begin
Code := GetFileAttributes(PChar(Directory));
Result := (Code <> $FFFFFFFF) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ExtractFilename
// Comment :
function ExtractFilename(s: string): string;
var
i : integer;
begin
result := s;
for i := length(s) downto 1 do
// Von hinten den Backslash suchen. Wenn gefunden alles ab Backslash kopieren
if s[i] = '\' then
begin
result := copy(s, i + 1, length(s));
// Nach dem ersten Backslash beenden
break;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ExtractFilenameW
// Author : MPö
// Comment :
function ExtractFilenameW(s: WideString): WideString;
var
i : integer;
begin
result := s;
for i := length(s) downto 1 do
// Von hinten den Backslash suchen. Wenn gefunden alles ab Backslash kopieren
if s[i] = '\' then
begin
result := copy(s, i + 1, length(s));
// Nach dem ersten Backslash beenden
break;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ExtractFilepath
// Comment :
function ExtractFilepath(s: string): string;
var
i : integer;
begin
result := s;
for i := length(s) downto 1 do
// Von hinten den Backslash suchen. Wenn gefunden alles bis inkl. Backslash kopieren
if s[i] = '\' then
begin
result := copy(s, 1, i);
// Nach dem ersten Backslash beenden
break;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ExtractFilepathW
// Author : MPö
// Comment :
function ExtractFilepathW(s: WideString): WideString;
var
i : integer;
begin
result := s;
for i := length(s) downto 1 do
// Von hinten den Backslash suchen. Wenn gefunden alles bis inkl. Backslash kopieren
if s[i] = '\' then
begin
result := copy(s, 1, i);
// Nach dem ersten Backslash beenden
break;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : HasBackslash
// Comment : Checks whether path ends with a backslash or not
function HasBackslash(Dir: string): Boolean;
begin
result := False;
if length(Dir) > 0 then
result := Dir[length(Dir)] = '\';
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : DelBackSlash
// Comment : Removes the last backslash of a path
function DelBackSlash(Dir: string): string;
begin
result := Dir;
if (length(dir) > 0) and (Dir[length(Dir)] = '\') then
SetLength(Result, Length(Result) - 1);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ForceDirectories
// Comment : Creates directories and its subdirectories
function ForceDirectories(Dir: string): Boolean;
begin
Result := True;
if Length(Dir) = 0 then
exit;
if HasBackslash(Dir) then
Dir := DelBackSlash(Dir);
if (Length(Dir) < 3) or DirectoryExists(Dir)
or (ExtractFilePath(Dir) = Dir) then
Exit; // avoid 'xyz:\' problem.
Result := ForceDirectories(ExtractFilePath(Dir)) and CreateDirectory(PChar(Dir), nil);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ChangeFileExt
// Comment : Changes the file extension
function ChangeFileExt(const szFilename, szNewExt: string): string;
var
rpos : integer;
begin
rpos := length(szFilename);
if (pos('.', szFilename) > 0) then
while (szFilename[rpos] <> '.') and (rpos > 0) do
dec(rpos);
Result := copy(szFilename, 1, rpos - 1) + szNewExt;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetFileSize
// Comment : Returns the filesize
function GetFileSize(Filename: String): Int64;
var
fFile : THandle;
wfd : TWIN32FINDDATA;
begin
result := -1;
if not FileExists(Filename) then
exit;
fFile := FindFirstfile(pchar(Filename), wfd);
if fFile = INVALID_HANDLE_VALUE then
exit;
result := (wfd.nFileSizeHigh * (Int64(MAXDWORD) + 1)) + wfd.nFileSizeLow;
windows.FindClose(fFile);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FileCreate
// Author :
// Comment :
function FileCreate(const FileName: string): Integer;
begin
Result := Integer(CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE,
0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0));
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FileOpen
// Comment : Opens a file. Returns its handle
function FileOpen(const FileName: string; Mode: LongWord): Integer;
const
AccessMode : array[0..2] of LongWord = (
GENERIC_READ,
GENERIC_WRITE,
GENERIC_READ or GENERIC_WRITE);
ShareMode : array[0..4] of LongWord = (
0,
0,
FILE_SHARE_READ,
FILE_SHARE_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE);
begin
Result := Integer(CreateFile(PChar(FileName), AccessMode[Mode and 3],
ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0));
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FileSeek
// Comment : Positions the filepointer
function FileSeek(Handle, Offset, Origin: Integer): Integer;
begin
Result := SetFilePointer(THandle(Handle), Offset, nil, Origin);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FileRead
// Comment : Reads the given amount of bytes into a buffer
function FileRead(Handle: Integer; var Buffer; Count: LongWord): Integer;
begin
if not ReadFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then
Result := -1;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FileWrite
// Comment : Writes the buffer into the file
function FileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer;
begin
if not WriteFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then
Result := -1;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : FileClose
// Comment : Closes the file handle open with FileOpen
procedure FileClose(Handle: Integer);
begin
CloseHandle(THandle(Handle));
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : putbinrestohdd
// Comment : Writes a binary resource to HDD
function putbinrestohdd(binresname, path: string): Boolean;
var
hi, hg, ResSize,
SizeWritten, hFile: cardinal;
begin
result := false;
hi := FindResource(hInstance, @binresname[1], 'BINRES');
if hi <> 0 then
begin
hg := LoadResource(hInstance, hi);
if hg <> 0 then
begin
ResSize := SizeofResource(hInstance, hi);
hFile := CreateFile(@path[1], GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE, nil, CREATE_ALWAYS,
FILE_ATTRIBUTE_ARCHIVE, 0);
if hFile <> INVALID_HANDLE_VALUE then
try
result := (WriteFile(hFile, LockResource(HG)^, ResSize,
SizeWritten, nil) and (SizeWritten = ResSize));
finally
CloseHandle(hFile);
end;
end;
end;
end;
function GetSystemFont: TLogFont;
begin
GetObject(GetStockObject(DEFAULT_GUI_FONT), sizeof(Result), @Result);
end;
function GetSystemFontName: WideString;
var
ncMetrics: TNonClientMetricsW;
begin
ncMetrics.cbSize := SizeOf(TNonClientMetricsW);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, SizeOf(TNonClientMetricsW), @ncMetrics, 0);
//Result := ncMetrics.
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetFileVersion
// Comment :
function GetFileVersion(const Filename: string): string;
type
PDWORDArr = ^DWORDArr;
DWORDArr = array[0..0] of DWORD;
var
VerInfoSize : DWORD;
VerInfo : Pointer;
VerValueSize : DWORD;
VerValue : PVSFixedFileInfo;
LangID : DWORD;
begin
result := '';
VerInfoSize := GetFileVersionInfoSize(PChar(Filename), LangID);
if VerInfoSize <> 0 then
begin
VerInfo := Pointer(GlobalAlloc(GPTR, VerInfoSize));
if Assigned(VerInfo) then
try
if GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo) then
begin
if VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize) then
begin
with VerValue^ do
begin
result := Format('%d.%d.%d.%d', [dwFileVersionMS shr 16, dwFileVersionMS and $FFFF,
dwFileVersionLS shr 16, dwFileVersionLS and $FFFF]);
end;
end
else
result := '';
end;
finally
GlobalFree(THandle(VerInfo));
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetImageLinkTimeStamp
// Author : NBe
// Comment : Get the 'link time stamp' of an portable executable image file (PE32)
// (written for Delphi 5, some types missing in Windows.pas of Delphi 4)
function GetImageLinkTimeStamp(const FileName: string): DWORD;
const
INVALID_SET_FILE_POINTER = DWORD(-1);
BorlandMagicTimeStamp = $2A425E19; // Delphi 4-6 (and above?)
FileTime1970 : TFileTime = (dwLowDateTime: $D53E8000; dwHighDateTime: $019DB1DE);
type
PImageSectionHeaders = ^TImageSectionHeaders;
TImageSectionHeaders = array[Word] of TImageSectionHeader;
type
PImageResourceDirectory = ^TImageResourceDirectory;
TImageResourceDirectory = packed record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
NumberOfNamedEntries: Word;
NumberOfIdEntries: Word;
end;
var
FileHandle : THandle;
BytesRead : DWORD;
ImageDosHeader : TImageDosHeader;
ImageNtHeaders : TImageNtHeaders;
SectionHeaders : PImageSectionHeaders;
Section : Word;
ResDirRVA : DWORD;
ResDirSize : DWORD;
ResDirRaw : DWORD;
ResDirTable : TImageResourceDirectory;
FileTime : TFileTime;
begin
Result := 0;
// Open file for read access
FileHandle := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil,
OPEN_EXISTING, 0, 0);
if (FileHandle <> INVALID_HANDLE_VALUE) then
try
// Read MS-DOS header to get the offset of the PE32 header
// (not required on WinNT based systems - but mostly available)
if not ReadFile(FileHandle, ImageDosHeader, SizeOf(TImageDosHeader),
BytesRead, nil) or (BytesRead <> SizeOf(TImageDosHeader)) or
(ImageDosHeader.e_magic <> IMAGE_DOS_SIGNATURE) then
begin
ImageDosHeader._lfanew := 0;
end;
// Read PE32 header (including optional header
if (SetFilePointer(FileHandle, ImageDosHeader._lfanew, nil, FILE_BEGIN) =
INVALID_SET_FILE_POINTER) then
begin
Exit;
end;
if not (ReadFile(FileHandle, ImageNtHeaders, SizeOf(TImageNtHeaders),
BytesRead, nil) and (BytesRead = SizeOf(TImageNtHeaders))) then
begin
Exit;
end;
// Validate PE32 image header
if (ImageNtHeaders.Signature <> IMAGE_NT_SIGNATURE) then
begin
Exit;
end;
// Seconds since 1970 (UTC)
Result := ImageNtHeaders.FileHeader.TimeDateStamp;
// Check for Borland's magic value for the link time stamp
// (we take the time stamp from the resource directory table)
if (ImageNtHeaders.FileHeader.TimeDateStamp = BorlandMagicTimeStamp) then
with ImageNtHeaders, FileHeader, OptionalHeader do
begin
// Validate Optional header
if (SizeOfOptionalHeader < IMAGE_SIZEOF_NT_OPTIONAL_HEADER) or
(Magic <> IMAGE_NT_OPTIONAL_HDR_MAGIC) then
begin
Exit;
end;
// Read section headers
SectionHeaders :=
GetMemory(NumberOfSections * SizeOf(TImageSectionHeader));
if Assigned(SectionHeaders) then
try
if (SetFilePointer(FileHandle,
SizeOfOptionalHeader - IMAGE_SIZEOF_NT_OPTIONAL_HEADER, nil,
FILE_CURRENT) = INVALID_SET_FILE_POINTER) then
begin
Exit;
end;
if not (ReadFile(FileHandle, SectionHeaders^, NumberOfSections *
SizeOf(TImageSectionHeader), BytesRead, nil) and (BytesRead =
NumberOfSections * SizeOf(TImageSectionHeader))) then
begin
Exit;
end;
// Get RVA and size of the resource directory
with DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE] do
begin
ResDirRVA := VirtualAddress;
ResDirSize := Size;
end;
// Search for section which contains the resource directory
ResDirRaw := 0;
for Section := 0 to NumberOfSections - 1 do
with SectionHeaders[Section] do
if (VirtualAddress <= ResDirRVA) and
(VirtualAddress + SizeOfRawData >= ResDirRVA + ResDirSize) then
begin
ResDirRaw := PointerToRawData - (VirtualAddress - ResDirRVA);
Break;
end;
// Resource directory table found?
if (ResDirRaw = 0) then
begin
Exit;
end;
// Read resource directory table
if (SetFilePointer(FileHandle, ResDirRaw, nil, FILE_BEGIN) =
INVALID_SET_FILE_POINTER) then
begin
Exit;
end;
if not (ReadFile(FileHandle, ResDirTable,
SizeOf(TImageResourceDirectory), BytesRead, nil) and
(BytesRead = SizeOf(TImageResourceDirectory))) then
begin
Exit;
end;
// Convert from DosDateTime to SecondsSince1970
if DosDateTimeToFileTime(HiWord(ResDirTable.TimeDateStamp),
LoWord(ResDirTable.TimeDateStamp), FileTime) then
begin
// FIXME: Borland's linker uses the local system time
// of the user who linked the executable image file.
// (is that information anywhere?)
Result := (ULARGE_INTEGER(FileTime).QuadPart -
ULARGE_INTEGER(FileTime1970).QuadPart) div 10000000;
end;
finally
FreeMemory(SectionHeaders);
end;
end;
finally
CloseHandle(FileHandle);
end;
end;
////////////////////////////////////////////////////////////////////////////////
//// GUITools //////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Procedure : ShowHelpText
// Author :
// Comment :
procedure ShowHelpText(hLib: THandle; wParam: WPARAM; lParam: LPARAM; hSB: HWND);
var
bla : array of Cardinal;
begin
if BOOL(HIWORD(wParam) and MF_POPUP) or
BOOL(HIWORD(wParam) and MF_SEPARATOR) or
(HIWORD(wParam) = $FFFF) {// leave menu} then
SendMessage(hSB, SB_SIMPLE, 0, 0)
else
MenuHelp(WM_MENUSELECT, wParam, lParam, HMENU(lParam), hLib, hSB, @bla);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : CreateToolTips
// Comment : Creates a Tooltip-Window
function CreateToolTips(hWnd: Cardinal; bBalloon: Boolean = False): Boolean;
const
TTF_PARSELINKS = $1000;
var
Styles : DWORD;
begin
Styles := TTS_ALWAYSTIP;
if bBalloon then
Styles := Styles or TTS_BALLOON;
result := False;
hToolTip := CreateWindowEx(0, 'Tooltips_Class32', nil, Styles,
Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT),
Integer(CW_USEDEFAULT), hWnd, 0, hInstance, nil);
if hToolTip <> 0 then
begin
SetWindowPos(hToolTip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or
SWP_NOSIZE or SWP_NOACTIVATE);
ti.cbSize := SizeOf(TToolInfo);
ti.uFlags := TTF_SUBCLASS or TTF_PARSELINKS;
ti.hInst := hInstance;
result := True;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : AddToolTip
// Comment : Adds a tooltip to a window
procedure AddToolTip(hwnd, id: Cardinal; ti: PToolInfo; Text: String; Caption: String = ''; IDIcon: DWORD = 0);
const
TTM_SETTITLE = WM_USER + 32;
var
Item : THandle;
Rect : TRect;
begin
Item := GetDlgItem(hWnd, id);
if (Item <> 0) and (GetClientRect(Item, Rect)) then
begin
//ZeroMemory(@ti, sizeof(TToolInfo));
ti.hwnd := Item;
ti.Rect := Rect;
ti.lpszText := PChar(Text);
SendMessage(hToolTip, TTM_ADDTOOL, 0, Integer(ti));
SendMessage(hToolTip, TTM_SETTITLE, IDIcon, Integer(@Caption[1]));
end;
end;
////////////////////////////////////////////////////////////////////////////////
//// WinTools //////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetWinDir
// Comment : Returns the Windows directory
function GetWinDir(): string;
begin
SetLength(Result, MAX_PATH + 1);
SetLength(Result, GetWindowsDirectory(PChar(Result), MAX_PATH));
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ComputerName
// Comment : Returns the computername
function GetCompName: string;
var
Buf : array[0..MAX_COMPUTERNAME_LENGTH] of Char;
Size : DWORD;
begin
Size := SizeOf(Buf);
if GetComputerName(Buf, Size) then
Result := Buf
else
Result := '';
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : ExpandEnvStr
// Comment : Mathias Simmack
function ExpandEnvStr(const szInput: string): string;
const
MAXSIZE = 32768;
begin
SetLength(Result,MAXSIZE);
SetLength(Result,ExpandEnvironmentStrings(pchar(szInput),
@Result[1],length(Result)));
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : UserName
// Comment : Returns the name of the currently loggon user
function GetCurrUserName: string;
var
Size : DWORD;
begin
Size := MAX_COMPUTERNAME_LENGTH + 1;
SetLength(Result, Size);
if GetUserName(PChar(Result), Size) then
SetLength(Result, Size)
else
Result := '';
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetSysDir
// Comment : Returns the System directory
function GetSysDir(): string;
begin
SetLength(Result, MAX_PATH + 1);
SetLength(Result, GetSystemDirectory(PChar(Result), MAX_PATH));
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetOSLanguageID
// Comment : Returns the language of the OS
function GetOSLanguageStr: string;
begin
SetLength(Result, MAX_PATH);
SetLength(Result, VerLanguageName(GetSystemDefaultLangId,
@Result[1], length(Result)));
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetOSLanguageStr
// Comment : Returns the language ID-String
function GetOSLanguageIDStr: string;
var
Buffer : array[0..MAX_PATH] of char;
len : Integer;
begin
ZeroMemory(@Buffer, sizeof(Buffer));
len := GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SABBREVLANGNAME, Buffer,
sizeof(Buffer));
SetString(result, Buffer, len);
end;
////////////////////////////////////////////////////////////////////////////////
// GetShellFolder
// Returns the special shell folders
// uses: ActiveX, ShlObj;
function GetShellFolder(CSIDL: integer): string;
var
pidl : PItemIdList;
FolderPath : string;
SystemFolder : Integer;
Malloc : IMalloc;
begin
Malloc := nil;
FolderPath := '';
SHGetMalloc(Malloc);
if Malloc = nil then
begin
Result := FolderPath;
Exit;
end;
try
SystemFolder := CSIDL;
if SUCCEEDED(SHGetSpecialFolderLocation(0, SystemFolder, pidl)) then
begin
SetLength(FolderPath, max_path);
if SHGetPathFromIDList(pidl, PChar(FolderPath)) then
begin
SetLength(FolderPath, length(PChar(FolderPath)));
end;
end;
Result := FolderPath;
finally
Malloc.Free(pidl);
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetAdminSid
// Author : NBe
// Comment :
function GetAdminSid: PSID;
const
// bekannte SIDs ... (WinNT.h)
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
// bekannte RIDs ... (WinNT.h)
SECURITY_BUILTIN_DOMAIN_RID: DWORD = $00000020;
DOMAIN_ALIAS_RID_ADMINS: DWORD = $00000220;
begin
Result := nil;
AllocateAndInitializeSid(SECURITY_NT_AUTHORITY, 2,
SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0, Result);
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : IsAdmin
// Author : NBe
// Comment :
function IsAdmin: LongBool;
var
TokenHandle : THandle;
ReturnLength : DWORD;
TokenInformation : PTokenGroups;
AdminSid : PSID;
Loop : Integer;
begin
Result := False;
TokenHandle := 0;
if OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, TokenHandle) then
try
ReturnLength := 0;
GetTokenInformation(TokenHandle, TokenGroups, nil, 0, ReturnLength);
TokenInformation := GetMemory(ReturnLength);
if Assigned(TokenInformation) then
try
if GetTokenInformation(TokenHandle, TokenGroups, TokenInformation,
ReturnLength, ReturnLength) then
begin
AdminSid := GetAdminSid;
for Loop := 0 to TokenInformation^.GroupCount - 1 do
begin
if EqualSid(TokenInformation^.Groups[Loop].Sid, AdminSid) then
begin
Result := True;
Break;
end;
end;
FreeSid(AdminSid);
end;
finally
FreeMemory(TokenInformation);
end;
finally
CloseHandle(TokenHandle);
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetOSVersionInfo
// Author : NBe
// Comment :
function GetOSVersionInfo(var Info: TOSVersionInfoEx): Boolean;
begin
FillChar(Info, SizeOf(TOSVersionInfoEx), 0);
Info.dwOSVersionInfoSize := SizeOf(TOSVersionInfoEx);
Result := GetVersionEx(TOSVersionInfo(Addr(Info)^));
if (not Result) then
begin
FillChar(Info, SizeOf(TOSVersionInfoEx), 0);
Info.dwOSVersionInfoSize := SizeOf(TOSVersionInfoEx);
Result := GetVersionEx(TOSVersionInfo(Addr(Info)^));
if (not Result) then
Info.dwOSVersionInfoSize := 0;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : GetOSVersionText
// Author : NBe
// Comment :
function GetOSVersionText: string;
var
Info : TOSVersionInfoEx;
Key : HKEY;
begin
Result := '';
if (not GetOSVersionInfo(Info)) then
Exit;
case Info.dwPlatformId of
{ Win32s }
VER_PLATFORM_WIN32s:
Result := 'Microsoft Win32s';
{ Windows 9x }
VER_PLATFORM_WIN32_WINDOWS:
if (Info.dwMajorVersion = 4) and (Info.dwMinorVersion = 0) then
begin
Result := 'Microsoft Windows 95';
if (Info.szCSDVersion[1] in ['B', 'C']) then
Result := Result + ' OSR2';
end
else if (Info.dwMajorVersion = 4) and (Info.dwMinorVersion = 10) then
begin
Result := 'Microsoft Windows 98';
if (Info.szCSDVersion[1] = 'A') then
Result := Result + ' SE';
end
else if (Info.dwMajorVersion = 4) and (Info.dwMinorVersion = 90) then
Result := 'Microsoft Windows Millennium Edition';
{ Windows NT }
VER_PLATFORM_WIN32_NT:
begin
{ Version }
if (Info.dwMajorVersion = 5) and (Info.dwMinorVersion = 2) then
Result := 'Microsoft Windows Server 2003'
else if (Info.dwMajorVersion = 5) and (Info.dwMinorVersion = 1) then
Result := 'Microsoft Windows XP'
else if (Info.dwMajorVersion = 5) and (Info.dwMinorVersion = 0) then
Result := 'Microsoft Windows 2000'
else
Result := 'Microsoft Windows NT';
{ Extended }
if (Info.dwOSVersionInfoSize >= SizeOf(TOSVersionInfoEx)) then
begin
{ ProductType }
if (Info.wProductType = VER_NT_WORKSTATION) then
begin
if (Info.dwMajorVersion = 4) then
Result := Result + #10'Workstation 4.0'
else if (Info.wSuiteMask and VER_SUITE_PERSONAL <> 0) then
Result := Result + #10'Home Edition'
else
Result := Result + #10'Professional';
end
else if (Info.wProductType = VER_NT_SERVER) then
begin
if (Info.dwMajorVersion = 5) and (Info.dwMinorVersion = 2) then
begin
if (Info.wSuiteMask and VER_SUITE_DATACENTER <> 0) then
Result := Result + #10'Datacenter Edition'
else if (Info.wSuiteMask and VER_SUITE_ENTERPRISE <> 0) then
Result := Result + #10'Enterprise Edition'
else if (Info.wSuiteMask = VER_SUITE_BLADE) then
Result := Result + #10'Web Edition'
else
Result := Result + #10'Standard Edition';
end
else if (Info.dwMajorVersion = 5) and (Info.dwMinorVersion = 0) then
begin
if (Info.wSuiteMask and VER_SUITE_DATACENTER <> 0) then
Result := Result + #10'Datacenter Server'
else if (Info.wSuiteMask and VER_SUITE_ENTERPRISE <> 0) then
Result := Result + #10'Advanced Server'
else
Result := Result + #10'Server';
end
else
begin
Result := Result + #10'Server ' +
IntToStr(Info.dwMajorVersion) + '.' +
IntToStr(Info.dwMinorVersion);
if (Info.wSuiteMask and VER_SUITE_ENTERPRISE <> 0) then
Result := Result + ', Enterprise Edition';
end;
end;
end;
{ CSDVersion }
if (Info.dwMajorVersion = 4) and
(StrIComp(Info.szCSDVersion, 'Service Pack 6') = 0) and
(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Hotfix\Q246009', 0,
KEY_QUERY_VALUE, Key) = ERROR_SUCCESS) then
begin
Result := Result + #10'Service Pack 6a';
RegCloseKey(Key);
end
else
Result := Result + #10 + string(Info.szCSDVersion);
Result := Result + #10'(Build ' +
IntToStr(Info.dwBuildNumber and $FFFF) + ')';
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : EnablePrivilege
// Author :
// Comment :
function EnablePrivilege(const Privilege: string; fEnable: Boolean; out PreviousState: Boolean): DWORD;
var
Token : THandle;
NewState : TTokenPrivileges;
Luid : TLargeInteger;
PrevState : TTokenPrivileges;
Return : DWORD;
begin
PreviousState := True;
if (GetVersion() > $80000000) then
// Win9x
Result := ERROR_SUCCESS
else
begin
// WinNT
if not OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, Token) then
Result := GetLastError()
else
try
if not LookupPrivilegeValue(nil, PChar(Privilege), Luid) then
Result := GetLastError()
else
begin
NewState.PrivilegeCount := 1;
NewState.Privileges[0].Luid := Luid;
if fEnable then
NewState.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED
else
NewState.Privileges[0].Attributes := 0;
if not AdjustTokenPrivileges(Token, False, NewState,
SizeOf(TTokenPrivileges), PrevState, Return) then
Result := GetLastError()
else
begin
Result := ERROR_SUCCESS;
PreviousState :=
(PrevState.Privileges[0].Attributes and SE_PRIVILEGE_ENABLED <> 0);
end;
end;
finally
CloseHandle(Token);
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
// Procedure : Min
// Author :
// Comment :
function Min(x, y: Cardinal): Integer;
begin
if x < y then
result := x
else
result := y;
end;
end.
|
unit FieldLogReportMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Rtti,
FMX.Grid.Style, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Fmx.Bind.Grid,
System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Controls, FMX.Layouts,
Fmx.Bind.Navigator, Data.Bind.Components, Data.Bind.Grid, Data.Bind.DBScope,
FMX.ScrollBox, FMX.Grid, FMX.Controls.Presentation, FMX.Edit, FMX.TabControl,
FMX.StdCtrls, FMX.WebBrowser, FMX.Memo, FMX.Objects,
System.Sensors, Generics.Collections;
type
TForm53 = class(TForm)
TabControl1: TTabControl;
TabItem1: TTabItem;
TabItem2: TTabItem;
TabItem3: TTabItem;
Edit1: TEdit;
Grid1: TGrid;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource;
Grid2: TGrid;
BindSourceDB2: TBindSourceDB;
LinkGridToDataSourceBindSourceDB2: TLinkGridToDataSource;
NavigatorBindSourceDB1: TBindNavigator;
NavigatorBindSourceDB2: TBindNavigator;
Memo1: TMemo;
WebBrowser1: TWebBrowser;
Button3: TButton;
Layout1: TLayout;
Image1: TImage;
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FGeocoders: TObjectList<TGeocoder>;
html: TStringList;
procedure OnGeocodeReverseEvent(const Address: TCivicAddress);
procedure ReverseLocation(Lat, Long: double);
public
{ Public declarations }
end;
var
Form53: TForm53;
implementation
{$R *.fmx}
uses
IOUtils, FMX.Surfaces, FieldLogReportDM, System.NetEncoding, Data.DB,
{$IFDEF ANDROID}
Androidapi.JNI.Os, Androidapi.JNI.JavaTypes, Androidapi.Helpers,
System.Android.Sensors;
{$ENDIF ANDROID}
{$IFDEF IOS}
System.iOS.Sensors;
{$ENDIF IOS}
{$IFDEF MACOS}
System.Mac.Sensors;
{$ENDIF MACOS}
{$IFDEF MSWINDOWS}
System.Win.Sensors;
{$ENDIF}
{$REGION 'stale code'}
{
// Based on code by Dave Nottage, Embarcadero MVP - delphiworlds.com
function BitmapAsBase64(const ABitmap: TBitmap): string; overload;
var
LInputStream: TBytesStream;
LOutputStream: TStringStream;
begin
Result := '';
if not(assigned(ABitmap)) or ABitmap.IsEmpty then
Exit;
LInputStream := TBytesStream.Create;
try
ABitmap.SaveToStream(LInputStream);
LInputStream.Position := 0;
LOutputStream := TStringStream.Create('');
try
TNetEncoding.Base64.Encode(LInputStream, LOutputStream);
Result := LOutputStream.DataString;
finally
LOutputStream.Free;
end;
finally
LInputStream.Free;
end;
end;
function GetAsBase64(const ABitmap: TBitmap): string; overload;
var
LInputStream: TBytesStream;
LOutputStream: TStringStream;
begin
Result := '';
if not(assigned(ABitmap)) or ABitmap.IsEmpty then Exit;
LInputStream := TBytesStream.Create;
try
ABitmap.SaveToStream(LInputStream);
LInputStream.Position := 0;
LOutputStream := TStringStream.Create('');
try
TNetEncoding.Base64.Encode(LInputStream, LOutputStream);
Result := LOutputStream.DataString;
finally
LOutputStream.DisposeOf;
end;
finally
LInputStream.DisposeOf;
end;
end;
procedure LoadJPEGSteam(bitmap: TBitmap; mem: TMemoryStream);
var
surface: TBitmapSurface;
begin
surface := TBitmapSurface.Create;
try
Surface.Assign(bitmap);
TBitmapCodecManager.SaveToStream(mem, Surface, 'jpg');
finally
Surface.DisposeOf;
end;
mem.Position := 0;
end;
procedure DisplayJPEGStream(bitmap: TBitmap; mem: TMemoryStream);
var
img: TBitmap;
begin
img := TBitmap.Create;
try
mem.Position := 0;
img.LoadFromStream(mem);
Bitmap.SetSize(img.Width, img.Height);
Bitmap.Canvas.BeginScene;
try
Bitmap.Canvas.DrawBitmap(img, img.BoundsF, bitmap.BoundsF, 1);
finally
Bitmap.Canvas.EndScene;
end;
finally
img.DisposeOf;
end;
mem.Position := 0;
end;
}
{$ENDREGION}
procedure TForm53.OnGeocodeReverseEvent(const Address: TCivicAddress);
begin
ShowMessage('test');
{
lblSubThoroughfare.Text := Address.SubThoroughfare;
lblThoroughfare.Text := Address.Thoroughfare;
lblSubLocality.Text := Address.SubLocality;
lblSubAdminArea.Text := Address.SubAdminArea;
lblZipCode.Text := Address.PostalCode;
lblLocality.Text := Address.Locality;
lblFeature.Text := Address.FeatureName;
lblCountry.Text := Address.CountryName;
lblCountryCode.Text := Address.CountryCode;
lblAdminArea.Text := Address.AdminArea;
}
end;
procedure TForm53.ReverseLocation( Lat, Long: double );
var
Geocoder: TGeocoder;
begin
// Setup an instance of TGeocoder
Geocoder := FGeocoders.Items[ FGeocoders.Add( TGeocoder.Current.Create )];
if not Geocoder.Supported then
Exception.Create('Not supported.');
Geocoder.OnGeocodeReverse := OnGeocodeReverseEvent;
// Translate location to address
Geocoder.GeocodeReverse(TLocationCoord2D.Create(Lat, Long));
for Geocoder in FGeocoders do
begin
if Geocoder.Geocoding then
ShowMessage('Geocoding!');
end;
end;
procedure TForm53.Button3Click(Sender: TObject);
var
jpegBytes: TByteDynArray;
begin
html := TStringList.Create;
try
html.BeginUpdate;
try
html.Add(format('<html><head><title>%s</title></head><body>',
[TNetEncoding.HTML.Encode(dmFieldLogger.qProjectsPROJ_TITLE.Value)]));
html.Add(format('<strong>Project</strong><h1>%s</h1><p><strong>Description:</strong>%s</p>',
[TNetEncoding.HTML.Encode(dmFieldLogger.qProjectsPROJ_TITLE.Value),
TNetEncoding.HTML.Encode(dmFieldLogger.qProjectsPROJ_DESC.Value)]));
html.Add('<p><strong>Log Entries:</strong></p>');
{
dmFieldLogger.qLogEntries.First;
while not dmFieldLogger.qLogEntries.Eof do
begin
ReverseLocation(
dmFieldLogger.qLogEntriesLATITUDE.Value,
dmFieldLogger.qLogEntriesLONGITUDE.Value);
dmFieldLogger.qLogEntries.Next;
end;
}
dmFieldLogger.qLogEntries.First;
while not dmFieldLogger.qLogEntries.Eof do
begin
jpegBytes := ResizeJpegField(dmFieldLogger.qLogEntriesPICTURE, 512);
html.Add(format('<h2>%s</h2><p>%s</p>'+
'<img src="data:image/jpg;base64,%s" alt="%s" />',
[DateTimeToStr(dmFieldLogger.qLogEntriesTIMEDATESTAMP.AsDateTime),
TNetEncoding.HTML.Encode(dmFieldLogger.qLogEntriesNOTE.Value),
TNetEncoding.Base64.EncodeBytesToString(jpegBytes),
DateTimeToStr(dmFieldLogger.qLogEntriesTIMEDATESTAMP.AsDateTime)]));
html.Add('<table>');
html.Add(format('<tr><td>Lat, Long:</td><td>%f, %f</td></tr>',
[dmFieldLogger.qLogEntriesLATITUDE.Value,dmFieldLogger.qLogEntriesLONGITUDE.Value]));
html.Add(format('<tr><td>Orentation:</td><td>%f, %f, %f</td></tr>',
[dmFieldLogger.qLogEntriesOR_X.Value,dmFieldLogger.qLogEntriesOR_Y.Value,dmFieldLogger.qLogEntriesOR_Z.Value]));
html.Add(format('<tr><td>Heading:</td><td>%f, %f, %f</td></tr>',
[dmFieldLogger.qLogEntriesHEADING_X.Value, dmFieldLogger.qLogEntriesHEADING_Y.Value, dmFieldLogger.qLogEntriesHEADING_Z.Value]));
html.Add(format('<tr><td>Velocity:</td><td>%f, %f, %f</td></tr>',
[dmFieldLogger.qLogEntriesV_X.Value, dmFieldLogger.qLogEntriesV_Y.Value, dmFieldLogger.qLogEntriesV_Z.Value]));
html.Add(format('<tr><td>Angle:</td><td>%f, %f, %f</td></tr>',
[dmFieldLogger.qLogEntriesANGLE_X.Value, dmFieldLogger.qLogEntriesANGLE_Y.Value, dmFieldLogger.qLogEntriesANGLE_Z.Value]));
html.Add(format('<tr><td>Motion:</td><td>%f</td></tr>',[dmFieldLogger.qLogEntriesMOTION.Value]));
html.Add(format('<tr><td>Speed:</td><td>%f</td></tr>',[dmFieldLogger.qLogEntriesSPEED.Value]));
html.Add('</table><hr>');
dmFieldLogger.qLogEntries.Next;
end;
html.Add('</body></html>');
WebBrowser1.LoadFromStrings(html.Text, 'about:blank');
memo1.Text := html.Text;
finally
Memo1.EndUpdate;
end;
finally
html.free;
end;
end;
procedure TForm53.FormCreate(Sender: TObject);
begin
FGeocoders := TObjectList<TGeocoder>.Create;
end;
procedure TForm53.FormDestroy(Sender: TObject);
begin
FGeocoders.Free;
end;
end.
|
unit Pessoa;
interface
uses
MVCFramework.Serializer.Commons, ModelBase, Generics.Collections, System.SysUtils,
PessoaFisica, PessoaJuridica, PessoaContato, PessoaTelefone, PessoaEndereco;
type
[MVCNameCase(ncLowerCase)]
TPessoa = class(TModelBase)
private
FID: Integer;
FNOME: string;
FTIPO: string;
FSITE: string;
FEMAIL: string;
FCLIENTE: string;
FFORNECEDOR: string;
FTRANSPORTADORA: string;
FCOLABORADOR: string;
FCONTADOR: string;
FPessoaFisica: TPessoaFisica;
FPessoaJuridica: TPessoaJuridica;
FListaPessoaContato: TObjectList<TPessoaContato>;
FListaPessoaEndereco: TObjectList<TPessoaEndereco>;
FListaPessoaTelefone: TObjectList<TPessoaTelefone>;
public
procedure ValidarInsercao; override;
procedure ValidarAlteracao; override;
procedure ValidarExclusao; override;
constructor Create; virtual;
destructor Destroy; override;
[MVCColumnAttribute('ID', True)]
[MVCNameAsAttribute('id')]
property Id: Integer read FID write FID;
[MVCColumnAttribute('NOME')]
[MVCNameAsAttribute('nome')]
property Nome: string read FNOME write FNOME;
[MVCColumnAttribute('TIPO')]
[MVCNameAsAttribute('tipo')]
property Tipo: string read FTIPO write FTIPO;
[MVCColumnAttribute('SITE')]
[MVCNameAsAttribute('site')]
property Site: string read FSITE write FSITE;
[MVCColumnAttribute('EMAIL')]
[MVCNameAsAttribute('email')]
property Email: string read FEMAIL write FEMAIL;
[MVCColumnAttribute('CLIENTE')]
[MVCNameAsAttribute('cliente')]
property Cliente: string read FCLIENTE write FCLIENTE;
[MVCColumnAttribute('FORNECEDOR')]
[MVCNameAsAttribute('fornecedor')]
property Fornecedor: string read FFORNECEDOR write FFORNECEDOR;
[MVCColumnAttribute('TRANSPORTADORA')]
[MVCNameAsAttribute('transportadora')]
property Transportadora: string read FTRANSPORTADORA write FTRANSPORTADORA;
[MVCColumnAttribute('COLABORADOR')]
[MVCNameAsAttribute('colaborador')]
property Colaborador: string read FCOLABORADOR write FCOLABORADOR;
[MVCColumnAttribute('CONTADOR')]
[MVCNameAsAttribute('contador')]
property Contador: string read FCONTADOR write FCONTADOR;
// objetos vinculados
[MVCNameAsAttribute('pessoaFisica')]
property PessoaFisica: TPessoaFisica read FPessoaFisica write FPessoaFisica;
[MVCNameAsAttribute('pessoaJuridica')]
property PessoaJuridica: TPessoaJuridica read FPessoaJuridica write FPessoaJuridica;
[MapperListOf(TPessoaContato)]
[MVCNameAsAttribute('listaPessoaContato')]
property ListaPessoaContato: TObjectList<TPessoaContato> read FListaPessoaContato write FListaPessoaContato;
[MapperListOf(TPessoaTelefone)]
[MVCNameAsAttribute('listaPessoaTelefone')]
property ListaPessoaTelefone: TObjectList<TPessoaTelefone> read FListaPessoaTelefone write FListaPessoaTelefone;
[MapperListOf(TPessoaEndereco)]
[MVCNameAsAttribute('listaPessoaEndereco')]
property ListaPessoaEndereco: TObjectList<TPessoaEndereco> read FListaPessoaEndereco write FListaPessoaEndereco;
end;
implementation
{ TPessoa }
constructor TPessoa.Create;
begin
FPessoaFisica := TPessoaFisica.Create;
FPessoaJuridica := TPessoaJuridica.Create;
//
FListaPessoaContato := TObjectList<TPessoaContato>.Create;
FListaPessoaEndereco := TObjectList<TPessoaEndereco>.Create;
FListaPessoaTelefone := TObjectList<TPessoaTelefone>.Create;
end;
destructor TPessoa.Destroy;
begin
FreeAndNil(FListaPessoaContato);
FreeAndNil(FListaPessoaEndereco);
FreeAndNil(FListaPessoaTelefone);
//
FreeAndNil(FPessoaFisica);
FreeAndNil(FPessoaJuridica);
inherited;
end;
procedure TPessoa.ValidarInsercao;
begin
inherited;
end;
procedure TPessoa.ValidarAlteracao;
begin
inherited;
end;
procedure TPessoa.ValidarExclusao;
begin
inherited;
end;
end.
|
unit UnitDemoSceneRaycastVehicle;
{$MODE Delphi}
interface
uses LCLIntf,LCLType,LMessages,SysUtils,Classes,Math,Kraft,KraftArcadeCarPhysics,UnitDemoScene,gl,glext;
type { TDemoSceneRaycastVehicle }
TDemoSceneRaycastVehicle=class(TDemoScene)
public
RigidBodyFloor:TKraftRigidBody;
ShapeFloorPlane:TKraftShapePlane;
Vehicle:TVehicle;
CarSteering:double;
CarSpeed:double;
Time:double;
InputKeyLeft,InputKeyRight,InputKeyUp,InputKeyDown,InputKeyBrake,InputKeyHandBrake:boolean;
constructor Create(const aKraftPhysics:TKraft); override;
destructor Destroy; override;
procedure Step(const DeltaTime:double); override;
procedure DebugDraw; override;
function HasOwnKeyboardControls:boolean; override;
procedure KeyDown(const aKey:Int32); override;
procedure KeyUp(const aKey:Int32); override;
function UpdateCamera(var aCameraPosition:TKraftVector3;var aCameraOrientation:TKraftQuaternion):boolean; override;
procedure StoreWorldTransforms; override;
procedure InterpolateWorldTransforms(const aAlpha:TKraftScalar); override;
end;
implementation
uses UnitFormMain;
const CarWidth=1.8;
CarLength=4.40;
CarHeight=1.55;
CarHalfWidth=CarWidth*0.5;
WheelRadius=0.75;
WheelY=-WheelRadius;
ProtectionHeightOffset=4;
CountDominos=64;
CountStreetElevations=64;
JumpingRampWidth=16.0;
JumpingRampHeight=16.0;
JumpingRampLength=64.0;
JumpingRampHalfWidth=JumpingRampWidth*0.5;
JumpingRampHalfHeight=JumpingRampHeight*0.5;
JumpingRampHalfLength=JumpingRampLength*0.5;
JumpingRampConvexHullPoints:array[0..5] of TKraftVector3=((x:-JumpingRampHalfWidth;y:0.0;z:0{$ifdef SIMD};w:0.0{$endif}),
(x:JumpingRampHalfWidth;y:0.0;z:0{$ifdef SIMD};w:0.0{$endif}),
(x:-JumpingRampHalfWidth;y:JumpingRampHeight;z:0.0{$ifdef SIMD};w:0.0{$endif}),
(x:JumpingRampHalfWidth;y:JumpingRampHeight;z:0.0{$ifdef SIMD};w:0.0{$endif}),
(x:-JumpingRampHalfWidth;y:0.0;z:JumpingRampLength{$ifdef SIMD};w:0.0{$endif}),
(x:JumpingRampHalfWidth;y:0.0;z:JumpingRampLength{$ifdef SIMD};w:0.0{$endif}));{}
{ TDemoSceneRaycastVehicle }
constructor TDemoSceneRaycastVehicle.Create(const aKraftPhysics: TKraft);
const Height=10;
var Index,i,j:Int32;
RigidBody:TKraftRigidBody;
Shape:TKraftShape;
ConvexHull:TKraftConvexHull;
begin
inherited Create(AKraftPhysics);
CarSteering:=0.0;
Time:=0.0;
RigidBodyFloor:=TKraftRigidBody.Create(KraftPhysics);
RigidBodyFloor.SetRigidBodyType(krbtSTATIC);
ShapeFloorPlane:=TKraftShapePlane.Create(KraftPhysics,RigidBodyFloor,Plane(Vector3Norm(Vector3(0.0,1.0,0.0)),0.0));
ShapeFloorPlane.Restitution:=0.3;
RigidBodyFloor.Finish;
RigidBodyFloor.SetWorldTransformation(Matrix4x4Translate(0.0,0.0,0.0));
RigidBodyFloor.CollisionGroups:=[0];
begin
ConvexHull:=TKraftConvexHull.Create(KraftPhysics);
ConvexHullGarbageCollector.Add(ConvexHull);
ConvexHull.Load(pointer(@JumpingRampConvexHullPoints),length(JumpingRampConvexHullPoints));
ConvexHull.Build;
ConvexHull.Finish;
for Index:=1 to 4 do begin
RigidBody:=TKraftRigidBody.Create(KraftPhysics);
RigidBody.SetRigidBodyType(krbtSTATIC);
Shape:=TKraftShapeConvexHull.Create(KraftPhysics,RigidBody,ConvexHull);
Shape.Restitution:=0.3;
Shape.Density:=1.0;
RigidBody.Finish;
RigidBody.SetWorldTransformation(Matrix4x4Translate(0.0,0.0,-((JumpingRampLength+(CarLength*2.0)))*Index));
RigidBody.CollisionGroups:=[0];
end;
for Index:=1 to 4 do begin
RigidBody:=TKraftRigidBody.Create(KraftPhysics);
RigidBody.SetRigidBodyType(krbtSTATIC);
Shape:=TKraftShapeConvexHull.Create(KraftPhysics,RigidBody,ConvexHull);
Shape.Restitution:=0.3;
Shape.Density:=1.0;
RigidBody.Finish;
RigidBody.SetWorldTransformation(Matrix4x4TermMul(Matrix4x4RotateY(PI),Matrix4x4Translate(-(JumpingRampWidth+(CarWidth*2.0)),0.0,-((JumpingRampLength+(CarLength*2.0)))*Index)));
RigidBody.CollisionGroups:=[0];
end;
end;
begin
// Dominos
for Index:=0 to CountDominos-1 do begin
RigidBody:=TKraftRigidBody.Create(KraftPhysics);
RigidBody.SetRigidBodyType(krbtDYNAMIC);
Shape:=TKraftShapeBox.Create(KraftPhysics,RigidBody,Vector3(0.125,1.0,0.5));
Shape.Restitution:=0.4;
Shape.Density:=1.0;
RigidBody.ForcedMass:=1.0;
RigidBody.Finish;
RigidBody.SetWorldTransformation(Matrix4x4TermMul(Matrix4x4TermMul(Matrix4x4Translate(0.0,TKraftShapeBox(Shape).Extents.y,-8.0-((Index/CountDominos)*4.0)),Matrix4x4RotateY((Index-((CountDominos-1)*0.5))*(pi/CountDominos)*2.0)),Matrix4x4Translate(JumpingRampWidth+(CarWidth*4),0.0,-12.0)));
RigidBody.CollisionGroups:=[0,1];
// RigidBody.Gravity.Vector:=Vector3(0.0,-9.81*4.0,0.0);
// RigidBody.Flags:=RigidBody.Flags+[krbfHasOwnGravity];
end;
end;//}
begin
// Street elevations
for Index:=0 to CountStreetElevations-1 do begin
RigidBody:=TKraftRigidBody.Create(KraftPhysics);
RigidBody.SetRigidBodyType(krbtSTATIC);
Shape:=TKraftShapeCapsule.Create(KraftPhysics,RigidBody,0.25,16);
Shape.Restitution:=0.4;
Shape.Density:=1.0;
RigidBody.ForcedMass:=1.0;
RigidBody.Finish;
RigidBody.SetWorldTransformation(Matrix4x4TermMul(
Matrix4x4RotateZ(PI*0.5),
Matrix4x4Translate(-(JumpingRampWidth+(CarWidth*4)),0.0,-(12.0+(Index*0.75)))
)
);
RigidBody.CollisionGroups:=[0];
end;
end;//}
begin
// Brick wall
for i:=0 to Height-1 do begin
for j:=0 to Height-1 do begin
if (i+j)>0 then begin
RigidBody:=TKraftRigidBody.Create(KraftPhysics);
RigidBody.SetRigidBodyType(krbtDYNAMIC);
Shape:=TKraftShapeBox.Create(KraftPhysics,RigidBody,Vector3(1.0,0.5,0.25));
Shape.Restitution:=0.4;
Shape.Density:=10.0;
// RigidBody.ForcedMass:=1.0;
RigidBody.Finish;
RigidBody.SetWorldTransformation(Matrix4x4Translate((((j+((i and 1)*0.5))-(Height*0.5))*(TKraftShapeBox(Shape).Extents.x*2.0))-((JumpingRampWidth+(CarWidth*4))*2),TKraftShapeBox(Shape).Extents.y+((Height-(i+1))*(TKraftShapeBox(Shape).Extents.y*2.0)),-8.0));
RigidBody.CollisionGroups:=[0];
RigidBody.SetToSleep;
end;
end;
end;
end; //}
Vehicle:=TVehicle.Create(KraftPhysics);
Vehicle.DownForce:=10.0;
Vehicle.FlightStabilizationForce:=6.0;
Vehicle.FlightStabilizationDamping:=0.7;
Vehicle.AxleFront.Width:=1.55;
Vehicle.AxleFront.Offset:=Vector2(1.51,-0.5);
Vehicle.AxleFront.Radius:=0.3;
Vehicle.AxleFront.WheelVisualScale:=1.0;//2.9;
Vehicle.AxleFront.StabilizerBarAntiRollForce:=15000.0;
Vehicle.AxleFront.RelaxedSuspensionLength:=0.6;
{Vehicle.AxleFront.SuspensionStiffness:=15000.0;
Vehicle.AxleFront.SuspensionDamping:=3000.0;
Vehicle.AxleFront.SuspensionRestitution:=1.0;}
{Vehicle.AxleFront.LaterialFriction:=0.6;
Vehicle.AxleFront.RollingFriction:=0.03;
Vehicle.AxleFront.RelaxedSuspensionLength:=0.45;
Vehicle.AxleFront.StabilizerBarAntiRollForce:=10000.0;
Vehicle.AxleFront.WheelVisualScale:=1.0;//2.9;
Vehicle.AxleFront.AfterFlightSlipperyK:=0.02;
Vehicle.AxleFront.BrakeSlipperyK:=0.5;
Vehicle.AxleFront.HandBrakeSlipperyK:=0.3;}
Vehicle.AxleFront.IsPowered:=false;
Vehicle.AxleRear.Width:=1.55;
Vehicle.AxleRear.Offset:=Vector2(-1.29,-0.5);
Vehicle.AxleRear.Radius:=0.3;
Vehicle.AxleRear.WheelVisualScale:=1.0;//2.9;
Vehicle.AxleRear.StabilizerBarAntiRollForce:=15000.0;
Vehicle.AxleRear.RelaxedSuspensionLength:=0.6;
{Vehicle.AxleRear.SuspensionStiffness:=9500.0;
Vehicle.AxleRear.SuspensionDamping:=3000.0;
Vehicle.AxleRear.SuspensionRestitution:=1.0;}
{Vehicle.AxleRear.LaterialFriction:=0.6;
Vehicle.AxleRear.RollingFriction:=0.03;
Vehicle.AxleRear.RelaxedSuspensionLength:=0.45;
Vehicle.AxleRear.StabilizerBarAntiRollForce:=10000.0;
Vehicle.AxleRear.WheelVisualScale:=1.0;//2.9;
Vehicle.AxleRear.AfterFlightSlipperyK:=0.02;
Vehicle.AxleRear.BrakeSlipperyK:=0.5;
Vehicle.AxleRear.HandBrakeSlipperyK:=0.2; }
Vehicle.AxleRear.IsPowered:=true;
Vehicle.RigidBody:=TKraftRigidBody.Create(aKraftPhysics);
Vehicle.RigidBody.SetRigidBodyType(krbtDYNAMIC);
{Vehicle.RigidBody.Flags:=Vehicle.RigidBody.Flags+[krbfHasForcedCenterOfMass];
Vehicle.RigidBody.ForcedCenterOfMass.x:=0;
Vehicle.RigidBody.ForcedCenterOfMass.y:=-0.3;
Vehicle.RigidBody.ForcedCenterOfMass.z:=0.0;
Vehicle.RigidBody.ForcedMass:=1500.0;}
Shape:=TKraftShapeBox.Create(aKraftPhysics,Vehicle.RigidBody,Vector3(CarHalfWidth,CarHeight*0.5,CarLength*0.5));
Shape.Restitution:=0.3;
Shape.Density:=200.0;
Shape.LocalTransform:=Matrix4x4Translate(0.0,0.0,0.0);
Shape.Flags:=Shape.Flags+[ksfHasForcedCenterOfMass];
Shape.ForcedCenterOfMass.x:=0;
Shape.ForcedCenterOfMass.y:=-0.6;
Shape.ForcedCenterOfMass.z:=0.0;
Shape.ForcedMass:=1500.0;
{Shape:=TKraftShapeBox.Create(aKraftPhysics,Vehicle.RigidBody,Vector3(1.0,1.0,2.0));
Shape.Restitution:=0.3;
Shape.Density:=10.0;
Shape.LocalTransform:=Matrix4x4Translate(0.0,1.75,1.0);}
Vehicle.RigidBody.Finish;
Vehicle.RigidBody.SetWorldTransformation(Matrix4x4TermMul(Matrix4x4RotateY(PI),Matrix4x4Translate(0.0,CarHeight+Vehicle.AxleFront.Radius,0.0)));
Vehicle.RigidBody.CollisionGroups:=[1];
Vehicle.RigidBody.CollideWithCollisionGroups:=[0,1];
Vehicle.RigidBody.AngularVelocityDamp:=10.0;//10.0;
Vehicle.RigidBody.LinearVelocityDamp:=0.05;
{Vehicle.RigidBody.Flags:=Vehicle.RigidBody.Flags+[TKraftRigidBodyFlag.krbfHasOwnGravity];
Vehicle.RigidBody.Gravity.x:=0.0;
Vehicle.RigidBody.Gravity.y:=0.0;
Vehicle.RigidBody.Gravity.z:=0.0;}
Vehicle.Reset;
InputKeyLeft:=false;
InputKeyRight:=false;
InputKeyUp:=false;
InputKeyDown:=false;
InputKeyBrake:=false;
InputKeyHandBrake:=false;
{begin
DummyRigidBody:=TKraftRigidBody.Create(KraftPhysics);
DummyRigidBody.SetRigidBodyType(krbtSTATIC);
Shape:=TKraftShapeBox.Create(KraftPhysics,DummyRigidBody,Vector3(4.0,25.0,2.0));
Shape.Restitution:=0.3;
DummyRigidBody.Finish;
DummyRigidBody.CollisionGroups:=[0];
DummyRigidBody.SetWorldTransformation(Matrix4x4TermMul(Matrix4x4RotateX(-0.35*pi),Matrix4x4Translate(0.0,0.0,-10.0)));
end;}
end;
destructor TDemoSceneRaycastVehicle.Destroy;
begin
FreeAndNil(Vehicle);
inherited Destroy;
end;
procedure TDemoSceneRaycastVehicle.Step(const DeltaTime:double);
begin
Time:=Time+DeltaTime;
Vehicle.InputVertical:=(ord(InputKeyUp) and 1)-(ord(InputKeyDown) and 1);
Vehicle.InputHorizontal:=(ord(InputKeyLeft) and 1)-(ord(InputKeyRight) and 1);
Vehicle.InputBrake:=InputKeyBrake;
Vehicle.InputHandBrake:=InputKeyHandBrake;
Vehicle.Update;
end;
procedure TDemoSceneRaycastVehicle.DebugDraw;
begin
inherited DebugDraw;
glDisable(GL_LIGHTING);
glEnable(GL_POLYGON_OFFSET_LINE);
glEnable(GL_POLYGON_OFFSET_POINT);
glPolygonOffset(-8,8);
glPointSize(8);
glLineWidth(4);
glColor4f(1,1,1,1);
Vehicle.DebugDraw;
glDisable(GL_DEPTH_TEST);
glDisable(GL_POLYGON_OFFSET_LINE);
glDisable(GL_POLYGON_OFFSET_POINT);
end;
function TDemoSceneRaycastVehicle.HasOwnKeyboardControls:boolean;
begin
result:=true;
end;
procedure TDemoSceneRaycastVehicle.KeyDown(const aKey:Int32);
begin
case aKey of
VK_LEFT:begin
InputKeyLeft:=true;
end;
VK_RIGHT:begin
InputKeyRight:=true;
end;
VK_UP:begin
InputKeyUp:=true;
end;
VK_DOWN:begin
InputKeyDown:=true;
end;
VK_SPACE:begin
InputKeyBrake:=true;
end;
VK_RETURN:begin
InputKeyHandBrake:=true;
end;
end;
end;
procedure TDemoSceneRaycastVehicle.KeyUp(const aKey:Int32);
begin
case aKey of
VK_LEFT:begin
InputKeyLeft:=false;
end;
VK_RIGHT:begin
InputKeyRight:=false;
end;
VK_UP:begin
InputKeyUp:=false;
end;
VK_DOWN:begin
InputKeyDown:=false;
end;
VK_SPACE:begin
InputKeyBrake:=false;
end;
VK_RETURN:begin
InputKeyHandBrake:=false;
end;
end;
end;
function TDemoSceneRaycastVehicle.UpdateCamera(var aCameraPosition:TKraftVector3;var aCameraOrientation:TKraftQuaternion):boolean;
var Position:TKraftVector3;
TargetMatrix:TKraftMatrix3x3;
LerpFactor:TKraftScalar;
begin
LerpFactor:=1.0-exp(-(1.0/20.0));
Position:=Vector3Add(Vector3Add(Vehicle.WorldPosition,Vector3ScalarMul(Vehicle.WorldForward,-5.0)),Vector3ScalarMul(Vehicle.WorldUp,0.0));
PKraftVector3(@TargetMatrix[2,0])^:=Vector3Norm(Vector3Sub(Vehicle.WorldPosition,Position));
PKraftVector3(@TargetMatrix[1,0])^:=Vehicle.WorldUp;
PKraftVector3(@TargetMatrix[0,0])^:=Vector3Cross(PKraftVector3(@TargetMatrix[1,0])^,PKraftVector3(@TargetMatrix[2,0])^);
PKraftVector3(@TargetMatrix[1,0])^:=Vector3Cross(PKraftVector3(@TargetMatrix[2,0])^,PKraftVector3(@TargetMatrix[0,0])^);
aCameraPosition:=Vector3Lerp(aCameraPosition,Position,LerpFactor);
aCameraOrientation:=QuaternionSlerp(aCameraOrientation,QuaternionFromMatrix3x3(TargetMatrix),LerpFactor);
result:=true;
end;
procedure TDemoSceneRaycastVehicle.StoreWorldTransforms;
begin
inherited StoreWorldTransforms;
Vehicle.StoreWorldTransforms;
end;
procedure TDemoSceneRaycastVehicle.InterpolateWorldTransforms(const aAlpha:TKraftScalar);
begin
inherited InterpolateWorldTransforms(aAlpha);
Vehicle.InterpolateWorldTransforms(aAlpha);
end;
initialization
RegisterDemoScene('Raycast vehicle',TDemoSceneRaycastVehicle);
end.
|
unit RootMainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus;
type
TformRootMain = class(TForm)
MainMenu: TMainMenu;
mitmHelp: TMenuItem;
mitmReadMe: TMenuItem;
N7: TMenuItem;
mitmWeb: TMenuItem;
mitmProductNews: TMenuItem;
mitmFaqs: TMenuItem;
mitmSupport: TMenuItem;
N8: TMenuItem;
mitmFeedback: TMenuItem;
N6: TMenuItem;
mitmAbout: TMenuItem;
mitmFile: TMenuItem;
mitmExit: TMenuItem;
N9: TMenuItem;
procedure mitmAboutClick(Sender: TObject);
procedure mitmHelpClick(Sender: TObject);
procedure WebClick(Sender: TObject);
procedure mitmExitClick(Sender: TObject);
private
FAboutTitle: string;
FAboutAuthor: string;
FAboutAddress: string;
FReadmeFile: string;
public
constructor Create(AOwner: TComponent); override;
property AboutTitle: string read FAboutTitle write FAboutTitle;
property AboutAuthor: string read FAboutAuthor write FAboutAuthor;
property AboutAddress: string read FAboutAddress write FAboutAddress;
end;
implementation
uses
DemoUtils, AboutForm;
{$R *.DFM}
constructor TformRootMain.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FReadmeFile := ExtractFilePath(Application.ExeName) + '\readme.txt';
end;
procedure TformRootMain.mitmAboutClick(Sender: TObject);
begin
with TformAbout.Create(Application) do begin
try
lablTitle.Caption := AboutTitle;
lablAuthorName.Caption := AboutAuthor;
lablAuthorAddress.Caption := AboutAddress;
ShowModal;
finally
Free;
end;
end;
end;
procedure TformRootMain.WebClick(Sender: TObject);
begin
if Sender = mitmReadMe then
OpenPrim(FReadmeFile)
else if Sender = mitmProductNews then
OpenPrim('http://www.pbe.com/winshoes/')
else if Sender = mitmFaqs then
OpenPrim('http://www.pbe.com/winshoes/')
else if Sender = mitmSupport then
OpenPrim('http://www.pbe.com/Winshoes/Documentation/TechSupport.html')
else if Sender = mitmFeedback then
MailTo(AboutAddress, AboutTitle);
end;
procedure TformRootMain.mitmHelpClick(Sender: TObject);
begin
mitmAbout.Caption := '&About ' + AboutTitle + '...';
mitmReadme.Enabled := FileExists(FReadmeFile);
end;
procedure TformRootMain.mitmExitClick(Sender: TObject);
begin
Close;
end;
end.
|
unit BookingReports;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Data.DB, Data.Win.ADODB, frxClass, frxDBSet, frxExportPDF, Vcl.StdCtrls,
frxPreview, Vcl.Buttons, frxExportHTML, Vcl.ComCtrls, Vcl.Grids,
Vcl.DBGrids, Vcl.ExtCtrls, Vcl.Imaging.jpeg;
type
TFRMBookingReports = class(TForm)
ADOTBookings: TADOTable;
frxdbAllBookings: TfrxDBDataset;
ADOQFindBookings: TADOQuery;
ADOCReports: TADOConnection;
BTNDateSearch: TButton;
DPStartDate: TDateTimePicker;
DPEndDate: TDateTimePicker;
BTNThisWeek: TButton;
BTNNextWeek: TButton;
BTNThisMonth: TButton;
BTNNextMonth: TButton;
BTNReserved: TButton;
BTNSettled: TButton;
BTNNoShow: TButton;
BTNBookings: TButton;
frxAllBookings: TfrxReport;
frxdbSelectedBookings: TfrxDBDataset;
frxSelectedBookings: TfrxReport;
Label8: TLabel;
Label1: TLabel;
Image1: TImage;
Bevel1: TBevel;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure BTNDateSearchClick(Sender: TObject);
procedure BTNBookingsClick(Sender: TObject);
procedure BTNThisWeekClick(Sender: TObject);
procedure BTNNextWeekClick(Sender: TObject);
procedure BTNThisMonthClick(Sender: TObject);
procedure BTNNextMonthClick(Sender: TObject);
procedure BTNReservedClick(Sender: TObject);
procedure BTNSettledClick(Sender: TObject);
procedure BTNNoShowClick(Sender: TObject);
private
public
{ Public declarations }
end;
var
FRMBookingReports: TFRMBookingReports;
implementation
{$R *.dfm}
Uses Global, LocateDatabase;
Procedure TFRMBookingReports.BTNBookingsClick(Sender: TObject);
Begin
frxAllBookings.ShowReport();
End;
//Procedure which runs query to find all bookings between specified dates
Procedure TFRMBookingReports.BTNDateSearchClick(Sender: TObject);
Begin
ADOQFindBookings.Close;
ADOQFindBookings.SQL.Clear;
ADOQFindBookings.SQL.Add('SELECT*');
ADOQFindBookings.SQL.Add('FROM Booking');
ADOQFindBookings.SQL.Add('WHERE ((Booking.DateOfDining)>=[Start Date]) '
+'And ((Booking.DateOfDining)<=[End Date])');
ADOQFindBookings.Parameters[0].Value := DateToStr(DPStartDate.Date);
ADOQFindBookings.Parameters[1].Value := DateToStr(DPEndDate.Date);
ADOQFindBookings.Open;
frxSelectedBookings.ShowReport();
End;
//Runs query to find all bookings made for current month
Procedure TFRMBookingReports.BTNNextMonthClick(Sender: TObject);
Begin
ADOQFindBookings.Close;
ADOQFindBookings.SQL.Clear;
ADOQFindBookings.SQL.Add('SELECT*');
ADOQFindBookings.SQL.Add('FROM Booking');
ADOQFindBookings.SQL.Add('WHERE ((Booking.DateOfDining)>=[Start Date]) '
+'And ((Booking.DateOfDining)<=[End Date])');
ADOQFindBookings.Parameters[0].Value := DateToStr(Date+31);
ADOQFindBookings.Parameters[1].Value := DateToStr(Date+62);
ADOQFindBookings.Open;
frxSelectedBookings.ShowReport();
End;
//Runs query to find all bookings made for next week
Procedure TFRMBookingReports.BTNNextWeekClick(Sender: TObject);
Begin
ADOQFindBookings.Close;
ADOQFindBookings.SQL.Clear;
ADOQFindBookings.SQL.Add('SELECT*');
ADOQFindBookings.SQL.Add('FROM Booking');
ADOQFindBookings.SQL.Add('WHERE ((Booking.DateOfDining)>=[Start Date]) '
+'And ((Booking.DateOfDining)<=[End Date])');
ADOQFindBookings.Parameters[0].Value := DateToStr(Date+7);
ADOQFindBookings.Parameters[1].Value := DateToStr(Date+14);
ADOQFindBookings.Open;
frxSelectedBookings.ShowReport();
End;
//Runs query to find all bookings with status 'No Show'
Procedure TFRMBookingReports.BTNNoShowClick(Sender: TObject);
Begin
ADOQFindBookings.Close;
ADOQFindBookings.SQL.Clear;
ADOQFindBookings.SQL.Add('SELECT*');
ADOQFindBookings.SQL.Add('FROM Booking');
ADOQFindBookings.SQL.Add('WHERE Booking.Status = [Entered Sitting]');
ADOQFindBookings.Parameters[0].Value := 'No Show';
ADOQFindBookings.Open;
frxSelectedBookings.ShowReport();
End;
//Runs query to find all bookings with status 'Reserved'
Procedure TFRMBookingReports.BTNReservedClick(Sender: TObject);
Begin
ADOQFindBookings.Close;
ADOQFindBookings.SQL.Clear;
ADOQFindBookings.SQL.Add('SELECT*');
ADOQFindBookings.SQL.Add('FROM Booking');
ADOQFindBookings.SQL.Add('WHERE Booking.Status = [Entered Sitting]');
ADOQFindBookings.Parameters[0].Value := 'Reserved';
ADOQFindBookings.Open;
frxSelectedBookings.ShowReport();
End;
//Runs query to find all bookings with status 'Settled'
Procedure TFRMBookingReports.BTNSettledClick(Sender: TObject);
Begin
ADOQFindBookings.Close;
ADOQFindBookings.SQL.Clear;
ADOQFindBookings.SQL.Add('SELECT*');
ADOQFindBookings.SQL.Add('FROM Booking');
ADOQFindBookings.SQL.Add('WHERE Booking.Status = [Entered Sitting]');
ADOQFindBookings.Parameters[0].Value := 'Settled';
ADOQFindBookings.Open;
frxSelectedBookings.ShowReport();
End;
//Runs quesry to find all bookings made for this month
Procedure TFRMBookingReports.BTNThisMonthClick(Sender: TObject);
Begin
ADOQFindBookings.Close;
ADOQFindBookings.SQL.Clear;
ADOQFindBookings.SQL.Add('SELECT*');
ADOQFindBookings.SQL.Add('FROM Booking');
ADOQFindBookings.SQL.Add('WHERE ((Booking.DateOfDining)>=[Start Date]) '
+'And ((Booking.DateOfDining)<=[End Date])');
ADOQFindBookings.Parameters[0].Value := DateToStr(Date);
ADOQFindBookings.Parameters[1].Value := DateToStr(Date+31);
ADOQFindBookings.Open;
frxSelectedBookings.ShowReport();
End;
//Runs query to find all bookings made for this week
procedure TFRMBookingReports.BTNThisWeekClick(Sender: TObject);
Begin
ADOQFindBookings.Close;
ADOQFindBookings.SQL.Clear;
ADOQFindBookings.SQL.Add('SELECT*');
ADOQFindBookings.SQL.Add('FROM Booking');
ADOQFindBookings.SQL.Add('WHERE ((Booking.DateOfDining)>=[Start Date]) '
+'And ((Booking.DateOfDining)<=[End Date])');
ADOQFindBookings.Parameters[0].Value := DateToStr(Date);
ADOQFindBookings.Parameters[1].Value := DateToStr(Date+7);
ADOQFindBookings.Open;
frxSelectedBookings.ShowReport();
End;
Procedure TFRMBookingReports.FormCreate(Sender: TObject);
Var I: Integer;
Begin
//Run procedure 'ReadPath' from form LocateDatase to read Ini file
//and retrive Database Path
FRMDatabaseLocate.ReadPath;
//Set connection of all TADOQuery's to path from Ini file
For I := 0 to ComponentCount - 1 Do
IF (Components[I] is TADOQuery)
Then TADOQuery(Components[I]).ConnectionString := DatabaseSource;
//Set connection of all TADOTable's to path from Ini file
For I := 0 to ComponentCount - 1 Do
IF (Components[I] is TADOTable)
Then TADOTable(Components[I]).ConnectionString := DatabaseSource;
End;
end.
|
var
a:array[0..100000] of string;
n,m,i,j:longint;
s:string;
procedure quicksort(m,n:longint);
var
i,j:longint;
x,temp:string;
begin
x:=a[(m+n) div 2];
i:=m;
j:=n;
repeat
while a[i]<x do i:=i+1;
while a[j]>x do j:=j-1;
if i<=j then
begin
temp:=a[i];
a[i]:=a[j];
a[j]:=temp;
i:=i+1;
j:=j-1;
end;
until i>j;
if m<j then quicksort(m,j);
if i<n then quicksort(i,n);
end;
function search(m,n:longint):longint;
var
i:longint;
begin
if m>n then exit(0);
if m=n then if a[m]=s then exit(1) else exit(0);
i:=(m+n) div 2;
if a[i]<s then search:=search(i+1,n);
if a[i]>s then search:=search(m,i-1);
if a[i]=s then exit(1);
end;
begin
readln(n);
for i:=1 to n do readln(a[i]);
quicksort(1,n);
readln(m);
j:=0;
for i:=1 to m do
begin
readln(s);
j:=j+search(1,n);
end;
writeln(j);
end. |
{
Esta unit é usada única e exclusivamente para registrar
nossas classes no InfraReflection.
Cada classe a ser reflexionada precisa ter uma herança aqui
por que os Getters e Setters da nossa classe devem permanecer protegidas
para que um programador inadvertidamente tente usar a classe em vez da
interface.
}
unit HibernateModelReflex;
interface
uses
HibernateModel;
type
TAccountReflex = class(TAccount);
implementation
uses
HibernateModelIntf, InfraCommonIntf, InfraValueTypeIntf,
InfraHibernateAnnotationIntf;
function RegisterAccountOnReflection: IClassInfo;
var
vPropInfo: IPropertyInfo;
vColumn: IColumn;
begin
with TypeService do
begin
with AddType(IAccount, 'Account', TAccount,
IInfraObject, GetType(IInfraObject)) do
begin
vPropInfo := AddPropertyInfo('ID', GetType(IInfraInteger),
@TAccountReflex.GetID);
// anotação para informar a persistencia qual o atributo que corresponde
// à chave primária.
vPropInfo.Annotate(IID);
vPropInfo := AddPropertyInfo('Name', GetType(IInfraString),
@TAccountReflex.GetName, @TAccountReflex.SetName);
// anotação da coluna por que nome no banco difere do nome do atributo.
vColumn := vPropInfo.Annotate(IColumn) as IColumn;
vColumn.Name := 'ACCOUNTNAME';
AddPropertyInfo('AccountNumber', GetType(IInfraString),
@TAccountReflex.GetAccountNumber, @TAccountReflex.SetAccountNumber);
AddPropertyInfo('InitialBalance', GetType(IInfraDouble),
@TAccountReflex.GetInitialBalance, @TAccountReflex.SetInitialBalance);
AddPropertyInfo('CurrentBalance', GetType(IInfraDouble),
@TAccountReflex.GetCurrentBalance, @TAccountReflex.SetCurrentBalance);
end;
end;
end;
initialization
RegisterAccountOnReflection;
end.
|
{ Subroutine STRING_SUBSTR (S1, ST, EN, S2)
*
* Extract a substring from a string. S1 is the string the substring
* is extracted from. ST and EN define the start and end range of
* characters to extract from S1. The substring range is clipped
* to the size of string S1, and the maximum length of S2. The resulting
* string is put into S2.
}
module string_substr;
define string_substr;
%include 'string2.ins.pas';
procedure string_substr ( {extract substring from a string}
in s1: univ string_var_arg_t; {input string to extract from}
in st: string_index_t; {start index of substring}
in en: string_index_t; {end index of substring}
in out s2: univ string_var_arg_t); {output substring}
val_param;
var
start, ennd: sys_int_machine_t; {real substring range indices}
p: sys_int_machine_t; {put index into S2}
g: sys_int_machine_t; {get index into S1}
begin
start := st; {init start of substring range}
if start < 1 then start := 1; {clip to start of S2}
ennd := en; {init end of substring range}
if ennd > s1.len then ennd := s1.len; {clip to end of string in S1}
if (ennd-start+1) > s2.max then {substring too big for S2 ?}
ennd := start+s2.max-1; {yes, chop off end to fit into S2}
p := 1; {init put pointer into S2}
for g := start to ennd do begin {once for each character in substring}
s2.str[p] := s1.str[g]; {copy one character}
p := p+1 {point to where to put next character}
end; {back for next character}
s2.len := max(p-1, 0); {set length of output string}
end;
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
}
{
Description:
various string manipulation functions
}
unit helper_strings;
interface
uses
sysutils,classes2,const_ares,synsock,windows,ares_types;
const
STR_UTF8BOM = chr($ef)+chr($bb)+chr($bf);
function reverse_order(const strin:string):string;
function get_first_word(const strin:string):string;
function chars_2_qword(const stringa:string):int64;
function chars_2_dword(const stringa:string):cardinal;
function chars_2_word(const stringa:string):word;
function int_2_qword_string(const numero:int64):string;
function int_2_dword_string(const numero:cardinal):string;
function int_2_word_string(const numero:word):string;
function hexstr_to_bytestr(const strin:string):string;
function bytestr_to_hexstr(const strin:string):string;
function bytestr_to_hexstr_bigend(const strin:string):string;
function isxdigit(Ch : char) : Boolean;
function isdigit(Ch : char) : boolean;
function xdigit(Ch : char) : Integer;
function HexToInt(const HexString : String) : cardinal;
function HexToInt_no_check(const HexString : String) : cardinal;
function caption_double_amperstand(strin:widestring):widestring;
function strip_at(const strin:string):string;
function strip_at_reverse(const strin:string):string;
function StripIllegalFileChars(const value:string):string;
function SplitString(str:String; lista:tmystringlist):integer;
function strippa_fastidiosi2(strin:widestring):widestring;
function strippa_fastidiosi(strin:widestring;con:widechar):widestring;
function strip_apos_amp(const str:string):string;
function ucfirst(const stringa:string):string;
function strip_track(const strin:string):string;
function trim_extended(stringa:string):string;
function format_currency(numero:int64):string;
function whl(const x:string):word; //X arriva già lowercase da supernodo
function wh(const xS:string):word;
function whlBuff(buff:pointer; len:byte):word; //X arriva già lowercase da supernodo
function StringCRC(const str:String; lower_case: Boolean): Word; //keyword slava
function crcstring(const strin:string):word;
//function strip_nl(linea:widestring):widestring;
function strip_returns(strin:widestring):widestring;
function strippa_parentesi(strin:widestring):widestring;
function get_player_displayname(filename:widestring; const estensione:string):widestring;
function strip_incomplete(nomefile:widestring):widestring;
function strip_vers(const strin:string):string;
function getfirstNumberStr(const strin:string):string;
function right_strip_at_agent(const strin:string):string;
function strip_websites_str(value:string):string;
function strip_char(const strin:string; illegalChar:string):string;
function bool_string(condition:boolean; trueString:string='On'; falseString:string='Off'):string;
function deUrlNick(nick:string):string;
function reverseorder(num:cardinal):cardinal; overload;
function reverseorder(num:word):word; overload;
function reverseorder(num:int64):int64; overload;
function explode(str:string; separator:string):targuments;
function rpos(const needle:string; const strin:string):integer;
implementation
uses
helper_urls,helper_unicode;
function explode(str:string; separator:string):targuments;
var
previouslen,ind:integer;
begin
if pos('&',str)=0 then begin
setlength(result,1);
result[0]:=str;
exit;
end;
previouslen:=1;
while (length(str)>0) do begin
setlength(result,previouslen);
ind:=pos('&',str);
if ind<>0 then begin
result[previouslen-1]:=copy(str,1,ind-1);
delete(str,1,ind);
end else begin
result[previouslen-1]:=str;
break;
end;
inc(previouslen);
end;
end;
function deUrlNick(nick:string):string;
begin
try
while (pos('\',nick)>0) do begin
nick:=copy(nick,1,pos('\',nick)-1)+ '.' + copy(nick,pos('\',nick)+1,length(nick));
end;
while (pos('/',nick)>0) do begin
nick:=copy(nick,1,pos('/',nick)-1)+ '.' + copy(nick,pos('/',nick)+1,length(nick));
end;
if pos(':',nick)>0 then begin
while (pos('http:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('http:',lowercase(nick))+3)+ '.' + copy(nick,pos('http:',lowercase(nick))+5,length(nick));
end;
while (pos('https:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('https:',lowercase(nick))+4)+ '.' + copy(nick,pos('https:',lowercase(nick))+6,length(nick));
end;
while (pos('file:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('file:',lowercase(nick))+3)+ '.' + copy(nick,pos('file:',lowercase(nick))+5,length(nick));
end;
while (pos('nntp:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('nntp:',lowercase(nick))+3)+ '.' + copy(nick,pos('nntp:',lowercase(nick))+5,length(nick));
end;
while (pos('news:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('news:',lowercase(nick))+3)+ '.' + copy(nick,pos('news:',lowercase(nick))+5,length(nick));
end;
while (pos('wais:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('wais:',lowercase(nick))+3)+ '.' + copy(nick,pos('wais:',lowercase(nick))+5,length(nick));
end;
while (pos('mailto:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('mailto:',lowercase(nick))+5)+ '.' + copy(nick,pos('mailto:',lowercase(nick))+7,length(nick));
end;
while (pos('gopher:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('gopher:',lowercase(nick))+5)+ '.' + copy(nick,pos('gopher:',lowercase(nick))+7,length(nick));
end;
while (pos('telnet:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('telnet:',lowercase(nick))+5)+ '.' + copy(nick,pos('telnet:',lowercase(nick))+7,length(nick));
end;
while (pos('ftp:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('ftp:',lowercase(nick))+2)+ '.' + copy(nick,pos('ftp:',lowercase(nick))+4,length(nick));
end;
while (pos('prospero:',lowercase(nick))>0) do begin
nick:=copy(nick,1,pos('prospero:',lowercase(nick))+7)+ '.' + copy(nick,pos('prospero:',lowercase(nick))+9,length(nick));
end;
end;
except
end;
result:=nick;
end;
function bool_string(condition:boolean; trueString:string='On'; falseString:string='Off'):string;
begin
if condition then result:=trueString
else result:=falseString;
end;
function right_strip_at_agent(const strin:string):string;
var
i:integer;
begin
result:='';
for i:=length(strin) downto 1 do
if strin[i]='@' then begin
result:=copy(strin,1,i-1);
exit;
end;
end;
function rpos(const needle:string; const strin:string):integer;
var
i:integer;
begin
result:=0;
if length(needle)>length(strin) then exit;
if length(needle)=length(strin) then begin
if needle<>strin then exit;
end;
for i:=length(strin) downto 1 do
if copy(strin,i,length(needle))=needle then begin
result:=i;
exit;
end;
end;
function getfirstNumberStr(const strin:string):string;
var
i:integer;
begin
result:='';
for i:=1 to length(strin) do
if ((ord(strin[i])>=48) and
(ord(strin[i])<=57)) then begin
result:=copy(strin,i,length(strin));
break;
end;
end;
function strip_incomplete(nomefile:widestring):widestring;
var
lonomefile:string;
begin
lonomefile:=lowercase(widestrtoutf8str(nomefile));
if pos('__incomplete_____',lonomefile)=1 then delete(lonomefile,1,17) else
if pos('__incomplete____',lonomefile)=1 then delete(lonomefile,1,16) else
if pos('__incomplete___',lonomefile)=1 then delete(lonomefile,1,15) else
if pos('__incomplete__',lonomefile)=1 then delete(lonomefile,1,14) else
if pos('___incomplete____',lonomefile)=1 then delete(lonomefile,1,16) else
if pos('___arestra___',lonomefile)=1 then delete(lonomefile,1,13);
result:=utf8strtowidestr(lonomefile);
end;
function get_player_displayname(filename:widestring; const estensione:string):widestring;
var
rec:ares_types.precord_title_album_artist;
title,artist,album:string;
begin
result:=extract_fnameW(filename);
if pos('___ARESTRA___',widestrtoutf8str(result))=1 then delete(result,1,13); // eventually remove ___ARESTRA___
rec:=AllocMem(sizeof(ares_types.record_title_album_artist));
try
//umediar.estrai_titolo_artista_album_da_stringa(rec,result);
artist:=trim(widestrtoutf8str(rec^.artist));
album:=trim(widestrtoutf8str(rec^.album));
title:=trim(widestrtoutf8str(rec^.title));
except
end;
FreeMem(rec,sizeof(record_title_album_artist));
delete(result,(length(result)-length(estensione))+1,length(estensione)); // remove extension
if ((length(title)>0) and (length(artist)>0) and (length(album)>0)) then result:=utf8strtowidestr(artist)+' - '+utf8strtowidestr(album)+' - '+utf8strtowidestr(title)
else
if ((length(title)>0) and (length(artist)>0)) then result:=utf8strtowidestr(artist)+' - '+utf8strtowidestr(title);
end;
function strippa_parentesi(strin:widestring):widestring;
var
i:integer;
begin
result:='';
for i:=1 to length(strin) do begin
if strin[i]='(' then result:=result+' ' else
if strin[i]=')' then result:=result+' ' else
if strin[i]='{' then result:=result+' ' else
if strin[i]='}' then result:=result+' ' else
if strin[i]='[' then result:=result+' ' else
if strin[i]=']' then result:=result+' ' else
if strin[i]='"' then result:=result+' ' else
if strin[i]='''' then result:=result+' ' else
if strin[i]='_' then result:=result+' ' else
result:=result+strin[i];
end;
end;
function strip_returns(strin:widestring):widestring;
var
i:integer;
begin
result:=strin;
for i:=1 to length(result) do
if ((result[i]=chr(13)) or (result[i]=chr(10))) then result[i]:=' ';
end;
{function strip_nl(linea:widestring):widestring;
begin
result:=linea;
while (pos('\nl',result)<>0) do
result:=copy(result,1,pos('\nl',result)-1)+
CRLF+
copy(result,pos('\nl',result)+3,length(result));
end;}
function crcstring(const strin:string):word; // for sha1 hashes
begin
result:=0;
if length(strin)<8 then exit;
inc(result,ord(strin[1]));
inc(result,ord(strin[2]));
inc(result,ord(strin[3]));
inc(result,ord(strin[4]));
inc(result,ord(strin[5]));
inc(result,ord(strin[6]));
inc(result,ord(strin[7]));
inc(result,ord(strin[8]));
end;
function StringCRC(const str: String; lower_case: Boolean): Word; //keyword slava
var
c: Char;
begin // counts 2-byte CRC of string. used for faster comparison
result:=Length(str);
if result>0 then begin
c:=str[result];
if lower_case then
if (c >= 'A') and (c <= 'Z') then inc(c, 32);
result:=Ord(c)+256*result;
end;
// using last character of string instead of first because almost all databases are already sorted by first character
end;
function wh(const xS:string):word; //gnutella query routing word hashing
var
xors:integer;
x:string;
j,b:integer;
i:integeR;
prod,ret:int64;
bits:byte;
begin
bits:=16;
//log (2) 655354 = 16 14;
x:=lowercase(xS);
xors := 0;
j := 0;
for i:=1 to length(x) do begin
b := ord(x[i]) and $FF;
b := b shl (j * 8);
xors := xors xor b;
j := (j + 1) mod 4;
end;
prod := xors * $4F1BBCDC;
ret := prod shl 32;
ret := ret shr (32 + (32 - bits));
result:= word(ret);
end;
function whlBuff(buff:pointer; len:byte):word; //X arriva già lowercase da supernodo
var
xors:integer;
j,b:integer;
i:integeR;
prod,ret:int64;
bits:byte;
begin
bits:=16;//log2(size);
//14;// log (2) 655354 = 16 14; //<--- limewire log (2) 16384
xors := 0;
j := 0;
for i:=0 to len-1 do begin
b := pbytearray(buff)[i] and $FF;
b := b shl (j * 8);
xors := xors xor b;
j := (j + 1) mod 4;
end;
prod := xors * $4F1BBCDC;
ret := prod shl 32; // 4
ret := ret shr (32 + (32 - bits)); // >>> ? bits=16
result:= word(ret);
end;
function whl(const x:string):word; //X arriva già lowercase da supernodo
var
xors:integer;
j,b:integer;
i:integeR;
prod,ret:int64;
bits:byte;
begin
bits:=16;//log2(size);
//14;// log (2) 655354 = 16 14; //<--- limewire log (2) 16384
xors := 0;
j := 0;
for i:=1 to length(x) do begin
b := ord(x[i]) and $FF;
b := b shl (j * 8);
xors := xors xor b;
j := (j + 1) mod 4;
end;
prod := xors * $4F1BBCDC;
ret := prod shl 32; // 4
ret := ret shr (32 + (32 - bits)); // >>> ? bits=16
result:= word(ret);
end;
function format_currency(numero:int64):string;
var
numeroi:Extended;
begin
numeroi:=numero;
result:=format('%0.n',[numeroi]);
end;
function StripIllegalFileChars(const value:string):string;
var
i:integer;
begin
result:='';
for i:=1 to length(value) do begin
if value[i]='\' then begin
result:=result+'_';
continue;
end;
if value[i]='/' then begin
result:=result+'_';
continue;
end;
if value[i]=':' then begin
result:=result+'_';
continue;
end;
if value[i]='*' then begin
result:=result+'_';
continue;
end;
if value[i]='?' then begin
result:=result+'_';
continue;
end;
if value[i]='"' then begin
result:=result+'_';
continue;
end;
if value[i]='<' then begin
result:=result+'_';
continue;
end;
if value[i]='>' then begin
result:=result+'_';
continue;
end;
if value[i]='|' then begin
result:=result+'_';
continue;
end;
result:=result+value[i];
end;
end;
function trim_extended(stringa:string):string;
var
i,rnum:integer;
c:char;
begin
result:='';
for i:=1 to length(stringa) do begin
if ((stringa[i]='ì') or
(stringa[i]='í') or
(stringa[i]='î') or
(stringa[i]='ï')) then stringa[i]:='i' else
if ((stringa[i]='è') or
(stringa[i]='é') or
(stringa[i]='ê') or
(stringa[i]='ë')) then stringa[i]:='e' else
if ((stringa[i]='à') or
(stringa[i]='á') or
(stringa[i]='ê')) then stringa[i]:='a' else
if ((stringa[i]='ù') or
(stringa[i]='ü')) then stringa[i]:='u' else
if ((stringa[i]='ò') or
(stringa[i]='ó')) then stringa[i]:='o' else
if stringa[i]='ç' then stringa[i]:='c' else
if stringa[i]='ñ' then stringa[i]:='n' else
if stringa[i]='"' then stringa[i]:='''';
rnum:=ord(stringa[i]);
if ((rnum<48) or
((rnum > 57) and (rnum < 65)) or
((rnum > 90) and (rnum < 97)) or
(rnum > 122)) then begin
c:=stringa[i];
if (c in ['(',')','@','^','?','<','>','*','|','!',',',':','/','\','#','.','=','?','_']) then result:=result+' ' else result:=result+stringa[i];
end else result:=result+stringa[i];
end;
while (pos(' ',result)<>0) do begin // togliamo doppi spazi
result:=copy(result,1,pos(' ',result))+copy(result,pos(' ',result)+2,length(result));
end;
result:=trim(result);
end;
function strip_track(const strin:string):string;
begin
result:=strin;
while (pos('Track',result)<>0) do
result:=copy(result,1,pos('Track',result)-1)+copy(result,pos('Track',result)+5,length(result));
end;
function ucfirst(const stringa:string):string;
var
str:string;
begin
result:=stringa;
if length(result)>0 then begin
str:=uppercase(copy(result,1,1));
result:=str+copy(result,2,length(result));
end;
end;
function strip_apos_amp(const str:string):string;
begin
result:=str;
while pos(''',result)>0 do
result:=copy(result,1,pos(''',result)-1)+''''+copy(result,pos(''',result)+6,length(result));
while pos('&',result)>0 do
result:=copy(result,1,pos('&',result)-1)+'&'+copy(result,pos('&',result)+5,length(result));
end;
function strip_websites_str(value:string):string;
begin
result:=value;
if pos('www.',result)<>0 then result:=''
else
if pos('.com',result)<>0 then result:='';
end;
function strippa_fastidiosi(strin:widestring;con:widechar):widestring;
var
i:integer;
begin
result:=strin;
try
for i:=1 to length(result) do
if ((integer(result[i])<33) or (integer(result[i])=160)) then result[i]:=con; //strippiamo caratteri fastidiosi
except
end;
end;
function strippa_fastidiosi2(strin:widestring):widestring;
var
i:integer;
num:integer;
begin
result:=strin;
try
for i:=1 to length(result) do begin
num:=integer(result[i]);
if ((num<33) or (num=160)) then
if ((num>9) or (num<2)) then result[i]:=' '; //strippiamo caratteri fastidiosi
end;
except
end;
end;
function SplitString(str:String; lista:tmystringlist):integer;
var
c:Char;
str1,str2:String;
j,num,max:Integer;
b:Boolean;
begin
lista.clear;
str1:='';
str2:=Trim(str);
if str2='' then begin
Result:=0;
exit;
end;
max:=Length(str)+128;
num:=0;
j:=0;
b:=false; // makes compiler happy
repeat
if Length(str2)>0 then begin
b:=false;
str2:=Trim(str2);
j:=pos(' ',str2);
c:=str2[1];
if c='"' then begin
j:=Pos('"',Copy(str2,2,max))+2;
b:=true;
end;
if j=0 then j:=Length(str2)
else begin
str:=Trim(Copy(str2,1,j));
if str[1]='"' then if str[Length(str)]='"' then str:=Copy(str,2,Length(str)-2);
lista.add(str);
str2:=Trim(Copy(str2,j,max));
inc(num);
j:=0;
end;
end else break;
until j=Length(str2);
if not b then lista.add(Trim(str2));
Result:=num+1;
end;
function strip_at(const strin:string):string;
var
i:integer;
begin
try
result:='';
for i:=1 to length(strin) do if ((strin[i]<>'@') and (strin[i]<>CHRNULL)) then result:=result+strin[i];
except
end;
end;
function strip_char(const strin:string; illegalChar:string):string;
var
i:integer;
begin
try
result:='';
for i:=1 to length(strin) do if strin[i]<>illegalChar then result:=result+strin[i];
except
end;
end;
function strip_at_reverse(const strin:string):string;
var
i:integer;
begin
try
if pos('@',strin)=0 then begin
result:=strin;
exit;
end;
result:='';
for i:=length(strin) downto 1 do if strin[i]='@' then begin
result:=copy(strin,1,i-1);
break;
end;
except
end;
end;
function caption_double_amperstand(strin:widestring):widestring; // fixes some component default textdrawing (accelerator keys)
var
i:integer;
begin
result:=strin;
i:=1;
while (i<=length(result)) do begin //doppio amperstand nel caso
if result[i]='&' then begin
result:=copy(result,1,i)+'&'+copy(result,i+1,length(result));
inc(i,2);
continue;
end else inc(i);
end;
end;
function xdigit(Ch : char) : Integer;
begin
if ch in ['0'..'9'] then
Result := ord(Ch) - ord('0')
else
Result := (ord(Ch) and 15) + 9;
end;
function isdigit(Ch : char) : boolean;
begin
result:=(ch in ['0'..'9']);
end;
function isxdigit(Ch : char) : Boolean;
begin
Result := (ch in ['0'..'9']) or (ch in ['a'..'z']) or (ch in ['A'..'Z']);
end;
function HexToInt(const HexString : String) : cardinal;
var
sss : string;
i:integer;
begin
result:=0;
try
if length(HexString)=0 then exit;
for i:=1 to length(HexString) do if not isxdigit(HexString[i]) then exit;
except
end;
sss := '$' + HexString;
result := StrToIntdef(sss,0);
end;
function HexToInt_no_check(const HexString : String) : cardinal;
var
s : string;
begin
s := '$' + HexString;
result := StrToIntdef(s,0);
end;
function int_2_word_string(const numero:word):string;
begin
setlength(result,2);
move(numero,result[1],2);
end;
function int_2_qword_string(const numero:int64):string;
begin
setlength(result,8);
move(numero,result[1],8);
end;
function int_2_dword_string(const numero:cardinal):string;
begin
setlength(result,4);
move(numero,result[1],4);
end;
function bytestr_to_hexstr(const strin:string):string;
var
i:integer;
begin
result:='';
for i:=1 to length(strin) do result:=result+inttohex(ord(strin[i]),2);
end;
function bytestr_to_hexstr_bigend(const strin:string):string;
var
i:integer;
tempstr:string;
num32:cardinal;
begin
if length(strin)<16 then begin
result:=bytestr_to_hexstr(strin);
exit;
end;
tempstr:=strin;
move(tempstr[1],num32,4);
num32:=synsock.ntohl(num32);
move(num32,tempstr[1],4);
move(tempstr[5],num32,4);
num32:=synsock.ntohl(num32);
move(num32,tempstr[5],4);
move(tempstr[9],num32,4);
num32:=synsock.ntohl(num32);
move(num32,tempstr[9],4);
move(tempstr[13],num32,4);
num32:=synsock.ntohl(num32);
move(num32,tempstr[13],4);
result:='';
for i:=1 to length(tempstr) do result:=result+inttohex(ord(tempstr[i]),2);
end;
function hexstr_to_bytestr(const strin:string):string;
var
i:integeR;
begin
result:='';
try
i:=1;
repeat
if i>=length(strin) then break;
result:=result+chr(hextoint(copy(strin,i,2)));
inc(i,2);
until (not true);
except
end;
end;
function chars_2_word(const stringa:string):word;
begin
if length(stringa)>=2 then begin
result:=ord(stringa[2]);
result:=result shl 8;
result:=result + ord(stringa[1]);
end else result:=0;
end;
function chars_2_qword(const stringa:string):int64;
begin
if length(stringa)>=8 then begin
fillchar(result,8,0);
move(stringa[1],result,8);
end else result:=0;
end;
function chars_2_dword(const stringa:string):cardinal;
begin
if length(stringa)>=4 then begin
result:=ord(stringa[4]);
result:=result shl 8;
result:=result + ord(stringa[3]);
result:=result shl 8;
result:=result + ord(stringa[2]);
result:=result shl 8;
result:=result + ord(stringa[1]);
end else result:=0;
end;
function reverseorder(num:cardinal):cardinal;
var
buffer,buffer2:array[0..3] of byte;
begin
move(num,buffer,4);
buffer2[0]:=buffer[3];
buffer2[1]:=buffer[2];
buffer2[2]:=buffer[1];
buffer2[3]:=buffer[0];
move(buffer2,result,4);
end;
function reverseorder(num:int64):int64;
var
buffer,buffer2:array[0..7] of byte;
begin
move(num,buffer,8);
buffer2[0]:=buffer[7];
buffer2[1]:=buffer[6];
buffer2[2]:=buffer[5];
buffer2[3]:=buffer[4];
buffer2[4]:=buffer[3];
buffer2[5]:=buffer[2];
buffer2[6]:=buffer[1];
buffer2[7]:=buffer[0];
move(buffer2,result,8);
end;
function reverseorder(num:word):word;
var
buffer,buffer2:array[0..1] of byte;
begin
move(num,buffer,2);
buffer2[0]:=buffer[1];
buffer2[1]:=buffer[0];
move(buffer2,result,2);
end;
function strip_vers(const strin:string):string;
var
i:integer;
begin
result:=strin;
for i:=1 to length(result) do
if ((not (result[i] in ['a'..'z'])) and
(not (result[i] in ['A'..'Z']))) then begin
result:=copy(result,1,i-1);
break;
end;
end;
function get_first_word(const strin:string):string;
var i:integer;
begin
result:=strin;
for i:=1 to length(result) do if ((result[i]=' ') or (result[i]='/')) then begin
result:=copy(result,1,i-1);
exit;
end;
end;
function reverse_order(const strin:string):string;
var i:integer;
begin
result:='';
for i:=length(strin) downto 1 do result:=result+strin[i];
end;
end.
|
{
Copyright 2009-2012 Convey Compliance Systems, Inc.
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.
}
{ Use the option SerializedWithJournal set to True if you want to synchronize
write operations with Journal writing to prevent overflowing Mongo database
memory }
unit MongoStream;
interface
uses
Classes, MongoDB, GridFS, MongoBson, MongoApi;
{$I MongoC_defines.inc}
const
E_FileNotFound = 90300;
E_FGridFileIsNil = 90301;
E_FGridFSIsNil = 90302;
E_StreamNotCreatedForWriting = 90303;
E_StatusMustBeOKInOrderToAllowStre = 90304;
E_DelphiMongoErrorFailedSignature = 90305;
E_FailedInitializingEncryptionKey = 90306;
SERIALIZE_WITH_JOURNAL_BYTES_WRITTEN = 1024 * 1024 * 10; (* Serialize with Journal every 10 megs written by default *)
type
TMongoStreamMode = (msmWrite, msmCreate);
TMongoStreamStatus = (mssOK, mssMissingChunks);
TMongoStreamModeSet = set of TMongoStreamMode;
TAESKeyLength = (akl128, akl192, akl256);
TMongoStream = class(TStream)
private
FCurPos: Int64;
FGridFS : TGridFS;
FGridFile : IGridFile;
FGridFileWriter : IGridfileWriter;
FStatus: TMongoStreamStatus;
FMongo: TMongo;
FSerializedWithJournal: Boolean;
FBytesWritten: Cardinal;
FDB : UTF8String;
FLastSerializeWithJournalResult: IBson;
FSerializeWithJournalByteWritten: Cardinal;
FZlibAESContext : Pointer;
FFlags : Integer;
procedure CheckGridFile;
procedure CheckGridFS;
procedure CheckSerializeWithJournal; {$IFDEF DELPHI2007} inline; {$ENDIF}
procedure CheckWriteSupport;
procedure EnforceStatusOK;
function GetCaseInsensitiveNames: Boolean; {$IFDEF DELPHI2007} inline; {$ENDIF}
function GetID: IBsonOID; {$IFDEF DELPHI2007} inline; {$ENDIF}
procedure SerializeWithJournal;
protected
function GetSize: {$IFNDEF VER130} Int64; override; {$ELSE}{$IFDEF Enterprise} Int64; override; {$ELSE} Longint; {$ENDIF}{$ENDIF}
{$IFDEF DELPHI2007}
procedure SetSize(NewSize: longint); override;
procedure SetSize(const NewSize: Int64); overload; override;
procedure SetSize64(const NewSize : Int64);
{$ELSE}
procedure SetSize(NewSize: {$IFDef Enterprise} Int64 {$Else} longint {$EndIf}); override;
{$ENDIF}
public
constructor Create(AMongo: TMongo; const ADB, AFileName: UTF8String; const
AMode: TMongoStreamModeSet; ACompressed: Boolean; const AEncryptionKey:
String = ''; AEncryptionBits: TAESKeyLength = akl128); overload;
constructor Create(AMongo: TMongo; const ADB, APrefix, AFileName: UTF8String;
const AMode: TMongoStreamModeSet; ACaseInsensitiveFileNames, ACompressed:
Boolean; const AEncryptionKey: String = ''; AEncryptionBits: TAESKeyLength
= akl128); overload;
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
{$IFDEF DELPHI2007}
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; overload; override;
function Seek(Offset: longint; Origin: Word ): longint; override;
{$ELSE}
function Seek(Offset: {$IFDef Enterprise} Int64 {$Else} longint {$EndIf}; Origin: {$IFNDEF VER130}TSeekOrigin{$Else}{$IFDef Enterprise}TSeekOrigin{$ELSE}Word{$ENDIF}{$ENDIF}): {$IFDef Enterprise} Int64 {$Else} longint {$EndIf}; override;
{$ENDIF}
function Write(const Buffer; Count: Longint): Longint; override;
property CaseInsensitiveNames: Boolean read GetCaseInsensitiveNames;
property ID: IBsonOID read GetID;
property LastSerializeWithJournalResult: IBson read FLastSerializeWithJournalResult;
property Mongo: TMongo read FMongo;
property SerializedWithJournal: Boolean read FSerializedWithJournal write FSerializedWithJournal default False;
property SerializeWithJournalByteWritten : Cardinal read FSerializeWithJournalByteWritten write FSerializeWithJournalByteWritten default SERIALIZE_WITH_JOURNAL_BYTES_WRITTEN;
property Status: TMongoStreamStatus read FStatus;
property Size: {$IFNDEF VER130}Int64 {$ELSE}{$IFDef Enterprise}Int64 {$ELSE}Longint{$ENDIF}{$ENDIF} read GetSize write {$IFDEF DELPHI2007}SetSize64{$ELSE}SetSize{$ENDIF};
end;
implementation
const
SFs = 'fs';
GET_LAST_ERROR_CMD = 'getLastError';
WAIT_FOR_JOURNAL_OPTION = 'j';
aklLenToKeyLen : array [TAESKeyLength] of integer = (128, 192, 256);
resourcestring
SFileNotFound = 'File %s not found (D%d)';
SFGridFileIsNil = 'FGridFile is nil (D%d)';
SFGridFSIsNil = 'FGridFS is nil (D%d)';
SStreamNotCreatedForWriting = 'Stream not created for writing (D%d)';
SStatusMustBeOKInOrderToAllowStre = 'Status must be OK in order to allow stream read operations (D%d)';
SFailedInitializingEncryptionKey = 'Failed initializing encryption key (D%d)';
constructor TMongoStream.Create(AMongo: TMongo; const ADB, AFileName:
UTF8String; const AMode: TMongoStreamModeSet; ACompressed: Boolean; const
AEncryptionKey: String = ''; AEncryptionBits: TAESKeyLength = akl128);
begin
Create(AMongo, ADB, SFs, AFileName, AMode, True, ACompressed, AEncryptionKey, AEncryptionBits);
end;
constructor TMongoStream.Create(AMongo: TMongo; const ADB, APrefix, AFileName:
UTF8String; const AMode: TMongoStreamModeSet; ACaseInsensitiveFileNames,
ACompressed: Boolean; const AEncryptionKey: String = ''; AEncryptionBits:
TAESKeyLength = akl128);
begin
inherited Create;
FSerializeWithJournalByteWritten := SERIALIZE_WITH_JOURNAL_BYTES_WRITTEN;
FDB := ADB;
FMongo := AMongo;
FStatus := mssOK;
FGridFS := TGridFS.Create(AMongo, FDB, APrefix);
FGridFS.CaseInsensitiveFileNames := ACaseInsensitiveFileNames;
FFlags := GRIDFILE_NOMD5;
if ACompressed then
FFlags := FFlags or GRIDFILE_COMPRESS;
if AEncryptionKey <> '' then
FFlags := FFlags or GRIDFILE_ENCRYPT;
if msmCreate in AMode then
begin
FGridFileWriter := FGridFS.writerCreate(AFileName, FFlags);
FGridFile := FGridFileWriter;
FGridFileWriter.Truncate(0);
end
else
begin
FGridFile := FGridFS.find(AFileName, msmWrite in AMode);
if FGridFile = nil then
raise EMongo.Create(SFileNotFound, AFileName, E_FileNotFound);
if msmWrite in AMode then
FGridFileWriter := FGridFile as IGridfileWriter;
if FGridFile.getStoredChunkCount <> FGridFile.getChunkCount then
FStatus := mssMissingChunks;
end;
FZlibAESContext := create_ZLib_AES_filter_context(FFlags);
gridfile_set_filter_context(FGridFile.Handle, FZlibAESContext);
if (AEncryptionKey <> '') and (ZLib_AES_filter_context_set_encryption_key(FZlibAESContext, PAnsiChar(AnsiString(AEncryptionKey)), aklLenToKeyLen[AEncryptionBits]) <> 0) then
raise EMongo.Create(SFailedInitializingEncryptionKey, E_FailedInitializingEncryptionKey);
end;
destructor TMongoStream.Destroy;
begin
FGridFileWriter := nil;
FGridFile := nil;
if FGridFS <> nil then
begin
FGridFS.Free;
FGridFS := nil;
end;
inherited;
if FZlibAESContext <> nil then
destroy_ZLib_AES_filter_context(FZlibAESContext, FFlags);
end;
procedure TMongoStream.CheckGridFile;
begin
if FGridFile = nil then
raise EMongo.Create(SFGridFileIsNil, E_FGridFileIsNil);
end;
procedure TMongoStream.CheckGridFS;
begin
if FGridFS = nil then
raise EMongo.Create(SFGridFSIsNil, E_FGridFSIsNil);
end;
procedure TMongoStream.CheckWriteSupport;
begin
if FGridFileWriter = nil then
raise EMongo.Create(SStreamNotCreatedForWriting, E_StreamNotCreatedForWriting);
end;
procedure TMongoStream.EnforceStatusOK;
begin
if FStatus <> mssOK then
raise EMongo.Create(SStatusMustBeOKInOrderToAllowStre, E_StatusMustBeOKInOrderToAllowStre);
end;
function TMongoStream.GetCaseInsensitiveNames: Boolean;
begin
CheckGridFS;
Result := FGridFS.CaseInsensitiveFileNames;
end;
function TMongoStream.GetID: IBsonOID;
begin
CheckGridFile;
Result := FGridFile.getId;
end;
function TMongoStream.GetSize: {$IFNDEF VER130}Int64{$ELSE}{$IFDef Enterprise}Int64{$ELSE}Longint{$ENDIF}{$ENDIF};
begin
CheckGridFile;
Result := FGridFile.getLength;
end;
function TMongoStream.Read(var Buffer; Count: Longint): Longint;
begin
EnforceStatusOK;
CheckGridFile;
Result := FGridFile.Read(@Buffer, Count);
inc(FCurPos, Result);
end;
{$IFDEF DELPHI2007}
function TMongoStream.Seek(Offset: longint; Origin: Word ): longint;
{$ELSE}
function TMongoStream.Seek(Offset: {$IFDef Enterprise} Int64 {$Else} longint {$EndIf}; Origin: {$IFNDEF VER130}TSeekOrigin{$Else}{$IFDef Enterprise}TSeekOrigin{$ELSE}Word{$ENDIF}{$ENDIF}): {$IFDef Enterprise} Int64 {$Else} longint {$EndIf};
{$ENDIF}
begin
CheckGridFile;
case Origin of
soFromBeginning : FCurPos := Offset;
soFromCurrent : FCurPos := FCurPos + Offset;
soFromEnd : FCurPos := Size + Offset;
end;
Result := FGridFile.Seek(FCurPos);
end;
{$IFDEF DELPHI2007}
function TMongoStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
case Origin of
soBeginning : FCurPos := Offset;
soCurrent : FCurPos := FCurPos + Offset;
soEnd : FCurPos := Size + Offset;
end;
Result := FGridFile.Seek(FCurPos);
end;
{$ENDIF}
{$IFDEF DELPHI2007}
procedure TMongoStream.SetSize(NewSize: longint);
{$ELSE}
procedure TMongoStream.SetSize(NewSize: {$IFDef Enterprise} Int64 {$Else} longint {$EndIf});
{$ENDIF}
begin
CheckWriteSupport;
FCurPos := FGridFileWriter.setSize(NewSize);
end;
{$IFDEF DELPHI2007}
procedure TMongoStream.SetSize(const NewSize: Int64);
begin
CheckWriteSupport;
FCurPos := FGridFileWriter.setSize(NewSize);
end;
{$ENDIF}
procedure TMongoStream.SerializeWithJournal;
var
Cmd : IBson;
begin
(* This command will cause Mongo database to wait until Journal file is written before returning *)
Cmd := BSON([GET_LAST_ERROR_CMD, 1, WAIT_FOR_JOURNAL_OPTION, 1]);
FLastSerializeWithJournalResult := FMongo.command(FDB, Cmd);
end;
procedure TMongoStream.CheckSerializeWithJournal;
begin
if FSerializedWithJournal and (FBytesWritten > FSerializeWithJournalByteWritten) then
begin
FBytesWritten := 0;
SerializeWithJournal;
end;
end;
{$IFDEF DELPHI2007}
procedure TMongoStream.SetSize64(const NewSize : Int64);
begin
SetSize(NewSize);
end;
{$ENDIF}
function TMongoStream.Write(const Buffer; Count: Longint): Longint;
begin
CheckWriteSupport;
Result := FGridFileWriter.Write(@Buffer, Count);
inc(FCurPos, Result);
inc(FBytesWritten, Result);
CheckSerializeWithJournal;
end;
end.
|
{********************************************************}
{ }
{ Zeos Database Objects }
{ PostgreSql Transaction component }
{ }
{ Copyright (c) 1999-2001 Sergey Seroukhov }
{ Copyright (c) 1999-2002 Zeos Development Group }
{ }
{********************************************************}
unit ZPgSqlTr;
interface
{$R *.dcr}
uses
Classes, ZDirPgSql, ZPgSqlCon, ZTransact, ZLibPgSql, ZSqlTypes, DB, ZDBaseConst;
{$IFNDEF LINUX}
{$INCLUDE ..\Zeos.inc}
{$ELSE}
{$INCLUDE ../Zeos.inc}
{$ENDIF}
type
{ PostgreSql transaction }
TZPgSqlTransact = class(TZTransact)
private
FNotice: AnsiString;
function GetDatabase: TZPgSqlDatabase;
function GetPID: Integer;
procedure SetDatabase(Value: TZPgSqlDatabase);
function GetLastInsertOid: Oid;
function GetTransIsolation: TZPgSqlTransIsolation;
procedure SetTransIsolation(const Value: TZPgSqlTransIsolation);
function GetNewStyleTransactions: Boolean;
procedure SetNewStyleTransactions(const Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
procedure Connect; override;
procedure Recovery(Force: Boolean); override;
procedure Reset;
function ExecSql(Sql: WideString): LongInt; override;
procedure AddMonitor(Monitor: TZMonitor); override;
procedure DeleteMonitor(Monitor: TZMonitor); override;
property PID: Integer read GetPID;
property LastInsertOid: Oid read GetLastInsertOid;
property Notice: AnsiString read FNotice;
published
property Database: TZPgSqlDatabase read GetDatabase write SetDatabase;
property AutoRecovery;
property TransactSafe;
property TransIsolation: TZPgSqlTransIsolation read GetTransIsolation
write SetTransIsolation;
property NewStyleTransactions: Boolean read GetNewStyleTransactions
write SetNewStyleTransactions default False;
end;
{ PostgreSQL class for asynchronous notifying}
TZPgSqlNotify = class(TZNotify)
private
FDatabase: TZPgSqlDatabase;
protected
procedure Disconnect(Sender: TObject); virtual;
procedure SetDatabase(Value: TZPgSqlDatabase); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
published
property Database: TZPgSqlDatabase read FDatabase write SetDatabase;
end;
implementation
{***************** TZPgSqlTransact implementation *****************}
{ Class constructor }
constructor TZPgSqlTransact.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHandle := TDirPgSqlTransact.Create(nil);
FQuery := TDirPgSqlQuery.Create(nil, TDirPgSqlTransact(FHandle));
AutoRecovery := True;
FDatabaseType := dtPostgreSql;
end;
{ Get database component }
function TZPgSqlTransact.GetDatabase: TZPgSqlDatabase;
begin
Result := TZPgSqlDatabase(FDatabase);
end;
{ Set database component }
procedure TZPgSqlTransact.SetDatabase(Value: TZPgSqlDatabase);
begin
inherited SetDatabase(Value);
end;
{ Retrieve backend server's process id (PID) }
function TZPgSqlTransact.GetPID: Integer;
begin
Result := TDirPgSqlTransact(Handle).PID;
end;
{ Get last inserted oid value }
function TZPgSqlTransact.GetLastInsertOid: Oid;
begin
Result := TDirPgSqlQuery(FQuery).LastInsertOid;
end;
{ Get transaction type }
function TZPgSqlTransact.GetTransIsolation: TZPgSqlTransIsolation;
begin
Result := TDirPgSqlTransact(FHandle).TransIsolation;
end;
{ Set transaction type }
procedure TZPgSqlTransact.SetTransIsolation(const Value: TZPgSqlTransIsolation);
begin
if Value <> TDirPgSqlTransact(FHandle).TransIsolation then
begin
Disconnect;
TDirPgSqlTransact(FHandle).TransIsolation := Value;
end;
end;
{ Execute Sql. Overrided to provide NoticeProcessor support}
function TZPgSqlTransact.ExecSql(Sql: WideString): LongInt;
begin
TDirPgSqlTransact(Handle).Notice := '';
Result := inherited ExecSql(Sql);
{ Setting possible notices from the database backend }
fNotice := TDirPgSqlTransact(Handle).Notice;
end;
{ Recovery after errors }
procedure TZPgSqlTransact.Recovery(Force: Boolean);
begin
if AutoRecovery or Force then
FHandle.Rollback;
end;
{ Connect to Sql-database }
procedure TZPgSqlTransact.Connect;
begin
inherited Connect;
ExecSql('SET DateStyle TO ''ISO''');
end;
{ Add monitor into monitor list }
procedure TZPgSqlTransact.AddMonitor(Monitor: TZMonitor);
begin
ZDirPgSql.MonitorList.AddMonitor(Monitor);
end;
{ Delete monitor from monitor list }
procedure TZPgSqlTransact.DeleteMonitor(Monitor: TZMonitor);
begin
ZDirPgSql.MonitorList.DeleteMonitor(Monitor);
end;
{ Reconnect to the database server}
procedure TZPgSqlTransact.Reset;
begin
TDirPgSqlTransact(Handle).Reset;
end;
function TZPgSqlTransact.GetNewStyleTransactions: Boolean;
begin
Result := TDirPgSqlTransact(FHandle).NewStyleTransactions;
end;
procedure TZPgSqlTransact.SetNewStyleTransactions(const Value: Boolean);
begin
TDirPgSqlTransact(FHandle).NewStyleTransactions := Value;
end;
{***************** TZPgSqlNotify implementation *****************}
{ Class constructor }
constructor TZPgSqlNotify.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHandle := TDirPgSqlNotify.Create(nil, nil);
SetTransact(TZPgSqlTransact.Create(Self));
TZPgSqlTransact(FTransact).TransactSafe:=False;
TZPgSqlTransact(FTransact).OnBeforeDisconnect:=Disconnect;
end;
{ Handles external Transaction's disable }
procedure TZPgSqlNotify.Disconnect(Sender: TObject);
begin
TZPgSqlTransact(FTransact).OnBeforeDisconnect:=nil;
Active:=False;
TZPgSqlTransact(FTransact).OnBeforeDisconnect:=Disconnect;
end;
destructor TZPgSqlNotify.Destroy;
begin
FTransact.Free;
inherited Destroy;
end;
procedure TZPgSqlNotify.SetDatabase(Value: TZPgSqlDatabase);
begin
if FDatabase<>Value then
begin
if Active then Close;
FDatabase:=Value;
FTransact.Database:=FDatabase;
end;
end;
procedure TZPgSqlNotify.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FDatabase) and (Operation = opRemove) then
Database:=nil;
end;
{ Open autoactivated datasets }
procedure TZPgSqlNotify.Loaded;
begin
inherited Loaded;
if Active and Assigned(Database) then
Open;
end;
end.
|
unit FileAccess;
interface
type
HCkBinData = Pointer;
HCkDateTime = Pointer;
HCkByteData = Pointer;
HCkFileAccess = Pointer;
HCkString = Pointer;
HCkStringBuilder = Pointer;
function CkFileAccess_Create: HCkFileAccess; stdcall;
procedure CkFileAccess_Dispose(handle: HCkFileAccess); stdcall;
procedure CkFileAccess_getCurrentDir(objHandle: HCkFileAccess; outPropVal: HCkString); stdcall;
function CkFileAccess__currentDir(objHandle: HCkFileAccess): PWideChar; stdcall;
procedure CkFileAccess_getDebugLogFilePath(objHandle: HCkFileAccess; outPropVal: HCkString); stdcall;
procedure CkFileAccess_putDebugLogFilePath(objHandle: HCkFileAccess; newPropVal: PWideChar); stdcall;
function CkFileAccess__debugLogFilePath(objHandle: HCkFileAccess): PWideChar; stdcall;
function CkFileAccess_getEndOfFile(objHandle: HCkFileAccess): wordbool; stdcall;
function CkFileAccess_getFileOpenError(objHandle: HCkFileAccess): Integer; stdcall;
procedure CkFileAccess_getFileOpenErrorMsg(objHandle: HCkFileAccess; outPropVal: HCkString); stdcall;
function CkFileAccess__fileOpenErrorMsg(objHandle: HCkFileAccess): PWideChar; stdcall;
procedure CkFileAccess_getLastErrorHtml(objHandle: HCkFileAccess; outPropVal: HCkString); stdcall;
function CkFileAccess__lastErrorHtml(objHandle: HCkFileAccess): PWideChar; stdcall;
procedure CkFileAccess_getLastErrorText(objHandle: HCkFileAccess; outPropVal: HCkString); stdcall;
function CkFileAccess__lastErrorText(objHandle: HCkFileAccess): PWideChar; stdcall;
procedure CkFileAccess_getLastErrorXml(objHandle: HCkFileAccess; outPropVal: HCkString); stdcall;
function CkFileAccess__lastErrorXml(objHandle: HCkFileAccess): PWideChar; stdcall;
function CkFileAccess_getLastMethodSuccess(objHandle: HCkFileAccess): wordbool; stdcall;
procedure CkFileAccess_putLastMethodSuccess(objHandle: HCkFileAccess; newPropVal: wordbool); stdcall;
function CkFileAccess_getVerboseLogging(objHandle: HCkFileAccess): wordbool; stdcall;
procedure CkFileAccess_putVerboseLogging(objHandle: HCkFileAccess; newPropVal: wordbool); stdcall;
procedure CkFileAccess_getVersion(objHandle: HCkFileAccess; outPropVal: HCkString); stdcall;
function CkFileAccess__version(objHandle: HCkFileAccess): PWideChar; stdcall;
function CkFileAccess_AppendAnsi(objHandle: HCkFileAccess; text: PWideChar): wordbool; stdcall;
function CkFileAccess_AppendBd(objHandle: HCkFileAccess; bd: HCkBinData): wordbool; stdcall;
function CkFileAccess_AppendSb(objHandle: HCkFileAccess; sb: HCkStringBuilder; charset: PWideChar): wordbool; stdcall;
function CkFileAccess_AppendText(objHandle: HCkFileAccess; str: PWideChar; charset: PWideChar): wordbool; stdcall;
function CkFileAccess_AppendUnicodeBOM(objHandle: HCkFileAccess): wordbool; stdcall;
function CkFileAccess_AppendUtf8BOM(objHandle: HCkFileAccess): wordbool; stdcall;
function CkFileAccess_DirAutoCreate(objHandle: HCkFileAccess; filePath: PWideChar): wordbool; stdcall;
function CkFileAccess_DirCreate(objHandle: HCkFileAccess; dirPath: PWideChar): wordbool; stdcall;
function CkFileAccess_DirDelete(objHandle: HCkFileAccess; dirPath: PWideChar): wordbool; stdcall;
function CkFileAccess_DirEnsureExists(objHandle: HCkFileAccess; dirPath: PWideChar): wordbool; stdcall;
procedure CkFileAccess_FileClose(objHandle: HCkFileAccess); stdcall;
function CkFileAccess_FileContentsEqual(objHandle: HCkFileAccess; filePath1: PWideChar; filePath2: PWideChar): wordbool; stdcall;
function CkFileAccess_FileCopy(objHandle: HCkFileAccess; existingFilepath: PWideChar; newFilepath: PWideChar; failIfExists: wordbool): wordbool; stdcall;
function CkFileAccess_FileDelete(objHandle: HCkFileAccess; filePath: PWideChar): wordbool; stdcall;
function CkFileAccess_FileExists(objHandle: HCkFileAccess; filePath: PWideChar): wordbool; stdcall;
function CkFileAccess_FileExists3(objHandle: HCkFileAccess; path: PWideChar): Integer; stdcall;
function CkFileAccess_FileOpen(objHandle: HCkFileAccess; filePath: PWideChar; accessMode: LongWord; shareMode: LongWord; createDisposition: LongWord; attributes: LongWord): wordbool; stdcall;
function CkFileAccess_FileRead(objHandle: HCkFileAccess; maxNumBytes: Integer; outData: HCkByteData): wordbool; stdcall;
function CkFileAccess_FileReadBd(objHandle: HCkFileAccess; maxNumBytes: Integer; binData: HCkBinData): wordbool; stdcall;
function CkFileAccess_FileRename(objHandle: HCkFileAccess; existingFilepath: PWideChar; newFilepath: PWideChar): wordbool; stdcall;
function CkFileAccess_FileSeek(objHandle: HCkFileAccess; offset: Integer; origin: Integer): wordbool; stdcall;
function CkFileAccess_FileSize(objHandle: HCkFileAccess; filePath: PWideChar): Integer; stdcall;
function CkFileAccess_FileWrite(objHandle: HCkFileAccess; data: HCkByteData): wordbool; stdcall;
function CkFileAccess_FileWriteBd(objHandle: HCkFileAccess; binData: HCkBinData; offset: Integer; numBytes: Integer): wordbool; stdcall;
function CkFileAccess_GenBlockId(objHandle: HCkFileAccess; index: Integer; length: Integer; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkFileAccess__genBlockId(objHandle: HCkFileAccess; index: Integer; length: Integer; encoding: PWideChar): PWideChar; stdcall;
function CkFileAccess_GetDirectoryName(objHandle: HCkFileAccess; path: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkFileAccess__getDirectoryName(objHandle: HCkFileAccess; path: PWideChar): PWideChar; stdcall;
function CkFileAccess_GetExtension(objHandle: HCkFileAccess; path: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkFileAccess__getExtension(objHandle: HCkFileAccess; path: PWideChar): PWideChar; stdcall;
function CkFileAccess_GetFileName(objHandle: HCkFileAccess; path: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkFileAccess__getFileName(objHandle: HCkFileAccess; path: PWideChar): PWideChar; stdcall;
function CkFileAccess_GetFileNameWithoutExtension(objHandle: HCkFileAccess; path: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkFileAccess__getFileNameWithoutExtension(objHandle: HCkFileAccess; path: PWideChar): PWideChar; stdcall;
function CkFileAccess_GetFileTime(objHandle: HCkFileAccess; path: PWideChar; which: Integer): HCkDateTime; stdcall;
function CkFileAccess_GetLastModified(objHandle: HCkFileAccess; path: PWideChar): HCkDateTime; stdcall;
function CkFileAccess_GetNumBlocks(objHandle: HCkFileAccess; blockSize: Integer): Integer; stdcall;
function CkFileAccess_GetTempFilename(objHandle: HCkFileAccess; dirPath: PWideChar; prefix: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkFileAccess__getTempFilename(objHandle: HCkFileAccess; dirPath: PWideChar; prefix: PWideChar): PWideChar; stdcall;
function CkFileAccess_OpenForAppend(objHandle: HCkFileAccess; filePath: PWideChar): wordbool; stdcall;
function CkFileAccess_OpenForRead(objHandle: HCkFileAccess; filePath: PWideChar): wordbool; stdcall;
function CkFileAccess_OpenForReadWrite(objHandle: HCkFileAccess; filePath: PWideChar): wordbool; stdcall;
function CkFileAccess_OpenForWrite(objHandle: HCkFileAccess; filePath: PWideChar): wordbool; stdcall;
function CkFileAccess_ReadBinaryToEncoded(objHandle: HCkFileAccess; filePath: PWideChar; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkFileAccess__readBinaryToEncoded(objHandle: HCkFileAccess; filePath: PWideChar; encoding: PWideChar): PWideChar; stdcall;
function CkFileAccess_ReadBlock(objHandle: HCkFileAccess; blockIndex: Integer; blockSize: Integer; outData: HCkByteData): wordbool; stdcall;
function CkFileAccess_ReadEntireFile(objHandle: HCkFileAccess; filePath: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkFileAccess_ReadEntireTextFile(objHandle: HCkFileAccess; filePath: PWideChar; charset: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkFileAccess__readEntireTextFile(objHandle: HCkFileAccess; filePath: PWideChar; charset: PWideChar): PWideChar; stdcall;
function CkFileAccess_ReassembleFile(objHandle: HCkFileAccess; partsDirPath: PWideChar; partPrefix: PWideChar; partExtension: PWideChar; reassembledFilename: PWideChar): wordbool; stdcall;
function CkFileAccess_ReplaceStrings(objHandle: HCkFileAccess; filePath: PWideChar; charset: PWideChar; existingString: PWideChar; replacementString: PWideChar): Integer; stdcall;
function CkFileAccess_SaveLastError(objHandle: HCkFileAccess; path: PWideChar): wordbool; stdcall;
function CkFileAccess_SetCurrentDir(objHandle: HCkFileAccess; dirPath: PWideChar): wordbool; stdcall;
function CkFileAccess_SetFileTimes(objHandle: HCkFileAccess; filePath: PWideChar; createTime: HCkDateTime; lastAccessTime: HCkDateTime; lastModTime: HCkDateTime): wordbool; stdcall;
function CkFileAccess_SetLastModified(objHandle: HCkFileAccess; filePath: PWideChar; lastModified: HCkDateTime): wordbool; stdcall;
function CkFileAccess_SplitFile(objHandle: HCkFileAccess; fileToSplit: PWideChar; partPrefix: PWideChar; partExtension: PWideChar; partSize: Integer; destDir: PWideChar): wordbool; stdcall;
function CkFileAccess_TreeDelete(objHandle: HCkFileAccess; path: PWideChar): wordbool; stdcall;
function CkFileAccess_WriteEntireFile(objHandle: HCkFileAccess; filePath: PWideChar; fileData: HCkByteData): wordbool; stdcall;
function CkFileAccess_WriteEntireTextFile(objHandle: HCkFileAccess; filePath: PWideChar; textData: PWideChar; charset: PWideChar; includedPreamble: wordbool): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkFileAccess_Create; external DLLName;
procedure CkFileAccess_Dispose; external DLLName;
procedure CkFileAccess_getCurrentDir; external DLLName;
function CkFileAccess__currentDir; external DLLName;
procedure CkFileAccess_getDebugLogFilePath; external DLLName;
procedure CkFileAccess_putDebugLogFilePath; external DLLName;
function CkFileAccess__debugLogFilePath; external DLLName;
function CkFileAccess_getEndOfFile; external DLLName;
function CkFileAccess_getFileOpenError; external DLLName;
procedure CkFileAccess_getFileOpenErrorMsg; external DLLName;
function CkFileAccess__fileOpenErrorMsg; external DLLName;
procedure CkFileAccess_getLastErrorHtml; external DLLName;
function CkFileAccess__lastErrorHtml; external DLLName;
procedure CkFileAccess_getLastErrorText; external DLLName;
function CkFileAccess__lastErrorText; external DLLName;
procedure CkFileAccess_getLastErrorXml; external DLLName;
function CkFileAccess__lastErrorXml; external DLLName;
function CkFileAccess_getLastMethodSuccess; external DLLName;
procedure CkFileAccess_putLastMethodSuccess; external DLLName;
function CkFileAccess_getVerboseLogging; external DLLName;
procedure CkFileAccess_putVerboseLogging; external DLLName;
procedure CkFileAccess_getVersion; external DLLName;
function CkFileAccess__version; external DLLName;
function CkFileAccess_AppendAnsi; external DLLName;
function CkFileAccess_AppendBd; external DLLName;
function CkFileAccess_AppendSb; external DLLName;
function CkFileAccess_AppendText; external DLLName;
function CkFileAccess_AppendUnicodeBOM; external DLLName;
function CkFileAccess_AppendUtf8BOM; external DLLName;
function CkFileAccess_DirAutoCreate; external DLLName;
function CkFileAccess_DirCreate; external DLLName;
function CkFileAccess_DirDelete; external DLLName;
function CkFileAccess_DirEnsureExists; external DLLName;
procedure CkFileAccess_FileClose; external DLLName;
function CkFileAccess_FileContentsEqual; external DLLName;
function CkFileAccess_FileCopy; external DLLName;
function CkFileAccess_FileDelete; external DLLName;
function CkFileAccess_FileExists; external DLLName;
function CkFileAccess_FileExists3; external DLLName;
function CkFileAccess_FileOpen; external DLLName;
function CkFileAccess_FileRead; external DLLName;
function CkFileAccess_FileReadBd; external DLLName;
function CkFileAccess_FileRename; external DLLName;
function CkFileAccess_FileSeek; external DLLName;
function CkFileAccess_FileSize; external DLLName;
function CkFileAccess_FileWrite; external DLLName;
function CkFileAccess_FileWriteBd; external DLLName;
function CkFileAccess_GenBlockId; external DLLName;
function CkFileAccess__genBlockId; external DLLName;
function CkFileAccess_GetDirectoryName; external DLLName;
function CkFileAccess__getDirectoryName; external DLLName;
function CkFileAccess_GetExtension; external DLLName;
function CkFileAccess__getExtension; external DLLName;
function CkFileAccess_GetFileName; external DLLName;
function CkFileAccess__getFileName; external DLLName;
function CkFileAccess_GetFileNameWithoutExtension; external DLLName;
function CkFileAccess__getFileNameWithoutExtension; external DLLName;
function CkFileAccess_GetFileTime; external DLLName;
function CkFileAccess_GetLastModified; external DLLName;
function CkFileAccess_GetNumBlocks; external DLLName;
function CkFileAccess_GetTempFilename; external DLLName;
function CkFileAccess__getTempFilename; external DLLName;
function CkFileAccess_OpenForAppend; external DLLName;
function CkFileAccess_OpenForRead; external DLLName;
function CkFileAccess_OpenForReadWrite; external DLLName;
function CkFileAccess_OpenForWrite; external DLLName;
function CkFileAccess_ReadBinaryToEncoded; external DLLName;
function CkFileAccess__readBinaryToEncoded; external DLLName;
function CkFileAccess_ReadBlock; external DLLName;
function CkFileAccess_ReadEntireFile; external DLLName;
function CkFileAccess_ReadEntireTextFile; external DLLName;
function CkFileAccess__readEntireTextFile; external DLLName;
function CkFileAccess_ReassembleFile; external DLLName;
function CkFileAccess_ReplaceStrings; external DLLName;
function CkFileAccess_SaveLastError; external DLLName;
function CkFileAccess_SetCurrentDir; external DLLName;
function CkFileAccess_SetFileTimes; external DLLName;
function CkFileAccess_SetLastModified; external DLLName;
function CkFileAccess_SplitFile; external DLLName;
function CkFileAccess_TreeDelete; external DLLName;
function CkFileAccess_WriteEntireFile; external DLLName;
function CkFileAccess_WriteEntireTextFile; external DLLName;
end.
|
unit avProcess;
interface
uses Windows, Classes, SysUtils, ComCtrls, Messages, Dialogs, PsApi, TlHelp32,
avJobs, avEngine;
type
NTSTATUS = Cardinal;
const
SystemProcessesAndThreadsInformation = 5;
STATUS_SUCCESS = NTSTATUS($00000000);
THREAD_TERMINATE = $0001;
MIN_WAIT_REASON = 0;
MAX_WAIT_REASON = 26;
MIN_THREAD_STATE = 0;
MAX_THREAD_STATE = 7;
type
PUnicodeString = ^TUnicodeString;
TUnicodeString = packed record
Length : WORD;
MaximumLength : WORD;
Buffer : PWideChar;
end;
SYSTEM_PROCESS_IMAGE_NAME_INFORMATION = packed record
ProcessId : Cardinal;
ImageName : TUnicodeString;
end;
PSYSTEM_PROCESS_IMAGE_NAME_INFORMATION = ^SYSTEM_PROCESS_IMAGE_NAME_INFORMATION;
PClientID = ^TClientID;
TClientID = packed record
UniqueProcess : cardinal;
UniqueThread : cardinal;
end;
PSYSTEM_THREADS = ^SYSTEM_THREADS;
SYSTEM_THREADS = packed record
KernelTime : LARGE_INTEGER;
UserTime : LARGE_INTEGER;
CreateTime : LARGE_INTEGER;
WaitTime : ULONG;
StartAddress : Pointer;
ClientID : TClientID;
Priority : Integer;
BasePriority : Integer;
ContextSwitchCount : ULONG;
State : Longint;
WaitReason : Longint;
Reserved : ULONG;
end;
PVM_COUNTERS = ^VM_COUNTERS;
VM_COUNTERS = packed record
PeakVirtualSize,
VirtualSize,
PageFaultCount,
PeakWorkingSetSize,
WorkingSetSize,
QuotaPeakPagedPoolUsage,
QuotaPagedPoolUsage,
QuotaPeakNonPagedPoolUsage,
QuotaNonPagedPoolUsage,
PagefileUsage,
PeakPagefileUsage : DWORD;
end;
PIO_COUNTERS = ^IO_COUNTERS;
IO_COUNTERS = packed record
ReadOperationCount,
WriteOperationCount,
OtherOperationCount,
ReadTransferCount,
WriteTransferCount,
OtherTransferCount : LARGE_INTEGER;
end;
PSYSTEM_PROCESSES = ^SYSTEM_PROCESSES;
SYSTEM_PROCESSES = packed record
NextEntryDelta,
ThreadCount : DWORD;
Reserved1 : array [0..5] of dword;
CreateTime,
UserTime,
KernelTime : LARGE_INTEGER;
ProcessName : TUnicodeString;
BasePriority : DWORD;
ProcessId,
InheritedFromProcessId,
HandleCount : DWORD;
Reserved2 : array [0..1] of dword;
VmCounters : VM_COUNTERS;
PrivatePageCount : ULONG;
IoCounters : IO_COUNTERS;
ThreadInfo : array [0..0] of SYSTEM_THREADS;
end;
PTOKEN_USER = ^TOKEN_USER;
TOKEN_USER = record
User : TSidAndAttributes;
end;
TProcessInfo = packed record
ProcessName : string;
ProcessId : cardinal;
Path : string;
User : string;
ThreadCount : DWORD;
HandleCount : DWORD;
BasePriority : DWORD;
ParentId : DWORD;
CreateTime,
UserTime,
KernelTime : LARGE_INTEGER;
PrivatePage : ULONG;
end;
procedure EnableDebugPrivileges;
procedure DisableDebugPrivileges;
function GetProcessesList(var ProcessList : TListView) : integer;
function GetThreadList(ProcessId : cardinal; var ThreadList : TListView): integer;
function GetFileName(ProcessId : cardinal) : string;
function GetFileNameEx(ProcessId : cardinal) : string;
function GetNamebySID(destSystem: PChar; sid : PSID) : PChar;
function GetProcessUserName(ProcessId : cardinal) : PChar;
function ZwQuerySystemInformation(dwSystemInformationClass: DWORD;
pSystemInformation: Pointer;
dwSystemInformationLength: DWORD;
var iReturnLength : DWORD): NTSTATUS;
stdcall; external 'ntdll.dll';
function OpenThread(dwDesiredAccess : DWORD;
bInheritHandle : BOOL;
dwThreadId : DWORD) : THandle;
stdcall; external 'kernel32.dll';
function GetProcessInfo(ProcessId : cardinal) : TProcessInfo;
function GetPathName(FullFileName : string) : string;
function KillProcessTP(ProcessId : cardinal) : boolean;
function KillProcessTJ(ProcessId : cardinal) : boolean;
function KillProcessTE(ProcessId : cardinal) : boolean;
function KillProcessWQ(ProcessId : cardinal) : boolean;
function KillProcessWC(ProcessId : cardinal) : boolean;
function KillProcessTT(ProcessId : cardinal) : boolean;
function Is64Process(ProcessId : cardinal) : integer;
implementation
procedure EnableDebugPrivileges;
var
hToken : THandle;
tp : TTokenPrivileges;
DebugNameValue : Int64;
ret : Cardinal;
begin
OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken);
LookupPrivilegeValue(nil,'SeDebugPrivilege', DebugNameValue);
tp.PrivilegeCount := 1;
tp.Privileges[0].Luid := DebugNameValue;
tp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, False, tp, sizeof(tp), nil, ret);
end;
procedure DisableDebugPrivileges;
var
hToken : THandle;
tp : TTokenPrivileges;
DebugNameValue : Int64;
ret : Cardinal;
begin
OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken);
LookupPrivilegeValue(nil, 'SeDebugPrivilege', DebugNameValue);
tp.PrivilegeCount := 1;
tp.Privileges[0].Luid := DebugNameValue;
tp.Privileges[0].Attributes := 0;
AdjustTokenPrivileges(hToken, False, tp, sizeof(tp), nil, ret);
end;
function GetProcessesList(var ProcessList: TListView): integer;
var
ret : NTSTATUS;
pBuffer, pCur : PSYSTEM_PROCESSES;
ReturnLength : DWORD;
ProcessName : String;
index : integer;
ProcessItem : TListItem;
begin
ProcessList.Clear;
Result := 0;
ReturnLength := 0;
ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
nil,
0,
ReturnLength);
pBuffer := AllocMem(ReturnLength);
ret := ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
pBuffer,
ReturnLength,
ReturnLength);
if ret = STATUS_SUCCESS then
begin
index := 0;
pCur := pBuffer;
while true do begin
inc(index);
if pCur.ProcessName.Length = 0 then ProcessName := 'System Idle Process'
else ProcessName := WideCharToString(pCur.ProcessName.Buffer);
with ProcessList do
begin
ProcessItem := Items.Add;
ProcessItem.Caption := ProcessName;
ProcessItem.SubItems.Add(IntToStr(pCur.ProcessId));
ProcessItem.SubItems.Add(string(GetProcessUserName(pCur.ProcessId)));
ProcessItem.SubItems.Add(GetFileNameEx(pCur.ProcessId));
end;
if pCur.NextEntryDelta = 0 then Break;
pCur := Ptr(DWORD(pCur) + pCur.NextEntryDelta);
end;
Result := index;
end;
FreeMem(pBuffer);
end;
function GetThreadList(ProcessId : cardinal; var ThreadList : TListView): integer;
const
ThreadStates : array[MIN_THREAD_STATE..MAX_THREAD_STATE] of String =
('Init', 'Ready', 'Running', 'Standby', 'Term', 'Wait', 'Trans', 'Unknown');
WaitReasons : array[MIN_WAIT_REASON..MAX_WAIT_REASON] of String =
('Executive', 'FreePage', 'PageIn', 'PoolAlloc', 'DelayExec', 'Suspend',
'UserRequest', 'WrExecutive', 'WrFreePage', 'WrPageIn', 'WrPoolAlloc',
'WrDelayExec', 'WrSuspend', 'WrUserRequest', 'WrEventPair', 'WrQueue',
'LpcReceive', 'WrLpcReply', 'WrVirtualMem', 'WrPageOut', 'WrRendezvous',
'Spare2', 'Spare3', 'Spare4', 'Spare5', 'Spare6', 'WrKernel');
var
ret : NTSTATUS;
pBuffer, pCur : PSYSTEM_PROCESSES;
ReturnLength : DWORD;
index : integer;
hThread : THandle;
ThreadItem : TListItem;
begin
ThreadList.Clear;
ReturnLength := 0;
ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
nil,
0,
ReturnLength);
GetMem(pBuffer, ReturnLength);
ret := ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
pBuffer,
ReturnLength,
ReturnLength);
if ret = STATUS_SUCCESS then
begin
pCur := pBuffer;
while true do begin
if pCur.ProcessId = ProcessId then
begin
Result := pCur.ThreadCount;
for index := 0 to pCur.ThreadCount-1 do
with ThreadList do
begin
ThreadItem := Items.Add;
ThreadItem.Caption := inttostr(pCur.ThreadInfo[index].ClientID.UniqueThread);
ThreadItem.SubItems.Add('0x' +
inttohex(integer(pCur.ThreadInfo[index].StartAddress), 8));
ThreadItem.SubItems.Add(inttostr(pCur.ThreadInfo[index].BasePriority));
ThreadItem.SubItems.Add(inttostr(pCur.ThreadInfo[index].Priority));
ThreadItem.SubItems.Add(ThreadStates[pCur.ThreadInfo[index].State]);
if pCur.ThreadInfo[index].WaitReason < 27 then
ThreadItem.SubItems.Add(WaitReasons[pCur.ThreadInfo[index].WaitReason]);
end;
end;
if pCur.NextEntryDelta = 0 then Break;
pCur := Ptr(DWORD(pCur) + pCur.NextEntryDelta);
end;
end;
FreeMem(pBuffer);
end;
function GetFileName(ProcessId : cardinal) : string;
var
hProcess : THandle;
begin
Result := '';
hProcess := OpenProcess(PROCESS_ALL_ACCESS, False, ProcessId);
if hProcess <> 0 then
try
SetLength(Result, MAX_PATH);
if GetModuleFileNameEx(hProcess, 0, PChar(Result), MAX_PATH) = 0 then
Result := '';
finally
CloseHandle(hProcess);
end;
end;
function DOSFileName(lpDeviceFileName: PWideChar): WideString;
var
lpDeviceName : array[0..1024] of WideChar;
lpDrive : WideString;
actDrive : WideChar;
FileName : WideString;
begin
FileName := '';
for actDrive := 'A' to 'Z' do
begin
lpDrive := WideString(actDrive) + ':';
if (QueryDosDeviceW(PWideChar(lpDrive), lpDeviceName, 1024) <> 0) then
begin
if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE, lpDeviceName, lstrlenW(lpDeviceName),
lpDeviceFileName, lstrlenW(lpDeviceName)) = CSTR_EQUAL) then
begin
FileName := WideString(lpDeviceFileName);
Delete(FileName, 1, lstrlenW(lpDeviceName));
FileName := WideString(lpDrive) + FileName;
Result := FileName;
end;
end;
end;
end;
function GetFileNameEx(ProcessId : cardinal) : string;
var
ReturnLength : DWORD;
ret : NTSTATUS;
ImageNameInformation : SYSTEM_PROCESS_IMAGE_NAME_INFORMATION;
begin
ImageNameInformation.ProcessId := ProcessId;
ImageNameInformation.ImageName.Length := 0;
ImageNameInformation.ImageName.MaximumLength := $1000;
GetMem(ImageNameInformation.ImageName.Buffer, $1000);
ret := ZwQuerySystemInformation(88,
@ImageNameInformation,
SizeOf(ImageNameInformation),
ReturnLength);
try
if ret = STATUS_SUCCESS then
Result := (DOSFileName(ImageNameInformation.ImageName.Buffer))
else
Result := '';
finally
FreeMem(ImageNameInformation.ImageName.Buffer);
ImageNameInformation.ImageName.Buffer := nil;
end;
end;
function GetPathName(FullFileName : string) : string;
var
StringLength : integer;
begin
StringLength := length(FullFileName);
while FullFileName[StringLength] <> '\' do
dec(StringLength);
Result := copy(FullFileName, 1, StringLength);
end;
function GetNamebySID(destSystem: PChar; sid: PSID):PChar;
var
Domain : PChar;
Needed : DWORD;
DomLen : DWORD;
use : SID_NAME_USE;
begin
Result := 0;
Needed := 0;
DomLen := 0;
LookupAccountSid(destSystem, sid, 0, Needed, 0, DomLen, use);
if GetLastError = ERROR_INSUFFICIENT_BUFFER then
begin
Result := HeapAlloc(GetProcessHeap, 0, Needed);
Domain := GetMemory(DomLen);
LookupAccountSid(destSystem, sid, Result, Needed, Domain, DomLen, use);
FreeMemory(Domain);
end;
end;
function GetProcessUserName(ProcessId : cardinal) : PChar;
var
Token : THandle;
Info : PTOKEN_USER;
Needed : DWORD;
begin
Result := 0;
if not OpenProcessToken(OpenProcess(PROCESS_ALL_ACCESS, FALSE, ProcessId),
TOKEN_QUERY, Token) then
exit;
Needed:=0;
GetTokenInformation(Token, TokenUser, 0, 0, Needed);
if GetLastError = ERROR_INSUFFICIENT_BUFFER then
begin
Info := HeapAlloc(GetProcessHeap, 0, Needed);
if GetTokenInformation(Token, TokenUser, Info, Needed, Needed) then
Result:=GetNamebySID(0, Info^.User.Sid);
HeapFree(GetProcessHeap,0, Info);
end;
end;
function GetProcessInfo(ProcessId : cardinal) : TProcessInfo;
var
ret : NTSTATUS;
pBuffer, pCur : PSYSTEM_PROCESSES;
ReturnLength : DWORD;
ProcessName : String;
index : integer;
ProcessItem : TListItem;
begin
ReturnLength := 0;
ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
nil,
0,
ReturnLength);
pBuffer := AllocMem(ReturnLength);
ret := ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
pBuffer,
ReturnLength,
ReturnLength);
if ret = STATUS_SUCCESS then
begin
pCur := pBuffer;
while true do begin
if pCur.ProcessId = ProcessId then
begin
Result.ProcessId := pCur.ProcessId;
Result.Path := GetFileNameEx(pCur.ProcessId);
Result.User := string(GetProcessUserName(pCur.ProcessId));
Result.ThreadCount := pCur.ThreadCount;
Result.HandleCount := pCur.HandleCount;
Result.BasePriority := pCur.BasePriority;
Result.ParentId := pCur.InheritedFromProcessId;
Result.CreateTime := pCur.CreateTime;
Result.UserTime := pCur.UserTime;
Result.KernelTime := pCur.KernelTime;
Result.PrivatePage := pCur.PrivatePageCount;
if pCur.ProcessName.Length = 0 then Result.ProcessName := 'System Idle Process'
else Result.ProcessName := WideCharToString(pCur.ProcessName.Buffer);
end;
if pCur.NextEntryDelta = 0 then Break;
pCur := Ptr(DWORD(pCur) + pCur.NextEntryDelta);
end;
end;
FreeMem(pBuffer);
end;
//завершение процесса с помощью API TrminateProcess
function KillProcessTP(ProcessId : cardinal) : boolean;
var
hProcess : THandle;
begin
hProcess := OpenProcess(PROCESS_TERMINATE, false, ProcessId);
if hProcess <> 0 then
begin
if TerminateProcess(hProcess, DWORD(-1)) then
Result := true
else
Result := false;
end
else
Result := false;
CloseHandle(hProcess);
end;
//завершение процесса последовательным вызовом API- функций
//CreateJobObject, AssignProcessToJobObject и TerminateJobObject
function KillProcessTJ(ProcessId : cardinal) : boolean;
var
hProcess,
hJob : THandle;
begin
hProcess := OpenProcess(PROCESS_SET_QUOTA or PROCESS_TERMINATE, false, ProcessId);
if hProcess <> 0 then
begin
hJob := CreateJobObject(nil, nil);
if hJob <> 0 then
begin
if (AssignProcessToJobObject(hJob, hProcess)) then
if (TerminateJobObject(hJob, DWORD(-1))) then
Result := true
else
Result := false
else
Result := false;
end
else
Result := false;
end
else
Result := false;
CloseHandle(hProcess);
CloseHandle(hJob);
end;
//Завершение процесса созданием удаленного
//потока с вызовом API-функции ExitProcess
function KillProcessTE(ProcessId : cardinal) : boolean;
var
hLibrary,
hProcess : THandle;
RtlCreateUserThread,
ExitProcessAddr,
Flag : DWORD;
begin
hLibrary := LoadLibrary('ntdll.dll');
RtlCreateUserThread := DWORD(GetProcAddress(hLibrary, 'RtlCreateUserThread'));
hLibrary := LoadLibrary('kernel32.dll');
ExitProcessAddr := DWORD(GetProcAddress(hLibrary, 'ExitProcess'));
hProcess := OpenProcess(PROCESS_ALL_ACCESS, false, ProcessId);
if hProcess <> 0 then
begin
asm
push 0
push 0
push 0
push ExitProcessAddr
push 0
push 0
push 0
push 0
push 0
push hProcess
call RtlCreateUserThread
mov Flag, eax
end;
if Flag = 0 then
Result := true
else
Result := false;
end
else
Result := false;
CloseHandle(hProcess);
end;
//Функция обратного вызова для KillProcessWQ
function QuitWindowsProc(Wnd : HWND; Param : LPARAM) : BOOL; stdcall;
var
ProcessId : cardinal;
begin
GetWindowThreadProcessId(Wnd, ProcessId);
if ProcessId = ULONG(Param) then
PostMessage(Wnd, WM_QUIT, 0, 0);
Result := true;
end;
//Завершение процесса путем отправки сообщения
//VM_QUIT окну процесса
function KillProcessWQ(ProcessId : cardinal) : boolean;
begin
EnumWindows(@QuitWindowsProc, LPARAM(ProcessId));
Result := true;
end;
//Функция обратного вызова для KillProcessWC
function CloseWindowsProc(Wnd : HWND; Param : LPARAM) : BOOL; stdcall;
var
ProcessId : cardinal;
begin
GetWindowThreadProcessId(Wnd, ProcessId);
if ProcessId = ULONG(Param) then
PostMessage(Wnd, WM_CLOSE, 0, 0);
Result := true;
end;
//Завершение процесса путем отправки сообщения
//VM_CLOSE окну процесса
function KillProcessWC(ProcessId : cardinal) : boolean;
begin
EnumWindows(@CloseWindowsProc, LPARAM(ProcessId));
Result := true;
end;
//Завершение процесса путем уничтожения всех
//его потоков API-функцией TerminateThread
function KillProcessTT(ProcessId : cardinal) : boolean;
var
ret : NTSTATUS;
pBuffer, pCur : PSYSTEM_PROCESSES;
ReturnLength : DWORD;
index : integer;
hThread : THandle;
begin
ReturnLength := 0;
Result := true;
ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
nil,
0,
ReturnLength);
GetMem(pBuffer, ReturnLength);
ret := ZwQuerySystemInformation(SystemProcessesAndThreadsInformation,
pBuffer,
ReturnLength,
ReturnLength);
if ret = STATUS_SUCCESS then
begin
pCur := pBuffer;
while true do begin
if pCur.ProcessId = ProcessId then
for index := 0 to pCur.ThreadCount-1 do
begin
hThread := OpenThread(THREAD_TERMINATE,
false,
pCur.ThreadInfo[index].ClientID.UniqueThread);
TerminateThread(hThread, DWORD(-1))
end;
if pCur.NextEntryDelta = 0 then Break;
pCur := Ptr(DWORD(pCur) + pCur.NextEntryDelta);
end;
end;
FreeMem(pBuffer);
end;
//определяет разрядность приложения в 64-разрядной Windows
//0 - не определено
//1 - 32-разрядное
//2 - 64-разрядное
function Is64Process(ProcessId : cardinal) : integer;
var
hProcess : THandle;
Wow64Process : BOOL;
begin
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION, false, ProcessId);
if hProcess <> 0 then
begin
IsWow64Process(hProcess, Wow64Process);
if Wow64Process then Result := 1
else Result := 2;
end
else
Result := 0;
end;
end.
|
unit VK.Client;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics,
FMX.Dialogs, IdHTTP, IdSSL, IdSSLOpenSSL, REST.Authenticator.OAuth.WebForm.FMX,
REST.Client, REST.Types, REST.Authenticator.OAuth,
DateUtils, IPPeerClient, VK.Types, system.JSON, System.StrUtils,
VK.JSON;
const
cAPIVersion = '5.50';
type
TVKApi = class(TObject)
private
const
cEndPoint = 'https://oauth.vk.com/authorize';
cEndMark = 2;
type
CountMessages = 0..200;
TVKAccountMethods = record
Owner: TVKApi;
procedure SetOnline;
procedure SetOffline;
end;
TVKWallMethods = record
Owner: TVKApi;
procedure Post(aOwnerID: string; aFriendsOnly,
aFromGroup: Boolean; aMessage: string);
end;
type
TVKMessageMethods = record
Owner: TVKApi;
{ затестить аргументы }
function Get(aOut: Boolean; aOffset: Cardinal;
aCount: CountMessages; aTimeOffset: Cardinal;
aFilters: TFiltersMessages; aPreviewLength:
Cardinal; aLastMessageId: Cardinal):
TVKMessageArray; overload;
function Get(aOut: Boolean; aOffset: Cardinal;
aCount: CountMessages; aTimeOffset: Cardinal;
aFilters: TFiltersMessages; aPreviewLength:
Cardinal): TVKMessageArray; overload;
function Get(aOut: Boolean; aOffset: Cardinal;
aCount: CountMessages; aTimeOffset: Cardinal;
aFilters: TFiltersMessages): TVKMessageArray; overload;
function Get(aOut: Boolean; aOffset: Cardinal;
aCount: CountMessages; aTimeOffset: Cardinal):
TVKMessageArray; overload;
function Get(aOut: Boolean; aOffset: Cardinal;
aCount: CountMessages): TVKMessageArray; overload;
function Get(aOut: Boolean; aOffset: Cardinal):
TVKMessageArray; overload;
function Get(aOut: Boolean): TVKMessageArray; overload;
end;
var
HTTP: TIdHTTP;
SSL: TIdSSLIOHandlerSocketOpenSSL;
Client: TRestClient;
Authenticator: TOAuth2Authenticator;
WebForm: Tfrm_OAuthWebForm;
AppID, AppKey: string;
FID: integer;
FMessageCount: integer;
function ParseStr(str, sub1, sub2: string): string;
procedure AfterRedirect(const AURL: string; var
DoCloseWebView: Boolean);
public
var
Account: TVKAccountMethods;
Wall: TVKWallMethods; { To be continued... }
Messages: TVKMessageMethods;
Dialogs: TArray<TVKMessage>;
property
ID: integer read FID;
property
MessageCount: integer read FMessageCount;
constructor Create(aAppID, aAppKey: string);
destructor Free;
procedure Auth(aScope: string);
end;
implementation
procedure TVKApi.TVKAccountMethods.SetOnline;
var
Request: TRESTRequest;
Response: TRESTResponse;
begin
with Owner do
begin
Response := TRESTResponse.Create(nil);
Request := TRESTRequest.Create(Client);
Request.Client := Client;
Request.Response := Response;
Request.ClearBody;
Request.Resource := 'account.setOnline';
Request.Method := TRESTRequestMethod.rmGET;
with Request.Params.AddItem do
begin
name := 'v';
Value := cAPIVersion;
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
Request.Execute;
end;
end;
procedure TVKApi.TVKAccountMethods.SetOffline;
var
Request: TRESTRequest;
begin
with Owner do
begin
Request := TRESTRequest.Create(Client);
Request.Client := Client;
Request.ClearBody;
Request.Resource := 'account.setOffline';
Request.Method := TRESTRequestMethod.rmGET;
with Request.Params.AddItem do
begin
name := 'v';
Value := cAPIVersion;
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
Request.Execute;
Request.Free;
end;
end;
function TVKApi.ParseStr(str, sub1, sub2: string): string;
var
st, fin: integer;
begin
st := Pos(sub1, str);
if st > 0 then
begin
str := Copy(str, st + length(sub1), length(str) - 1);
st := 1;
fin := Pos(sub2, str);
Result := Copy(str, st, fin - st);
str := Copy(str, fin + length(sub2), length(str) - 1);
end;
end;
constructor TVKApi.Create(aAppID, aAppKey: string);
begin
Authenticator := TOAuth2Authenticator.Create(nil);
Client := TRestClient.Create('https://api.vk.com/method');
Client.Authenticator := Authenticator;
SSL := TIdSSLIOHandlerSocketOpenSSL.Create;
HTTP := TIdHTTP.Create;
HTTP.IOHandler := SSL;
WebForm := Tfrm_OAuthWebForm.Create(nil);
WebForm.OnAfterRedirect := AfterRedirect;
AppID := aAppID;
AppKey := aAppKey;
Account.Owner := Self;
Messages.Owner := Self;
end;
destructor TVKApi.Free;
begin
HTTP.Free;
SSL.Free;
WebForm.Free;
Authenticator.Free;
Client.Free;
end;
procedure TVKApi.Auth;
begin
Authenticator.AccessToken := EmptyStr;
Authenticator.ClientID := AppID;
Authenticator.ClientSecret := AppKey;
Authenticator.ResponseType := TOAuth2ResponseType.rtTOKEN;
Authenticator.AuthorizationEndpoint := cEndPoint;
Authenticator.Scope := aScope;
WebForm.ShowWithURL(Authenticator.AuthorizationRequestURI);
end;
procedure TVKApi.AfterRedirect(const AURL: string; var
DoCloseWebView: Boolean);
var
i: integer;
str: string;
Params: TStringList;
begin
i := Pos('#access_token=', AURL);
if (i > 0) and (Authenticator.AccessToken = EmptyStr) then
begin
str := AURL;
Delete(str, 1, i);
Params := TStringList.Create;
try
Params.Delimiter := '&';
Params.DelimitedText := str;
Authenticator.AccessToken := Params.Values['access_token'];
Authenticator.AccessTokenExpiry := IncSecond(Now,
StrToInt(Params.Values['expires_in']));
FID := StrToInt(Params.Values['user_id']);
finally
Params.Free;
end;
WebForm.Close;
end;
end;
{ TVKApi.TVKWall }
procedure TVKApi.TVKWallMethods.Post(aOwnerID: string;
aFriendsOnly, aFromGroup: Boolean; aMessage: string);
var
Request: TRESTRequest;
Response: TRESTResponse;
begin
with Owner do
begin
Response := TRESTResponse.Create(nil);
Request := TRESTRequest.Create(Client);
Request.Client := Client;
Request.Response := Response;
Request.Resource := 'wall.post';
Request.Method := TRESTRequestMethod.rmPOST;
Request.Params.Clear;
with Request.Params.AddItem do
begin
name := 'v';
Value := cAPIVersion;
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'owner_id';
Value := aOwnerID;
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'message';
Value := aMessage;
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
Request.Execute;
end;
end;
{ TVKApi.TVKMessageMethods }
function TVKApi.TVKMessageMethods.Get(aOut: Boolean; aOffset:
Cardinal; aCount: CountMessages; aTimeOffset: Cardinal;
aFilters: TFiltersMessages; aPreviewLength, aLastMessageId:
Cardinal): TVKMessageArray;
var
Request: TRESTRequest;
Response: TRESTResponse;
JSONObject: TJSONObject;
JsonArray: TJSONArray;
JsonAttachments: TJSONArray;
Dialogs_Temp: TArray<TVKMessage>;
s: string;
i, j: Integer;
begin
with Owner do
begin
Response := TRESTResponse.Create(nil);
Request := TRESTRequest.Create(Client);
Request.Client := Client;
Request.Response := Response;
Request.Resource := 'messages.get';
Request.Method := TRESTRequestMethod.rmPOST;
Request.Params.Clear;
with Request.Params.AddItem do
begin
name := 'v';
Value := cAPIVersion;
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'out';
Value := IntToStr(Ord(aOut));
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'offset';
Value := IntToStr(aOffset);
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'count';
Value := IntToStr(aCount);
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'time_offset';
Value := IntToStr(aTimeOffset);
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'filters';
Value := IntToStr(Ord(aFilters));
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'preview_length';
Value := IntToStr(aPreviewLength);
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
with Request.Params.AddItem do
begin
name := 'last_message_id';
Value := IntToStr(aLastMessageId);
Kind := TRESTRequestParameterKind.pkGETorPOST;
Options := [poDoNotEncode];
end;
Request.Execute;
// parsing JSON
JSONObject := TJSONObject.ParseJSONValue(Response.Content)
as TJSONObject;
// s := JSONObject.Pairs[0].JsonValue.ToString;
JSONObject := TJSONObject.ParseJSONValue(JSONObject.Pairs
[0].JsonValue.ToString) as TJSONObject;
FMessageCount := StrToInt(JSONObject.Pairs[0].JsonValue.Value);
JsonArray := JSONObject.Pairs[1].JsonValue as TJSONArray;
SetLength(Dialogs_Temp, JsonArray.Size);
for i := 0 to JsonArray.Size - 1 do
begin
// Dialogs_Temp[i] := TVKMessage.Create;
Dialogs_Temp[i].ID := StrToInt((JsonArray.Items[i] as
TJSONObject).Values['id'].ToString);
Dialogs_Temp[i].UserId := StrToInt((JsonArray.Items[i]
as TJSONObject).Values['user_id'].ToString);
// Dialogs_Temp[i].FromId := StrToInt((JsonArray.Items[i]
// as TJSONObject).Values['from_id'].ToString);
Dialogs_Temp[i].Date := StrToInt((JsonArray.Items[i]
as TJSONObject).Values['date'].ToString);
Dialogs_Temp[i]._Out := StrToInt((JsonArray.Items[i]
as TJSONObject).Values['out'].ToString) = 1;
Dialogs_Temp[i].ReadState := StrToInt((JsonArray.Items
[i] as TJSONObject).Values['read_state'].ToString) = 1;
Dialogs_Temp[i].Title := (JsonArray.Items[i] as
TJSONObject).Values['title'].ToString;
Dialogs_Temp[i].Body := (JsonArray.Items[i] as
TJSONObject).Values['body'].ToString;
JsonAttachments := nil;
JsonAttachments := (JsonArray.Items[i] as TJSONObject).Values
['attachments'] as TJSONArray;
if Assigned(JSONAttachments) then
Dialogs_Temp[i].Attachments := Copy(ParseAttachments(JsonAttachments), 0);
end;
Insert(Dialogs_Temp, dialogs, 0);
end;
end;
function TVKApi.TVKMessageMethods.Get(aOut: Boolean; aOffset:
Cardinal; aCount: CountMessages; aTimeOffset: Cardinal;
aFilters: TFiltersMessages; aPreviewLength: Cardinal):
TVKMessageArray;
begin
Get(aOut, aOffset, aCount, aTimeOffset, aFilters, aPreviewLength, 0)
end;
function TVKApi.TVKMessageMethods.Get(aOut: Boolean; aOffset:
Cardinal; aCount: CountMessages; aTimeOffset: Cardinal;
aFilters: TFiltersMessages): TVKMessageArray;
begin
Get(aOut, aOffset, aCount, aTimeOffset, aFilters, 0, 0)
end;
function TVKApi.TVKMessageMethods.Get(aOut: Boolean; aOffset:
Cardinal; aCount: CountMessages; aTimeOffset: Cardinal):
TVKMessageArray;
begin
Get(aOut, aOffset, aCount, aTimeOffset, TFiltersMessages.ALL, 0, 0)
end;
function TVKApi.TVKMessageMethods.Get(aOut: Boolean; aOffset:
Cardinal; aCount: CountMessages): TVKMessageArray;
begin
Get(aOut, aOffset, aCount, 0, TFiltersMessages.ALL, 0, 0)
end;
function TVKApi.TVKMessageMethods.Get(aOut: Boolean; aOffset:
Cardinal): TVKMessageArray;
begin
Get(aOut, aOffset, 200, 0, TFiltersMessages.ALL, 0, 0)
end;
function TVKApi.TVKMessageMethods.Get(aOut: Boolean): TVKMessageArray;
begin
Get(aOut, 0, 200, 0, TFiltersMessages.ALL, 0, 0)
end;
end.
|
unit StyleView1;
{
Demonstrate how to apply XSLT stylesheets to an XML document.
Uses DOM interfaces from Microsoft XML parser.
Requires MSXML v3 package from Microsoft.
Copyright © Keith Wood (kbwood@iprimus.com.au)
Written May 18, 2000.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, ExtCtrls, OleCtrls, SHDocVw, ActiveX, MSXML2_TLB;
type
TfrmStylesheets = class(TForm)
pnlControls: TPanel;
Label1: TLabel;
edtXML: TEdit;
btnXML: TButton;
Label3: TLabel;
edtElement: TEdit;
Label2: TLabel;
edtXSLT: TEdit;
btnXSLT: TButton;
btnTransform: TButton;
btnSave: TButton;
pgcStylesheets: TPageControl;
tabXML: TTabSheet;
memXML: TRichEdit;
tabDOM: TTabSheet;
trvDOM: TTreeView;
tabXSLT: TTabSheet;
memXSLT: TRichEdit;
tabHTML: TTabSheet;
brsOutput: TWebBrowser;
tabRTF: TTabSheet;
memOutput: TRichEdit;
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnXMLClick(Sender: TObject);
procedure btnXSLTClick(Sender: TObject);
procedure edtXMLChange(Sender: TObject);
procedure trvDOMChange(Sender: TObject; Node: TTreeNode);
procedure btnTransformClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
XMLDoc: IXMLDOMDocument;
XSLTDoc: IXMLDOMDocument;
XMLNode: IXMLDOMNode;
HTMLOutput: Boolean;
procedure ClearTreeView;
public
end;
var
frmStylesheets: TfrmStylesheets;
implementation
{$R *.DFM}
resourcestring
NoDOM = 'Couldn''t create the DOM';
NoOutput = 'Nothing generated by the transformation';
Results = 'Results';
XMLFilter = 'XML files (*.xml)|*.xml|All files (*.*)|*.*';
XMLOpen = 'Open XML data file';
XSLTFilter = 'XSLT files (*.xsl)|*.xsl|All files (*.*)|*.*';
XSLTOpen = 'Open XSLT stylesheet file';
HTMLFilter = 'HTML files (*.html,*.htm)|*.html;*.htm|All files (*.*)|*.*';
HTMLSave = 'Save HTML file';
TextFilter = 'Text files (*.txt)|*.txt|Rich-text files (*.rtf)|*.rtf|' +
'Comma-separated files (*.csv)|*.csv|All files (*.*)|*.*';
TextSave = 'Save text file';
{ TXMLNode --------------------------------------------------------------------}
type
{ Object wrapper for a node reference }
TXMLNode = class(TObject)
public
Node: IXMLDOMNode;
constructor Create(Node: IXMLDOMNode);
end;
constructor TXMLNode.Create(Node: IXMLDOMNode);
begin
inherited Create;
Self.Node := Node;
end;
{ TfrmStylesheets -------------------------------------------------------------}
{ Format a DOM node for display }
function NodeDisplay(Node: IXMLDOMNode): string;
begin
Result := Node.Text;
Result := '<' + Node.NodeName + '>' + Copy(Result, 1, 30);
end;
{ Instantiate the DOMs }
procedure TfrmStylesheets.FormCreate(Sender: TObject);
begin
XMLDoc := CoDOMDocument.Create;
XSLTDoc := CoDOMDocument.Create;
dlgOpen.InitialDir := ExtractFilePath(Application.ExeName);
brsOutput.Navigate('about:blank');
end;
{ Release the DOMs }
procedure TfrmStylesheets.FormDestroy(Sender: TObject);
begin
ClearTreeView;
XMLNode := nil;
XMLDoc := nil;
XSLTDoc := nil;
end;
{ Free up the objects within the tree view }
procedure TfrmStylesheets.ClearTreeView;
var
Index: Integer;
begin
for Index := 0 to trvDOM.Items.Count - 1 do
TXMLNode(trvDOM.Items[Index].Data).Free;
trvDOM.Items.Clear;
end;
{ Find an XML source file }
procedure TfrmStylesheets.btnXMLClick(Sender: TObject);
{ Load the DOM elements into a tree view recursively }
procedure LoadElements(Node: IXMLDOMNode; Parent: TTreeNode);
var
Index: Integer;
Current: TTreeNode;
begin
if (Node.nodeType = NODE_ELEMENT) or (Node.nodeType = NODE_DOCUMENT) then
begin
Current := trvDOM.Items.AddChildObject(Parent,
NodeDisplay(Node), TXMLNode.Create(Node));
for Index := 0 to Node.childNodes.length - 1 do
LoadElements(Node.childNodes[Index], Current);
end;
end;
begin
with dlgOpen do
begin
Filename := edtXML.Text;
Filter := XMLFilter;
Title := XMLOpen;
if Execute then
begin
edtXML.Text := Filename;
memXML.Lines.Clear;
trvDOM.Items.BeginUpdate;
try
ClearTreeView;
{ Load the XML data }
memXML.Lines.LoadFromFile(edtXML.Text);
if not XMLDoc.load(edtXML.Text) then
with XMLDoc.parseError do
begin
MessageDlg(Reason + ' at ' + IntToStr(Line) + ',' +
IntToStr(LinePos), mtError, [mbOK], 0);
Exit;
end;
{ Load the DOM tree view }
LoadElements(XMLDoc, nil);
trvDOM.Items[0].Expand(True);
trvDOM.TopItem := trvDOM.Items[0];
trvDOMChange(trvDOM, trvDOM.Items[0]);
finally
trvDOM.Items.EndUpdate;
pgcStylesheets.ActivePage := tabDOM;
end;
end;
end;
end;
{ Find an XSLT stylesheet }
procedure TfrmStylesheets.btnXSLTClick(Sender: TObject);
begin
with dlgOpen do
begin
Filename := edtXSLT.Text;
Filter := XSLTFilter;
Title := XSLTOpen;
if Execute then
begin
edtXSLT.Text := Filename;
memXSLT.Lines.Clear;
{ Load the XSLT stylesheet }
memXSLT.Lines.LoadFromFile(edtXSLT.Text);
HTMLOutput := (Pos('<html>', memXSLT.Lines.Text) > 0) or
(Pos('<HTML>', memXSLT.Lines.Text) > 0);
if not XSLTDoc.load(edtXSLT.Text) then
with XSLTDoc.parseError do
begin
MessageDlg(Reason + ' at ' + IntToStr(Line) + ',' +
IntToStr(LinePos), mtError, [mbOK], 0);
Exit;
end;
pgcStylesheets.ActivePage := tabXSLT;
end;
end;
end;
{ Dis/enable merge button }
procedure TfrmStylesheets.edtXMLChange(Sender: TObject);
begin
btnTransform.Enabled := ((edtXML.Text <> '') and (edtXSLT.Text <> ''));
end;
{ Select the node to operate on }
procedure TfrmStylesheets.trvDOMChange(Sender: TObject; Node: TTreeNode);
begin
XMLNode := TXMLNode(Node.Data).Node;
edtElement.Text := NodeDisplay(XMLNode);
end;
{ Apply the stylesheet to the data and see the results }
procedure TfrmStylesheets.btnTransformClick(Sender: TObject);
var
Output: WideString;
TempStream: TStringStream;
StreamAdapter: TStreamAdapter;
begin
{ Combine the two and display the results }
Output := XMLNode.transformNode(XSLTDoc);
if Output = '' then
MessageDlg(NoOutput, mtError, [mbOK], 0);
with memOutput.DefAttributes do
begin
{ Reset default style }
Color := memOutput.Font.Color;
Name := memOutput.Font.Name;
Size := memOutput.Font.Size;
Style := memOutput.Font.Style;
end;
memOutput.PlainText := HTMLOutput;
tabHTML.TabVisible := HTMLOutput;
tabRTF.TabVisible := not HTMLOutput;
TempStream := TStringStream.Create(Output);
try
{ Load into memo }
TempStream.Position := 0;
memOutput.Lines.LoadFromStream(TempStream);
if HTMLOutput then
begin
{ Load into browser }
TempStream.Position := 0;
StreamAdapter := TStreamAdapter.Create(TempStream);
(brsOutput.Document as IPersistStreamInit).Load(StreamAdapter);
pgcStylesheets.ActivePage := tabHTML;
end
else
{ Show rich text memo }
pgcStylesheets.ActivePage := tabRTF;
finally
TempStream.Free;
end;
btnSave.Enabled := True;
end;
{ Save the resulting output }
procedure TfrmStylesheets.btnSaveClick(Sender: TObject);
begin
with dlgSave do
begin
if HTMLOutput then
begin
Filter := HTMLFilter;
Title := HTMLSave;
end
else
begin
Filter := TextFilter;
Title := TextSave;
end;
if Execute then
memOutput.Lines.SaveToFile(Filename);
end;
end;
end.
|
unit LogItem;
{$mode objfpc}{$H+}
interface
uses
SysUtils,
LogEntityFace;
type
{ TLogItem }
TLogItem = object
public
constructor Init;
private
fNumber: longint;
fTime: TDateTime;
fTag: string;
fObjectName: string;
fText: string;
public
procedure Clear;
property Number: integer read fNumber write fNumber;
property Time: TDateTime read fTime write fTime;
property Tag: string read fTag write fTag;
property ObjectName: string read fObjectName write fObjectName;
property Text: string read fText write fText;
destructor Done;
end;
PLogItem = ^TLogItem;
IStandardLogTagToString = interface
function ToString(const aTag: TStandardLogTag): string;
end;
{ TStandardLogTagToString }
TStandardLogTagToString = class(TInterfacedObject, IStandardLogTagToString)
public
function ToString(const aTag: TStandardLogTag): string; overload;
end;
const
LOG_TAG_STARTUP_CAPTION = 'STARTUP';
LOG_TAG_DEBUG_CAPTION = ' ';
LOG_TAG_WARNING_CAPTION = 'WARNING';
LOG_TAG_ERROR_CAPTION = 'ERROR';
LOG_TAG_END = 'END';
implementation
{ TStandardLogTagToString }
function TStandardLogTagToString.ToString(const aTag: TStandardLogTag): string;
begin
case aTag of
logTagStartup: result := LOG_TAG_STARTUP_CAPTION;
logTagDebug: result := LOG_TAG_DEBUG_CAPTION;
logTagWarning: result := LOG_TAG_WARNING_CAPTION;
logTagError: result := LOG_TAG_ERROR_CAPTION;
logTagEnd: result := LOG_TAG_END;
end;
end;
{ TLogItem }
constructor TLogItem.Init;
begin
Clear;
Time := Now;
end;
procedure TLogItem.Clear;
begin
Number := 0;
Time := 0;
Tag := '';
ObjectName := '';
Text := '';
end;
destructor TLogItem.Done;
begin
Clear;
end;
end.
|
unit FrustumCulling;
// © 2004 by Steve M.
interface
uses
SysUtils, OpenGL12, Geometry, VectorTypes;
type
TFrustum = class
private
Planes: array[0..5] of TVector4f;
procedure NormalizePlane(Plane: Integer);
public
function IsPointWithin(const p: TVector3f): Boolean;
function IsSphereWithin(const p: TVector3f; const r: Single): Boolean;
function IsBoxWithin(const p, dim: TVector3f): Boolean;
procedure Calculate;
end;
var
Frustum: TFrustum;
implementation
const
Right = 0;
Left = 1;
Bottom = 2;
Top = 3;
Back = 4;
Front = 5;
A = 0;
B = 1;
C = 2;
D = 3;
procedure TFrustum.NormalizePlane(Plane: Integer);
var
Magnitude: Single;
begin
Magnitude := Sqrt(Sqr(Planes[Plane][A])+Sqr(Planes[Plane][B])+Sqr(Planes[Plane][C]));
Planes[Plane][A] := Planes[Plane][A]/Magnitude;
Planes[Plane][B] := Planes[Plane][B]/Magnitude;
Planes[Plane][C] := Planes[Plane][C]/Magnitude;
Planes[Plane][D] := Planes[Plane][D]/Magnitude;
end;
procedure TFrustum.Calculate;
var
ProjM, ModM, Clip: array[0..15] of Single;
begin
glGetFloatv(GL_PROJECTION_MATRIX, @ProjM);
glGetFloatv(GL_MODELVIEW_MATRIX, @ModM);
// multiply projection and modelview matrix
Clip[ 0] := ModM[ 0]*ProjM[ 0] + ModM[ 1]*ProjM[ 4] + ModM[ 2]*ProjM[ 8] + ModM[ 3]*ProjM[12];
Clip[ 1] := ModM[ 0]*ProjM[ 1] + ModM[ 1]*ProjM[ 5] + ModM[ 2]*ProjM[ 9] + ModM[ 3]*ProjM[13];
Clip[ 2] := ModM[ 0]*ProjM[ 2] + ModM[ 1]*ProjM[ 6] + ModM[ 2]*ProjM[10] + ModM[ 3]*ProjM[14];
Clip[ 3] := ModM[ 0]*ProjM[ 3] + ModM[ 1]*ProjM[ 7] + ModM[ 2]*ProjM[11] + ModM[ 3]*ProjM[15];
Clip[ 4] := ModM[ 4]*ProjM[ 0] + ModM[ 5]*ProjM[ 4] + ModM[ 6]*ProjM[ 8] + ModM[ 7]*ProjM[12];
Clip[ 5] := ModM[ 4]*ProjM[ 1] + ModM[ 5]*ProjM[ 5] + ModM[ 6]*ProjM[ 9] + ModM[ 7]*ProjM[13];
Clip[ 6] := ModM[ 4]*ProjM[ 2] + ModM[ 5]*ProjM[ 6] + ModM[ 6]*ProjM[10] + ModM[ 7]*ProjM[14];
Clip[ 7] := ModM[ 4]*ProjM[ 3] + ModM[ 5]*ProjM[ 7] + ModM[ 6]*ProjM[11] + ModM[ 7]*ProjM[15];
Clip[ 8] := ModM[ 8]*ProjM[ 0] + ModM[ 9]*ProjM[ 4] + ModM[10]*ProjM[ 8] + ModM[11]*ProjM[12];
Clip[ 9] := ModM[ 8]*ProjM[ 1] + ModM[ 9]*ProjM[ 5] + ModM[10]*ProjM[ 9] + ModM[11]*ProjM[13];
Clip[10] := ModM[ 8]*ProjM[ 2] + ModM[ 9]*ProjM[ 6] + ModM[10]*ProjM[10] + ModM[11]*ProjM[14];
Clip[11] := ModM[ 8]*ProjM[ 3] + ModM[ 9]*ProjM[ 7] + ModM[10]*ProjM[11] + ModM[11]*ProjM[15];
Clip[12] := ModM[12]*ProjM[ 0] + ModM[13]*ProjM[ 4] + ModM[14]*ProjM[ 8] + ModM[15]*ProjM[12];
Clip[13] := ModM[12]*ProjM[ 1] + ModM[13]*ProjM[ 5] + ModM[14]*ProjM[ 9] + ModM[15]*ProjM[13];
Clip[14] := ModM[12]*ProjM[ 2] + ModM[13]*ProjM[ 6] + ModM[14]*ProjM[10] + ModM[15]*ProjM[14];
Clip[15] := ModM[12]*ProjM[ 3] + ModM[13]*ProjM[ 7] + ModM[14]*ProjM[11] + ModM[15]*ProjM[15];
//Clip:=MatrixMultiply(ModM, ProjM);
// extract frustum planes from clipping matrix
Planes[Right][A] := clip[ 3] - clip[ 0];
Planes[Right][B] := clip[ 7] - clip[ 4];
Planes[Right][C] := clip[11] - clip[ 8];
Planes[Right][D] := clip[15] - clip[12];
NormalizePlane(Right);
Planes[Left][A] := clip[ 3] + clip[ 0];
Planes[Left][B] := clip[ 7] + clip[ 4];
Planes[Left][C] := clip[11] + clip[ 8];
Planes[Left][D] := clip[15] + clip[12];
NormalizePlane(Left);
Planes[Bottom][A] := clip[ 3] + clip[ 1];
Planes[Bottom][B] := clip[ 7] + clip[ 5];
Planes[Bottom][C] := clip[11] + clip[ 9];
Planes[Bottom][D] := clip[15] + clip[13];
NormalizePlane(Bottom);
Planes[Top][A] := clip[ 3] - clip[ 1];
Planes[Top][B] := clip[ 7] - clip[ 5];
Planes[Top][C] := clip[11] - clip[ 9];
Planes[Top][D] := clip[15] - clip[13];
NormalizePlane(Top);
Planes[Back][A] := clip[ 3] - clip[ 2];
Planes[Back][B] := clip[ 7] - clip[ 6];
Planes[Back][C] := clip[11] - clip[10];
Planes[Back][D] := clip[15] - clip[14];
NormalizePlane(Back);
Planes[Front][A] := clip[ 3] + clip[ 2];
Planes[Front][B] := clip[ 7] + clip[ 6];
Planes[Front][C] := clip[11] + clip[10];
Planes[Front][D] := clip[15] + clip[14];
NormalizePlane(Front);
end;
function TFrustum.IsPointWithin(const p: TVector3f): Boolean;
var
i : Integer;
begin
Result:=true;
for i:=0 to 5 do
if (Planes[i][A]*p[A] + Planes[i][B]*p[B] + Planes[i][C]*p[C] + Planes[i][D]) <= 0 then begin
Result:=False;
exit;
end;
end;
function TFrustum.IsSphereWithin(const p: TVector3f; const r: Single): Boolean;
var
i : Integer;
begin
Result:=true;
for i:=0 to 5 do
if (Planes[i][A]*p[A] + Planes[i][B]*p[B] + Planes[i][C]*p[C] + Planes[i][D]) <= -r then begin
Result:=False;
exit;
end;
end;
function TFrustum.IsBoxWithin(const p, dim: TVector3f): Boolean;
// p: box position - NOTE: z is at bottom!
// dim: box dimensions
var
i : Integer;
begin
Result:=true;
for i:=0 to 5 do begin
if (Planes[i][A]*(p[A]-dim[A]/2) + Planes[i][B]*(p[B]-dim[B]/2) + Planes[i][C]*(p[C]) + Planes[i][D]) > 0 then continue;
if (Planes[i][A]*(p[A]-dim[A]/2) + Planes[i][B]*(p[B]+dim[B]/2) + Planes[i][C]*(p[C]) + Planes[i][D]) > 0 then continue;
if (Planes[i][A]*(p[A]-dim[A]/2) + Planes[i][B]*(p[B]+dim[B]/2) + Planes[i][C]*(p[C]+dim[C]) + Planes[i][D]) > 0 then continue;
if (Planes[i][A]*(p[A]-dim[A]/2) + Planes[i][B]*(p[B]-dim[B]/2) + Planes[i][C]*(p[C]+dim[C]) + Planes[i][D]) > 0 then continue;
if (Planes[i][A]*(p[A]+dim[A]/2) + Planes[i][B]*(p[B]-dim[B]/2) + Planes[i][C]*(p[C]) + Planes[i][D]) > 0 then continue;
if (Planes[i][A]*(p[A]+dim[A]/2) + Planes[i][B]*(p[B]+dim[B]/2) + Planes[i][C]*(p[C]) + Planes[i][D]) > 0 then continue;
if (Planes[i][A]*(p[A]+dim[A]/2) + Planes[i][B]*(p[B]+dim[B]/2) + Planes[i][C]*(p[C]+dim[C]) + Planes[i][D]) > 0 then continue;
if (Planes[i][A]*(p[A]+dim[A]/2) + Planes[i][B]*(p[B]-dim[B]/2) + Planes[i][C]*(p[C]+dim[C]) + Planes[i][D]) > 0 then continue;
Result := False;
end;
end;
initialization
Frustum:=TFrustum.Create;
finalization
Frustum.Free;
end.
|
unit RT_WolaniaGenerator;
interface
uses
Classes, SysUtils, jvuiblib;
type
TRT_WolaniaGenerator = class (TObject)
private
FData: TSQLResult;
protected
property Data: TSQLResult read FData;
public
constructor Create(AData: TSQLResult);
procedure GenerateHTML(Output: TStrings);
end;
implementation
{ TRT_WolaniaGenerator }
constructor TRT_WolaniaGenerator.Create(AData: TSQLResult);
begin
inherited Create;
FData := AData;
end;
procedure TRT_WolaniaGenerator.GenerateHTML(Output: TStrings);
begin
Output.Add('<html>');
Output.Add(' <head>');
Output.Add(' <META HTTP-EQUIV="Content-Type" content="text/html; charset=windows-1250">');
Output.Add(' </head>');
Output.Add(' <body bgcolor=white>');
Output.Add(' <table bgcolor=black cellspacing=1 cellpadding=3 border=0>');
Output.Add(' <tr><td nowrap><font color=white><b>OBSZAR</b></font></td><td nowrap><font color=white><b>NAZWA</b></font></td><td nowrap><font color=white><b>POCZATEK</b></font></td><td nowrap><font color=white>' + '<b>KONIEC</b></font></td><td nowrap><font color=white><b>POSTOJ1</b></font></td><td nowrap><font color=white><b>POSTOJ2</b></font></td><td nowrap><font color=white><b>POSTOJ3</b></font></td><td nowrap><font color=white><b>POSTOJ4</b></font></td><' + 'td nowrap><font color=white><b>POSTOJ5</b></font></td><td nowrap><font color=white><b>POSTOJ6</b></font></td></tr>');
while not Data.Eof do
begin
Output.Add(Format('<tr bgcolor=white><td nowrap>%s</td><td nowrap>%s</td><td nowrap>%s</td><td nowrap>%s</td><td nowrap>%s</td><td nowrap>%s</td><td nowrap>%s</td><td nowrap>%s</td><td nowrap>%s</td><td nowrap>%s</td></tr>', [
Data.ByNameAsString['OBSZAR'],
Data.ByNameAsString['NAZWA'],
Data.ByNameAsString['POCZATEK'],
Data.ByNameAsString['KONIEC'],
Data.ByNameAsString['POSTOJ1'],
Data.ByNameAsString['POSTOJ2'],
Data.ByNameAsString['POSTOJ3'],
Data.ByNameAsString['POSTOJ4'],
Data.ByNameAsString['POSTOJ5'],
Data.ByNameAsString['POSTOJ6']
]));
Data.Next;
end;
Output.Add(' </table>');
Output.Add(' </body>');
Output.Add('</html>');
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado à tabela [PESSOA]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit PessoaController;
interface
uses
Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos,
VO, PessoaVO, Generics.Collections;
type
TPessoaController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaLista(pFiltro: String): TObjectList<TPessoaVO>;
class function ConsultaObjeto(pFiltro: String): TPessoaVO;
class procedure Insere(pObjeto: TPessoaVO);
class function Altera(pObjeto: TPessoaVO): Boolean;
class function Exclui(pId: Integer): Boolean;
class function ExcluiContato(pId: Integer): Boolean;
class function ExcluiEndereco(pId: Integer): Boolean;
class function ExcluiTelefone(pId: Integer): Boolean;
class function GetDataSet: TClientDataSet; override;
class procedure SetDataSet(pDataSet: TClientDataSet); override;
class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
end;
implementation
uses T2TiORM,
PessoaFisicaVO, PessoaJuridicaVO, PessoaContatoVO, PessoaEnderecoVO,
PessoaTelefoneVO, PessoaAlteracaoVO;
class procedure TPessoaController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TPessoaVO>;
begin
try
Retorno := TT2TiORM.Consultar<TPessoaVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TPessoaVO>(Retorno);
finally
end;
end;
class function TPessoaController.ConsultaLista(pFiltro: String): TObjectList<TPessoaVO>;
begin
try
Result := TT2TiORM.Consultar<TPessoaVO>(pFiltro, '-1', True);
finally
end;
end;
class function TPessoaController.ConsultaObjeto(pFiltro: String): TPessoaVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TPessoaVO>(pFiltro, True);
finally
end;
end;
class procedure TPessoaController.Insere(pObjeto: TPessoaVO);
var
UltimoID: Integer;
Contato: TPessoaContatoVO;
Endereco: TPessoaEnderecoVO;
Telefone: TPessoaTelefoneVO;
ContatosEnumerator: TEnumerator<TPessoaContatoVO>;
EnderecosEnumerator: TEnumerator<TPessoaEnderecoVO>;
TelefonesEnumerator: TEnumerator<TPessoaTelefoneVO>;
TipoPessoa: String;
begin
try
TipoPessoa := pObjeto.Tipo;
UltimoID := TT2TiORM.Inserir(pObjeto);
// Tipo de Pessoa
if TipoPessoa = 'F' then
begin
pObjeto.PessoaFisicaVO.IdPessoa := UltimoID;
TT2TiORM.Inserir(pObjeto.PessoaFisicaVO);
end
else if TipoPessoa = 'J' then
begin
pObjeto.PessoaJuridicaVO.IdPessoa := UltimoID;
TT2TiORM.Inserir(pObjeto.PessoaJuridicaVO);
end;
// Contatos
ContatosEnumerator := pObjeto.ListaPessoaContatoVO.GetEnumerator;
try
with ContatosEnumerator do
begin
while MoveNext do
begin
Contato := Current;
Contato.IdPessoa := UltimoID;
TT2TiORM.Inserir(Contato);
end;
end;
finally
FreeAndNil(ContatosEnumerator);
end;
// Endereços
EnderecosEnumerator := pObjeto.ListaPessoaEnderecoVO.GetEnumerator;
try
with EnderecosEnumerator do
begin
while MoveNext do
begin
Endereco := Current;
Endereco.IdPessoa := UltimoID;
TT2TiORM.Inserir(Endereco);
end;
end;
finally
FreeAndNil(EnderecosEnumerator);
end;
// Telefones
TelefonesEnumerator := pObjeto.ListaPessoaTelefoneVO.GetEnumerator;
try
with TelefonesEnumerator do
begin
while MoveNext do
begin
Telefone := Current;
Telefone.IdPessoa := UltimoID;
TT2TiORM.Inserir(Telefone);
end;
end;
finally
FreeAndNil(TelefonesEnumerator);
end;
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TPessoaController.Altera(pObjeto: TPessoaVO): Boolean;
var
ContatosEnumerator: TEnumerator<TPessoaContatoVO>;
EnderecosEnumerator: TEnumerator<TPessoaEnderecoVO>;
TelefonesEnumerator: TEnumerator<TPessoaTelefoneVO>;
PessoaAlteracao: TPessoaAlteracaoVO;
PessoaOld: TPessoaVO;
TipoPessoa: String;
begin
try
PessoaOld := ConsultaObjeto('ID='+pObjeto.Id.ToString);
Result := TT2TiORM.Alterar(pObjeto);
TipoPessoa := pObjeto.Tipo;
// Tipo de Pessoa
try
if TipoPessoa = 'F' then
begin
if pObjeto.PessoaFisicaVO.Id > 0 then
Result := TT2TiORM.Alterar(pObjeto.PessoaFisicaVO)
else
Result := TT2TiORM.Inserir(pObjeto.PessoaFisicaVO) > 0;
end
else if TipoPessoa = 'J' then
begin
if pObjeto.PessoaJuridicaVO.Id > 0 then
Result := TT2TiORM.Alterar(pObjeto.PessoaJuridicaVO)
else
Result := TT2TiORM.Inserir(pObjeto.PessoaJuridicaVO) > 0;
end;
finally
end;
// Contatos
try
ContatosEnumerator := pObjeto.ListaPessoaContatoVO.GetEnumerator;
with ContatosEnumerator do
begin
while MoveNext do
begin
if Current.Id > 0 then
Result := TT2TiORM.Alterar(Current)
else
begin
Current.IdPessoa := pObjeto.Id;
Result := TT2TiORM.Inserir(Current) > 0;
end;
end;
end;
finally
FreeAndNil(ContatosEnumerator);
end;
// Endereços
try
EnderecosEnumerator := pObjeto.ListaPessoaEnderecoVO.GetEnumerator;
with EnderecosEnumerator do
begin
while MoveNext do
begin
if Current.Id > 0 then
Result := TT2TiORM.Alterar(Current)
else
begin
Current.IdPessoa := pObjeto.Id;
Result := TT2TiORM.Inserir(Current) > 0;
end;
end;
end;
finally
FreeAndNil(EnderecosEnumerator);
end;
// Telefones
try
TelefonesEnumerator := pObjeto.ListaPessoaTelefoneVO.GetEnumerator;
with TelefonesEnumerator do
begin
while MoveNext do
begin
if Current.Id > 0 then
Result := TT2TiORM.Alterar(Current)
else
begin
Current.IdPessoa := pObjeto.Id;
Result := TT2TiORM.Inserir(Current) > 0;
end;
end;
end;
finally
FreeAndNil(TelefonesEnumerator);
end;
// Alteração - Para Registro 0175 do Sped Fiscal.
PessoaAlteracao := TPessoaAlteracaoVO.Create;
PessoaAlteracao.IdPessoa := pObjeto.Id;
PessoaAlteracao.DataAlteracao := Date;
PessoaAlteracao.ObjetoAntigo := PessoaOld.ToJsonString;
PessoaAlteracao.ObjetoNovo := pObjeto.ToJsonString;
TT2TiORM.Inserir(PessoaAlteracao)
finally
FreeAndNil(PessoaAlteracao);
FreeAndNil(PessoaOld);
end;
end;
class function TPessoaController.Exclui(pId: Integer): Boolean;
begin
try
raise Exception.Create('Não é permitido excluir uma Pessoa.');
finally
end;
end;
class function TPessoaController.ExcluiContato(pId: Integer): Boolean;
var
ObjetoLocal: TPessoaContatoVO;
begin
try
ObjetoLocal := TPessoaContatoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPessoaController.ExcluiEndereco(pId: Integer): Boolean;
var
ObjetoLocal: TPessoaEnderecoVO;
begin
try
ObjetoLocal := TPessoaEnderecoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPessoaController.ExcluiTelefone(pId: Integer): Boolean;
var
ObjetoLocal: TPessoaTelefoneVO;
begin
try
ObjetoLocal := TPessoaTelefoneVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TPessoaController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TPessoaController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TPessoaController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TPessoaVO>(TObjectList<TPessoaVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TPessoaController);
finalization
Classes.UnRegisterClass(TPessoaController);
end.
|
program airtimeimporter;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp, DateUtils, IniFiles, fphttpclient,
// indy
IdBaseComponent, IdComponent, IdHTTP, httpsend, ssl_openssl,
// JSON
fpjson, jsonparser,
// mongo
Mongo, MongoDB, MongoCollection, BSON, BSONTypes;
type
{ TAirTimeImporter }
TAirTimeImporter = class(TCustomApplication)
private
procedure AddRecordToMongoDB(const collection: string; const aRecord: IBSONObject);
procedure GetDataFromAirtime(const SearchType: string; const CurrentDate: TDateTime);
procedure GetAllTimeDataFromAirtime(const SearchType: string; const CurrentDate: TDateTime);
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TAirTimeImporter }
procedure TAirTimeImporter.AddRecordToMongoDB(const collection: string; const aRecord: IBSONObject);
var
mongo: TMongo;
db: TMongoDB;
coll: TMongoCollection;
begin
mongo := TMongo.Create;
try
mongo.Connect;
db := mongo.getDB('bittube');
coll := db.GetCollection(collection);
coll.Insert(aRecord);
finally
mongo.Free;
end;
end;
procedure TAirTimeImporter.GetAllTimeDataFromAirtime(const SearchType: string; const CurrentDate: TDateTime);
var
HTTP: TidHTTP;
ToDate: TDateTime;
AResult: TMemoryStream;
WorkDate: TDateTime;
SingleRec: IBSONObject;
JSONData: TJSONData;
JSONParser: TJSONParser;
Parameters: TStringList;
begin
HTTP := TidHTTP.Create(nil);
try
WorkDate := CurrentDate;
ToDate := Now;
Parameters := TStringList.Create;
try
Parameters.StrictDelimiter := True;
Parameters.Delimiter := '&';
AResult := TMemoryStream.Create;
try
while DateOf(WorkDate) < DateOf(ToDate) do
begin
Parameters.Values['type'] := SearchType;
HTTP.Request.ContentType := 'application/x-www-form-urlencoded';
HTTP.Post('https://airtime.bit.tube/getStats', Parameters, AResult);
AResult.Position := 0;
JSONParser := TJSONParser.Create(AResult);
try
JSONData := JSONParser.Parse;
try
SingleRec := TBSONObject.Create;
SingleRec.Put('date', WorkDate);
SingleRec.Put('allestimated', JSONData.FindPath('stats[0].allestimated').AsFloat);
SingleRec.Put('allcalculated', JSONData.FindPath('stats[0].allcalculated').AsFloat);
SingleRec.Put('allrejected', JSONData.FindPath('stats[0].allrejected').AsFloat);
SingleRec.Put('numviewers', JSONData.FindPath('stats[0].numviewers').AsInt64);
SingleRec.Put('numusers', JSONData.FindPath('stats[0].numusers').AsInt64);
SingleRec.Put('numchannels', JSONData.FindPath('stats[0].numchannels').AsInt64);
AddRecordToMongoDB(SearchType, SingleRec);
WorkDate := IncDay(WorkDate);
Parameters.Clear;
AResult.Clear;
finally
JSONData.Free;
end;
finally
JSONParser.Free;
end;
end;
finally
AResult.Free;
end;
finally
Parameters.Free;
end;
finally
HTTP.Free;
end;
end;
procedure TAirTimeImporter.GetDataFromAirtime(const SearchType: string; const CurrentDate: TDateTime);
var
I: Integer;
LogMsg: string;
ToDate: TDateTime;
AResult: TMemoryStream;
LastByte: Byte;
NumTries: Integer;
Position: Integer;
WorkDate: TDateTime;
SingleRec: IBSONObject;
JSONData: TJSONData;
JSONArray: TJSONArray;
JSONParser: TJSONParser;
Parameters: TStringList;
JSONStream: TMemoryStream;
NoErrorResponse: Boolean;
AirTime: Double;
EarnedCoins: Double;
SumEarnedPerDay: Double;
begin
WorkDate := CurrentDate;
ToDate := Now;
Parameters := TStringList.Create;
try
Parameters.StrictDelimiter := True;
Parameters.Delimiter := '&';
AResult := TMemoryStream.Create;
JSONStream := TMemoryStream.Create;
try
while DateOf(WorkDate) < DateOf(ToDate) do
begin
try
NoErrorResponse := False;
NumTries := 0;
Parameters.Values['type'] := SearchType;
Parameters.Values['pageNumber'] := '0';
Parameters.Values['pageSize'] := '1000000';
Parameters.Values['dateStart'] := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz', WorkDate);
Parameters.Values['dateEnd'] := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz', IncDay(WorkDate));
while (NoErrorResponse = False) and (NumTries < 5) do
begin
if HttpPostURL('https://airtime.bit.tube/getStats', Parameters.DelimitedText, AResult) then
begin
NoErrorResponse := True;
AResult.Position := 0;
LastByte := 0;
while (AResult.Position < AResult.Size) and (LastByte <> Ord('{')) do
LastByte := AResult.ReadByte;
if AResult.Size > 0 then
AResult.Position := AResult.Position - 1;
if AResult.Position > 0 then
begin
AResult.SaveToFile(ExtractFilePath(ParamStr(0)) + 'AResult.json');
NoErrorResponse := False;
LogMsg := 'type: %s, date: %s, corrupted response, retrying %d!';
WriteLn(Format(LogMsg, [SearchType, Parameters.Values['dateStart'], NumTries + 1]));
end;
JSONStream.Clear;
JSONStream.CopyFrom(AResult, AResult.Size - AResult.Position);
JSONStream.Position := 0;
AResult.SaveToFile(ExtractFilePath(ParamStr(0)) + 'JSONStream.json');
end
else
begin
LogMsg := 'type: %s, date: %s, HTTP POST Failed!';
WriteLn(Format(LogMsg, [SearchType, Parameters.Values['dateStart']]));
end;
Inc(NumTries);
end;
JSONParser := TJSONParser.Create(JSONStream);
try
JSONData := JSONParser.Parse;
try
SumEarnedPerDay := 0;
// get the data count
JSONArray := TJSONArray(JSONData.FindPath('stats'));
if SameText(SearchType, 'creators') or SameText(SearchType, 'viewers') then
begin
for I := 0 to JSONArray.Count - 1 do
begin
AirTime := JSONArray.Items[I].FindPath('airtime').AsFloat / 24 / 60 / 60;
if SameText(SearchType, 'creators') then
EarnedCoins := JSONArray.Items[I].FindPath('sum_creator_reward').AsFloat / 100000000
else if SameText(SearchType, 'viewers') then
EarnedCoins := JSONArray.Items[I].FindPath('sum_viewer_reward').AsFloat / 100000000;
SumEarnedPerDay := SumEarnedPerDay + (EarnedCoins / AirTime);
end;
end;
SingleRec := TBSONObject.Create;
SingleRec.Put('date', WorkDate);
SingleRec.Put('count', JSONArray.Count);
if SameText(SearchType, 'creators') or SameText(SearchType, 'viewers') then
begin
case JSONArray.Count > 0 of
true: SingleRec.Put('earnedPerDay', SumEarnedPerDay / JSONArray.Count);
false: SingleRec.Put('earnedPerDay', 0);
end;
end;
WriteLn(Format('type: %s, date: %s', [SearchType, Parameters.Values['dateStart']]));
AddRecordToMongoDB(SearchType, SingleRec);
WorkDate := IncDay(WorkDate);
Parameters.Clear;
AResult.Clear;
finally
FreeAndNil(JSONData);
end;
finally
FreeAndNil(JSONParser);
end;
except
on E: Exception do
begin
WriteLn(Format('Error working on %s: %s', [SearchType, E.Message]));
end;
end;
end;
finally
JSONStream.Free;
AResult.Free;
end;
finally
Parameters.Free;
end;
end;
procedure TAirTimeImporter.DoRun;
var
ErrorMsg: String;
CurrentDate: TDateTime;
LastDateName: string;
LastDateFile: TIniFile;
begin
// quick check parameters
ErrorMsg:=CheckOptions('h', 'help');
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h', 'help') then begin
WriteHelp;
Terminate;
Exit;
end;
LastDateName := ExtractFilePath(ParamStr(0)) + 'settings.ini';
CurrentDate := EncodeDateTime(2018,8,1,0,0,0,0);
if FileExists(LastDateName) then
begin
LastDateFile := TIniFile.Create(LastDateName);
try
CurrentDate := LastDateFile.ReadDate('Settings', 'LastDate', EncodeDateTime(2018,08,01,0,0,0,0));
finally
LastDateFile.Free;
end;
end;
GetDataFromAirtime('viewers', CurrentDate);
GetDataFromAirtime('creators', CurrentDate);
GetDataFromAirtime('overviewPayments', CurrentDate);
//GetAllTimeDataFromAirtime('systemStats', CurrentDate);
LastDateFile := TIniFile.Create(LastDateName);
try
LastDateFile.WriteDate('Settings', 'LastDate', Now);
finally
LastDateFile.Free;
end;
// stop program loop
Terminate;
end;
constructor TAirTimeImporter.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TAirTimeImporter.Destroy;
begin
inherited Destroy;
end;
procedure TAirTimeImporter.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ', ExeName, ' -h');
end;
var
Application: TAirTimeImporter;
begin
Application:=TAirTimeImporter.Create(nil);
Application.Title:='AirTimeImporter';
Application.Run;
Application.Free;
end.
|
unit unVendedor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, unPadrao, Menus, DB, ActnList, Buttons, ExtCtrls, ComCtrls,
DBClient, Datasnap.Provider,
Data.SqlExpr, StdCtrls, DBCtrls, Mask, FMTBcd, System.Actions, uniGUIClasses,
uniEdit, uniDBEdit, uniButton, uniBitBtn, uniSpeedButton, uniPanel,
uniGUIBaseClasses, uniStatusBar, uniCheckBox, uniDBCheckBox;
type
TfrmVendedor = class(TfrmPadrao)
sqldPadrao: TSQLDataSet;
dspPadrao: TDataSetProvider;
cdsPadrao: TClientDataSet;
sqldPadraoIDVENDEDOR: TIntegerField;
sqldPadraoVENDEDOR: TStringField;
sqldPadraoATIVO: TStringField;
cdsPadraoIDVENDEDOR: TIntegerField;
cdsPadraoVENDEDOR: TStringField;
cdsPadraoATIVO: TStringField;
dbeIdVendedor: TUniDBEdit;
dbeVendedor: TUniDBEdit;
dbcbAtivo: TUniDBCheckBox;
procedure FormCreate(Sender: TObject);
procedure cdsPadraoAfterInsert(DataSet: TDataSet);
procedure cdsPadraoAfterScroll(DataSet: TDataSet);
private
public
end;
var
frmVendedor: TfrmVendedor;
implementation
uses ConstPadrao, Funcoes, VarGlobal;
{$R *.dfm}
procedure TfrmVendedor.FormCreate(Sender: TObject);
begin
inherited;
FieldNames := FN_VENDEDOR;
DisplayLabels := DL_VENDEDOR;
aCaption := 'Vendedor';
end;
procedure TfrmVendedor.cdsPadraoAfterInsert(DataSet: TDataSet);
begin
inherited;
//Incrementa('VENDEDOR', cdsPadraoIDVENDEDOR, GetConnection);
cdsPadraoATIVO.AsString := 'S';
SetFocusIfCan(dbeVendedor);
end;
procedure TfrmVendedor.cdsPadraoAfterScroll(DataSet: TDataSet);
begin
inherited;
dbcbAtivo.Enabled := (DataSet.State = dsEdit) or
((DataSet.State = dsBrowse) and (not DataSet.IsEmpty));
end;
initialization
RegisterClass(TfrmVendedor);
finalization
UnRegisterClass(TfrmVendedor);
end.
|
{ Public include file for the base part of the ray tracer.
*
* The high level routines and the basic interfaces between the components are
* defined here. This does not include details of ray geometry, what a color
* is, and the like. No ray-tracable objects or shaders are included in this
* layer.
*
* Any actual ray tracer implementation must provide objects, shaders, and
* define color. Public symbols for these are intended to be named TYPEn,
* where each set of mutually exclusive routines uses a different N.
*
* This ray tracer library comes with TYPE1 routines. These implement "normal"
* geometry and colors. See the RAY_TYPE1 include file for details.
}
type
ray_context_p_t = ^ray_context_t; {pointer to static context for rays}
ray_object_class_p_t = ^ray_object_class_t; {pointer to static obj class info}
ray_object_p_t = ^ray_object_t;
ray_object_t = record {one instance of an object}
class_p: ray_object_class_p_t; {pointer to static object class info}
data_p: univ_ptr; {pointer to object-specific data for this instance}
end;
ray_base_t = record {minimum required data for a ray}
context_p: ray_context_p_t; {pointer to static context info}
end;
ray_hit_info_t = record {data from object INTERSECT_CHECK routines}
object_p: ray_object_p_t; {points to object that the ray hit}
distance: real; {ray distance to hit point}
shader_parms_p: univ_ptr; {pointer to parameters for the shader}
enter: boolean; {TRUE if ray is entering object, not leaving}
end;
ray_shader_t = ^procedure ( {resolve color given hit info}
in var ray: univ ray_base_t; {the ray that hit the object}
in var hit_info: ray_hit_info_t; {saved info about the ray/object intersection}
out color: univ sys_int_machine_t); {returned color, defined by TYPEn convention}
ray_context_t = record {static context for each ray}
top_level_obj_p: ray_object_p_t; {pointer to top level "world" object}
object_parms_p: univ_ptr; {points to parameters for top level object}
backg_shader: ray_shader_t; {pointer to shader routine for background color}
backg_hit_info: ray_hit_info_t; {hit block for when ray hit nothing}
end;
ray_geom_flag_values = ( {all separately requestable isect geom parms}
ray_geom_point, {XYZ coordinates of intersection point}
ray_geom_unorm {unit normal vector to surface}
);
ray_geom_flags_t = {set of all requestable intersect geometry values}
set of ray_geom_flag_values;
ray_geom_info_t = record {returned intersection geometry information}
point: vect_3d_t; {coordinate of intersection point}
unorm: vect_3d_t; {unit normal vector of surface}
flags: ray_geom_flags_t; {flags for what really got returned}
end;
{
* Box descriptor and associated data structures.
*
* RAY_BOX_T defines a paralellpiped volume that is used in doing object/box
* intersection checks. It contains redundant information to allow for faster
* object/box intersection checks. The basic box is defined by a corner point
* and the vectors along the three edges intersecting at the corner point. The
* UNORM and WIDTH fields supply redundant information, but make it easy to
* determine whether a point is in the slice of space between the planes of two
* opposite faces. For a rectangular box, UNORM and EDGE point in the same
* direction, and WIDTH is the magnitued of EDGE. Intersection routines,
* however, should not assume that the box is rectangular. Even a axis aligned
* cube can turn into an arbitrary paralelpiped after tranformation.
}
ray_box_edge_t = record {used for describing one edge of a box}
edge: vect_3d_t; {vector from POINT (below) along box edge}
unorm: vect_3d_t; {unit normal to box face not along this edge}
width: real; {dist along UNORM between the opposite faces}
end;
ray_box_t = record {describes a paralellpiped volume}
point: vect_3d_t; {one of the corner points of the box}
edge: {describes the 3 independent sets of edges}
array[1..3] of ray_box_edge_t;
end;
{
* All the entry points that are pointed to from the OBJECT_CLASS block.
}
ray_object_create_proc_t = ^procedure ( {create a new object instance}
in out object: ray_object_t; {object instance to be filled in}
in gcrea_p: univ_ptr; {data for creating this object instance}
out stat: sys_err_t); {completion status code}
val_param;
ray_object_isect_check_proc_t = ^function ( {check for ray hit this object}
in out gray: univ ray_base_t; {ray to intersect with object}
in var object: ray_object_t; {object to intersect ray with}
in gparms_p: univ_ptr; {pointer to run time TYPEn-specific params}
out hit_info: ray_hit_info_t; {returned intersection info}
out shader: ray_shader_t) {pointer to shader to resolve color here}
:boolean; {TRUE if ray hit this object}
val_param;
ray_object_isect_geom_proc_t = ^procedure ( {get detailed intersect geometry}
in hit_info: ray_hit_info_t; {info about the intersection}
in flags: ray_geom_flags_t; {flags for the requested parameters}
out geom_info: ray_geom_info_t); {returned geometry info}
val_param;
ray_object_isect_box_proc_t = ^procedure ( {return object/box intersect status}
in box: ray_box_t; {descriptor for a paralellpiped volume}
in object: ray_object_t; {object to intersect with the box}
out here: boolean; {TRUE if ISECT_CHECK could be true in box}
out enclosed: boolean); {TRUE if solid obj and completely encloses box}
val_param;
ray_object_add_child_proc_t = ^procedure ( {add child to an aggregate object}
in aggr_obj: ray_object_t; {aggregate object to add child to}
var object: ray_object_t); {child object to add to aggregate object}
val_param;
{
* Static object data.
*
* Each object implementation exports only this structure. All routines and
* other information about the object can be found by examining data in this
* structure.
*
* For now the RAY_OBJECT_CLASS_MAKE_T entry point needs to be called to
* fill in a RAY_OBJECT_CLASS_T structure. Eventually those should be
* statically defined and declared external in the TYPEn include file.
}
ray_object_class_t = record {static info about an object class}
create: ray_object_create_proc_t; {create new instance of this object}
intersect_check: {intersect object with a ray}
ray_object_isect_check_proc_t;
hit_geom: {get more information about a ray hit}
ray_object_isect_geom_proc_t;
intersect_box: {intersect object with a box}
ray_object_isect_box_proc_t;
add_child: {add child to aggregate obj}
ray_object_add_child_proc_t; {NIL if not aggregate object}
end;
{
* Subroutines.
}
procedure ray_close; {close use of ray tracer, release resources}
val_param; extern;
procedure ray_init ( {init ray tracer, must be first call}
in out parent_mem: util_mem_context_t); {all new ray mem will be below this}
val_param; extern;
function ray_mem_alloc_perm ( {alloc un-releasable mem under ray tracer context}
in size: sys_int_adr_t) {amount of memory to allocate}
:univ_ptr; {pnt to new mem, bombs prog on no mem}
val_param; extern;
procedure ray_trace ( {resolve the color of ray}
in out ray: univ ray_base_t; {the ray to trace}
out color: univ sys_int_machine_t); {returned color, format defined by TYPEn}
val_param; extern;
|
unit uEventHandler;
interface
uses
ExtCtrls, Classes;
type
TOnCaptionChange = procedure(Sender: TObject; const Value: String) of object;
TCaptionListener = record
Listener: TObject;
Proc: TOnCaptionChange
end;
PCaptionListener = ^TCaptionListener;
TSpeaker = class
private
CaptionListeners: Array of PCaptionListener;
function FindCaptionListener(Listener: TObject): PCaptionListener;
function AddCaptionListener(Listener: TObject; Proc: TOnCaptionChange): PCaptionListener;
procedure RemoveCaptionListener(Listener: TObject);
public
Obj: TObject;
procedure RegisterCaptionListener(Listener: TObject; Proc: TOnCaptionChange);
procedure UnregisterCaptionListener(Listener: TObject);
procedure CaptionChange(Caption: String);
destructor Destroy; override;
end;
TEventHandler = class
private
SpeakerList: TList;
function FindSpeaker(Speaker: TObject): TSpeaker;
function AddSpeaker(Speaker: TObject): TSpeaker;
public
procedure RemoveSpeaker(Speaker: TObject);
procedure RegisterCaptionListener(Speaker: TObject; Listener: TObject; Proc: TOnCaptionChange);
procedure UnregisterCaptionListener(Speaker: TObject; Listener: TObject);
procedure CaptionChange(Speaker: TObject; Caption: String);
constructor Create;
destructor Destroy; override;
end;
implementation
{ TSpeakerHandler }
constructor TEventHandler.Create;
begin
SpeakerList := TList.Create;
end;
destructor TEventHandler.Destroy;
begin
while SpeakerList.Count > 0 do
begin
TSpeaker(SpeakerList[0]).Free;
SpeakerList.Delete(0);
end;
SpeakerList.Free;
inherited;
end;
function TEventHandler.AddSpeaker(Speaker: TObject): TSpeaker;
var
sp: TSpeaker;
begin
sp := TSpeaker.Create;
sp.Obj := Speaker;
SpeakerList.Add(Pointer(sp));
Result := sp;
end;
procedure TEventHandler.RemoveSpeaker(Speaker: TObject);
var
i: Integer;
begin
for i := 0 to SpeakerList.Count - 1 do
if TSpeaker(SpeakerList[i]).Obj = Speaker then
begin
TSpeaker(SpeakerList[i]).Free;
SpeakerList.Delete(i);
Break;
end;
end;
procedure TEventHandler.RegisterCaptionListener(Speaker: TObject;
Listener: TObject; Proc: TOnCaptionChange);
var
sp: TSpeaker;
begin
sp := FindSpeaker(Speaker);
if not Assigned(sp) then
sp := AddSpeaker(Speaker);
sp.RegisterCaptionListener(Listener, Proc);
end;
procedure TEventHandler.UnregisterCaptionListener(Speaker: TObject;
Listener: TObject);
var
sp: TSpeaker;
begin
sp := FindSpeaker(Speaker);
if Assigned(sp) then
sp.UnregisterCaptionListener(Listener);
end;
function TEventHandler.FindSpeaker(Speaker: TObject): TSpeaker;
var
i: Integer;
begin
Result := nil;
for i := 0 to SpeakerList.Count - 1 do
if TSpeaker(SpeakerList[i]).Obj = Speaker then
begin
Result := TSpeaker(SpeakerList[i]);
Break;
end;
end;
procedure TEventHandler.CaptionChange(Speaker: TObject; Caption: String);
var
sp: TSpeaker;
begin
sp := FindSpeaker(Speaker);
if Assigned(sp) then
sp.CaptionChange(Caption);
end;
{ TSpeaker }
function TSpeaker.AddCaptionListener(Listener: TObject;
Proc: TOnCaptionChange): PCaptionListener;
var
p: PCaptionListener;
begin
New(p);
p.Listener := Listener;
p.Proc := Proc;
SetLength(CaptionListeners, Length(CaptionListeners) + 1);
CaptionListeners[Length(CaptionListeners) - 1] := p;
Result := p;
end;
procedure TSpeaker.CaptionChange(Caption: String);
var
i: Integer;
begin
for i := Low(CaptionListeners) to High(CaptionListeners) do
CaptionListeners[i].Proc(CaptionListeners[i].Listener, Caption);
end;
destructor TSpeaker.Destroy;
var
i: Integer;
begin
Obj := nil;
for i := Low(CaptionListeners) to High(CaptionListeners) do
Dispose(CaptionListeners[i]);
inherited;
end;
function TSpeaker.FindCaptionListener(Listener: TObject): PCaptionListener;
var
i: Integer;
begin
Result := nil;
for i := Low(CaptionListeners) to High(CaptionListeners) do
begin
if CaptionListeners[i].Listener = Listener then
begin
Result := PCaptionListener(CaptionListeners[i]);
Break;
end;
end;
end;
procedure TSpeaker.RegisterCaptionListener(Listener: TObject; Proc: TOnCaptionChange);
begin
if FindCaptionListener(Listener) = nil then
AddCaptionListener(Listener, Proc);
end;
procedure TSpeaker.RemoveCaptionListener(Listener: TObject);
var
i: Integer;
Idx: Integer;
begin
Idx := -1;
for i := Low(CaptionListeners) to High(CaptionListeners) do
if CaptionListeners[i].Listener = Listener then
begin
Dispose(CaptionListeners[i]);
Idx := i;
Break;
end;
if Idx <> -1 then
begin
for i := Idx to High(CaptionListeners) - 1 do
CaptionListeners[i] := CaptionListeners[i + 1];
SetLength(CaptionListeners, Length(CaptionListeners) - 1);
end;
end;
procedure TSpeaker.UnregisterCaptionListener(Listener: TObject);
begin
if FindCaptionListener(Listener) <> nil then
RemoveCaptionListener(Listener);
end;
end.
|
//https://github.com/ideasawakened/iaLib
//For upcoming blog article at: https://www.ideasawakened.com/blog
unit iaDemo.SyncBucket.ConsoleMode;
interface
uses
System.Classes,
Data.Cloud.CloudAPI,
iaRTL.SyncBucket.Items,
iaRTL.SyncBucket.ToFolder;
type
TConsoleModeSyncBucketToFolder = class
private
fSyncBucketToFolder:TSyncBucketToFolder;
procedure ConsoleLog(const LogText:string);
procedure DoOnPrepareSyncAction(const SyncItem:TSyncItem; const ActionToTake:TSyncAction; var SkipAction:Boolean);
procedure DoOnAfterSyncAction(const SyncItem:TSyncItem; const ActionTaken:TSyncAction; const LocalFileName:string);
public
constructor Create;
destructor Destroy; override;
procedure PerformSync;
end;
implementation
uses
System.SysUtils,
System.RTTI,
iaRTL.Syncbucket.Config;
constructor TConsoleModeSyncBucketToFolder.Create;
var
BucketConfig:TSyncBucketConfig;
begin
BucketConfig.LoadFromINI;
fSyncBucketToFolder := TSyncBucketToFolder.Create(BucketConfig, ConsoleLog);
fSyncBucketToFolder.OnPrepareSyncAction := DoOnPrepareSyncAction;
fSyncBucketToFolder.OnAfterSyncAction := DoOnAfterSyncAction;
end;
destructor TConsoleModeSyncBucketToFolder.Destroy;
begin
fSyncBucketToFolder.Free;
inherited;
end;
procedure TConsoleModeSyncBucketToFolder.PerformSync;
begin
fSyncBucketToFolder.SyncToFolder;
end;
procedure TConsoleModeSyncBucketToFolder.ConsoleLog(const LogText: string);
begin
//toconsider: Multi-thread protection, if desired
WriteLn(LogText);
end;
procedure TConsoleModeSyncBucketToFolder.DoOnPrepareSyncAction(const SyncItem:TSyncItem; const ActionToTake:TSyncAction; var SkipAction:Boolean);
begin
ConsoleLog(Format('PrepareSync action triggered for bucket item "%s". Will take action: "%s"', [SyncItem.ObjectKey, TRttiEnumerationType.GetName(ActionToTake)]));
end;
procedure TConsoleModeSyncBucketToFolder.DoOnAfterSyncAction(const SyncItem:TSyncItem; const ActionTaken:TSyncAction; const LocalFileName:string);
begin
ConsoleLog(Format('AfterSync action triggered for bucket item "%s". Action taken: "%s" on local filename "%s"', [SyncItem.ObjectKey, TRttiEnumerationType.GetName(ActionTaken), LocalFileName]));
end;
end.
|
unit DrawingGridCode;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Grids;
const
UM_INVALIDATEROW = WM_USER+321;
type
TForm1 = class(TForm)
StatusBar: TStatusBar;
Button1: TButton;
OpenDialog1: TOpenDialog;
Label1: TLabel;
StringGrid1: TStringGrid;
Edit1: TEdit;
procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure StringGrid1Enter(Sender: TObject);
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure StringGrid1Exit(Sender: TObject);
private
{ Private declarations }
FGridActive: Boolean;
Procedure UMInvalidateRow( var msg: TMessage ); message UM_INVALIDATEROW;
public
{ Public declarations }
end;
var
Form1: TForm1;
dummy: Integer;
implementation
{$R *.DFM}
type
TGridCracker = class( TStringgrid ); // gives access to protected methods
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
grid: TStringgrid;
begin
// Task: color the current row
grid:= Sender as TStringgrid;
if FGridActive and (aRow = grid.Row) and (aCol >= grid.FixedCols) then
begin
grid.Canvas.brush.Color := clBlue;
grid.canvas.font.color := clWhite;
grid.canvas.FillRect( Rect );
InflateRect( rect, -2, -2 );
grid.Canvas.TextRect( Rect, rect.left, rect.top, grid.cells[aCol, aRow]);
end
else if (gdSelected In State) and not grid.Focused then Begin
grid.Canvas.brush.Color := grid.color;
grid.canvas.font.color := grid.font.color;
grid.canvas.FillRect( Rect );
InflateRect( rect, -2, -2 );
grid.Canvas.TextRect( Rect, rect.left, rect.top, grid.cells[aCol, aRow]);
End;
end;
procedure TForm1.StringGrid1Enter(Sender: TObject);
begin
if sender is TStringgrid then
With TGridCracker( sender ) do
POstMessage( self.handle, UM_INVALIDATEROW, Row, Integer(sender));
FGridActive := true;
{ Cannot rely on grid.focused here, it is not yet true when the
message send above is processed for some reason. }
end;
procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
var
grid: TStringgrid;
begin
grid:= Sender as TStringgrid;
If grid.Row <> aRow Then
PostMessage( handle, UM_INVALIDATEROW, grid.Row, Integer(grid));
PostMessage( handle, UM_INVALIDATEROW, aRow, Integer(grid));
end;
procedure TForm1.UMInvalidateRow(var msg: TMessage);
begin
TGridCracker( msg.lparam ).InvalidateRow( msg.wparam );
end;
procedure TForm1.StringGrid1Exit(Sender: TObject);
begin
if sender is TStringgrid then
With TGridCracker( sender ) do
POstMessage( self.handle, UM_INVALIDATEROW, Row, Integer(sender));
FGridActive := false;
end;
********
type
TGridCracker = Class( TStringgrid );
// required to access protected method Invalidaterow
procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
With TGridCracker( Sender As TStringgrid ) Do Begin
InvalidateRow( Row );
InvalidateRow( aRow );
End;
end;
procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
grid: TStringgrid;
begin
If gdFixed In State Then Exit;
grid := Sender As TStringgrid;
If grid.Row = aRow Then Begin
With Grid.Canvas.Brush Do Begin
Color := $C0FFFF; // pale yellow
Style := bsSolid;
End;
grid.Canvas.FillRect( Rect );
grid.Canvas.Font.Color := clBlack;
grid.Canvas.TextRect( Rect, Rect.Left+2, Rect.Top+2, grid.Cells[acol,
arow]);
Grid.Canvas.Brush := grid.Brush;
End;
end;
end.
|
unit VisibleDSA.AlgoVisHelper;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
FMX.Types,
FMX.Forms,
FMX.Graphics;
const
CL_RED = $FFF44336;
CL_PINK = $FFE91E63;
CL_PURPLE = $FF9C27B0;
CL_DEEPPURPLE = $FF673AB7;
CL_INDIGO = $FF3F51B5;
CL_BLUE = $FF2196F3;
CL_LIGHTBLUE = $FF03A9F4;
CL_CYAN = $FF00BCD4;
CL_TEAL = $FF009688;
CL_GREEN = $FF4CAF50;
CL_LIGHTGREEN = $FF8BC34A;
CL_LIME = $FFCDDC39;
CL_YELLOW = $FFFFEB3B;
CL_AMBER = $FFFFC107;
CL_ORANGE = $FFFF9800;
CL_DEEPORANGE = $FFFF5722;
CL_BROWN = $FF795548;
CL_GREY = $FF9E9E9E;
CL_BLUEGREY = $FF607D8B;
CL_BLACK = $FF000000;
CL_WHITE = $FFFFFFFF;
type
TColor = type Cardinal;
TAlgoVisHelper = class
private
class var _fillColor: TColor;
class var _fillStyle: TBrushKind;
class var _strokeColor: TColor;
class var _strokeWidth: integer;
class var _strokeStyle: TBrushKind;
public
class procedure SetStroke(strokeWidth: integer; color: TColor = CL_BLACK; style: TBrushKind = TBrushKind.Solid);
class procedure SetFill(color: TColor = CL_BLACK; style: TBrushKind = TBrushKind.Solid);
// 正圆形
class procedure DrawCircle(canvas: TCanvas; x, y, r: integer);
class procedure FillCircle(canvas: TCanvas; x, y, r: integer);
// 矩形
class procedure FillRectangle(canvas: TCanvas; x, y, w, h: integer);
// 直角坐标
class procedure DrawCoordinates(canvas: TCanvas);
// Pause
class procedure Pause(interval: integer);
end;
implementation
{ TAlgoVisHelper }
class procedure TAlgoVisHelper.DrawCircle(canvas: TCanvas; x, y, r: integer);
var
a: TRectF;
begin
a := TRectF.Create(x - r, y - r, x + r, y + r);
canvas.Stroke.Color := _strokeColor;
canvas.Stroke.Thickness := 1;
canvas.Stroke.Kind := TBrushKind.Solid;
if canvas.BeginScene then
begin
try
canvas.DrawEllipse(a, 1);
finally
canvas.EndScene;
end;
end;
end;
class procedure TAlgoVisHelper.DrawCoordinates(canvas: TCanvas);
var
x1, y1, x2, y2: Integer;
begin
canvas.Stroke.Color := CL_INDIGO;
canvas.Stroke.Thickness := 1;
canvas.Stroke.Kind := TBrushKind.Solid;
canvas.Stroke.Dash := TStrokeDash.Dot;
if canvas.BeginScene then
begin
try
// 横轴
x1 := 0;
y1 := canvas.Height div 2;
x2 := canvas.Width;
y2 := y1;
canvas.DrawLine(TPointF.Create(x1, y1), TPointF.Create(x2, y2), 1);
// 竖轴
x1 := canvas.Width div 2;
y1 := 0;
x2 := x1;
y2 := canvas.Height;
canvas.DrawLine(TPointF.Create(x1, y1), TPointF.Create(x2, y2), 1);
finally
canvas.EndScene;
end;
end;
end;
class procedure TAlgoVisHelper.FillRectangle(canvas: TCanvas; x, y, w, h: integer);
var
a: TRectF;
begin
a := TRectF.Create(x, y, x + w, y + h);
canvas.Fill.Color := _fillColor;
canvas.Fill.Kind := _fillStyle;
if canvas.BeginScene then
begin
try
canvas.FillRect(a, 0, 0, AllCorners, 1)
finally
canvas.EndScene;
end;
end;
end;
class procedure TAlgoVisHelper.Pause(interval: integer);
begin
Sleep(interval);
Application.ProcessMessages;
end;
class procedure TAlgoVisHelper.FillCircle(canvas: TCanvas; x, y, r: integer);
var
a: TRectF;
begin
a := TRectF.Create(x - r, y - r, x + r, y + r);
canvas.Fill.Color := _fillColor;
canvas.Fill.Kind := _fillStyle;
if canvas.BeginScene then
begin
try
canvas.FillEllipse(a, 1);
finally
canvas.EndScene;
end;
end;
end;
class procedure TAlgoVisHelper.SetFill(color: TColor; style: TBrushKind);
begin
_fillColor := color;
_fillStyle := style;
end;
class procedure TAlgoVisHelper.SetStroke(strokeWidth: integer; color: TColor; style: TBrushKind);
begin
_strokeColor := color;
_strokeWidth := strokeWidth;
_strokeStyle := style;
end;
end.
|
unit interfaces.Cliente;
interface
Type
IObservadorCliente = interface // IObserver
['{2488845B-6F57-483E-916A-280344B7D196}']
procedure AtualizarCliente;
end;
IClienteObservado = interface // ISubject
['{DE682D40-0EE4-4E94-A9D2-05BC024B542D}']
procedure AdicionarObservador(Observer : IObservadorCliente);
procedure RemoverObservador(Observer : IObservadorCliente);
procedure RemoverTodosObservadores;
procedure Notificar;
end;
implementation
end.
|
unit tlbutil;
////////////////////////////////////////////////////////////////////////////////
//
// TTypeLibrary
// |
// |_ TCoClass (TTypeClass)
// | |_ TCoMember (Interfaces)
// |_ TInterface (TTypeClass)
// | |_ TMember (Properties and Functions)
// | |_ TComDataType (Params and result Value)
// |_ TEnum (TTypeClass)
// | |_ TComDataType (Values)
// |_ TRecord (TTypeClass)
// | |_ TComDataType (Fields)
// |_ TAlias (TTypeClass)
// | |_ TComDataType (AliasType)
// |_ TModules (TTypeClass)
// |_ TMember (Functions)
// |_ TComDataType (Params and result Value)
//
////////////////////////////////////////////////////////////////////////////////
interface
uses
Windows, SysUtils, Classes, Contnrs, ActiveX, ComObj;
// Data type names
const
DATA_TYPE_NAMES: Array [0..31] of String =
('', '', 'SmallInt', 'Integer', 'Single', 'Double', 'Currency', 'Date',
'String', 'IDispatch','Integer', 'Boolean', 'Variant', 'IUnknown', 'Decimal', '',
'Char', 'Byte', 'Word', 'LongWord', 'Int64', 'Int64', 'Integer', 'LongWord',
'Void', 'HResult', 'Pointer', 'Array', 'Array', 'Type', 'PChar', 'PWideChar');
// Array bound type
type
PArrayBound = ^TArrayBound;
TArrayBound = packed record
lBound: Integer;
uBound: Integer;
end;
// Com data type class
type
TComDataType = class(TObject)
private
// Private declarations
FVT: Integer;
FIsOptional: Boolean;
FConstValue: Integer;
FName: String;
FIsUserDefined:Boolean;
FIsArray: Boolean;
FBounds: TList;
FGuid: TGUID;
protected
// Protected declarations
function GetDataTypeName: String;
function GetBoundsCount: Integer;
function GetBounds(Index: Integer): TArrayBound;
procedure SetName(Value: String);
procedure SetVT(Value: Integer);
procedure SetIsUserDefined(Value: Boolean);
procedure SetIsArray(Value: Boolean);
procedure AddBound(LowBound, HiBound: Integer);
public
// Public declarations
constructor Create;
destructor Destroy; override;
property Name: String read FName;
property DataType: Integer read FVT;
property DataTypeName: String read GetDataTypeName;
property IsArray: Boolean read FIsArray;
property IsUserDefined: Boolean read FIsUserDefined;
property IsOptional: Boolean read FIsOptional;
property BoundsCount: Integer read GetBoundsCount;
property Bounds[Index: Integer]: TArrayBound read GetBounds;
property UserDefinedRef: TGUID read FGuid;
property ConstValue: Integer read FConstValue;
end;
// Base class for all type information based objects
type
TTypeClass = class(TObject)
private
// Private declarations
FLoaded: Boolean;
FGuid: TGUID;
FName: String;
FTypeInfo: ITypeInfo;
protected
// Protected declarations
procedure LoadBaseInfo;
public
// Public declarations
constructor Create(TypeInfo: ITypeInfo);
destructor Destroy; override;
procedure Load; virtual;
property Loaded: Boolean read FLoaded;
property Guid: TGUID read FGuid;
property Name: String read FName;
end;
// Alias type info object
type
TAlias = class(TTypeClass)
private
// Private declarations
FAliasType: TComDataType;
protected
// Protected declarations
public
// Public declarations
constructor Create(TypeInfo: ITypeInfo);
destructor Destroy; override;
procedure Load; override;
property AliasType: TComDataType read FAliasType;
end;
// Record type info object
type
TRecord = class(TTypeClass)
private
// Private declarations
FFields: TObjectList;
protected
// Protected declarations
function GetFields(Index: Integer): TComDataType;
function GetFieldCount: Integer;
public
// Public declarations
constructor Create(TypeInfo: ITypeInfo);
destructor Destroy; override;
procedure Load; override;
property Fields[Index: Integer]: TComDataType read GetFields;
property FieldCount: Integer read GetFieldCount;
end;
// Enumeration type info object
type
TEnum = class(TTypeClass)
private
// Private declarations
FValues: TObjectList;
protected
// Protected declarations
function GetValues(Index: Integer): TComDataType;
function GetValueCount: Integer;
public
// Public declarations
constructor Create(TypeInfo: ITypeInfo);
destructor Destroy; override;
procedure Load; override;
property Values[Index: Integer]: TComDataType read GetValues;
property ValueCount: Integer read GetValueCount;
end;
// Member type class for interface functions and properties
type
TMember = class(TObject)
private
// Private declarations
FID: Integer;
FIsDispatch: Boolean;
FIsHidden: Boolean;
FName: String;
FParams: TObjectList;
FValue: TComDataType;
FCanRead: Boolean;
FCanWrite: Boolean;
protected
// Protected declarations
procedure Load(TypeInfo: ITypeInfo; VarDesc: PVarDesc; Index: Integer); overload;
procedure Load(TypeInfo: ITypeInfo; FuncDesc: PFuncDesc; Index: Integer); overload;
function GetParam(Index: Integer): TComDataType;
function GetParamCount: Integer;
public
// Public declarations
constructor Create(TypeInfo: ITypeInfo; FuncDesc: PFuncDesc; Index: Integer); overload;
constructor Create(TypeInfo: ITypeInfo; VarDesc: PVarDesc; Index: Integer); overload;
destructor Destroy; override;
property ID: Integer read FID;
property IsDispatch: Boolean read FIsDispatch;
property IsHidden: Boolean read FIsHidden;
property Name: String read FName;
property Params[Index: Integer]: TComDataType read GetParam;
property ParamCount: Integer read GetParamCount;
property CanRead: Boolean read FCanRead;
property CanWrite: Boolean read FCanWrite;
property Value: TComDataType read FValue;
end;
// Interface type info object
type
TInterface = class(TTypeClass)
private
// Private declarations
FProperties: TObjectList;
FFunctions: TObjectList;
protected
// Protected declarations
procedure LoadVariables;
procedure LoadMembers;
function GetProperty(Index: Integer): TMember;
function GetFunction(Index: Integer): TMember;
function GetPropertyCount: Integer;
function GetFunctionCount: Integer;
public
// Public declarations
constructor Create(TypeInfo: ITypeInfo);
destructor Destroy; override;
procedure Load; override;
property Properties[Index: Integer]: TMember read GetProperty;
property PropertyCount: Integer read GetPropertyCount;
property Functions[Index: Integer]: TMember read GetFunction;
property FunctionCount: Integer read GetFunctionCount;
end;
// CoClass member type class
type
TCoMember = class(TObject)
private
// Private declarations
FGuid: TGUID;
FName: String;
FIsDispatch: Boolean;
FIsDefault: Boolean;
FIsSource: Boolean;
FCanCreate: Boolean;
protected
// Protected declarations
public
// Public declarations
constructor Create;
destructor Destroy; override;
property Guid: TGUID read FGuid;
property IsDispatch: Boolean read FIsDispatch;
property IsDefault: Boolean read FIsDefault;
property IsSource: Boolean read FIsSource;
property CanCreate: Boolean read FCanCreate;
property Name: String read FName;
end;
// CoClass type info object
type
TCoClass = class(TTypeClass)
private
// Private declarations
FInterfaces: TObjectList;
protected
// Protected declarations
function GetInterface(Index: Integer): TCoMember;
function GetInterfaceCount: Integer;
public
// Public declarations
constructor Create(TypeInfo: ITypeInfo);
destructor Destroy; override;
procedure Load; override;
property Interfaces[Index: Integer]: TCoMember read GetInterface;
property InterfaceCount: Integer read GetInterfaceCount;
end;
// TModule type info object
type
TModule = class(TTypeClass)
private
// Private declarations
FFunctions: TObjectList;
protected
// Protected declarations
function GetFunction(Index: Integer): TMember;
function GetFunctionCount: Integer;
public
// Public declarations
constructor Create(TypeInfo: ITypeInfo);
destructor Destroy; override;
procedure Load; override;
end;
// Type library wrapper object
type
TTypeLibrary = class(TObject)
private
// Private declarations
FTypeLib: ITypeLib;
FGuid: TGUID;
FName: String;
FDescription: String;
FModules: TObjectList;
FCoClasses: TObjectList;
FInterfaces: TObjectList;
FRecords: TObjectList;
FAliases: TObjectList;
FEnums: TObjectList;
protected
// Protected declarations
function GetModule(Index: Integer): TModule;
function GetCoClass(Index: Integer): TCoClass;
function GetInterface(Index: Integer): TInterface;
function GetRecord(Index: Integer): TRecord;
function GetEnum(Index: Integer): TEnum;
function GetAlias(Index: Integer): TAlias;
function GetCoClassCount: Integer;
function GetInterfaceCount: Integer;
function GetRecordCount: Integer;
function GetEnumCount: Integer;
function GetAliasCount: Integer;
function GetModuleCount: Integer;
procedure Load(TypeLibrary: String);
public
// Public declarations
constructor Create(TypeLibrary: String);
destructor Destroy; override;
property Name: String read FName;
property Description: String read FDescription;
property Guid: TGUID read FGuid;
property CoClasses[Index: Integer]: TCoClass read GetCoClass;
property CoClassCount: Integer read GetCoClassCount;
property Interfaces[Index: Integer]: TInterface read GetInterface;
property InterfaceCount: Integer read GetInterfaceCount;
property Records[Index: Integer]: TRecord read GetRecord;
property RecordCount: Integer read GetRecordCount;
property Enums[Index: Integer]: TEnum read GetEnum;
property EnumCount: Integer read GetEnumCount;
property Aliases[Index: Integer]: TAlias read GetAlias;
property AliasCount: Integer read GetAliasCount;
property Modules[Index: Integer]: TModule read GetModule;
property ModuleCount: Integer read GetModuleCount;
end;
// Type utils exception type
type
ETypeUtilException= class(Exception);
// Resource strings
resourcestring
resTypeInfoNil = 'TypeInfo must be a non-nil interface pointer';
// Utility functions
procedure LoadDataType(TypeInfo: ITypeInfo; Description: TTypeDesc; DataType: TComDataType); overload;
procedure LoadDataType(TypeInfo: ITypeInfo; Description: TElemDesc; DataType: TComDataType); overload;
////////////////////////////////////////////////////////////////////////////////
implementation
////////////////////////////////////////////////////////////////////////////////
// TModule
procedure TModule.Load;
var ptAttr: PTypeAttr;
pfDesc: PFuncDesc;
dwCount: Integer;
begin
// Check loaded state
if FLoaded then exit;
// Get type info attributes
if (FTypeInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
// Add properties and methods
for dwCount:=0 to Pred(ptAttr^.cFuncs) do
begin
// Get the function description
if (FTypeInfo.GetFuncDesc(dwCount, pfDesc) = S_OK) then
begin
// The member will load itself
FFunctions.Add(TMember.Create(FTypeInfo, pfDesc, dwCount));
// Release the function description
FTypeInfo.ReleaseFuncDesc(pfDesc);
end;
end;
// Release the type attributes
FTypeInfo.ReleaseTypeAttr(ptAttr);
end;
// Perform inherited (sets the loaded state)
inherited Load;
end;
function TModule.GetFunction(Index: Integer): TMember;
begin
// Return the object
result:=TMember(FFunctions[Index]);
end;
function TModule.GetFunctionCount: Integer;
begin
// Return the count
result:=FFunctions.Count;
end;
constructor TModule.Create(TypeInfo: ITypeInfo);
begin
// Perform inherited
inherited Create(TypeInfo);
// Set starting defaults
FFunctions:=TObjectList.Create;
FFunctions.OwnsObjects:=True;
end;
destructor TModule.Destroy;
begin
// Free the function list
FFunctions.Free;
// Perform inherited
inherited Destroy;
end;
// TCoClass
procedure TCoClass.Load;
var ptAttr1: PTypeAttr;
ptAttr2: PTypeAttr;
ptInfo: ITypeInfo;
pwName: PWideChar;
cmbrInt: TCoMember;
hrType: HRefType;
dwFlags: Integer;
dwCount: Integer;
begin
// Check loaded state
if FLoaded then exit;
// Load the CoClass default and source interfaces
if (FTypeInfo.GetTypeAttr(ptAttr1) = S_OK) then
begin
// Iterate the vars of the enumeration
for dwCount:=0 to Pred(ptAttr1^.cImplTypes) do
begin
// Get the reference type via the index
if (FTypeInfo.GetRefTypeOfImplType(dwCount, hrType) = S_OK) then
begin
// Get implemented type for this interface
if (FTypeInfo.GetImplTypeFlags(dwCount, dwFlags) = S_OK) then
begin
// Get the type info so we can get the name
if (FTypeInfo.GetRefTypeInfo(hrType, ptInfo) = S_OK) then
begin
// Get the attributes
if (ptInfo.GetTypeAttr(ptAttr2) = S_OK) then
begin
// Create the coclass member
cmbrInt:=TCoMember.Create;
cmbrInt.FGuid:=ptAttr2^.guid;
// Get the name
if (ptInfo.GetDocumentation(MEMBERID_NIL, @pwName, nil, nil, nil) = S_OK) then
begin
// Name
if Assigned(pwName) then
begin
cmbrInt.FName:=OleStrToString(pwName);
SysFreeString(pwName);
end;
end;
// Get the kind
cmbrInt.FIsDispatch:=(ptAttr2^.typekind = TKIND_DISPATCH);
// Get default and source flags
cmbrInt.FIsDefault:=((dwFlags and IMPLTYPEFLAG_FDEFAULT) > 0);
cmbrInt.FIsSource:=((dwFlags and IMPLTYPEFLAG_FSOURCE) > 0);
cmbrInt.FCanCreate:=((ptAttr2^.wTypeFlags and TYPEFLAG_FCANCREATE) > 0);
// Add to interface member list
FInterfaces.Add(cmbrInt);
// Release the type info attributes
ptInfo.ReleaseTypeAttr(ptAttr2);
end;
// Release the type info
ptInfo:=nil;
end;
end;
end;
end;
// Release the type attr
FTypeInfo.ReleaseTypeAttr(ptAttr1);
end;
// Perform inherited (sets the loaded state)
inherited Load;
end;
function TCoClass.GetInterface(Index: Integer): TCoMember;
begin
// Return the object
result:=TCoMember(FInterfaces[Index]);
end;
function TCoClass.GetInterfaceCount: Integer;
begin
// Return the count
result:=FInterfaces.Count;
end;
constructor TCoClass.Create(TypeInfo: ITypeInfo);
begin
// Perform inherited
inherited Create(TypeInfo);
// Create member list
FInterfaces:=TObjectList.Create;
FInterfaces.OwnsObjects:=True;
end;
destructor TCoClass.Destroy;
begin
// Free the member list
FInterfaces.Free;
// Perform inherited
inherited Destroy;
end;
// TCoMember
constructor TCoMember.Create;
begin
// Perform inherited
inherited Create;
// Set starting defaults
FGuid:=GUID_NULL;
FName:='';
FIsDispatch:=False;
FIsDefault:=False;
FIsSource:=False;
FCanCreate:=False;
end;
destructor TCoMember.Destroy;
begin
// Perform inherited
inherited Destroy;
end;
// TMember
procedure TMember.Load(TypeInfo: ITypeInfo; VarDesc: PVarDesc; Index: Integer);
var pwName: PWideChar;
begin
// Set the ID (for dispatch based items)
FIsDispatch:=(VarDesc^.varkind = VAR_DISPATCH);
if FIsDispatch then
FID:=VarDesc^.memid
else
FID:=0;
// Get the name
if (TypeInfo.GetDocumentation(VarDesc^.memid, @pwName, nil, nil, nil) = S_OK) then
begin
// Name
if Assigned(pwName) then
begin
FName:=OleStrToString(pwName);
SysFreeString(pwName);
end;
end;
// Is this read only, or read write
FCanWrite:=((VarDesc^.wVarFlags and VARFLAG_FREADONLY) = 0);
// Load the data type info
LoadDataType(TypeInfo, VarDesc^.elemdescVar, FValue);
// Determine if member is hidden
FIsHidden:=((VarDesc^.wVarFlags and VARFLAG_FHIDDEN) > 0);
end;
procedure TMember.Load(TypeInfo: ITypeInfo; FuncDesc: PFuncDesc; Index: Integer);
var pwName: PWideChar;
pwNames: PBStrList;
cdtParam: TComDataType;
dwNames: Integer;
dwParams: Integer;
dwCount: Integer;
begin
// Set the ID (for dispatch based items)
FIsDispatch:=(FuncDesc^.funckind = FUNC_DISPATCH);
if FIsDispatch then
FID:=FuncDesc^.memid
else
FID:=0;
// Get the name
if (TypeInfo.GetDocumentation(FuncDesc^.memid, @pwName, nil, nil, nil) = S_OK) then
begin
// Name
if Assigned(pwName) then
begin
FName:=OleStrToString(pwName);
SysFreeString(pwName);
end;
end;
// Is this read only, or read write
case FuncDesc^.invkind of
INVOKE_FUNC :
begin
// Doesnt make sense for functions
FCanRead:=False;
FCanWrite:=False;
end;
INVOKE_PROPERTYGET : FCanWrite:=False;
INVOKE_PROPERTYPUT : FCanRead:=False;
INVOKE_PROPERTYPUTREF : FCanRead:=False;
end;
// Load the params for the functions
dwParams:=FuncDesc^.cParams;
Inc(dwParams);
if (dwParams > 1) and (FuncDesc^.invkind in [INVOKE_PROPERTYPUT, INVOKE_PROPERTYPUTREF]) then Dec(dwParams);
// Allocate string array large enough for the names
pwNames:=AllocMem(dwParams * SizeOf(POleStr));
// Get the names
dwNames:=0;
if (TypeInfo.GetNames(FuncDesc^.memid, pwNames, Succ(FuncDesc^.cParams), dwNames) = S_OK) then
begin
// Make sure all name entries are allocated (even if we have to do it ourselves)
for dwCount:=dwNames to Pred(dwParams) do pwNames[dwCount]:=StringToOleStr(Format('Param%d', [dwCount]));
// Need to decrease the cParams by 2. One is to account for the fact that we
// got the member name in the string array, the other is to account for the
// fact that the list is zero based
Dec(dwParams, 2);
// Build up the parameter list
for dwCount:=0 to dwParams do
begin
// Create the parameter
cdtParam:=TComDataType.Create;
// Set the name
cdtParam.FName:=OleStrToString(pwNames[Succ(dwCount)]);
// Load the data type
LoadDataType(TypeInfo, FuncDesc^.lprgelemdescParam[dwCount], cdtParam);
// Determine if optional
cdtParam.FIsOptional:=((FuncDesc^.lprgelemdescParam[dwCount].paramdesc.wParamFlags and PARAMFLAG_FOPT) > 0);
// Add to the parameter list
FParams.Add(cdtParam);
end;
end;
// Free the strings
for dwCount:=0 to Succ(dwParams) do SysFreeString(pwNames[dwCount]);
// Free the string array
FreeMem(pwNames);
// Set the return type for the function/property
case FuncDesc^.invkind of
INVOKE_FUNC : LoadDataType(TypeInfo, FuncDesc^.elemdescFunc, FValue);
INVOKE_PROPERTYGET :
begin
if not(FIsDispatch) and (FuncDesc^.cParams > 0) then
LoadDataType(TypeInfo, FuncDesc^.lprgelemdescParam[Pred(FuncDesc^.cParams)], FValue)
else
LoadDataType(TypeInfo, FuncDesc^.elemdescFunc, FValue);
end;
INVOKE_PROPERTYPUT,
INVOKE_PROPERTYPUTREF:
begin
// cParams MUST be at least one
LoadDataType(TypeInfo, FuncDesc^.lprgelemdescParam[Pred(FuncDesc^.cParams)], FValue);
end
end;
end;
function TMember.GetParam(Index: Integer): TComDataType;
begin
// Return the object
result:=TComDataType(FParams[Index]);
end;
function TMember.GetParamCount: Integer;
begin
// Return the count
result:=FParams.Count;
end;
constructor TMember.Create(TypeInfo: ITypeInfo; VarDesc: PVarDesc; Index: Integer);
begin
// Perform inherited
inherited Create;
// Create the object list
FID:=0;
FName:='';
FParams:=TObjectList.Create;
FParams.OwnsObjects:=true;
FValue:=TComDataType.Create;
FCanRead:=True;
FCanWrite:=True;
FIsDispatch:=False;
FIsHidden:=False;
// Load the member information
Load(TypeInfo, VarDesc, Index);
end;
constructor TMember.Create(TypeInfo: ITypeInfo; FuncDesc: PFuncDesc; Index: Integer);
begin
// Perform inherited
inherited Create;
// Create the object list
FID:=0;
FName:='';
FParams:=TObjectList.Create;
FParams.OwnsObjects:=true;
FValue:=TComDataType.Create;
FCanRead:=True;
FCanWrite:=True;
FIsDispatch:=False;
FIsHidden:=False;
// Load the member information
Load(TypeInfo, FuncDesc, Index);
end;
destructor TMember.Destroy;
begin
// Free the parameter list
FParams.Free;
// Free the value type
FValue.Free;
// Perform inherited
inherited Destroy;
end;
// TInterface
procedure TInterface.LoadMembers;
var ptAttr: PTypeAttr;
pfDesc: PFuncDesc;
dwCount: Integer;
begin
// Get type info attributes
if (FTypeInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
// Add properties and methods
for dwCount:=0 to Pred(ptAttr^.cFuncs) do
begin
// Get the function description
if (FTypeInfo.GetFuncDesc(dwCount, pfDesc) = S_OK) then
begin
// Check the invokation kind
if (pfDesc^.invkind = INVOKE_FUNC) then
// The member will load itself
FFunctions.Add(TMember.Create(FTypeInfo, pfDesc, dwCount))
else
// The member will load itself
FProperties.Add(TMember.Create(FTypeInfo, pfDesc, dwCount));
// Release the function description
FTypeInfo.ReleaseFuncDesc(pfDesc);
end;
end;
// Release the type attributes
FTypeInfo.ReleaseTypeAttr(ptAttr);
end;
end;
procedure TInterface.LoadVariables;
var ptAttr: PTypeAttr;
pvDesc: PVarDesc;
dwCount: Integer;
begin
// Get type info attributes
if (FTypeInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
// Add variables (which are properties)
for dwCount:=0 to Pred(ptAttr^.cVars) do
begin
// Get the var description
if (FTypeInfo.GetVarDesc(dwCount, pvDesc) = S_OK) then
begin
// Create the property member
FProperties.Add(TMember.Create(FTypeInfo, pvDesc, dwCount));
// Release the var desc
FTypeInfo.ReleaseVarDesc(pvDesc);
end;
end;
// Release the type attributes
FTypeInfo.ReleaseTypeAttr(ptAttr);
end;
end;
procedure TInterface.Load;
begin
// Check loaded state
if FLoaded then exit;
// Load the variables
LoadVariables;
// Load the members (functions/properties)
LoadMembers;
// Perform inherited (sets the loaded state)
inherited Load;
end;
function TInterface.GetProperty(Index: Integer): TMember;
begin
// Return object
result:=TMember(FProperties[Index]);
end;
function TInterface.GetFunction(Index: Integer): TMember;
begin
// Return the object
result:=TMember(FFunctions[Index]);
end;
function TInterface.GetPropertyCount: Integer;
begin
// Return the count
result:=FProperties.Count;
end;
function TInterface.GetFunctionCount: Integer;
begin
// Return the count
result:=FFunctions.Count;
end;
constructor TInterface.Create(TypeInfo: ITypeInfo);
begin
// Perform inherited
inherited Create(TypeInfo);
// Set starting defaults
FProperties:=TObjectList.Create;
FProperties.OwnsObjects:=True;
FFunctions:=TObjectList.Create;
FFunctions.OwnsObjects:=True;
end;
destructor TInterface.Destroy;
begin
// Free the object lists
FProperties.Free;
FFunctions.Free;
// Perform inherited
inherited Destroy;
end;
// TEnum
procedure TEnum.Load;
var ptAttr: PTypeAttr;
pvDesc: PVarDesc;
pwName: PWideChar;
cdtValue: TComDataType;
dwCount: Integer;
begin
// Bail if loaded
if FLoaded then exit;
// Load the constant values
if (FTypeInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
// Iterate the vars of the record
for dwCount:=0 to Pred(ptAttr^.cVars) do
begin
// Get the var description
if (FTypeInfo.GetVarDesc(dwCount, pvDesc) = S_OK) then
begin
// Create the value data object
cdtValue:=TComDataType.Create;
// Get documentation
if (FTypeInfo.GetDocumentation(pvDesc^.memid, @pwName, nil, nil, nil) = S_OK) then
begin
// Name
if Assigned(pwName) then
begin
cdtValue.FName:=OleStrToString(pwName);
SysFreeString(pwName);
end;
end;
// Constant value
cdtValue.FVT:=pvDesc^.varkind;
cdtValue.FConstValue:=pvDesc^.lpvarValue^;
// Add to the value list
FValues.Add(cdtValue);
// Release the var desc
FTypeInfo.ReleaseVarDesc(pvDesc);
end;
end;
// Release the type attr
FTypeInfo.ReleaseTypeAttr(ptAttr);
end;
// Perform inherited (sets the loaded state)
inherited Load;
end;
function TEnum.GetValues(Index: Integer): TComDataType;
begin
// Return the value field
result:=TComDataType(FValues[Index]);
end;
function TEnum.GetValueCount: Integer;
begin
// Return count
result:=FValues.Count;
end;
constructor TEnum.Create(TypeInfo: ITypeInfo);
begin
// Perform inherited
inherited Create(TypeInfo);
// Set starting defaults
FValues:=TObjectList.Create;
FValues.OwnsObjects:=True;
end;
destructor TEnum.Destroy;
begin
// Free the value list
FValues.Free;
// Perform inherited
inherited Destroy;
end;
// TRecord
procedure TRecord.Load;
var ptAttr: PTypeAttr;
pvDesc: PVarDesc;
pwName: PWideChar;
cdtField: TComDataType;
dwCount: Integer;
begin
// Bail if loaded
if FLoaded then exit;
// Load the fields
if (FTypeInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
// Iterate the vars of the record
for dwCount:=0 to Pred(ptAttr^.cVars) do
begin
// Get the var description
if (FTypeInfo.GetVarDesc(dwCount, pvDesc) = S_OK) then
begin
// Create the field data object
cdtField:=TComDataType.Create;
// Get documentation
if (FTypeInfo.GetDocumentation(pvDesc^.memid, @pwName, nil, nil, nil) = S_OK) then
begin
// Name
if Assigned(pwName) then
begin
cdtField.FName:=OleStrToString(pwName);
SysFreeString(pwName);
end;
end;
// Load the data type info
LoadDataType(FTypeInfo, pvDesc^.elemdescVar, cdtField);
// Add to the field list
FFields.Add(cdtField);
// Release the var desc
FTypeInfo.ReleaseVarDesc(pvDesc);
end;
end;
// Release the type attr
FTypeInfo.ReleaseTypeAttr(ptAttr);
end;
// Perform inherited (sets the loaded state)
inherited Load;
end;
function TRecord.GetFields(Index: Integer): TComDataType;
begin
// Return the data field
result:=TComDataType(FFields[Index]);
end;
function TRecord.GetFieldCount: Integer;
begin
// Return the count
result:=FFields.Count;
end;
constructor TRecord.Create(TypeInfo: ITypeInfo);
begin
// Perform inherited
inherited Create(TypeInfo);
// Set starting defaults
FFields:=TObjectList.Create;
FFields.OwnsObjects:=True;
end;
destructor TRecord.Destroy;
begin
// Free the field list
FFields.Free;
// Perform inherited
inherited Destroy;
end;
// TAlias
procedure TAlias.Load;
var ptAttr: PTypeAttr;
begin
// Bail if already loaded
if FLoaded then exit;
// Get the type info attributes
if (FTypeInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
// Get the data type that this describes
LoadDataType(FTypeInfo, ptAttr^.tdescAlias, FAliasType);
// Release the type info attr
FTypeInfo.ReleaseTypeAttr(ptAttr);
end;
// Perform inherited (sets the loaded state)
inherited Load;
end;
constructor TAlias.Create(TypeInfo: ITypeInfo);
begin
// Perform inherited
inherited Create(TypeInfo);
// Set starting defaults
FAliasType:=TComDataType.Create;
end;
destructor TAlias.Destroy;
begin
// Free the alias data type
FAliasType.Free;
// Perform inherited
inherited Destroy;
end;
// TTypeClass
procedure TTypeClass.LoadBaseInfo;
var ptAttr: PTypeAttr;
pwName: PWideChar;
begin
// Get the class name
if (FTypeInfo.GetDocumentation(MEMBERID_NIL, @pwName, nil, nil, nil) = S_OK) then
begin
// Name
if Assigned(pwName) then
begin
FName:=OleStrToString(pwName);
SysFreeString(pwName);
end;
end;
// Get the type info attributes
if (FTypeInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
// Set the guid
FGuid:=ptAttr^.guid;
// Release the pointer to the attributes
FTypeInfo.ReleaseTypeAttr(ptAttr);
end;
end;
procedure TTypeClass.Load;
begin
// Set the loaded flag
FLoaded:=True;
end;
constructor TTypeClass.Create(TypeInfo: ITypeInfo);
begin
// Perform inherited
inherited Create;
// Check for nil being passed
if Assigned(TypeInfo) then
FTypeInfo:=TypeInfo
else
raise ETypeUtilException.CreateRes(@resTypeInfoNil);
// Set starting defaults
FLoaded:=False;
FGuid:=GUID_NULL;
FName:='';
// Load the base type information
LoadBaseInfo;
end;
destructor TTypeClass.Destroy;
begin
// Release the type info
FTypeInfo:=nil;
// Perform inherited
inherited Destroy;
end;
// TTypeLibrary
function TTypeLibrary.GetModule(Index: Integer): TModule;
begin
// Return object
result:=TModule(FModules[Index]);
// Load the object
result.Load;
end;
function TTypeLibrary.GetCoClass(Index: Integer): TCoClass;
begin
// Return object
result:=TCoClass(FCoClasses[Index]);
// Load the object
result.Load;
end;
function TTypeLibrary.GetInterface(Index: Integer): TInterface;
begin
// Return object
result:=TInterface(FInterfaces[Index]);
// Load the object
result.Load;
end;
function TTypeLibrary.GetRecord(Index: Integer): TRecord;
begin
// Return object
result:=TRecord(FRecords[Index]);
// Load the object
result.Load;
end;
function TTypeLibrary.GetEnum(Index: Integer): TEnum;
begin
// Return object
result:=TEnum(FEnums[Index]);
// Load the object
result.Load;
end;
function TTypeLibrary.GetAlias(Index: Integer): TAlias;
begin
// Return object
result:=TAlias(FAliases[Index]);
// Load the object
result.Load;
end;
function TTypeLibrary.GetCoClassCount: Integer;
begin
// Return count
result:=FCoClasses.Count;
end;
function TTypeLibrary.GetModuleCount: Integer;
begin
// Return count
result:=FModules.Count;
end;
function TTypeLibrary.GetInterfaceCount: Integer;
begin
// Return count
result:=FInterfaces.Count;
end;
function TTypeLibrary.GetRecordCount: Integer;
begin
// Return count
result:=FRecords.Count;
end;
function TTypeLibrary.GetEnumCount: Integer;
begin
// Return count
result:=FEnums.Count;
end;
function TTypeLibrary.GetAliasCount: Integer;
begin
// Return count
result:=FAliases.Count;
end;
procedure TTypeLibrary.Load(TypeLibrary: String);
var pwFileName: PWideChar;
pwName: PWideChar;
pwDesc: PWideChar;
ptlAttr: PTLibAttr;
ptAttr: PTypeAttr;
ptInfo: ITypeInfo;
dwCount: Integer;
hrStatus: HResult;
begin
// Attempt to load the type library
pwFileName:=StringToOleStr(TypeLibrary);
hrStatus:=LoadTypeLib(pwFileName, FTypeLib);
SysFreeString(pwFileName);
// Check result
if (hrStatus <> S_OK) then raise Exception.Create(SysErrorMessage(hrStatus));
// Get the type library name
if (FTypeLib.GetDocumentation(-1, @pwName, @pwDesc, nil, nil) = S_OK) then
begin
// Name
if Assigned(pwName) then
begin
FName:=OleStrToString(pwName);
SysFreeString(pwName);
end;
// Description
if Assigned(pwDesc) then
begin
FDescription:=OleStrToString(pwDesc);
SysFreeString(pwDesc);
end;
end;
// Get the guid
if (FTypeLib.GetLibAttr(ptlAttr) = S_OK) then
begin
FGuid:=ptlAttr^.Guid;
// Release the library attr
FTypeLib.ReleaseTLibAttr(ptlAttr);
end;
// Get the type info count in the library
for dwCount:=0 to Pred(FTypeLib.GetTypeInfoCount) do
begin;
// Get the type info at the given index
if (FTypeLib.GetTypeInfo(dwCount, ptInfo) = S_OK) then
begin
// Get the type info attribute
if (ptInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
// Create the desired sub object
case ptAttr.typekind of
TKIND_ENUM : FEnums.Add(TEnum.Create(ptInfo));
TKIND_RECORD : FRecords.Add(TRecord.Create(ptInfo));
TKIND_MODULE : FModules.Add(TModule.Create(ptInfo));
TKIND_INTERFACE,
TKIND_DISPATCH : FInterfaces.Add(TInterface.Create(ptInfo));
TKIND_COCLASS : FCoClasses.Add(TCoClass.Create(ptInfo));
TKIND_ALIAS : FAliases.Add(TAlias.Create(ptInfo));
end;
// Release the type attribute
ptInfo.ReleaseTypeAttr(ptAttr);
end;
// Release the type info
ptInfo:=nil;
end;
end;
end;
constructor TTypeLibrary.Create(TypeLibrary: String);
begin
// Perform inherited
inherited Create;
// Set starting defaults
FTypeLib:=nil;
FGuid:=GUID_NULL;
FName:='';
FDescription:='';
FCoClasses:=TObjectList.Create;
FCoClasses.OwnsObjects:=True;
FInterfaces:=TObjectList.Create;
FInterfaces.OwnsObjects:=True;
FRecords:=TObjectList.Create;
FRecords.OwnsObjects:=True;
FAliases:=TObjectList.Create;
FAliases.OwnsObjects:=True;
FEnums:=TObjectList.Create;
FEnums.OwnsObjects:=True;
FModules:=TObjectList.Create;
FModules.OwnsObjects:=True;
// Load the classes
Load(TypeLibrary);
end;
destructor TTypeLibrary.Destroy;
begin
// Clear interfaces
FTypeLib:=nil;
// Free object lists
FModules.Free;
FCoClasses.Free;
FInterfaces.Free;
FRecords.Free;
FAliases.Free;
FEnums.Free;
// Perform inherited
inherited Destroy;
end;
// TComDataType
function TComDataType.GetBoundsCount: Integer;
begin
// Return count
result:=FBounds.Count;
end;
function TComDataType.GetDataTypeName;
begin
// Return the delphi data type name
result:=DATA_TYPE_NAMES[FVT];
end;
function TComDataType.GetBounds(Index: Integer): TArrayBound;
begin
// Return the requested bounds
result:=PArrayBound(FBounds[Index])^;
end;
procedure TComDataType.SetName(Value: String);
begin
// Callable by "friends"
FName:=Value;
end;
procedure TComDataType.SetVT(Value: Integer);
begin
// Callable by "friends"
FVT:=Value;
end;
procedure TComDataType.SetIsUserDefined(Value: Boolean);
begin
// Callable by "friends"
FIsUserDefined:=True;
end;
procedure TComDataType.SetIsArray(Value: Boolean);
begin
// Callable by "friends"
FIsArray:=True;
end;
procedure TComDataType.AddBound(LowBound, HiBound: Integer);
var paBound: PArrayBound;
begin
// Allocate memory
paBound:=AllocMem(SizeOf(TArrayBound));
// Set bounds
paBound^.lBound:=LowBound;
paBound^.uBound:=HiBound;
// Add to the list
FBounds.Add(paBound);
end;
constructor TComDataType.Create;
begin
// Perform inherited
inherited Create;
// Set starting values
FVT:=0;
FName:='';
FIsOptional:=False;
FIsUserDefined:=False;
FIsArray:=False;
FConstValue:=0;
FBounds:=TList.Create;
FGuid:=GUID_NULL;
end;
destructor TComDataType.Destroy;
var dwBounds: Integer;
begin
// Clear all array bounds
for dwBounds:=0 to Pred(FBounds.Count) do
begin
FreeMem(PArrayBound(FBounds[dwBounds]));
end;
// Free the list
FBounds.Free;
// Perform inherited
inherited Destroy;
end;
procedure LoadDataType(TypeInfo: ITypeInfo; Description: TElemDesc; DataType: TComDataType);
var ptInfo: ITypeInfo;
ptAttr: PTypeAttr;
udType: Cardinal;
dwBounds: Integer;
begin
// Get the data type from the type desc
DataType.FVT:=Description.tdesc.vt;
// Need to figure out what the actual type is
udType:=0;
case DataType.FVT of
VT_PTR,
VT_SAFEARRAY :
begin
// Get the data type from the pointer type
DataType.FVT:=Description.tdesc.ptdesc.vt;
// If user defined, set the udt reftype
if (DataType.FVT = VT_USERDEFINED) then udType:=Description.tdesc.padesc.tdescElem.hreftype;
end;
// Get the type from the array description
VT_CARRAY :
begin
// Set array flag
DataType.FIsArray:=True;
// Add the bounds
for dwBounds:=0 to Pred(Description.tdesc.padesc^.cDims) do
begin
with Description.tdesc.padesc^ do
begin
DataType.AddBound(rgbounds[dwBounds].lLbound, Pred(rgbounds[dwBounds].cElements));
end;
end;
// Set the data type
DataType.FVT:=Description.tdesc.padesc.tdescElem.vt;
end;
// Get the user defined reftype
VT_USERDEFINED : udType:=Description.tdesc.hreftype;
end;
// Check for user defined type
if (DataType.FVT = VT_USERDEFINED) then
begin
// User defined
DataType.FIsUserDefined:=True;
// Try to get the referenced type info
if (TypeInfo.GetRefTypeInfo(udType, ptInfo) = S_OK) then
begin
// Get the attributes so we can get the guid
if (ptInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
DataType.FGuid:=ptAttr^.guid;
// Release the type attributes
ptInfo.ReleaseTypeAttr(ptAttr);
end;
// Release the type info
ptInfo:=nil;
end;
end;
end;
procedure LoadDataType(TypeInfo: ITypeInfo; Description: TTypeDesc; DataType: TComDataType);
var ptInfo: ITypeInfo;
ptAttr: PTypeAttr;
udType: Cardinal;
dwBounds: Integer;
begin
// Get the data type from the type desc
DataType.FVT:=Description.vt;
// Need to figure out what the actual type is
udType:=0;
case DataType.FVT of
VT_PTR,
VT_SAFEARRAY :
begin
// Get the data type from the pointer type
DataType.FVT:=Description.ptdesc.vt;
// If user defined, set the udt reftype
if (DataType.FVT = VT_USERDEFINED) then udType:=Description.padesc.tdescElem.hreftype;
end;
// Get the type from the array description
VT_CARRAY :
begin
// Set array flag
DataType.FIsArray:=True;
// Add the bounds
for dwBounds:=0 to Pred(Description.padesc^.cDims) do
begin
with Description.padesc^ do
begin
DataType.AddBound(rgbounds[dwBounds].lLbound, Pred(rgbounds[dwBounds].cElements));
end;
end;
// Set the array data type
DataType.FVT:=Description.padesc.tdescElem.vt;
end;
// Get the user defined reftype
VT_USERDEFINED : udType:=Description.hreftype;
end;
// Check for user defined type
if (DataType.FVT = VT_USERDEFINED) then
begin
// User defined
DataType.FIsUserDefined:=True;
// Try to get the referenced type info
if (TypeInfo.GetRefTypeInfo(udType, ptInfo) = S_OK) then
begin
// Get the attributes so we can get the guid
if (ptInfo.GetTypeAttr(ptAttr) = S_OK) then
begin
DataType.FGuid:=ptAttr^.guid;
// Release the type attributes
ptInfo.ReleaseTypeAttr(ptAttr);
end;
// Release the type info
ptInfo:=nil;
end;
end;
end;
end.
|
unit fmClient;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TfrmClient = class(TForm)
btnDemo1: TButton;
Memo1: TMemo;
edtName: TLabeledEdit;
procedure btnDemo1Click(Sender: TObject);
private
procedure AddLine(const s: string);
public
end;
var
frmClient: TfrmClient;
implementation
uses ZmqIntf;
{$R *.dfm}
procedure TfrmClient.AddLine(const s: string);
begin
Memo1.Lines.Add(s);
Application.ProcessMessages;
end;
procedure TfrmClient.btnDemo1Click(Sender: TObject);
var
Context: IZMQContext;
Requester: PZMQSocket;
I: Integer;
Msg: WideString;
begin
Context := ZMQ.CreateContext;
// Socket to talk to server
AddLine('Connecting to hello world server');
Requester := Context.Socket(stRequest);
Requester.Connect('tcp://localhost:5559');
for I := 0 to 50 do
begin
Msg := Format('Hello %d from %s', [I, edtName.Text]);
AddLine(Format('Sending... %s', [Msg]));
Requester.SendString(Msg);
Requester.RecvString(Msg);
AddLine(Format('Received %d - %s', [I, Msg]));
end;
Requester.Free;
Context := nil;
end;
end.
|
unit fieldlogger.authentication;
interface
uses
FireDAC.Comp.Client;
type
TAuthentication = class
public
class function Authenticate(conn: TFDConnection;
Username, Password: string): boolean;
end;
implementation
{ TAuthentication }
class function TAuthentication.Authenticate(conn: TFDConnection;
Username, Password: string): boolean;
begin
Result := False;
conn.Connected := False;
conn.Params.Values['USER_NAME'] := Username;
conn.Params.Values['Password'] := Password;
try
conn.Connected := True;
finally
Result := conn.Connected;
end;
end;
end.
|
unit SubDividerProgressForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;
type
TfrmProgress = class(TForm)
prg: TProgressBar;
lblStatus: TLabel;
private
FObjectName: string;
{ Private declarations }
public
{ Public declarations }
property ObjectName: string read FObjectName write FObjectName;
procedure SetParams(AMin, AMax, AStep: integer; const AName: string);
procedure StepIt;
end;
var
frmProgress: TfrmProgress;
implementation
{$R *.dfm}
const sLoadingMessage = 'Загружено %d из %d %s';
procedure TfrmProgress.SetParams(AMin, AMax, AStep: integer; const AName: string);
begin
prg.Max := AMax;
prg.Min := AMin;
prg.Position := 0;
prg.Step := AStep;
lblStatus.Caption := '';
FObjectName := AName;
(prg.Owner as TWinControl).Update;
end;
procedure TfrmProgress.StepIt;
begin
prg.StepIt;
lblStatus.Caption := Format(sLoadingMessage, [prg.Position, prg.Max, FObjectName]);
lblStatus.Update;
prg.Update;
end;
end.
|
unit UMyShareInfo;
interface
uses Generics.Collections, UModelUtil, UChangeInfo, Classes, UDataSetInfo;
type
{$Region ' 共享路径 数据结构 ' }
// 共享路径信息
TSharePathInfo = class
public
FullPath : string;
PathType : string;
public
constructor Create( _FullPath, _PathType : string );
end;
TSharePathPair = TPair< string , TSharePathInfo >;
TSharePathHash = class(TStringDictionary< TSharePathInfo >);
// 共享路径控制器
TMySharePathInfo = class( TMyDataInfo )
public
SharePathHash : TSharePathHash;
public
constructor Create;
destructor Destroy; override;
end;
{$EndRegion}
{$Region ' 共享路径 数据接口 ' }
// 访问 集合
TSharePathAccessInfo = class
public
SharePathHash : TSharePathHash;
public
constructor Create;
destructor Destroy; override;
end;
// 访问 Item
TSharePathItemAccessInfo = class( TSharePathAccessInfo )
public
FullPath : string;
protected
SharePathInfo : TSharePathInfo;
public
constructor Create( _FullPath : string );
protected
function FindSharePathInfo : Boolean;
end;
{$EndRegion}
{$Region ' 共享路径 数据修改 ' }
// 修改 指定路径 父类
TSharePathWriteInfo = class( TSharePathItemAccessInfo )
end;
// 添加
TSharePathAddInfo = class( TSharePathWriteInfo )
private
PathType : string;
public
procedure SetPathType( _PathType : string );
procedure Update;
end;
// 删除
TSharePathRemoveInfo = class( TSharePathWriteInfo )
public
procedure Update;
end;
{$EndRegion}
{$Region ' 共享路径 数据读取 ' }
// 读取 是否存在一条共享路径
TSharePathReadIsExistShare = class( TSharePathAccessInfo )
public
function get : Boolean;
end;
// 读取 文件是否共享
TSharePathReadIsEnable = class( TSharePathAccessInfo )
private
FilePath : string;
public
constructor Create( _FilePath : string );
function get : Boolean;
end;
// 读取 所有共享路径
TSharePathReadPathList = class( TSharePathAccessInfo )
public
function get : TStringList;
end;
// 读取 信息辅助类
MySharePathInfoReadUtil = class
public
class function ReadIsExistShare : Boolean; // 是否存在共享路径
class function ReadFileIsEnable( FilePath : string ): Boolean; // 文件是否共享
class function ReadSharePathList : TStringList; // 读取所有共享路径
end;
{$EndRegion}
{$Region ' 共享下载 数据结构 ' }
// 共享下载信息
TShareDownInfo = class
public
DesPcID : string;
FullPath : string;
SavePath : string;
public
constructor Create( _DesPcID, _FullPath : string );
procedure SetSavePath( _SavePath : string );
end;
TShareDownList = class( TObjectList<TShareDownInfo> )end;
// 试用版功能限制
TShareDownDisableInfo = class
public
DesPcID, FilePath, SavePath : string;
FileSize, CompletedSize : Int64;
FileTime : TDateTime;
public
constructor Create( _DesPcID, _FilePath, _SavePath : string );
procedure SetSizeInfo( _FileSize, _CompletedSize : Int64 );
procedure SetFileTime( _FileTime : TDateTime );
end;
TShareDownDisableList = class( TObjectList<TShareDownDisableInfo> )end;
// 下载 历史记录器
TMyShareDownInfo = class( TMyDataInfo )
public
ShareDownList : TShareDownList;
ShareDownDisableList : TShareDownDisableList;
public
constructor Create;
destructor Destroy; override;
end;
{$EndRegion}
{$Region ' 共享下载 数据接口 ' }
// 访问 集合
TShareDownAccessInfo = class
public
ShareDownList : TShareDownList;
ShareDownDisableList : TShareDownDisableList;
public
constructor Create;
destructor Destroy; override;
end;
// 访问 Item
TShareDownItemAccessInfo = class( TShareDownAccessInfo )
public
DesPcID, FullPath : string;
protected
ShareDownIndex : Integer;
ShareDownInfo : TShareDownInfo;
public
constructor Create( _DesPcID, _FullPath : string );
protected
function FindShareDownInfo : Boolean;
end;
// 访问 免费限制
TShareDownDisableAccessInfo = class( TShareDownAccessInfo )
public
DesPcID, FilePath : string;
protected
ShareDownDisableIndex : Integer;
ShareDownDisableInfo : TShareDownDisableInfo;
public
constructor Create( _DesPcID, _FilePath : string );
protected
function FindShareDownDisable : Boolean;
end;
{$EndRegion}
{$Region ' 共享下载 数据修改 ' }
{$Region ' 修改 Item 信息 ' }
// 修改 父类
TShareDownWriteInfo = class( TShareDownItemAccessInfo )
end;
// 添加
TShareDownAddInfo = class( TShareDownWriteInfo )
private
SavePath : string;
public
procedure SetSavePath( _SavePath : string );
procedure Update;
end;
// 删除
TShareDownRemoveInfo = class( TShareDownWriteInfo )
public
procedure Update;
end;
{$EndRegion}
{$Region ' 修改 试用限制 信息 ' }
// 修改
TShareDownDisableWriteInfo = class( TShareDownDisableAccessInfo )
end;
// 添加
TShareDownDisableAddInfo = class( TShareDownDisableWriteInfo )
public
SavePath : string;
FileSize, CompletedSize : Int64;
FileTime : TDateTime;
public
procedure SetSavePath( _SavePath : string );
procedure SetSizeInfo( _FileSize, _CompletedSize : Int64 );
procedure SetFileTime( _FileTime : TDateTime );
procedure Update;
end;
// 删除
TShareDownDisableRemoveInfo = class( TShareDownDisableWriteInfo )
public
procedure Update;
end;
{$EndRegion}
{$EndRegion}
{$Region ' 共享下载 数据读取 ' }
{$Region ' 读取 Item 集合 ' }
TShareDownReadInfo = class( TShareDownAccessInfo )
end;
// 是否存在 相同的 下载路径
TShareDownReadIsExistDownPath = class( TShareDownReadInfo )
public
DownloadPath : string;
public
constructor Create( _DownloadPath : string );
function get : Boolean;
end;
// 获取 Pc 的下载路径
TShareDownReadPcShareDown = class( TShareDownReadInfo )
public
PcID : string;
public
constructor Create( _PcID : string );
function get : TStringList;
end;
// 读取 根目录
TShareDownReadRootPath = class( TShareDownReadInfo )
public
PcID, FilePath : string;
public
constructor Create( _PcID, _FilePath : string );
function get : string;
end;
// 读取 冲突的路径
TShareDownReadConflictPath = class( TShareDownItemAccessInfo )
public
function get : TStringList;
end;
{$EndRegion}
{$Region ' 读取 Item ' }
// 读取根路径信息
TShareDownReadRootInfo = class( TShareDownItemAccessInfo )
end;
// 读取 保存路径
TShareDownReadSavePath = class( TShareDownReadRootInfo )
public
function get : string;
end;
// 是否存在 路径
TShareDownReadIsExist = class( TShareDownReadRootInfo )
public
function get : Boolean;
end;
{$EndRegion}
{$Region ' 读取 免费下载 ' }
// 读取免费限制的
TShareDownReadDisablePath = class( TShareDownReadInfo )
public
function get : TShareDownDisableList;
end;
{$EndRegion}
// 读取信息 辅助类
MyShareDownInfoReadUtil = class
public
class function ReadSavePath( DesPcID, FullPath : string ): string;
class function ReadIsEnable( DesPcID, FullPath : string ): Boolean;
class function ReadConfilctPathList( DesPcID, FullPath : string ): TStringList;
public
class function ReadRootPath( DesPcID, FilePath : string ): string;
class function ReadDownPathIsExist( DownPath : string ): Boolean;
class function ReadPcDownPathList( PcID : string ): TStringList;
public
class function ReadDisablePathList : TShareDownDisableList;
end;
{$EndRegion}
var
MySharePathInfo : TMySharePathInfo;
MyShareDownInfo : TMyShareDownInfo;
implementation
uses UMyClient, UMyUtil, UMyShareControl, UMyNetPcInfo;
{ TSharePathInfo }
constructor TSharePathInfo.Create(_FullPath, _PathType: string);
begin
FullPath := _FullPath;
PathType := _PathType;
end;
{ TMySharePathInfo }
constructor TMySharePathInfo.Create;
begin
inherited Create;
SharePathHash := TSharePathHash.Create;
end;
destructor TMySharePathInfo.Destroy;
begin
SharePathHash.Free;
inherited;
end;
{ TSharePathAddInfo }
procedure TSharePathAddInfo.SetPathType(_PathType: string);
begin
PathType := _PathType;
end;
procedure TSharePathAddInfo.Update;
begin
// 已存在
if FindSharePathInfo then
Exit;
SharePathInfo := TSharePathInfo.Create( FullPath, PathType );
SharePathHash.AddOrSetValue( FullPath, SharePathInfo );
end;
{ TSharePathRemoveInfo }
procedure TSharePathRemoveInfo.Update;
begin
// 不存在
if not FindSharePathInfo then
Exit;
SharePathHash.Remove( FullPath );
end;
{ TShareDownInfo }
constructor TShareDownInfo.Create(_DesPcID, _FullPath: string);
begin
DesPcID := _DesPcID;
FullPath := _FullPath;
end;
procedure TShareDownInfo.SetSavePath(_SavePath: string);
begin
SavePath := _SavePath;
end;
{ TMyShareDownInfo }
constructor TMyShareDownInfo.Create;
begin
inherited;
ShareDownList := TShareDownList.Create;
ShareDownDisableList := TShareDownDisableList.Create;
end;
destructor TMyShareDownInfo.Destroy;
begin
ShareDownDisableList.Free;
ShareDownList.Free;
inherited;
end;
{ TShareDownRemoveInfo }
procedure TShareDownRemoveInfo.Update;
begin
// 不存在
if not FindShareDownInfo then
Exit;
// 删除
ShareDownList.Delete( ShareDownIndex );
end;
{ TShareDownAddInfo }
procedure TShareDownAddInfo.SetSavePath(_SavePath: string);
begin
SavePath := _SavePath;
end;
procedure TShareDownAddInfo.Update;
begin
// 已存在
if FindShareDownInfo then
Exit;
// 添加
ShareDownInfo := TShareDownInfo.Create( DesPcID, FullPath );
ShareDownInfo.SetSavePath( SavePath );
ShareDownList.Add( ShareDownInfo );
end;
{ TShareDownDisableInfo }
constructor TShareDownDisableInfo.Create(_DesPcID, _FilePath,
_SavePath: string);
begin
DesPcID := _DesPcID;
FilePath := _FilePath;
SavePath := _SavePath;
end;
procedure TShareDownDisableInfo.SetFileTime(_FileTime: TDateTime);
begin
FileTime := _FileTime;
end;
procedure TShareDownDisableInfo.SetSizeInfo(_FileSize, _CompletedSize: Int64);
begin
FileSize := _FileSize;
CompletedSize := _CompletedSize;
end;
{ TShareDownDisableAddInfo }
procedure TShareDownDisableAddInfo.SetFileTime(_FileTime: TDateTime);
begin
FileTime := _FileTime;
end;
procedure TShareDownDisableAddInfo.SetSavePath(_SavePath: string);
begin
SavePath := _SavePath;
end;
procedure TShareDownDisableAddInfo.SetSizeInfo(_FileSize,
_CompletedSize: Int64);
begin
FileSize := _FileSize;
CompletedSize := _CompletedSize;
end;
procedure TShareDownDisableAddInfo.Update;
begin
// 已存在
if FindShareDownDisable then
Exit;
// 添加
ShareDownDisableInfo := TShareDownDisableInfo.Create( DesPcID, FilePath, SavePath );
ShareDownDisableInfo.SetSizeInfo( FileSize, CompletedSize );
ShareDownDisableInfo.SetFileTime( FileTime );
ShareDownDisableList.Add( ShareDownDisableInfo );
end;
{ TShareDownDisableRemoveInfo }
procedure TShareDownDisableRemoveInfo.Update;
begin
// 不存在
if not FindShareDownDisable then
Exit;
// 删除
ShareDownDisableList.Delete( ShareDownDisableIndex )
end;
{ TShareDownDisableRead }
function TShareDownReadDisablePath.get: TShareDownDisableList;
var
i : Integer;
DesPcID, FilePath, SavePath : string;
ShareDownDisableInfo : TShareDownDisableInfo;
begin
Result := TShareDownDisableList.Create;
for i := 0 to ShareDownDisableList.Count - 1 do
begin
DesPcID := ShareDownDisableList[i].DesPcID;
FilePath := ShareDownDisableList[i].FilePath;
SavePath := ShareDownDisableList[i].SavePath;
ShareDownDisableInfo := TShareDownDisableInfo.Create( DesPcID, FilePath, SavePath );
ShareDownDisableInfo.SetSizeInfo( ShareDownDisableList[i].FileSize, ShareDownDisableList[i].CompletedSize );
ShareDownDisableInfo.SetFileTime( ShareDownDisableList[i].FileTime );
Result.Add( ShareDownDisableInfo );
end;
end;
{ TMySharePathReadIsShare }
function TSharePathReadIsExistShare.get: Boolean;
begin
Result := SharePathHash.Count > 0;
end;
{ TMySharePathReadEnable }
constructor TSharePathReadIsEnable.Create(_FilePath: string);
begin
inherited Create;
FilePath := _FilePath;
end;
function TSharePathReadIsEnable.get: Boolean;
var
p : TSharePathPair;
begin
Result := False;
for p in SharePathHash do
if MyMatchMask.CheckEqualsOrChild( FilePath, p.Value.FullPath ) then
begin
Result := True;
Break;
end;
end;
{ MySharePathReadInfoUtil }
class function MySharePathInfoReadUtil.ReadFileIsEnable(FilePath: string): Boolean;
var
MySharePathReadEnable : TSharePathReadIsEnable;
begin
MySharePathReadEnable := TSharePathReadIsEnable.Create( FilePath );
Result := MySharePathReadEnable.get;
MySharePathReadEnable.Free;
end;
class function MySharePathInfoReadUtil.ReadIsExistShare: Boolean;
var
MySharePathReadIsShare : TSharePathReadIsExistShare;
begin
MySharePathReadIsShare := TSharePathReadIsExistShare.Create;
Result := MySharePathReadIsShare.get;
MySharePathReadIsShare.Free;
end;
class function MySharePathInfoReadUtil.ReadSharePathList: TStringList;
var
SharePathReadPathList : TSharePathReadPathList;
begin
SharePathReadPathList := TSharePathReadPathList.Create;
Result := SharePathReadPathList.get;
SharePathReadPathList.Free;
end;
{ TMyShareDownReadDownloadExist }
constructor TShareDownReadIsExistDownPath.Create(_DownloadPath: string);
begin
inherited Create;
DownloadPath := _DownloadPath;
end;
function TShareDownReadIsExistDownPath.get: Boolean;
var
i : Integer;
begin
Result := False;
for i := 0 to ShareDownList.Count - 1 do
if ShareDownList[i].SavePath = DownloadPath then
begin
Result := True;
Break;
end;
end;
{ TMyShareDownReadRootPath }
constructor TShareDownReadRootPath.Create(_PcID, _FilePath: string);
begin
inherited Create;
PcID := _PcID;
FilePath := _FilePath;
end;
function TShareDownReadRootPath.get: string;
var
i : Integer;
begin
Result := '';
for i := 0 to ShareDownList.Count - 1 do
begin
if ShareDownList[i].DesPcID <> PcID then
Continue;
if MyMatchMask.CheckEqualsOrChild( FilePath, ShareDownList[i].FullPath ) then
begin
Result := ShareDownList[i].FullPath;
Break;
end;
end;
end;
{ TMyShareDownReadSavePath }
function TShareDownReadSavePath.get: string;
begin
Result := '';
if not FindShareDownInfo then
Exit;
Result := ShareDownInfo.SavePath;
end;
{ TMyShareDownReadExist }
function TShareDownReadIsExist.get: Boolean;
begin
Result := FindShareDownInfo;
end;
{ MyShareDownInfoReadUtil }
class function MyShareDownInfoReadUtil.ReadConfilctPathList(DesPcID,
FullPath: string): TStringList;
var
MyShareDownReadConflictPath : TShareDownReadConflictPath;
begin
MyShareDownReadConflictPath := TShareDownReadConflictPath.Create( DesPcID, FullPath );
Result := MyShareDownReadConflictPath.get;
MyShareDownReadConflictPath.Free;
end;
class function MyShareDownInfoReadUtil.ReadDisablePathList: TShareDownDisableList;
var
ShareDownDisableRead : TShareDownReadDisablePath;
begin
ShareDownDisableRead := TShareDownReadDisablePath.Create;
Result := ShareDownDisableRead.get;
ShareDownDisableRead.Free;
end;
class function MyShareDownInfoReadUtil.ReadDownPathIsExist(
DownPath: string): Boolean;
var
MyShareDownReadDownloadExist : TShareDownReadIsExistDownPath;
begin
MyShareDownReadDownloadExist := TShareDownReadIsExistDownPath.Create( DownPath );
Result := MyShareDownReadDownloadExist.get;
MyShareDownReadDownloadExist.Free;
end;
class function MyShareDownInfoReadUtil.ReadPcDownPathList(
PcID: string): TStringList;
var
MyShareDownReadPcDownPath : TShareDownReadPcShareDown;
begin
MyShareDownReadPcDownPath := TShareDownReadPcShareDown.Create( PcID );
Result := MyShareDownReadPcDownPath.get;
MyShareDownReadPcDownPath.Free;
end;
class function MyShareDownInfoReadUtil.ReadIsEnable(DesPcID,
FullPath: string): Boolean;
var
MyShareDownReadExist : TShareDownReadIsExist;
begin
MyShareDownReadExist := TShareDownReadIsExist.Create( DesPcID, FullPath );
Result := MyShareDownReadExist.get;
MyShareDownReadExist.Free;
end;
class function MyShareDownInfoReadUtil.ReadRootPath(DesPcID,
FilePath: string): string;
var
MyShareDownReadRootPath : TShareDownReadRootPath;
begin
MyShareDownReadRootPath := TShareDownReadRootPath.Create( DesPcID, FilePath );
Result := MyShareDownReadRootPath.get;
MyShareDownReadRootPath.Free;
end;
class function MyShareDownInfoReadUtil.ReadSavePath(DesPcID,
FullPath: string): string;
var
MyShareDownReadSavePath : TShareDownReadSavePath;
begin
MyShareDownReadSavePath := TShareDownReadSavePath.Create( DesPcID, FullPath );
Result := MyShareDownReadSavePath.get;
MyShareDownReadSavePath.Free;
end;
{ TMyShareDownReadConflictPath }
function TShareDownReadConflictPath.get: TStringList;
var
i : Integer;
SelectPath : string;
begin
Result := TStringList.Create;
for i := 0 to ShareDownList.Count - 1 do
begin
if ShareDownList[i].DesPcID <> DesPcID then
Continue;
SelectPath := ShareDownList[i].FullPath;
if MyMatchMask.CheckEqualsOrChild( SelectPath, FullPath ) or
MyMatchMask.CheckChild( FullPath, SelectPath )
then
Result.Add( SelectPath );
end;
end;
{ TMyShareDownReadPcDownPath }
constructor TShareDownReadPcShareDown.Create(_PcID: string);
begin
inherited Create;
PcID := _PcID;
end;
function TShareDownReadPcShareDown.get: TStringList;
var
i : Integer;
begin
Result := TStringList.Create;
for i := 0 to ShareDownList.Count - 1 do
if ShareDownList[i].DesPcID = PcID then
Result.Add( ShareDownList[i].FullPath );
end;
{ TSharePathAccessInfo }
constructor TSharePathAccessInfo.Create;
begin
MySharePathInfo.EnterData;
SharePathHash := MySharePathInfo.SharePathHash;
end;
destructor TSharePathAccessInfo.Destroy;
begin
MySharePathInfo.LeaveData;
inherited;
end;
{ TSharePathItemAccessInfo }
constructor TSharePathItemAccessInfo.Create(_FullPath: string);
begin
inherited Create;
FullPath := _FullPath;
end;
function TSharePathItemAccessInfo.FindSharePathInfo: Boolean;
begin
Result := SharePathHash.ContainsKey( FullPath );
if Result then
SharePathInfo := SharePathHash[ FullPath ];
end;
{ TSharePathReadPathList }
function TSharePathReadPathList.get: TStringList;
var
p : TSharePathPair;
begin
Result := TStringList.Create;
for p in SharePathHash do
Result.Add( p.Value.FullPath );
end;
{ TShareDownAccessInfo }
constructor TShareDownAccessInfo.Create;
begin
MyShareDownInfo.EnterData;
ShareDownList := MyShareDownInfo.ShareDownList;
ShareDownDisableList := MyShareDownInfo.ShareDownDisableList;
end;
destructor TShareDownAccessInfo.Destroy;
begin
MyShareDownInfo.LeaveData;
inherited;
end;
{ TShareDownItemAccessInfo }
constructor TShareDownItemAccessInfo.Create(_DesPcID, _FullPath: string);
begin
inherited Create;
DesPcID := _DesPcID;
FullPath := _FullPath;
end;
function TShareDownItemAccessInfo.FindShareDownInfo: Boolean;
var
i : Integer;
begin
Result := False;
for i := 0 to ShareDownList.Count - 1 do
if ( ShareDownList[i].DesPcID = DesPcID ) and
( ShareDownList[i].FullPath = FullPath )
then
begin
ShareDownInfo := ShareDownList[i];
ShareDownIndex := i;
Result := True;
Break;
end;
end;
{ TShareDownDisableAccessInfo }
constructor TShareDownDisableAccessInfo.Create(_DesPcID, _FilePath: string);
begin
inherited Create;
DesPcID := _DesPcID;
FilePath := _FilePath;
end;
function TShareDownDisableAccessInfo.FindShareDownDisable: Boolean;
var
i : Integer;
begin
Result := False;
for i := 0 to ShareDownDisableList.Count - 1 do
if ( ShareDownDisableList[i].DesPcID = DesPcID ) and
( ShareDownDisableList[i].FilePath = FilePath )
then
begin
ShareDownDisableIndex := i;
ShareDownDisableInfo := ShareDownDisableList[i];
Result := True;
Break;
end;
end;
end.
|
unit unitUltimateSplash;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, pngimage, StdCtrls, ComCtrls;
type
TfrmUltimateSplash = class(TForm)
Image1: TImage;
ProgressBar1: TProgressBar;
Timer1: TTimer;
Label1: TLabel;
Label3: TLabel;
procedure Timer1Timer(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
progresValue : integer;
procedure updateProgress(aStatusCaption : String; currentProcess, totalProcess : Integer);
end;
var
frmUltimateSplash: TfrmUltimateSplash;
implementation
uses Unit1, uFadeForm;
{$R *.dfm}
{ TfrmUltimateSplash }
{ TfrmUltimateSplash }
procedure TfrmUltimateSplash.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if frmFadeForm <> nil then
frmFadeForm.Close;
MainForm.Enabled := true;
end;
procedure TfrmUltimateSplash.Timer1Timer(Sender: TObject);
begin
ProgressBar1.StepIt;
end;
procedure TfrmUltimateSplash.updateProgress(aStatusCaption: String;
currentProcess, totalProcess: Integer);
Var
valueCaption : Integer;
begin
//Description label - describes the current task being performed
label1.Caption := aStatusCaption;
label1.Repaint;
//Work out percent complete
valueCaption := round((currentProcess / totalProcess) * 100);
//update percentage label
label3.Caption := inttostr(valueCaption) + '%';
end;
end.
|
unit F08;
interface
uses typelist,F13;
procedure lihat_laporan (var Buku_Hilang:List_Buku_Hilang; var Buku:List_Buku);
{ Prosedur ini mencetak buku-buku apa saja yang pernah dilaporkan
sebagai buku hilang yang tersimpan di array buku hilang }
implementation
procedure lihat_laporan (var Buku_Hilang:List_Buku_Hilang; var Buku:List_Buku);
{ Prosedur ini mencetak buku-buku apa saja yang pernah dilaporkan
sebagai buku hilang yang tersimpan di array buku hilang }
// KAMUS LOKAL
var
i,j,id:integer;
judul:string;
// ALGORITMA
begin
// input dari user
writeln('Buku yang hilang :');
for i:=1 to Buku_Hilang.Neff do
begin
for j:=1 to Buku.Neff do
// Menggunakan 2 looping agar array List Buku Hilang dan List Buku dapat disearch
// untuk mencari judul buku dari array List Buku, karena tidak ada judul di array List Buku Hilang
begin
if Buku_Hilang.listBuku_Hilang[i].ID_Buku_Hilang = Buku.listbuku[j].ID_Buku then
begin
judul:=Buku.listbuku[j].Judul_Buku;
id:=Buku_Hilang.listBuku_Hilang[i].ID_Buku_Hilang;
// Mengeluarkan ID, Judul, serta tanggal pelaporan buku-buku yang hilang
writeln(id,' | ',judul,' | ',Buku_Hilang.listBuku_Hilang[i].Tanggal_Laporan.hari,'/',Buku_Hilang.listBuku_Hilang[i].Tanggal_Laporan.bulan,'/',Buku_Hilang.listBuku_Hilang[i].Tanggal_Laporan.tahun);
end; // else do nothing
end;
end;
end;
end. |
unit ClientCommon;
interface
uses Math, SysUtils, ActnList, Windows, Variants;
type
PHierarchyItemRecord = ^THierarchyItemRecord;
THierarchyItemRecord = record
ID: word;
MainID: word;
end;
THierarchyDictRecord = record
//имя хранимой процедуры для загрузки справочника
sDictProc: shortstring;
//имя редактируемой таблицы - справочника
sDictTable: shortstring;
//Название атрибута (ID элемента справочника)
sItemIDAttr: shortstring;
//Порядковый номер атрибута (ID элемента справочника) в _процедуре_
iItemIDAttrID: smallint;
//Название атрибута (Полное имя элемента справочника)
sItemFullNameAttr: shortstring;
//Порядковый номер атрибута (Полное имя элемента справочника) в _процедуре_
iItemFullNameAttrID: smallint;
//Название атрибута (Код элемента справочника)
sItemCodeAttr: shortstring;
//Порядковый номер атрибута (Код элемента справочника) в _процедуре_
iItemCodeAttrID: smallint;
//Название атрибута (Уровень элемента справочника)
sItemTypeAttr: shortstring;
//Порядковый номер атрибута (Уровень элемента справочника) в _процедуре_
iItemTypeAttrID: smallint;
//Название атрибута (ID родительского элемента справочника)
sMainItemIDAttr: shortstring;
//Порядковый номер атрибута (ID родительского элемента справочника) в _процедуре_
iMainItemIDAttrID: smallint;
end;
THierarchyDictType = (dtDistrict, dtPetrolRegion, dtTectonicStruct);
function VarFloatToStr(const Value: variant;
const Precision:byte = 3): shortstring;
function ReduceArrayDimCount(var vArray: variant;
const iColumnIndex: smallint = 0): variant;
function FloatToStrEx(F:real; Precision: byte = 3):string;
function DateToStrEx(Adtm: TDateTime): string;
function GetDictEx(const ATableName: shortstring;
const AColumnList: string = '*';
const AFilter: string = ''):variant;
function GetSingleValue(var AQueryResult: variant;
const AColumnIndex: smallint = 0; const ARowIndex: smallint = 0): variant;
function GetComputerAndUserName(var AComputerName, AUserName: string): smallint;
procedure FetchPriorities(const APriority: smallint; AActionList: TActionList);
function StrToFloatEx(S: string; Precision: smallint = 3): single;
function StrToFloatF(S: string; Precision: smallint = 3): single;
function StrToDateEx(const S:string): TDateTime;
function GetFirstSimilarName(var ADict: variant; const AName: shortstring;
const AColIndex: byte = 1): variant; overload;
function GetFirstSimilarName(var ADict: variant; const AName: shortstring;
var AResultID: integer; const AColIndex: byte = 1): variant; overload;
function GetObjectId(var ADict: variant;const AObjectName: shortstring;
const AColIndex: byte = 1): integer;
function GetObjectName(var ADict: variant; const AObjectId: single;
const AColIndex: byte = 1): variant;
function StrToIntEx(const S: string): Integer;
function GetSimilarNamesArray(var ADict: variant;const AName: shortstring;
const AColIndex: byte = 1): variant;
function ReplaceComma(const Source, CommaToReplace, ReplacingComma: shortstring): string;
function GetObject(var ADict: variant; const AObjectId: integer): variant;
var
IServer: OleVariant;//}ICommonServer;//Test;
//Тип сервера приложений
iServerType: byte = 0; //0 - основной сервер, 1 - тестовый
iClientAppType: integer;
iEmployeeID: integer;
sEmployeeName: WideString;
iGroupID: smallint;
vTableDict: Variant;
implementation
function VarFloatToStr(const Value: variant;
const Precision:byte=3): shortstring;
begin
case varType(Value) of
varSingle, varDouble, varCurrency:
Result:=FloatToStrEx(Value, Precision);
else
Result:='';
end;//case
end;
{
<SUB NAME='ReduceArrayDimCount'>
<PARAMETERS>
<PARAMETER NAME='vArray' DATATYPE='variant' TYPE='var'>
Число с плавающей запятой </PARAMETER>
<PARAMETER NAME='iColumnIndex' DATATYPE='smallint' TYPE='in'>
Желаемое количество знаков после запятой </PARAMETER>
<PARAMETER NAME='Возвращаемое значение' DATATYPE='variant' TYPE='out'>
Строка </PARAMETER>
</PARAMETERS>
Функция преобразовывает указанный столбец
двумерного массива вида [количество_столбцов, количество_строк]
в одномерный массив
</SUB>
}
function ReduceArrayDimCount(var vArray: variant;
const iColumnIndex: smallint=0): variant;
var i: word;
iHB: word;
begin
if not varIsEmpty(vArray) then
begin
if varArrayDimCount(vArray)=2 then
begin
iHB:= varArrayHighBound(vArray, 2);
Result:= varArrayCreate([0, iHB], varVariant);
for i:=0 to iHB do
Result[i]:= vArray[iColumnIndex, i];
end
else Result:= vArray;
end
else Result:=UnAssigned;
end;
{
<SUB NAME='FloatToStrEx'>
<PARAMETERS>
<PARAMETER NAME='F' DATATYPE='real' TYPE='in'>
Число с плавающей запятой </PARAMETER>
<PARAMETER NAME='Precision' DATATYPE='byte' TYPE='in'>
Желаемое количество знаков после запятой </PARAMETER>
<PARAMETER NAME='Возвращаемое значение' DATATYPE='string' TYPE='out'>
Строка </PARAMETER>
</PARAMETERS>
Функция проводит преобразование числа в строку,
сохраняя заданное количество знаков после запятой
</SUB>
}
function FloatToStrEx(F:real; Precision: byte=3):string;
var Temp: extended;
begin
try
Temp:=Power(10,Precision);
F:=Round(F*Temp)/Temp;
if F<>-1
then Result:=StringReplace(FloatToStr(F), ',', '.', [rfReplaceAll])
else Result:='NULL';
except on EConvertError
do Result:='NULL';
end;//try
end;
function DateToStrEx(Adtm: TDateTime): string;
begin
Result:= DateToStr(Adtm);
if pos ('01.01.', Result)=1 then Delete(Result, 1, 6);
if Adtm=0 then Result:='';
end;
function GetSingleValue(var AQueryResult: variant;
const AColumnIndex:smallint=0; const ARowIndex:smallint=0):variant;
begin
Result:=UnAssigned;
if (not varIsEmpty(AQueryResult))
and (not varIsNull(AQueryResult))
then
if (not varIsNull(AQueryResult[AColumnIndex,ARowIndex]))
and (not varIsEmpty(AQueryResult[AColumnIndex,ARowIndex]))
then Result:=AQueryResult[AColumnIndex,ARowIndex]
end;
function GetComputerAndUserName(var AComputerName, AUserName: string):smallint;
var pC, pU:pointer;
iC, iU:cardinal;
p:PWideChar;
begin
Result:=0;
try
iC:=MAX_COMPUTERNAME_LENGTH + 1;
iU:=MAX_COMPUTERNAME_LENGTH + 1;
GetMem(pC,iC);
GetMem(pU,iU);
try
if (Windows.GetComputerNameW(pC, iC))
and (Windows.GetUserNameW(pU, iU)) then
begin
p:=pC;
AComputerName:=p;
p:=pU;
AUserName:=p;
end;
finally
FreeMem(pC);
FreeMem(pU);
end;//try...finally
except on Exception do Result:=-1;
end;//try...except
end;
procedure FetchPriorities(const APriority: smallint; AActionList:TActionList);
var iRemnant: integer; // остаток
iPart: integer; // целая часть
iPriority: integer; // приоритет текущей операции
i,j: integer;
begin
iPart:=APriority;
i:=0;
repeat
iRemnant:= iPart mod 2;
iPart:=iPart div 2;
// это чтоб math не подключать
iPriority:=iRemnant*round(exp(i*ln(2)));
if (iPriority>0) then
for j:=0 to AActionList.ActionCount-1 do
begin
if (AActionList.Actions[j].Tag=iPriority) then
begin
(AActionList.Actions[j] as TAction).Visible:=true;
(AActionList.Actions[j] as TAction).Enabled:=true;
end;
end;
inc(i);
until (iPart=0);
end;
function StrToFloatF(S: string; Precision:smallint=3): single;
var Separator: string;
begin
if (DecimalSeparator=',') then
Separator:='.'
else
Separator:=',';
if (pos(Separator,S)>0) then
S:=StringReplace(S, Separator, DecimalSeparator, [rfReplaceAll]);
Result:=(Int(StrToFloat(S)*Power(10, Precision)))/Power(10, Precision);
end;
function StrToFloatEx(S: string; Precision:smallint=3): single;
var Separator: string;
begin
if (DecimalSeparator=',') then
Separator:='.'
else
Separator:=',';
if (pos(Separator,S)>0) then
S:=StringReplace(S, Separator, DecimalSeparator, [rfReplaceAll]);
try
Result:=(Int(StrToFloat(S)*Power(10, Precision)))/Power(10, Precision);
except on EConvertError do Result:=-1;
end;//try
end;
function StrToDateEx(const S:string):TDateTime;
begin
try
Result:=StrToDate(S);
except on EConvertError do
Result:=0;
end;//try
end;
//Функция заменяет в заданной строке
//заданный символ (или несколько) CommaToReplace
//на другой заданный символ (или несколько) ReplacingComma
function ReplaceComma(const Source,CommaToReplace,ReplacingComma:shortstring):string;
var s:shortstring;
i:integer;
begin
s:=Source;
i:=Pos(CommaToReplace,s);
if i>0 then
begin
Delete(s,i,Length(CommaToReplace));
Insert(ReplacingComma,s,i);
end;
Result:=s;
end;
function StrToIntEx(const S:string):integer;
var E:integer;
begin
Val(S, Result, E);
if E<>0 then Result:=-1;
end;
function GetDictEx(const ATableName: shortstring;
const AColumnList: string = '*';
const AFilter: string = ''):variant;
begin
if IServer.SelectRows(ATableName, ' ' + AColumnList + ' ', AFilter, null) >= 0 then
Result:=IServer.QueryResult;
end;
function GetObjectId(var ADict:variant;const AObjectName:shortstring;
const AColIndex:byte=1):integer;
var i:integer;
begin
Result:=0;
if not varIsEmpty(ADict)then
case varArrayDimCount(ADict) of
2:begin
for i:=0 to varArrayHighBound(ADict,2) do
if AnsiUpperCase(Trim(ADict[AColIndex,i])) = AnsiUpperCase(Trim(AObjectName)) then
begin
Result:=ADict[0,i];
break;
end;
end;
1:begin
for i:=0 to varArrayHighBound(ADict,1) do
if AnsiUpperCase(Trim(ADict[i])) = AnsiUpperCase(Trim(AObjectName)) then
begin
Result:=ADict[i];
break;
end;
end;
end;//case
end;
function GetObjectName(var ADict:variant;const AObjectId:single;
const AColIndex:byte=1):variant;
var i:integer;
begin
try
Result:=Unassigned;//Null;
if not varIsEmpty(ADict)then
case varArrayDimCount(ADict) of
2:begin
for i:=0 to varArrayHighBound(ADict,2) do
if ADict[0,i]=AObjectId then
begin
Result:=ADict[AColIndex,i];
break;
end;
end;
1:begin
for i:=0 to varArrayHighBound(ADict,1) do
if ADict[i]=AObjectId then
begin
Result:=ADict[i];
break;
end;
end;
end;//case
except on Exception do Result:=Unassigned;
end;//try
end;
function GetFirstSimilarName(var ADict:variant; const AName:shortstring;
const AColIndex: byte = 1): variant;
var i:integer;
begin
Result:=ANSIUpperCase(AName);
if not varIsEmpty(ADict) then
if AColIndex <= varArrayHighBound(ADict, 1) then
for i:=0 to varArrayHighBound(ADict, 2) do
if pos(Result,ANSIUpperCase(ADict[AColIndex, i]))=1 then
begin
Result:=ADict[AColIndex,i];
break;
end;
end;
function GetFirstSimilarName(var ADict:variant; const AName:shortstring;
var AResultID: integer; const AColIndex: byte = 1): variant;
var i:integer;
begin
Result:=ANSIUpperCase(AName);
if not varIsEmpty(ADict) then
if AColIndex <= varArrayHighBound(ADict, 1) then
for i:=0 to varArrayHighBound(ADict, 2) do
if pos(Result,ANSIUpperCase(ADict[AColIndex, i]))=1 then
begin
Result:=ADict[AColIndex,i];
AResultID:= ADict[0, i];
break;
end;
end;
function GetSimilarNamesArray(var ADict:variant;const AName:shortstring;
const AColIndex:byte=1): variant;
var i,j,k:integer;
s:shortstring;
begin
k:=0;
for i:=0 to varArrayHighBound(ADict,2) do
begin
s:=ADict[AColIndex,i];
if AnsiUpperCase(Copy(s,1,Length(AName)))=AnsiUpperCase(AName)
then
// if pos(AName,)<>0 then
begin
if varIsEmpty(Result)then Result:=varArrayCreate([0,varArrayHighBound(ADict,1),0,0],varOleStr);
varArrayRedim(Result,k);
for j:=0 to varArrayHighBound(ADict,1)do
Result[j,k]:=ADict[j,i];
inc(k);
end;
end;
end;
function GetObject(var ADict: variant; const AObjectId:integer): variant;
var i,iHB,j: integer;
begin
iHB:=varArrayHighBound(ADict,1);
Result:=varArrayCreate([0,iHB],varVariant);
for i := 0 to varArrayHighBound(ADict,2) do
if ADict[0,i]=AObjectId then
begin
for j:=0 to iHB do
Result[j]:=ADict[j,i];
break;
end;
end;
end. |
Unit F07;
interface
uses F13, typelist;
procedure lapor_hilang (var Buku_Hilang:List_Buku_Hilang; username:string);
{ Prosedur yang menerima input dari user berupa id,
judul, dan tanggal laporan buku yang hilang,
kemudian menyimpannya ke array buku hilang }
implementation
procedure lapor_hilang (var Buku_Hilang:List_Buku_Hilang; username:string);
{ Prosedur yang menerima input dari user berupa id,
judul, dan tanggal laporan buku yang hilang,
kemudian menyimpannya ke array buku hilang }
// KAMUS LOKAL
var
id:integer;
judul:string;
tanggal_lapor:string;
tanggal1: tanggal;
// ALGORITMA
begin
// Input dari user
write('Masukkan id buku: ');
readln(id);
write('Masukkan judul buku: ');
readln(judul);
write('Masukkan tanggal pelaporan: ');
readln(tanggal_lapor);
// Memasukkan input dari user ke array buku hilang dengan index + 1
// diasumsikan ID, judul, dan format tanggal pelaporan valid
Buku_Hilang.Neff:=Buku_Hilang.Neff+1;
Buku_Hilang.listBuku_Hilang[Buku_Hilang.Neff].Username:=username;
Buku_Hilang.listBuku_Hilang[Buku_Hilang.Neff].ID_Buku_Hilang:=id;
loadTanggal(tanggal_lapor, tanggal1);
Buku_Hilang.listBuku_Hilang[Buku_Hilang.Neff].Tanggal_Laporan:=tanggal1;
end;
end.
|
uses crt;
type tdates=record
jour:1..31;
mois:1..12;
an:1900..2100;
end;
var date,aff:tdates;
mois:integer;
procedure date_to_day(var tdate:tdates);
begin
writeln('Entrer la date d''aujourd''hui: ');
repeat
write('Entrer le mois: ');
readln(tdate.mois);
mois:=tdate.mois;
until ((tdate.mois<=12) and (tdate.mois>=1));
write('Entrer le jour: ');
case mois of
1,3,5,7,8,10,12:
begin
repeat
readln(tdate.jour);
until ((tdate.jour<=31)and(tdate.jour>=1));
end;
4,6,9,11:
begin
repeat
readln(tdate.jour);
until ((tdate.jour<=30)and(tdate.jour>=1));
end;
2:
begin
repeat
readln(tdate.jour);
until ((tdate.jour<=29)and(tdate.jour>=1));
end;
end;
write('Entrer an: ');
repeat
readln(tdate.an);
until ((tdate.an<=2100)and(tdate.an>=1900));
end;
procedure affichage;
begin
write(date.jour,'/',date.mois,'/',date.an);
end;
{procedure tomorrow;
begin
if ((date.mois=2)and(date.jour=29)) then
begin
date.jour:=1;
date.mois:=3;
end
else if ((date.mois=12)and(date.jour=31)) then
begin
date.jour:=1;
date.mois:=1;
date.an:=date.an+1;
end
else
begin
mois:=date.mois;
case mois of
4,6,9,11:
begin
if date.jour=30 then
begin
date.jour:=1;
date.mois:=date.mois+1;
end
else date.jour:=date.jour+1;
end;
1,3,5,7,8,10,12:
begin
if date.jour=31 then
begin
date.jour:=date.jour+1;
date.mois:=date.mois+1;
end
else date.jour:=date.jour+1;
end;
end;
end;
end;} {
procedure signe;
begin
case mois of
end;
end; }
BEGIN
clrscr;
date_to_day(date);
write('La date d''aujourd''hui: ');
affichage;
writeln;
{tomorrow;
write('La date de demain: ');
affichage;}
readkey;
END. |
(********************)
(* *)
(* Calculs du CRC *)
(* *)
(********************)
Unit CRC;
Interface
Function UpdateCRC(crc:Word;data:Byte):Word;
Function CalcTable(data,genpoly,accum:Word):Word;
Procedure InitCRC;
Implementation
Var CRCtable : array[0..255] of Word;
(* MAJ du CRC *)
Function UpdateCRC(crc:Word;data:Byte):Word;
begin
UpDateCRC := (crc SHL 8) XOR ( CRCtable[ (crc SHR 8) XOR data] );
end;
(* calculate CRC table entry *)
Function CalcTable(data,genpoly,accum:Word):Word;
var i : Word;
begin
data := data SHL 8;
for i := 8 downto 1 do
begin
if ( (data XOR accum) AND $8000 <> 0 )
then accum := (accum SHL 1) XOR genpoly
else accum := accum SHL 1;
data := data SHL 1;
end;
CalcTable := accum;
end;
(* Init de la table CRC *)
Procedure InitCRC;
var i : Integer;
begin
for i := 0 to 255 do CRCtable[i] := CalcTable(i,$1021,0);
end;
End. |
unit XmlDSig;
interface
type
HCkPublicKey = Pointer;
HCkBinData = Pointer;
HCkXmlDSig = Pointer;
HCkXml = Pointer;
HCkString = Pointer;
HCkStringArray = Pointer;
HCkStringBuilder = Pointer;
HCkXmlCertVault = Pointer;
function CkXmlDSig_Create: HCkXmlDSig; stdcall;
procedure CkXmlDSig_Dispose(handle: HCkXmlDSig); stdcall;
procedure CkXmlDSig_getDebugLogFilePath(objHandle: HCkXmlDSig; outPropVal: HCkString); stdcall;
procedure CkXmlDSig_putDebugLogFilePath(objHandle: HCkXmlDSig; newPropVal: PWideChar); stdcall;
function CkXmlDSig__debugLogFilePath(objHandle: HCkXmlDSig): PWideChar; stdcall;
procedure CkXmlDSig_getLastErrorHtml(objHandle: HCkXmlDSig; outPropVal: HCkString); stdcall;
function CkXmlDSig__lastErrorHtml(objHandle: HCkXmlDSig): PWideChar; stdcall;
procedure CkXmlDSig_getLastErrorText(objHandle: HCkXmlDSig; outPropVal: HCkString); stdcall;
function CkXmlDSig__lastErrorText(objHandle: HCkXmlDSig): PWideChar; stdcall;
procedure CkXmlDSig_getLastErrorXml(objHandle: HCkXmlDSig; outPropVal: HCkString); stdcall;
function CkXmlDSig__lastErrorXml(objHandle: HCkXmlDSig): PWideChar; stdcall;
function CkXmlDSig_getLastMethodSuccess(objHandle: HCkXmlDSig): wordbool; stdcall;
procedure CkXmlDSig_putLastMethodSuccess(objHandle: HCkXmlDSig; newPropVal: wordbool); stdcall;
function CkXmlDSig_getNumReferences(objHandle: HCkXmlDSig): Integer; stdcall;
function CkXmlDSig_getNumSignatures(objHandle: HCkXmlDSig): Integer; stdcall;
function CkXmlDSig_getSelector(objHandle: HCkXmlDSig): Integer; stdcall;
procedure CkXmlDSig_putSelector(objHandle: HCkXmlDSig; newPropVal: Integer); stdcall;
function CkXmlDSig_getVerboseLogging(objHandle: HCkXmlDSig): wordbool; stdcall;
procedure CkXmlDSig_putVerboseLogging(objHandle: HCkXmlDSig; newPropVal: wordbool); stdcall;
procedure CkXmlDSig_getVersion(objHandle: HCkXmlDSig; outPropVal: HCkString); stdcall;
function CkXmlDSig__version(objHandle: HCkXmlDSig): PWideChar; stdcall;
function CkXmlDSig_getWithComments(objHandle: HCkXmlDSig): wordbool; stdcall;
procedure CkXmlDSig_putWithComments(objHandle: HCkXmlDSig; newPropVal: wordbool); stdcall;
function CkXmlDSig_CanonicalizeFragment(objHandle: HCkXmlDSig; xml: PWideChar; fragmentId: PWideChar; version: PWideChar; prefixList: PWideChar; withComments: wordbool; outStr: HCkString): wordbool; stdcall;
function CkXmlDSig__canonicalizeFragment(objHandle: HCkXmlDSig; xml: PWideChar; fragmentId: PWideChar; version: PWideChar; prefixList: PWideChar; withComments: wordbool): PWideChar; stdcall;
function CkXmlDSig_CanonicalizeXml(objHandle: HCkXmlDSig; xml: PWideChar; version: PWideChar; withComments: wordbool; outStr: HCkString): wordbool; stdcall;
function CkXmlDSig__canonicalizeXml(objHandle: HCkXmlDSig; xml: PWideChar; version: PWideChar; withComments: wordbool): PWideChar; stdcall;
function CkXmlDSig_GetCerts(objHandle: HCkXmlDSig; sa: HCkStringArray): wordbool; stdcall;
function CkXmlDSig_GetKeyInfo(objHandle: HCkXmlDSig): HCkXml; stdcall;
function CkXmlDSig_GetPublicKey(objHandle: HCkXmlDSig): HCkPublicKey; stdcall;
function CkXmlDSig_IsReferenceExternal(objHandle: HCkXmlDSig; index: Integer): wordbool; stdcall;
function CkXmlDSig_LoadSignature(objHandle: HCkXmlDSig; xmlSig: PWideChar): wordbool; stdcall;
function CkXmlDSig_LoadSignatureBd(objHandle: HCkXmlDSig; binData: HCkBinData): wordbool; stdcall;
function CkXmlDSig_LoadSignatureSb(objHandle: HCkXmlDSig; sbXmlSig: HCkStringBuilder): wordbool; stdcall;
function CkXmlDSig_ReferenceUri(objHandle: HCkXmlDSig; index: Integer; outStr: HCkString): wordbool; stdcall;
function CkXmlDSig__referenceUri(objHandle: HCkXmlDSig; index: Integer): PWideChar; stdcall;
function CkXmlDSig_SaveLastError(objHandle: HCkXmlDSig; path: PWideChar): wordbool; stdcall;
function CkXmlDSig_SetHmacKey(objHandle: HCkXmlDSig; key: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkXmlDSig_SetPublicKey(objHandle: HCkXmlDSig; pubKey: HCkPublicKey): wordbool; stdcall;
function CkXmlDSig_SetRefDataBd(objHandle: HCkXmlDSig; index: Integer; binData: HCkBinData): wordbool; stdcall;
function CkXmlDSig_SetRefDataFile(objHandle: HCkXmlDSig; index: Integer; path: PWideChar): wordbool; stdcall;
function CkXmlDSig_SetRefDataSb(objHandle: HCkXmlDSig; index: Integer; sb: HCkStringBuilder; charset: PWideChar): wordbool; stdcall;
function CkXmlDSig_UseCertVault(objHandle: HCkXmlDSig; certVault: HCkXmlCertVault): wordbool; stdcall;
function CkXmlDSig_VerifyReferenceDigest(objHandle: HCkXmlDSig; index: Integer): wordbool; stdcall;
function CkXmlDSig_VerifySignature(objHandle: HCkXmlDSig; verifyReferenceDigests: wordbool): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkXmlDSig_Create; external DLLName;
procedure CkXmlDSig_Dispose; external DLLName;
procedure CkXmlDSig_getDebugLogFilePath; external DLLName;
procedure CkXmlDSig_putDebugLogFilePath; external DLLName;
function CkXmlDSig__debugLogFilePath; external DLLName;
procedure CkXmlDSig_getLastErrorHtml; external DLLName;
function CkXmlDSig__lastErrorHtml; external DLLName;
procedure CkXmlDSig_getLastErrorText; external DLLName;
function CkXmlDSig__lastErrorText; external DLLName;
procedure CkXmlDSig_getLastErrorXml; external DLLName;
function CkXmlDSig__lastErrorXml; external DLLName;
function CkXmlDSig_getLastMethodSuccess; external DLLName;
procedure CkXmlDSig_putLastMethodSuccess; external DLLName;
function CkXmlDSig_getNumReferences; external DLLName;
function CkXmlDSig_getNumSignatures; external DLLName;
function CkXmlDSig_getSelector; external DLLName;
procedure CkXmlDSig_putSelector; external DLLName;
function CkXmlDSig_getVerboseLogging; external DLLName;
procedure CkXmlDSig_putVerboseLogging; external DLLName;
procedure CkXmlDSig_getVersion; external DLLName;
function CkXmlDSig__version; external DLLName;
function CkXmlDSig_getWithComments; external DLLName;
procedure CkXmlDSig_putWithComments; external DLLName;
function CkXmlDSig_CanonicalizeFragment; external DLLName;
function CkXmlDSig__canonicalizeFragment; external DLLName;
function CkXmlDSig_CanonicalizeXml; external DLLName;
function CkXmlDSig__canonicalizeXml; external DLLName;
function CkXmlDSig_GetCerts; external DLLName;
function CkXmlDSig_GetKeyInfo; external DLLName;
function CkXmlDSig_GetPublicKey; external DLLName;
function CkXmlDSig_IsReferenceExternal; external DLLName;
function CkXmlDSig_LoadSignature; external DLLName;
function CkXmlDSig_LoadSignatureBd; external DLLName;
function CkXmlDSig_LoadSignatureSb; external DLLName;
function CkXmlDSig_ReferenceUri; external DLLName;
function CkXmlDSig__referenceUri; external DLLName;
function CkXmlDSig_SaveLastError; external DLLName;
function CkXmlDSig_SetHmacKey; external DLLName;
function CkXmlDSig_SetPublicKey; external DLLName;
function CkXmlDSig_SetRefDataBd; external DLLName;
function CkXmlDSig_SetRefDataFile; external DLLName;
function CkXmlDSig_SetRefDataSb; external DLLName;
function CkXmlDSig_UseCertVault; external DLLName;
function CkXmlDSig_VerifyReferenceDigest; external DLLName;
function CkXmlDSig_VerifySignature; external DLLName;
end.
|
unit uthrImportarFinanceiroTFO;
interface
uses
System.Classes, VCL.Dialogs, Windows, VCL.Forms, System.SysUtils, clUtil,
clEntregador, clAgentes, clEntrega, Messages, Controls,
System.DateUtils;
type
TCSVFinanceiro = record
_codigoagenteTFO: String;
_nomeagenteTFO: String;
_identregador: String;
_nomeentregador: String;
_atribuicao: String;
_idcliente: String;
_nomecliente: String;
_pedido: String;
_nossonumero: String;
_cep: String;
_volume: String;
_pesoreal: String;
_pesopago: String;
_valorverba: String;
_advalorem: String;
_valorpago: String;
_situacao: String;
_tipopeso: String;
end;
thrImportarFinanceiroTFO = class(TThread)
private
{ Private declarations }
entregador: TEntregador;
entrega: TEntrega;
agentes: TAgente;
CSVFinanceiro: TCSVFinanceiro;
protected
procedure Execute; override;
procedure AtualizaLog;
procedure AtualizaProgress;
procedure TerminaProcesso;
function TrataLinha(sLinha: String): String;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure thrImportaBaixas.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ thrImportaBaixas }
uses ufrmImportarFinanceiro, uGlobais;
function thrImportarFinanceiroTFO.TrataLinha(sLinha: String): String;
var
iConta: Integer;
sLin: String;
bFlag: Boolean;
begin
if Pos('"', sLinha) = 0 then
begin
Result := sLinha;
Exit;
end;
iConta := 1;
bFlag := False;
sLin := '';
while sLinha[iConta] >= ' ' do
begin
if sLinha[iConta] = '"' then
begin
if bFlag then
bFlag := False
else
bFlag := True;
end;
if bFlag then
begin
if sLinha[iConta] = ';' then
sLin := sLin + ' '
else
sLin := sLin + sLinha[iConta];
end
else
sLin := sLin + sLinha[iConta];
Inc(iConta);
end;
Result := sLin;
end;
procedure thrImportarFinanceiroTFO.Execute;
var
ArquivoCSV: TextFile;
Contador, I, LinhasTotal, iVolumes, iRet, iAtraso, iCadastro: Integer;
Linha, campo, codigo, sDescricao, agente, sMess, sData: String;
dVerba: Double;
bFlagPrimeiro, bAtivo: Boolean;
d: Real;
// Lê Linha e Monta os valores
function MontaValor: String;
var
ValorMontado: String;
begin
ValorMontado := '';
Inc(I);
While Linha[I] >= ' ' do
begin
If Linha[I] = ';' then // vc pode usar qualquer delimitador ... eu
// estou usando o ";"
break;
ValorMontado := ValorMontado + Linha[I];
Inc(I);
end;
Result := ValorMontado;
end;
begin
entregador := TEntregador.Create;
entrega := TEntrega.Create;
agentes := TAgente.Create;
bFlagPrimeiro := False;
LinhasTotal := TUtil.NumeroDeLinhasTXT(frmImportarFinanceiro.sFile);
// Carregando o arquivo ...
AssignFile(ArquivoCSV, frmImportarFinanceiro.sFile);
try
Reset(ArquivoCSV);
Readln(ArquivoCSV, Linha);
sDescricao := Copy(Linha, 0, 18);
sData := Copy(Linha, 20, 10);
if sDescricao <> 'EXPRESSA DATA BASE' then
begin
MessageDlg('Arquivo informado não é de Entrada de Financeiro !',
mtWarning, [mbOK], 0);
Abort;
end;
Readln(ArquivoCSV, Linha);
Readln(ArquivoCSV, Linha);
Contador := 3;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, Linha);
Linha := TrataLinha(Linha);
with CSVFinanceiro do
begin
_codigoagenteTFO := MontaValor;
_nomeagenteTFO := MontaValor;
_identregador := MontaValor;
_nomeentregador := MontaValor;
_atribuicao := MontaValor;
_idcliente := MontaValor;
_nomecliente := MontaValor;
_pedido := MontaValor;
_nossonumero := MontaValor;
_cep := MontaValor;
_volume := MontaValor;
_pesoreal := MontaValor;
_pesopago := MontaValor;
_valorverba := MontaValor;
_advalorem := MontaValor;
_valorpago := MontaValor;
_situacao := MontaValor;
_tipopeso := MontaValor;
end;
if entrega.getObject(CSVFinanceiro._nossonumero, 'NOSSONUMERO') then
begin
if StrToInt(CSVFinanceiro._identregador) > 0 then
begin
if (entrega.entregador <> StrToInt(CSVFinanceiro._identregador)) then
begin
entrega.entregador := StrToInt(CSVFinanceiro._identregador);
end;
end;
if (not TUtil.Empty(CSVFinanceiro._atribuicao)) then
begin
entrega.Atribuicao := StrToDateTime(CSVFinanceiro._atribuicao);
end;
entrega.PesoReal := StrToFloat(CSVFinanceiro._pesoreal);
entrega.VerbaDistribuicao := StrToFloat(CSVFinanceiro._valorverba);
entrega.Advalorem := StrToFloat(CSVFinanceiro._advalorem);
entrega.ValorFranquia := StrToFloat(CSVFinanceiro._valorpago);
entrega.PesoCobrado := StrToFloat(CSVFinanceiro._pesopago);
entrega.TipoPeso := CSVFinanceiro._tipopeso;
entrega.DataCredito := StrToDate(sData);
entrega.Credito := 'S';
if (not entrega.Update()) then
begin
sMensagem := 'Erro ao salvar Financeiro do NN ' +
entrega.NossoNumero + ' !';
Synchronize(AtualizaLog);
end;
end
else
begin
if entregador.getObject(CSVFinanceiro._identregador, 'CODIGO') then
begin
entrega.agente := entregador.agente;
end;
entrega.entregador := StrToInt(CSVFinanceiro._identregador);
entrega.NossoNumero := CSVFinanceiro._nossonumero;
entrega.Cliente := StrToInt(CSVFinanceiro._idcliente);
entrega.NF := '0';
entrega.Consumidor := 'DADOS FINANCEIRO';
entrega.Endereco := '';
entrega.Complemento := '';
entrega.Bairro := '';
entrega.Cidade := '';
entrega.Cep := CSVFinanceiro._cep;
entrega.Telefone := '';
entrega.Volumes := StrToInt(CSVFinanceiro._volume);
entrega.Baixado := 'S';
entrega.Pago := 'S';
if (not TUtil.Empty(CSVFinanceiro._atribuicao)) then
begin
entrega.Atribuicao := StrToDateTime(CSVFinanceiro._atribuicao);
end;
entrega.Status := 0;
entrega.PesoReal := StrToFloat(CSVFinanceiro._pesoreal);
entrega.VerbaDistribuicao := StrToFloat(CSVFinanceiro._valorverba);
entrega.Advalorem := StrToFloat(CSVFinanceiro._advalorem);
entrega.ValorFranquia := StrToFloat(CSVFinanceiro._valorpago);
entrega.Fechado := 'S';
entrega.Extrato := '0';
entrega.VerbaEntregador := 0;
entrega.DiasAtraso := 0;
entrega.VolumesExtra := 0;
entrega.ValorExtra := 0;
entrega.PesoCobrado := StrToFloat(CSVFinanceiro._pesopago);
entrega.TipoPeso := CSVFinanceiro._tipopeso;
entrega.Recebido := 'S';
entrega.Ctrc := 0;
entrega.Manifesto := 0;
entrega.Rastreio := '';
entrega.Lote := 0;
entrega.Retorno := '';
entrega.DataCredito := StrToDate(sData);
entrega.Credito := 'S';
if (not entrega.Insert()) then
begin
sMensagem := 'Erro ao incluir Financeiro do NN ' +
entrega.NossoNumero + ' !';
Synchronize(AtualizaLog);
end;
sMensagem := 'NN ' + entrega.NossoNumero + ' incluido!';
Synchronize(AtualizaLog);
end;
I := 0;
bFlagPrimeiro := False;
iConta := Contador;
iTotal := LinhasTotal;
dPosicao := (iConta / iTotal) * 100;
Inc(Contador, 1);
if not(Self.Terminated) then
begin
Synchronize(AtualizaProgress);
end
else
begin
entregador.Free;
entrega.Free;
agentes.Free;
Abort;
end;
end;
finally
CloseFile(ArquivoCSV);
Application.MessageBox('Importação concluída!', 'Importação de Baixas',
MB_OK + MB_ICONINFORMATION);
sMensagem := 'Importação terminada em ' +
FormatDateTime('dd/mm/yyyy hh:mm:ss', Now);
Synchronize(AtualizaLog);
Synchronize(TerminaProcesso);
entregador.Free;
entrega.Free;
agentes.Free;
end;
end;
procedure thrImportarFinanceiroTFO.AtualizaLog;
begin
frmImportarFinanceiro.cxLog.Lines.Add(sMensagem);
frmImportarFinanceiro.cxLog.Refresh;
end;
procedure thrImportarFinanceiroTFO.AtualizaProgress;
begin
frmImportarFinanceiro.cxProgressBar1.Position := dPosicao;
frmImportarFinanceiro.cxProgressBar1.Properties.Text := 'Registro ' +
IntToStr(iConta) + ' de ' + IntToStr(iTotal);
frmImportarFinanceiro.cxProgressBar1.Refresh;
if not(frmImportarFinanceiro.actImportarImportar.Visible) then
begin
frmImportarFinanceiro.actImportarCancelar.Visible := True;
frmImportarFinanceiro.actImportarSair.Enabled := False;
frmImportarFinanceiro.actImportarImportar.Enabled := False;
end;
end;
procedure thrImportarFinanceiroTFO.TerminaProcesso;
begin
frmImportarFinanceiro.actImportarCancelar.Visible := False;
frmImportarFinanceiro.actImportarSair.Enabled := True;
frmImportarFinanceiro.actImportarImportar.Enabled := True;
frmImportarFinanceiro.cxProgressBar1.Properties.Text := '';
frmImportarFinanceiro.cxProgressBar1.Position := 0;
frmImportarFinanceiro.cxProgressBar1.Visible := False;
frmImportarFinanceiro.cxProgressBar1.Clear;
end;
end.
|
unit StringUtils;
interface
uses
System.Classes;
type
TStringUtils = class
public
class function StreamToString(AStream: TStream): string;
end;
implementation
class function TStringUtils.StreamToString(AStream: TStream): string;
var
S: TStringStream;
begin
S := TStringStream.Create;
try
S.LoadFromStream(AStream);
Result := S.DataString;
finally
S.Free;
end;
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.Scene3D.Renderer.Passes.WeightBlendedOrderIndependentTransparencyRenderPass;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
interface
uses SysUtils,
Classes,
Math,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Framework,
PasVulkan.Application,
PasVulkan.FrameGraph,
PasVulkan.Scene3D,
PasVulkan.Scene3D.Renderer.Globals,
PasVulkan.Scene3D.Renderer,
PasVulkan.Scene3D.Renderer.Instance;
type { TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass }
TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass=class(TpvFrameGraph.TRenderPass)
private
fOnSetRenderPassResourcesDone:boolean;
procedure OnSetRenderPassResources(const aCommandBuffer:TpvVulkanCommandBuffer;
const aPipelineLayout:TpvVulkanPipelineLayout;
const aRenderPassIndex:TpvSizeInt;
const aPreviousInFlightFrameIndex:TpvSizeInt;
const aInFlightFrameIndex:TpvSizeInt);
private
fVulkanRenderPass:TpvVulkanRenderPass;
fInstance:TpvScene3DRendererInstance;
fResourceCascadedShadowMap:TpvFrameGraph.TPass.TUsedImageResource;
fResourceSSAO:TpvFrameGraph.TPass.TUsedImageResource;
fResourceDepth:TpvFrameGraph.TPass.TUsedImageResource;
fResourceAccumulation:TpvFrameGraph.TPass.TUsedImageResource;
fResourceRevealage:TpvFrameGraph.TPass.TUsedImageResource;
fMeshVertexShaderModule:TpvVulkanShaderModule;
fMeshFragmentShaderModule:TpvVulkanShaderModule;
fMeshMaskedFragmentShaderModule:TpvVulkanShaderModule;
fGlobalVulkanDescriptorSetLayout:TpvVulkanDescriptorSetLayout;
fGlobalVulkanDescriptorPool:TpvVulkanDescriptorPool;
fGlobalVulkanDescriptorSets:array[0..MaxInFlightFrames-1] of TpvVulkanDescriptorSet;
fVulkanPipelineShaderStageMeshVertex:TpvVulkanPipelineShaderStage;
fVulkanPipelineShaderStageMeshFragment:TpvVulkanPipelineShaderStage;
fVulkanPipelineShaderStageMeshMaskedFragment:TpvVulkanPipelineShaderStage;
fVulkanGraphicsPipelines:array[TpvScene3D.TMaterial.TAlphaMode] of TpvScene3D.TGraphicsPipelines;
fVulkanPipelineLayout:TpvVulkanPipelineLayout;
fParticleVertexShaderModule:TpvVulkanShaderModule;
fParticleFragmentShaderModule:TpvVulkanShaderModule;
fVulkanPipelineShaderStageParticleVertex:TpvVulkanPipelineShaderStage;
fVulkanPipelineShaderStageParticleFragment:TpvVulkanPipelineShaderStage;
fVulkanParticleGraphicsPipeline:TpvVulkanGraphicsPipeline;
public
constructor Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance); reintroduce;
destructor Destroy; override;
procedure AcquirePersistentResources; override;
procedure ReleasePersistentResources; override;
procedure AcquireVolatileResources; override;
procedure ReleaseVolatileResources; override;
procedure Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt); override;
procedure Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt); override;
end;
implementation
{ TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass }
constructor TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance);
begin
inherited Create(aFrameGraph);
fInstance:=aInstance;
Name:='WeightBlendedOrderIndependentTransparencyRenderPass';
MultiviewMask:=fInstance.SurfaceMultiviewMask;
Queue:=aFrameGraph.UniversalQueue;
Size:=TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,
1.0,
1.0,
1.0,
fInstance.CountSurfaceViews);
fResourceCascadedShadowMap:=AddImageInput('resourcetype_cascadedshadowmap_data',
'resource_cascadedshadowmap_data_final',
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
[]
);
fResourceSSAO:=AddImageInput('resourcetype_ssao_final',
'resource_ssao_data_final',
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
[]
);
if fInstance.Renderer.SurfaceSampleCountFlagBits=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT) then begin
fResourceDepth:=AddImageDepthInput('resourcetype_depth',
'resource_depth_data',
VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,//VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
[TpvFrameGraph.TResourceTransition.TFlag.Attachment]
);
end else begin
fResourceDepth:=AddImageDepthInput('resourcetype_msaa_depth',
'resource_msaa_depth_data',
VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,//VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
[TpvFrameGraph.TResourceTransition.TFlag.Attachment]
);
end;
fResourceAccumulation:=AddImageOutput('resourcetype_wboit_accumulation',
'resource_weightblendedorderindependenttransparency_accumulation',
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
TpvFrameGraph.TLoadOp.Create(TpvFrameGraph.TLoadOp.TKind.Clear,
TpvVector4.InlineableCreate(0.0,0.0,0.0,0.0)),
[TpvFrameGraph.TResourceTransition.TFlag.Attachment]
);
fResourceRevealage:=AddImageOutput('resourcetype_wboit_revealage',
'resource_weightblendedorderindependenttransparency_revealage',
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
TpvFrameGraph.TLoadOp.Create(TpvFrameGraph.TLoadOp.TKind.Clear,
TpvVector4.InlineableCreate(1.0,1.0,1.0,1.0)),
[TpvFrameGraph.TResourceTransition.TFlag.Attachment]
);
end;
destructor TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.Destroy;
begin
inherited Destroy;
end;
procedure TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.AcquirePersistentResources;
var Stream:TStream;
MeshFragmentSpecializationConstants:TpvScene3DRendererInstance.TMeshFragmentSpecializationConstants;
begin
inherited AcquirePersistentResources;
MeshFragmentSpecializationConstants:=fInstance.MeshFragmentSpecializationConstants;
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('mesh_vert.spv');
try
fMeshVertexShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream);
finally
Stream.Free;
end;
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('mesh_'+fInstance.Renderer.MeshFragTypeName+'_shading_'+fInstance.Renderer.MeshFragShadowTypeName+'_wboit_frag.spv');
try
fMeshFragmentShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream);
finally
Stream.Free;
end;
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('mesh_'+fInstance.Renderer.MeshFragTypeName+'_shading_'+fInstance.Renderer.MeshFragShadowTypeName+'_wboit_alphatest_frag.spv');
try
fMeshMaskedFragmentShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream);
finally
Stream.Free;
end;
fVulkanPipelineShaderStageMeshVertex:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_VERTEX_BIT,fMeshVertexShaderModule,'main');
fVulkanPipelineShaderStageMeshFragment:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fMeshFragmentShaderModule,'main');
MeshFragmentSpecializationConstants.SetPipelineShaderStage(fVulkanPipelineShaderStageMeshFragment);
fVulkanPipelineShaderStageMeshMaskedFragment:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fMeshMaskedFragmentShaderModule,'main');
MeshFragmentSpecializationConstants.SetPipelineShaderStage(fVulkanPipelineShaderStageMeshMaskedFragment);
/// --
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('particle_vert.spv');
try
fParticleVertexShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream);
//fFrameGraph.VulkanDevice.DebugMarker.SetObjectName(fParticleVertexShaderModule.Handle,TVkDebugReportObjectTypeEXT.VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,'fParticleVertexShaderModule');
finally
Stream.Free;
end;
Stream:=pvScene3DShaderVirtualFileSystem.GetFile('particle_wboit_frag.spv');
try
fParticleFragmentShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream);
//fFrameGraph.VulkanDevice.DebugMarker.SetObjectName(fParticleFragmentShaderModule.Handle,TVkDebugReportObjectTypeEXT.VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,'fParticleFragmentShaderModule');
finally
Stream.Free;
end;
fVulkanPipelineShaderStageParticleVertex:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_VERTEX_BIT,fParticleVertexShaderModule,'main');
fVulkanPipelineShaderStageParticleFragment:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fParticleFragmentShaderModule,'main');
//ParticleFragmentSpecializationConstants.SetPipelineShaderStage(fVulkanPipelineShaderStageParticleFragment);
end;
procedure TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.ReleasePersistentResources;
begin
FreeAndNil(fVulkanPipelineShaderStageMeshVertex);
FreeAndNil(fVulkanPipelineShaderStageMeshFragment);
FreeAndNil(fVulkanPipelineShaderStageMeshMaskedFragment);
FreeAndNil(fMeshVertexShaderModule);
FreeAndNil(fMeshFragmentShaderModule);
FreeAndNil(fMeshMaskedFragmentShaderModule);
FreeAndNil(fVulkanPipelineShaderStageParticleVertex);
FreeAndNil(fVulkanPipelineShaderStageParticleFragment);
FreeAndNil(fParticleVertexShaderModule);
FreeAndNil(fParticleFragmentShaderModule);
inherited ReleasePersistentResources;
end;
procedure TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.AcquireVolatileResources;
var InFlightFrameIndex:TpvSizeInt;
AlphaMode:TpvScene3D.TMaterial.TAlphaMode;
PrimitiveTopology:TpvScene3D.TPrimitiveTopology;
FaceCullingMode:TpvScene3D.TFaceCullingMode;
VulkanGraphicsPipeline:TpvVulkanGraphicsPipeline;
begin
inherited AcquireVolatileResources;
fVulkanRenderPass:=VulkanRenderPass;
fGlobalVulkanDescriptorSetLayout:=TpvVulkanDescriptorSetLayout.Create(fInstance.Renderer.VulkanDevice);
fGlobalVulkanDescriptorSetLayout.AddBinding(0,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
3,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.AddBinding(1,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
3,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.AddBinding(2,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.AddBinding(3,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.AddBinding(4,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.AddBinding(5,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.AddBinding(6,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.AddBinding(7,
VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.AddBinding(8,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1,
TVkShaderStageFlags(VK_SHADER_STAGE_FRAGMENT_BIT),
[]);
fGlobalVulkanDescriptorSetLayout.Initialize;
fGlobalVulkanDescriptorPool:=TpvVulkanDescriptorPool.Create(fInstance.Renderer.VulkanDevice,TVkDescriptorPoolCreateFlags(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT),fInstance.Renderer.CountInFlightFrames);
fGlobalVulkanDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,9*fInstance.Renderer.CountInFlightFrames);
fGlobalVulkanDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,3*fInstance.Renderer.CountInFlightFrames);
fGlobalVulkanDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,2*fInstance.Renderer.CountInFlightFrames);
fGlobalVulkanDescriptorPool.Initialize;
for InFlightFrameIndex:=0 to FrameGraph.CountInFlightFrames-1 do begin
fGlobalVulkanDescriptorSets[InFlightFrameIndex]:=TpvVulkanDescriptorSet.Create(fGlobalVulkanDescriptorPool,
fGlobalVulkanDescriptorSetLayout);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(0,
0,
3,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER),
[fInstance.Renderer.GGXBRDF.DescriptorImageInfo,
fInstance.Renderer.CharlieBRDF.DescriptorImageInfo,
fInstance.Renderer.SheenEBRDF.DescriptorImageInfo],
[],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(1,
0,
3,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER),
[fInstance.Renderer.ImageBasedLightingEnvMapCubeMaps.GGXDescriptorImageInfo,
fInstance.Renderer.ImageBasedLightingEnvMapCubeMaps.CharlieDescriptorImageInfo,
fInstance.Renderer.ImageBasedLightingEnvMapCubeMaps.LambertianDescriptorImageInfo],
[],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(2,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER),
[],
[fInstance.CascadedShadowMapVulkanUniformBuffers[InFlightFrameIndex].DescriptorBufferInfo],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(3,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER),
[TVkDescriptorImageInfo.Create(fInstance.Renderer.ShadowMapSampler.Handle,
fResourceCascadedShadowMap.VulkanImageViews[InFlightFrameIndex].Handle,
fResourceCascadedShadowMap.ResourceTransition.Layout)],// TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))],
[],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(4,
0,
2,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER),
[TVkDescriptorImageInfo.Create(fInstance.Renderer.SSAOSampler.Handle,
fResourceSSAO.VulkanImageViews[InFlightFrameIndex].Handle,
fResourceSSAO.ResourceTransition.Layout), // TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))],
fInstance.SceneMipmappedArray2DImages[InFlightFrameIndex].ArrayDescriptorImageInfo],
[],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(5,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER),
[],
[fInstance.FrustumClusterGridGlobalsVulkanBuffers[InFlightFrameIndex].DescriptorBufferInfo],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(6,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER),
[],
[fInstance.FrustumClusterGridIndexListVulkanBuffers[InFlightFrameIndex].DescriptorBufferInfo],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(7,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER),
[],
[fInstance.FrustumClusterGridDataVulkanBuffers[InFlightFrameIndex].DescriptorBufferInfo],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].WriteToDescriptorSet(8,
0,
1,
TVkDescriptorType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER),
[],
[fInstance.ApproximationOrderIndependentTransparentUniformVulkanBuffer.DescriptorBufferInfo],
[],
false);
fGlobalVulkanDescriptorSets[InFlightFrameIndex].Flush;
end;
fVulkanPipelineLayout:=TpvVulkanPipelineLayout.Create(fInstance.Renderer.VulkanDevice);
fVulkanPipelineLayout.AddPushConstantRange(TVkShaderStageFlags(VK_SHADER_STAGE_VERTEX_BIT),0,SizeOf(TpvScene3D.TVertexStagePushConstants));
fVulkanPipelineLayout.AddDescriptorSetLayout(fInstance.Renderer.Scene3D.GlobalVulkanDescriptorSetLayout);
fVulkanPipelineLayout.AddDescriptorSetLayout(fGlobalVulkanDescriptorSetLayout);
fVulkanPipelineLayout.Initialize;
for AlphaMode:=Low(TpvScene3D.TMaterial.TAlphaMode) to High(TpvScene3D.TMaterial.TAlphaMode) do begin
for PrimitiveTopology:=Low(TpvScene3D.TPrimitiveTopology) to High(TpvScene3D.TPrimitiveTopology) do begin
for FaceCullingMode:=Low(TpvScene3D.TFaceCullingMode) to High(TpvScene3D.TFaceCullingMode) do begin
FreeAndNil(fVulkanGraphicsPipelines[AlphaMode,PrimitiveTopology,FaceCullingMode]);
end;
end;
end;
for AlphaMode:=Low(TpvScene3D.TMaterial.TAlphaMode) to High(TpvScene3D.TMaterial.TAlphaMode) do begin
if AlphaMode=TpvScene3D.TMaterial.TAlphaMode.Opaque then begin
continue;
end;
for PrimitiveTopology:=Low(TpvScene3D.TPrimitiveTopology) to High(TpvScene3D.TPrimitiveTopology) do begin
for FaceCullingMode:=Low(TpvScene3D.TFaceCullingMode) to High(TpvScene3D.TFaceCullingMode) do begin
VulkanGraphicsPipeline:=TpvVulkanGraphicsPipeline.Create(fInstance.Renderer.VulkanDevice,
fInstance.Renderer.VulkanPipelineCache,
0,
[],
fVulkanPipelineLayout,
fVulkanRenderPass,
VulkanRenderPassSubpassIndex,
nil,
0);
try
VulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageMeshVertex);
if AlphaMode=TpvScene3D.TMaterial.TAlphaMode.Mask then begin
VulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageMeshMaskedFragment);
end else begin
VulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageMeshFragment);
end;
VulkanGraphicsPipeline.InputAssemblyState.Topology:=TVkPrimitiveTopology(PrimitiveTopology);
VulkanGraphicsPipeline.InputAssemblyState.PrimitiveRestartEnable:=false;
fInstance.Renderer.Scene3D.InitializeGraphicsPipeline(VulkanGraphicsPipeline);
VulkanGraphicsPipeline.ViewPortState.AddViewPort(0.0,0.0,fInstance.Width,fInstance.Height,0.0,1.0);
VulkanGraphicsPipeline.ViewPortState.AddScissor(0,0,fInstance.Width,fInstance.Height);
VulkanGraphicsPipeline.RasterizationState.DepthClampEnable:=false;
VulkanGraphicsPipeline.RasterizationState.RasterizerDiscardEnable:=false;
VulkanGraphicsPipeline.RasterizationState.PolygonMode:=VK_POLYGON_MODE_FILL;
case FaceCullingMode of
TpvScene3D.TFaceCullingMode.Normal:begin
VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_BACK_BIT);
VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_COUNTER_CLOCKWISE;
end;
TpvScene3D.TFaceCullingMode.Inversed:begin
VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_BACK_BIT);
VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_CLOCKWISE;
end;
else begin
VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_NONE);
VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_COUNTER_CLOCKWISE;
end;
end;
VulkanGraphicsPipeline.RasterizationState.DepthBiasEnable:=false;
VulkanGraphicsPipeline.RasterizationState.DepthBiasConstantFactor:=0.0;
VulkanGraphicsPipeline.RasterizationState.DepthBiasClamp:=0.0;
VulkanGraphicsPipeline.RasterizationState.DepthBiasSlopeFactor:=0.0;
VulkanGraphicsPipeline.RasterizationState.LineWidth:=1.0;
VulkanGraphicsPipeline.MultisampleState.RasterizationSamples:=fInstance.Renderer.SurfaceSampleCountFlagBits;
if (AlphaMode=TpvScene3D.TMaterial.TAlphaMode.Mask) and (VulkanGraphicsPipeline.MultisampleState.RasterizationSamples<>VK_SAMPLE_COUNT_1_BIT) then begin
VulkanGraphicsPipeline.MultisampleState.SampleShadingEnable:=true;
VulkanGraphicsPipeline.MultisampleState.MinSampleShading:=1.0;
VulkanGraphicsPipeline.MultisampleState.CountSampleMasks:=0;
VulkanGraphicsPipeline.MultisampleState.AlphaToCoverageEnable:=true;
VulkanGraphicsPipeline.MultisampleState.AlphaToOneEnable:=false;
end else begin
VulkanGraphicsPipeline.MultisampleState.SampleShadingEnable:=false;
VulkanGraphicsPipeline.MultisampleState.MinSampleShading:=0.0;
VulkanGraphicsPipeline.MultisampleState.CountSampleMasks:=0;
VulkanGraphicsPipeline.MultisampleState.AlphaToCoverageEnable:=false;
VulkanGraphicsPipeline.MultisampleState.AlphaToOneEnable:=false;
end;
VulkanGraphicsPipeline.ColorBlendState.LogicOpEnable:=false;
VulkanGraphicsPipeline.ColorBlendState.LogicOp:=VK_LOGIC_OP_COPY;
VulkanGraphicsPipeline.ColorBlendState.BlendConstants[0]:=0.0;
VulkanGraphicsPipeline.ColorBlendState.BlendConstants[1]:=0.0;
VulkanGraphicsPipeline.ColorBlendState.BlendConstants[2]:=0.0;
VulkanGraphicsPipeline.ColorBlendState.BlendConstants[3]:=0.0;
VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(true,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ONE,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ONE,
VK_BLEND_OP_ADD,
TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT));
VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(true,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_OP_ADD,
TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT));
VulkanGraphicsPipeline.DepthStencilState.DepthTestEnable:=true;
VulkanGraphicsPipeline.DepthStencilState.DepthWriteEnable:=false;
if fInstance.ZFar<0.0 then begin
VulkanGraphicsPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_GREATER_OR_EQUAL;
end else begin
VulkanGraphicsPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_LESS_OR_EQUAL;
end;
VulkanGraphicsPipeline.DepthStencilState.DepthBoundsTestEnable:=false;
VulkanGraphicsPipeline.DepthStencilState.StencilTestEnable:=false;
VulkanGraphicsPipeline.Initialize;
VulkanGraphicsPipeline.FreeMemory;
finally
fVulkanGraphicsPipelines[AlphaMode,PrimitiveTopology,FaceCullingMode]:=VulkanGraphicsPipeline;
end;
end;
end;
end;
FreeAndNil(fVulkanParticleGraphicsPipeline);
VulkanGraphicsPipeline:=TpvVulkanGraphicsPipeline.Create(fInstance.Renderer.VulkanDevice,
fInstance.Renderer.VulkanPipelineCache,
0,
[],
fVulkanPipelineLayout,
fVulkanRenderPass,
VulkanRenderPassSubpassIndex,
nil,
0);
try
VulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageParticleVertex);
VulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageParticleFragment);
VulkanGraphicsPipeline.InputAssemblyState.Topology:=VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
VulkanGraphicsPipeline.InputAssemblyState.PrimitiveRestartEnable:=false;
fInstance.Renderer.Scene3D.InitializeParticleGraphicsPipeline(VulkanGraphicsPipeline);
VulkanGraphicsPipeline.ViewPortState.AddViewPort(0.0,0.0,fInstance.Width,fInstance.Height,0.0,1.0);
VulkanGraphicsPipeline.ViewPortState.AddScissor(0,0,fInstance.Width,fInstance.Height);
VulkanGraphicsPipeline.RasterizationState.DepthClampEnable:=false;
VulkanGraphicsPipeline.RasterizationState.RasterizerDiscardEnable:=false;
VulkanGraphicsPipeline.RasterizationState.PolygonMode:=VK_POLYGON_MODE_FILL;
{ VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_BACK_BIT);
VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_COUNTER_CLOCKWISE;}
VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_NONE);
VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_COUNTER_CLOCKWISE;
VulkanGraphicsPipeline.RasterizationState.DepthBiasEnable:=false;
VulkanGraphicsPipeline.RasterizationState.DepthBiasConstantFactor:=0.0;
VulkanGraphicsPipeline.RasterizationState.DepthBiasClamp:=0.0;
VulkanGraphicsPipeline.RasterizationState.DepthBiasSlopeFactor:=0.0;
VulkanGraphicsPipeline.RasterizationState.LineWidth:=1.0;
VulkanGraphicsPipeline.MultisampleState.RasterizationSamples:=fInstance.Renderer.SurfaceSampleCountFlagBits;
VulkanGraphicsPipeline.MultisampleState.SampleShadingEnable:=false;
VulkanGraphicsPipeline.MultisampleState.MinSampleShading:=0.0;
VulkanGraphicsPipeline.MultisampleState.CountSampleMasks:=0;
VulkanGraphicsPipeline.MultisampleState.AlphaToCoverageEnable:=false;
VulkanGraphicsPipeline.MultisampleState.AlphaToOneEnable:=false;
VulkanGraphicsPipeline.ColorBlendState.LogicOpEnable:=false;
VulkanGraphicsPipeline.ColorBlendState.LogicOp:=VK_LOGIC_OP_COPY;
VulkanGraphicsPipeline.ColorBlendState.BlendConstants[0]:=0.0;
VulkanGraphicsPipeline.ColorBlendState.BlendConstants[1]:=0.0;
VulkanGraphicsPipeline.ColorBlendState.BlendConstants[2]:=0.0;
VulkanGraphicsPipeline.ColorBlendState.BlendConstants[3]:=0.0;
VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(true,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ONE,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ONE,
VK_BLEND_FACTOR_ONE,
VK_BLEND_OP_ADD,
TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT));
VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(true,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_OP_ADD,
VK_BLEND_FACTOR_ZERO,
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_OP_ADD,
TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or
TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT));
VulkanGraphicsPipeline.DepthStencilState.DepthTestEnable:=true;
VulkanGraphicsPipeline.DepthStencilState.DepthWriteEnable:=false;
if fInstance.ZFar<0.0 then begin
VulkanGraphicsPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_GREATER_OR_EQUAL;
end else begin
VulkanGraphicsPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_LESS_OR_EQUAL;
end;
VulkanGraphicsPipeline.DepthStencilState.DepthBoundsTestEnable:=false;
VulkanGraphicsPipeline.DepthStencilState.StencilTestEnable:=false;
VulkanGraphicsPipeline.Initialize;
VulkanGraphicsPipeline.FreeMemory;
finally
fVulkanParticleGraphicsPipeline:=VulkanGraphicsPipeline;
end;
end;
procedure TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.ReleaseVolatileResources;
var Index:TpvSizeInt;
AlphaMode:TpvScene3D.TMaterial.TAlphaMode;
PrimitiveTopology:TpvScene3D.TPrimitiveTopology;
FaceCullingMode:TpvScene3D.TFaceCullingMode;
begin
FreeAndNil(fVulkanParticleGraphicsPipeline);
for AlphaMode:=Low(TpvScene3D.TMaterial.TAlphaMode) to High(TpvScene3D.TMaterial.TAlphaMode) do begin
for PrimitiveTopology:=Low(TpvScene3D.TPrimitiveTopology) to High(TpvScene3D.TPrimitiveTopology) do begin
for FaceCullingMode:=Low(TpvScene3D.TFaceCullingMode) to High(TpvScene3D.TFaceCullingMode) do begin
FreeAndNil(fVulkanGraphicsPipelines[AlphaMode,PrimitiveTopology,FaceCullingMode]);
end;
end;
end;
FreeAndNil(fVulkanPipelineLayout);
for Index:=0 to fInstance.Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fGlobalVulkanDescriptorSets[Index]);
end;
FreeAndNil(fGlobalVulkanDescriptorPool);
FreeAndNil(fGlobalVulkanDescriptorSetLayout);
inherited ReleaseVolatileResources;
end;
procedure TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt);
begin
inherited Update(aUpdateInFlightFrameIndex,aUpdateFrameIndex);
end;
procedure TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.OnSetRenderPassResources(const aCommandBuffer:TpvVulkanCommandBuffer;
const aPipelineLayout:TpvVulkanPipelineLayout;
const aRenderPassIndex:TpvSizeInt;
const aPreviousInFlightFrameIndex:TpvSizeInt;
const aInFlightFrameIndex:TpvSizeInt);
begin
if not fOnSetRenderPassResourcesDone then begin
fOnSetRenderPassResourcesDone:=true;
aCommandBuffer.CmdBindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS,
fVulkanPipelineLayout.Handle,
1,
1,
@fGlobalVulkanDescriptorSets[aInFlightFrameIndex].Handle,
0,
nil);
end;
end;
procedure TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.Execute(const aCommandBuffer:TpvVulkanCommandBuffer;
const aInFlightFrameIndex,aFrameIndex:TpvSizeInt);
var InFlightFrameState:TpvScene3DRendererInstance.PInFlightFrameState;
begin
inherited Execute(aCommandBuffer,aInFlightFrameIndex,aFrameIndex);
InFlightFrameState:=@fInstance.InFlightFrameStates^[aInFlightFrameIndex];
if InFlightFrameState^.Ready then begin
fOnSetRenderPassResourcesDone:=false;
if fInstance.Renderer.UseOITAlphaTest or fInstance.Renderer.Scene3D.HasTransmission then begin
fInstance.Renderer.Scene3D.Draw(fVulkanGraphicsPipelines[TpvScene3D.TMaterial.TAlphaMode.Mask],
-1,
aInFlightFrameIndex,
InFlightFrameState^.ViewRenderPassIndex,
InFlightFrameState^.FinalViewIndex,
InFlightFrameState^.CountFinalViews,
FrameGraph.DrawFrameIndex,
aCommandBuffer,
fVulkanPipelineLayout,
OnSetRenderPassResources,
[TpvScene3D.TMaterial.TAlphaMode.Mask],
@InFlightFrameState^.Jitter);
end;
fInstance.Renderer.Scene3D.Draw(fVulkanGraphicsPipelines[TpvScene3D.TMaterial.TAlphaMode.Blend],
-1,
aInFlightFrameIndex,
InFlightFrameState^.ViewRenderPassIndex,
InFlightFrameState^.FinalViewIndex,
InFlightFrameState^.CountFinalViews,
FrameGraph.DrawFrameIndex,
aCommandBuffer,
fVulkanPipelineLayout,
OnSetRenderPassResources,
[TpvScene3D.TMaterial.TAlphaMode.Blend],
@InFlightFrameState^.Jitter);
fInstance.Renderer.Scene3D.DrawParticles(fVulkanParticleGraphicsPipeline,
-1,
aInFlightFrameIndex,
InFlightFrameState^.ViewRenderPassIndex,
InFlightFrameState^.FinalViewIndex,
InFlightFrameState^.CountFinalViews,
FrameGraph.DrawFrameIndex,
aCommandBuffer,
fVulkanPipelineLayout,
OnSetRenderPassResources);
end;
end;
end.
|
unit IO;
interface
procedure ParseCMDLine(out FilenameInput: string; out FilenameOutput: string);
function ReadFileToString(const AFilename: string): string;
procedure WriteStringToFile(const AStr: string; const AFilename: string);
implementation
uses
Classes, SysUtils;
procedure ParseCMDLine(out FilenameInput: string; out FilenameOutput: string);
begin
if ParamCount <> 2 then
raise Exception.Create('Input parameters is bad');
FilenameInput := ParamStr(1);
FilenameOutput := ParamStr(2);
end;
function ReadFileToString(const AFilename: string): string;
var
fl: TStringList;
begin
fl := TStringList.Create;
try
fl.LoadFromFile(AFilename);
Result := fl.Text;
finally
fl.Free;
end;
end;
procedure WriteStringToFile(const AStr: string; const AFilename: string);
var
fl: TStringList;
begin
fl := TStringList.Create;
try
fl.Text := AStr;
fl.SaveToFile(AFilename);
finally
fl.Free;
end;
end;
end.
|
unit funciones;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Math;
const
pi = 3.14159265358979323846;
half_pi = 1.57079632679489661923;
rad = 3.14159265358979323846 / 180;{conversion factor for degrees
into radians}
function DistanciaEnMillas(lat1, lon1, lat2, lon2: double): double;
function Rumbo(lat1, lon1, lat2, lon2: double): double;
function VelocidadEnNudos(lat1, lon1, lat2, lon2, minutos: double): double;
procedure DecimalToFraction(Decimal: extended; var FractionNumerator: extended;
var FractionDenominator: extended; AccuracyFactor: extended);
function DecimalAFraccion(decimal: extended; max_digitos_denom: integer = 3): string;
function LetrasColumnasExcel(columna: integer): string;
function HoraOK(StrHora: string): boolean;
function GradoDecimalAGradoMinuto(d:double):double;
implementation
function atan2(y, x: extended): extended;
begin
if x = 0.0 then
begin
if y = 0.0 then
(* Error! Give error message and stop program *)
else if y > 0.0 then
atan2 := half_pi
else
atan2 := -half_pi;
end
else
begin
if x > 0.0 then
atan2 := arctan(y / x)
else if x < 0.0 then
begin
if y >= 0.0 then
atan2 := arctan(y / x) + pi
else
atan2 := arctan(y / x) - pi;
end;
end;
end; {atan2}
function Rumbo(lat1, lon1, lat2, lon2: double): double;
var
latInicio, longInicio, latFin, longFin, x, dist, angulo: double;
begin
lat1 := lat1 / 100; //se transforma GGMM,MM en GG,MMMM
lat1 := int(lat1) + ((lat1 - int(lat1)) * 100 / 60);
lon1 := lon1 / 100;
lon1 := int(lon1) + ((lon1 - int(lon1)) * 100 / 60);
lat2 := lat2 / 100;
lat2 := int(lat2) + ((lat2 - int(lat2)) * 100 / 60);
lon2 := lon2 / 100;
lon2 := int(lon2) + ((lon2 - int(lon2)) * 100 / 60);
//Asumimos que es el cuadrante SO, por lo tanto las posiciones se convierten a negarivo
//Para la distancia no importa, pero el rumbo daría al revés
latInicio:=degtorad(-1*lat1);
longInicio:=degtorad(-1*lon1);
latFin:=degtorad(-1*lat2);
longFin:=degtorad(-1*lon2);
x:=sin(latInicio)*sin(latFin)+cos(latInicio)*cos(latFin)*cos(longFin-longInicio);
dist:=60*arccos(x);
x:=(sin(latFin)-sin(latInicio)*cos(dist/60))/sin(dist/60)/cos(latInicio);
if x>=1 then
x:=1;
if x<=-1 then
x:=-1;
angulo:=arccos(x);
if sin(longFin-longInicio)<0 then
angulo:=2*PI-angulo;
dist:=dist*180/pi;
angulo:=round(angulo*180/pi);
if angulo=0 then
angulo:=360;
Result:=angulo;
end;
//La función CalcularMilla requiere en sus parámetros la notación
//de grados y minutos decimales, de la forma GGMM,MM
function DistanciaEnMillas(lat1, lon1, lat2, lon2: double): double;
var
radius, dlon, dlat, a, distance: extended;
begin
// 6378.137 es el radio de la tiera en km y 1.852 es la medida de una milla náutica en Km
//radius:=6378.137/1.852; {Earth equatorial radius in Km; as used in most GPS}
radius := 3443.918466522678;
//Se convierte todo todo a grados con decimales
lat1 := lat1 / 100; //se transforma GGMM,MM en GG,MMMM
lat1 := int(lat1) + ((lat1 - int(lat1)) * 100 / 60);
lon1 := lon1 / 100;
lon1 := int(lon1) + ((lon1 - int(lon1)) * 100 / 60);
lat2 := lat2 / 100;
lat2 := int(lat2) + ((lat2 - int(lat2)) * 100 / 60);
lon2 := lon2 / 100;
lon2 := int(lon2) + ((lon2 - int(lon2)) * 100 / 60);
{The Haversine formula}
dlon := (lon2 - lon1) * rad;
dlat := (lat2 - lat1) * rad;
a := sqr(sin(dlat / 2)) + cos(lat1 * rad) * cos(lat2 * rad) * sqr(sin(dlon / 2));
distance := radius * (2 * atan2(sqrt(a), sqrt(1 - a)));
Result := int(distance * 100) / 100;
end;
function VelocidadEnNudos(lat1, lon1, lat2, lon2, minutos: double): double;
var
dist_millas: double;
veloc_prom: double;
begin
if minutos > 0 then
begin
dist_millas := DistanciaEnMillas(lat1, lon1, lat2, lon2);
veloc_prom := dist_millas * 60 / minutos;
end
else
begin
veloc_prom := 0;
end;
Result := int(veloc_prom * 100) / 100;
end;
procedure DecimalToFraction(Decimal: extended; var FractionNumerator: extended;
var FractionDenominator: extended; AccuracyFactor: extended);
var
DecimalSign: extended;
Z: extended;
PreviousDenominator: extended;
ScratchValue: extended;
begin
if Decimal < 0.0 then
DecimalSign := -1.0
else
DecimalSign := 1.0;
Decimal := Abs(Decimal);
if Decimal = Int(Decimal) then { handles exact integers including 0 }
begin
FractionNumerator := Decimal * DecimalSign;
FractionDenominator := 1.0;
Exit;
end;
if (Decimal < 1.0E-19) then { X oe 0 already taken care of }
begin
FractionNumerator := DecimalSign;
FractionDenominator := 9999999999999999999.0;
Exit;
end;
if (Decimal > 1.0E+19) then
begin
FractionNumerator := 9999999999999999999.0 * DecimalSign;
FractionDenominator := 1.0;
Exit;
end;
Z := Decimal;
PreviousDenominator := 0.0;
FractionDenominator := 1.0;
repeat
Z := 1.0 / (Z - Int(Z));
ScratchValue := FractionDenominator;
FractionDenominator := FractionDenominator * Int(Z) + PreviousDenominator;
PreviousDenominator := ScratchValue;
FractionNumerator := Int(Decimal * FractionDenominator + 0.5)
{ Rounding Function }
until
(Abs((Decimal - (FractionNumerator / FractionDenominator))) < AccuracyFactor) or
(Z = Int(Z));
FractionNumerator := DecimalSign * FractionNumerator;
end; {procedure DecimalToFraction}
function DecimalAFraccion(decimal: extended; max_digitos_denom: integer = 3): string;
var
numerador, denominador, AccurracyFactor: extended;
begin
if (max_digitos_denom > 0) and (max_digitos_denom < 5) then
AccurracyFactor := 0.5 * power(10, -1 * max_digitos_denom);
DecimalToFraction(decimal, numerador, denominador, AccurracyFactor);
Result := FormatFloat('0', int(numerador)) + '/' + FormatFloat('0', int(denominador));
end;
function LetrasColumnasExcel(columna: integer): string;
var
l1, l2: string;
nl2, nl1: integer;
begin
if (columna < 1) or (columna > 702) then //Columna702="ZZ"
Result := ''
else
begin
nl1 := (columna - 1) div 26;
nl2 := columna - (26 * nl1);
if nl1 > 0 then
l1 := CHR(nl1 + 64)
else
l1 := '';
if nl2 > 0 then
l2 := CHR(nl2 + 64)
else
l2 := '';
Result := l1 + l2;
end;
end;
function HoraOK(StrHora: string): boolean;
var
hora: TDateTime;
begin
try
//Intento asignar el texto a una variable datetime. Si da error
//es porque el texto pasado no es una hora válida
hora := StrToTime(Strhora);
Result := True;
except
Result := False;
end;
end;
function GradoDecimalAGradoMinuto(d: double): double;
begin
//se transforma GG,MMMM en GGMM,MM
Result:= (int(d) + ((d - int(d)) * 60/100))*100;
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.command.deleter;
interface
uses
DB,
Rtti,
SysUtils,
ormbr.command.abstract,
dbebr.factory.interfaces,
dbcbr.rtti.helper;
type
TCommandDeleter = class(TDMLCommandAbstract)
public
constructor Create(AConnection: IDBConnection; ADriverName: TDriverName;
AObject: TObject); override;
function GenerateDelete(AObject: TObject): string;
end;
implementation
uses
ormbr.objects.helper,
ormbr.core.consts,
dbcbr.mapping.classes,
dbcbr.mapping.explorer;
{ TCommandDeleter }
constructor TCommandDeleter.Create(AConnection: IDBConnection;
ADriverName: TDriverName; AObject: TObject);
begin
inherited Create(AConnection, ADriverName, AObject);
end;
function TCommandDeleter.GenerateDelete(AObject: TObject): string;
var
LColumn: TColumnMapping;
LPrimaryKey: TPrimaryKeyColumnsMapping;
begin
FParams.Clear;
LPrimaryKey := TMappingExplorer
.GetMappingPrimaryKeyColumns(AObject.ClassType);
if LPrimaryKey = nil then
raise Exception.Create(cMESSAGEPKNOTFOUND);
for LColumn in LPrimaryKey.Columns do
begin
with FParams.Add as TParam do
begin
Name := LColumn.ColumnName;
DataType := LColumn.FieldType;
ParamType := ptUnknown;
Value := LColumn.ColumnProperty.GetNullableValue(AObject).AsVariant;
end;
end;
FResultCommand := FGeneratorCommand.GeneratorDelete(AObject, FParams);
Result := FResultCommand;
end;
end.
|
unit Helper.TDataSet;
interface
uses
Data.DB, System.SysUtils;
type
THelperDataSet = class helper for TDataSet
procedure WhileNotEof(proc: TProc);
procedure ForEachRow(proc: TProc);
function GetMaxIntegerValue(const fieldName: string): integer;
end;
implementation
function THelperDataSet.GetMaxIntegerValue(const fieldName: string): integer;
var
MaxValue: integer;
CurrentValue: integer;
begin
MaxValue := 0;
self.WhileNotEof(
procedure
begin
CurrentValue := self.FieldByName(fieldName).AsInteger;
if CurrentValue > MaxValue then
MaxValue := CurrentValue;
end);
Result := MaxValue;
end;
procedure THelperDataSet.WhileNotEof(proc: TProc);
var
Bookmark: TBookmark;
begin
Bookmark := self.GetBookmark;
// stworzenie zakładki
self.DisableControls;
try
self.First;
while not self.Eof do
begin
proc();
self.Next;
end;
finally
if self.BookmarkValid(Bookmark) then
self.GotoBookmark(Bookmark);
self.FreeBookmark(Bookmark);
self.EnableControls;
end;
end;
procedure THelperDataSet.ForEachRow(proc: TProc);
begin
WhileNotEof(proc);
end;
end.
|
unit aOPCSource;
interface
uses
System.Classes,
System.SysUtils,
IniFiles, SyncObjs,
uDataTypes,
aCustomOPCSource, uDCObjects, uUserMessage;
const
NameSpaceSection = 'NameSpace';
cMaxGroupForSingleUpdate = 5000;
сV30_ProtocolSet = [30, 31, 32];
type
EDataLinkError = class(Exception)
end;
EDataLinkNotFound = class(Exception)
end;
EThreadTerminated = class(Exception)
end;
ENotInhibitException = class(Exception)
end;
TaOPCUpdateMode = (umAuto, umPacket, umEach, umStreamPacket);
TMessageStrEvent = procedure(Sender: TObject; MessageStr: string) of object;
TCrackOPCLink = class(TaOPCDataLink)
end;
TaOPCSource = class;
TOPCUpdateThread = class(TThread)
private
ConnectionError: string;
// DataLinkGroupIndex: Integer;
ErrorCode: Integer;
ErrorString: string;
Moment: TDateTime;
// PhysID: string;
DataLinkGroup: TOPCDataLinkGroup;
GroupsForUpdate: TOPCDataLinkGroupList;
TimeOfLastBadConnect: TDateTime;
Value: string;
FOPCSource: TaOPCSource;
function GetOPCSource: TaOPCSource;
procedure UpdateStreamPacket_V30;
protected
procedure Execute; override;
public
ForceUpdate: Boolean;
Interval: Integer;
property OPCSource: TaOPCSource read GetOPCSource write FOPCSource;
procedure DoError;
procedure DoLog(aMsg: string);
// procedure SetActiveFalse;
// procedure SetActiveTrue;
// procedure UpdateData;
end;
TaOPCSource = class(TaCustomMultiOPCSource)
private
// FcsLockOPCSource:TCriticalSection;
FInterval: Integer;
FKeepConnection: Boolean;
FOnError: TMessageStrEvent;
FPassword: string;
FPermission: string;
FThread: TOPCUpdateThread;
FUser: string;
FDescription: string;
FOnRequest: TNotifyEvent;
FPacketUpdate: Boolean;
FUpdateMode: TaOPCUpdateMode;
FError: string;
FLogMsg: string;
FProtocolVersion: Integer;
FServerTimeDataLink: TaOPCDataLink;
FUserMessages: TUserMessageList;
FOnNewUserMessage: TNotifyEvent;
FAvtoShowMessage: Boolean;
FEnableMessage: Boolean;
// FLanguage: TUserLanguage;
FOnLog: TMessageStrEvent;
FLanguage: string;
procedure SetInterval(const Value: Integer);
procedure SetKeepConnection(const Value: Boolean);
procedure SetPassword(const Value: string);
procedure SetPermission(const Value: string);
procedure SetUser(const Value: string);
procedure SetConnected(const Value: Boolean);
procedure SetDescription(const Value: string);
procedure SetPacketUpdate(const Value: Boolean);
procedure SetServerTimeID(const Value: TPhysID);
function GetServerTimeID: TPhysID;
function GetServerTime: TDateTime;
procedure CalcPhysIDs;
procedure SetUpdateMode(const Value: TaOPCUpdateMode);
procedure SetProtocolVersion(const Value: Integer);
procedure SetAvtoShowMessage(const Value: Boolean);
procedure SetEnableMessage(const Value: Boolean);
protected
FStreamedConnected: Boolean;
FPhysIDs: string;
FPhysIDsChanged: Boolean;
FDataLinkGroupsChanged: Boolean;
// методы вызываемые из потока
procedure SyncDoActive;
procedure SyncDoNotActive;
procedure SyncConnect;
procedure SyncDisconnect;
procedure SyncChangeData;
procedure SyncUpdateDataLinks;
procedure SyncUpdateDataLinksData;
procedure SyncError;
procedure SyncRequest;
procedure SyncNewUserMessage;
procedure SyncLog;
//
procedure SetLanguage(const Value: string); virtual;
procedure DoUpdateThreadTerminate(Sender: TObject);
// procedure SetLanguage(const Value: TUserLanguage); virtual;
procedure CheckAnswer(aAnswer: string; aParamCount: Integer = 0); virtual;
procedure DoEndUpdate; override;
function GetNameSpaceFileName: string;
procedure Loaded; override;
procedure AddDataLink(DataLink: TaOPCDataLink; OldSource: TaCustomOPCSource = nil); override;
procedure RemoveDataLink(DataLink: TaOPCDataLink); override;
procedure Reconnect; virtual;
procedure DoConnect; virtual;
procedure DoDisconnect; virtual;
procedure Connect; virtual;
procedure Disconnect; virtual;
procedure CheckLock; virtual;
procedure Authorize(aUser: string; aPassword: string); virtual;
function GetConnected: Boolean; virtual; abstract;
procedure DoActive; override;
procedure DoError(ErrorStr: string);
procedure DoRequest;
procedure DoChangeData;
procedure DoNewUserMessage;
procedure DoUpdateDataLinksThreaded;
// обновить показания данными групп
procedure DoUpdateDataLinksData;
// отработать изменение данных (вызов обработчика изменения данных)
procedure DoUpdateDataLinks;
procedure DoNotActive; override;
function GetRemoteMachine: string; virtual;
procedure SetRemoteMachine(const Value: string); virtual;
function ExtractValue(var aValues: string; var aValue: string; var aErrorCode: Integer; var aErrorStr: string;
var aMoment: TDateTime): Boolean; virtual;
// function GetDS: Char; virtual; abstract;
// procedure LoadFS; virtual; abstract;
procedure ChangeData;
// procedure TryConnection; virtual; abstract;
procedure HistoryDateToClient(Stream: TStream; aDataKindSet: TDataKindSet); virtual;
procedure ValuesDateToClient(s: TStream);
public
FNameSpaceParentID: string;
FNameSpaceCash: TStrings;
FNameSpaceTimeStamp: TDateTime;
// function GetStringRes(idx: UInt32): String;
// function GetStringResStr(idx: string): String;
function IsReal: Boolean; override;
function ExtractParamsFromAnswer(aAnswer: string; aParamCount: Integer = 0): string;
function OPCStringToFloat(aStr: string): Double;
property Connected: Boolean read GetConnected write SetConnected default false;
property Error: string read FError;
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
function GetOPCName: string; override;
// function GetSensorProperties(id: string): TSensorProperties; virtual;
function GetSensorPropertiesEx(id: string): string; virtual;
function SetSensorPropertiesEx(id: string; sl: TStrings): string; virtual;
function GetGroupProperties(id: string): string; virtual;
function SetGroupProperties(id: string; sl: TStrings): string; virtual;
function GetDeviceProperties(id: string): string; virtual;
function SetDeviceProperties(id: string; sl: TStrings): string; virtual;
function GetPermissions(PhysIDs: string): string; virtual;
function GetValue(PhysID: string; aAsText: Boolean = False): string; virtual;
function SendModBus(aSystemType: integer; aRequest: string;
aRetByteCount: integer; aTimeOut: integer): string; virtual;
function SendModBusEx(aConnectionName: string; aRequest: string;
aRetByteCount: integer; aTimeOut: integer): string; virtual;
function GetSensorValue(PhysID: string; var ErrorCode: integer; var
ErrorString: string; var Moment: TDateTime): string; virtual;
function GetSensorsValues(PhysIDs: string): string; virtual;
procedure FillSensorsValuesStream(var aValuesStream: TMemoryStream); virtual;
function GetSensorValueOnMoment(PhysID: string; var Moment: TDateTime): string; virtual;
// возвращает показания датчиков на заданный момент времени Moment
// PhysIDs - список адресов через ; (точку с запятой)
// в ответе список показаний через ; (точку с запятой) в том же порядке
function GetSensorsValueOnMoment(PhysIDs: string; Moment: TDateTime): string; virtual;
function DelSensorValue(PhysID: string; Moment: TDateTime): string; virtual;
function SetSensorValue(PhysID, Value: string; Moment: TDateTime = 0): string; virtual;
procedure IncSensorValue(PhysID: string; aIncValue: Double; Moment: TDateTime); virtual;
function DelSensorValues(PhysID: string; Date1, Date2: TDateTime): string; virtual;
function RecalcSensor(PhysID: string; Date1, Date2: TDateTime; Script: string): string; virtual;
procedure InsertValues(PhysID: string; aBuffer: TSensorDataArr); virtual;
function ExecSql(Sql: string): string; virtual;
function LoadLookup(aName: string; var aTimeStamp: TDateTime): string; virtual;
procedure ForceUpdate;
// устаревшее
// function GetSensorJurnal(var Stream: TMemoryStream; SensorPath: string;
// Date1, Date2: TDateTime): string; virtual; abstract;
// устаревшее
// function GetStateJurnal(var Stream: TMemoryStream; SensorPath: string;
// Date1, Date2: TDateTime): string; virtual; abstract;
procedure FillHistory(Stream: TStream; SensorID: string;
Date1: TDateTime; Date2: TDateTime = 0;
aDataKindSet: TDataKindSet = [dkValue];
aCalcLeftVal: Boolean = True; aCalcRightVal: Boolean = True); virtual; abstract;
function Login(const aUserName, aPassword: string): Boolean; virtual; abstract;
// получить иерархию в виде списка строк
procedure FillNameSpaceStrings(aNameSpace: TStrings; aRootID: string = ''; aLevelCount: Integer = 0;
aKinds: TDCObjectKindSet = []); virtual; abstract;
function GetNameSpace(aObjectID: string = ''; aLevelCount: Integer = 0): boolean; virtual; abstract;
function GetUserPermission(const aUser, aPassword, aObject: String): String; virtual; abstract;
function GetUsers: string; virtual; abstract;
function GetClientList: string; virtual;
function GetThreadList: string; virtual; abstract;
function GetThreadProp(aThreadName: string): string; virtual; abstract;
function GetSensorsReadError: string; virtual; abstract;
function CalcVolume(aSensorID: Integer; aDate1, aDate2: TDateTime): extended; virtual; abstract;
function GetTimes(aSensorID: Integer; aDate1, aDate2: TDateTime): string; virtual; abstract;
function GetStatistic(aSensorID: string; aDate1, aDate2: TDateTime): string; virtual; abstract;
function SetThreadState(ConnectionName: string; NewState: Boolean): string; virtual; abstract;
function SetThreadLock(ConnectionName: string; NewState: Boolean): string; virtual; abstract;
procedure GetFile(aFileName: string; aStream: TStream); virtual; abstract;
procedure UploadFile(aFileName: string; aDestDir: string = ''); virtual;
procedure DownloadSetup(aFileName: string; aStream: TStream); virtual;
procedure LoadNameSpace(aCustomIniFile: TCustomIniFile; aSectionName: string = '');
procedure SaveNameSpace(aCustomIniFile: TCustomIniFile; aSectionName: string = '');
procedure CheckForNewNameSpace(aCustomIniFile: TCustomIniFile; aSectionName:
string = ''; aReconnect: boolean = false);
procedure ChangePassword(aUser, aOldPassword, aNewPassword: string); virtual; abstract;
procedure SendUserMessage(aUserGUID: string; aMessage: string); virtual; abstract;
function GetMessage: TUserMessage; virtual; abstract;
procedure DisconnectUser(aUserGUID: string); virtual; abstract;
property ServerTime: TDateTime read GetServerTime;
property UserMessages: TUserMessageList read FUserMessages;
procedure UpdateDescription; virtual;
published
// случается, когда прошел цикл опроса датчиков
property OnRequest: TNotifyEvent read FOnRequest write FOnRequest;
property OnError: TMessageStrEvent read FOnError write FOnError;
property OnLog: TMessageStrEvent read FOnLog write FOnLog;
property OnNewUserMessage: TNotifyEvent read FOnNewUserMessage write FOnNewUserMessage;
property RemoteMachine: string read GetRemoteMachine write SetRemoteMachine;
property User: string read FUser write SetUser;
property Password: string read FPassword write SetPassword;
property Permission: string read FPermission write SetPermission;
property PacketUpdate: Boolean read FPacketUpdate write SetPacketUpdate default True;
property UpdateMode: TaOPCUpdateMode read FUpdateMode write SetUpdateMode default umPacket;
property Description: string read FDescription write SetDescription;
property ProtocolVersion: Integer read FProtocolVersion write SetProtocolVersion default 1;
property Interval: Integer read FInterval write SetInterval default 1000;
property KeepConnection: Boolean read FKeepConnection write SetKeepConnection default false;
property ServerTimeID: TPhysID read GetServerTimeID write SetServerTimeID;
property EnableMessage: Boolean read FEnableMessage write SetEnableMessage default True;
property AutoShowMessage: Boolean read FAvtoShowMessage write SetAvtoShowMessage default True;
property Language: string read FLanguage write SetLanguage;
// property InhibitWNDProcException: Boolean read FInhibitWNDProcException write SetInhibitWNDProcException;
end;
implementation
uses
DC.StrUtils,
uCommonClass,
aOPCLog, uOPCCash,
// uUserMessageForm,
aOPCConsts;
{ TaOPCSource }
{
********************************* TaOPCSource **********************************
}
constructor TaOPCSource.Create(aOwner: TComponent);
begin
inherited;
// FcsLockOPCSource := TCriticalSection.Create;
FThread := nil;
FKeepConnection := false;
FInterval := 1000;
UpdateMode := umPacket;
FProtocolVersion := 1; // c 05.04.2007
// FProtocolVersion := 2; // c 16.07.2007
// FProtocolVersion := 3; // c 17.07.2007
FNameSpaceCash := TStringList.Create;
FNameSpaceTimeStamp := -1;
FUserMessages := TUserMessageList.Create;
FServerTimeDataLink := TaOPCDataLink.Create(nil);
FServerTimeDataLink.OPCSource := Self;
FAvtoShowMessage := True;
FEnableMessage := True;
// FLanguage := langRU;
end;
function TaOPCSource.DelSensorValue(PhysID: string; Moment: TDateTime): string;
begin
end;
function TaOPCSource.DelSensorValues(PhysID: string; Date1, Date2: TDateTime): string;
begin
end;
destructor TaOPCSource.Destroy;
begin
Active := false;
FreeAndNil(FNameSpaceCash);
FreeAndNil(FUserMessages);
FreeAndNil(FServerTimeDataLink);
inherited;
end;
procedure TaOPCSource.Connect;
begin
end;
procedure TaOPCSource.Disconnect;
begin
end;
procedure TaOPCSource.DoActive;
begin
// уже есть поток - выходим
if Assigned(FThread) then
Exit;
// создаем новый
FThread := TOPCUpdateThread.Create(True);
FThread.OnTerminate := DoUpdateThreadTerminate;
FThread.FreeOnTerminate := True;
FThread.Interval := Interval;
FThread.OPCSource := Self;
FThread.Start;
FActive := True;
FError := '';
inherited;
end;
procedure TaOPCSource.DoChangeData;
var
i: Integer;
// iGroup: integer;
CrackDataLink: TCrackOPCLink;
DataLinkGroup: TOPCDataLinkGroup;
tmpFloat: extended;
begin
DataLinkGroup := FThread.DataLinkGroup;
DataLinkGroup.NeedUpdate := false;
for i := 0 to DataLinkGroup.DataLinks.Count - 1 do
begin
CrackDataLink := TCrackOPCLink(DataLinkGroup.DataLinks.Items[i]);
CrackDataLink.FErrorCode := DataLinkGroup.ErrorCode;
CrackDataLink.FErrorString := DataLinkGroup.ErrorString;
CrackDataLink.FValue := DataLinkGroup.Value;
CrackDataLink.FOldValue := DataLinkGroup.OldValue;
TryStrToFloat(CrackDataLink.FValue, CrackDataLink.FFloatValue);
if OpcFS.DecimalSeparator <> FormatSettings.DecimalSeparator then
begin
tmpFloat := StrToFloatDef(CrackDataLink.FValue, UnUsedValue, OpcFS);
if tmpFloat <> UnUsedValue then
CrackDataLink.FValue := FloatToStr(tmpFloat);
end;
CrackDataLink.FMoment := DataLinkGroup.Moment;
CrackDataLink.ChangeData;
end;
end;
procedure TaOPCSource.DoConnect;
begin
end;
procedure TaOPCSource.DoDisconnect;
begin
end;
procedure TaOPCSource.DoUpdateDataLinks;
var
iLink, iGroup: Integer;
CrackDataLink: TCrackOPCLink;
aDataLinkGroup: TOPCDataLinkGroup;
begin
for iGroup := 0 to FThread.GroupsForUpdate.Count - 1 do
begin
aDataLinkGroup := FThread.GroupsForUpdate.Items[iGroup];
for iLink := 0 to aDataLinkGroup.DataLinks.Count - 1 do
begin
CrackDataLink := TCrackOPCLink(aDataLinkGroup.DataLinks.Items[iLink]);
CrackDataLink.ChangeData;
end;
end;
end;
procedure TaOPCSource.DoUpdateDataLinksThreaded;
var
i: Integer;
iGroup: Integer;
CrackDataLink: TCrackOPCLink;
DataLinkGroup: TOPCDataLinkGroup;
begin
for iGroup := 0 to FThread.GroupsForUpdate.Count - 1 do
begin
DataLinkGroup := FThread.GroupsForUpdate.Items[iGroup];
for i := 0 to DataLinkGroup.DataLinks.Count - 1 do
begin
CrackDataLink := TCrackOPCLink(DataLinkGroup.DataLinks.Items[i]);
CrackDataLink.DoChangeDataThreaded;
end;
end;
end;
procedure TaOPCSource.DownloadSetup(aFileName: string; aStream: TStream);
begin
end;
procedure TaOPCSource.DoUpdateThreadTerminate(Sender: TObject);
begin
FThread := nil;
end;
procedure TaOPCSource.DoEndUpdate;
begin
FDataLinkGroupsChanged := True;
inherited;
ForceUpdate;
end;
procedure TaOPCSource.DoError(ErrorStr: string);
begin
FError := ErrorStr;
if Assigned(FOnError) then
FOnError(Self, ErrorStr)
else
OPCLog.WriteToLog(ErrorStr);
end;
procedure TaOPCSource.DoNewUserMessage;
var
i: Integer;
begin
if AutoShowMessage then
begin
UserMessages.Lock;
try
for i := 0 to UserMessages.Count - 1 do
begin
{ TODO : Добавить вывод сообщения пользователю }
//ShowUserMessage(UserMessages[i], Self);
// ShowUserMessage(TUserMessage(aList[i]), Self);
UserMessages[i].Free;
end;
UserMessages.Clear;
finally
UserMessages.UnLock;
end;
end;
if Assigned(FOnNewUserMessage) then
OnNewUserMessage(Self);
end;
procedure TaOPCSource.DoNotActive;
begin
// останавливаем поток, если он есть
if Assigned(FThread) then
begin
FThread.Terminate;
while Assigned(FThread) do
CheckSynchronize(1000);
end;
FActive := False;
inherited;
// if FThread <> nil then
// begin
// FThread.FreeOnTerminate := True;
//
// FThread.Terminate;
// while Assigned(FThread) do
// CheckSynchronize(1000);
//
// CheckLock; // проверим, не выполняет ли наш OPCSource, что-то длительное
//
// FThread := nil;
// end;
//
// FActive := false;
// inherited;
end;
function TaOPCSource.ExecSql(Sql: string): string;
begin
end;
function TaOPCSource.ExtractParamsFromAnswer(aAnswer: string;
aParamCount: integer): string;
begin
CheckAnswer(aAnswer, aParamCount);
Result := Copy(aAnswer, Length(sOk) + 1, Length(aAnswer) - Length(sOk));
end;
function TaOPCSource.ExtractValue(var aValues: string;
var aValue: string; var aErrorCode: Integer; var aErrorStr: string; var aMoment: TDateTime): Boolean;
var
p: Integer;
begin
Result := True;
// Value
p := pos(';', aValues);
if p > 0 then
begin
aValue := Copy(aValues, 1, p - 1);
aValues := Copy(aValues, p + 1, Length(aValues));
end;
if ProtocolVersion > 0 then
begin
// ErrorCode
p := pos(';', aValues);
if p > 0 then
begin
aErrorCode := StrToIntDef(Copy(aValues, 1, p - 1), 0);
aValues := Copy(aValues, p + 1, Length(aValues));
end;
end;
// ErrorStr
p := pos(';', aValues);
if p > 0 then
begin
aErrorStr := Copy(aValues, 1, p - 1);
aValues := Copy(aValues, p + 1, Length(aValues));
if ProtocolVersion = 0 then
begin
if aErrorStr <> '' then
aErrorCode := 1
else
aErrorCode := 0;
end;
end;
// Moment
p := pos(';', aValues);
if p > 0 then
begin
aMoment := StrToDateTime(Copy(aValues, 1, p - 1), OpcFS);
aValues := Copy(aValues, p + 1, Length(aValues));
end
else
begin
aMoment := StrToDateTime(aValues, OpcFS);
aValues := '';
end;
end;
procedure TaOPCSource.FillSensorsValuesStream(var aValuesStream: TMemoryStream);
begin
end;
procedure TaOPCSource.ForceUpdate;
begin
if FThread <> nil then
FThread.ForceUpdate := True;
end;
function TaOPCSource.GetRemoteMachine: string;
begin
end;
function TaOPCSource.RecalcSensor(PhysID: string; Date1, Date2: TDateTime; Script: string): string;
begin
end;
procedure TaOPCSource.Reconnect;
begin
end;
procedure TaOPCSource.RemoveDataLink(DataLink: TaOPCDataLink);
var
DataLinkGroup: TOPCDataLinkGroup;
begin
DataLinkGroup := FindDataLinkGroup(DataLink);
if DataLinkGroup <> nil then
begin
DataLinkGroup.DataLinks.Remove(DataLink);
if DataLinkGroup.DataLinks.Count = 0 then
DataLinkGroup.Deleted := True;
end;
TCrackOPCLink(DataLink).FOPCSource := nil;
FDataLinkGroupsChanged := True;
end;
procedure TaOPCSource.SetInterval(const Value: Integer);
begin
if (FInterval <> Value) and (Value >= 10) then
begin
if (FThread <> nil) and Active then
FThread.Interval := Value;
FInterval := Value;
end;
end;
procedure TaOPCSource.SetKeepConnection(const Value: Boolean);
begin
if Value <> FKeepConnection then
begin
FKeepConnection := Value;
if not Value then
Disconnect;
end;
end;
procedure TaOPCSource.SetLanguage(const Value: string);
begin
FLanguage := Value;
end;
//procedure TaOPCSource.SetLanguage(const Value: TUserLanguage);
//begin
// FLanguage := Value;
//end;
procedure TaOPCSource.SetPassword(const Value: string);
begin
FPassword := Value;
end;
procedure TaOPCSource.SetPermission(const Value: string);
begin
FPermission := Value;
end;
procedure TaOPCSource.SetProtocolVersion(const Value: Integer);
begin
FProtocolVersion := Value;
end;
procedure TaOPCSource.SetRemoteMachine(const Value: string);
begin
end;
function TaOPCSource.SetSensorPropertiesEx(id: string; sl: TStrings): string;
begin
end;
function TaOPCSource.SetSensorValue(PhysID, Value: string; Moment: TDateTime = 0): string;
begin
end;
procedure TaOPCSource.SetServerTimeID(const Value: TPhysID);
begin
FServerTimeDataLink.PhysID := Value;
end;
procedure TaOPCSource.SetUser(const Value: string);
begin
FUser := Value;
end;
procedure TaOPCSource.SyncChangeData;
begin
DoChangeData;
end;
procedure TaOPCSource.UpdateDescription;
begin
end;
procedure TaOPCSource.SyncConnect;
begin
if Assigned(OnConnect) then
OnConnect(Self);
end;
procedure TaOPCSource.SyncDisconnect;
begin
if Assigned(OnDisconnect) then
OnDisconnect(Self);
end;
procedure TaOPCSource.SyncDoActive;
begin
FActive := True;
if Assigned(OnActivate) then
OnActivate(Self);
end;
procedure TaOPCSource.SyncDoNotActive;
begin
FActive := false;
if Assigned(OnDeactivate) then
OnDeactivate(Self);
end;
procedure TaOPCSource.SyncError;
begin
DoError(FThread.ConnectionError);
end;
procedure TaOPCSource.SyncLog;
begin
if Assigned(FOnLog) then
FOnLog(Self, FLogMsg);
end;
procedure TaOPCSource.SyncNewUserMessage;
begin
DoNewUserMessage;
end;
procedure TaOPCSource.SyncRequest;
begin
DoRequest;
end;
procedure TaOPCSource.SyncUpdateDataLinks;
begin
DoUpdateDataLinks;
end;
procedure TaOPCSource.SyncUpdateDataLinksData;
begin
DoUpdateDataLinksData;
end;
procedure TaOPCSource.UploadFile(aFileName: string; aDestDir: string = '');
begin
end;
procedure TaOPCSource.ValuesDateToClient(s: TStream);
var
d: TDateTime;
aRecSize: Int64;
begin
if ServerOffsetFromUTC = ClientOffsetFromUTC then
Exit;
// нужно перебрать все записи вида, и заменить в них даты на правильные
// ID: Word;
// TDCSensorDataRec_V30 = packed record
// Value: Double;
// ErrorCode: SmallInt;
// Time: TDateTime;
// end;
aRecSize := SizeOf(Word) + SizeOf(Double) + SizeOf(SmallInt);
if s.Size < aRecSize then
Exit;
s.Position := aRecSize;
while s.Position < s.Size do
begin
s.Read(d, SizeOf(d));
d := DateToClient(d);
s.Position := s.Position - SizeOf(d);
s.Write(d, SizeOf(d));
s.Position := s.Position + aRecSize;
end;
s.Position := 0;
end;
{ TOPCUpdateThread }
{
******************************* TOPCUpdateThread *******************************
}
procedure TOPCUpdateThread.DoError;
begin
OPCSource.DoError(ConnectionError);
end;
procedure TOPCUpdateThread.DoLog(aMsg: string);
begin
if not Assigned(FOPCSource) then
Exit;
FOPCSource.FLogMsg := aMsg;
Synchronize(FOPCSource.SyncLog);
//FOPCSource.SyncLog;
end;
procedure TOPCUpdateThread.Execute;
const
MinInterval = 100;
var
iGroup, j: Integer;
Values: string;
PhysIDs: string;
CurPhysID: string;
ValuesStream: TMemoryStream;
SensorData: TDCSensorDataRec;
aIndex_V30: Word;
aSensorData_V30: TDCSensorDataRec_V30;
aUserMessage: TUserMessage;
aDataRecived: Boolean;
aExceptionMessage: string;
function ExtractPhysID(var aPhysIDs: string): string;
var
p: Integer;
begin
p := pos(';', aPhysIDs);
if p > 0 then
begin
Result := Copy(aPhysIDs, 1, p - 1);
aPhysIDs := Copy(aPhysIDs, p + 1, Length(aPhysIDs));
end
else
begin
Result := aPhysIDs;
aPhysIDs := '';
end;
end;
procedure ExtractValue(var aValues: string;
var aValue: string; var aErrorCode: Integer; var aErrorStr: string;
var aMoment: TDateTime);
var
p: Integer;
begin
// Value
p := pos(';', aValues);
if p > 0 then
begin
aValue := Copy(aValues, 1, p - 1);
aValues := Copy(aValues, p + 1, Length(aValues));
end;
if OPCSource.ProtocolVersion > 0 then
begin
// ErrorCode
p := pos(';', aValues);
if p > 0 then
begin
aErrorCode := StrToIntDef(Copy(aValues, 1, p - 1), 0);
aValues := Copy(aValues, p + 1, Length(aValues));
end;
end;
// ErrorStr
p := pos(';', aValues);
if p > 0 then
begin
aErrorStr := Copy(aValues, 1, p - 1);
aValues := Copy(aValues, p + 1, Length(aValues));
if OPCSource.ProtocolVersion = 0 then
begin
if aErrorStr <> '' then
aErrorCode := 1
else
aErrorCode := 0;
end;
end;
// Moment
p := pos(';', aValues);
if p > 0 then
begin
aMoment := StrToDateTime(Copy(aValues, 1, p - 1), OPCSource.OpcFS);
aValues := Copy(aValues, p + 1, Length(aValues));
end
else
begin
aMoment := StrToDateTime(aValues, OPCSource.OpcFS);
aValues := '';
end;
end;
begin
TimeOfLastBadConnect := 0;
GroupsForUpdate := TOPCDataLinkGroupList.Create;
ValuesStream := TMemoryStream.Create;
// CoInitialize(nil);
try
while not Terminated do
begin
try
DoLog('begin');
if OPCSource.IsLocked then
begin
Sleep(MinInterval);
Continue;
end;
// обновление списка адресов запрашиваемых датчиков (пакетный режим) и
// очистка помеченных на удаление групп
if OPCSource.FDataLinkGroupsChanged then
OPCSource.CalcPhysIDs;
DoLog('Получение группы данных...');
{$REGION 'Получение группы данных'}
aExceptionMessage := '';
// режим получения данных по всем тегам в потоке
if OPCSource.UpdateMode = umStreamPacket then
begin
try
DoLog('FillSensorsValuesStream...');
OPCSource.FillSensorsValuesStream(ValuesStream);
DoLog('FillSensorsValuesStream OK');
if OPCSource.ProtocolVersion in сV30_ProtocolSet then
begin
if ValuesStream.Position < ValuesStream.Size then
ValuesStream.Read(aIndex_V30, SizeOf(aIndex_V30))
else
aIndex_V30 := $FFFF;
end;
except
on e: EThreadTerminated do
exit;
on e: Exception do
begin
aExceptionMessage := e.Message;
ValuesStream.Clear;
Synchronize(OPCSource.SyncError);
// SendMessage(OPCSource.FWindowHandle, am_Error, 0, 0);
end;
end;
end
else if OPCSource.PacketUpdate then
begin
try
PhysIDs := OPCSource.FPhysIDs;
if PhysIDs <> '' then
begin
if OPCSource.FPhysIDsChanged then
begin
OPCSource.FPhysIDsChanged := false;
DoLog('GetSensorsValues...');
Values := OPCSource.GetSensorsValues(PhysIDs);
DoLog('GetSensorsValues OK');
end
else
Values := OPCSource.GetSensorsValues('');
end
else
Values := '';
CurPhysID := ExtractPhysID(PhysIDs);
except
on e: EThreadTerminated do
exit;
on e: Exception do
begin
ConnectionError := e.Message;
aExceptionMessage := e.Message;
Values := '';
CurPhysID := ExtractPhysID(PhysIDs);
OPCSource.FPhysIDsChanged := True;
Synchronize(OPCSource.SyncError);
// SendMessage(OPCSource.FWindowHandle, am_Error, 0, 0);
end;
end;
end;
{$ENDREGION}
DoLog('Получение группы данных OK');
DoLog('цикл по группам...');
// цикл по группам
GroupsForUpdate.Clear;
for iGroup := 0 to OPCSource.FDataLinkGroups.Count - 1 do
begin
if Terminated then
exit;
DataLinkGroup := OPCSource.FDataLinkGroups.Items[iGroup];
if not OPCSource.FPacketUpdate and ((OPCSource.UpdateMode = umEach) or ((OPCSource.UpdateMode = umAuto))) then
{$REGION 'umEach'}
begin
if DataLinkGroup.PhysID = '' then
Continue;
Moment := 0;
try
// OPCSource.Connect;
try
Value := OPCSource.GetSensorValue(DataLinkGroup.PhysID, ErrorCode, ErrorString, Moment);
aDataRecived := True;
except
on e: EThreadTerminated do
exit;
on e: Exception do
begin
aExceptionMessage := e.Message;
Value := e.Message;
ErrorString := e.Message;
ErrorCode := 1;
end;
end;
except
on e: EThreadTerminated do
exit;
on e: Exception do
begin
ConnectionError := e.Message;
if Terminated then
exit
else
Synchronize(OPCSource.SyncError);
// SendMessage(OPCSource.FWindowHandle, am_Error, 0, 0);
// OPCSource.Disconnect;
for j := 0 to 10000 div MinInterval do
begin
if Terminated then
exit;
Sleep(MinInterval);
if Terminated then
exit;
end;
break;
end;
end;
end
{$ENDREGION}
else if OPCSource.UpdateMode = umStreamPacket then
{$REGION 'umStreamPacket'}
begin
if aExceptionMessage <> '' then
begin
aDataRecived := True;
Value := DataLinkGroup.Value;
TryStrToFloat(Value, DataLinkGroup.FloatValue);
ErrorCode := -1;
ErrorString := aExceptionMessage;
Moment := DataLinkGroup.Moment;
end
else
begin
if (OPCSource.ProtocolVersion in сV30_ProtocolSet) then
begin
aDataRecived := (iGroup = aIndex_V30);
if aDataRecived then
begin
ValuesStream.Read(aSensorData_V30, SizeOf(aSensorData_V30));
Value := FloatToStr(aSensorData_V30.Value);
ErrorCode := aSensorData_V30.ErrorCode;
if ErrorCode = 0 then
ErrorString := ''
else if Assigned(OPCSource.States) then
ErrorString := OPCSource.States.Items.Values[IntToStr(ErrorCode)];
Moment := aSensorData_V30.Time;
if ValuesStream.Position < ValuesStream.Size then
ValuesStream.Read(aIndex_V30, SizeOf(aIndex_V30));
end;
end
else
begin
if ValuesStream.Position >= ValuesStream.Size then
Continue;
ValuesStream.Read(SensorData, SizeOf(SensorData));
Value := FloatToStr(SensorData.Value);
ErrorCode := SensorData.ErrorCode;
if ErrorCode = 0 then
ErrorString := ''
else if Assigned(OPCSource.States) then
ErrorString := OPCSource.States.Items.Values[IntToStr(ErrorCode)];
Moment := SensorData.Time;
aDataRecived := True;
end;
end;
end
{$ENDREGION}
else
{$REGION 'umPacket'}
begin
DataLinkGroup := TOPCDataLinkGroup(OPCSource.FDataLinkGroups.Items[iGroup]);
if (DataLinkGroup.PhysID = CurPhysID) and (DataLinkGroup.PhysID <> '') then
begin
if (Values = '') and (aExceptionMessage = '') then
begin
OPCSource.FDataLinkGroupsChanged := True;
Continue;
end;
if aExceptionMessage = '' then
begin
aDataRecived := OPCSource.ExtractValue(Values, Value, ErrorCode, ErrorString, Moment);
CurPhysID := ExtractPhysID(PhysIDs);
end
else
begin
aDataRecived := True;
Value := DataLinkGroup.Value;
TryStrToFloat(Value, DataLinkGroup.FloatValue);
ErrorCode := -1;
ErrorString := aExceptionMessage;
Moment := DataLinkGroup.Moment;
CurPhysID := ExtractPhysID(PhysIDs);
end;
end
else
Continue;
end;
{$ENDREGION}
if DataLinkGroup.PhysID = '' then
Continue;
if DataLinkGroup.UpdateOnChangeMoment or DataLinkGroup.NeedUpdate
or
(
aDataRecived and
((DataLinkGroup.Value <> Value) or
(DataLinkGroup.ErrorCode <> ErrorCode) or
(DataLinkGroup.ErrorString <> ErrorString))
) then
begin
if Terminated then Exit;
if DataLinkGroup.UpdateOnChangeMoment then
Moment := OPCSource.ServerTime; // now;
if aDataRecived then
begin
if DataLinkGroup.Value <> Value then
DataLinkGroup.OldValue := DataLinkGroup.Value;
DataLinkGroup.Value := Value;
TryStrToFloat(Value, DataLinkGroup.FloatValue);
DataLinkGroup.ErrorString := ErrorString;
DataLinkGroup.ErrorCode := ErrorCode;
DataLinkGroup.Moment := Moment;
end
else if DataLinkGroup.UpdateOnChangeMoment then
DataLinkGroup.Moment := Moment;
if Terminated then Exit;
if (OPCSource.PacketUpdate and (OPCSource.UpdateMode = umAuto))
or (OPCSource.UpdateMode in [umPacket, umStreamPacket]) then
begin
GroupsForUpdate.Add(DataLinkGroup);
if GroupsForUpdate.Count > cMaxGroupForSingleUpdate then
begin
if Terminated then
exit;
Synchronize(OPCSource.SyncUpdateDataLinksData);
// SendMessage(OPCSource.FWindowHandle, am_UpdateDataLinksData, 0, 0);
OPCSource.DoUpdateDataLinksThreaded;
if Terminated then
exit;
Synchronize(OPCSource.SyncUpdateDataLinks);
// SendMessage(OPCSource.FWindowHandle, am_UpdateDataLinks, 0, 0);
GroupsForUpdate.Clear;
end;
end
else
Synchronize(OPCSource.SyncChangeData);
// SendMessage(OPCSource.FWindowHandle, am_ChangeData, 0, 0);
end;
end;
DoLog('цикл по группам OK');
DoLog('SyncUpdateDataLinks...');
if GroupsForUpdate.Count > 0 then
begin
if Terminated then
exit;
Synchronize(OPCSource.SyncUpdateDataLinksData);
// SendMessage(OPCSource.FWindowHandle, am_UpdateDataLinksData, 0, 0);
OPCSource.DoUpdateDataLinksThreaded;
if Terminated then
exit;
Synchronize(OPCSource.SyncUpdateDataLinks);
// SendMessage(OPCSource.FWindowHandle, am_UpdateDataLinks, 0, 0);
GroupsForUpdate.Clear;
end;
DoLog('SyncUpdateDataLinks OK');
// проверим наличие новых сообщений от других пользователей
DoLog('Check message...');
repeat
// читаем сообщение с сервера
aUserMessage := OPCSource.GetMessage;
if not Assigned(aUserMessage) then
break;
// добавляем его в список
OPCSource.UserMessages.AddMessage(aUserMessage);
// сообщим о новом сообщении пользователю
Synchronize(OPCSource.SyncNewUserMessage);
// SendMessage(OPCSource.FWindowHandle, am_NewUserMessage, 0, 0);
until Terminated or not(Assigned(aUserMessage));
DoLog('Check message OK');
// отчитаемся, что мы прошли цикл опроса
OPCSource.CurrentMoment := OPCSource.GetServerTime; // Now;
if Terminated then
exit;
DoLog('SyncRequest...');
Synchronize(OPCSource.SyncRequest);
DoLog('SyncRequest OK');
// SendMessage(OPCSource.FWindowHandle, am_Request, 0, 0);
DoLog('before wait');
for j := 0 to Interval div MinInterval do
begin
if Terminated then
exit;
if ForceUpdate then
begin
ForceUpdate := false;
break;
end;
Sleep(MinInterval);
if Terminated then
exit;
end;
DoLog('after wait');
DoLog('begin');
except
on e: EThreadTerminated do
exit;
on e: Exception do
OPCLog.WriteToLog('Ошибка в потоке : ' + e.Message);
end;
end;
finally
// CoUninitialize;
ValuesStream.Free;
GroupsForUpdate.Free;
// OutputDebugString('Выход из потока TOPCUpdateThread');
end;
end;
function TOPCUpdateThread.GetOPCSource: TaOPCSource;
begin
if Terminated then
raise
EThreadTerminated.Create('Попытка обращения к OPCSource во время остановки потока.');
Result := FOPCSource;
end;
procedure TOPCUpdateThread.UpdateStreamPacket_V30;
var
aStream: TMemoryStream;
aStreamSize: Int64;
aIndex: Word;
aRec: TDCSensorDataRec_V30;
begin
aStream := TMemoryStream.Create;
try
OPCSource.FillSensorsValuesStream(aStream);
aStreamSize := aStream.Size;
aStream.Position := 0;
while aStream.Position < aStreamSize do
begin
aStream.Read(aIndex, SizeOf(aIndex));
aStream.Read(aRec, SizeOf(aRec));
end;
finally
aStream.Free;
end;
end;
{
procedure TOPCUpdateThread.SetActiveFalse;
begin
OPCSource.fActive:=false;
if Assigned(OPCSource.OnDeactivate) then
OPCSource.OnDeactivate(OPCSource);
end;
}
{
procedure TOPCUpdateThread.SetActiveTrue;
begin
OPCSource.fActive:=true;
if Assigned(OPCSource.OnActivate) then
OPCSource.OnActivate(OPCSource);
end;
}
{
procedure TOPCUpdateThread.UpdateData;
begin
CrackDataLink:=TCrackOPCLink(OPCSource.FDataLinks.Items[DataLinkIndex]);
CrackDataLink.fErrorCode:=ErrorCode;
CrackDataLink.fErrorString:=ErrorString;
CrackDataLink.fValue:=Value;
CrackDataLink.fMoment:=Moment;
CrackDataLink.ChangeData;
end;
}
procedure TaOPCSource.SetAvtoShowMessage(const Value: Boolean);
begin
FAvtoShowMessage := Value;
end;
procedure TaOPCSource.SetConnected(const Value: Boolean);
begin
if (csReading in ComponentState) then
FStreamedConnected := Value
else
begin
FNameSpaceTimeStamp := 0;
if Value then
Connect
else
Disconnect;
end;
end;
function TaOPCSource.GetSensorValue(PhysID: string;
var ErrorCode: integer; var ErrorString: string;
var Moment: TDateTime): string;
begin
Result := 'GetSensorValue Реализация только у наследников';
end;
function TaOPCSource.GetValue(PhysID: string; aAsText: Boolean = False): string;
begin
end;
procedure TaOPCSource.HistoryDateToClient(Stream: TStream; aDataKindSet: TDataKindSet);
var
d: TDateTime;
aRecSize: Int64;
begin
if ServerOffsetFromUTC = ClientOffsetFromUTC then
Exit;
aRecSize := 0;
if dkValue in aDataKindSet then
aRecSize := aRecSize + SizeOf(Extended);
if dkState in aDataKindSet then
aRecSize := aRecSize + SizeOf(Extended);
if dkUser in aDataKindSet then
aRecSize := aRecSize + SizeOf(Extended);
Stream.Position := 0;
while Stream.Position < Stream.Size do
begin
Stream.Read(d, SizeOf(d));
d := DateToClient(d);
Stream.Position := Stream.Position - SizeOf(d);
Stream.Write(d, SizeOf(d));
Stream.Position := Stream.Position + aRecSize;
end;
Stream.Position := 0;
end;
procedure TaOPCSource.IncSensorValue(PhysID: string; aIncValue: Double; Moment: TDateTime);
begin
raise ENotImplemented.Create('IncSensorValue not Implemented');
end;
procedure TaOPCSource.InsertValues(PhysID: string; aBuffer: TSensorDataArr);
begin
end;
function TaOPCSource.IsReal: Boolean;
begin
Result := True;
end;
procedure TaOPCSource.SetDescription(const Value: string);
begin
FDescription := Value;
end;
function TaOPCSource.SetDeviceProperties(id: string; sl: TStrings): string;
begin
end;
procedure TaOPCSource.SetEnableMessage(const Value: Boolean);
begin
FEnableMessage := Value;
end;
function TaOPCSource.SetGroupProperties(id: string; sl: TStrings): string;
begin
end;
function TaOPCSource.GetClientList: string;
begin
Result := 'GetClientList Реализация только у наследников';
end;
function TaOPCSource.GetDeviceProperties(id: string): string;
begin
end;
function TaOPCSource.GetGroupProperties(id: string): string;
begin
end;
function TaOPCSource.GetNameSpaceFileName: string;
begin
Result := OPCCash.Path + '\' + GetOPCName + '_NameSpace.cash';
end;
function TaOPCSource.GetOPCName: string;
begin
Result := RemoteMachine;
end;
function TaOPCSource.GetPermissions(PhysIDs: string): string;
begin
end;
function TaOPCSource.GetSensorValueOnMoment(PhysID: string;
var Moment: TDateTime): string;
begin
Result := 'GetSensorValueOnMoment Реализация только у наследников';
end;
function TaOPCSource.GetServerTime: TDateTime;
begin
Result := 0;
if FServerTimeDataLink.PhysID <> '' then
Result := StrToFloatDef(FServerTimeDataLink.Value, 0);
if Result = 0 then
Result := Now;
end;
function TaOPCSource.GetServerTimeID: TPhysID;
begin
Result := FServerTimeDataLink.PhysID;
end;
//function TaOPCSource.GetStringRes(idx: UInt32): String;
//begin
// Result := uDCLang.GetStringRes(idx, Ord(Language));
//end;
//
//function TaOPCSource.GetStringResStr(idx: string): String;
//begin
// Result := uDCLang.GetStringResStr(idx, LanguageToStr(Language));
//end;
procedure TaOPCSource.DoRequest;
var
iGroup, iDataLink: Integer;
//DataLinkGroup: TOPCDataLinkGroup;
//DataLink: TaOPCDataLink;
begin
for iGroup := FDataLinkGroups.Count - 1 downto 0 do
begin
//DataLinkGroup := TOPCDataLinkGroup(FDataLinkGroups.Items[iGroup]);
if not Assigned(FDataLinkGroups[iGroup]) then
Continue;
for iDataLink := FDataLinkGroups[iGroup].DataLinks.Count - 1 downto 0 do
begin
//DataLink := TaOPCDataLink(DataLinkGroup.DataLinks[iDataLink]);
if Assigned(FDataLinkGroups[iGroup].DataLinks[iDataLink])
and Assigned(FDataLinkGroups[iGroup].DataLinks[iDataLink].OnRequest) then
FDataLinkGroups[iGroup].DataLinks[iDataLink].OnRequest(FDataLinkGroups[iGroup].DataLinks[iDataLink]);
end;
end;
if Assigned(FOnRequest) then
FOnRequest(Self);
end;
procedure TaOPCSource.DoUpdateDataLinksData;
var
i: integer;
iGroup: integer;
CrackDataLink: TCrackOPCLink;
DataLinkGroup: TOPCDataLinkGroup;
aGroupValue: string;
aGroupFloatValue: Double;
begin
for iGroup := 0 to FThread.GroupsForUpdate.Count - 1 do
begin
DataLinkGroup := TOPCDataLinkGroup(FThread.GroupsForUpdate.Items[iGroup]);
DataLinkGroup.NeedUpdate := False;
if OpcFS.DecimalSeparator <> FormatSettings.DecimalSeparator then
aGroupValue := StringReplace(DataLinkGroup.Value, OpcFS.DecimalSeparator, FormatSettings.DecimalSeparator, [])
else
aGroupValue := DataLinkGroup.Value;
TryStrToFloat(aGroupValue, aGroupFloatValue);
for i := 0 to DataLinkGroup.DataLinks.Count - 1 do
begin
CrackDataLink := TCrackOPCLink(DataLinkGroup.DataLinks.Items[i]);
CrackDataLink.FErrorCode := DataLinkGroup.ErrorCode;
CrackDataLink.FErrorString := DataLinkGroup.ErrorString;
// если еще не было данных, то будем считать Старые равными Новым
if CrackDataLink.FOldValue = '' then
begin
CrackDataLink.FOldValue := aGroupValue;
CrackDataLink.FOldFloatValue := aGroupFloatValue;
end
else
begin
CrackDataLink.FOldValue := CrackDataLink.FValue;
CrackDataLink.FOldFloatValue := CrackDataLink.FFloatValue;
end;
CrackDataLink.FValue := aGroupValue;
CrackDataLink.FFloatValue := aGroupFloatValue;
CrackDataLink.FMoment := DataLinkGroup.Moment;
end;
end;
end;
// function TaOPCSource.GetSensorProperties(id: string): TSensorProperties;
// begin
// end;
function TaOPCSource.GetSensorPropertiesEx(id: string): string;
begin
end;
function TaOPCSource.GetSensorsValueOnMoment(PhysIDs: string; Moment: TDateTime): string;
begin
Result := 'GetSensorsValueOnMoment Реализация только у наследников';
end;
function TaOPCSource.GetSensorsValues(PhysIDs: string): string;
begin
Result := 'Error:GetSensorsValues Реализация только у наследников';
end;
procedure TaOPCSource.SetPacketUpdate(const Value: Boolean);
begin
FPacketUpdate := Value;
if FPacketUpdate then
CalcPhysIDs;
end;
// процедура вызывается только внутри потока и только она может уменьшить
// размер списка групп FDataLinkGroups
procedure TaOPCSource.CalcPhysIDs;
var
i: Integer;
aNeedPack: Boolean;
aDataLinkGroup: TOPCDataLinkGroup;
begin
FPhysIDs := '';
FPhysIDsChanged := True;
aNeedPack := false;
for i := 0 to FDataLinkGroups.Count - 1 do
begin
aDataLinkGroup := TOPCDataLinkGroup(FDataLinkGroups.Items[i]);
// помеченные на удаление удаляем
if Assigned(aDataLinkGroup) and aDataLinkGroup.Deleted then
begin
FDataLinkGroups.Items[i] := nil;
FreeAndNil(aDataLinkGroup);
end;
// расчитываем необходимость упаковки
if not Assigned(aDataLinkGroup) then
begin
aNeedPack := True;
Continue;
end;
if PacketUpdate and (aDataLinkGroup.PhysID <> '') then
begin
if UpdateMode in [umAuto, umPacket, umStreamPacket] then
FPhysIDs := FPhysIDs + ';' + aDataLinkGroup.PhysID;
end;
end;
FPhysIDs := Copy(FPhysIDs, 2, Length(FPhysIDs));
if aNeedPack then
begin
FDataLinkGroupsLock.Enter;
try
// упаковку выполняем в критической секции
FDataLinkGroups.Pack;
finally
FDataLinkGroupsLock.Leave;
end;
end;
if not (UpdateMode in [umStreamPacket]) then
FDataLinkGroupsChanged := false;
//ForceUpdate;
end;
procedure TaOPCSource.AddDataLink(DataLink: TaOPCDataLink;
OldSource: TaCustomOPCSource = nil);
begin
inherited AddDataLink(DataLink, OldSource);
FDataLinkGroupsChanged := True;
// ForceUpdate;
// CalcPhysIDs;
end;
procedure TaOPCSource.Loaded;
begin
inherited Loaded;
Connected := FStreamedConnected;
end;
function TaOPCSource.LoadLookup(aName: string;
var aTimeStamp: TDateTime): string;
begin
Result := 'Error:LoadLookup Реализация только у наследников';
end;
procedure TaOPCSource.LoadNameSpace(aCustomIniFile: TCustomIniFile;
aSectionName: string = '');
begin
if aSectionName = '' then
aSectionName := 'NameSpace'
else
aSectionName := aSectionName + '\NameSpace';
FNameSpaceTimeStamp := aCustomIniFile.ReadDateTime(aSectionName, 'TimeStamp', 0);
if FileExists(GetNameSpaceFileName) then
// загружаемся из файла (новый режим)
FNameSpaceCash.LoadFromFile(GetNameSpaceFileName)
else
// попытаемся использовать старый режим загрузки из реестра
aCustomIniFile.ReadSection(aSectionName + 'Data', FNameSpaceCash);
end;
function TaOPCSource.OPCStringToFloat(aStr: string): Double;
begin
if OpcFS.DecimalSeparator <> FormatSettings.DecimalSeparator then
Result := StrToFloat(StringReplace(aStr, OpcFS.DecimalSeparator, FormatSettings.DecimalSeparator, []))
else
Result := StrToFloat(aStr);
end;
{
procedure TaOPCSource.NameStaceToObjectList(var aObjectList: TDCObjectList);
var
i: Integer;
ALevel: Integer;
//aObjectLevel: Integer;
aCaption: string;
Data: TStrings;
CurrStr: string;
aObject, aNewObject, aNextObject: TDCObject;
//aSensor: TDCCustomSensor;
CaseStairs: integer;
aRefTableName: string;
begin
// уже добавленный в список объект
aObject := nil;
// проходим по предварительно загруженной иерархии
for i := 0 to FNameSpaceCash.Count - 1 do
begin
// вычитываем информационную строку и определяем грубину вложенности
CurrStr := GetBufStart(PChar(FNameSpaceCash[i]), ALevel);
// вычитываем наименование объекта
aCaption := ExtractData(CurrStr);
// вычитываем данные по объекту, создаем и наполняем объект
Data := TStringList.Create;
try
while CurrStr<>'' do
Data.Add(ExtractData(CurrStr));
if Data.Strings[1] = '1' then
begin
aNewObject := TDCObject.Create;
aNewObject.Kind := StrToIntDef(Data.Strings[2],1000);
aNewObject.ServerChildCount := StrToIntDef(Data.Strings[5], 0);
end
else
begin
aNewObject := TSensor.Create;
aNewObject.Kind := 0;
with TSensor(aNewObject) do
begin
DisplayFormat := Data.Strings[2];
SensorUnitName := Data.Strings[3];
// SensorKind := StrToIntDef(Data.Strings[1],0);
//
aRefTableName := Data.Strings[6];
if aRefTableName <> '' then
begin
LookupList := aOPCConnection.GetLookupByTableName(aRefTableName);
if Data.Count >= 10 then
begin
if Data.Strings[9] = '1' then
LookupList.ShowValue := svLeft
else if Data.Strings[9] = '2' then
LookupList.ShowValue := svRight;
end;
end;
CaseStairs := StrToIntDef(Data.Strings[5],0);
case CaseStairs of
0: StairsOptions := [soIncrease,soDecrease];
1: StairsOptions := [];
2: StairsOptions := [soIncrease];
3: StairsOptions := [soDecrease];
end;
end;
end;
// добавляем объект в список
aObjectList.Add(aNewObject);
//aNewObject.Owner := aOPCConnection;
aNewObject.Name := aCaption;
aNewObject.IDStr := Data.Strings[0];
// определяем родетеля обхекта
if aObject = nil then
aNewObject.Parent := nil
else if aObject.Level = ALevel then
aNewObject.Parent := aObject.Parent
else if aObject.Level = (ALevel - 1) then
aNewObject.Parent := aObject
else if aObject.Level > ALevel then
begin
aNextObject := aObject.Parent;
while Assigned(aNextObject) and (aNextObject.Level >= ALevel) do
aNextObject := aNextObject.Parent;
aNewObject.Parent := aNextObject;
end
else
raise Exception.CreateFmt('ALevel=%d - aObject.Level=%d',[ALevel, aObject.Level]);
aObject := aNewObject;
finally
FreeAndNil(Data);
end;
end;
end;
}
procedure TaOPCSource.SaveNameSpace(aCustomIniFile: TCustomIniFile; aSectionName: string = '');
// var
// i:integer;
begin
if aSectionName = '' then
aSectionName := 'NameSpace'
else
aSectionName := aSectionName + '\NameSpace';
try
FNameSpaceCash.SaveToFile(GetNameSpaceFileName);
// сохраняем время последнего обновления
aCustomIniFile.WriteDateTime(aSectionName, 'TimeStamp', FNameSpaceTimeStamp);
except
on e: Exception do
OPCLog.WriteToLogFmt('Не удалось сохранить иерархию в файл %s. Ошибка: %s',
[GetNameSpaceFileName, e.Message]);
end;
{ СТАРЫЙ ВАРИАНТ ХРАНЕНИЯ
//очищаем секцию с данными
aCustomIniFile.EraseSection(aSectionName+'Data');
//сохраняем новые данные
for i:=0 to FNameSpaceCash.Count-1 do
aCustomIniFile.WriteString(aSectionName+'Data',FNameSpaceCash.Strings[i],IntToStr(i));
}
// FNameSpaceCash.SaveToFile(GetNameSpaceFileName);
end;
procedure TaOPCSource.ChangeData;
var
DataLinkGroup: TOPCDataLinkGroup;
i: Integer;
CrackDataLink: TCrackOPCLink;
tmpFloat: extended;
begin
DataLinkGroup := FThread.DataLinkGroup;
// TOPCDataLinkGroup(DataLinkGroups.Items[fThread.DataLinkGroupIndex]);
DataLinkGroup.NeedUpdate := false;
for i := 0 to DataLinkGroup.DataLinks.Count - 1 do
begin
CrackDataLink := TCrackOPCLink(DataLinkGroup.DataLinks.Items[i]);
CrackDataLink.FErrorCode := DataLinkGroup.ErrorCode; // fThread.ErrorCode;
CrackDataLink.FErrorString := DataLinkGroup.ErrorString;
// fThread.ErrorString;
CrackDataLink.FValue := DataLinkGroup.Value;
if OpcFS.DecimalSeparator <> FormatSettings.DecimalSeparator then
begin
tmpFloat := StrToFloatDef(CrackDataLink.FValue, UnUsedValue, OpcFS);
if tmpFloat <> UnUsedValue then
CrackDataLink.FValue := FloatToStr(tmpFloat);
end;
CrackDataLink.FMoment := DataLinkGroup.Moment; // fThread.Moment;
CrackDataLink.ChangeData;
end; // for
end;
procedure TaOPCSource.CheckAnswer(aAnswer: string; aParamCount: Integer = 0);
var
i: Integer;
aFoundParamCount: Integer;
begin
if Copy(aAnswer, 1, Length(sError)) = sError then
raise Exception.Create(Copy(aAnswer, Length(sError) + 1, Length(aAnswer)))
else if Copy(aAnswer, 1, Length(sOk)) <> sOk then
raise Exception.CreateFmt(sUnknownAnswer, [aAnswer]);
if aParamCount <> 0 then
begin
if Length(aAnswer) > Length(sOk) then
aFoundParamCount := 1
else
aFoundParamCount := 0;
for i := 1 to Length(aAnswer) do
if aAnswer[i] = cParamsDelimiter then
inc(aFoundParamCount);
if aParamCount <> aFoundParamCount then
raise Exception.CreateFmt(sBadParamCount, [aFoundParamCount, aParamCount]);
end;
end;
procedure TaOPCSource.CheckForNewNameSpace(aCustomIniFile: TCustomIniFile;
aSectionName: string = '';
aReconnect: boolean = false);
begin
if not aReconnect then
FNameSpaceTimeStamp := aCustomIniFile.ReadDateTime(aSectionName +
'\NameSpace', 'TimeStamp', 0)
else
FNameSpaceTimeStamp := -1;
if Connected and GetNameSpace then
SaveNameSpace(aCustomIniFile, aSectionName)
else
LoadNameSpace(aCustomIniFile, aSectionName);
end;
procedure TaOPCSource.CheckLock;
begin
end;
procedure TaOPCSource.SetUpdateMode(const Value: TaOPCUpdateMode);
begin
FUpdateMode := Value;
if FUpdateMode = umPacket then
PacketUpdate := True
else if FUpdateMode = umEach then
PacketUpdate := false;
end;
procedure TaOPCSource.Authorize(aUser: string; aPassword: string);
begin
end;
function TaOPCSource.SendModBus(aSystemType: integer; aRequest: string;
aRetByteCount, aTimeOut: integer): string;
begin
Result := 'SendModBus Реализация только у наследников';
end;
function TaOPCSource.SendModBusEx(aConnectionName, aRequest: string;
aRetByteCount, aTimeOut: integer): string;
begin
Result := 'SendModBusEx Реализация только у наследников';
end;
end.
|
unit RRManagerEditNextSubstructureInfoFrame;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
RRManagerBaseObjects, RRManagerObjects, StdCtrls,
CommonComplexCombo, RRManagerBaseGUI;
type
// TfrmNextSubstructureInfo = class(TFrame)
TfrmNextSubstructureInfo = class(TBaseFrame)
gbxAll: TGroupBox;
Label1: TLabel;
edtClosingIsogypse: TEdit;
Label2: TLabel;
EdtPerspectiveArea: TEdit;
edtAmplitude: TEdit;
Label4: TLabel;
edtControlDensity: TEdit;
Label5: TLabel;
Label3: TLabel;
Label6: TLabel;
edtMapError: TEdit;
private
function GetSubstructure: TOldSubstructure;
{ Private declarations }
protected
procedure FillControls(ABaseObject: TBaseObject); override;
procedure ClearControls; override;
procedure RegisterInspector; override;
public
{ Public declarations }
property Substructure: TOldSubstructure read GetSubstructure;
procedure Save; override;
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.DFM}
{ TfrmNextSubstructureInfo }
procedure TfrmNextSubstructureInfo.ClearControls;
begin
edtClosingIsogypse.Clear;
edtPerspectiveArea.Clear;
edtControlDensity.Clear;
edtAmplitude.Clear;
edtMapError.Clear;
end;
constructor TfrmNextSubstructureInfo.Create(AOwner: TComponent);
begin
inherited;
EditingClass := TOldSubstructure;
end;
procedure TfrmNextSubstructureInfo.FillControls(ABaseObject: TBaseObject);
var S: TOldSubstructure;
begin
if not Assigned(ABaseObject) then S := Substructure
else S := ABaseObject as TOldSubstructure;
edtClosingIsogypse.Text := trim(Format('%7.2f', [S.ClosingIsoGypse]));
edtPerspectiveArea.Text := trim(Format('%7.2f', [S.PerspectiveArea]));
edtControlDensity.Text := trim(Format('%7.2f', [S.ControlDensity]));
edtAmplitude.Text := trim(Format('%7.2f', [S.Amplitude]));
edtMapError.Text := trim(Format('%7.2f', [S.MapError]));
end;
function TfrmNextSubstructureInfo.GetSubstructure: TOldSubstructure;
begin
Result := EditingObject as TOldSubstructure;
end;
procedure TfrmNextSubstructureInfo.RegisterInspector;
begin
inherited;
// регистрируем контролы, которые под инспектором
Inspector.Add(edtClosingIsogypse, nil, ptFloat, 'замыкающая изогипса', true);
Inspector.Add(edtPerspectiveArea, nil, ptFloat, 'перспективная площадь', true);
Inspector.Add(edtControlDensity, nil, ptFloat, 'контрольная плотность', true);
Inspector.Add(edtAmplitude, nil, ptFloat, 'амплитуда', true);
Inspector.Add(edtMapError, nil, ptFloat, 'случайная ошибка карты', true);
end;
procedure TfrmNextSubstructureInfo.Save;
begin
inherited;
try
Substructure.ClosingIsogypse := StrToFloat(edtClosingIsogypse.Text);
except
Substructure.ClosingIsogypse := 0;
end;
try
Substructure.PerspectiveArea := StrToFloat(EdtPerspectiveArea.Text);
except
Substructure.PerspectiveArea := 0;
end;
try
Substructure.ControlDensity := StrToFloat(edtControlDensity.Text);
except
Substructure.ControlDensity := 0;
end;
try
Substructure.Amplitude := StrToFloat(edtAmplitude.Text);
except
Substructure.Amplitude := 0;
end;
try
Substructure.MapError := StrToFloat(edtMapError.Text);
except
Substructure.MapError := 0;
end;
end;
end.
|
unit uFormMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.Math.Vectors, FMX.Media, FMX.Controls3D, FMX.ScrollBox, FMX.Memo,
FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Layouts,
ZXing.BarcodeFormat,
FMX.Platform,
System.Diagnostics,
System.Threading,
ZXing.ReadResult,
ZXing.ScanManager, FMX.ListBox;
type
TScanBufferEvent = procedure(Sender: TObject; ABitmap: TBitmap) of object;
TFormMain = class(TForm)
Layout2: TLayout;
Memo1: TMemo;
ToolBar3: TToolBar;
Camera1: TCamera;
SwitchScanning: TSwitch;
PaintBox1: TPaintBox;
LabelFPS: TLabel;
btnBackCamera: TSpeedButton;
btnFrontCamera: TSpeedButton;
cbResolutions: TComboBox;
Layout3: TLayout;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
procedure SwitchScanningSwitch(Sender: TObject);
procedure btnBackCameraClick(Sender: TObject);
procedure btnFrontCameraClick(Sender: TObject);
procedure cbResolutionsChange(Sender: TObject);
private
FScanManager: TScanManager;
FScanInProgress: Boolean;
FFrameTake: Integer;
FStopwatch: TStopwatch;
FFrameCount: Integer;
FVideoSettings: TArray<TVideoCaptureSetting>;
FActive: Boolean;
FBuffer: TBitmap;
FViewportBuffer: TBitmap;
FVideoCamera: TVideoCaptureDevice;
FOnScanBuffer: TScanBufferEvent;
procedure DoScanBuffer(Sender: TObject; const ATime: TMediaTime);
procedure SynchroniseBuffer;
function AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean;
procedure LoadResolutions;
procedure StartCapture;
procedure StopCapture;
function GetDevice(Kind : TCameraKind): TVideoCaptureDevice;
// procedure GetImage();
end;
var
FormMain: TFormMain;
implementation
{$R *.fmx}
procedure TFormMain.FormCreate(Sender: TObject);
var
AppEventSvc: IFMXApplicationEventService;
begin
if TPlatformServices.Current.SupportsPlatformService
(IFMXApplicationEventService, IInterface(AppEventSvc)) then
begin
AppEventSvc.SetApplicationEventHandler(AppEvent);
end;
FActive := False;
FBuffer := TBitmap.Create();
FVideoCamera := GetDevice(TCameraKind.FrontCamera);
FVideoCamera.OnSampleBufferReady := DoScanBuffer;
FFrameTake := 0;
btnBackCamera.IsPressed := true;
FVideoSettings := nil;
LoadResolutions();
FScanManager := TScanManager.Create(TBarcodeFormat.Auto, nil);
end;
function TFormMain.GetDevice (Kind : TCameraKind): TVideoCaptureDevice;
var
I: Integer;
D: TCaptureDevice;
begin
for I := 0 to TCaptureDeviceManager.Current.Count - 1 do
begin
D := TCaptureDeviceManager.Current.Devices[I];
if (D.MediaType = TMediaType.Video) and (D is TVideoCaptureDevice) then
begin
if (Kind = TCameraKind.FrontCamera) and (TVideoCaptureDevice(D).Position = TDevicePosition.Front) then
begin
Result := TVideoCaptureDevice(D);
Break;
end;
if (Kind = TCameraKind.BackCamera) and (TVideoCaptureDevice(D).Position = TDevicePosition.Back) then
begin
Result := TVideoCaptureDevice(D);
Break;
end;
end;
end;
if Result = nil then
Result := TCaptureDeviceManager.Current.DefaultVideoCaptureDevice;
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
FBuffer.Free;
StopCapture();
FScanManager.Free;
end;
{ Make sure the camera is released if you're going away. }
function TFormMain.AppEvent(AAppEvent: TApplicationEvent;
AContext: TObject): Boolean;
begin
case AAppEvent of
TApplicationEvent.WillBecomeInactive, TApplicationEvent.EnteredBackground,
TApplicationEvent.WillTerminate:
StopCapture();
end;
end;
procedure TFormMain.StartCapture;
begin
FVideoCamera.Quality := TVideoCaptureQuality.MediumQuality;
FVideoCamera.FocusMode := TFocusMode.ContinuousAutoFocus;
FBuffer.Clear(TAlphaColors.White);
FActive := true;
LabelFPS.Text := 'Starting capture...';
FFrameCount := 0;
FStopwatch := TStopwatch.StartNew;
FVideoCamera.StartCapture;
end;
procedure TFormMain.StopCapture;
begin
FActive := False;
if FVideoCamera <> nil then
begin
FVideoCamera.StopCapture;
// FreeAndNil(FVideoCamera);
LabelFPS.Text := '';
end;
end;
procedure TFormMain.DoScanBuffer(Sender: TObject; const ATime: TMediaTime);
var
sec: double;
begin
TThread.Synchronize(TThread.CurrentThread, SynchroniseBuffer);
sec := FStopwatch.Elapsed.TotalSeconds;
{ Ignore the first 3 seconds to get up to speed }
if (sec > 3) then
begin
sec := sec - 3;
Inc(FFrameCount);
LabelFPS.Text := Format('%.2f fps (%d x %d)',
[FFrameCount / sec, FBuffer.Width, FBuffer.Height]);
end;
end;
procedure TFormMain.SynchroniseBuffer;
begin
if FActive = False then
begin
Exit;
end;
FVideoCamera.SampleBufferToBitmap(FBuffer, true);
if Assigned(FOnScanBuffer) then
FOnScanBuffer(Self, FBuffer);
PaintBox1.Repaint;
end;
procedure TFormMain.btnBackCameraClick(Sender: TObject);
begin
// CameraComponent1.Kind := TCameraKind.BackCamera;
LoadResolutions();
end;
procedure TFormMain.btnFrontCameraClick(Sender: TObject);
begin
// CameraComponent1.Kind := TCameraKind.FrontCamera;
LoadResolutions();
end;
procedure TFormMain.LoadResolutions();
var
i: Integer;
begin
cbResolutions.Clear;
// FVideoSettings := CameraComponent1.AvailableCaptureSettings;
for i := Low(FVideoSettings) to High(FVideoSettings) do
begin
cbResolutions.Items.Add(FVideoSettings[i].Width.toString + ' x ' +
FVideoSettings[i].Height.toString + ' x ' + FVideoSettings[i]
.FrameRate.toString + ' fps');
end;
if (cbResolutions.Items.Count > 0) then
begin
cbResolutions.ItemIndex := 0;
// CameraComponent1.SetCaptureSetting(FVideoSettings[0]);
end;
end;
procedure TFormMain.cbResolutionsChange(Sender: TObject);
begin
// StopCamera();
// if FVideoSettings <> nil then
// CameraComponent1.SetCaptureSetting(FVideoSettings[cbResolutions.ItemIndex]);
end;
procedure TFormMain.PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
var
SR, DR, PR: TRectF;
begin
if (SwitchScanning.IsChecked) then
begin
PR := RectF(0, 0, PaintBox1.Width, PaintBox1.Height);
Canvas.Fill.Kind := TBrushKind.Solid;
Canvas.Fill.Color := TAlphaColors.Black;
Canvas.FillRect(PR, 0, 0, [], 1);
if (FBuffer.Width > 0) then
begin
SR := RectF(0, 0, FBuffer.Width, FBuffer.Height);
DR := SR;
if (DR.Width < PaintBox1.Width) and (DR.Height < PaintBox1.Height) then
RectCenter(DR, PR)
else
DR := DR.FitInto(PR);
Canvas.DrawBitmap(FBuffer, SR, DR, 1);
end;
end;
end;
procedure TFormMain.SwitchScanningSwitch(Sender: TObject);
begin
if (SwitchScanning.IsChecked) then
begin
// Memo1.Lines.Clear;
// CameraComponent1.Active := True;
// Application.ProcessMessages();
// ResetCapture();
StartCapture();
end
else
StopCapture();
// StopCamera();
end;
end.
|
{$include kode.inc}
unit syn_simple;
{$define KODE_MAXVOICES := 16}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_plugin,
kode_types,
kode_voicemanager;
type
myPlugin = class(KPlugin)
private
FVoices : KVoiceManager;
FMaster : Single;
public
procedure on_Create; override;
procedure on_destroy; override;
procedure on_StateChange(AState:LongWord); override;
procedure on_ParameterChange(AIndex:LongWord; AValue:Single); override;
procedure on_midiEvent(AOffset:LongWord; AMsg1,AMsg2,AMsg3:Byte); override;
procedure on_ProcessBlock(inputs,outputs:PPSingle; frames:LongWord); override;
procedure on_processSample(inputs,outputs:PPSingle); override;
procedure on_postProcess; override;
{$ifdef KODE_GUI}
function on_OpenEditor(AParent:Pointer) : Pointer; override;
procedure on_CloseEditor; override;
{$endif}
end;
KPluginClass = myPlugin;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
_plugin_id,
{$ifdef KODE_GUI}
kode_color,
kode_editor,
kode_rect,
kode_widget,
kode_widget_color,
kode_widget_slider,
{$endif}
kode_const,
kode_flags,
kode_parameter,
kode_utils,
//kode_voice,
syn_simple_voice;
const
osc_types : array[0..7] of PChar = ( 'off', 'const', 'input', 'noise', 'ramp', 'saw', 'squ', 'sin' );
//flt_types : array[0..4] of PChar = ( 'off', 'lowpass', 'highpass', 'bandpass', 'notch' );
//----------
procedure myPlugin.on_Create;
var
i : longint;
//{$ifdef KODE_GUI}
//var w : KWidget;
//{$endif}
begin
FName := 'syn_simple';
FAuthor := 'skei.audio';
FUniqueId := KODE_MAGIC + syn_simple_id;
FVersion := 0;
FProduct := FName;
KSetFlag(FFlags, kpf_isSynth + kpf_receiveMidi + kpf_perSample );
appendParameter( KParamText.create(' o1.type', 4, 8, osc_types ));
appendParameter( KParamFloat.create('o1.vol', 1 ));
appendParameter( KParamFloat.create('o1.vol.a', 10, 1, 50 ));
appendParameter( KParamFloat.create('o1.vol.r', 20, 1, 50 ));
appendParameter( KParamInt.create( 'o1.pitch', 0 , -24,24 ));
appendParameter( KParamFloat.create('master', 1 ));
FVoices := KVoiceManager.create(self);
for i := 0 to KODE_MAXVOICES-1 do FVoices.appendVoice( KVoiceSimple1.create );
FMaster := 0;
{$ifdef KODE_GUI}
KSetFlag(FFlags,kpf_hasEditor);
FEditor := nil;
FEditorRect.setup(400,165);
{$endif}
end;
//----------
procedure myPlugin.on_destroy;
begin
FVoices.destroy;
end;
//----------
procedure myPlugin.on_StateChange(AState:LongWord);
begin
case AState of
kps_resume,
kps_sampleRate: FVoices.on_setSampleRate(FSampleRate);
end;
end;
//----------
procedure myPlugin.on_ParameterChange(AIndex: LongWord; AValue: Single);
begin
case AIndex of
0..4 : FVoices.on_control(AIndex,AValue);
5 : FMaster := AValue*AValue*AValue;
end;
end;
//----------
procedure myPlugin.on_midiEvent(AOffset: LongWord; AMsg1, AMsg2, AMsg3: Byte);
begin
FVoices.on_midi(AOffset,AMsg1,AMsg2,AMsg3);
end;
//----------
procedure myPlugin.on_processBlock(inputs, outputs: PPSingle; frames: LongWord);
begin
FVoices.on_preProcess;
end;
//----------
procedure myPlugin.on_processSample(inputs,outputs:PPSingle);
var
outs : array[0..1] of single;
begin
FVoices.on_process(outs);
outputs[0]^ := outs[0] * FMaster;
outputs[1]^ := outs[1] * FMaster;
end;
//----------
procedure myPlugin.on_postProcess;
begin
FVoices.on_postProcess;
end;
//----------------------------------------------------------------------
// editor
//----------------------------------------------------------------------
{$ifdef KODE_GUI}
function myPlugin.on_OpenEditor(AParent:Pointer) : Pointer;
var
panel : KWidget;
widget : KWidget;
editor : KEditor;
i : LongInt;
begin
editor := KEditor.create(self,FEditorRect,AParent);
panel := KWidget_Color.create( rect(0,0,400,70), color(0.7), kwa_fillClient );
panel.margins(10,10);
panel.padding(5,5);
editor.appendWidget(panel);
{ widgets }
for i := 0 to 5 do
begin
widget := KWidget_Slider.create( rect(20), 0, kwa_fillTop );
panel.appendWidget( widget );
editor.connect( widget, FParameters[i] );
end;
{ }
{.$ifdef KODE_VST}
editor.on_align;
editor.paint(FEditorRect);
{.$endif}
editor.show;
result := editor;
end;
{$endif}
//----------
{$ifdef KODE_GUI}
procedure myPlugin.on_CloseEditor;
begin
FEditor.hide;
FEditor.destroy;
FEditor := nil;
end;
{$endif}
//----------------------------------------------------------------------
end.
|
{
ID: a_zaky01
PROG: window
LANG: PASCAL
}
type
rectangle=record
llx,lly,urx,ury,col:longint;
end;
var
k,z,size,i:longint;
area:int64;
trect:rectangle;
task:string;
ch:char;
percent:extended;
num:array[1..4] of longint;
rect:array[0..63] of rectangle;
val:array[chr(0)..chr(255)] of integer;
show:array[0..63] of boolean;
name:array[0..63] of char;
pos:array[0..63] of integer;
procedure calc(rect0:rectangle; cover:integer);
var
temp:rectangle;
begin
while (cover<=size) and ((rect0.llx>=rect[cover].urx)
or (rect0.urx<=rect[cover].llx)
or (rect0.lly>=rect[cover].ury)
or (rect0.ury<=rect[cover].lly)) do inc(cover);
if cover>size then area:=area + (rect0.urx-rect0.llx)*(rect0.ury-rect0.lly)
else
begin
if rect0.ury>rect[cover].ury then
begin
temp:=rect0;
temp.lly:=rect[cover].ury;
rect0.ury:=temp.lly;
calc(temp,cover+1);
end;
if rect0.lly<rect[cover].lly then
begin
temp:=rect0;
temp.ury:=rect[cover].lly;
rect0.lly:=temp.ury;
calc(temp,cover+1);
end;
if rect0.urx>rect[cover].urx then
begin
temp:=rect0;
temp.llx:=rect[cover].urx;
calc(temp,cover+1);
end;
if rect0.llx<rect[cover].llx then
begin
temp:=rect0;
temp.urx:=rect[cover].llx;
calc(temp,cover+1);
end;
end;
end;
procedure swap(var a,b:longint);
var
temp:longint;
begin
temp:=a;
a:=b;
b:=temp;
end;
begin
assign(input,'window.in');
assign(output,'window.out');
reset(input);
rewrite(output);
k:=0;
for ch:='a' to 'z' do
begin
inc(k);
val[ch]:=k;
end;
for ch:='A' to 'Z' do
begin
inc(k);
val[ch]:=k;
end;
for ch:='0' to '9' do
begin
inc(k);
val[ch]:=k;
end;
size:=0;
while not eof do
begin
readln(task);
case task[1] of
'w': begin
ch:=task[3];
z:=0;
fillchar(num,sizeof(num),0);
for i:=4 to length(task) do
if task[i]=')' then break
else if task[i]=',' then inc(z)
else num[z]:=10*num[z]+ord(task[i])-ord('0');
inc(size);
with rect[size] do
begin
llx:=num[1];
lly:=num[2];
urx:=num[3];
ury:=num[4];
if llx>urx then swap(llx,urx);
if lly>ury then swap(lly,ury);
end;
show[val[ch]]:=true;
pos[val[ch]]:=size;
name[size]:=ch;
end;
't': begin
ch:=task[3];
trect:=rect[pos[val[ch]]];
for i:=pos[val[ch]] to size-1 do
begin
rect[i]:=rect[i+1];
name[i]:=name[i+1];
pos[val[name[i]]]:=i;
end;
rect[size]:=trect;
pos[val[ch]]:=size;
name[size]:=ch;
end;
'b': begin
ch:=task[3];
trect:=rect[pos[val[ch]]];
for i:=pos[val[ch]] downto 2 do
begin
rect[i]:=rect[i-1];
name[i]:=name[i-1];
pos[val[name[i]]]:=i;
end;
rect[1]:=trect;
pos[val[ch]]:=1;
name[1]:=ch;
end;
'd': begin
ch:=task[3];
dec(size);
for i:=pos[val[ch]] to size do
begin
rect[i]:=rect[i+1];
name[i]:=name[i+1];
pos[val[name[i]]]:=i;
end;
show[val[ch]]:=false;
end;
's': begin
ch:=task[3];
area:=0;
calc(rect[pos[val[ch]]],pos[val[ch]]+1);
with rect[pos[val[ch]]] do percent:=area*100/((urx-llx)*(ury-lly));
writeln(percent:0:3);
end;
end;
end;
close(input);
close(output);
end.
|
Program SL8;
Uses crt;
Var x, y, e:real;
Begin
Clrscr;
Write ('X = ');
ReadLn (x);
If (x > 3.61)
Then y:= ln(abs(1 + x));
If (x >= 2.8) and (x <= 3.8)
Then y:= exp(-(x-8) * Ln(e));
If (x<2.8)
Then y:= cos(x);
Write ('Y = ', y:8:4);
Repeat until keypressed;
End. |
unit form_Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.Bluetooth, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts,
FMX.ListBox, System.Bluetooth.Components, System.SyncObjs, System.Rtti,
System.Threading, FMX.Edit, FMX.ScrollBox, FMX.Memo;
type
TFormMain = class(TForm)
Bluetooth: TBluetooth;
FreeListBox: TListBox;
btnInfo: TButton;
FreeLbl: TLabel;
AniIndicator1: TAniIndicator;
btnPair: TButton;
PairedListBox: TListBox;
Panel1: TPanel;
ListBoxInfo: TListBox;
btnCreateSocket: TButton;
PairedLbl: TLabel;
FreeBtnRefresh: TButton;
PairedBtnRefresh: TButton;
pnlFree: TPanel;
pnlPaired: TPanel;
pnlCommunication: TPanel;
memoCommIncomming: TMemo;
lblCommunication: TLabel;
edtSend: TEdit;
btnSend: TButton;
pnlSend: TPanel;
btnFreeSocket: TButton;
Timer: TTimer;
btnUnpair: TButton;
Button1: TButton;
Button2: TButton;
memoCommOutgoing: TMemo;
Panel2: TPanel;
procedure btnInfoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BluetoothDiscoveryEnd(const Sender: TObject;
const ADeviceList: TBluetoothDeviceList);
procedure PairedBtnRefreshClick(Sender: TObject);
procedure FreeBtnRefreshClick(Sender: TObject);
procedure btnCreateSocketClick(Sender: TObject);
procedure PairedListBoxChange(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure btnFreeSocketClick(Sender: TObject);
procedure btnUnpairClick(Sender: TObject);
procedure btnPairClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
// BTClient: Array of TBluetoothDevice;
BTClient: TBluetoothDevice;
FormMain: TFormMain;
BTManager: TBluetoothManager;
BTAdapter: TBluetoothAdapter;
BTSocket: TBluetoothSocket;
ReceiverLoop: ITask;
RecCount: Integer;
implementation
const
DiscoveryTime = 20000;
BTPortPooling = 100;
// HC-06 Serial port service info
ServiceName = 'Dev B';
ServiceGUI = '{00001101-0000-1000-8000-00805F9B34FB}';
{$R *.fmx}
// Functions Declaration
function GetServiceName(GUID: string): string;
var
LServices: TBluetoothServiceList;
LDevice: TBluetoothDevice;
I: Integer;
begin
// LDevice := FPairedDevices[ComboboxPaired.ItemIndex] as TBluetoothDevice;
LDevice:=BTClient;
LServices := LDevice.GetServices;
for I := 0 to LServices.Count - 1 do
begin
if StringToGUID(GUID) = LServices[I].UUID then
begin
Result := LServices[I].Name;
break;
end;
end;
end;
// Procedures Declaration
procedure TFormMain.btnUnpairClick(Sender: TObject);
begin
Bluetooth.UnPair(Bluetooth.CurrentManager.LastPairedDevices.Items[PairedListBox.ItemIndex]);
end;
procedure TFormMain.Button1Click(Sender: TObject);
var
DiscoveryLoop: ITask;
begin
DiscoveryLoop := TTask.Create( procedure()
var
i,j: integer;
begin
FormMain.Button1.Enabled:=False;
RecCount:=0;
Timer.Enabled:=True;
for j := 0 to 10000 do
begin
BTSocket.SendData( TEncoding.ASCII.GetBytes(edtSend.Text+#10) );
inc(RecCount);
// Tinterlocked.Increment(RecCount);
end;
FormMain.Button1.Enabled:=True;
Timer.Enabled:=False;
end);
DiscoveryLoop.Start;
end;
procedure TFormMain.btnPairClick(Sender: TObject);
begin
Bluetooth.Pair(Bluetooth.CurrentManager.LastDiscoveredDevices.Items[FreeListBox.ItemIndex]);
end;
procedure TFormMain.btnInfoClick(Sender: TObject);
begin
ListBoxInfo.Clear;
ListBoxInfo.Items.Add(BTClient.DeviceName);
ListBoxInfo.Items.Add(BTClient.Address);
// ListBoxInfo.Items.Add('BT State: '+inttostr(BTClient.State));
// ListBoxInfo.Items.Add('BT Type: '+inttostr(BTClient.BluetoothType));
ListBoxInfo.Items.Add('BT Type: '+inttostr(BTClient.ClassDeviceMajor)+'.'+inttostr(BTClient.ClassDevice));
end;
procedure TFormMain.btnCreateSocketClick(Sender: TObject);
var
ToSend: TBytes;
begin
if (BTSocket = nil) then
try
memoCommOutgoing.Lines.Add(GetServiceName(ServiceGUI)+' '+ServiceGUI);
memoCommOutgoing.GoToTextEnd;
BTSocket := BTClient.CreateClientSocket(StringToGUID(ServiceGUI), False);
BTSocket.Connect;
Bluetooth.CurrentManager.SocketTimeout:=BTPortPooling;
if BTSocket <> nil then
begin
ToSend := TEncoding.ASCII.GetBytes('Init: '+FormatDateTime('c',now)+#10);
memoCommOutgoing.Lines.Add('Init: '+FormatDateTime('c',now));
memoCommOutgoing.GoToTextEnd;
if ReceiverLoop=nil then
begin
ReceiverLoop := TTask.Create( procedure()
var
ToRead, SubBytes: TBytes;
Temp: String;
I: Integer;
begin
while BTSocket.Connected do
begin
ToRead:=BTSocket.ReadData;
SubBytes:=SubBytes+ToRead;
for I := 0 to length(SubBytes)-1 do
begin
if SubBytes[i]=10 then
begin
SetString(Temp, PAnsiChar(@SubBytes[0]), i);
memoCommIncomming.Lines.Add('<--: '+trim(Temp));
memoCommIncomming.GoToTextEnd;
SetLength(ToRead, length(SubBytes)-i-1);
move(SubBytes[i+1],ToRead[0],length(SubBytes)-i-1);
SetLength(SubBytes, length(ToRead));
move(ToRead[0],SubBytes[0],length(ToRead));
// exit;
break;
end;
end;
end;
end);
end;
end;
btnCreateSocket.Enabled:=False;
btnFreeSocket.Enabled:=True;
PairedListBox.Enabled:=False;
if ReceiverLoop<>nil then ReceiverLoop.Start;
except
on E : Exception do
begin
memoCommOutgoing.Lines.Add('Error: '+E.Message);
memoCommOutgoing.GoToTextEnd;
end;
end;
end;
procedure TFormMain.btnFreeSocketClick(Sender: TObject);
begin
memoCommOutgoing.Lines.Clear;
memoCommIncomming.Lines.Clear;
IF BTSocket<>nil then
begin
FreeAndNil(BTSocket);
end;
// Parallel task should end becasue socket is destroyed and there is while condition
if ReceiverLoop<>nil then
begin
try
FreeAndNil(ReceiverLoop);
except
end;
end;
btnCreateSocket.Enabled:=True;
btnFreeSocket.Enabled:=False;
PairedListBox.Enabled:=True;
end;
procedure TFormMain.btnSendClick(Sender: TObject);
var
ToSend: TBytes;
begin
if (BTSocket <> nil) and (BTSocket.Connected) then
try
ToSend := TEncoding.ASCII.GetBytes(edtSend.Text+#10);
BTSocket.SendData(ToSend);
memoCommOutgoing.Lines.Add('-->: '+edtSend.Text);
memoCommOutgoing.GoToTextEnd;
except
on E : Exception do
begin
memoCommOutgoing.Lines.Add('Error: '+E.Message);
memoCommOutgoing.GoToTextEnd;
end;
end;
end;
procedure TFormMain.FormCreate(Sender: TObject);
var
I:Integer;
begin
Bluetooth.Enabled:=True;
// Add paired list
PairedListBox.Clear;
for I := 0 to Bluetooth.PairedDevices.Count-1 do PairedListBox.Items.Add(Bluetooth.PairedDevices.Items[i].DeviceName);
// Add free list
end;
procedure TFormMain.FreeBtnRefreshClick(Sender: TObject);
begin
Bluetooth.CurrentManager.StartDiscovery(DiscoveryTime);
AniIndicator1.Enabled:=True;
AniIndicator1.Visible:=True;
end;
procedure TFormMain.BluetoothDiscoveryEnd(const Sender: TObject;
const ADeviceList: TBluetoothDeviceList);
var
i: integer;
begin
AniIndicator1.Enabled:=False;
AniIndicator1.Visible:=False;
for I := 0 to Bluetooth.CurrentManager.LastDiscoveredDevices.Count-1 do
begin
FreeListBox.Items.Add(Bluetooth.CurrentManager.LastDiscoveredDevices.Items[i].DeviceName);
end;
end;
procedure TFormMain.PairedBtnRefreshClick(Sender: TObject);
var
I: integer;
begin
PairedListBox.Clear;
for I := 0 to Bluetooth.PairedDevices.Count-1 do PairedListBox.Items.Add(Bluetooth.PairedDevices.Items[i].DeviceName);
end;
procedure TFormMain.PairedListBoxChange(Sender: TObject);
begin
if PairedListBox.Count<>0 then BTClient:=Bluetooth.PairedDevices.Items[PairedListBox.Selected.Index];
btnInfoClick(nil);
btnCreateSocket.Enabled:=True;
end;
end.
|
program registro_de_movimentacoes;
{Feito por Felipe Schreiber Fernandes DRE 116 206 990
Turma ELL170 EL3
última modificação:24/11/2016}
uses minhaEstante;
const
MAX=200;
ALFANUM='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
type
cadastro=record
EP:char;
cod:integer;
qtd:real;
nome:string;
end;
matrix=array[1..MAX] of cadastro;
fEntradaSaida=file of cadastro;
procedure inicializarMatriz(var matrizInicial:matrix);
var
indice:integer;
begin
for indice:=0 to MAX do
begin
matrizInicial[indice].nome:='-';
matrizInicial[indice].cod:=-1;
matrizInicial[indice].EP:= '-';
matrizInicial[indice].qtd:=0;
end;
end;
procedure abrirCriar(var fHistorico,fEntrada,fSaida,fConcatenado,fMerge:fEntradaSaida;var matHistorico:matrix);
{Esse procedimento cria ou abre cinco arquivos de uma só vez, um com todas as transações, um de entrada, um de saída,um concatenado e por fim o do merge}
var
nome,nomeBase:string;
{nome do arquivo salvo ou que será criado na parte externa do programa}
indMat:integer;
{indMat é o indice para variar a posição da matriz ao copiar os dados do arquivo para ela}
Begin
writeln('informe o nome do arquivo a ser aberto ou criado');
readln(nomeBase);
assign(fHistorico,nomeBase);
nome:=nomeBase + '_Entrada';
assign(fEntrada,nome);
nome:=nomeBase + '_Saida';
assign(fSaida,nome);
nome:=nomeBase + '_Concatenado';
assign(fConcatenado,nome);
nome:=nomeBase + '_Merge';
assign(fMerge,nome);
{$I-}
reset(fHistorico);
reset(fEntrada);
reset(fSaida);
reset(fConcatenado);
reset(fMerge);
{$I+}
If (ioresult = 2) then
begin
rewrite(fHistorico);
rewrite(fEntrada);
rewrite(fSaida);
rewrite(fConcatenado);
rewrite(fMerge);
writeln('o histórico foi criado');
end
else
begin
writeln('o histórico foi aberto');
end;
{começar a copiar os dados do arquivo para a matriz}
indMat:=1;
while (not eof(fHistorico)) and (indMat<=MAX) do
begin
{esse laço garante que todos os dados do arquivo serão copiados}
read(fHistorico,matHistorico[indMat]);
indMat:=indMat+1;
{a variável indMat garante que os dados serão copiados em diferentes posições da matriz}
end;
if (filepos(fHistorico) <> filesize(fHistorico)) then
{se por um acaso a cópia de dados terminar antes de se chegar ao fim do arquivo, ou seja, o indMat possui um limite inferior à quantidade de posições, exibirá tal mensagem ao usuário}
begin
writeln('nem todos os arquivos foram copiados para a matriz, aumente o valor da constante');
end;
end;
procedure gravarMovimentacao(var matProc:matrix);
var
ind:integer;
{ind é uma variável de controle das posições da matriz}
posi:integer;
{posi é uma variável para descubrir o primeiro espaço livre na matriz para preencher os dados da movimentação}
Begin
posi:=0;
ind:=1;
while (ind<=MAX) and (matProc[ind].cod <> -1) do
{quando o ind tiver o valor MAX estará na última posição da matriz e, caso esteja preenchida, possuirá, ao final do bloco de comandos, o valor MAX+1, daí é necessário que o se encerre o bloco de comandos visto que essa posição está além do limite da matriz}
{esse laço é para encontrar a primeira posição não ocupada na matriz}
begin
{como todos os registros da matriz no campo do codigo foram inicializados com menos um (-1) então se o respectivo campo for diferente disso significa que tal posição da matriz já foi preenchida}
ind:=ind+1;
end;
posi:=ind;
{caso o referido campo esteja livre, ou seja, preenchido com menos um (-1),então essa é a primeira posição desocupada da matriz e a variável posi armazenará o valor da ind (que é a variável de controle), uma vez que quando for diferente chegará ao fim do incremento da ind}
if (posi<>MAX+1) then
{essa condição garante que tem espaço sobrando na matriz para preencher com dados, para tal é preciso que o valor da variável posi esteja dentro do limite da matriz}
{Na situação limite, quando todos as posições da matriz estiverem preenchidas, a variável ind terá o valor de MAX+1}
begin
matProc[posi].nome:=lerString(1,20,ALFANUM,'Digite o nome do produto a ser inserido.Só pode conter letras e números, não usar caracteres especiais');
lerInteiro(matProc[posi].cod,1001,9999,'insira o código do produto.O valor tem que ser um inteiro entre 1001 e 9999');
matProc[posi].qtd:=lerReal(0,32767,'diga a quantidade de entrada/saída. Ela deve ser um real entre 0 e 32767');
matProc[posi].EP:=lerChar('epEP','Informe se a transação foi de [E]ntrada ou [S]aída.Digite em letra maiúscula E para Entrada ou P para Saída.Só pode conter um caractere');
writeln('produto inserido com sucesso');
writeln();
writeln();
end
else
begin
writeln('não há mais espaço disponível para inserir movimentações.', ' Se você desejar aumentar o número de transações guardadas basta trocar o valor da constante');
writeln();
writeln();
end;
end;
procedure ordenar_por_codigo(var matProc:matrix);
{algoritmo do tipo BubbleSort}
var
ind1,ind2:integer;
aux:cadastro;
Begin
For ind1:=1 to MAX-1 do
Begin
For ind2:=1 to MAX-1 do
Begin
if (matProc[ind2].cod > matProc[ind2+1].cod) then
Begin
aux:=matProc[ind2];
matProc[ind2]:=matProc[ind2+1];
matProc[ind2+1]:=aux;
End;
End;
End;
end;
procedure printMerge(var fMerge:fEntradaSaida);
var
cadastroTemp:cadastro;
controle:integer;
begin
controle:=0
seek(fMerge,0);
while (not eof(fMerge)) do
begin
controle:=1;
read(fMerge,cadastroTemp);
{copia os dados temporariamente para uma variável}
if (cadastroTemp.cod<>-1) then
{esse laço evita a exibição de movimentações não preenchidas}
begin
writeln('o código do produto é: ',cadastroTemp.cod);
writeln('o nome do item é ',cadastroTemp.nome);
case cadastroTemp.EP of
'E':
Begin
writeln('Entraram ',cadastroTemp.qtd:5:3, 'unidades');
end;
'P':
Begin
writeln('Saíram ', cadastroTemp.qtd:5:3,' unidades');
End;
end;{end do case}
end;{end do if}
end;{end do while}
if (controle=0) then
begin
writeln('o arquivo merge está vazio');
end
else
begin
writeln('fim da exibição');
end;
end;
procedure printEntrada(var fEntrada:fEntradaSaida);
{esse procedimento exibe apenas as movimentações de Entrada}
var
cadastroTemp:cadastro;
controle:integer;
begin
controle:=0;
seek(fEntrada,0);
while not eof(fEntrada) do
begin
read(fEntrada,cadastroTemp);
if (cadastroTemp.cod<>-1) then
begin
writeln('o código do produto é: ',cadastroTemp.cod:4);
writeln('o nome do item é ',cadastroTemp.nome);
writeln('Entraram ',cadastroTemp.qtd:5:3, 'unidades');
controle:=1;
end;
end;
if (controle=0) then
begin
writeln('não houve transações de entrada ou você ainda não efetuou a separação do arquivo em entrada e saída');
end
else
begin
writeln('fim da exibição');
end;
end;
procedure printConcatenado(var fConcatenado:fEntradaSaida);
{esse procedimento exibe apenas o arquivo concatenado}
var
cadastroTemp:cadastro;
controle:integer;{essa variável serve para saber se o arquivo concatenado existe}
begin
controle:=0;
seek(fConcatenado,0);
while not eof(fConcatenado) do
begin
controle:=1;
read(fConcatenado,cadastroTemp);
if (cadastroTemp.cod<>-1) then
begin
writeln('o código do produto é: ',cadastroTemp.cod:4);
writeln('o nome do item é ',cadastroTemp.nome);
if cadastroTemp.EP= 'E' then
begin
writeln('Entraram ',cadastroTemp.qtd:5:3, 'unidades');
end
else
begin
writeln('Saíram ',cadastroTemp.qtd:5:3,' unidades');
end;
end;
end;
if (controle = 0) then
begin
writeln('o arquivo concatenado está vazio');
end
else
begin
writeln('fim da exibição');
end;
end;
procedure printSaida(var fSaida:fEntradaSaida);
{esse procedimento imprime apenas as movimentações de saída}
var
cadastroTemp:cadastro;
controle:integer;
{essa variável serve para controlar se houve ou não transações}
begin
controle:=0;
seek(fSaida,0);
while not eof(fSaida) do
begin
read(fSaida,cadastroTemp);
if (cadastroTemp.cod<>-1) then
begin
writeln('o código do produto é: ',cadastroTemp.cod:4);
writeln('o nome do item é ',cadastroTemp.nome);
writeln('Saíram ',cadastroTemp.qtd:5:3, 'unidades');
controle:=1;
end;
end;
if (controle=0) then
begin
writeln('não houve transações de saída ou você ainda não efetuou a separação do arquivo em entrada e saída');
end
else
begin
writeln('fim da exibição');
end;
end;
procedure printMovimentacoes(matProc:matrix);
{esse procedimento imprime apenas as movimentações de determinado produto}
var
codigo,ind:integer;
name:string;
op:char;
Begin
op:=lerChar('cnCN','como deseja buscar as transações do produto, por código ou por nome?Digite apenas uma letra, C para código ou N para nome');
case op of
'C':
Begin
lerInteiro(codigo,1001,9999,'Digite o código do produto.Ele deve ser um inteiro entre 1001 e 9999.');
for ind:=1 to MAX do
begin
if (matProc[ind].cod = codigo) then
begin
writeln('o código do produto é: ',matProc[ind].cod:4);
writeln('o nome do item é ',matProc[ind].nome);
case matProc[ind].EP of
'E':
Begin
writeln('Entrada de ',matProc[ind].qtd:5:3,' unidades');
End;
'P':
Begin
writeln('Saída de ',matProc[ind].qtd:5:3,' unidades');
End;
end;{end do case interno}
end;{end do if}
end;{end do for}
end;{end do case 'C'}
'N':
Begin
writeln('qual o nome do produto?');
readln(name);
for ind:=1 to MAX do
begin
if (matProc[ind].nome = name) then
begin
writeln('o código do produto é: ',matProc[ind].cod:4);
writeln('o nome do item é ',matProc[ind].nome);
case matProc[ind].EP of
'E':
Begin
writeln('Entrada de ',matProc[ind].qtd:5:3,' unidades');
End;
'P':
Begin
writeln('Saída de ',matProc[ind].qtd:5:3,' unidades');
End;
end;{end do case interno}
end;{end do if}
end;{end do for}
end;{end do case 'N'}
end;{end do case externo}
end;{end do procedure}
procedure printHistorico(matProc:matrix);
{esse procedimento imprime na tela todos as transações e suas respectivas informações}
var
ind,controle:integer;
begin
controle:=0;
{a variável de controle serve para saber se o arquivo está vazio ou não}
for ind:=1 to MAX do
begin
if (matProc[ind].cod <> -1) then
{essa condição estabelece um limite de transações a serem exibidas na tela.Como todos os elementos do record no campo designado para o código foram inicializados com menos um (-1) então se estiver preenchido com algo diferente indica a presença de uma transação, evitando a necessidade de se exibir algo que ainda não foi preenchido}
begin
controle:=1;
writeln('o código do produto é: ',matProc[ind].cod:4);
writeln('o nome do item é ',matProc[ind].nome);
case matProc[ind].EP of
'E':
Begin
writeln('Entrada de ',matProc[ind].qtd:5:3,' unidades');
End;
'P':
Begin
writeln('Saída de ',matProc[ind].qtd:5:3,' unidades');
End;
end;{end do case}
end;{end do if}
end;{end do for}
if (controle=0) then
begin
writeln('o arquivo está vazio');
end
else
begin
writeln('fim da exibição');
end;
end;
procedure salvar(var fHistorico:fEntradaSaida; matHistorico:matrix);
{Esse procedimento copia os dados da matriz para o arquivo e salva todos os arquivos}
Var
ind:integer;
begin
seek(fHistorico,0);
for ind:=1 to MAX do
begin
if (matHistorico[ind].qtd <> -1) then
{Como todos os elementos do record no campo designado para a quantidade foram inicializados com menos um (-1) então se estiver preenchido com algo diferente indica apresença de um produto preenchido, evitando a necessidade de se passar para o arquivo algo que ainda não foi preenchido}
begin
write(fHistorico,matHistorico[ind]);
end
end;
end;
procedure separar_em_entrada_ou_saida(var fHistorico,fEntradas,fSaidas:fEntradaSaida);
var
historicoTemp:cadastro;
{essa variável armazena temporariamente os dados do arquivo}
Begin
seek(fHistorico,0);
seek(fEntradas,0);
seek(fSaidas,0);
while (not eof(fHistorico)) do
begin
read(fHistorico,historicoTemp);
if (historicoTemp.EP = 'E') then
begin
write(fEntradas,historicoTemp);
end
else
begin
write(fSaidas,historicoTemp);
end;
end;
end;
procedure concatenar(var fConcatenado,fEntrada,fSaida:fEntradaSaida);
var
cadastroTemp:cadastro;
{armazena temporariamente os dados dos arquivos}
Begin
seek(fConcatenado,0);
seek(fEntrada,0);
seek(fSaida,0);
while (not eof(fEntrada)) do
{primeiro lê todos os dados do arquivo de entrada, passa para uma variável e aí passa para o arquivo concatenado}
begin
read(fEntrada,cadastroTemp);
write(fConcatenado,cadastroTemp);
end;
while (not eof(fSaida)) do
{o mesmo processo é realizado, só que com o arquivo de saída}
begin
read(fSaida,cadastroTemp);
write(fConcatenado,cadastroTemp);
end;
end;
procedure fazer_merge(var fMerge,fEntrada,fSaida:fEntradaSaida);
var
cadastroS,cadastroE:cadastro;
Begin
seek(fEntrada,0);
seek(fSaida,0);
seek(fMerge,0);
while (not eof(fEntrada)) and (not eof(fSaida)) do
{até que se chegue ao final de um dos arquivos o merge ocorrerá normalmente}
Begin
{copia os dados de cada arquivo para armazenamentos temporários para possibilitar a respectiva comparação}
read(fEntrada,cadastroE);
read(fSaida,cadastroS);
{começa a copiar para o merge o menor dos dois códigos comparados}
if (cadastroS.cod > cadastroE.cod) then
Begin
write(fMerge,cadastroE);
seek(fSaida,filepos(fSaida)-1);
{é necessário voltar uma posição no arquivo cujo dado não foi copiado para realizar a próxima comparação}
End
Else
{o mesmo processo é realizado, só que no caso oposto}
Begin
write(fMerge,cadastroS);
seek(fEntrada,filepos(fEntrada)-1);
End;
End;{end do while}
if (filepos(fEntrada) = filesize(fEntrada)) then
{essa condição é para ver qual arquivo chegou ao fim primeiro, visto que é impossível que ambos cheguem ao mesmo tempo}
begin
while not eof(fSaida) do
{se o de entrada chegou ao fim primeiro, então significa que o de saída não foi totalmente passado para o arquivo merge}
begin
read(fSaida,cadastroS);
write(fMerge,cadastroS);
end;
End
Else
{mesmo procedimento anterior, só que para o caso oposto}
Begin
while not eof(fEntrada) do
begin
read(fEntrada,cadastroE);
write(fMerge,cadastroE);
end;{end do while}
end;{end do else}
End;{end do procedure}
{Programa Principal}
VAR
matrizPrincipal:matrix;
Historico,Entrada,Saida,Concatenado,Merge:fEntradaSaida;
choice:integer;
BEGIN
choice:=0;
inicializarMatriz(matrizPrincipal);
abrirCriar(Historico,Entrada,Saida,Concatenado,Merge,matrizPrincipal);
repeat
writeln('escolha uma opção:');
writeln();
writeln('1-Fazer Movimentação');
writeln();
writeln('2-Buscar movimentações pelo nome ou pelo código');
writeln();
writeln('3- Ordenar movimentações por código');
writeln();
writeln('4-Dividir o arquivo em entrada e saída');
writeln();
writeln('5-Concatenar os arquivos de entrada e saída');
writeln();
writeln('6-Fazer um merge dos arquivos de entrada e saída');
writeln();
writeln('7-Exibir todas as movimentações ');
writeln();
writeln('8-Exibir as movimentações de entrada');
writeln();
writeln('9-Exibir as movimentações de saída');
writeln();
writeln('10-Exibir as movimentações do arquivo concatenado');
writeln();
writeln('11-Exibir as movimentações do arquivo merge');
writeln();
writeln('12-Sair do programa');
writeln();
lerInteiro(choice,1,12,'Escolha uma opção entre 1 e 12. Ela deve ser um inteiro');
case choice of
1:
begin
gravarMovimentacao(matrizPrincipal);
salvar(Historico,matrizPrincipal);
end;
2:
begin
printMovimentacoes(matrizPrincipal);
end;
3:
begin
ordenar_por_codigo(matrizPrincipal);
salvar(Historico,matrizPrincipal);
end;
4:
begin
separar_em_entrada_ou_saida(Historico,Entrada,Saida);
writeln();
writeln('os arquivos de entrada e de saida foram criados');
writeln();
end;
5:
begin
ordenar_por_codigo(matrizPrincipal);
separar_em_entrada_ou_saida(Historico,Entrada,Saida); concatenar(Concatenado,Entrada,Saida);
end;
6:
Begin
ordenar_por_codigo(matrizPrincipal);
salvar(Historico,matrizPrincipal);
separar_em_entrada_ou_saida(Historico,Entrada,Saida);
{Para fazer o merge é necessário que antes os arquivos de entradae saída estejam ordenados e estejam preenchidos}
fazer_merge(Merge,Entrada,Saida);
writeln('o arquivo merge foi criado');
End;
7:
Begin
printHistorico(matrizPrincipal);
End;
8:
Begin
printEntrada(Entrada);
End;
9:
Begin
printSaida(Saida);
End;
10:
Begin
printConcatenado(Concatenado);
End;
11:
Begin
printMerge(Merge);
End;
12:
Begin
salvar(Historico,matrizPrincipal);
close(Entrada);
close(Saida);
close(Concatenado);
close(Merge);
writeln('arquivos salvos com sucesso');
End;
end;{end do case}
until (choice=12);
END.
|
unit uFormRenderVCL;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls;
type
TForm17 = class(TForm)
btnRender: TButton;
Panel1: TPanel;
TrackBarAnitAlias: TTrackBar;
LabelAntiAlias: TLabel;
LabelTime: TLabel;
Image1: TImage;
procedure TrackBarAnitAliasChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnRenderClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form17: TForm17;
implementation
{$R *.dfm}
uses uRendererVCL, System.Diagnostics;
procedure TForm17.btnRenderClick(Sender: TObject);
var sw: TStopwatch; r: TRendererVCL;
begin
LabelTime.Caption := 'Rendering... Please wait.';
self.Invalidate;
Application.ProcessMessages;
sw := TStopwatch.StartNew;
r := TRendererVCL.Create(round(Image1.Width), round(Image1.Height), TrackBarAnitAlias.Position);
Image1.Picture.Assign(r.DoRender);
sw.Stop;
LabelTime.Caption := IntToStr(sw.ElapsedMilliseconds) + ' msec ('
+ IntToStr(sw.ElapsedTicks) + ' ticks)';
end;
procedure TForm17.FormCreate(Sender: TObject);
begin
TrackBarAnitAliasChange(self);
end;
procedure TForm17.TrackBarAnitAliasChange(Sender: TObject);
begin
LabelAntiAlias.Caption := 'Anti-Aliasing Level: ' + TrackBarAnitAlias.Position.ToString;
end;
end.
|
unit lcid_conv;
{ MS Locale ID to Windows Code Page converter }
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LConvEncoding;
function LCIDToWinCP(ALCID: Word): Word;
function WinCPToLCID(AWinCP: Word): Word;
function ConvToUTF8FromLCID(ALCID: Word; AStr: string): string;
function ConvToUTF8FromCP(ACP: Word; AStr: string): string;
function IsLCIDDirectionRTL(ALCID: Word): Boolean;
implementation
type
T_LCID_CP = record
LCID: Word;
CP: Word;
end;
const
lcid_cp_list: array [0..119] of T_LCID_CP = (
// Latin 2 / Central European
(LCID: 1052; CP: 1250), // Albanian
(LCID: 1050; CP: 1250), // Croatian
(LCID: 1029; CP: 1250), // Czech
(LCID: 1038; CP: 1250), // Hungarian
(LCID: 1045; CP: 1250), // Polish
(LCID: 1048; CP: 1250), // Romanian - Romania
(LCID: 2074; CP: 1250), // Serbian - Latin
(LCID: 1051; CP: 1250), // Slovak
(LCID: 1060; CP: 1250), // Slovenian
// Cyrillic
(LCID: 2092; CP: 1251), // Azeri - Cyrillic
(LCID: 1059; CP: 1251), // Belarusian
(LCID: 1026; CP: 1251), // Bulgarian
(LCID: 1087; CP: 1251), // Kazakh
(LCID: 1088; CP: 1251), // Kyrgyz - Cyrillic
(LCID: 1104; CP: 1251), // Mongolian
(LCID: 1049; CP: 1251), // Russian
(LCID: 2073; CP: 1251), // Russian - Moldova
(LCID: 3098; CP: 1251), // Serbian - Cyrillic
(LCID: 1092; CP: 1251), // Tatar
(LCID: 1058; CP: 1251), // Ukrainian
(LCID: 2115; CP: 1251), // Uzbek - Cyrillic
// Latin 1 / Western European
(LCID: 1078; CP: 1252), // Afrikaans
(LCID: 1069; CP: 1252), // Basque
(LCID: 1027; CP: 1252), // Catalan
(LCID: 1030; CP: 1252), // Danish
(LCID: 2067; CP: 1252), // Dutch - Belgium
(LCID: 1043; CP: 1252), // Dutch - Netherlands
(LCID: 3081; CP: 1252), // English - Australia
(LCID: 10249; CP: 1252), // English - Belize
(LCID: 4105; CP: 1252), // English - Canada
(LCID: 9225; CP: 1252), // English - Caribbean
(LCID: 2057; CP: 1252), // English - Great Britain
(LCID: 16393; CP: 1252), // English - India
(LCID: 6153; CP: 1252), // English - Ireland
(LCID: 8201; CP: 1252), // English - Jamaica
(LCID: 5129; CP: 1252), // English - New Zealand
(LCID: 13321; CP: 1252), // English - Phillippines
(LCID: 7177; CP: 1252), // English - Southern Africa
(LCID: 11273; CP: 1252), // English - Trinidad
(LCID: 1033; CP: 1252), // English - United States
(LCID: 12297; CP: 1252), // English - Zimbabwe
(LCID: 1080; CP: 1252), // Faroese
(LCID: 1035; CP: 1252), // Finnish
(LCID: 2060; CP: 1252), // French - Belgium
(LCID: 11276; CP: 1252), // French - Cameroon
(LCID: 3084; CP: 1252), // French - Canada
(LCID: 9228; CP: 1252), // French - Congo
(LCID: 12300; CP: 1252), // French - Cote d'Ivoire
(LCID: 1036; CP: 1252), // French - France
(LCID: 5132; CP: 1252), // French - Luxembourg
(LCID: 13324; CP: 1252), // French - Mali
(LCID: 6156; CP: 1252), // French - Monaco
(LCID: 14348; CP: 1252), // French - Morocco
(LCID: 10252; CP: 1252), // French - Senegal
(LCID: 4108; CP: 1252), // French - Switzerland
(LCID: 7180; CP: 1252), // French - West Indies
(LCID: 1110; CP: 1252), // Galician
(LCID: 3079; CP: 1252), // German - Austria
(LCID: 1031; CP: 1252), // German - Germany
(LCID: 5127; CP: 1252), // German - Liechtenstein
(LCID: 4103; CP: 1252), // German - Luxembourg
(LCID: 2055; CP: 1252), // German - Switzerland
(LCID: 1039; CP: 1252), // Icelandic
(LCID: 1057; CP: 1252), // Indonesian
(LCID: 1040; CP: 1252), // Italian - Italy
(LCID: 2064; CP: 1252), // Italian - Switzerland
(LCID: 2110; CP: 1252), // Malay - Brunei
(LCID: 1086; CP: 1252), // Malay - Malaysia
(LCID: 1044; CP: 1252), // Norwegian - Bokml
(LCID: 2068; CP: 1252), // Norwegian - Nynorsk
(LCID: 1046; CP: 1252), // Portuguese - Brazil
(LCID: 2070; CP: 1252), // Portuguese - Portugal
(LCID: 11274; CP: 1252), // Spanish - Argentina
(LCID: 16394; CP: 1252), // Spanish - Bolivia
(LCID: 13322; CP: 1252), // Spanish - Chile
(LCID: 9226; CP: 1252), // Spanish - Colombia
(LCID: 5130; CP: 1252), // Spanish - Costa Rica
(LCID: 7178; CP: 1252), // Spanish - Dominican Republic
(LCID: 12298; CP: 1252), // Spanish - Ecuador
(LCID: 17418; CP: 1252), // Spanish - El Salvador
(LCID: 4106; CP: 1252), // Spanish - Guatemala
(LCID: 18442; CP: 1252), // Spanish - Honduras
(LCID: 2058; CP: 1252), // Spanish - Mexico
(LCID: 19466; CP: 1252), // Spanish - Nicaragua
(LCID: 6154; CP: 1252), // Spanish - Panama
(LCID: 15370; CP: 1252), // Spanish - Paraguay
(LCID: 10250; CP: 1252), // Spanish - Peru
(LCID: 20490; CP: 1252), // Spanish - Puerto Rico
(LCID: 1034; CP: 1252), // Spanish - Spain (Traditional)
(LCID: 14346; CP: 1252), // Spanish - Uruguay
(LCID: 8202; CP: 1252), // Spanish - Venezuela
(LCID: 1089; CP: 1252), // Swahili
(LCID: 2077; CP: 1252), // Swedish - Finland
(LCID: 1053; CP: 1252), // Swedish - Sweden
// Greek
(LCID: 1032; CP: 1253), // Greek
// Turkish
(LCID: 1068; CP: 1254), // Azeri - Latin
(LCID: 1055; CP: 1254), // Turkish
// Hebrew
(LCID: 1037; CP: 1255), // Hebrew
// Arabic
(LCID: 5121; CP: 1256), // Arabic - Algeria
(LCID: 15361; CP: 1256), // Arabic - Bahrain
(LCID: 3073; CP: 1256), // Arabic - Egypt
(LCID: 2049; CP: 1256), // Arabic - Iraq
(LCID: 11265; CP: 1256), // Arabic - Jordan
(LCID: 13313; CP: 1256), // Arabic - Kuwait
(LCID: 12289; CP: 1256), // Arabic - Lebanon
(LCID: 4097; CP: 1256), // Arabic - Libya
(LCID: 6145; CP: 1256), // Arabic - Morocco
(LCID: 8193; CP: 1256), // Arabic - Oman
(LCID: 16385; CP: 1256), // Arabic - Qatar
(LCID: 1025; CP: 1256), // Arabic - Saudi Arabia
(LCID: 10241; CP: 1256), // Arabic - Syria
(LCID: 7169; CP: 1256), // Arabic - Tunisia
(LCID: 14337; CP: 1256), // Arabic - United Arab Emirates
(LCID: 9217; CP: 1256), // Arabic - Yemen
(LCID: 1065; CP: 1256), // Farsi - Persian
(LCID: 1056; CP: 1256), // Urdu
// Baltic
(LCID: 1061; CP: 1257), // Estonian
(LCID: 1062; CP: 1257), // Latvian
(LCID: 1063; CP: 1257), // Lithuanian
// Vietnamese
(LCID: 1066; CP: 1258) // Vietnamese
);
function LCIDToWinCP(ALCID: Word): Word;
var
i: Integer;
begin
Result := 1252; // Latin
for i := Low(lcid_cp_list) to High(lcid_cp_list) do
begin
if lcid_cp_list[i].LCID = ALCID then
begin
Result := lcid_cp_list[i].CP;
Exit;
end;
end;
end;
function WinCPToLCID(AWinCP: Word): Word;
begin
case AWinCP of
1250: Result := 1052; // CP: 1250 - Albanian
1251: Result := 1049; // CP: 1251 - Russian
1252: Result := 1033; // CP: 1252 - English - United States
1253: Result := 1032; // CP: 1253 - Greek
1254: Result := 1055; // CP: 1254 - Turkish
1255: Result := 1037; // CP: 1255 - Hebrew
1256: Result := 1025; // CP: 1256 - Arabic - Saudi Arabia
1257: Result := 1061; // CP: 1257 - Estonian
1258: Result := 1066; // CP: 1258 - Vietnamese
else
Result := 0; // UTF-8
end;
end;
function ConvToUTF8FromLCID(ALCID: Word; AStr: string): string;
var
wcp: Word;
begin
if (ALCID <> 0) or (ALCID <> 1033) then
begin
wcp := LCIDToWinCP(ALCID);
// convert to codepage
case wcp of
1250: Result := CP1250ToUTF8(AStr);
1251: Result := CP1251ToUTF8(AStr);
1252: Result := CP1252ToUTF8(AStr);
1253: Result := CP1253ToUTF8(AStr);
1254: Result := CP1254ToUTF8(AStr);
1255: Result := CP1255ToUTF8(AStr);
1256: Result := CP1256ToUTF8(AStr);
1257: Result := CP1257ToUTF8(AStr);
1258: Result := CP1258ToUTF8(AStr);
else
Result := AStr;
end;
end
else
Result := AStr;
end;
function ConvToUTF8FromCP(ACP: Word; AStr: string): string;
begin
// convert to codepage
case ACP of
1250: Result := CP1250ToUTF8(AStr);
1251: Result := CP1251ToUTF8(AStr);
1252: Result := CP1252ToUTF8(AStr);
1253: Result := CP1253ToUTF8(AStr);
1254: Result := CP1254ToUTF8(AStr);
1255: Result := CP1255ToUTF8(AStr);
1256: Result := CP1256ToUTF8(AStr);
1257: Result := CP1257ToUTF8(AStr);
1258: Result := CP1258ToUTF8(AStr);
else
Result := AStr;
end;
end;
function IsLCIDDirectionRTL(ALCID: Word): Boolean;
var
wcp: Word;
begin
Result := False;
if (ALCID <> 0) or (ALCID <> 1033) then
begin
wcp := LCIDToWinCP(ALCID);
case wcp of
1255: Result := True; // Hebrew
1256: Result := True; // Arabic
end;
end
end;
end.
|
unit U_Configuracoes;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.Edit, FMX.SearchBox, FMX.ListBox, FMX.Layouts,
FMX.Objects, FMX.StdCtrls;
type
TfrmConfiguracoesGerais = class(TForm)
layoutMain: TLayout;
layoutClient: TLayout;
Rectangle1: TRectangle;
ListBox1: TListBox;
ToolBar1: TToolBar;
lblTitulo: TLabel;
SearchBox1: TSearchBox;
lbxitArtigos: TListBoxItem;
lbxitTipDenuncias: TListBoxItem;
lbxitTipReceitas: TListBoxItem;
lbxitUnidades: TListBoxItem;
ListBoxItem1: TListBoxItem;
procedure lbxitArtigosClick(Sender: TObject);
procedure lbxitTipDenunciasClick(Sender: TObject);
procedure ListBoxItem1Click(Sender: TObject);
procedure lbxitTipReceitasClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
const
ARTIGO = 'ARTIGOS COD. SANITÁRIO';
BANCO = 'BANCO DE DADOS';
TIPDEN = 'TIPOS DE DENÚNCIAS';
public
{ Public declarations }
end;
var
frmConfiguracoesGerais: TfrmConfiguracoesGerais;
implementation
uses
U_CadastroArtigos, U_SISVISA, U_CadastroTipoDenuncia,
U_CadastroProcedDenuncia, U_CadastroTipoReceita;
{$R *.fmx}
procedure TfrmConfiguracoesGerais.lbxitTipDenunciasClick(Sender: TObject);
var FormTipDen: TfrmCadastroTipoDenuncia;
begin
if not ASsigned(FormTipDen) then
FormTipDen := TfrmCadastroTipoDenuncia.Create(Self);
layoutClient.RemoveObject(0);
layoutClient.AddObject(FormTipDen.Layout1);
formTipDen.lblTitulo.text := TIPDEN;
end;
procedure TfrmConfiguracoesGerais.lbxitTipReceitasClick(Sender: TObject);
var FormTipRec : TfrmCadastroTipReceita;
begin
if not Assigned(FormTipRec) then
FormTipRec := TfrmCadastroTipReceita.Create(Self);
layoutClient.RemoveObject(0);
layoutClient.AddObject(FormTipRec.Layout1);
end;
procedure TfrmConfiguracoesGerais.ListBoxItem1Click(Sender: TObject);
var FormProcedDen : TFrmCadastroProcedDenuncia;
begin
if not Assigned(FormProcedDen) then
FormProcedDen := TfrmCadastroProcedDenuncia.Create(Self);
layoutClient.RemoveObject(0);
layoutClient.AddObject(FormProcedDen.Layout1);
end;
procedure TfrmConfiguracoesGerais.FormCreate(Sender: TObject);
begin
lbxitArtigos.Visible := False;
lbxitUnidades.Visible := False;
end;
procedure TfrmConfiguracoesGerais.lbxitArtigosClick(Sender: TObject);
var
FormArtigo: TfrmCadastroArtigos;
begin
if not Assigned(FormArtigo) then
FormArtigo := TfrmCadastroArtigos.Create(Self);
layoutClient.RemoveObject(0);
layoutClient.AddObject(FormArtigo.Layout1);
FormArtigo.lblTitulo.Text := ARTIGO;
end;
end.
|
unit MediaFilesController;
interface
uses
Generics.Collections,
MediaFile,
Aurelius.Engine.ObjectManager;
type
TMediaFilesController = class
private
FManager: TObjectManager;
public
constructor Create;
destructor Destroy; override;
function GetAllMediaFiles: TList<TMediaFile>;
procedure DeleteMediaFile(MediaFile: TMediaFile);
end;
implementation
uses
DBConnection;
{ TMediaFilesController }
constructor TMediaFilesController.Create;
begin
FManager := TDBConnection.GetInstance.CreateObjectManager;
end;
procedure TMediaFilesController.DeleteMediaFile(MediaFile: TMediaFile);
begin
if not FManager.IsAttached(MediaFile) then
MediaFile := FManager.Find<TMediaFile>(MediaFile.Id);
FManager.Remove(MediaFile);
end;
destructor TMediaFilesController.Destroy;
begin
FManager.Free;
inherited;
end;
function TMediaFilesController.GetAllMediaFiles: TList<TMediaFile>;
begin
FManager.Clear;
Result := FManager.FindAll<TMediaFile>;
end;
end.
|
unit FmWebSocketTest;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, rtcInfo, rtcConn, rtcDataCli, rtcHttpCli, Vcl.StdCtrls, SynEdit,
SuperObject;
type
TMainFnWSTest = class(TForm)
Client: TRtcHttpClient;
Memo1: TSynEdit;
SockReq: TRtcDataRequest;
btnCheck: TButton;
btnIncome: TButton;
btnReconnect: TButton;
btnCloseShift: TButton;
btnOpen: TButton;
procedure CheckClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SockReqConnectLost(Sender: TRtcConnection);
procedure SockReqWSConnect(Sender: TRtcConnection);
procedure SockReqWSDataReceived(Sender: TRtcConnection);
procedure SockReqWSDataIn(Sender: TRtcConnection);
procedure SockReqWSDataOut(Sender: TRtcConnection);
procedure SockReqWSDataSent(Sender: TRtcConnection);
procedure SockReqWSDisconnect(Sender: TRtcConnection);
procedure btnIncomeClick(Sender: TObject);
procedure btnReconnectClick(Sender: TObject);
procedure btnCloseShiftClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
private
{ Private declarations }
procedure MemoAdd( i:Integer; s: String; obj:TObject);
procedure OpenShift();
public
{ Public declarations }
end;
var
MainFnWSTest: TMainFnWSTest;
implementation
{$R *.dfm}
procedure TMainFnWSTest.btnCloseShiftClick(Sender: TObject);
var
_params: ISuperObject;
_command: ISuperObject; checkPay: ISuperObject;
checkPayRow: ISuperObject;
checkTotal: ISuperObject;
list: ISuperObject;
begin
_command := SO('{}');
_command.S['command'] := 'closeShift';//'openShift';
// _command.O['params'] := _params;
Client.wSend(wf_Text,UTF8String(_command.AsJSon()));
end;
procedure TMainFnWSTest.btnIncomeClick(Sender: TObject);
var
_params: ISuperObject;
_command: ISuperObject; checkPay: ISuperObject;
checkPayRow: ISuperObject;
checkTotal: ISuperObject;
list: ISuperObject;
begin
_params := SO('{}');
checkTotal := SO('{}');
checkTotal.D['TOTALSUM']:=10;
_params.O['CHECKTOTAL']:= checkTotal;
checkPay := SA([]);
checkPayRow := SO('{}');
checkPayRow.I['ROWNUM'] := 1;
checkPayRow.S['PAYMENTFORM'] := 'ÃÎÒ²ÂÊÀ';
checkPayRow.D['SUM'] := 10.00;
checkPay.AsArray.Add(checkPayRow);
list := SO('{}');
list.O['LIST'] := checkPay;
_params.O['CHECKPAY']:= list;
_command := SO('{}');
_command.S['command'] := 'sendIncomeCheck';//'openShift';
_command.O['params'] := _params;
Client.wSend(wf_Text,UTF8String(_command.AsJSon()));
end;
procedure TMainFnWSTest.btnOpenClick(Sender: TObject);
begin
OpenShift;
end;
procedure TMainFnWSTest.btnReconnectClick(Sender: TObject);
begin
if not Client.isConnected then
begin
SockReq.client.Connect();
SockReq.Request.URI:='/Universal9Assist/eReceiptHandler';
SockReq.Request.WSUpgrade:=True;
SockReq.PostMethod();
end;
end;
procedure TMainFnWSTest.CheckClick(Sender: TObject);
var _params: ISuperObject;
_command: ISuperObject;
checkBody: ISuperObject;
checkBodyRow: ISuperObject;
checkTax: ISuperObject;
checkTaxRow: ISuperObject;
checkTotal: ISuperObject;
_obj: ISuperObject;
list: ISuperObject;
checkPay: ISuperObject;
checkPayRow: ISuperObject;
function getCheck():String;
var check: TRtcRecord;
_command:TRtcRecord;
begin
check := TRtcRecord.Create;
_command := TRtcRecord.Create;
try
check.NewRecord('CHECKTOTAL');
check.asRecord['CHECKTOTAL'].asFloat['TOTALSUM'] := 12;
//-------------------------------
check.NewArray('CHECKPAY');
check.asArray['CHECKPAY'].NewRecord(0);
// check.asArray['CHECKPAY'].AsRecord[0].asInteger['ROWNUM'] = 1;
check.asArray['CHECKPAY'].AsRecord[0].asInteger['PAYFORMCODE'] := 0;
check.asArray['CHECKPAY'].AsRecord[0].asFloat['SUM'] := 12;
check.asArray['CHECKPAY'].AsRecord[0].asFloat['SUMPROVIDED'] := 12;
{ check.asArray['CHECKPAY'].NewRecord(1);
check.asArray['CHECKPAY'].AsRecord[1].asInteger['PAYFORMCODE'] := 1;
check.asArray['CHECKPAY'].AsRecord[1].asFloat['SUM'] := 0;
}
//------------------------------- CHECKTAX
check.NewArray('CHECKTAX');
check.asArray['CHECKTAX'].NewRecord(0);
check.asArray['CHECKTAX'].AsRecord[0].asInteger['TYPE'] := 0;
check.asArray['CHECKTAX'].AsRecord[0].asString['NAME'] := 'ÏÄÂ';
check.asArray['CHECKTAX'].AsRecord[0].asString['LETTER'] := 'À';
check.asArray['CHECKTAX'].AsRecord[0].asFloat['PRC'] := 12;
check.asArray['CHECKTAX'].AsRecord[0].asFloat['TURNOVER'] := 12;
check.asArray['CHECKTAX'].AsRecord[0].asFloat['SUM'] := 2;
//------------------------------- CHECKBODY
check.NewArray('CHECKBODY');
check.asArray['CHECKBODY'].NewRecord(0);
check.asArray['CHECKBODY'].AsRecord[0].asString['NAME'] := 'Ïðîäóêò';
check.asArray['CHECKBODY'].AsRecord[0].asString['UNITNAME'] := 'êã';
check.asArray['CHECKBODY'].AsRecord[0].asFloat['AMOUNT'] := 2;
check.asArray['CHECKBODY'].AsRecord[0].asFloat['PRICE'] := 6;
check.asArray['CHECKBODY'].AsRecord[0].asFloat['COST'] := 12;
check.asArray['CHECKBODY'].AsRecord[0].asString['LETTERS'] := 'À';
_command.asString['command'] := 'sendCheck';
_command.NewRecord('params').asRecord['CHECK'] := check;
Client.wSend(wf_Text,UTF8String(_command.toJSon()));
Result := _command.toJSON;
finally
_command.Free;
check.Free;
end;
end;
begin
if not Client.isConnected then
begin
SockReq.client.Connect();
SockReq.Request.URI:='/Universal9Assist/eReceiptHandler';
SockReq.Request.WSUpgrade:=True;
SockReq.PostMethod();
end;
ShowMessage(getCheck);
Exit;
_params := SO('{}');
checkTotal := SO('{}');
checkTotal.D['TOTALSUM']:=10;
_params.O['CHECKTOTAL']:= checkTotal;
checkPay := SA([]);
checkPayRow := SO('{}');
checkPayRow.I['ROWNUM'] := 1;
checkPayRow.S['PAYMENTFORM'] := 'ÃÎÒ²ÂÊÀ';
checkPayRow.D['SUM'] := 10.00;
checkPay.AsArray.Add(checkPayRow);
checkPayRow := SO('{}');
checkPayRow.I['ROWNUM'] := 2;
checkPayRow.S['PAYMENTFORM'] := 'ÊÀÐÒÊÀ';
checkPayRow.D['SUM'] := 0.0;
checkPay.AsArray.Add(checkPayRow);
list := SO('{}');
list.O['LIST'] := checkPay;
_params.O['CHECKPAY']:= list;
// checkTaxRow := SO('{}');
// checkTaxRow.I['ROWNUM'] := 3;
// checkTaxRow.D['TAXPRC'] := 7.00;
// checkTax.AsArray.Add(checkTaxRow);
checkTax := SA([]);
checkTaxRow := SO('{}');
checkTaxRow.I['ROWNUM'] := 1;
checkTaxRow.D['TAXPRC'] := 20.00;
checkTaxRow.D['TAXSUM'] := 1.67;
checkTax.AsArray.Add(checkTaxRow);
list := SO('{}');
list.O['LIST'] := checkTax;
_params.O['CHECKTAX']:= list;
list := SO('{}');
list.O['LIST'] := checkPay;
_params.O['CHECKPAY']:= list;
checkBody := SA([]);
checkBodyRow := SO('{}');
checkBodyRow.I['ROWNUM'] := 1;
checkBodyRow.S['NAME'] := 'Êóðÿ÷å ñòåãíî';
checkBodyRow.S['UNITNAME'] := 'êã';
checkBodyRow.D['AMOUNT'] := 1;
checkBodyRow.D['PRICE'] := 10.00;
checkBodyRow.D['COST'] := 10.00;
checkBody.AsArray.add(checkBodyRow);
list := SO('{}');
list.O['LIST'] := checkBody;
_params.O['CHECKBODY']:= list;
// _params.O['CHECkPAY']:= _obj;
_command := SO('{}');
_command.S['command'] := 'sendCheck';//'openShift';
_command.O['params'] := _params;
// _command.I['requestId'] := 0;
Client.wSend(wf_Text,UTF8String(_command.AsJSon()));
end;
procedure TMainFnWSTest.FormCreate(Sender: TObject);
begin
SockReq.client.Connect();
SockReq.Request.URI:='/Universal9Assist/eReceiptHandler';
SockReq.Request.WSUpgrade:=True;
SockReq.PostMethod();
end;
procedure TMainFnWSTest.MemoAdd(i: Integer; s: String; obj: TObject);
begin
Memo1.Lines.Add(s);
end;
procedure TMainFnWSTest.OpenShift;
var v: TRtcRecord;
begin
v := tRtcRecord.Create;
v.asString['command'] := 'openShift';
v.NewRecord('params');
v.asRecord['params'].asString['CASHIER'] := 'Òåñò Ê.À.';
Client.wSend(wf_Text,UTF8String(v.toJSON()));
end;
procedure TMainFnWSTest.SockReqConnectLost(Sender: TRtcConnection);
begin
Memo1.Lines.Add('Connection Lost');
end;
procedure TMainFnWSTest.SockReqWSConnect(Sender: TRtcConnection);
begin
Memo1.Lines.Add('Connected');
end;
procedure TMainFnWSTest.SockReqWSDataIn(Sender: TRtcConnection);
begin
// Memo1.Lines.Add('<<<< in '+IntToStr(Sender.DataIn)+' <<--');
end;
procedure TMainFnWSTest.SockReqWSDataOut(Sender: TRtcConnection);
begin
//Memo1.Lines.Add('<<<< out '+IntToStr(Sender.DataOut)+' <<--');
end;
procedure TMainFnWSTest.SockReqWSDataReceived(Sender: TRtcConnection);
var
wf:TRtcWSFrame;
s:RtcString;
begin
wf:=Sender.wsFrameIn; // <- using the "Sender.FrameIn" property
if wf.wfStarted and (wf.wfOpcode=wf.waOpcode) then // Started receiving a new Frame set ...
Memo1.lines.Add('---> IN: '+wf.wfHeadInfo);
if wf.wfFinished and (wf.wfOpcode=wf_Text) and (wf.waPayloadLength<100000) then // short text message
begin
if wf.wfComplete then
begin
s:= (wf.wfRead); // <- reading Frame "Payload" data ...
Memo1.lines.add('IN ('+
IntToStr(wf.wfTotalInOut)+'/'+
IntToStr(wf.wfTotalLength)+') >>> '+
UTF8Decode(s));
end
else // if ws.Complete then // -> this would buffer everything received
begin
s:=wf.wfRead; // <- reading Frame "Payload" data ...
if wf.wfOpcode=wf_Text then
Memo1.lines.Add('IN ('+
IntToStr(wf.wfTotalInOut)+'/'+
IntToStr(wf.wfTotalLength)+') TXT >>> '+
s)
else
Memo1.lines.Add('IN ('+
IntToStr(wf.wfTotalInOut)+'/'+
IntToStr(wf.wfTotalLength)+') BIN ('+IntToStr(length(s))+') >>>');
end;
if wf.wfDone then // <- Frame Done (all read)
if wf.waFinal then // <- final Frame?
Memo1.lines.add('IN DONE, '+
IntToStr(wf.wfTotalInOut)+'/'+IntToStr(wf.wfTotalLength)+' bytes <-----')
else // More data shoud arrive in this next Frame ...
Memo1.lines.Add('<--- IN ... MORE --->'+wf.wfHeadInfo);
end;
end;
procedure TMainFnWSTest.SockReqWSDataSent(Sender: TRtcConnection);
var
wf:TRtcWSFrame;
bytes:int64;
data:RtcString;
begin
wf:=Sender.wsFrameOut;
{ If there is no Frame object, then this is just a notification
that all been was sent (Web Socket Frames sending queue is empty). }
if wf=nil then
MemoAdd(4,'---> ALL SENT <---', Sender)
{ We've used "ws-file" in Send() when sending files in a single Frame with "waPayloadLength" set }
else if wf.wfName='ws-file' then
begin
if wf.wfStarted then // <- we have NOT read any "Payload" data from this Frame yet ...
MemoAdd(2,'---> OUT: '+wf.wfHeadInfo,Sender);
if wf.wfDone then // <- Frame is done, no "Payload" data left to be read ...
MemoAdd(2,'OUT! '+
IntToStr(wf.wfPayloadInOut)+'/'+
IntToStr(wf.waPayloadLength)+' bytes <-----',Sender)
else
begin
MemoAdd(3,'SENT '+
IntToStr(wf.wfPayloadInOut)+'/'+
IntToStr(wf.waPayloadLength)+' bytes', Sender);
{ How many bytes do we have to send out in this Frame?
PayloadLength = Payload length of the current Frame,
PayloadInOut = Payload already read and sent }
bytes:=wf.waPayloadLength - wf.wfPayloadInOut;
{ Limit the number of bytes copied to sending buffers and sent out at once.
Using smaller buffers will slow down file transfer and use a bit more CPU,
but it also reduces the amount of RAM required per Client for sending files. }
if bytes>32*1024 then
bytes:=32*1024; // 32 KB is relatively small
// Read the next file chunk and add it to this Frames "PayLoad" for sending ...
wf.wfWriteEx( Read_FileEx(wf.asText['fname'], wf.wfPayloadInOut, bytes) );
if wf.wfComplete then // Payload complete, no more bytes can be added to this Frame ...
MemoAdd(3,'OUT Complete, '+IntToStr(wf.waPayloadLength)+' bytes', Sender);
end;
end
{ We've used "ws-multi" in Send() when sending files in multiple frames with "wfTotalLength" set }
else if wf.wfName='ws-multi' then
begin
if wf.wfDone then
MemoAdd(3,'OUT! '+wf.wfHeadInfo,Sender);
if wf.wfTotalInOut<wf.wfTotalLength then
begin
if wf.wfTotalInOut=0 then
MemoAdd(2,'---> OUT Start: '+IntToStr(wf.wfTotalLength)+' bytes --->',Sender);
{ How many bytes are left to be sent from the File?
wf.wfTotalLength = our file size (total bytes to send),
wf.wfTotalInOut = number of bytes already sent }
bytes:=wf.wfTotalLength - wf.wfTotalInOut;
{ Limit the number of bytes sent out at once. }
if bytes>8*1024 then
bytes:=8*1024; // using 8 KB here as an example
// Read the next file chunk and add it to this Frames "PayLoad" for sending ...
wf.wfWriteEx( Read_FileEx(wf.asText['fname'], wf.wfTotalInOut, bytes) );
MemoAdd(3,'SENT '+
IntToStr(wf.wfTotalInOut)+'/'+
IntToStr(wf.wfTotalLength)+' bytes', Sender);
end
else // File complete
MemoAdd(2,'OUT Complete: '+
IntToStr(wf.wfTotalInOut)+'/'+
IntToStr(wf.wfTotalLength)+' bytes <-----', Sender);
end
{ We've used "ws-chunks" in Send() when sending files in multiple chunks }
else if wf.wfName='ws-chunks' then
begin
if wf.wfDone then
MemoAdd(3,'OUT! '+wf.wfHeadInfo,Sender);
if not wf.wfFinished then
begin
if wf.wfTotalInOut=0 then
MemoAdd(2,'---> OUT Start: '+IntToStr(wf.asLargeInt['total'])+' bytes --->',Sender);
{ For demonstration purposes, we will NOT be checking the size of the file
being sent. Instead, we will try to read the next 16KB bytes from the file
in every "OnWSDataSent" event, until we get an empty string back as a result. }
data:=Read_File(wf.asText['fname'], wf.wfTotalInOut, 16*1024);
if length(data)>0 then
begin
// We have some content, send it out ...
wf.wfWrite(data);
MemoAdd(3,'SENT '+
IntToStr(wf.wfTotalInOut)+'/'+
IntToStr(wf.wfTotalLength)+' bytes', Sender);
end
else
begin
{ No content returned from Read_File, we need to set the "wfFinished"
flag to TRUE, so the last Frame will be sent out with "waFinal=TRUE". }
wf.wfFinished:=True;
MemoAdd(2,'OUT Complete: '+
IntToStr(wf.wfTotalInOut)+'/'+
IntToStr(wf.wfTotalLength)+' bytes <-----', Sender);
end;
end;
end
else if wf.wfName='' then // all Frames without a name ...
begin
if wf.wfStarted then
MemoAdd(2,'-=+> OUT: '+wf.wfHeadInfo, Sender);
MemoAdd(3,'SENT '+IntToStr(wf.wfPayloadInOut)+'/'+IntToStr(wf.waPayloadLength), Sender);
if wf.wfDone then
MemoAdd(2,'OUT! '+IntToStr(wf.waPayloadLength)+' bytes <+=---', Sender);
end;
end;
procedure TMainFnWSTest.SockReqWSDisconnect(Sender: TRtcConnection);
begin
Memo1.Lines.Add('disconnect');
Client.disconnect;
end;
end.
|
// ----------------------------------------------------------------------------
// Unit : PxFPC.pas - a part of PxLib
// Author : Matthias Hryniszak
// Date : 2005-03-28
// Version : 1.0
// Description : Freepascal - Delphi compatibility fucntions required by PxLib
// Changes log : 2005-03-28 - initial version
// ToDo : Testing.
// ----------------------------------------------------------------------------
unit PxFPC;
{$I PxDefines.inc}
interface
uses
Windows, SysUtils, SyncObjs;
{$IFDEF FPC}
type
TSimpleEvent = class (SyncObjs.TSimpleEvent)
procedure Acquire; override;
procedure Release; override;
end;
function SetServiceStatus(hServiceStatus: SERVICE_STATUS_HANDLE; var lpServiceStatus: TServiceStatus): BOOL; stdcall;
function QueryServiceStatus(hService: SC_HANDLE; var lpServiceStatus: TServiceStatus): BOOL; stdcall;
function StartServiceCtrlDispatcher(var lpServiceStartTable: TServiceTableEntry): BOOL; stdcall;
function FileSetDate(FileName: String; Age: Longint): Longint;
function TryStrToDate(const S: string; out Value: TDateTime): Boolean;
function TryStrToTime(const S: string; out Value: TDateTime): Boolean;
// missing imports..
function OleInitialize(pReserved: Pointer): HResult; external 'OLE32' name 'OleInitialize';
procedure OleUninitialize; external 'OLE32' name 'OleUninitialize';
{$ENDIF}
implementation
{$IFDEF FPC}
uses
RtlConsts;
{ TSimpleEvent }
procedure TSimpleEvent.Acquire;
begin
end;
procedure TSimpleEvent.Release;
begin
end;
{ *** }
function SetServiceStatus(hServiceStatus: SERVICE_STATUS_HANDLE; var lpServiceStatus: TServiceStatus): BOOL; stdcall;
begin
Result := Windows.SetServiceStatus(hServiceStatus, @lpServiceStatus);
end;
function QueryServiceStatus(hService: SC_HANDLE; var lpServiceStatus: TServiceStatus): BOOL; stdcall;
begin
Result := Windows.QueryServiceStatus(hService, @lpServiceStatus);
end;
function StartServiceCtrlDispatcher(var lpServiceStartTable: TServiceTableEntry): BOOL; stdcall;
begin
Result := Windows.StartServiceCtrlDispatcher(@lpServiceStartTable);
end;
function FileSetDate(FileName: String; Age: Longint): Longint;
var
H: THandle;
begin
H := FileOpen(FileName, 0);
Result := SysUtils.FileSetDate(H, Age);
FileClose(H);
end;
function TryStrToDate(const S: string; out Value: TDateTime): Boolean;
begin
try
Value := StrToDate(S);
Result := True;
except
Result := False;
end;
end;
function TryStrToTime(const S: string; out Value: TDateTime): Boolean;
begin
try
Value := StrToTime(S);
Result := True;
except
Result := False;
end;
end;
{$ENDIF}
end.
|
//------------------------------------------------------------------------------
//
// Voxelizer
// Copyright (C) 2021 by Jim Valavanis
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
//------------------------------------------------------------------------------
// Site : https://sourceforge.net/projects/voxelizer/
//------------------------------------------------------------------------------
unit vxl_gl;
interface
uses
Windows,
Graphics,
dglOpenGL,
models;
var
gld_max_texturesize: integer = 0;
gl_tex_format: integer = GL_RGBA8;
gl_tex_filter: integer = GL_LINEAR;
procedure glInit;
procedure ResetCamera;
procedure glBeginScene(const Width, Height: integer);
procedure glEndScene(dc: HDC);
procedure glRenderEnviroment;
procedure glRenderModel(const t: model_t);
type
TCDCamera = record
x, y, z: glfloat;
ax, ay, az: glfloat;
end;
var
camera: TCDCamera;
var
pt_rendredtriangles: integer = 0;
var
modeltexture: TGLuint = 0;
function gld_CreateTexture(const pic: TPicture; const transparent: boolean): TGLUint;
implementation
uses
SysUtils,
Classes,
Math,
vxl_utils,
vxl_defs;
procedure ResetCamera;
begin
camera.x := 0.0;
camera.y := -1.0;
camera.z := -4.0;
camera.ax := 0.0;
camera.ay := 0.0;
camera.az := 0.0;
end;
{------------------------------------------------------------------}
{ Initialise OpenGL }
{------------------------------------------------------------------}
procedure glInit;
begin
glClearColor(0.0, 0.0, 0.0, 0.0); // Black Background
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glClearDepth(1.0); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enable Depth Buffer
glDepthFunc(GL_LESS); // The Type Of Depth Test To Do
glEnable(GL_POINT_SIZE);
glGetIntegerv(GL_MAX_TEXTURE_SIZE, @gld_max_texturesize);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); //Realy Nice perspective calculations
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
end;
procedure infinitePerspective(fovy: GLdouble; aspect: GLdouble; znear: GLdouble);
var
left, right, bottom, top: GLdouble;
m: array[0..15] of GLdouble;
begin
top := znear * tan(fovy * pi / 360.0);
bottom := -top;
left := bottom * aspect;
right := top * aspect;
m[ 0] := (2 * znear) / (right - left);
m[ 4] := 0;
m[ 8] := (right + left) / (right - left);
m[12] := 0;
m[ 1] := 0;
m[ 5] := (2 * znear) / (top - bottom);
m[ 9] := (top + bottom) / (top - bottom);
m[13] := 0;
m[ 2] := 0;
m[ 6] := 0;
m[10] := -1;
m[14] := -2 * znear;
m[ 3] := 0;
m[ 7] := 0;
m[11] := -1;
m[15] := 0;
glMultMatrixd(@m);
end;
procedure glBeginScene(const Width, Height: integer);
begin
glDisable(GL_CULL_FACE);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
infinitePerspective(64.0, width / height, 0.01);
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity; // Reset The View
glTranslatef(camera.x, camera.y, camera.z);
glRotatef(camera.az, 0, 0, 1);
glRotatef(camera.ay, 0, 1, 0);
glRotatef(camera.ax, 1, 0, 0);
end;
procedure glEndScene(dc: HDC);
begin
SwapBuffers(dc); // Display the scene
end;
procedure glRenderEnviroment;
const
DRUNIT = 2.5;
DREPEATS = 10;
DWORLD = DREPEATS + 1;
var
i: integer;
begin
if opt_renderevniroment then
begin
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINES);
for i := -DREPEATS to DREPEATS do
begin
glVertex3f((DREPEATS + 1) * DRUNIT, 0.0, i * DRUNIT);
glVertex3f(-(DREPEATS + 1) * DRUNIT, 0.0, i * DRUNIT);
end;
for i := -DREPEATS to DREPEATS do
begin
glVertex3f(i * DRUNIT, 0.0, (DREPEATS + 1) * DRUNIT);
glVertex3f(i * DRUNIT, 0.0, -(DREPEATS + 1) * DRUNIT);
end;
glEnd;
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glColor3f(0.7, 0.7, 0.7);
glBegin(GL_QUADS);
glVertex3f(DWORLD * DRUNIT, -DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, 0.0, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, 0.0, -DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, 0.0, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, 0.0, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, 0.0, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, 0.0, DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, 0.0, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, 0.0, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DWORLD * DRUNIT, DWORLD * DRUNIT);
glEnd;
glDisable(GL_CULL_FACE);
glColor3f(0.1, 0.1, 0.2);
glBegin(GL_QUADS);
glVertex3f(DWORLD * DRUNIT, DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DRUNIT / 50, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DRUNIT / 50, -DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DRUNIT / 50, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DRUNIT / 50, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DRUNIT / 50, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DRUNIT / 50, DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, DWORLD * DRUNIT, -DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, -DRUNIT / 50, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, -DRUNIT / 50, DWORLD * DRUNIT);
glVertex3f(DWORLD * DRUNIT, DWORLD * DRUNIT, DWORLD * DRUNIT);
glVertex3f(-DWORLD * DRUNIT, DWORLD * DRUNIT, DWORLD * DRUNIT);
glEnd;
end;
end;
procedure glRenderFaces(const mVertCount, mFaceCount: integer;
const mVert: array of fvec5_t; const mFace: array of ivec3_t);
var
i: integer;
procedure _render_rover(const r: integer);
begin
glTexCoord2f(-mVert[r].u, -mVert[r].v);
glvertex3f(mVert[r].x, mVert[r].y, mVert[r].z);
end;
begin
glBegin(GL_TRIANGLES);
for i := 0 to mFaceCount - 1 do
begin
_render_rover(mFace[i].x);
_render_rover(mFace[i].y);
_render_rover(mFace[i].z);
end;
glEnd;
pt_rendredtriangles := pt_rendredtriangles + mFaceCount;
end;
procedure glRenderModel(const t: model_t);
begin
if opt_renderwireframe then
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE )
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL );
glColor4f(1.0, 1.0, 1.0, 1.0);
glEnable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glDisable(GL_ALPHA_TEST);
glBindTexture(GL_TEXTURE_2D, modeltexture);
pt_rendredtriangles := 0;
glRenderFaces(t.mVertCount, t.mFaceCount, t.mVert, t.mFace);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
end;
function RGBSwap(const l: LongWord): LongWord;
var
A: packed array[0..3] of byte;
tmp: byte;
begin
PLongWord(@A)^ := l;
tmp := A[0];
A[0] := A[2];
A[2] := tmp;
Result := PLongWord(@A)^;
end;
function gld_CreateTexture(const pic: TPicture; const transparent: boolean): TGLUint;
const
TEXTDIM = 256;
var
buffer, line: PLongWordArray;
bm: TBitmap;
i, j: integer;
dest: PLongWord;
begin
bm := TBitmap.Create;
bm.Width := TEXTDIM;
bm.Height := TEXTDIM;
bm.PixelFormat := pf32bit;
bm.Canvas.StretchDraw(Rect(0, 0, TEXTDIM, TEXTDIM), pic.Graphic);
GetMem(buffer, TEXTDIM * TEXTDIM * SizeOf(LongWord));
dest := @buffer[0];
for j := bm.Height - 1 downto 0 do
begin
line := bm.ScanLine[j];
for i := bm.Width - 1 downto 0 do
begin
dest^ := RGBSwap(line[i]);
inc(dest);
end;
end;
bm.Free;
if transparent then
for i := 0 to TEXTDIM * TEXTDIM - 1 do
if buffer[i] and $FFFFFF = 0 then
buffer[i] := 0
else
buffer[i] := buffer[i] or $FF000000;
glGenTextures(1, @Result);
glBindTexture(GL_TEXTURE_2D, Result);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
TEXTDIM, TEXTDIM,
0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
FreeMem(buffer, TEXTDIM * TEXTDIM * SizeOf(LongWord));
end;
end.
|
(*
@abstract(Contient des méthodes qui Fournissent l'état à la demande de toute touche appuyée sur le clavier.@br
Et un ensemble de fonctions pour travailler avec des codes de touches virtuelles.)
Notez que Windows mappe les boutons de la souris avec des codes de touches virtuelles et que vous
utiliser les fonctions / classes de cette unité pour vérifier également les boutons de la souris.@br
Reportez-vous à la section 'Codes Touches virtuelles' dans les révisions des programmeurs Win32 pour une liste de
constantes de code de touches (les constantes VK_ * sont déclarées dans l'unité 'Windows').
--------------------------------------------------------------------------------
@created(2018-05-04)
@author(J.Delauney)
Historique : @br
@unorderedList(
@item(04/05/2018 : Creation )
)
--------------------------------------------------------------------------------
@bold(Notes) :
--------------------------------------------------------------------------------
@bold(Dependances) : Aucune
--------------------------------------------------------------------------------
@bold(Credits :)@br
@unorderedList(
@item(J.Delauney (BeanzMaster))
)
--------------------------------------------------------------------------------
@bold(LICENCE) : MPL / LGPL
-------------------------------------------------------------------------------- *)
unit BZKeyboard;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\bzscene_options.inc}
//==============================================================================
interface
uses
lcltype, lclintf, classes
{$IFDEF MSWINDOWS}
,Windows
{$ENDIF}
{$IFDEF LINUX}
,x, xlib, KeySym
{$ENDIF}
{$IFDEF DARWIN}
{ fatal: 'not implemented yet' }
// Il semblerait qu'en utilisant "NSEvent" il soit possible d'intercepter les evenements clavier
// à la fois sous Carbon et Cocoa. Mais aucunes idées de comment implémenter ça.
// FPCMacOSAll
{$ENDIF};
//==============================================================================
type
{ Code d'une touche virtuelle }
TBZVirtualKeyCode = Integer;
{ Tampon de stockage, de l'état des touches pressées (code de 0 à 255) }
TBZKeyBufferState = array[0..255] of byte;
const
{ pseudo touche pour la roulette de la souris vers le haut (nous réaffectons la touche F23), voir "KeyboardNotifyWheelMoved" }
VK_MOUSEWHEELUP = VK_F23;
{ pseudo touche pour la roulette de la souris vers le bas (nous réaffectons la touche F23), voir "KeyboardNotifyWheelMoved" }
VK_MOUSEWHEELDOWN = VK_F24;
{ @abstract(Vérifie si la touche correspondant au "char" donné est appuyée.)
Le caractère est mappé sur le "clavier principal" uniquement, et non sur le clavier numérique.(virtuel) @br
Les combinaisons Shift / Ctrl / Alt qui peuvent être nécessaires pour taper les caractères spéciaux sont ignorés. @br
C'est à dire que 'a' équivaut à 'A' et sur mon clavier français '5' = '(' = '[' car ils ont tous le même Code de touche physique).}
function IsKeyDown(c : Char) : Boolean; overload;
{ Vérifie si la touche correspondant au "Code Virtuel" donné est appuyée. @br
Cette fonction est juste là pour englober "GetKeyState".}
function IsKeyDown(vk : TBZVirtualKeyCode) : Boolean; overload;
{ Renvoie la première touche enfoncée dont le code virtuelle est >= à minVkCode. @br
Si aucune touche n'est enfoncée, la valeur de retour est -1. Cette fonction n'attend PAS la saisie de l'utilisateur. @br
Si vous ne vous souciez pas de plusieurs pressions de touches, n'utilisez pas le paramètre. }
function KeyPressed(minVkCode : TBZVirtualKeyCode = 0) : TBZVirtualKeyCode;
{ Convertit un code de touche virtuel vers son nom
Le nom est exprimé à l'aide des paramètres locale de l'OS. }
function VirtualKeyCodeToKeyName(vk : TBZVirtualKeyCode) : String;
{ Convertit un nom de touche en son code virtuel.@br
La comparaison n'est PAS sensible à la casse. Si aucune correspondance n'est trouvée, retourne -1.@br
Le nom est exprimé à l'aide des paramètres locale de l'OS., sauf pour les boutons de la souris
qui sont traduits en 'LBUTTON', 'MBUTTON' et 'RBUTTON'.}
function KeyNameToVirtualKeyCode(const keyName : String) : TBZVirtualKeyCode;
{ Renvoie le code virtuel correspondant au caractère donné. @br
Le code renvoyé n'est pas traduit, exemple : 'a' et 'A' donneront le même résultat. @br
Une valeur de retour de -1 signifie que le caractère n'est peut être pas entré en utilisant le clavier physique.}
function CharToVirtualKeyCode(c : Char) : TBZVirtualKeyCode;
{ Utilisez cette procédure pour informer le mouvement de la roue de la souris
et simuler l'appui d'une touche (VK_MOUSEWHEELUP/VK_MOUSEWHEELDOWN), qui sera intercepté par IsKeyDown et/ou KeyPressed. @br
A placer dans les évènement OnMouseWheel des controles graphique (form, tpanel ect...)}
procedure KeyboardNotifyWheelMoved(wheelDelta : Integer);
{ @abstract(Renvoie le nombre de touche pressées silmutanément et le buffer contenant l'etat des touche.)
Example : @br
@longcode(#
HitKeyCount := GetBufferKeyState(Buffer);
if HitKeyCount>0 then
begin
if ((Buffer[VK_NUMPAD1] and $80) <> 0) and ((Buffer[VK_RSHIFT] and $80) <> 0) then inputkey := 1
else if ((Buffer[VK_NUMPAD2] and $80) <> 0) then inputkey := 2;
end;
#)}
function GetBufferKeyState(Var Buffer: TBZKeyBufferState):Byte;
//{$IFDEF LINUX}function VirtualKeyToXKeySym(Key: Word): TKeySym;{$ENDIF}
//==============================================================================
var
{ Variable globale du dernier état de la roulette de la souris }
vLastWheelDelta : Integer;
//==============================================================================
implementation
uses
SysUtils;
//==============================================================================
const
cLBUTTON = 'Left Mouse Button';
cMBUTTON = 'Middle Mouse Button';
cRBUTTON = 'Right Mouse Button';
cUP = 'Up';
cDOWN = 'Down';
cRIGHT = 'Right';
cLEFT = 'Left';
cPAGEUP = 'Page up';
cPAGEDOWN = 'Page down';
cHOME = 'Home';
cEND = 'End';
cMOUSEWHEELUP = 'Mouse Wheel Up';
cMOUSEWHEELDOWN = 'Mouse Wheel Down';
cPAUSE = 'Pause';
cSNAPSHOT = 'Print Screen';
cNUMLOCK = 'Num Lock';
cINSERT = 'Insert';
cDELETE = 'Delete';
cDIVIDE = 'Num /';
cLWIN = 'Left Win';
cRWIN = 'Right Win';
cAPPS = 'Application Key';
c0 = '~';
c1 = '[';
c2 = ']';
c3 = ';';
c4 = '''';
c5 = '<';
c6 = '>';
c7 = '/';
c8 = '\';
//c9 = '^';
{$IFDEF LINUX}
function VirtualKeyToXKeySym(Key: Word): TKeySym;
begin
case Key of
VK_BACK: Result := XK_BackSpace;
VK_TAB: Result := XK_Tab;
VK_CLEAR: Result := XK_Clear;
VK_RETURN: Result := XK_Return;
VK_SHIFT: Result := XK_Shift_L;
VK_CONTROL: Result := XK_Control_L;
VK_MENU: Result := XK_VoidSymbol; // alt key crashes app, XK_Alt_R;
VK_CAPITAL: Result := XK_Caps_Lock;
VK_ESCAPE: Result := XK_Escape;
VK_SPACE: Result := XK_space;
VK_PRIOR: Result := XK_Prior;
VK_NEXT: Result := XK_Next;
VK_END: Result := XK_End;
VK_HOME: Result := XK_Home;
VK_LEFT: Result := XK_Left;
VK_UP: Result := XK_Up;
VK_RIGHT: Result := XK_Right;
VK_DOWN: Result := XK_Down;
VK_SELECT: Result := XK_Select;
VK_PRINT: Result := XK_Print;
VK_EXECUTE: Result := XK_Execute;
VK_INSERT: Result := XK_Insert;
VK_DELETE: Result := XK_Delete;
VK_HELP: Result := XK_Help;
VK_0: Result := XK_0;
VK_1: Result := XK_1;
VK_2: Result := XK_2;
VK_3: Result := XK_3;
VK_4: Result := XK_4;
VK_5: Result := XK_5;
VK_6: Result := XK_6;
VK_7: Result := XK_7;
VK_8: Result := XK_8;
VK_9: Result := XK_9;
VK_A: Result := XK_a;
VK_B: Result := XK_b;
VK_C: Result := XK_c;
VK_D: Result := XK_d;
VK_E: Result := XK_e;
VK_F: Result := XK_f;
VK_G: Result := XK_g;
VK_H: Result := XK_h;
VK_I: Result := XK_i;
VK_J: Result := XK_j;
VK_K: Result := XK_k;
VK_L: Result := XK_l;
VK_M: Result := XK_m;
VK_N: Result := XK_n;
VK_O: Result := XK_o;
VK_P: Result := XK_p;
VK_Q: Result := XK_q;
VK_R: Result := XK_r;
VK_S: Result := XK_s;
VK_T: Result := XK_t;
VK_U: Result := XK_u;
VK_V: Result := XK_v;
VK_W: Result := XK_w;
VK_X: Result := XK_x;
VK_Y: Result := XK_y;
VK_Z: Result := XK_z;
VK_NUMPAD0: Result := XK_KP_0;
VK_NUMPAD1: Result := XK_KP_1;
VK_NUMPAD2: Result := XK_KP_2;
VK_NUMPAD3: Result := XK_KP_3;
VK_NUMPAD4: Result := XK_KP_4;
VK_NUMPAD5: Result := XK_KP_5;
VK_NUMPAD6: Result := XK_KP_6;
VK_NUMPAD7: Result := XK_KP_7;
VK_NUMPAD8: Result := XK_KP_8;
VK_NUMPAD9: Result := XK_KP_9;
VK_MULTIPLY: Result := XK_KP_Multiply;
VK_ADD: Result := XK_KP_Add;
VK_SEPARATOR: Result := XK_KP_Separator;
VK_SUBTRACT: Result := XK_KP_Subtract;
VK_DECIMAL: Result := XK_KP_Decimal;
VK_DIVIDE: Result := XK_KP_Divide;
VK_F1: Result := XK_F1;
VK_F2: Result := XK_F2;
VK_F3: Result := XK_F3;
VK_F4: Result := XK_F4;
VK_F5: Result := XK_F5;
VK_F6: Result := XK_F6;
VK_F7: Result := XK_F7;
VK_F8: Result := XK_F8;
VK_F9: Result := XK_F9;
VK_F10: Result := XK_F10;
VK_F11: Result := XK_F11;
VK_F12: Result := XK_F12;
VK_F13: Result := XK_F13;
VK_F14: Result := XK_F14;
VK_F15: Result := XK_F15;
VK_F16: Result := XK_F16;
VK_F17: Result := XK_F17;
VK_F18: Result := XK_F18;
VK_F19: Result := XK_F19;
VK_F20: Result := XK_F20;
VK_F21: Result := XK_F21;
VK_F22: Result := XK_F22;
VK_F23: Result := XK_F23;
VK_F24: Result := XK_F24;
VK_NUMLOCK: Result := XK_Num_Lock;
VK_SCROLL: Result := XK_Scroll_Lock;
else
Result := XK_VoidSymbol;
end;
end;
{$ENDIF}
function VirtualKeyCodeToKeyName(vk : TBZVirtualKeyCode) : String;
var
nSize : Integer;
begin
// Win32 API can't translate mouse button virtual keys to string
case vk of
VK_LBUTTON : Result:=cLBUTTON;
VK_MBUTTON : Result:=cMBUTTON;
VK_RBUTTON : Result:=cRBUTTON;
VK_UP : Result:=cUP;
VK_DOWN : Result:=cDOWN;
VK_LEFT : Result:=cLEFT;
VK_RIGHT : Result:=cRIGHT;
VK_PRIOR : Result:=cPAGEUP;
VK_NEXT : Result:=cPAGEDOWN;
VK_HOME : Result:=cHOME;
VK_END : Result:=cEND;
VK_MOUSEWHEELUP : Result:=cMOUSEWHEELUP;
VK_MOUSEWHEELDOWN : Result:=cMOUSEWHEELDOWN;
VK_PAUSE : Result := cPAUSE;
VK_SNAPSHOT : Result := cSNAPSHOT;
VK_NUMLOCK : Result := cNUMLOCK;
VK_INSERT : Result := cINSERT;
VK_DELETE : Result := cDELETE;
VK_DIVIDE : Result := cDIVIDE;
VK_LWIN : Result := cLWIN;
VK_RWIN : Result := cRWIN;
VK_APPS : Result := cAPPS;
192 : Result := c0;
219 : Result := c1;
221 : Result := c2;
186 : Result := c3;
222 : Result := c4;
188 : Result := c5;
190 : Result := c6;
191 : Result := c7;
220 : Result := c8;
// 221 : Result := c9;
else
begin
{$IFDEF MSWINDOWS}
nSize:=32; // should be enough
SetLength(Result, nSize);
vk:=MapVirtualKey(vk, 0);
nSize:=GetKeyNameText((vk and $FF) shl 16, PChar(Result), nSize);
SetLength(Result, nSize);
{$ELSE}
nSize:=32; // should be enough
SetLength(Result, nSize);
Result := XKeysymToString(VirtualKeyToXKeySym(vk));
{$ENDIF}
end;
end;
end;
function KeyNameToVirtualKeyCode(const keyName : String) : TBZVirtualKeyCode;
var
i : Integer;
begin
// ok, I admit this is plain ugly. 8)
Result:=-1;
for i:=0 to 255 do
begin
if SameText(VirtualKeyCodeToKeyName(i), keyName) then
begin
Result:=i;
Break;
end;
end;
end;
function GetBufferKeyState(Var Buffer: TBZKeyBufferState):Byte;
Var
iLoop, Count : Byte;
HitKey : SmallInt;
begin
Count := 0;
FillByte(Buffer,255,0);
For iLoop := 0 to 255 do
begin
HitKey := GetKeyState(iLoop);
if HitKey<>0 then
begin
Buffer[iLoop]:=HitKey;
inc(Count);
End;
Result:=Count;
End;
End;
function KeyPressed(minVkCode : TBZVirtualKeyCode = 0) : TBZVirtualKeyCode;
var
i : Integer;
buf : TBZKeyBufferState;
begin
Result:=-1;
//FillByte(Buf,255,0);
if GetBufferKeyState({%H-}Buf)>0 then
begin
for i:=minVkCode to 255 do
begin
if (buf[i] and $80)<>0 then
begin
Result:=i;
Exit;
end;
end;
End;
if vLastWheelDelta<>0 then
begin
if vLastWheelDelta>0 then Result:=VK_MOUSEWHEELUP
else Result:=VK_MOUSEWHEELDOWN;
//vLastWheelDelta:=0;
end;
//if ((Buffer[VK_NUMPAD1] and $80) <> 0) then
//inputkey := 1
//else if ((Buffer[VK_NUMPAD2] and $80) <> 0) then
//inputkey := 2
End;
function IsKeyDown(C:Char):Boolean;
begin
c := UpperCase(c)[1];
Result := GetKeyState(Ord(c)) < 0;
End;
function IsKeyDown(vk : TBZVirtualKeyCode) : Boolean;
begin
case vk of
VK_MOUSEWHEELUP:
begin
Result := vLastWheelDelta > 0;
if Result then
vLastWheelDelta := 0;
end;
VK_MOUSEWHEELDOWN:
begin
Result := vLastWheelDelta < 0;
if Result then
vLastWheelDelta := 0;
end;
else
Result := GetKeyState(vk) < 0;
end;
end;
procedure KeyboardNotifyWheelMoved(wheelDelta : Integer);
begin
vLastWheelDelta:=wheelDelta;
end;
function CharToVirtualKeyCode(c : Char) : TBZVirtualKeyCode;
begin
{$IFDEF MSWINDOWS}
Result:=VkKeyScan(c) and $FF;
if Result=$FF then Result:=-1;
{$ELSE}
c := UpperCase(c)[1];
Result := Ord(c);
{$ENDIF}
end;
//==============================================================================
initialization
finalization
//==============================================================================
end.
|
PROGRAM Prime(INPUT, OUTPUT);
CONST
Min = 2;
Max = 100;
TYPE
SetType = SET OF Min .. Max;
VAR
Sieve: SetType;
PROCEDURE ScreeningSieve(VAR Sieve: SetType); //Divider делитель
VAR //Counter счётчик
Counter, Divider: INTEGER;
BEGIN {ScreeningSieve}
Divider := Min;
WHILE (Divider * Divider) <= Max
DO
BEGIN
Counter := Divider;
{WHILE Counter <= (Max DIV Divider)
DO
BEGIN
IF Counter IN Sieve = true
THEN
INC(Counter);
END;}
FOR Counter := Divider TO Max DIV Divider
DO
Sieve := Sieve - [Counter*Divider];
INC(Divider)
END
END; {ScreeningSieve}
PROCEDURE PrintSieve(VAR Sieve: SetType);
VAR
Counter: INTEGER;
BEGIN {PrintSieve}
Counter := Min;
WHILE Counter <= Max
DO
BEGIN
IF Counter IN Sieve
THEN
WRITE(Counter :3);
INC(Counter)
END;
WRITELN
END; {PrintSieve}
BEGIN {Prime}
Sieve := [Min .. Max];
ScreeningSieve(Sieve);
PrintSieve(Sieve)
END. {Prime}
|
unit untCalcularImpostoExercicio2Test;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, untCalcularImpostoExercicio2, Generics.Collections, untDependente,
untFuncionario;
type
// Test methods for class TCalcularImpostoExercicio2
TestTCalcularImpostoExercicio2 = class(TTestCase)
strict private
FCalcularImpostoExercicio2: TCalcularImpostoExercicio2;
private
procedure prPrepararFuncionario(const pFuncionario: TFuncionario);
procedure prPrepararListaDependente(const pFuncionario: TFuncionario);
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure fcRetornarValorIRTest;
procedure fcRetornarValorINSSTest;
end;
implementation
procedure TestTCalcularImpostoExercicio2.prPrepararFuncionario(const pFuncionario: TFuncionario);
begin
pFuncionario.Id_Funcionario := 1;
pFuncionario.Salario := 1000;
prPrepararListaDependente(pFuncionario);
end;
procedure TestTCalcularImpostoExercicio2.prPrepararListaDependente(const pFuncionario: TFuncionario);
var
vDependenteAux: TDependente;
begin
vDependenteAux := TDependente.Create;
vDependenteAux.Id_Dependente := 1;
vDependenteAux.IsCalcularIR := 1;
vDependenteAux.IsCalcularINSS := 1;
pFuncionario.ListaDependentes.Add(vDependenteAux);
vDependenteAux := TDependente.Create;
vDependenteAux.Id_Dependente := 2;
vDependenteAux.IsCalcularIR := 1;
vDependenteAux.IsCalcularINSS := 0;
pFuncionario.ListaDependentes.Add(vDependenteAux);
vDependenteAux := TDependente.Create;
vDependenteAux.Id_Dependente := 3;
vDependenteAux.IsCalcularIR := 0;
vDependenteAux.IsCalcularINSS := 1;
pFuncionario.ListaDependentes.Add(vDependenteAux);
end;
procedure TestTCalcularImpostoExercicio2.SetUp;
begin
FCalcularImpostoExercicio2 := TCalcularImpostoExercicio2.Create;
end;
procedure TestTCalcularImpostoExercicio2.TearDown;
begin
FCalcularImpostoExercicio2.Free;
FCalcularImpostoExercicio2 := nil;
end;
procedure TestTCalcularImpostoExercicio2.fcRetornarValorIRTest;
var
ReturnValue: Double;
vFuncionario: TFuncionario;
begin
vFuncionario := TFuncionario.Create;
prPrepararFuncionario(vFuncionario);
// TODO: Setup method call parameters
ReturnValue := FCalcularImpostoExercicio2.fcRetornarValorIR(vFuncionario);
// TODO: Validate method results
CheckEquals(120,ReturnValue,'Valor incorreto para o cálculo de IR.');
end;
procedure TestTCalcularImpostoExercicio2.fcRetornarValorINSSTest;
var
ReturnValue: Double;
vFuncionario: TFuncionario;
begin
vFuncionario := TFuncionario.Create;
prPrepararFuncionario(vFuncionario);
// TODO: Setup method call parameters
ReturnValue := FCalcularImpostoExercicio2.fcRetornarValorINSS(vFuncionario);
// TODO: Validate method results
CheckEquals(80,ReturnValue,'Valor incorreto para o cálculo do INSS.');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTCalcularImpostoExercicio2.Suite);
end.
|
unit Blur;
interface
uses
Windows, Graphics, Forms, ComCtrls, LibGfl,
cxLookAndFeelPainters, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxSpinEdit, ActnList, cxButtons, RzTrkBar, Controls, Classes,
ExtCtrls, StdCtrls;
type
TfrmBlur = class(TForm)
PreViewImage: TImage;
Panel1: TPanel;
Panel3: TPanel;
tbBlur: TRzTrackBar;
mbCancel: TcxButton;
mbOk: TcxButton;
ActionList1: TActionList;
ActionOk: TAction;
seBlur: TcxSpinEdit;
Label1: TLabel;
Panel2: TPanel;
Label2: TLabel;
tbSharpen: TRzTrackBar;
seSharpen: TcxSpinEdit;
procedure ActionOkExecute(Sender: TObject);
procedure CreateBMP;
procedure tbBlurChange(Sender: TObject);
procedure seBlurClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure tbSharpenChange(Sender: TObject);
procedure seSharpenClick(Sender: TObject);
private
FClonBitmap: PGFL_BITMAP;
FSharpen: Integer;
FBlur: Integer;
FOriginalBMP: PGFL_BITMAP;
Fhbmp: HBitmap;
procedure ApplyUpdates;
function CalSize(var X, Y: Integer; ASize: Integer): Boolean;
procedure SetBlur(const Value: Integer);
procedure SetSharpen(const Value: Integer);
procedure SetOriginalBMP(const Value: PGFL_BITMAP);
procedure Sethbmp(const Value: HBitmap);
public
property Blur: Integer read FBlur write SetBlur;
property Sharpen: Integer read FSharpen write SetSharpen;
property OriginalBMP: PGFL_BITMAP read FOriginalBMP write SetOriginalBMP;
property hbmp: HBitmap read Fhbmp write Sethbmp;
end;
function GetBlurForm(var Sharpen, Blur: Integer; gfl_bmp: PGFL_BITMAP): Integer;
implementation
//uses mainFrm;
{$R *.dfm}
function GetBlurForm(var Sharpen, Blur: Integer; gfl_bmp: PGFL_BITMAP): Integer;
var
BlurForm: TfrmBlur;
begin
BlurForm := TfrmBlur.Create(Application);
try
BlurForm.OriginalBMP := gfl_bmp;
BlurForm.CreateBMP;
Result := BlurForm.ShowModal;
if Result = mrOK then
begin
Blur := BlurForm.Blur;
Sharpen := BlurForm.tbSharpen.Position;
end;
finally
BlurForm.Free;
end;
end;
function TfrmBlur.CalSize(var X, Y: Integer; ASize: Integer): Boolean;
var
k: Extended;
begin
k := OriginalBMP.Width / OriginalBMP.Height;
if k >= 1 then
begin
X := ASize;
Y := Trunc(ASize / k);
end
else
begin
X := Trunc(ASize * k);
Y := ASize;
end;
Result := ((OriginalBMP.Width > X) and (OriginalBMP.Height > Y));
end;
procedure TfrmBlur.ApplyUpdates;
var
i: Integer;
pvbBitmap: PGFL_BITMAP;
begin
seBlur.Value := Blur;
tbBlur.Position := Blur;
seSharpen.Value := Sharpen;
tbSharpen.Position := Sharpen;
pvbBitmap := gflCloneBitmap(FClonBitmap);
// if tbBlur.Position > 0 then
// for i := 1 to Blur do
gflBlur(pvbBitmap, nil, Blur);
//gflSharpen(pvbBitmap, nil, Sharpen);
hbmp := CreateBitmap(pvbBitmap.Width, pvbBitmap.Height, pvbBitmap.ColorUsed, pvbBitmap.BitsPerComponent, nil);
gflConvertBitmapIntoDDB(pvbBitmap, Fhbmp);
PreViewImage.Picture.Bitmap.Handle := hbmp;
gflFreeBitmap(pvbBitmap);
end; // procedure ApplyUpdates
procedure TfrmBlur.ActionOkExecute(Sender: TObject);
begin
mbOk.SetFocus;
ModalResult := mrOK;
end;
procedure TfrmBlur.CreateBMP;
var
W, H: Integer;
begin
FClonBitmap := gflCloneBitmap(OriginalBMP);
CalSize(W, H, PreViewImage.Width);
Panel1.DoubleBuffered := True;
gflResize(FClonBitmap, nil, W, H, GFL_RESIZE_BILINEAR, 0);
ApplyUpdates;
end;
procedure TfrmBlur.tbBlurChange(Sender: TObject);
begin
Blur := tbBlur.Position;
ApplyUpdates;
end;
procedure TfrmBlur.seBlurClick(Sender: TObject);
begin
Blur := seBlur.Value;
ApplyUpdates;
end;
procedure TfrmBlur.FormDestroy(Sender: TObject);
begin
DeleteObject(hbmp);
gflFreeBitmap(FClonBitmap);
end;
procedure TfrmBlur.SetBlur(const Value: Integer);
begin
FBlur := Value;
ApplyUpdates;
end;
procedure TfrmBlur.SetSharpen(const Value: Integer);
begin
FSharpen := Value;
ApplyUpdates;
end;
procedure TfrmBlur.tbSharpenChange(Sender: TObject);
begin
Sharpen := tbSharpen.Position;
ApplyUpdates;
end;
procedure TfrmBlur.seSharpenClick(Sender: TObject);
begin
Sharpen := seSharpen.Value;
ApplyUpdates;
end;
procedure TfrmBlur.SetOriginalBMP(const Value: PGFL_BITMAP);
begin
FOriginalBMP := Value;
end;
procedure TfrmBlur.Sethbmp(const Value: HBitmap);
begin
Fhbmp := Value;
end;
end.
|
unit PluginManager;
interface
uses
{$IFDEF DELPHIXE3_LVL}
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.ExtCtrls,
{$ELSE}
Windows,
SysUtils,
Classes,
Graphics,
ExtCtrls,
Dialogs,
{$ENDIF }
Helpers,
Forms,
uObjects,
uConstsProg,
sLabel;
type
EPluginManagerError = class(Exception);
EPluginLoadError = class(EPluginManagerError);
EDuplicatePluginError = class(EPluginLoadError);
EPluginsLoadError = class(EPluginLoadError)
private
FItems: TStrings;
public
constructor Create(const AText: String; const AFailedPlugins: TStrings);
destructor Destroy; override;
property FailedPluginFileNames: TStrings read FItems;
end;
IPlugin = interface
// protected
function GetIndex: Integer;
function GetHandle: HMODULE;
function GetIcon: TIcon;
procedure DestroyIcon;
function GetFileName: String;
function GetID: TGUID;
function GetName: String;
function GetVersion: String;
function GetAuthorName: String;
function GetEmailAuthor: String;
function GetSiteAuthor: String;
function GetIndexIcon: Integer;
procedure SetIndexIcon(i: Integer);
function GetUpdatedIcons: Boolean;
procedure SetUpdatedIcons(Value: Boolean);
function GetUpdatedActive: Boolean;
procedure SetUpdatedActive(Value: Boolean);
function GetUpdatedPremium: Boolean;
procedure SetUpdatedPremium(Value: Boolean);
function GetOptionsIndexIcon: Integer;
procedure SetOptionsIndexIcon(Value: Integer);
function GetGetedGraphRating: Boolean;
procedure SetGetedGraphRating(Value: Boolean);
function GetImageGraphRating: TImage;
procedure SetImageGraphRating(Value: TImage);
function GetPanelStatistic: TPanel;
procedure SetPanelStatistic(Value: TPanel);
function GetPanelInfoRank: TPanel;
procedure SetPanelInfoRank(Value: TPanel);
function GetGlobalRank: String;
procedure SetGlobalRank(Value: String);
function GetGlobalRankLabel: TsLabelFX;
procedure SetGlobalRankLabel(Value: TsLabelFX);
function GetPictureRatings: TMemoryStream;
procedure SetPictureRatings(Value: TMemoryStream);
function GetTaskIndexIcon: Integer;
procedure SetTaskIndexIcon(Value: Integer);
function GetItemIndex: Integer;
procedure SetItemIndex(Value: Integer);
function GetSalePremIndexIcon: Integer;
procedure SetSalePremIndexIcon(Value: Integer);
function GetMask: String;
function GetDescription: String;
function GetFilterIndex: Integer;
procedure SetFilterIndex(const AValue: Integer);
// public
property Index: Integer read GetIndex;
property Handle: HMODULE read GetHandle;
property FileName: String read GetFileName;
property ID: TGUID read GetID;
property Name: String read GetName;
property Version: String read GetVersion;
property AuthorName: String read GetAuthorName;
property EmailAuthor: String read GetEmailAuthor;
property SiteAuthor: String read GetSiteAuthor;
property Icon: TIcon read GetIcon;
property IndexIcon: Integer read GetIndexIcon write SetIndexIcon;
property UpdatedIcons: Boolean read GetUpdatedIcons write SetUpdatedIcons;
property UpdatedActive: Boolean read GetUpdatedActive
write SetUpdatedActive;
property UpdatedPremium: Boolean read GetUpdatedPremium
write SetUpdatedPremium;
property OptionsIndexIcon: Integer read GetOptionsIndexIcon
write SetOptionsIndexIcon;
property GetedGraphRating: Boolean read GetGetedGraphRating
write SetGetedGraphRating;
property ImageGraphRating: TImage read GetImageGraphRating
write SetImageGraphRating;
property PanelStatistic: TPanel read GetPanelStatistic
write SetPanelStatistic;
property PanelInfoRank: TPanel read GetPanelInfoRank write SetPanelInfoRank;
property GlobalRank: string read GetGlobalRank write SetGlobalRank;
property GlobalRankLabel: TsLabelFX read GetGlobalRankLabel
write SetGlobalRankLabel;
property PictureRatings: TMemoryStream read GetPictureRatings
write SetPictureRatings;
property TaskIndexIcon: Integer read GetTaskIndexIcon
write SetTaskIndexIcon;
property ItemIndex: Integer read GetItemIndex write SetItemIndex;
property SalePremIndexIcon: Integer read GetSalePremIndexIcon
write SetSalePremIndexIcon;
property Mask: String read GetMask;
property Description: String read GetDescription;
property FilterIndex: Integer read GetFilterIndex write SetFilterIndex;
end;
IServiceProvider = interface
function CreateInterface(const APlugin: IPlugin; const AIID: TGUID;
out Intf): Boolean;
end;
IProvider = interface(IServiceProvider)
procedure Delete;
end;
IPluginManager = interface
// protected
function GetItem(const AIndex: Integer): IPlugin;
function GetCount: Integer;
// public
function LoadPlugin(const AFileName: String): IPlugin;
procedure UnloadPlugin(const AIndex: Integer);
procedure LoadPlugins(const AFolder: String; const AFileExt: String = '');
procedure Ban(const AFileName: String);
procedure Unban(const AFileName: String);
procedure SaveSettings(const ARegPath: String);
procedure LoadSettings(const ARegPath: String);
property Items[const AIndex: Integer]: IPlugin read GetItem; default;
property Count: Integer read GetCount;
function IndexOf(const AID: TGUID): Integer;
procedure DoLoaded;
procedure UnloadAll;
procedure ProvidersListCreate;
procedure SetVersion(const AVersion: Integer);
procedure RegisterServiceProvider(const AProvider: IServiceProvider);
end;
TBasicProvider = class(TCheckedInterfacedObject, IUnknown, IServiceProvider,
IProvider)
private
FManager: IPluginManager;
FPlugin: PluginManager.IPlugin;
protected
// IUnknown
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
// IServiceProvider
function CreateInterface(const APlugin: IPlugin; const AIID: TGUID;
out Intf): Boolean; virtual;
// IProvider
procedure Delete;
public
constructor Create(const AManager: IPluginManager;
const APlugin: PluginManager.IPlugin);
property Manager: IPluginManager read FManager;
property Plugin: PluginManager.IPlugin read FPlugin;
end;
function Plugins: IPluginManager;
implementation
uses
{$IFDEF DELPHIXE3_LVL}
System.Win.Registry,
{$ELSE}
Registry,
{$ENDIF }
uProcedures,
PluginAPI;
resourcestring
rsPluginsLoadError = 'One or more plugins has failed to load:' +
sLineBreak + '%s';
rsDuplicatePlugin = 'Plugin is already loaded.' + sLineBreak +
'ID: %s; Name: %s;' + sLineBreak + 'File name 1: %s' + sLineBreak +
'File name 2: %s';
type
IProviderManager = interface
['{799F9F9F-9030-43B1-B184-0950962B09A5}']
procedure RegisterProvider(const AProvider: IProvider);
end;
// TPlugin = class;
TPluginManager = class(TCheckedInterfacedObject, IUnknown, IPluginManager)
private
FItems: array of IPlugin;
FCount: Integer;
FBanned: TStringList;
FVersion: Integer;
FProviders: TInterfaceList;
protected
function CreateInterface(const APlugin: PluginManager.IPlugin;
const AIID: TGUID; out Intf): Boolean;
// PluginManager.IPluginManager
function GetItem(const AIndex: Integer): PluginManager.IPlugin;
function GetCount: Integer;
function CanLoad(const AFileName: String): Boolean;
procedure SetVersion(const AVersion: Integer);
procedure RegisterServiceProvider(const AProvider: IServiceProvider);
// ICore
function GetVersion: Integer;
public
constructor Create;
destructor Destroy; override;
property Count: Integer read GetCount;
property Items[const AIndex: Integer]: PluginManager.IPlugin
read GetItem; default;
// PluginManager.IPluginManager
function LoadPlugin(const AFileName: String): IPlugin;
procedure UnloadPlugin(const AIndex: Integer);
procedure LoadPlugins(const AFolder, AFileExt: String);
function IndexOf(const APlugin: IPlugin): Integer; overload;
function IndexOf(const AID: TGUID): Integer; overload;
procedure Ban(const AFileName: String);
procedure Unban(const AFileName: String);
procedure SaveSettings(const ARegPath: String);
procedure LoadSettings(const ARegPath: String);
procedure UnloadAll;
procedure DoLoaded;
procedure ProvidersListCreate;
end;
TPlugin = class(TCheckedInterfacedObject, IUnknown, IPlugin, IProviderManager,
IDestroyNotify, IPlugins, ICore)
private
FManager: TPluginManager;
FFileName: String;
FHandle: HMODULE;
FIconPlugin: TIcon;
FIndexIcon: Integer;
FUpdatedIcons: Boolean;
FUpdatedActive: Boolean;
FUpdatedPremium: Boolean;
FOptionsIndexIcon: Integer;
FGetedGraphRating: Boolean;
FImageGraphRating: TImage;
FPanelStatistic: TPanel;
FPanelInfoRank: TPanel;
FGlobalRank: String;
FGlobalRankLabel: TsLabelFX;
FPictureRatings: TMemoryStream;
FTaskIndexIcon: Integer;
FItemIndex: Integer;
FSalePremIndexIcon: Integer;
FInit: TInitPluginFunc;
FDone: TDonePluginFunc;
FFilterIndex: Integer;
FPlugin: PluginAPI.IPlugin;
FID: TGUID;
FName: String;
FVersion: String;
FAuthorName: String;
FEmailAuthor: String;
FSiteAuthor: String;
FPluginType: Integer;
FInfoRetrieved: Boolean;
FMask: String;
FDescription: String;
FProviders: array of IProvider;
procedure GetInfo;
procedure ReleasePlugin;
procedure ReleaseProviders;
protected
function CreateInterface(const AIID: TGUID; out Intf): Boolean;
// IUnknown
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
// IPlugin
function GetFileName: String;
function GetID: TGUID;
function GetName: String;
function GetVersion: String;
function GetAuthorName: String;
function GetEmailAuthor: String;
function GetSiteAuthor: String;
function GetIndex: Integer;
function GetHandle: HMODULE;
function GetIcon: TIcon;
procedure DestroyIcon;
function GetIndexIcon: Integer;
procedure SetIndexIcon(i: Integer);
function GetUpdatedIcons: Boolean;
procedure SetUpdatedIcons(Value: Boolean);
function GetUpdatedActive: Boolean;
procedure SetUpdatedActive(Value: Boolean);
function GetUpdatedPremium: Boolean;
procedure SetUpdatedPremium(Value: Boolean);
function GetOptionsIndexIcon: Integer;
procedure SetOptionsIndexIcon(Value: Integer);
function GetGetedGraphRating: Boolean;
procedure SetGetedGraphRating(Value: Boolean);
function GetImageGraphRating: TImage;
procedure SetImageGraphRating(Value: TImage);
function GetPanelStatistic: TPanel;
procedure SetPanelStatistic(Value: TPanel);
function GetPanelInfoRank: TPanel;
procedure SetPanelInfoRank(Value: TPanel);
function GetGlobalRank: String;
procedure SetGlobalRank(Value: String);
function GetGlobalRankLabel: TsLabelFX;
procedure SetGlobalRankLabel(Value: TsLabelFX);
function GetPictureRatings: TMemoryStream;
procedure SetPictureRatings(Value: TMemoryStream);
function GetTaskIndexIcon: Integer;
procedure SetTaskIndexIcon(Value: Integer);
function GetItemIndex: Integer;
procedure SetItemIndex(Value: Integer);
function GetSalePremIndexIcon: Integer;
procedure SetSalePremIndexIcon(Value: Integer);
function GetMask: String;
function GetDescription: String;
function GetFilterIndex: Integer;
procedure SetFilterIndex(const AValue: Integer);
// ICore
function GetCoreVersion: Integer; safecall;
function ICore.GetVersion = GetCoreVersion;
// IPlugins
function GetCount: Integer; safecall;
function GetPlugin(const AIndex: Integer): PluginAPI.IPlugin; safecall;
// IProviderManager
procedure RegisterProvider(const AProvider: IProvider);
// IDestroyNotify
procedure Delete; safecall;
public
constructor Create(const APluginManger: TPluginManager;
const AFileName: String); virtual;
destructor Destroy; override;
end;
{ TPluginManager }
constructor TPluginManager.Create;
begin
OutputDebugString('TPluginManager.Create');
SetName('TPluginManager');
inherited Create;
FBanned := TStringList.Create;
FProviders := TInterfaceList.Create;
SetVersion(1);
end;
destructor TPluginManager.Destroy;
begin
OutputDebugString('TPluginManager.Destroy');
UnloadAll;
FreeAndNil(FProviders);
FreeAndNil(FBanned);
inherited;
end;
procedure TPluginManager.DoLoaded;
var
X: Integer;
LoadNotify: ILoadNotify;
begin
for X := 0 to GetCount - 1 do
if Supports(Plugins[X], ILoadNotify, LoadNotify) then
LoadNotify.Loaded;
end;
function TPluginManager.LoadPlugin(const AFileName: String): IPlugin;
begin
if CanLoad(AFileName) then
begin
Result := nil;
Exit;
end;
// Загружаем плагин
try
Result := TPlugin.Create(Self, AFileName);
except
on E: Exception do
raise EPluginLoadError.Create
(Format('[%s] %s', [E.ClassName, E.Message]));
end;
// Заносим в список
if Length(FItems) <= FCount then // "Capacity"
SetLength(FItems, Length(FItems) + 64);
FItems[FCount] := Result;
Inc(FCount);
end;
procedure TPluginManager.LoadPlugins(const AFolder, AFileExt: String);
var
Path: String;
sr: TSearchRec;
Failures: TStringList;
FailedPlugins: TStringList;
function PluginOK(const APluginName, AFileExt: String): Boolean;
begin
Result := (AFileExt = '');
if Result then
Exit;
Result := SameFileName(ExtractFileExt(APluginName), AFileExt);
end;
begin
Path := IncludeTrailingPathDelimiter(AFolder);
Sleep(100);
Failures := TStringList.Create;
FailedPlugins := TStringList.Create;
try
if FindFirst(Path + '*.*', 0, sr) = 0 then
try
repeat
if ((sr.Attr and faDirectory) = 0) and PluginOK(sr.Name, AFileExt)
then
begin
try
LoadPlugin(Path + sr.Name);
except
on E: Exception do
begin
FailedPlugins.Add(sr.Name);
Failures.Add(Format('%s: %s', [sr.Name, E.Message]));
end;
end;
end;
Application.ProcessMessages;
until FindNext(sr) <> 0;
finally
FindClose(sr);
end;
if Failures.Count > 0 then
raise EPluginsLoadError.Create(Format(rsPluginsLoadError, [Failures.Text]
), FailedPlugins);
finally
FreeAndNil(FailedPlugins);
FreeAndNil(Failures);
end;
end;
procedure TPluginManager.ProvidersListCreate;
begin
if not Assigned(FProviders) then
FProviders := TInterfaceList.Create;
end;
procedure TPluginManager.UnloadAll;
procedure NotifyRelease;
var
X: Integer;
Notify: IDestroyNotify;
begin
for X := FCount - 1 downto 0 do // for X := 0 to FCount - 1 do
begin
if Supports(FItems[X], IDestroyNotify, Notify) then
Notify.Delete;
end;
end;
begin
NotifyRelease;
FCount := 0;
Finalize(FItems);
FreeAndNil(FProviders);
end;
procedure TPluginManager.UnloadPlugin(const AIndex: Integer);
var
X: Integer;
Notify: IDestroyNotify;
begin
FItems[AIndex] := nil;
// Сдвинуть плагины в списке, чтобы закрыть "дырку"
for X := AIndex to FCount - 1 do
FItems[X] := FItems[X + 1];
// Не забыть учесть последний
FItems[FCount - 1] := nil;
Dec(FCount);
end;
function TPluginManager.IndexOf(const APlugin: IPlugin): Integer;
begin
Result := IndexOf(APlugin.ID);
end;
function TPluginManager.IndexOf(const AID: TGUID): Integer;
var
X: Integer;
ID: TGUID;
begin
Result := -1;
for X := 0 to FCount - 1 do
begin
ID := FItems[X].ID;
if CompareMem(@ID, @AID, SizeOf(TGUID)) then
begin
Result := X;
Break;
end;
end;
end;
procedure TPluginManager.Ban(const AFileName: String);
begin
Unban(AFileName);
FBanned.Add(AFileName);
end;
procedure TPluginManager.Unban(const AFileName: String);
var
X: Integer;
begin
for X := 0 to FBanned.Count - 1 do
if SameFileName(FBanned[X], AFileName) then
begin
FBanned.Delete(X);
Break;
end;
end;
function TPluginManager.CanLoad(const AFileName: String): Boolean;
var
X: Integer;
begin
// Не грузить отключенные
for X := 0 to FBanned.Count - 1 do
if SameFileName(FBanned[X], AFileName) then
begin
Result := true;
Exit;
end;
// Не грузить уже загруженные
for X := 0 to FCount - 1 do
if SameFileName(FItems[X].FileName, AFileName) then
begin
Result := true;
Exit;
end;
Result := False;
end;
const
SRegDisabledPlugins = 'Disabled plugins';
SRegPluginX = 'Plugin%d';
procedure TPluginManager.SaveSettings(const ARegPath: String);
var
Reg: TRegIniFile;
Path: String;
X: Integer;
begin
Reg := TRegIniFile.Create(ARegPath, KEY_ALL_ACCESS);
try
// Удаляем старые
Reg.EraseSection(SRegDisabledPlugins);
Path := ARegPath + '\' + SRegDisabledPlugins;
if not Reg.OpenKey(Path, true) then
Exit;
// Сохраняем новые
for X := 0 to FBanned.Count - 1 do
Reg.WriteString(Path, Format(SRegPluginX, [X]), FBanned[X]);
finally
FreeAndNil(Reg);
end;
end;
procedure TPluginManager.SetVersion(const AVersion: Integer);
begin
FVersion := AVersion;
end;
procedure TPluginManager.LoadSettings(const ARegPath: String);
var
Reg: TRegIniFile;
Path: String;
X: Integer;
begin
Reg := TRegIniFile.Create(ARegPath, KEY_READ);
try
FBanned.BeginUpdate;
try
FBanned.Clear;
// Читаем
Path := ARegPath + '\' + SRegDisabledPlugins;
if not Reg.OpenKey(Path, true) then
Exit;
Reg.ReadSectionValues(Path, FBanned);
// Убираем "Plugin5=" из строк
for X := 0 to FBanned.Count - 1 do
FBanned[X] := FBanned.ValueFromIndex[X];
finally
FBanned.EndUpdate;
end;
finally
FreeAndNil(Reg);
end;
end;
function TPluginManager.CreateInterface(const APlugin: PluginManager.IPlugin;
const AIID: TGUID; out Intf): Boolean;
var
Provider: IServiceProvider;
X: Integer;
begin
Pointer(Intf) := nil;
Result := False;
for X := 0 to FProviders.Count - 1 do
begin
Provider := IServiceProvider(FProviders[X]);
if Provider.CreateInterface(APlugin, AIID, Intf) then
begin
Result := true;
Exit;
end;
end;
end;
procedure TPluginManager.RegisterServiceProvider(const AProvider
: IServiceProvider);
begin
FProviders.Add(AProvider);
end;
function TPluginManager.GetCount: Integer;
begin
Result := FCount;
end;
function TPluginManager.GetItem(const AIndex: Integer): PluginManager.IPlugin;
begin
Result := FItems[AIndex];
end;
function TPluginManager.GetVersion: Integer;
begin
Result := FVersion;
end;
{ TBasicProvider }
constructor TBasicProvider.Create(const AManager: IPluginManager;
const APlugin: PluginManager.IPlugin);
var
Manager: IProviderManager;
begin
inherited Create;
FManager := AManager;
FPlugin := APlugin;
if Supports(APlugin, IProviderManager, Manager) then
Manager.RegisterProvider(Self);
SetName(Format('TBasicProvider(%s): %s', [ExtractFileName(APlugin.FileName),
ClassName]));
end;
function TBasicProvider.CreateInterface(const APlugin: IPlugin;
const AIID: TGUID; out Intf): Boolean;
begin
Result := Succeeded(inherited QueryInterface(AIID, Intf));
end;
function TBasicProvider.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
if Failed(Result) then
Result := FPlugin.QueryInterface(IID, Obj);
end;
procedure TBasicProvider.Delete;
begin
FPlugin := nil;
FManager := nil;
end;
{ TPlugin }
constructor TPlugin.Create(const APluginManger: TPluginManager;
const AFileName: String);
function SafeLoadLibrary(const FileName: string; ErrorMode: UINT): HMODULE;
const
LOAD_WITH_ALTERED_SEARCH_PATH = $008;
var
OldMode: UINT;
FPUControlWord: Word;
begin
OldMode := SetErrorMode(ErrorMode);
try
{$IFNDEF CPUX64}
asm
FNSTCW FPUControlWord
end;
try
{$ENDIF}
Result := LoadLibraryEx(PChar(FileName), 0,
LOAD_WITH_ALTERED_SEARCH_PATH);
{$IFNDEF CPUX64}
finally
asm
FNCLEX
FLDCW FPUControlWord
end;
end;
{$ENDIF}
finally
SetErrorMode(OldMode);
end;
end;
var
Ind: Integer;
begin
OutputDebugString(PChar('TPlugin.Create: ' + ExtractFileName(AFileName)));
SetName(Format('TPlugin(%s)', [ExtractFileName(AFileName)]));
inherited Create;
FManager := APluginManger;
FFileName := AFileName;
FFilterIndex := -1;
FHandle := SafeLoadLibrary(AFileName, SEM_NOOPENFILEERRORBOX or
SEM_FAILCRITICALERRORS);
Win32Check(FHandle <> 0);
FDone := GetProcAddress(FHandle, SPluginDoneFuncName);
FInit := GetProcAddress(FHandle, SPluginInitFuncName);
Win32Check(Assigned(FInit));
FPlugin := FInit(Self);
Win32Check(Assigned(FPlugin));
Ind := FManager.IndexOf(FPlugin.ID);
if Ind >= 0 then
raise EDuplicatePluginError.CreateFmt(rsDuplicatePlugin,
[GUIDToString(FPlugin.ID), FPlugin.Name, FManager[Ind].FileName,
AFileName]);
FID := FPlugin.ID;
FName := FPlugin.Name;
FVersion := FPlugin.Version;
FAuthorName := FPlugin.AuthorName;
FEmailAuthor := FPlugin.EmailAuthor;
FSiteAuthor := FPlugin.SiteAuthor;
FPluginType := FPlugin.PluginType;
// FServiceName := FServicePlugin.ServiceName;
// FServices := FServicePlugin.Services;
SetName(Format('TPlugin(%s): %s', [ExtractFileName(AFileName),
GUIDToString(FID)]));
end;
destructor TPlugin.Destroy;
begin
OutputDebugString(PChar('TPlugin.Destroy: ' + ExtractFileName(FFileName)));
Delete;
if Assigned(FDone) then
FDone;
if FHandle <> 0 then
begin
FreeLibrary(FHandle);
FHandle := 0;
end;
inherited;
end;
procedure TPlugin.Delete;
begin
ReleaseProviders;
ReleasePlugin;
end;
procedure TPlugin.ReleaseProviders;
var
X: Integer;
begin
for X := High(FProviders) downto 0 do
FProviders[X].Delete;
Finalize(FProviders);
end;
procedure TPlugin.ReleasePlugin;
var
Notify: IDestroyNotify;
begin
if Supports(FPlugin, IDestroyNotify, Notify) then
Notify.Delete;
FPlugin := nil;
end;
function TPlugin.CreateInterface(const AIID: TGUID; out Intf): Boolean;
var
X: Integer;
begin
Pointer(Intf) := nil;
Result := False;
for X := 0 to High(FProviders) do
begin
Result := FProviders[X].CreateInterface(Self, AIID, Intf);
if Result then
Break;
end;
end;
function TPlugin.GetFileName: String;
begin
Result := FFileName;
end;
function TPlugin.GetID: TGUID;
begin
Result := FID;
end;
function TPlugin.GetName: String;
begin
Result := FName;
end;
function TPlugin.GetVersion: String;
begin
Result := FVersion;
end;
function TPlugin.GetAuthorName: String;
begin
Result := FAuthorName;
end;
function TPlugin.GetEmailAuthor: String;
begin
Result := FEmailAuthor;
end;
function TPlugin.GetSiteAuthor: String;
begin
Result := FSiteAuthor;
end;
function TPlugin.GetIndexIcon: Integer;
begin
Result := FIndexIcon;
end;
procedure TPlugin.SetIndexIcon(i: Integer);
begin
FIndexIcon := i;
end;
function TPlugin.GetUpdatedIcons: Boolean;
begin
Result := FUpdatedIcons;
end;
procedure TPlugin.SetUpdatedIcons(Value: Boolean);
begin
FUpdatedIcons := Value;
end;
function TPlugin.GetUpdatedActive: Boolean;
begin
Result := FUpdatedActive;
end;
procedure TPlugin.SetUpdatedActive(Value: Boolean);
begin
FUpdatedActive := Value;
end;
function TPlugin.GetUpdatedPremium: Boolean;
begin
Result := FUpdatedPremium;
end;
procedure TPlugin.SetUpdatedPremium(Value: Boolean);
begin
FUpdatedPremium := Value;
end;
function TPlugin.GetOptionsIndexIcon: Integer;
begin
Result := FOptionsIndexIcon;
end;
procedure TPlugin.SetOptionsIndexIcon(Value: Integer);
begin
FOptionsIndexIcon := Value;
end;
function TPlugin.GetGetedGraphRating: Boolean;
begin
Result := FGetedGraphRating;
end;
procedure TPlugin.SetGetedGraphRating(Value: Boolean);
begin
FGetedGraphRating := Value;
end;
function TPlugin.GetImageGraphRating: TImage;
begin
Result := FImageGraphRating;
end;
procedure TPlugin.SetImageGraphRating(Value: TImage);
begin
FImageGraphRating := Value;
end;
function TPlugin.GetPanelStatistic: TPanel;
begin
Result := FPanelStatistic;
end;
procedure TPlugin.SetPanelStatistic(Value: TPanel);
begin
FPanelStatistic := Value;
end;
function TPlugin.GetPanelInfoRank: TPanel;
begin
Result := FPanelInfoRank;
end;
procedure TPlugin.SetPanelInfoRank(Value: TPanel);
begin
FPanelInfoRank := Value;
end;
function TPlugin.GetGlobalRank: String;
begin
Result := FGlobalRank;
end;
procedure TPlugin.SetGlobalRank(Value: String);
begin
FGlobalRank := Value;
end;
function TPlugin.GetGlobalRankLabel: TsLabelFX;
begin
Result := FGlobalRankLabel;
end;
procedure TPlugin.SetGlobalRankLabel(Value: TsLabelFX);
begin
FGlobalRankLabel := Value;
end;
function TPlugin.GetPictureRatings: TMemoryStream;
begin
Result := FPictureRatings;
end;
procedure TPlugin.SetPictureRatings(Value: TMemoryStream);
begin
FPictureRatings := Value;
end;
function TPlugin.GetTaskIndexIcon: Integer;
begin
Result := FTaskIndexIcon;
end;
procedure TPlugin.SetTaskIndexIcon(Value: Integer);
begin
FTaskIndexIcon := Value;
end;
function TPlugin.GetItemIndex: Integer;
begin
Result := FItemIndex;
end;
procedure TPlugin.SetItemIndex(Value: Integer);
begin
FItemIndex := Value;
end;
function TPlugin.GetSalePremIndexIcon: Integer;
begin
Result := FSalePremIndexIcon;
end;
procedure TPlugin.SetSalePremIndexIcon(Value: Integer);
begin
FSalePremIndexIcon := Value;
end;
function TPlugin.GetHandle: HMODULE;
begin
Result := FHandle;
end;
function TPlugin.GetIcon: TIcon;
begin
FIconPlugin := TIcon.Create;
try
FIconPlugin.LoadFromResourceName(FHandle, 'Icon_1');
Result := FIconPlugin;
except
end;
end;
procedure TPlugin.DestroyIcon;
begin
try
if Assigned(FIconPlugin { <> nil } ) then
FIconPlugin.Free;
except
end;
end;
function TPlugin.GetIndex: Integer;
begin
Result := FManager.IndexOf(Self);
end;
procedure TPlugin.GetInfo;
var
Plugin: IExportImportPluginInfo;
begin
if FInfoRetrieved then
Exit;
if Supports(FPlugin, IExportImportPluginInfo, Plugin) then
begin
FMask := Plugin.Mask;
FDescription := Plugin.Description;
end
else
begin
FMask := '';
FDescription := '';
end;
FInfoRetrieved := true;
end;
function TPlugin.GetMask: String;
begin
GetInfo;
Result := FMask;
end;
function TPlugin.GetDescription: String;
begin
GetInfo;
Result := FDescription;
end;
function TPlugin.GetFilterIndex: Integer;
begin
Result := FFilterIndex;
end;
procedure TPlugin.SetFilterIndex(const AValue: Integer);
begin
FFilterIndex := AValue;
end;
function TPlugin._AddRef: Integer;
begin
Result := inherited _AddRef;
end;
function TPlugin._Release: Integer;
begin
Result := inherited _Release;
end;
function TPlugin.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
// Оболочка TPlugin
Result := inherited QueryInterface(IID, Obj);
// Сам плагин
if Failed(Result) and Assigned(FPlugin) then
Result := FPlugin.QueryInterface(IID, Obj);
// Уже созданные провайдеры
if Failed(Result) then
begin
if CreateInterface(IID, Obj) then
Result := S_OK;
end;
// Потенциальные провайдеры (создаются)
if Failed(Result) then
begin
if FManager.CreateInterface(Self, IID, Obj) then
Result := S_OK;
end;
end;
procedure TPlugin.RegisterProvider(const AProvider: IProvider);
begin
SetLength(FProviders, Length(FProviders) + 1);
FProviders[High(FProviders)] := AProvider;
end;
function TPlugin.GetCoreVersion: Integer;
begin
Result := FManager.GetVersion;
end;
function TPlugin.GetCount: Integer;
begin
Result := FManager.Count;
end;
function TPlugin.GetPlugin(const AIndex: Integer): PluginAPI.IPlugin;
begin
Supports(FManager[AIndex], PluginAPI.IPlugin, Result);
end;
{ EPluginsLoadError }
constructor EPluginsLoadError.Create(const AText: String;
const AFailedPlugins: TStrings);
begin
inherited Create(AText);
FItems := TStringList.Create;
FItems.Assign(AFailedPlugins);
end;
destructor EPluginsLoadError.Destroy;
begin
FreeAndNil(FItems);
inherited;
end;
// ________________________________________________________________
var
FPluginManager: IPluginManager;
function Plugins: IPluginManager;
begin
Result := FPluginManager;
end;
initialization
FPluginManager := TPluginManager.Create;
finalization
if Assigned(FPluginManager) then
FPluginManager.UnloadAll;
FPluginManager := nil;
end.
|
Unit logik_04;
Interface
Uses crt, liste;
Const
High: Integer = 1;
Low: Integer = 0;
Type
box_p = ^box_t;
{
LISTENZEUGS-TYPENDEKL
}
box_node_p = ^box_node_t;
box_node_t = Object (node_t)
box_pointer: box_p;
Constructor init (BP: box_p);
End;
box_p_liste_p = ^box_p_liste_t;
box_p_liste_t = Object (liste_t)
Destructor done;
Procedure push (bnp: box_node_p);
Function get_actual: box_node_p;
End;
box_t_liste_p = ^box_t_liste_t;
box_t_liste_t = Object (liste_t)
Function get_actual: box_p;
End;
{
LOGIKOBJEKT-DEKL
}
connection_p = ^connection_t;
box_t = Object (node_t)
Name: String;
zustand: Integer;
zn: Integer;
changed: Boolean;
schaltzeit, wait: Single;
e, a: box_p_liste_p;
Constructor init (iname: String; z: Integer);
Destructor done; Virtual;
Procedure connect_e (connection: connection_p);
Procedure connect_a (connection: connection_p);
Procedure set_zustand (z: Integer); Virtual;
Procedure set_name (iname: String);
Procedure show;
Function get_name: String;
Procedure update; Virtual; { Ausgangspuffer updaten }
Procedure step; Virtual; { neu berechnen }
Function gimme_zustand: Integer; Virtual;
Function has_changed: Boolean;
End;
connection_t = Object (box_t)
Procedure update; Virtual;
Procedure set_zustand (z: Integer); Virtual;
End;
NOT_p = ^NOT_t;
NOT_t = Object (box_t)
Procedure step; Virtual; { neu berechnen }
End;
AND_p = ^AND_t;
AND_t = Object (box_t)
Procedure step; Virtual; { neu berechnen }
End;
NAND_p = ^NAND_t;
NAND_t = Object (box_t)
Procedure step; Virtual; { neu berechnen }
End;
OR_p = ^OR_t;
OR_t = Object (box_t)
Procedure step; Virtual; { neu berechnen }
End;
NOR_p = ^NOR_t;
NOR_t = Object (box_t)
Procedure step; Virtual; { neu berechnen }
End;
schalter_p = ^AND_t;
schalter_t = Object (box_t)
Procedure ein;
Procedure aus;
End;
{
NETZ-OBJEKT-DEKL
}
logik_netz_t = Object
box_liste: box_t_liste_p;
Time: Single; { in sekunden }
delta_t: Single; { in sekunden }
Constructor init (idt: Single);
Destructor done;
Procedure push (BP: box_p);
Procedure step;
Procedure update_all;
Procedure show_all;
Procedure run (runtime: Single); {in sekunden }
End;
Implementation
(**********************************************************************)
(********* LISTENMETHODEN *********************************)
(**********************************************************************)
(*
* BOX-NODE_Object
*
*)
Constructor box_node_t. init; Begin Inherited init; box_pointer := BP End;
(*
* BOX-POINTER-LISTE_Object
*
*)
Destructor box_p_liste_t. done;
Var temp: node_p;
Begin
If isempty Then Exit; { liste ist leer }
setfirst; { wir fangen vorne an }
Repeat
Dispose (pop, done); { popen und lschen }
Until isempty; { bis Liste leer }
first := Nil;
last := Nil;
actual := Nil;
End;
Function box_p_liste_t. get_actual: box_node_p; Begin get_actual := box_node_p (Inherited get_actual) End;
Procedure box_p_liste_t. push (bnp: box_node_p);
Begin
Inherited push (bnp)
End;
(*
* BOX-TYP-LISTE_Object
*
*)
Function box_t_liste_t. get_actual: box_p; Begin get_actual := box_p (Inherited get_actual) End;
(**********************************************************************)
(********* LOGIK-METHODEN *********************************)
(**********************************************************************)
(*
* NETZ-Object
*
*)
Constructor logik_netz_t. init;
Begin
box_liste := New (box_t_liste_p, init);
delta_t := idt;
Time := 0
End;
Destructor logik_netz_t. done; Begin Dispose (box_liste, done) End;
Procedure logik_netz_t. push (BP: box_p);
Begin
box_liste^. push (BP)
End;
Procedure logik_netz_t. step;
Var
BP: box_p;
Begin
{
alles neuberechnen
}
box_liste^. setfirst;
Repeat
BP := box_liste^. get_actual;
BP^. step;
box_liste^. next;
Until BP^. next = Nil;
End;
Procedure logik_netz_t. update_all;
Var
BP: box_p;
Begin
{
und updaten
}
box_liste^. setfirst;
Repeat
BP := box_liste^. get_actual;
BP^. update;
box_liste^. next;
Until BP^. next = Nil;
End;
Procedure logik_netz_t. run; Begin End;
Procedure logik_netz_t. show_all;
Var
BP: box_p;
Begin
{
alle anzeigen
}
box_liste^. setfirst;
Repeat
BP := box_liste^. get_actual;
BP^. show;
box_liste^. next;
Until BP^. next = Nil;
End;
(*
* BOX-Object
*
*)
Constructor box_t. init;
Begin
e := New (box_p_liste_p, init);
a := New (box_p_liste_p, init);
set_zustand (z);
set_name (iname);
zustand := 0;
changed := True;
End;
Destructor box_t. done;
Begin
Dispose (a, done);
Dispose (e, done);
End;
Function box_t. has_changed: Boolean; Begin has_changed := changed End;
Procedure box_t. show;
Begin
Write (Name, ' :'); GotoXY (10, WhereY);
Write ('Z=', zustand); GotoXY (20, WhereY);
WriteLn ('Z(n+1)=', zn);
End;
Procedure box_t. set_zustand; Begin zn := z End;
Procedure box_t. set_name; Begin Name := iname End;
Function box_t. get_name: String; Begin get_name := Name End;
Procedure box_t. update;
Var
Ap: box_node_p;
Begin
zustand := zn; { sich selbst updaten }
A^. setfirst;
If a^. get_actual <> Nil Then {sind berhaupt ausgnge da ? }
Repeat
Ap := a^. get_actual;
AP^. box_pointer^. set_zustand (zustand); { und alle anderen Ausgnge auch }
A^. next;
Until Ap^. next = Nil;
End;
Procedure box_t. step; Begin End; { tut nix }
Function box_t. gimme_zustand: Integer; Begin gimme_zustand := zustand End;
Procedure box_t. connect_a;
Begin
a^. push (New (box_node_p, init (connection) ) )
End;
Procedure box_t. connect_e;
Begin
e^. push (New (box_node_p, init (connection) ) )
End;
(*
* CONNECTION-Object
*
*)
Procedure connection_t. update; Begin zustand := zn End;
Procedure connection_t. set_zustand; Begin zustand := z; zn := zustand End;
(*
* NOT-Object
*
*)
Procedure NOT_t. step;
Begin
E^. setfirst;
With e^. get_actual^. box_pointer^ Do
Begin
If (true{has_changed}) And (gimme_zustand <= Low) Then
self.set_zustand (High)
Else
self.set_zustand (Low);
changed := has_changed
End
End;
(*
* AND-Object
*
*)
Procedure AND_t. step;
Var
produkt: Integer;
ep: box_node_p;
Begin
PRODUKT := High;
E^. setfirst;
Repeat
ep := e^. get_actual;
PRODUKT := PRODUKT * ep^. box_pointer^. gimme_zustand;
e^. next;
Until ep^. next = Nil;
If produkt <= Low Then
Begin
If zustand <> Low Then Begin
set_zustand (Low);
changed := True
End Else
changed := False;
End
Else
Begin
If zustand <> High Then Begin
set_zustand (High);
changed := True
End Else
changed := False;
End;
End;
(*
* OR-Object
*
*)
Procedure OR_t. step;
Var
SUMME: Integer;
ep: box_node_p;
Begin
SUMME := Low;
E^. setfirst;
Repeat
ep := e^. get_actual;
SUMME := SUMME + ep^. box_pointer^. gimme_zustand;
e^. next;
Until ep^. next = Nil;
If SUMME <= Low Then
Begin
If zustand <> Low Then
Begin
set_zustand (Low);
changed := True
End Else
changed := False
End Else
Begin
If zustand <> High Then
Begin
set_zustand (High);
changed := True
End Else
changed := False
End
End;
(*
* NAND-Object
*
*)
Procedure NAND_t. step;
Var
produkt: Integer;
ep: box_node_p;
Begin
PRODUKT := High;
E^. setfirst;
Repeat
ep := e^. get_actual;
PRODUKT := PRODUKT * ep^. box_pointer^. gimme_zustand;
e^. next;
Until ep^. next = Nil;
If produkt <= Low Then
Begin
If zustand <> Low Then Begin
set_zustand (Low);
changed := True
End Else
changed := False;
End
Else
Begin
If zustand <> High Then Begin
set_zustand (High);
changed := True
End Else
changed := False;
End;
if has_changed then if zn<=LOW then zn:=HIGH else zn:=LOW;
End;
(*
* NOR-Object
*
*)
Procedure NOR_t. step;
Var
SUMME: Integer;
ep: box_node_p;
Begin
SUMME := Low;
E^. setfirst;
Repeat
ep := e^. get_actual;
SUMME := SUMME + ep^. box_pointer^. gimme_zustand;
e^. next;
Until ep^. next = Nil;
If SUMME <= Low Then
Begin
If zustand <> Low Then
Begin
set_zustand (Low);
changed := True
End Else
changed := False
End Else
Begin
If zustand <> High Then
Begin
set_zustand (High);
changed := True
End Else
changed := False
End;
if has_changed then if zn<=LOW then zn:=HIGH else zn:=LOW;
End;
(*
* SCHALTER-Object
*
*)
Procedure schalter_t. ein;
Begin
If zustand <> High Then Begin
set_zustand (High);
changed := True
End Else
changed := False;
End;
Procedure schalter_t. aus; Begin
If zustand <> Low Then Begin
set_zustand (Low);
changed := True
End Else
changed := False;
End;
Begin
End. |
unit CatInet;
{
Catarinka - Internet related functions
Copyright (c) 2003-2014 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
GetTinyUrl function by Rodrigo Ruz V., released under the MIT license
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
Winapi.Windows, Winapi.WinSock, System.SysUtils, System.Win.Registry,
Winapi.WinInet;
{$ELSE}
Windows, WinSock, SysUtils, Registry, WinInet;
{$ENDIF}
function GetAbsoluteURL(const baseURL, relURL: string): string;
function GetTinyUrl(const URL: string): string;
function IPAddrToName(const IP: string): string;
function IsValidIP(const IP: string): Boolean;
function NameToIPAddr(const name: string): string;
procedure DisableProxy(const agent: string);
procedure EnableProxy(const agent, proxy: string);
procedure IESettingsChanged(const agent: string);
implementation
uses CatStrings;
procedure DisableProxy(const agent: string);
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey
('\Software\Microsoft\Windows\CurrentVersion\Internet Settings', True)
then
begin
Reg.WriteInteger('ProxyEnable', 0);
Reg.CloseKey;
end;
finally
Reg.Free;
end;
IESettingsChanged(agent);
end;
procedure EnableProxy(const agent, proxy: string);
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey
('\Software\Microsoft\Windows\CurrentVersion\Internet Settings', True)
then
begin
Reg.WriteString('ProxyServer', proxy); // format: proxy:proxyport
Reg.WriteInteger('ProxyEnable', 1);
Reg.CloseKey;
end;
finally
Reg.Free;
end;
IESettingsChanged(agent);
end;
// Usage example:
// GetAbsoluteURL('http://someurl.com/demo/','/index.html')
// will return http://someurl.com/index.html
function GetAbsoluteURL(const baseURL, relURL: string): string;
procedure TruncateStr(var s: string);
var
i: Integer;
begin
for i := 1 to length(s) do
if (s[i] = #0) then
begin
SetLength(s, i - 1);
Exit;
end;
end;
var
buflen: DWORD;
begin
buflen := 10240;
SetLength(Result, buflen);
InternetCombineUrl(
{$IFDEF UNICODE}PWideChar{$ELSE}PChar{$ENDIF}(baseURL),
{$IFDEF UNICODE}PWideChar{$ELSE}PChar{$ENDIF}(relURL),
{$IFDEF UNICODE}PWideChar{$ELSE}PChar{$ENDIF}(Result), buflen,
ICU_BROWSER_MODE);
TruncateStr(Result);
// workaround, ipv6
Result := replacestr(Result, '%5B', '[');
Result := replacestr(Result, '%5D', ']');
end;
procedure IESettingsChanged(const agent: string);
var
HInet: HINTERNET;
begin
HInet := InternetOpen({$IFDEF UNICODE}PWideChar{$ELSE}PChar{$ENDIF}(agent),
INTERNET_OPEN_TYPE_DIRECT, nil, nil, INTERNET_FLAG_OFFLINE);
try
if HInet <> nil then
InternetSetOption(HInet, INTERNET_OPTION_SETTINGS_CHANGED, nil, 0);
finally
InternetCloseHandle(HInet);
end;
end;
function IPAddrToName(const IP: string): string;
var
WSAData: TWSAData;
HostEnt: PHostEnt;
Addr: Longint;
begin
Result := EmptyStr;
if WSAStartup(MakeWord(1, 1), WSAData) <> 0 then
Exit;
Addr := inet_addr(PAnsiChar(ansistring(IP)));
HostEnt := gethostbyaddr(@Addr, 4, PF_INET);
if HostEnt = nil then
Exit;
Result := string(HostEnt^.h_name);
WSACleanup;
end;
function IsValidIP(const IP: string): Boolean;
begin
Result := ((IP <> emptystr) and
(inet_addr(PAnsiChar(ansistring(IP))) <>
integer(INADDR_NONE)));
end;
function NameToIPAddr(const name: string): string;
var
p: PHostEnt;
a: TInAddr;
WSAData: TWSAData;
begin
Result := '0.0.0.0';
WSAStartup($101, WSAData);
p := GetHostByName(PAnsiChar(AnsiString(name)));
if Assigned(p) then
begin
A := PInAddr(p^.h_Addr_List^)^;
Result := string(inet_ntoa(A));
end;
end;
// By Rodrigo Ruz (MIT license)
function GetTinyUrl(const URL: string): string;
const
tinyurl = 'http://tinyurl.com/api-create.php?url=%s';
BuffSize = 2048;
var
hInter, UrlHandle: HINTERNET;
BytesRead: Cardinal;
Buffer: Pointer;
begin
Result := emptystr;
hInter := InternetOpen('', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(hInter) then
begin
GetMem(Buffer, BuffSize);
try
UrlHandle := InternetOpenUrl(hInter, PChar(Format(tinyurl, [URL])), nil,
0, INTERNET_FLAG_RELOAD, 0);
if Assigned(UrlHandle) then
begin
InternetReadFile(UrlHandle, Buffer, BuffSize, BytesRead);
if BytesRead > 0 then
SetString(Result, PAnsiChar(Buffer), BytesRead);
InternetCloseHandle(UrlHandle);
end;
finally
FreeMem(Buffer);
end;
InternetCloseHandle(hInter);
end
end;
// ------------------------------------------------------------------------//
end.
|
unit uLogOptions;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, GnuGettext, uTools, uMain,
Vcl.Buttons;
type
TfLogOptions = class(TForm)
FontDialog1: TFontDialog;
lblLogFont: TLabel;
tLogFont: TEdit;
lblLogFontSize: TLabel;
bSelect: TButton;
tLogFontSize: TEdit;
bSave: TBitBtn;
bCancel: TBitBtn;
procedure bSelectClick(Sender: TObject);
procedure FontDialog1Apply(Sender: TObject; Wnd: HWND);
procedure FontDialog1Close(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure bCancelClick(Sender: TObject);
procedure bSaveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fLogOptions: TfLogOptions;
implementation
{$R *.dfm}
procedure TfLogOptions.bCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfLogOptions.bSaveClick(Sender: TObject);
begin
Config.LogSettings.Font := FontDialog1.Font.Name;
Config.LogSettings.FontSize := FontDialog1.Font.Size;
fMain.AdjustLogFont(FontDialog1.Font.Name, FontDialog1.Font.Size);
SaveSettings;
Close;
end;
procedure TfLogOptions.bSelectClick(Sender: TObject);
begin
FontDialog1.Execute();
end;
procedure TfLogOptions.FontDialog1Apply(Sender: TObject; Wnd: HWND);
begin
tLogFont.Text := FontDialog1.Font.Name;
tLogFontSize.Text := IntToStr(FontDialog1.Font.Size);
end;
procedure TfLogOptions.FontDialog1Close(Sender: TObject);
begin
tLogFont.Text := FontDialog1.Font.Name;
tLogFontSize.Text := IntToStr(FontDialog1.Font.Size);
end;
procedure TfLogOptions.FormCreate(Sender: TObject);
begin
TranslateComponent(Self);
end;
procedure TfLogOptions.FormShow(Sender: TObject);
begin
tLogFont.Text := Config.LogSettings.Font;
tLogFontSize.Text := IntToStr(Config.LogSettings.FontSize);
FontDialog1.Font.Name := Config.LogSettings.Font;
FontDialog1.Font.Size := Config.LogSettings.FontSize;
end;
end.
|
unit GRRClientGISQueries;
interface
uses Classes, Contnrs, Version;
type
TQueryType = (qtOrganizations, qtQueries, qtXLQuery);
TGRRReportQuery = class
private
FTitle: string;
FQueryType: TQueryType;
FSelected: Boolean;
public
property Title: string read FTitle;
property QueryType: TQueryType read FQueryType ;
property Selected: Boolean read FSelected write FSelected;
procedure Execute(AFileName: string); virtual;
constructor Create; virtual;
end;
TGRRReportQueryClass = class of TGRRReportQuery;
TGRRReportQueries = class(TObjectList)
private
FOnExecute: TNotifyEvent;
FVersions: TVersions;
function GetItems(const Index: Integer): TGRRReportQuery;
function GetSelectedCount: integer;
public
property Versions: TVersions read FVersions write FVersions;
property Items[const Index: Integer]: TGRRReportQuery read GetItems;
property SelectedCount: integer read GetSelectedCount;
property OnExcecute: TNotifyEvent read FOnExecute write FOnExecute;
procedure Execute(AFileName: string); virtual;
procedure MakeList(ALst: TStrings);
function AddReport(AGRRReportQueryClass: TGRRReportQueryClass): TGRRReportQuery;
constructor Create; virtual;
end;
TGRRReportXLQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportConcreteQueries = class(TGRRReportQueries)
public
constructor Create; override;
end;
TGRRReportGISXLQueries = class(TGRRReportQueries)
public
procedure Execute(AFileName: string); override;
constructor Create; override;
end;
TGRRReportAllOrganizationsQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportVINKOrganizationsQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportPlannedDrillingQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportDrillingQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportDrillingWithResultQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportDrillingWithNoResultQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportNoDrillingQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportPlannedSeismicQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportPlanned2DSeismicQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportPlanned3DSeismicQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportSeismicQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReport2DSeismicQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReport3DSeismicQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportNoSeismicQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportPlannedNIRQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportNIRQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportNoNIRQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportPlannedWorkQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportFactWorkQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
TGRRReportNoWorkQuery = class(TGRRReportQuery)
public
constructor Create; override;
end;
implementation
{ TGRRReportQuery }
constructor TGRRReportQuery.Create;
begin
end;
procedure TGRRReportQuery.Execute;
begin
end;
{ TGRRReportVINKOrganizationsQuery }
constructor TGRRReportVINKOrganizationsQuery.Create;
begin
inherited;
FTitle := 'По ВИНК';
FQueryType := qtOrganizations;
end;
{ TGRRReportAllOrganizationsQuery }
constructor TGRRReportAllOrganizationsQuery.Create;
begin
inherited;
FTitle := 'По организациям';
FQueryType := qtOrganizations;
end;
{ TGRRReportPlannedDrillingQuery }
constructor TGRRReportPlannedDrillingQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым запланировано бурение на отчетный период';
FQueryType := qtQueries;
end;
{ TGRRReportDrillingQuery }
constructor TGRRReportDrillingQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым выполнялось бурение в отчетном периоде';
FQueryType := qtQueries;
end;
{ TGRRReportDrillingWithResultQuery }
constructor TGRRReportDrillingWithResultQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым выполнялось результативное бурение в отчетном периоде';
FQueryType := qtQueries;
end;
{ TGRRReportDrillingWithNoResultQuery }
constructor TGRRReportDrillingWithNoResultQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым выполнялось бурение, но результат получен не был';
FQueryType := qtQueries;
end;
{ TGRRReportNoDrillingQuery }
constructor TGRRReportNoDrillingQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым было запланировано, но не выполнено бурение';
FQueryType := qtQueries;
end;
{ TGRRReportPlannedSeismicQuery }
constructor TGRRReportPlannedSeismicQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были запланированы сейсморазведочные работы';
FQueryType := qtQueries;
end;
{ TGRRReportPlanned2DSeismicQuery }
constructor TGRRReportPlanned2DSeismicQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были запланированы 2D сейсморазведочные работы';
FQueryType := qtQueries;
end;
{ TGRRReportPlanned3DSeismicQuery }
constructor TGRRReportPlanned3DSeismicQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были запланированы 3D сейсморазведочные работы';
FQueryType := qtQueries;
end;
{ TGRRReport2DSeismicQuery }
constructor TGRRReport2DSeismicQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были выполнены 2D сейсморазведочные работы';
FQueryType := qtQueries;
end;
{ TGRRReport3DSeismicQuery }
constructor TGRRReport3DSeismicQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были выполнены 3D сейсморазведочные работы';
FQueryType := qtQueries;
end;
{ TGRRReportNoSeismicQuery }
constructor TGRRReportNoSeismicQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были запланированы, но не выполнены сейсморазведочные работы';
FQueryType := qtQueries;
end;
{ TGRRReportNIRQuery }
constructor TGRRReportNIRQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были выполнены НИР';
FQueryType := qtQueries;
end;
{ TGRRReportNoNIRQuery }
constructor TGRRReportNoNIRQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были запланированы, но не выполнены НИР';
FQueryType := qtQueries;
end;
{ TGRRReportSeismicQuery }
constructor TGRRReportSeismicQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были выполнены сейсморазведочные работы';
FQueryType := qtQueries;
end;
{ TGRRReportPlannedNIRQuery }
constructor TGRRReportPlannedNIRQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были запланированы НИР';
FQueryType := qtQueries;
end;
{ TGRRReportNoWorkQuery }
constructor TGRRReportNoWorkQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были запланированы, но не выполнены ГРР';
FQueryType := qtQueries;
end;
{ TGRRReportFactWorkQuery }
constructor TGRRReportFactWorkQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде выполнялись ГРР';
FQueryType := qtQueries;
end;
{ TGRRReportPlannedWorkQuery }
constructor TGRRReportPlannedWorkQuery.Create;
begin
inherited;
FTitle := 'Участки, по которым в отчетном периоде были запланированы ГРР';
FQueryType := qtQueries;
end;
{ TGRRReportQueries }
function TGRRReportQueries.AddReport(
AGRRReportQueryClass: TGRRReportQueryClass): TGRRReportQuery;
begin
Result := AGRRReportQueryClass.Create;
inherited Add(Result);
end;
constructor TGRRReportQueries.Create;
begin
inherited Create(True);
end;
procedure TGRRReportQueries.Execute(AFileName: string);
var i: integer;
begin
for i := 0 to Count - 1 do
if Items[i].Selected then
begin
Items[i].Execute(AFileName);
if Assigned(FOnExecute) then FOnExecute(Self);
end;
end;
function TGRRReportQueries.GetItems(const Index: Integer): TGRRReportQuery;
begin
Result := inherited Items[Index] as TGRRReportQuery;
end;
function TGRRReportQueries.GetSelectedCount: integer;
var i: integer;
begin
Result := 0;
for i := 0 to Count - 1 do
Result := Result + Ord(Items[i].Selected);
end;
procedure TGRRReportQueries.MakeList(ALst: TStrings);
var i: integer;
begin
ALst.Clear;
for i := 0 to Count - 1 do
ALst.AddObject(Items[i].Title, Items[i]);
end;
{ TGRRReportConcreteQueries }
constructor TGRRReportConcreteQueries.Create;
begin
inherited;
AddReport(TGRRReportAllOrganizationsQuery);
AddReport(TGRRReportVINKOrganizationsQuery);
AddReport(TGRRReportPlannedDrillingQuery);
AddReport(TGRRReportDrillingQuery);
AddReport(TGRRReportDrillingWithResultQuery);
AddReport(TGRRReportDrillingWithNoResultQuery);
AddReport(TGRRReportNoDrillingQuery);
AddReport(TGRRReportPlannedSeismicQuery);
AddReport(TGRRReportPlanned2DSeismicQuery);
AddReport(TGRRReportPlanned3DSeismicQuery);
AddReport(TGRRReport2DSeismicQuery);
AddReport(TGRRReport3DSeismicQuery);
AddReport(TGRRReportPlannedNIRQuery);
AddReport(TGRRReportNIRQuery);
AddReport(TGRRReportNoNIRQuery);
AddReport(TGRRReportPlannedWorkQuery);
AddReport(TGRRReportFactWorkQuery);
AddReport(TGRRReportNoWorkQuery);
end;
{ TGRRReportXLQuery }
constructor TGRRReportXLQuery.Create;
begin
inherited;
FTitle := 'Excel-отчет для карты';
FQueryType := qtXLQuery;
end;
{ TGRRReportGISXLQueries }
constructor TGRRReportGISXLQueries.Create;
begin
inherited;
AddReport(TGRRReportXLQuery);
end;
procedure TGRRReportGISXLQueries.Execute(AFileName: string);
var i: Integer;
begin
for i := 0 to Versions.Count - 1 do
begin
Items[i].Execute(AFileName);
if Assigned(FOnExecute) then FOnExecute(Self);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.