text stringlengths 14 6.51M |
|---|
unit HiddenTests;
interface
uses
System.Classes,
TestFramework,
NtHiddenId;
type
THiddenTests = class(TTestCase)
private
FValue: THiddenId;
FCustomValue: THiddenId;
procedure Encode(value: Integer);
procedure EncodeCustom(value: Integer);
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure EncodeZero;
procedure EncodeVeryShort;
procedure EncodeShort;
procedure EncodeMedium;
procedure EncodeLong;
procedure EncodeVeryLong;
procedure EncodeCustomShort;
procedure Parse;
procedure ParseTriple;
end;
implementation
uses
System.Generics.Collections;
procedure THiddenTests.SetUp;
begin
inherited;
FValue := THiddenId.Create;
FCustomValue := THiddenId.Create;
FCustomValue.Value := [zwInvisibleTimes, zwNoBreakSpace, zwPopDirectionalFormatting, zwWordJoiner];
end;
procedure THiddenTests.TearDown;
begin
inherited;
FValue.Free;
end;
procedure THiddenTests.Encode(value: Integer);
var
encoded: String;
decoded: Integer;
begin
encoded := FValue.Encode(value);
decoded := FValue.Decode(encoded);
Check(decoded = value);
end;
procedure THiddenTests.EncodeCustom(value: Integer);
var
encoded: String;
decoded: Integer;
begin
encoded := FCustomValue.Encode(value);
decoded := FCustomValue.Decode(encoded);
Check(decoded = value);
end;
procedure THiddenTests.EncodeZero;
begin
Encode(0);
end;
procedure THiddenTests.EncodeVeryShort;
begin
Encode(1);
end;
procedure THiddenTests.EncodeShort;
begin
Encode(28);
end;
procedure THiddenTests.EncodeCustomShort;
begin
EncodeCustom(28);
end;
procedure THiddenTests.EncodeMedium;
begin
Encode(4151);
end;
procedure THiddenTests.EncodeLong;
begin
Encode(90123);
end;
procedure THiddenTests.EncodeVeryLong;
begin
Encode(650123);
end;
procedure THiddenTests.Parse;
const
VALUE = 'Hello';
ID = 123;
var
encoded: String;
part: TDecodedString;
begin
encoded := FValue.Inject(VALUE, ID);
part := FValue.Parse(encoded);
Check(part.Value = VALUE);
Check(part.Id = ID);
end;
procedure THiddenTests.ParseTriple;
const
VALUE1 = 'First part';
VALUE2 = 'Second part';
VALUE3 = 'Third part';
ID1 = 123;
ID2 = 234;
ID3 = 3456;
var
encoded: String;
parts: TList<TDecodedString>;
begin
encoded := FValue.Inject(VALUE1, ID1) + FValue.Inject(VALUE2, ID2) + FValue.Inject(VALUE3, ID3);
parts := TList<TDecodedString>.Create;
try
FValue.Parse(encoded, parts);
Check(parts.Count = 3);
Check(parts[0].Value = VALUE1);
Check(parts[0].Id = ID1);
Check(parts[1].Value = VALUE2);
Check(parts[1].Id = ID2);
Check(parts[2].Value = VALUE3);
Check(parts[2].Id = ID3);
finally
parts.Free;
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(THiddenTests.Suite);
end.
|
unit txFilterSql;
interface
uses SysUtils, txDefs, txFilter, DataLank;
type
TtxSqlQueryFragments=class(TObject)
private
FItemType:TtxItemType;
AliasCount,FParentID:integer;
AddedWhere:boolean;
DbCon:TDataConnection;
function BuildSQL:UTF8String;
function SqlStr(const s:UTF8String):UTF8String;
function Criterium(const El:TtxFilterElement;
const SubQryField, SubQryFrom: UTF8String;
ParentsOnly, Reverse: boolean):UTF8String;
public
Limit:integer;
Fields,Tables,Where,GroupBy,Having,OrderBy:UTF8String;
EnvVars:array[TtxFilterEnvVar] of integer;
constructor Create(ItemType: TtxItemType);
destructor Destroy; override;
procedure AddFilter(f:TtxFilter);
procedure AddWhere(const s:UTF8String);
procedure AddWhereSafe(const s:UTF8String);
procedure AddOrderBy(const s:UTF8String);
procedure AddFrom(const s:UTF8String);
property SQL:UTF8String read BuildSQL;
property ParentID:integer read FParentID;
end;
EtxSqlQueryError=class(Exception);
TIdList=class(TObject)
private
idCount,idSize:integer;
ids:array of integer;
function GetList:UTF8String;
function GetItem(Idx:integer):integer;
procedure SetItem(Idx,Value:integer);
public
constructor Create;
destructor Destroy; override;
procedure Add(id:integer);
procedure AddList(list:TIdList);
procedure AddClip(id:integer; var Clip:integer);
procedure Clear;
function Contains(id:integer):boolean;
property List:UTF8String read GetList;
property Count:integer read idCount;
property Item[Idx:integer]:integer read GetItem write SetItem; default;
end;
implementation
uses txSession, Classes, Variants;
{ TtxSqlQueryFragments }
constructor TtxSqlQueryFragments.Create(ItemType: TtxItemType);
var
t:UTF8String;
fe:TtxFilterEnvVar;
begin
inherited Create;
AliasCount:=0;
Limit:=-1;
FParentID:=0;
FItemType:=ItemType;
DbCon:=Session.DbCon;
case FItemType of
itObj:
begin
Fields:='Obj.id, Obj.pid, Obj.name, Obj.'+sqlDesc+', Obj.weight, Obj.c_uid, Obj.c_ts, Obj.m_uid, Obj.m_ts, ObjType.icon, ObjType.name AS typename';
Tables:='Obj LEFT JOIN ObjType ON ObjType.id=Obj.objtype_id'#13#10;
Where:='';
GroupBy:='';
Having:='';
OrderBy:='Obj.weight, Obj.name, Obj.c_ts';
end;
itReport:
begin
Fields:='Rpt.id, Rpt.obj_id, Rpt.'+sqlDesc+', Rpt.uid, Rpt.ts, Rpt.toktype_id, Rpt.reftype_id, Rpt.obj2_id,'+
' Obj.name, Obj.pid, ObjType.icon, ObjType.name AS typename,'+
' UsrObj.id AS usrid, UsrObj.name AS usrname, UsrObjType.icon AS usricon, UsrObjType.name AS usrtypename,'+
' RelTokType.icon AS tokicon, RelTokType.name AS tokname, RelTokType.system AS toksystem,'+
' RelRefType.icon AS reficon, RelRefType.name AS refname,'+
' RelObj.name AS relname, RelObjType.icon AS relicon, RelObjType.name AS reltypename';
Tables:='Rpt'#13#10+
'INNER JOIN Obj ON Obj.id=Rpt.obj_id'#13#10+
'INNER JOIN ObjType ON ObjType.id=Obj.objtype_id'#13#10+
'INNER JOIN Obj AS UsrObj ON UsrObj.id=Rpt.uid'#13#10+
'INNER JOIN ObjType AS UsrObjType ON UsrObjType.id=UsrObj.objtype_id'#13#10+
'LEFT OUTER JOIN Obj AS RelObj ON RelObj.id=Rpt.obj2_id'#13#10+
'LEFT OUTER JOIN ObjType AS RelObjType ON RelObjType.id=RelObj.objtype_id'#13#10+
'LEFT OUTER JOIN TokType AS RelTokType ON RelTokType.id=Rpt.toktype_id'#13#10+
'LEFT OUTER JOIN RefType AS RelRefType ON RelRefType.id=Rpt.reftype_id'#13#10;
Where:='';
GroupBy:='';
Having:='';
OrderBy:='Rpt.ts DESC';
end;
itJournalEntry:
begin
Fields:='Jre.id, Jre.obj_id, Jre.ts, Jre.minutes, Jre.uid,'+
' Jre.jrt_id, Jrt.icon AS jrt_icon, Jrt.name AS jrt_name,'+
' Obj.name, Obj.pid, ObjType.icon, ObjType.name AS typename,'+
' UsrObj.id AS usrid, UsrObj.name AS usrname, UsrObjType.icon AS usricon, UsrObjType.name AS usrtypename';
Tables:='Jre'#13#10+
'INNER JOIN Jrt ON Jrt.id=Jre.jrt_id'#13#10+
//'INNER JOIN Jrl ON Jrl.id=Jrt.jrl_id'#13#10+
'INNER JOIN Obj ON Obj.id=Jre.obj_id'#13#10+
'INNER JOIN ObjType ON ObjType.id=Obj.objtype_id'#13#10+
'INNER JOIN Obj AS UsrObj ON UsrObj.id=Jre.uid'#13#10+
'INNER JOIN ObjType AS UsrObjType ON UsrObjType.id=UsrObj.objtype_id'#13#10;
Where:='';
GroupBy:='';
Having:='';
OrderBy:='Jre.ts DESC';
end;
else
begin
t:=txItemTypeTable[ItemType];
Fields:='*';
Tables:=t+#13#10;
Where:='';
GroupBy:='';
Having:='';
OrderBy:=t+'.weight, '+t+'.name, '+t+'.c_ts';
end;
end;
if Use_ObjTokRefCache and (FItemType in [itObj,itReport,itJournalEntry]) then
begin
Fields:=Fields+', ObjTokRefCache.tokHTML, ObjTokRefCache.refHTML';
Tables:=Tables+'LEFT OUTER JOIN ObjTokRefCache ON ObjTokRefCache.id=Obj.id'#13#10;
end;
for fe:=TtxFilterEnvVar(0) to fe_Unknown do EnvVars[feMe]:=0;
EnvVars[feMe]:=Session.UserID;
end;
destructor TtxSqlQueryFragments.Destroy;
begin
//clean-up
DbCon:=nil;
inherited;
end;
function CritDate(fx:TtxFilterElement):UTF8String;
var
i:integer;
begin
case fx.IDType of
dtNumber:
if TryStrToInt(string(fx.ID),i) then
//Result:='{d '''+FormatDate('yyyy-mm-dd',Date-i)+'''}'
Result:=UTF8String(FloatToStr(Date-i))//SQLite allows storing Delphi date-as-float
else
raise EtxSqlQueryError.Create('Invalid ID at position: '+IntToStr(fx.Idx1));
//TODO
else
raise EtxSqlQueryError.Create('Unsupported IDType at position: '+IntToStr(fx.Idx1));
end;
end;
function CritTime(fx:TtxFilterElement):UTF8String;
var
dy,dm,dd,th,tm,ts,tz:word;
d:TDateTime;
i,l:integer;
procedure Next(var vv:word;max:integer);
var
j:integer;
begin
vv:=0;
j:=i+max;
while (i<=l) and (i<j) and (fx.ID[i] in ['0'..'9']) do
begin
vv:=vv*10+(byte(fx.ID[i]) and $0F);
inc(i);
end;
while (i<=l) and not(fx.ID[i] in ['0'..'9']) do inc(i);
end;
begin
case fx.IDType of
dtNumber,dtSystem:
begin
//defaults
dy:=1900;
dm:=1;
dd:=1;
th:=0;
tm:=0;
ts:=0;
tz:=0;
l:=Length(fx.ID);
i:=1;
while (i<=l) and not(fx.ID[i] in ['0'..'9']) do inc(i);
if i<=l then
begin
Next(dy,4);//year
if i<=l then
begin
Next(dm,2);//month
if i<=l then
begin
Next(dd,2);//day
Next(th,2);//hours
Next(tm,2);//minutes
Next(ts,2);//seconds
Next(tz,3);//milliseconds
end;
end;
end;
d:=EncodeDate(dy,dm,dd)+EncodeTime(th,tm,ts,tz);
//Result:='{ts '''+FormatDate('yyyy-mm-dd hh:nn:ss.zzz',d)+'''}';
Result:=UTF8String(FloatToStr(d));//SQLite allows storing Delphi date-as-float
end;
//TODO
else
raise EtxSqlQueryError.Create('Unsupported IDType at position: '+IntToStr(fx.Idx1));
end;
end;
procedure TtxSqlQueryFragments.AddFilter(f: TtxFilter);
var
i,j,k:integer;
s,t:UTF8String;
qr:TQueryResult;
fx:TtxFilter;
fq:TtxSqlQueryFragments;
procedure AddWhereQuery(const Field,Query:UTF8String);
var
ids:TIdList;
begin
if f[i].Prefetch then
begin
ids:=TIdList.Create;
try
qr:=TQueryResult.Create(Session.DbCon,s,[]);
try
while qr.Read do ids.Add(qr.GetInt(0));
finally
qr.Free;
end;
AddWhere(Field+' in ('+ids.List+')');
finally
ids.Free;
end;
end
else
AddWhere(Field+' in ('+Query+')');
end;
const
RefBSel:array[boolean] of UTF8String=('1','2');
begin
//TODO: when FItemType<>itObj
for i:=0 to f.Count-1 do
begin
//check global para count?
for j:=1 to f[i].ParaOpen do Where:=Where+'(';
//no para's when not AddedWhere?
AddedWhere:=false;
case f[i].Action of
faChild:
//dummy check:
if (f[i].IDType=dtNumber) and (f[i].ID='0') and (f[i].Descending) then
AddWhere('1=1')//match all
else
AddWhere('Obj.pid'+Criterium(f[i],'Obj.id','',true,false));
faObj:
AddWhere('Obj.id'+Criterium(f[i],'Obj.id','',false,false));
faObjType:
if (f[i].IDType=dtNumber) and (f[i].ID='0') then
if f[i].Descending then
AddWhere('1=1')//match all
else
AddWhere('0=1')//match none
else
AddWhere('ObjType.id'+Criterium(f[i],'DISTINCT ObjType.id','',false,false));
faTokType:
//dummy check:
if (f[i].IDType=dtNumber) and (f[i].ID='0') and (f[i].Descending) then
AddWhere('EXISTS (SELECT id FROM Tok WHERE obj_id=Obj.id)')
else
begin
inc(AliasCount);
t:='ttSQ'+IntToStrU(AliasCount);
s:='SELECT DISTINCT Tok.obj_id FROM Tok WHERE Tok.toktype_id'+Criterium(f[i],
'DISTINCT '+t+'.toktype_id','RIGHT JOIN Tok AS '+t+' ON '+t+'.obj_id=Obj.id',false,false);
if f[i].Parameters<>'' then
begin
fx:=TtxFilter.Create;
try
fx.FilterExpression:=f[i].Parameters;
for j:=0 to fx.Count-1 do
case fx[j].Action of
faModified:
s:=s+' AND Tok.m_ts<'+CritDate(fx[j]);
faFrom:
s:=s+' AND Tok.m_ts>='+CritTime(fx[j]);
faTill:
s:=s+' AND Tok.m_ts<='+CritTime(fx[j])
else
raise EtxSqlQueryError.Create('Unexpected tt parameter at position '+IntToStr(fx[j].Idx1));
end;
//TODO: fx[j].Operator
finally
fx.Free;
end;
end;
AddWhereQuery('Obj.id',s);
end;
faRefType:
//dummy check:
if (f[i].IDType=dtNumber) and (f[i].ID='0') and (f[i].Descending) then
AddWhere('EXISTS (SELECT id FROM Ref WHERE obj1_id=Obj.id)')
else
begin
inc(AliasCount);
t:='rtSQ'+IntToStrU(AliasCount);
s:='SELECT DISTINCT Ref.obj1_id FROM Ref WHERE Ref.reftype_id'+Criterium(f[i],
'DISTINCT '+t+'.reftype_id','RIGHT JOIN Ref AS '+t+' ON '+t+'.obj1_id=Obj.id',false,false);
if f[i].Parameters<>'' then
begin
fx:=TtxFilter.Create;
try
fx.FilterExpression:=f[i].Parameters;
for j:=0 to fx.Count-1 do
case fx[j].Action of
faModified:
s:=s+' AND Ref.m_ts<'+CritDate(fx[j]);
faFrom:
s:=s+' AND Ref.m_ts>='+CritTime(fx[j]);
faTill:
s:=s+' AND Ref.m_ts<='+CritTime(fx[j]);
else
raise EtxSqlQueryError.Create('Unexpected rt parameter at position '+IntToStr(fx[j].Idx1));
end;
//TODO: fx[j].Operator
finally
fx.Free;
end;
end;
AddWhereQuery('Obj.id',s);
end;
faRef,faBackRef:
begin
s:='';
if f[i].Parameters<>'' then
begin
fx:=TtxFilter.Create;
try
fx.FilterExpression:=f[i].Parameters;
for j:=0 to fx.Count-1 do
case fx[j].Action of
faRefType:
begin
inc(AliasCount);
t:='rxSQ'+IntToStrU(AliasCount);
s:=s+' AND Ref.reftype_id'+Criterium(fx[j],
'DISTINCT '+t+'.id','RIGHT JOIN Ref AS '+t+' ON '+t+'.ref_obj'+RefBSel[f[i].Action=faBackRef]+'_id=Obj.id',false,false);
end;
faModified:
s:=s+' AND Ref.m_ts<'+CritDate(fx[j]);
faFrom:
s:=s+' AND Ref.m_ts>='+CritTime(fx[j]);
faTill:
s:=s+' AND Ref.m_ts<='+CritTime(fx[j]);
else
raise EtxSqlQueryError.Create('Unexpected rx parameter at position '+IntToStr(f[i].Idx1));
end;
//TODO: fx[j].Operator
finally
fx.Free;
end;
end;
AddWhere('Obj.id IN (SELECT Ref.obj'+RefBSel[f[i].Action=faRef]+'_id FROM Ref WHERE Ref.obj'+RefBSel[f[i].Action=faBackRef]+'_id'+Criterium(f[i],
'Obj.id','',false,false)+s+')');
end;
faParent:
case f[i].IDType of
dtNumber:
if TryStrToInt(string(f[i].ID),j) then FParentID:=j else
raise EtxSqlQueryError.Create('Invalid ID at position: '+IntToStr(f[i].Idx1));
//TODO
//dtSystem:;
//dtSubQuery:;
//dtEnvironment:;
else
raise EtxSqlQueryError.Create('Unsupported IDType at position: '+IntToStr(f[i].Idx1));
end;
faModified:
AddWhere('Obj.m_ts<'+CritDate(f[i]));
faFrom:
AddWhere('Obj.m_ts>='+CritTime(f[i]));
faTill:
AddWhere('Obj.m_ts<='+CritTime(f[i]));
faFilter:
begin
if f[i].Descending then raise EtxSqlQueryError.Create('Descending into filter not supported');
fx:=TtxFilter.Create;
try
//TODO: detect loops?
qr:=TQueryResult.Create(Session.DbCon,'SELECT Flt.expression FROM Flt WHERE Flt.id'+Criterium(f[i],'','',false,false)+' LIMIT 1',[]);
try
if qr.EOF then raise EtxSqlQueryError.Create('Filter not found at position '+IntToStr(f[i].Idx1));
fx.FilterExpression:=UTF8Encode(qr.GetStr(0));
finally
qr.Free;
end;
if fx.ParseError<>'' then raise EtxSqlQueryError.Create(
'Invalid filter at position '+IntToStr(f[i].Idx1)+': '+fx.ParseError);
if f[i].Prefetch then
begin
fq:=TtxSqlQueryFragments.Create(FItemType);
try
fq.AddFilter(fx);
fq.Fields:='Obj.id';
fq.OrderBy:='';
AddWhereQuery('Obj.id',fq.SQL);
finally
fq.Free;
end;
end
else
AddFilter(fx);
finally
fx.Free;
end;
end;
faName:
begin
AddWhere('Obj.name='+SqlStr(f[i].ID));
OrderBy:='Obj.m_ts, Obj.weight, Obj.name';
end;
faDesc:
begin
AddWhere('Obj.'+sqlDesc+' LIKE '+SqlStr(f[i].ID));
OrderBy:='Obj.m_ts, Obj.weight, Obj.name';
end;
faSearchName:
begin
AddWhere('Obj.name LIKE '+SqlStr(f[i].ID));//parentheses?
OrderBy:='Obj.m_ts, Obj.weight, Obj.name';
end;
faSearch:
begin
//parameters?
k:=1;
s:='';
t:=f[i].ID;
while k<=Length(t) do
begin
j:=k;
while (k<=Length(t)) and not(AnsiChar(t[k]) in [#0..#32]) do inc(k);
if k-j<>0 then
begin
if s<>'' then s:=s+' AND ';
s:=s+'(Obj.name LIKE '+SqlStr('%'+Copy(t,j,k-j)+'%')+' OR Obj.'+sqlDesc+' LIKE '+SqlStr('%'+Copy(t,j,k-j)+'%')+')';
end;
inc(k);
end;
if s='' then s:='0=1';//match none? match all?
AddWhere(s);//parentheses?
OrderBy:='Obj.m_ts, Obj.weight, Obj.name';
end;
faSearchReports:
begin
AddFrom('INNER JOIN Rpt ON Rpt.obj_id=Obj.id');
//parameters?
k:=1;
s:='';
t:=f[i].ID;
while k<=Length(t) do
begin
j:=k;
while (k<=Length(t)) and not(AnsiChar(t[k]) in [#0..#32]) do inc(k);
if k-j<>0 then
begin
if s<>'' then s:=s+' AND ';
s:=s+'Rpt.'+sqlDesc+' LIKE '+SqlStr('%'+Copy(t,j,k-j)+'%');
end;
inc(k);
end;
if s='' then s:='0=1';//match none? match all?
AddWhere('('+s+')');
//OrderBy:=//assert already Rpt.ts desc
end;
faTerm:
begin
AddFrom('INNER JOIN Trm ON Trm.obj_id=Obj.id');
//parameters?
k:=1;
s:='';
t:=f[i].ID;
while k<=Length(t) do
begin
j:=k;
while (k<=Length(t)) and not(AnsiChar(t[k]) in [#0..#32]) do inc(k);
if k-j<>1 then
begin
if s<>'' then s:=s+' OR ';//AND?
//s:=s+'Trm.term LIKE '+SqlStr('%'+Copy(t,j,k-j)+'%');
s:=s+'Trm.term='+SqlStr(Copy(t,j,k-j));
end;
inc(k);
end;
if s='' then s:='0=1';//match none? match all?
AddWhere('('+s+')');
end;
faAlwaysTrue:
if (f[i].ParaClose=0) and (i<>f.Count-1) then
case f[i].Operator of
foAnd:;//skip
foAndNot:Where:=Where+'NOT ';
else AddWhere('1=1');
end
else AddWhere('1=1');
faAlwaysFalse:
if (f[i].ParaClose=0) and (i<>f.Count-1) then
case f[i].Operator of
foOr:;//skip
foOrNot:Where:=Where+'NOT ';
else AddWhere('0=1');
end
else AddWhere('0=1');
faSQL:
begin
AddWhereSafe(f[i].ID);
AddWhereSafe(f[i].Parameters);
end;
faExtra:;//TODO: filterparameters
faPath:
AddWhere('Obj.id'+Criterium(f[i],'Obj.pid','',false,true));
faPathObjType:
AddWhere('Obj.objtype_id'+Criterium(f[i],'DISTINCT ObjType.pid','',false,true));
faPathTokType:
begin
inc(AliasCount);
t:='ptSQ'+IntToStrU(AliasCount);
AddWhereQuery('Obj.id','SELECT DISTINCT Tok.obj_id FROM Tok WHERE Tok.toktype_id'+Criterium(f[i],
'DISTINCT '+t+'.toktype_pid','RIGHT JOIN Tok AS '+t+' ON '+t+'.obj_id=Obj.id',false,true));
end;
faPathRefType:
begin
inc(AliasCount);
t:='prSQ'+IntToStrU(AliasCount);
AddWhereQuery('Obj.id','SELECT DISTINCT Ref.obj1_id FROM Ref WHERE Ref.reftype_id'+Criterium(f[i],
'DISTINCT '+t+'.reftype_pid','RIGHT JOIN Ref AS '+t+' ON '+t+'.obj1_id=Obj.id',false,true));
end;
faPathInclSelf:
AddWhere('Obj.id'+Criterium(f[i],'Obj.id','',false,true));
faCreated:
AddWhere('Obj.c_uid'+Criterium(f[i],'Obj.id','',false,false));
faTokCreated:
begin
s:='SELECT DISTINCT Tok.obj_id FROM Tok WHERE Tok.c_uid'+Criterium(f[i],'Obj.id','',false,false);
if f[i].Parameters<>'' then
begin
fx:=TtxFilter.Create;
try
fx.FilterExpression:=f[i].Parameters;
for j:=0 to fx.Count-1 do
case fx[j].Action of
faModified:
s:=s+' AND Tok.m_ts<'+CritDate(fx[j]);
faFrom:
s:=s+' AND Tok.m_ts>='+CritTime(fx[j]);
faTill:
s:=s+' AND Tok.m_ts<='+CritTime(fx[j]);
else
raise EtxSqlQueryError.Create('Unexpected ttr parameter at position '+IntToStr(fx[j].Idx1));
end;
//TODO: fx[j].Operator
finally
fx.Free;
end;
end;
AddWhereQuery('Obj.id',s);
end;
faRefCreated,faBackRefCreated:
begin
s:='';
if f[i].Parameters<>'' then
begin
fx:=TtxFilter.Create;
try
fx.FilterExpression:=f[i].Parameters;
for j:=0 to fx.Count-1 do
case fx[j].Action of
faRefType:
begin
inc(AliasCount);
t:='urSQ'+IntToStrU(AliasCount);
s:=s+' AND Ref.reftype_id'+Criterium(fx[j],'DISTINCT '+t+'.id','RIGHT JOIN Ref AS '+t+' ON '+t+
'.ref_obj'+RefBSel[fx[j].Action=faBackRefCreated]+'_id=Obj.id',false,false);
end;
faModified:
s:=s+' AND Ref.m_ts<'+CritDate(fx[j]);
faFrom:
s:=s+' AND Ref.m_ts>='+CritTime(fx[j]);
faTill:
s:=s+' AND Ref.m_ts<='+CritTime(fx[j]);
else
raise EtxSqlQueryError.Create('Unexpected rtr parameter at position '+IntToStr(fx[j].Idx1));
end;
//TODO: fx[j].Operator
finally
fx.Free;
end;
end;
AddWhereQuery('Obj.id','SELECT DISTINCT Ref.obj'+RefBSel[f[i].Action=faBackRefCreated]+'_id FROM Ref WHERE Ref.c_uid'+
Criterium(f[i],'Obj.id','',false,false)+s);
end;
faRecentObj:
begin
AddWhere('Obj.id'+Criterium(f[i],'Obj.id','',false,false));
AddOrderBy('Obj.m_ts DESC');
end;
faRecentTok:
begin
AddFrom('INNER JOIN Tok ON Obj.id=Tok.obj_id');
AddOrderBy('Tok.m_ts DESC');
inc(AliasCount);
t:='ttSQ'+IntToStrU(AliasCount);
if f[i].Prefetch then
AddWhereQuery('Tok.id','SELECT DISTINCT Tok.id FROM Tok WHERE Tok.toktype_id'+Criterium(f[i],
'DISTINCT '+t+'toktype_id','RIGHT JOIN Tok AS '+t+' ON '+t+'.obj_id=Obj.id',false,false))
else
AddWhere('Tok.toktype_id'+Criterium(f[i],
'DISTINCT '+t+'toktype_id','RIGHT JOIN Tok AS '+t+' ON '+t+'.obj_id=Obj.id',false,false));
end;
faRecentRef,faRecentBackRef:
begin
AddFrom('INNER JOIN Ref ON Ref.obj'+RefBSel[f[i].Action=faRecentBackRef]+'_id=Obj.id');
AddOrderBy('Ref.m_ts DESC');
inc(AliasCount);
t:='rtSQ'+IntToStrU(AliasCount);
if f[i].Prefetch then
AddWhereQuery('Ref.id','SELECT DISTINCT Ref.id FROM Ref WHERE Ref.reftype_id'+Criterium(f[i],
'DISTINCT '+t+'reftype_id','RIGHT JOIN Ref AS '+t+' ON '+t+'.obj'+
RefBSel[f[i].Action=faRecentBackRef]+'_id=Obj.id',false,false))
else
AddWhere('Ref.reftype_id'+Criterium(f[i],
'DISTINCT '+t+'.reftype_id','RIGHT JOIN Ref AS '+t+' ON '+t+'.obj'+
RefBSel[f[i].Action=faRecentBackRef]+'_id=Obj.id',false,false));
end;
faUser:
begin
AddFrom('INNER JOIN Usr ON Usr.uid=Obj.id');
AddWhere('Obj.id'+Criterium(f[i],'Usr.uid','',false,false));
end;
faRealm:
AddWhere('Obj.rlm_id'+Criterium(f[i],'Rlm.id','',false,false));
faUnread:
begin
if Session.IsAdmin('logins') and not((f[i].IDType=dtNumber) and ((f[i].ID='0') or (f[i].ID=''))) then
s:=Criterium(f[i],'Obj.id','',false,false)
else
s:='='+IntToStrU(Session.UserID);
AddWhere('EXISTS (SELECT Obx.id FROM Obx'+
' LEFT OUTER JOIN Urx ON Urx.uid'+s+
' AND Obx.id BETWEEN Urx.id1 AND Urx.id2'+
' WHERE Obx.obj_id=Obj.id AND Urx.id IS NULL)');
end;
faJournal,faJournalUser,faJournalEntry,faJournalEntryUser:
begin
if Session.IsAdmin('journals') then s:='' else
begin
s:='';
k:=0;
for j:=0 to Length(Session.Journals)-1 do
if Session.Journals[j].CanConsult then
begin
s:=s+','+IntToStrU(Session.Journals[j].jrl_id);
inc(k);
end;
case k of
0:raise Exception.Create('You currently have no consult permissions on any journals.');//s:=' AND 0=1';//?
1:s[1]:='=';
else
begin
s[1]:='(';
s:='IN '+s+')';
end;
end;
s:='Jrt.jrl_id'+s;
end;
if f[i].Parameters<>'' then
begin
fx:=TtxFilter.Create;
try
fx.FilterExpression:=f[i].Parameters;
for j:=0 to fx.Count-1 do
case fx[j].Action of
faJournal:
begin
if s<>'' then s:=s+' AND ';
s:=s+'Jrt.jrl_id'+Criterium(fx[j],'Jrl.id','',false,false);
end;
else
raise EtxSqlQueryError.Create('Unexpected j parameter at position '+IntToStr(fx[j].Idx1));
end;
//TODO: fx[j].Operator
finally
fx.Free;
end;
end;
if s<>'' then s:=s+' AND ';
case f[i].Action of
faJournal:
AddWhereQuery('Obj.id','SELECT DISTINCT Jre.obj_id FROM Jre INNER JOIN Jrt ON Jrt.id=Jre.jrt_id WHERE '+s+
'Jrt.jrl_id'+Criterium(f[i],'Jrl.id','',false,false));
faJournalUser:
AddWhereQuery('Obj.id','SELECT DISTINCT Jre.uid FROM Jre INNER JOIN Jrt ON Jrt.id=Jre.jrt_id WHERE '+s+
'Jrt.jrl_id'+Criterium(f[i],'Jrl.id','',false,false));
faJournalEntry:
AddWhereQuery('Obj.id','SELECT DISTINCT Jre.obj_id FROM Jre INNER JOIN Jrt ON Jrt.id=Jre.jrt_id WHERE '+s+
'Jre.uid'+Criterium(f[i],'Obj.id','',false,false));
faJournalEntryUser:
AddWhereQuery('Obj.id','SELECT DISTINCT Jre.uid FROM Jre INNER JOIN Jrt ON Jrt.id=Jre.jrt_id WHERE '+s+
'Jre.obj_id'+Criterium(f[i],'Obj.id','',false,false));
end;
end;
else
raise EtxSqlQueryError.Create('Unsupported filter action at position '+IntToStr(f[i].Idx1));
end;
//check global para count?
for j:=1 to f[i].ParaClose do Where:=Where+')';
if (i<>f.Count-1) and AddedWhere then
Where:=Where+' '+txFilterOperatorSQL[f[i].Operator]+' ';
end;
end;
function TtxSqlQueryFragments.BuildSQL: UTF8String;
var
m:TMemoryStream;
procedure Add1(const s:UTF8String);
begin
m.Write(s[1],Length(s));
end;
procedure Add(const t,u:UTF8String);
begin
if u<>'' then
begin
m.Write(t[1],Length(t));
m.Write(u[1],Length(u));
end;
end;
var
l:integer;
begin
m:=TMemoryStream.Create;
try
Add1('SELECT ');
Add1(Fields);
Add1(#13#10'FROM ');
Add1(Tables);//assert ends in #13#10
Add('WHERE ',Where);
Add(#13#10'GROUP BY ',GroupBy);
Add(#13#10'HAVING ',Having);
Add(#13#10'ORDER BY ',OrderBy);
if Limit<>-1 then Add1(#13#10'LIMIT '+IntToStrU(Limit));
//MySql: Add1(' LIMIT '+IntToStrU(Limit)+',0');
l:=m.Position;
SetLength(Result,l);
m.Position:=0;
m.Read(Result[1],l);
finally
m.Free;
end;
end;
procedure TtxSqlQueryFragments.AddWhere(const s:UTF8String);
begin
Where:=Where+s;
AddedWhere:=true;
end;
procedure TtxSqlQueryFragments.AddWhereSafe(const s:UTF8String);
var
i,j:integer;
begin
j:=0;
for i:=1 to Length(s) do
case s[i] of
'''':inc(j);
';':if (j and 1)=0 then raise EtxSqlQueryError.Create('Semicolon in external SQL not allowed');
//TODO: detect and refuse comment? '--' and '/*'
end;
if (j and 1)=1 then raise EtxSqlQueryError.Create('Unterminated string in external SQL detected');
Where:=Where+s;
AddedWhere:=true;
end;
procedure TtxSqlQueryFragments.AddFrom(const s:UTF8String);
begin
if s<>'' then
if Pos(s,Tables)=0 then
Tables:=Tables+s+#13#10;
end;
function TtxSqlQueryFragments.SqlStr(const s:UTF8String): UTF8String;
var
i,j:integer;
begin
j:=0;
for i:=1 to Length(s) do if s[i]='''' then inc(j);
if j=0 then
Result:=''''+s+''''
else
begin
i:=Length(s)+j+2;
SetLength(Result,i);
Result[1]:='''';
Result[i]:='''';
i:=1;
j:=2;
while i<=Length(s) do
begin
if s[i]='''' then
begin
Result[j]:='''';
inc(j);
end;
Result[j]:=s[i];
inc(j);
inc(i);
end;
end;
end;
function TtxSqlQueryFragments.Criterium(const El:TtxFilterElement;
const SubQryField, SubQryFrom: UTF8String;
ParentsOnly, Reverse: boolean): UTF8String;
const
idGrow=$1000;
var
ItemType:TtxItemType;
idSQL,t:UTF8String;
ids,ids1:TIdList;
i,j,l:integer;
fe:TtxFilterEnvVar;
f:TtxFilter;
fq:TtxSqlQueryFragments;
qr:TQueryResult;
begin
ItemType:=txFilterActionItemType[El.Action];
idSQL:='';
ids:=TIdList.Create;
try
t:=txItemTypeTable[ItemType];
case El.IDType of
dtNumber:
if TryStrToInt(string(El.ID),i) then ids.Add(i) else
raise EtxSqlQueryError.Create('Invalid ID at position: '+IntToStr(El.Idx1));
dtNumberList:
begin
i:=1;
l:=Length(El.ID);
while (i<=l) and not(AnsiChar(El.ID[i]) in ['0'..'9']) do inc(i);
while (i<=l) do
begin
j:=0;
while (i<=l) and (AnsiChar(El.ID[i]) in ['0'..'9']) do
begin
j:=j*10+(byte(El.ID[i]) and $F);
inc(i);
end;
ids.Add(j);
while (i<=l) and not(AnsiChar(El.ID[i]) in ['0'..'9']) do inc(i);
end;
end;
dtSystem: //TODO: realms?
case ItemType of
itObj:
idSQL:='SELECT Obj.id FROM Obj WHERE Obj.name LIKE '+SqlStr(El.ID);
itObjType,itTokType,itRefType,itRealm:
idSQL:='SELECT '+t+'.id FROM '+t+' WHERE '+t+'.system='+SqlStr(El.ID);
itFilter:
idSQL:='SELECT Flt.id FROM Flt WHERE Flt.name='+SqlStr(El.ID);
itUser:
idSQL:='SELECT Usr.uid FROM Usr WHERE Usr.login='+SqlStr(El.ID);
itJournal:
idSQL:='SELECT Jrl.id FROM Jrl WHERE Jrl.system='+SqlStr(El.ID);
else
raise EtxSqlQueryError.Create('String search on '+txItemTypeName[ItemType]+' is not allowed');
end;
dtSubQuery:
begin
f:=TtxFilter.Create;
fq:=TtxSqlQueryFragments.Create(ItemType);
try
f.FilterExpression:=El.ID;
if f.ParseError<>'' then
raise EtxSqlQueryError.Create('Error in sub-query :'+f.ParseError);
fq.AddFilter(f);
fq.Fields:=SubQryField;
fq.AddFrom(SubQryFrom);
fq.OrderBy:='';
idSQL:=fq.BuildSQL;
//TODO: realms?
finally
f.Free;
fq.Free;
end;
end;
dtEnvironment:
begin
fe:=TtxFilter.GetFilterEnvVar(El.ID);
case fe of
feUs:idSQL:='SELECT Obj.id FROM Obj WHERE Obj.pid='+IntToStrU(EnvVars[feMe]);
fe_Unknown:raise EtxSqlQueryError.Create('Unknown Filter Environment Variable: '+string(El.ID));
else ids.Add(EnvVars[fe]);
end;
end;
else raise EtxSqlQueryError.Create('Unsupported IDType at position '+IntToStr(El.Idx1));
end;
if (El.Descending or El.Prefetch) and (idSQL<>'') then
begin
qr:=TQueryResult.Create(Session.DbCon,idSQL,[]);
try
while qr.Read do ids.Add(qr.GetInt(0));
finally
qr.Free;
end;
idSQL:='';
end;
if El.Descending then
begin
if Reverse then
if Use_ObjPath and (ItemType=itObj) then
if idSQL='' then
if ids.Count=1 then
idSQL:='SELECT pid FROM ObjPath WHERE oid='+IntToStrU(ids[0])
else
idSQL:='SELECT pid FROM ObjPath WHERE oid IN ('+ids.List+')'
else
idSQL:='SELECT pid FROM ObjPath WHERE oid IN ('+idSQL+')'
else
begin
i:=0;
while i<ids.Count do
begin
qr:=TQueryResult.Create(Session.DbCon,'SELECT '+t+'.pid FROM '+t+' WHERE '+t+'.id='+IntToStrU(ids[i]),[]);
try
while qr.Read do ids.Add(qr.GetInt(0));
finally
qr.Free;
end;
inc(i);
end;
end
else
if ParentsOnly then
begin
if Use_ObjPath and (ItemType=itObj) then
if idSQL='' then
if ids.Count=1 then
idSQL:='SELECT DISTINCT X2.pid FROM ObjPath X1 INNER JOIN Obj X2 ON X1.pid<>X1.oid AND X2.id=X1.oid WHERE X1.pid='+IntToStrU(ids[0])
else
idSQL:='SELECT DISTINCT X2.pid FROM ObjPath X1 INNER JOIN Obj X2 ON X1.pid<>X1.oid AND X2.id=X1.oid WHERE X1.pid IN ('+ids.List+')'
else
idSQL:='SELECT DISTINCT X2.pid FROM ObjPath X1 INNER JOIN Obj X2 ON X1.pid<>X1.oid AND X2.id=X1.oid WHERE X1.pid IN ('+idSQL+')'
else
begin
ids1:=TIdList.Create;
try
ids1.AddList(ids);
ids.Clear;
i:=0;
while i<ids1.Count do
begin
//only add those with children
qr:=TQueryResult.Create(Session.DbCon,'SELECT '+t+'.id FROM '+t+' WHERE '+t+'.pid='+IntToStrU(ids1[i]),[]);
try
if not qr.EOF then ids.Add(ids1[i]);
while qr.Read do ids1.AddClip(qr.GetInt(0),i);
finally
qr.Free;
end;
inc(i);
end;
finally
ids1.Free;
end;
end;
end
else
begin
//full expand
if Use_ObjPath and (ItemType=itObj) then
if idSQL='' then
if ids.Count=1 then
idSQL:='SELECT oid FROM ObjPath WHERE pid='+IntToStrU(ids[0])
else
idSQL:='SELECT oid FROM ObjPath WHERE pid IN ('+ids.List+')'
else
idSQL:='SELECT oid FROM ObjPath WHERE pid IN ('+idSQL+')'
else
begin
i:=0;
while i<ids.Count do
begin
qr:=TQueryResult.Create(Session.DbCon,'SELECT '+t+'.id FROM '+t+' WHERE '+t+'.pid='+IntToStrU(ids[i]),[]);
try
while qr.Read do ids.Add(qr.GetInt(0));
finally
qr.Free;
end;
inc(i);
end;
end;
end;
end
else
if Reverse then //one level up
for i:=0 to ids.Count-1 do
begin
qr:=TQueryResult.Create(Session.DbCon,'SELECT '+t+'.pid FROM '+t+' WHERE '+t+'.id='+IntToStrU(ids[i]),[]);
try
ids[i]:=qr.GetInt(0);
finally
qr.Free;
end;
end;
if idSQL='' then
case ids.Count of
0:Result:='=-1';
1:Result:='='+IntToStrU(ids[0]);
else Result:=' IN ('+ids.List+')';
end
else
Result:=' IN ('+idSQL+')';
finally
ids.Free;
end;
end;
procedure TtxSqlQueryFragments.AddOrderBy(const s: UTF8String);
begin
if s<>'' then
if OrderBy='' then OrderBy:=s else
if Pos(s,OrderBy)=0 then
OrderBy:=s+', '+OrderBy;
end;
{ TIdList }
constructor TIdList.Create;
begin
inherited Create;
Clear;
end;
destructor TIdList.Destroy;
begin
SetLength(ids,0);
inherited;
end;
const
IdListGrow=$1000;
procedure TIdList.Add(id: integer);
begin
if idCount=idSize then
begin
inc(idSize,IdListGrow);
SetLength(ids,idSize);
end;
ids[idCount]:=id;
inc(idCount);
end;
procedure TIdList.AddList(list: TIdList);
var
l:integer;
begin
l:=List.Count;
while (idSize<idCount+l) do inc(idSize,IdListGrow);
SetLength(ids,idSize);
Move(list.ids[0],ids[idCount],l*4);
inc(idCount,l);
end;
procedure TIdList.AddClip(id:integer; var Clip:integer);
var
i:integer;
begin
//things before Clip no longer needed
i:=Clip div IdListGrow;
if i<>0 then
begin
i:=i*IdListGrow;
//shrink? keep data for re-use (idSize)
Move(ids[i],ids[0],i*4);
dec(Clip,i);
dec(idCount,i);
end;
Add(id);
end;
procedure TIdList.Clear;
begin
idCount:=0;
idSize:=0;
//SetLength(ids,idSize);//keep allocated data for re-use
end;
function TIdList.GetList: UTF8String;
var
i:integer;
begin
if idCount=0 then Result:='' else
begin
Result:=IntToStrU(ids[0]);
i:=1;
while i<idCount do
begin
Result:=Result+','+IntToStrU(ids[i]) ;
inc(i);
end;
end;
end;
function TIdList.GetItem(Idx: integer): integer;
begin
Result:=ids[Idx];
end;
procedure TIdList.SetItem(Idx, Value: integer);
begin
ids[Idx]:=Value;
end;
function TIdList.Contains(id:integer):boolean;
var
i:integer;
begin
i:=0;
while (i<idCount) and (ids[i]<>id) do inc(i);
Result:=i<idCount;
end;
end.
|
unit Odontologia.Modelo.Medico;
interface
uses
Data.DB,
SimpleDAO,
SimpleInterface,
SimpleQueryRestDW,
System.SysUtils,
Odontologia.Modelo.Conexion.RestDW,
Odontologia.Modelo.Medico.Interfaces,
Odontologia.Modelo.Estado,
Odontologia.Modelo.Estado.Interfaces,
Odontologia.Modelo.Entidades.Medico;
type
TModelMedico = class(TInterfacedOBject, iModelMedico)
private
FEntidad : TDMEDICO;
FDAO : iSimpleDao<TDMEDICO>;
FDataSource : TDataSource;
FESTADO : iModelEstado;
public
constructor Create;
destructor Destroy; override;
class function New : iModelMedico;
function Entidad : TDMEDICO; overload;
function Entidad(aEntidad: TDMEDICO) : iModelMedico; overload;
function DAO : iSimpleDAO<TDMEDICO>;
function DataSource(aDataSource: TDataSource) : iModelMedico;
function Estado : iModelEstado;
end;
implementation
{ TModelMedico }
constructor TModelMedico.Create;
begin
FEntidad := TDMEDICO.Create;
FDAO := TSimpleDAO<TDMEDICO>
.New(TSimpleQueryRestDW<TDMEDICO>
.New(ModelConexion.RESTDWDataBase1));
FESTADO := TModelEstado.New;
end;
function TModelMedico.DAO: iSimpleDao<TDMEDICO>;
begin
Result := FDAO;
end;
function TModelMedico.DataSource(aDataSource: TDataSource): iModelMedico;
begin
Result := Self;
FDataSource := aDataSource;
FDAO.DataSource(FDataSource);
end;
destructor TModelMedico.Destroy;
begin
FreeAndNil(FEntidad);
inherited;
end;
function TModelMedico.Entidad(aEntidad: TDMEDICO): iModelMedico;
begin
Result := Self;
FEntidad := aEntidad;
end;
function TModelMedico.Entidad: TDMEDICO;
begin
Result := FEntidad;
end;
class function TModelMedico.New: iModelMedico;
begin
Result := Self.Create;
end;
function TModelMedico.Estado: iModelEstado;
begin
Result := FESTADO;
end;
end.
|
unit FSelectDrive;
(*====================================================================
Dialog box for selecting the drive to be scanned
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, FileCtrl, ExtCtrls,
UTypes;
type
{ TFormSelectDrive }
TFormSelectDrive = class(TForm)
ListBoxDrives: TListBox;
Panel1: TPanel;
ButtonCancel: TButton;
ButtonOK: TButton;
CheckBoxNoQueries: TCheckBox;
procedure ButtonOKClick(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormShow(Sender: TObject);
procedure ListBoxDrivesDblClick(Sender: TObject);
procedure CheckBoxNoQueriesClick(Sender: TObject);
private
SaveItemIndex: Integer;
public
procedure DefaultHandler(var Message); override;
procedure SetFormSize;
{ Public declarations }
end;
var
FormSelectDrive: TFormSelectDrive;
implementation
uses IniFiles, UDrives, FSettings;
{$R *.dfm}
//-----------------------------------------------------------------------------
procedure TFormSelectDrive.ButtonOKClick(Sender: TObject);
begin
if ListBoxDrives.MultiSelect and (ListBoxDrives.SelCount >= 0) or
(ListBoxDrives.ItemIndex >= 0) then
ModalResult := mrOk;
end;
//-----------------------------------------------------------------------------
procedure TFormSelectDrive.ButtonCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFormSelectDrive.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
var
i: integer;
begin
for i := 0 to DriveList.Count - 1 do
Dispose(TPDrive(DriveList.Objects[i]));
DriveList.Clear;
end;
//-----------------------------------------------------------------------------
procedure TFormSelectDrive.FormShow(Sender: TObject);
var
i: Integer;
begin
Screen.Cursor := crHourGlass; // sometimes it takes long time to create the list
BuildDriveList;
if (ListBoxDrives.MultiSelect)
then
begin
if (ListBoxDrives.Items.Count > 0) then
begin
SaveItemIndex := 0;
for i:= 0 to pred(ListBoxDrives.Items.Count) do
if ListBoxDrives.Selected[i] then
begin
SaveItemIndex := i;
break;
end;
end
end
else
begin
if (ListBoxDrives.ItemIndex) >= 0 then
SaveItemIndex := ListBoxDrives.ItemIndex;
end;
ListBoxDrives.Items.Clear;
for i := 0 to pred(DriveList.Count) do
ListBoxDrives.Items.Add(DriveList.Strings[i]);
if SaveItemIndex > pred(DriveList.Count) then SaveItemIndex := pred(DriveList.Count);
try
if (ListBoxDrives.MultiSelect)
then
ListBoxDrives.Selected[SaveItemIndex] := true
else
ListBoxDrives.ItemIndex := SaveItemIndex;
except
end;
ActiveControl := ListBoxDrives;
Screen.Cursor := crDefault;
CheckBoxNoQueries.Checked := g_CommonOptions.bNoQueries;
BringToFront;
end;
//-----------------------------------------------------------------------------
// Resizable form - restore the size from the last time
procedure TFormSelectDrive.SetFormSize;
var
IniFile: TIniFile;
SLeft, STop, SWidth, SHeight: integer;
begin
IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
SLeft := IniFile.ReadInteger ('ScanDiskWindow', 'Left',
(Screen.Width - Width) div 2);
STop := IniFile.ReadInteger ('ScanDiskWindow', 'Top',
(Screen.Height - Height) div 2);
SWidth := IniFile.ReadInteger ('ScanDiskWindow', 'Width', Width);
SHeight := IniFile.ReadInteger ('ScanDiskWindow', 'Height', Height);
SaveItemIndex := IniFile.ReadInteger ('ScanDiskWindow', 'Position', 0);
IniFile.Free;
SetBounds(SLeft, STop, SWidth, SHeight);
end;
//-----------------------------------------------------------------------------
procedure TFormSelectDrive.ListBoxDrivesDblClick(Sender: TObject);
var
i: integer;
begin
///ButtonOKClick(Sender);
i:= DriveList.IndexOf(ListBoxDrives.Items[ListBoxDrives.ItemIndex]);
//showmessage(TDriveObj(DriveList.Objects[i]).Drive.Name);
showmessage(TPDrive(DriveList.Objects[i]).Name);
//showmessage(ListBoxDrives.Items[ListBoxDrives.ItemIndex]);
end;
//-----------------------------------------------------------------------------
// Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay
// to the top window, so we must have this handler in all forms.
procedure TFormSelectDrive.DefaultHandler(var Message);
begin
with TMessage(Message) do
if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and
g_CommonOptions.bDisableCdAutorun
then
Result := 1
else
inherited DefaultHandler(Message)
end;
//-----------------------------------------------------------------------------
procedure TFormSelectDrive.CheckBoxNoQueriesClick(Sender: TObject);
begin
g_CommonOptions.bNoQueries := CheckBoxNoQueries.Checked;
end;
//-----------------------------------------------------------------------------
end.
|
// SwinGame.pas was generated on 2016-05-18 15:40:10.114231
//
// This is a wrapper unit that exposes all of the SwinGame API in a single
// location. To create a SwinGame project all you should need to use is
// SwinGame and sgTypes.
unit SwinGame;
interface
uses sgTypes, sgAnimations, sgAudio, sgCamera, sgGeometry, sgGraphics, sgImages, sgInput, sgNetworking, sgWeb, sgPhysics, sgResources, sgSprites, sgText, sgTimers, sgUtils, sgUserInterface, sgArduino, sgDrawingOptions, sgWindowManager;
type Point2D = sgTypes.Point2D;
type Vector = sgTypes.Vector;
type Rectangle = sgTypes.Rectangle;
type Quad = sgTypes.Quad;
type Circle = sgTypes.Circle;
type LineSegment = sgTypes.LineSegment;
type Triangle = sgTypes.Triangle;
type Resolution = sgTypes.Resolution;
type WndIR = sgTypes.WndIR;
type Window = sgTypes.Window;
type SoundEffect = sgTypes.SoundEffect;
type Music = sgTypes.Music;
type Matrix2D = sgTypes.Matrix2D;
type Color = sgTypes.Color;
type AnimationScript = sgTypes.AnimationScript;
type Animation = sgTypes.Animation;
type BmpIR = sgTypes.BmpIR;
type Bitmap = sgTypes.Bitmap;
type DrawingDest = sgTypes.DrawingDest;
type DrawingOptions = sgTypes.DrawingOptions;
type CollisionSide = sgTypes.CollisionSide;
type ResourceKind = sgTypes.ResourceKind;
type CollisionTestKind = sgTypes.CollisionTestKind;
type SpriteEventKind = sgTypes.SpriteEventKind;
type Sprite = sgTypes.Sprite;
type SpriteEventHandler = sgTypes.SpriteEventHandler;
type SpriteFunction = sgTypes.SpriteFunction;
type SpriteSingleFunction = sgTypes.SpriteSingleFunction;
type Timer = sgTypes.Timer;
type Font = sgTypes.Font;
type FontStyle = sgTypes.FontStyle;
type FontAlignment = sgTypes.FontAlignment;
type MouseButton = sgTypes.MouseButton;
type KeyCode = sgTypes.KeyCode;
type FreeNotifier = sgTypes.FreeNotifier;
type GUIElementKind = sgTypes.GUIElementKind;
type EventKind = sgTypes.EventKind;
type FileDialogSelectType = sgTypes.FileDialogSelectType;
type Panel = sgTypes.Panel;
type Region = sgTypes.Region;
type GUIEventCallback = sgTypes.GUIEventCallback;
type ArduinoDevice = sgTypes.ArduinoDevice;
type ConnectionType = sgTypes.ConnectionType;
type HRESPIR = sgTypes.HRESPIR;
type HttpResponse = sgTypes.HttpResponse;
type CONIR = sgTypes.CONIR;
type MSGIR = sgTypes.MSGIR;
type SVRRIR = sgTypes.SVRRIR;
type Connection = sgTypes.Connection;
type Message = sgTypes.Message;
type ServerSocket = sgTypes.ServerSocket;
// Returns the number of Animations within an Animation Script.
function AnimationCount(script: AnimationScript): Longint; overload;
// Returns the current cell (the part of the image or sprite) of this animation.
// This can be used to animate an image or sprite.
function AnimationCurrentCell(anim: Animation): Longint; overload;
// Returns the vector assigned to the current frame in the animation.
function AnimationCurrentVector(anim: Animation): Vector; overload;
// Indicates if an animation has ended. Animations with loops will never end.
function AnimationEnded(anim: Animation): Boolean; overload;
// Returns true if the animation entered a new frame on its last update.
// This can be used to trigger actions on frames within an animation.
function AnimationEnteredFrame(anim: Animation): Boolean; overload;
// Returns the amount of time spent in the current frame. When this exceeds
// the frames duration the animation moves to the next frame.
function AnimationFrameTime(anim: Animation): Single; overload;
// The index of the animation within the animation template that has the supplied name.
function AnimationIndex(temp: AnimationScript; const name: String): Longint; overload;
// The name of the animation currently being played.
function AnimationName(temp: Animation): String; overload;
// The name of the animation within the animation template at the specified index.
function AnimationName(temp: AnimationScript; idx: Longint): String; overload;
// Returns the name of the Animation Script.
function AnimationScriptName(script: AnimationScript): String; overload;
// Returns the `AnimationScript` that has been loaded with the specified ``name``,
// see `LoadAnimationScriptNamed`.
function AnimationScriptNamed(const name: String): AnimationScript; overload;
// Assign a new starting animation to the passed in animation from the `AnimationScript`.
// This may play a sound if the first frame of the animation is linked to a sound effect.
procedure AssignAnimation(anim: Animation; idx: Longint; script: AnimationScript); overload;
// Assign a new starting animation to the passed in animation from the `AnimationScript`.
// This may play a sound if the first frame of the animation is linked to a sound effect.
procedure AssignAnimation(anim: Animation; const name: String; script: AnimationScript); overload;
// Assign a new starting animation to the passed in animation from the `AnimationScript`.
// This may play a sound if the first frame of the animation is linked to a sound effect, and withSound is true.
procedure AssignAnimation(anim: Animation; const name: String; script: AnimationScript; withSound: Boolean); overload;
// Assign a new starting animation to the passed in animation from the `AnimationScript`.
// This may play a sound if the first frame of the animation is linked to a sound effect, and
// ``withSound`` is ``true``.
procedure AssignAnimation(anim: Animation; idx: Longint; script: AnimationScript; withSound: Boolean); overload;
// Creates an animation from a `AnimationScript`. This may play a sound effect
// if the animation is set to play a sound effect on its first frame.
function CreateAnimation(const identifier: String; script: AnimationScript): Animation; overload;
// Creates an animation from an `AnimationScript`. This may play a sound effect
// if the animation is set to play a sound effect on its first frame.
function CreateAnimation(identifier: Longint; script: AnimationScript): Animation; overload;
// Creates an animation from an `AnimationScript`. If ``withSound`` is ``true``, this may
// play a sound effect if the animation is set to play a sound effect on its first frame.
function CreateAnimation(identifier: Longint; script: AnimationScript; withSound: Boolean): Animation; overload;
// Creates an animation from a `AnimationScript`. If ``withSound`` is ``true``, this may
// play a sound effect if the animation is set to play a sound effect on its first frame.
function CreateAnimation(const identifier: String; script: AnimationScript; withSound: Boolean): Animation; overload;
// Uses the animation information to draw a bitmap at the specified
// point.
procedure DrawAnimation(ani: Animation; bmp: Bitmap; const pt: Point2D); overload;
// Uses the animation information to draw a bitmap at the specified
// point given the passed in options.
procedure DrawAnimation(ani: Animation; bmp: Bitmap; const pt: Point2D; const opts: DrawingOptions); overload;
// Uses the `Animation` information to draw a `Bitmap` at the specified
// ``x``,``y`` location.
procedure DrawAnimation(ani: Animation; bmp: Bitmap; x: Single; y: Single); overload;
// Uses the animation information to draw a bitmap at the specified
// x,y location given the passed in options.
procedure DrawAnimation(ani: Animation; bmp: Bitmap; x: Single; y: Single; const opts: DrawingOptions); overload;
// Disposes of the resources used in the animation.
procedure FreeAnimation(var ani: Animation); overload;
// Frees loaded animation frames data. Use this when you will no longer be
// using the animation for any purpose, including within sprites.
procedure FreeAnimationScript(var scriptToFree: AnimationScript); overload;
// Determines if SwinGame has animation frames loaded for the supplied ``name``.
// This checks against all loaded animation frames, those loaded without a name
// are assigned the filename as a default.
function HasAnimationScript(const name: String): Boolean; overload;
// Load animation details from a animation frames file.
function LoadAnimationScript(const filename: String): AnimationScript; overload;
// Loads and returns a `AnimationScript`. The supplied ``filename`` is used to
// locate the `AnimationScript` to load. The supplied ``name`` indicates the
// name to use to refer to this in SwinGame. The `AnimationScript` can then be
// retrieved by passing this ``name`` to the `AnimationScriptNamed` function.
function LoadAnimationScriptNamed(const name: String; const filename: String): AnimationScript; overload;
// Releases all of the animation templates that have been loaded.
procedure ReleaseAllAnimationScripts(); overload;
// Releases the SwinGame resources associated with the animation template of the
// specified ``name``.
procedure ReleaseAnimationScript(const name: String); overload;
// Restarts the animation. This may play a sound effect if the first frame
// triggers a sound.
procedure RestartAnimation(anim: Animation); overload;
// Restarts the animation. This may play a sound effect if the first frame
// triggers a sound and withSound is true.
procedure RestartAnimation(anim: Animation; withSound: Boolean); overload;
// Updates the animation, updating the time spent and possibly moving to a new
// frame in the animation. This may play a sound effect if the new frame
// triggers a sound.
procedure UpdateAnimation(anim: Animation); overload;
// Updates the animation a certain percentage and possibly moving to a new
// frame in the animation. This may play a sound effect if the new frame
// triggers a sound.
procedure UpdateAnimation(anim: Animation; pct: Single); overload;
// Updates the animation a certain percentage and possibly moving to a new
// frame in the animation. This may play a sound effect if the new frame
// triggers a sound and withSound is true.
procedure UpdateAnimation(anim: Animation; pct: Single; withSound: Boolean); overload;
// `AudioReady` indicates if SwinGame's audio has been opened. Sound effects
// and Music can only be played with the audio is "ready".
function AudioReady(): Boolean; overload;
// `CloseAudio` is used to clean up the resources used by SwinGame audio. If
// `OpenAudio` is called, this must be called to return the resources used
// before the program terminates.
procedure CloseAudio(); overload;
// Fades the music in over a number of milliseconds, and then continues to
// play the music repeatedly until the program ends or the music is stopped.
// The music fades from 0 volume up to the currently set music volume.
procedure FadeMusicIn(const name: String; ms: Longint); overload;
// Fades the music in over a number of milliseconds, and then continues to
// play the music repeatedly until the program ends or the music is stopped.
// The music fades from 0 volume up to the currently set music volume.
procedure FadeMusicIn(mus: Music; ms: Longint); overload;
// This version of FadeMusicIn fades the music in then plays the 'Music'
// for a given number of loops.Setting loops to -1 repeats the music
// infinitely, other values larger than 0 indicate the number of times that
// the music should be played.
procedure FadeMusicIn(mus: Music; loops: Longint; ms: Longint); overload;
// This version of FadeMusicIn fades the music in then plays the 'Music'
// for a given number of loops.Setting loops to -1 repeats the music
// infinitely, other values larger than 0 indicate the number of times that
// the music should be played.
procedure FadeMusicIn(const name: String; loops: Longint; ms: Longint); overload;
// Fades the currently playing music out over a number of milli seconds.
procedure FadeMusicOut(ms: Longint); overload;
// Frees the resources used by a `Music` resource. All loaded
// `Music` should be freed once it is no longer needed.
procedure FreeMusic(var mus: Music); overload;
// Frees the resources used by a `SoundEffect` resource. All loaded
// `SoundEffect`s should be freed once they are no longer needed.
procedure FreeSoundEffect(var effect: SoundEffect); overload;
// Determines if SwinGame has a music value loaded for the supplied name.
// This checks against all music values loaded using `LoadMusicNamed`.
function HasMusic(const name: String): Boolean; overload;
// Determines if SwinGame has a sound effect loaded for the supplied name.
// This checks against all sounds loaded, those loaded without a name
// are assigned the filename as a default
function HasSoundEffect(const name: String): Boolean; overload;
// Loads the `Music` from the supplied filename. The music will be loaded
// from the Resources/sounds folder unless a full path to the file is passed
// in. If you are passing in the full path and you want toensure that your game
// is able to work across multiple platforms correctly ensure that you use
// `PathToResource` to get the full path to the files in the projects
// resources folder.
//
// LoadMusic can load mp3, wav and ogg audio files.
//
// `FreeMusic` should be called to free the resources used by the
// `Music` data once the resource is no longer needed.
function LoadMusic(const filename: String): Music; overload;
// Loads and returns a music value. The supplied ``filename`` is used to
// locate the music file to load. The supplied ``name`` indicates the
// name to use to refer to this Music value. The `Music` can then be
// retrieved by passing this ``name`` to the `MusicNamed` function.
function LoadMusicNamed(const name: String; const filename: String): Music; overload;
// Loads the `SoundEffect` from the supplied filename. The sound will be loaded
// from the Resources/sounds folder unless a full path to the file is passed
// in. If you are passing in the full path and you want to ensure that your game
// is able to work across multiple platforms correctly then use
// `PathToResource` to get the full path to the files in the projects
// resources folder.
//
// LoadSoundEffect can load wav and ogg audio files.
//
// `FreeSoundEffect` should be called to free the resources used by the
// `SoundEffect` data once the resource is no longer needed.
function LoadSoundEffect(const filename: String): SoundEffect; overload;
// Loads and returns a sound effect. The supplied ``filename`` is used to
// locate the sound effect to load. The supplied ``name`` indicates the
// name to use to refer to this SoundEffect. The `SoundEffect` can then be
// retrieved by passing this ``name`` to the `SoundEffectNamed` function.
function LoadSoundEffectNamed(const name: String; const filename: String): SoundEffect; overload;
// Returns the filename that SwinGame uses to load to this music data.
function MusicFilename(mus: Music): String; overload;
// Returns the name that SwinGame uses to refer to this music data. This
// name can be used to fetch and release this music resource.
function MusicName(mus: Music): String; overload;
// Returns the `Music` that has been loaded with the specified name.
// This works with music data loaded using `LoadMusicNamed`.
function MusicNamed(const name: String): Music; overload;
// This function indicates if music is currently playing. As only one music
// resource can be playing at a time this does not need to be told which
// music resource to check for.
function MusicPlaying(): Boolean; overload;
// This function returns the current volume of the music. This will be a
// value between 0 and 1, with 1 indicating 100% of the `Music` resources
// volume.
function MusicVolume(): Single; overload;
// `OpenAudio` is used to initialise the SwinGame audio code. This should be
// called at the start of your programs code, and is usually coded into the
// starting project templates. After initialising the audio code you can
// load and play `Music` using `LoadMusic` and `PlayMusic`, load and play
// `SoundEffect`s using `LoadSoundEffect` and `PlaySoundEffect`. At the end
// of the program you need to call `CloseAudio` to ensure that the audio
// code is correctly terminated.
procedure OpenAudio(); overload;
// Pauses the currently playing music. See `ResumeMusic`.
procedure PauseMusic(); overload;
// PlayMusic starts playing a `Music` resource. SwinGame only allows one
// music resource to be played at a time. Starting to play a new music
// resource will stop the currently playing music track. You can also stop
// the music by calling `StopMusic`.
//
// By default SwinGame starts playing music at its full volume. This can be
// controlled by calling `SetMusicVolume`. The current volume can be checked
// with `MusicVolume`.
//
// To test if a `Music` resource is currently playing you can use the
// `MusicPlaying` function.
//
// This version of PlayMusic can be used to play background music that is
// looped infinitely. The currently playing music is stopped and the new
// music resource will start playing, and will repeat until `StopMusic` is
// called, or another resource is played.
procedure PlayMusic(const name: String); overload;
// PlayMusic starts playing a `Music` resource. SwinGame only allows one
// music resource to be played at a time. Starting to play a new music
// resource will stop the currently playing music track. You can also stop
// the music by calling `StopMusic`.
//
// By default SwinGame starts playing music at its full volume. This can be
// controlled by calling `SetMusicVolume`. The current volume can be checked
// with `MusicVolume`.
//
// To test if a `Music` resource is currently playing you can use the
// `MusicPlaying` function.
//
// This version of PlayMusic can be used to play background music that is
// looped infinitely. The currently playing music is stopped and the new
// music resource will start playing, and will repeat until `StopMusic` is
// called, or another resource is played.
procedure PlayMusic(mus: Music); overload;
// This version of PlayMusic allows you to control the number of times the
// `Music` resource is repeated. It starts playing the supplied `Music`
// resource, repeating it the numder of times specified in the loops
// parameter. Setting loops to -1 repeats the music infinitely, other values
// larger than 0 indicate the number of times that the music should be
// played.
procedure PlayMusic(mus: Music; loops: Longint); overload;
// This version of PlayMusic allows you to control the number of times the
// `Music` resource is repeated. It starts playing the supplied `Music`
// resource, repeating it the numder of times specified in the loops
// parameter. Setting loops to -1 repeats the music infinitely, other values
// larger than 0 indicate the number of times that the music should be
// played.
procedure PlayMusic(const name: String; loops: Longint); overload;
// There are several versions of PlaySoundEffect that can be used to control
// the way the sound effect plays, allowing you to control its volume and
// the number of times the code loops. In all cases the started sound effect
// is mixed with the currently playing sound effects and music.
//
// With this version of PlaySoundEffect, the started sound effect will be
// played at full volume.
procedure PlaySoundEffect(effect: SoundEffect); overload;
// There are several versions of PlaySoundEffect that can be used to control
// the way the sound effect plays, allowing you to control its volume and
// the number of times the code loops. In all cases the started sound effect
// is mixed with the currently playing sound effects and music.
//
// With this version of PlaySoundEffect, the started sound effect will be
// played at full volume.
procedure PlaySoundEffect(const name: String); overload;
// This version of PlaySoundEffect allows you to control the volume of the
// sounds playback. The vol parameter will take a value between 0 and 1
// indicating the percentage of full volume to play at.
// For example, 0.1 plays the sound effect at 10% of its original volume.
procedure PlaySoundEffect(effect: SoundEffect; vol: Single); overload;
// This version of PlaySoundEffect allows you to indicate the number of times
// the sound effect is repeated. Setting the loops parameter to -1 will cause
// the sound effect to be looped infinitely, setting it to a value larger than
// 0 plays the sound effect the number of times indicated, calling with a
// value of 0 means the sound effect is not played.
procedure PlaySoundEffect(effect: SoundEffect; loops: Longint); overload;
// This version of PlaySoundEffect allows you to control the volume of the
// sounds playback. The vol parameter will take a value between 0 and 1
// indicating the percentage of full volume to play at.
// For example, 0.1 plays the sound effect at 10% of its original volume.
procedure PlaySoundEffect(const name: String; vol: Single); overload;
// This version of PlaySoundEffect allows you to indicate the number of times
// the sound effect is repeated. Setting the loops parameter to -1 will cause
// the sound effect to be looped infinitely, setting it to a value larger than
// 0 plays the sound effect the number of times indicated, calling with a
// value of 0 means the sound effect is not played.
procedure PlaySoundEffect(const name: String; loops: Longint); overload;
// This version of PlaySoundEffect allows you to control both the number
// of times the `SoundEffect` is repeated, and its playback volume.
procedure PlaySoundEffect(effect: SoundEffect; loops: Longint; vol: Single); overload;
// This version of PlaySoundEffect allows you to control both the number
// of times the `SoundEffect` is repeated, and its playback volume.
procedure PlaySoundEffect(const name: String; loops: Longint; vol: Single); overload;
// Releases all of the music data that have been loaded.
procedure ReleaseAllMusic(); overload;
// Releases all of the sound effects that have been loaded.
procedure ReleaseAllSoundEffects(); overload;
// Releases the music that have been loaded with the supplied name.
procedure ReleaseMusic(const name: String); overload;
// Releases the SwinGame resources associated with the sound effect of the
// specified ``name``.
procedure ReleaseSoundEffect(const name: String); overload;
// Resume currently paused music. See `PauseMusic`.
procedure ResumeMusic(); overload;
// This procedure allows you to set the volume of the currently playing
// music. The vol parameter indicates the percentage of the original volume,
// for example, 0.1 sets the playback volume to 10% of its full volume.
procedure SetMusicVolume(value: Single); overload;
// Returns the filename that SwinGame used to load to this sound effect.
function SoundEffectFilename(effect: SoundEffect): String; overload;
// Returns the name that SwinGame uses to refer to this sound effect. This
// name can be used to fetch and release this sound effect resource.
function SoundEffectName(effect: SoundEffect): String; overload;
// Returns the `SoundEffect` that has been loaded with the specified name,
// see `LoadSoundEffectNamed`.
function SoundEffectNamed(const name: String): SoundEffect; overload;
// This function can be used to check if a sound effect is currently
// playing.
function SoundEffectPlaying(const name: String): Boolean; overload;
// This function can be used to check if a sound effect is currently
// playing.
function SoundEffectPlaying(effect: SoundEffect): Boolean; overload;
// Stops playing the current music resource.
procedure StopMusic(); overload;
// Stops all occurances of the effect `SoundEffect` that is currently playing.
procedure StopSoundEffect(effect: SoundEffect); overload;
// Stops all occurances of the named `SoundEffect` that are currently playing.
procedure StopSoundEffect(const name: String); overload;
// `TryOpenAudio` attempts to open the audio device for SwinGame to use.
// If this fails `TryOpenAudio` returns false to indicate that the audio
// device has not opened correctly and audio cannot be played.
function TryOpenAudio(): Boolean; overload;
// Returns the current camera position in world coordinates. This is the top
// left hand corner of the screen.
function CameraPos(): Point2D; overload;
// Returns the x location of the camera in game coordinates. This represents
// the left most x value shown on the screen, with the right of the screen
// being at `CameraX` + `ScreenWidth`.
function CameraX(): Single; overload;
// Returns the y location of the camera in game coordinates. This represents
// the stop most y value shown on the screen, with bottom of screen being
// at `CameraY` + `ScreenHeight`.
function CameraY(): Single; overload;
// Set the camera view to be centered over the specific sprite. The offset
// vector allows you to move the sprite from the direct center of the screen.
procedure CenterCameraOn(s: Sprite; const offset: Vector); overload;
// Set the camera view to be centered over the specified sprite, with an
// offset from the center of the sprite if needed. The sprites size (width
// and height) are taken into account. Use x and y offset of 0.0 if you want
// the camera to be exaclty over the center of the sprite.
procedure CenterCameraOn(s: Sprite; offsetX: Single; offsetY: Single); overload;
// Move the camera (offset its world x and y values) using the specified
// vector. For example, if you move the camera by the same speed vector of
// a sprite the camera will "track" (be locked on to) the sprite as it moves.
procedure MoveCameraBy(const offset: Vector); overload;
// Move the camera (offset its world x and y values) using the specified
// dx (change in x) and dy (change in x) values.
procedure MoveCameraBy(dx: Single; dy: Single); overload;
// Move the camera view to a world location specified as a Point2D.
// This will be the new top left corner of the screen.
procedure MoveCameraTo(const pt: Point2D); overload;
// Move the camera view to a world location specified by the x and y values.
// This will be the new top left corner of the screen.
procedure MoveCameraTo(x: Single; y: Single); overload;
// Tests if the point pt is on the screen.
function PointOnScreen(const pt: Point2D): Boolean; overload;
// Tests if the rectangle rect is on the screen.
function RectOnScreen(const rect: Rectangle): Boolean; overload;
// Change the position of the camera to a specified world coordinate. This
// will then be the new top left most position of the screen within the world.
procedure SetCameraPos(const pt: Point2D); overload;
// Change the X position of the camera to a specified world coordinate. This
// will then be the new left most position of the screen within the world.
procedure SetCameraX(x: Single); overload;
// Change the Y position of the camera to a specified world coordinate. This
// will then be the new top most position of the screen within the world.
procedure SetCameraY(y: Single); overload;
// Translate a Point2D from world coordinates to screen coordinates.
function ToScreen(const worldPoint: Point2D): Point2D; overload;
// Translate the points in a rectangle to screen coordinates. This can
// be used to indicate the screen area used by a rectangle in game
// coordinates.
function ToScreen(const rect: Rectangle): Rectangle; overload;
// Translate a world x value to the current screen x value which is based on
// the camera position.
function ToScreenX(worldX: Single): Single; overload;
// Translate a world y value to the current screen y value set by the camera.
function ToScreenY(worldY: Single): Single; overload;
// Translate a Point2D from screen coordinates to world coordinates.
function ToWorld(const screenPoint: Point2D): Point2D; overload;
// Translate a screen x value (based on the camera) to a world x value
function ToWorldX(screenX: Single): Single; overload;
// Translate a screen y value (based on the camera) to a world y value
function ToWorldY(screenY: Single): Single; overload;
// Adds the two parameter vectors (``v1`` and ``v2``) together and returns
// the result as a new `Vector`.
function AddVectors(const v1: Vector; const v2: Vector): Vector; overload;
// Use a matrix to transform all of the points in a triangle.
procedure ApplyMatrix(const m: Matrix2D; var tri: Triangle); overload;
// Use a matrix to transform all of the points in a quad.
procedure ApplyMatrix(const m: Matrix2D; var quad: Quad); overload;
// Calculates the angle from one vector to another.
function CalculateAngle(const v1: Vector; const v2: Vector): Single; overload;
// Calculates the angle between two sprites.
function CalculateAngle(s1: Sprite; s2: Sprite): Single; overload;
// Calculates the angle from x1,y1 to x2,y2.
function CalculateAngle(x1: Single; y1: Single; x2: Single; y2: Single): Single; overload;
// Calculates the angle between two points.
function CalculateAngleBetween(const pt1: Point2D; const pt2: Point2D): Single; overload;
// Return the center point of a circle.
function CenterPoint(const c: Circle): Point2D; overload;
// Creates a circle at the given x,y location with the indicated radius.
function CircleAt(x: Single; y: Single; radius: Single): Circle; overload;
// Creates a Circle at the point pt with the given radius.
function CircleAt(const pt: Point2D; radius: Single): Circle; overload;
// Returns the radius of the passed in circle.
function CircleRadius(const c: Circle): Single; overload;
// Returns the X value of the center point of a circle.
function CircleX(const c: Circle): Single; overload;
// Returns the Y value of the center point of a circle.
function CircleY(const c: Circle): Single; overload;
// Returns the point that lies on the circle's radius that is closest to the fromPt.
function ClosestPointOnCircle(const fromPt: Point2D; const c: Circle): Point2D; overload;
// Returns the closest point on the line from the x,y point.
function ClosestPointOnLine(x: Single; y: Single; const line: LineSegment): Point2D; overload;
// Returns the point on the line that is closest to the indicated point.
function ClosestPointOnLine(const fromPt: Point2D; const line: LineSegment): Point2D; overload;
// Returns the point on the line that is closest to the circle.
function ClosestPointOnLineFromCircle(const c: Circle; const line: LineSegment): Point2D; overload;
// Returns the point on the rectangle that is closest to the circle.
function ClosestPointOnRectFromCircle(const c: Circle; const rect: Rectangle): Point2D; overload;
// Returns the cosine of the passed in angle (in degrees).
function Cosine(angle: Single): Single; overload;
// Creates a circle at the given x,y location with the indicated radius.
function CreateCircle(x: Single; y: Single; radius: Single): Circle; overload;
// Creates a Circle at the point pt with the given radius.
function CreateCircle(const pt: Point2D; radius: Single): Circle; overload;
// Returns a line segment from x1,y1 to x2,y2.
function CreateLine(x1: Single; y1: Single; x2: Single; y2: Single): LineSegment; overload;
// Returns a line from pt1 to pt2.
function CreateLine(const pt1: Point2D; const pt2: Point2D): LineSegment; overload;
// Returns a new `Vector` created from the start and end points of a
// `LineSegment`. Useful for calculating angle vectors or extracting a
// normal vector (see `LineNormal`) for the line.
function CreateLineAsVector(const line: LineSegment): Vector; overload;
// Returns a line from the origin to the end of the mv vector.
function CreateLineFromVector(const mv: Vector): LineSegment; overload;
// Returns a line from a starting point to the point at the end of the
// mv vector.
function CreateLineFromVector(const pt: Point2D; const mv: Vector): LineSegment; overload;
// Returns a line from the x,y starting point to the point at the end of the
// mv vector.
function CreateLineFromVector(x: Single; y: Single; const mv: Vector): LineSegment; overload;
// Returns a rectangle from a given x,y location with a given width
// and height.
function CreateRectangle(x: Single; y: Single; w: Single; h: Single): Rectangle; overload;
// Returns a rectangle that encloses th epoints in a triangle.
function CreateRectangle(const tri: Triangle): Rectangle; overload;
// Returns a rectangle that encloses the two points on the line segment.
function CreateRectangle(const line: LineSegment): Rectangle; overload;
// Returns a rectangle that encloses a circle.
function CreateRectangle(const c: Circle): Rectangle; overload;
// Returns a rectangle with pt1 and pt2 defining the two distant edge points.
function CreateRectangle(const pt1: Point2D; const pt2: Point2D): Rectangle; overload;
// Returns a rectangle at a given point with a specified width and height.
function CreateRectangle(const pt: Point2D; width: Single; height: Single): Rectangle; overload;
// Returns a triangle from the points passed in.
function CreateTriangle(ax: Single; ay: Single; bx: Single; by: Single; cx: Single; cy: Single): Triangle; overload;
// Returns a triangle made up of the three points passed in.
function CreateTriangle(const a: Point2D; const b: Point2D; const c: Point2D): Triangle; overload;
// Returns a new `Vector` created using the angle and magnitude (length).
// The angle and magnitude are scalar values and the angle is in degrees.
function CreateVectorFromAngle(angle: Single; magnitude: Single): Vector; overload;
// Returns a vector from a point to the specified rectangle.
function CreateVectorFromPointToRect(const pt: Point2D; const rect: Rectangle): Vector; overload;
// Returns a vector from the specified point to the specified rectangle.
function CreateVectorFromPointToRect(x: Single; y: Single; const rect: Rectangle): Vector; overload;
// Returns a vector from the specified point to the specified rectangle.
function CreateVectorFromPointToRect(x: Single; y: Single; rectX: Single; rectY: Single; rectWidth: Single; rectHeight: Single): Vector; overload;
// Returns a `Vector` created from the difference from the ``p1`` to
// the second ``p2`` points (`Point2D`).
function CreateVectorFromPoints(const p1: Point2D; const p2: Point2D): Vector; overload;
// Returns a new `Vector` using the x and y value of a Point2D parameter.
function CreateVectorToPoint(const p1: Point2D): Vector; overload;
// Returns the point at the opposite side of a circle from a given point ``pt``.
function DistantPointOnCircle(const pt: Point2D; const c: Circle): Point2D; overload;
// Finds the opposite side of a circle from a given point ``pt`` when travelling along the
// vector ``heading``. Returns False if the ray projected from point ``pt`` misses the circle.
function DistantPointOnCircleHeading(const pt: Point2D; const c: Circle; const heading: Vector; out oppositePt: Point2D): Boolean; overload;
// Calculates the dot product (scalar product) between the two vector
// parameters rovided (``v1`` and ``v2``). It returns the result as a
// scalar value.
//
// If the result is 0.0 it means that the vectors are orthogonal (at right
// angles to each other). If ``v1`` and ``v2`` are unit vectors (length of
// 1.0) and the dot product is 1.0, it means that ``v1`` and ``v2`` vectors
// are parallel.
function DotProduct(const v1: Vector; const v2: Vector): Single; overload;
// Ensures that the passed in rectangle has a positive width and height.
procedure FixRectangle(var rect: Rectangle); overload;
// Ensures that the passed in rectangle has a positive width and height.
procedure FixRectangle(var x: Single; var y: Single; var width: Single; var height: Single); overload;
// Returns the identity matrix. When a Matrix2D or Vector is multiplied by
// the identity matrix the result is the original matrix or vector.
function IdentityMatrix(): Matrix2D; overload;
// Returns a rectangle that is inset from rect the amount specified.
function InsetRectangle(const rect: Rectangle; insetAmount: Single): Rectangle; overload;
// Returns the intersection of two rectangles.
function Intersection(const rect1: Rectangle; const rect2: Rectangle): Rectangle; overload;
// Returns a new Vector that is an inverted version of the parameter
// vector (v). In other words, the -/+ sign of the x and y values are changed.
function InvertVector(const v: Vector): Vector; overload;
// Returns a new `Vector` that is a based on the parameter ``v`` however
// its magnitude (length) will be limited (truncated) if it exceeds the
// specified limit value.
function LimitVector(const v: Vector; limit: Single): Vector; overload;
// Returns a new `Vector` created from the start and end points of a
// `LineSegment`. Useful for calculating angle vectors or extracting a
// normal vector (see `LineNormal`) for the line.
function LineAsVector(const line: LineSegment): Vector; overload;
// Returns a line segment from x1,y1 to x2,y2.
function LineFrom(x1: Single; y1: Single; x2: Single; y2: Single): LineSegment; overload;
// Returns a line from pt1 to pt2.
function LineFrom(const pt1: Point2D; const pt2: Point2D): LineSegment; overload;
// Returns a line from the origin to the end of the mv vector.
function LineFromVector(const mv: Vector): LineSegment; overload;
// Returns a line from a starting point to the point at the end of the
// mv vector.
function LineFromVector(const pt: Point2D; const mv: Vector): LineSegment; overload;
// Returns a line from the x,y starting point to the point at the end of the
// mv vector.
function LineFromVector(x: Single; y: Single; const mv: Vector): LineSegment; overload;
// Returns the intersection point of two lines.
function LineIntersectionPoint(const line1: LineSegment; const line2: LineSegment; out pt: Point2D): Boolean; overload;
// Returns true if the line segment intersects the circle.
function LineIntersectsCircle(const l: LineSegment; const c: Circle): Boolean; overload;
// Returns true if the line intersects the rectangle.
function LineIntersectsRect(const line: LineSegment; const rect: Rectangle): Boolean; overload;
// Returns the squared line magnitude.
function LineMagnitudeSq(const line: LineSegment): Single; overload;
// Returns the squared magnitude of the line from the points given.
function LineMagnitudeSq(x1: Single; y1: Single; x2: Single; y2: Single): Single; overload;
// Returns the mid point of the line segment.
function LineMidPoint(const line: LineSegment): Point2D; overload;
// Returns a unit vector (length is 1.0) that is "normal" (prependicular) to
// the ``line`` parameter. A normal vector is useful for calculating the
// result of a collision such as sprites bouncing off walls (lines).
function LineNormal(const line: LineSegment): Vector; overload;
// Returns true if the two line segments intersect.
function LineSegmentsIntersect(const line1: LineSegment; const line2: LineSegment): Boolean; overload;
// Get a text description of the line segment.
function LineToString(const ln: LineSegment): String; overload;
// Calculate the inverse of a matrix.
function MatrixInverse(const m: Matrix2D): Matrix2D; overload;
// Multiplies the `Vector` parameter ``v`` with the `Matrix2D` ``m`` and
// returns the result as a `Vector`. Use this to transform the vector with
// the matrix (to apply scaling, rotation or translation effects).
function MatrixMultiply(const m: Matrix2D; const v: Vector): Vector; overload;
// Multiplies the two `Matrix2D` parameters, ``m1`` by ``m2``, and returns
// the result as a new `Matrix2D`. Use this to combine the effects to two
// matrix transformations.
function MatrixMultiply(const m1: Matrix2D; const m2: Matrix2D): Matrix2D; overload;
// This function returns a string representation of a Matrix.
function MatrixToString(const m: Matrix2D): String; overload;
// Returns the sum of pt1 and pt2
function PointAdd(const pt1: Point2D; const pt2: Point2D): Point2D; overload;
// Create a Point2D that points at the X,Y location passed in.
function PointAt(x: Single; y: Single): Point2D; overload;
// Create a Point2D that points at the point from the startPoint at the end of the offset vector.
function PointAt(const startPoint: Point2D; const offset: Vector): Point2D; overload;
// Returns True if the point ``pt`` is in the circle.
function PointInCircle(const pt: Point2D; const c: Circle): Boolean; overload;
// Returns True if the point ``pt`` is in the circle defined by x, y, radius.
function PointInCircle(const pt: Point2D; x: Single; y: Single; radius: Single): Boolean; overload;
// Returns True if the point ``ptX``, ``ptY`` is in the circle.
function PointInCircle(ptX: Single; ptY: Single; cX: Single; cY: Single; radius: Single): Boolean; overload;
// Returns True if point ``pt`` is in the Rectangle ``rect``.
function PointInRect(const pt: Point2D; const rect: Rectangle): Boolean; overload;
// Returns true if the x,y point is within the rectangle.
function PointInRect(x: Single; y: Single; const rect: Rectangle): Boolean; overload;
// Returns true if the point is within the rectangle.
function PointInRect(const pt: Point2D; x: Single; y: Single; w: Single; h: Single): Boolean; overload;
// Returns true if the point (ptX, ptY) is within the rectangle.
function PointInRect(ptX: Single; ptY: Single; x: Single; y: Single; w: Single; h: Single): Boolean; overload;
// Returns true if the point ``pt`` is in the Triangle ``tri``.
function PointInTriangle(const pt: Point2D; const tri: Triangle): Boolean; overload;
// Returns the distance from the x,y point to the line segment.
function PointLineDistance(x: Single; y: Single; const line: LineSegment): Single; overload;
// Returns distance from the line, or if the intersecting point on the line nearest
// the point tested is outside the endpoints of the line, the distance to the
// nearest endpoint.
//
// Returns -1 on zero-valued denominator conditions to return an illegal distance. (
// modification of Brandon Crosby's VBA code)
function PointLineDistance(const pt: Point2D; const line: LineSegment): Single; overload;
// Returns True if point ``pt`` is on the line segment ``line``.
function PointOnLine(const pt: Point2D; const line: LineSegment): Boolean; overload;
// Returns True if point ``pt`` is on the line segment ``line``.
function PointOnLine(const pt: Point2D; x: Single; y: Single; endX: Single; endY: Single): Boolean; overload;
// Returns True of `pt1` is at the same point as `pt2`.
function PointOnPoint(const pt1: Point2D; const pt2: Point2D): Boolean; overload;
// Returns the distance from point to point.
function PointPointDistance(const pt1: Point2D; const pt2: Point2D): Single; overload;
// Get a text description of the point2D.
function PointToString(const pt: Point2D): String; overload;
// Returns a quad for the passed in points.
function QuadFrom(const rect: Rectangle): Quad; overload;
// Returns a quad for the passed in points.
function QuadFrom(xTopLeft: Single; yTopLeft: Single; xTopRight: Single; yTopRight: Single; xBottomLeft: Single; yBottomLeft: Single; xBottomRight: Single; yBottomRight: Single): Quad; overload;
// Create a Point2D that points at the X,Y location passed in.
function RandomScreenPoint(): Point2D; overload;
// Returns the distance from the ray origin to the edge of the circle where the ray heads in the
// direction indicated in the ray_heading parameter. This returns -1 where the ray does not hit
// the circle.
function RayCircleIntersectDistance(const ray_origin: Point2D; const ray_heading: Vector; const c: Circle): Single; overload;
// Returns the intersection point of a ray with a line, returning true if the ray intesects with the line.
function RayIntersectionPoint(const fromPt: Point2D; const heading: Vector; const line: LineSegment; out pt: Point2D): Boolean; overload;
// Returns the rectangle details after it moved the amount specified within
// the vector.
function RectangleAfterMove(const rect: Rectangle; const mv: Vector): Rectangle; overload;
// Returns the bottom (y) value of a rectangle.
function RectangleBottom(const rect: Rectangle): Single; overload;
// Returns the bottom left corner of the rectangle.
function RectangleBottomLeft(const rect: Rectangle): Point2D; overload;
// Returns the bottom right corner of the rectangle.
function RectangleBottomRight(const rect: Rectangle): Point2D; overload;
// Returns the center point of the rectangle.
function RectangleCenter(const rect: Rectangle): Point2D; overload;
// Returns the center of the bottom line of the rectangle.
function RectangleCenterBottom(const rect: Rectangle): Point2D; overload;
// Returns the center of the left line of the rectangle.
function RectangleCenterLeft(const rect: Rectangle): Point2D; overload;
// Returns the center of the right line of the rectangle.
function RectangleCenterRight(const rect: Rectangle): Point2D; overload;
// Returns the center of the top line of the rectangle.
function RectangleCenterTop(const rect: Rectangle): Point2D; overload;
// Returns a rectangle from a given x,y location with a given width
// and height.
function RectangleFrom(x: Single; y: Single; w: Single; h: Single): Rectangle; overload;
// Returns a rectangle that encloses the points in a triangle.
function RectangleFrom(const tri: Triangle): Rectangle; overload;
// Returns a rectangle that encloses the two points on the line segment.
function RectangleFrom(const line: LineSegment): Rectangle; overload;
// Returns a rectangle that encloses a circle.
function RectangleFrom(const c: Circle): Rectangle; overload;
// Returns a rectangle with pt1 and pt2 defining the two distant edge points.
function RectangleFrom(const pt1: Point2D; const pt2: Point2D): Rectangle; overload;
// Returns a rectangle at a given point with a specified width and height.
function RectangleFrom(const pt: Point2D; width: Single; height: Single): Rectangle; overload;
// Returns the left (x) value of a rectangle.
function RectangleLeft(const rect: Rectangle): Single; overload;
// Returns a rectangle that is offset by the vector.
function RectangleOffset(const rect: Rectangle; const vec: Vector): Rectangle; overload;
// Returns the right (x) value of a rectangle.
function RectangleRight(const rect: Rectangle): Single; overload;
// Get a text description of the rectangle.
function RectangleToString(const rect: Rectangle): String; overload;
// Returns the top (y) value of a rectangle.
function RectangleTop(const rect: Rectangle): Single; overload;
// Returns the top left corner of the rectangle.
function RectangleTopLeft(const rect: Rectangle): Point2D; overload;
// Returns the top right corner of the rectangle.
function RectangleTopRight(const rect: Rectangle): Point2D; overload;
// Returns true if the two rectangles intersect.
function RectanglesIntersect(const rect1: Rectangle; const rect2: Rectangle): Boolean; overload;
// Returns a rotation matrix that rotates 2d points by the angle.
function RotationMatrix(deg: Single): Matrix2D; overload;
// Returns a matrix that can be used to scale 2d points (both x and y).
function ScaleMatrix(scale: Single): Matrix2D; overload;
// Create a scale matrix that scales x and y to
// different degrees.
function ScaleMatrix(const scale: Point2D): Matrix2D; overload;
// Create a matrix that can scale, rotate then translate geometry points.
function ScaleRotateTranslateMatrix(const scale: Point2D; deg: Single; const translate: Point2D): Matrix2D; overload;
// Change the location of a point on a Quad.
procedure SetQuadPoint(var q: Quad; idx: Longint; value: Point2D); overload;
// Returns the sine of the passed in angle (in degrees).
function Sine(angle: Single): Single; overload;
// Subtracts the second vector parameter (``v2``) from the first vector
// (``v1``) and returns the result as new `Vector`.
function SubtractVectors(const v1: Vector; const v2: Vector): Vector; overload;
// Returns the tangent of the passed in angle (in degrees).
function Tangent(angle: Single): Single; overload;
// Returns the two tangent points on the circle given the indicated vector.
function TangentPoints(const fromPt: Point2D; const c: Circle; out p1: Point2D; out p2: Point2D): Boolean; overload;
// Returns a matrix that can be used to translate 2d points. Moving them
// by dx and dy.
function TranslationMatrix(dx: Single; dy: Single): Matrix2D; overload;
// Returns a translation matric used to translate 2d points by the
// distance in the Point2D.
function TranslationMatrix(const pt: Point2D): Matrix2D; overload;
// Returns the barycenter point of the triangle.
function TriangleBarycenter(const tri: Triangle): Point2D; overload;
// Returns a triangle from the points passed in.
function TriangleFrom(ax: Single; ay: Single; bx: Single; by: Single; cx: Single; cy: Single): Triangle; overload;
// Returns a triangle made up of the three points passed in.
function TriangleFrom(const a: Point2D; const b: Point2D; const c: Point2D): Triangle; overload;
// Returns true if the triangle intersects with the rectangle.
function TriangleRectangleIntersect(const tri: Triangle; const rect: Rectangle): Boolean; overload;
// Get a text description of the triangle.
function TriangleToString(const tri: Triangle): String; overload;
// Returns the unit vector of the parameter vector (v). The unit vector has a
// magnitude of 1, resulting in a vector that indicates the direction of
// the original vector.
function UnitVector(const v: Vector): Vector; overload;
// Calculates the angle of a vector.
function VectorAngle(const v: Vector): Single; overload;
// Returns a new `Vector` created using the angle and magnitude (length).
// The angle and magnitude are scalar values and the angle is in degrees.
function VectorFromAngle(angle: Single; magnitude: Single): Vector; overload;
// Returns a vector from a point to the specified rectangle.
function VectorFromPointToRect(const pt: Point2D; const rect: Rectangle): Vector; overload;
// Returns a vector from the specified point to the specified rectangle.
function VectorFromPointToRect(x: Single; y: Single; const rect: Rectangle): Vector; overload;
// Returns a vector from the specified point to the specified rectangle.
function VectorFromPointToRect(x: Single; y: Single; rectX: Single; rectY: Single; rectWidth: Single; rectHeight: Single): Vector; overload;
// Returns a `Vector` created from the difference from the ``p1`` to
// the second ``p2`` points (`Point2D`).
function VectorFromPoints(const p1: Point2D; const p2: Point2D): Vector; overload;
// Returns true if the vector ends within the rectangle when started at the origin.
function VectorInRect(const v: Vector; const rect: Rectangle): Boolean; overload;
// Return true if the vector (used as a point) is within the rectangle
function VectorInRect(const v: Vector; x: Single; y: Single; w: Single; h: Single): Boolean; overload;
// Test to see if the ``x`` and ``y`` components of the provided vector
// parameter ``v`` are zero.
function VectorIsZero(const v: Vector): Boolean; overload;
// Returns the magnitude (or "length") of the parameter vector (v) as a
// scalar value.
function VectorMagnitude(const v: Vector): Single; overload;
// Returns the squared magnitude (or "length") of the parameter vector (v) as a
// scalar value.
function VectorMagnitudeSq(const v: Vector): Single; overload;
// Multiplies each component (``x`` and ``y`` values) of the ``v1`` vector
// by the ``s`` scalar value and returns the result as a new `Vector`.
function VectorMultiply(const v: Vector; s: Single): Vector; overload;
// Returns a new `Vector` that is perpendicular ("normal") to the parameter
// vector ``v`` provided. The concept of a "normal" vector is usually
// extracted from (or associated with) a line. See `LineNormal`.
function VectorNormal(const v: Vector): Vector; overload;
// Returns a vector out of a circle for a given circle.
function VectorOutOfCircleFromCircle(const src: Circle; const bounds: Circle; const velocity: Vector): Vector; overload;
// Returns the vector out of a circle from a given point.
function VectorOutOfCircleFromPoint(const pt: Point2D; const c: Circle; const velocity: Vector): Vector; overload;
// Returns a vector that can be used to move a circle out of a rectangle.
function VectorOutOfRectFromCircle(const c: Circle; const rect: Rectangle; const velocity: Vector): Vector; overload;
// Determines the vector needed to move from point ``pt`` out of rectangle ``rect`` given the velocity specified
function VectorOutOfRectFromPoint(const pt: Point2D; const rect: Rectangle; const velocity: Vector): Vector; overload;
// Returns the vector needed to move rectangle ``src`` out of rectangle``bounds`` given the velocity specified.
function VectorOutOfRectFromRect(const src: Rectangle; const bounds: Rectangle; const velocity: Vector): Vector; overload;
// Returns a new `Vector` using the ``x`` and ``y`` values provided.
function VectorTo(x: Single; y: Single): Vector; overload;
// Creates a new `Vector` with the ``x`` and ``y`` values provided, and will
// invert the ``y`` value if the ``invertY`` parameter is True. The inversion
// of the ``y`` value provides a convienient option for handling screen
// related vectors.
function VectorTo(x: Single; y: Single; invertY: Boolean): Vector; overload;
// Returns a new `Vector` using the x and y value of a Point2D parameter.
function VectorToPoint(const p1: Point2D): Vector; overload;
// Get a text description of the Vector.
function VectorToString(const v: Vector): String; overload;
// Determines if two vectors are equal.
function VectorsEqual(const v1: Vector; const v2: Vector): Boolean; overload;
// Determines if two vectors are not equal.
function VectorsNotEqual(const v1: Vector; const v2: Vector): Boolean; overload;
// Returns the two widest points on the circle that lie along the indicated vector.
procedure WidestPoints(const c: Circle; const along: Vector; out pt1: Point2D; out pt2: Point2D); overload;
// Returns the details of one of the available resolutions. Use idx from 0 to
// `NumberOfResolutions` - 1 to access all of the available resolutions.
function AvailableResolution(idx: Longint): Resolution; overload;
// Get the blue value of ``color``.
function BlueOf(c: Color): Byte; overload;
// Get the brightness of the ``color``.
function BrightnessOf(c: Color): Single; overload;
// Clear the screen black.
procedure ClearScreen(); overload;
// Clear the screen to a specified color.
procedure ClearScreen(toColor: Color); overload;
// The color AliceBlue
function ColorAliceBlue(): Color; overload;
// The color AntiqueWhite
function ColorAntiqueWhite(): Color; overload;
// The color Aqua
function ColorAqua(): Color; overload;
// The color Aquamarine
function ColorAquamarine(): Color; overload;
// The color Azure
function ColorAzure(): Color; overload;
// The color Beige
function ColorBeige(): Color; overload;
// The color Bisque
function ColorBisque(): Color; overload;
// The color Black
function ColorBlack(): Color; overload;
// The color BlanchedAlmond
function ColorBlanchedAlmond(): Color; overload;
// The color Blue
function ColorBlue(): Color; overload;
// The color BlueViolet
function ColorBlueViolet(): Color; overload;
// The color Green
function ColorBrightGreen(): Color; overload;
// The color Brown
function ColorBrown(): Color; overload;
// The color BurlyWood
function ColorBurlyWood(): Color; overload;
// The color CadetBlue
function ColorCadetBlue(): Color; overload;
// The color Chartreuse
function ColorChartreuse(): Color; overload;
// The color Chocolate
function ColorChocolate(): Color; overload;
// Gets a color given its RGBA components.
procedure ColorComponents(c: Color; out r: Byte; out g: Byte; out b: Byte; out a: Byte); overload;
// The color Coral
function ColorCoral(): Color; overload;
// The color CornflowerBlue
function ColorCornflowerBlue(): Color; overload;
// The color Cornsilk
function ColorCornsilk(): Color; overload;
// The color Crimson
function ColorCrimson(): Color; overload;
// The color Cyan
function ColorCyan(): Color; overload;
// The color DarkBlue
function ColorDarkBlue(): Color; overload;
// The color DarkCyan
function ColorDarkCyan(): Color; overload;
// The color DarkGoldenrod
function ColorDarkGoldenrod(): Color; overload;
// The color DarkGray
function ColorDarkGray(): Color; overload;
// The color DarkGreen
function ColorDarkGreen(): Color; overload;
// The color DarkKhaki
function ColorDarkKhaki(): Color; overload;
// The color DarkMagenta
function ColorDarkMagenta(): Color; overload;
// The color DarkOliveGreen
function ColorDarkOliveGreen(): Color; overload;
// The color DarkOrange
function ColorDarkOrange(): Color; overload;
// The color DarkOrchid
function ColorDarkOrchid(): Color; overload;
// The color DarkRed
function ColorDarkRed(): Color; overload;
// The color DarkSalmon
function ColorDarkSalmon(): Color; overload;
// The color DarkSeaGreen
function ColorDarkSeaGreen(): Color; overload;
// The color DarkSlateBlue
function ColorDarkSlateBlue(): Color; overload;
// The color DarkSlateGray
function ColorDarkSlateGray(): Color; overload;
// The color DarkTurquoise
function ColorDarkTurquoise(): Color; overload;
// The color DarkViolet
function ColorDarkViolet(): Color; overload;
// The color DeepPink
function ColorDeepPink(): Color; overload;
// The color DeepSkyBlue
function ColorDeepSkyBlue(): Color; overload;
// The color DimGray
function ColorDimGray(): Color; overload;
// The color DodgerBlue
function ColorDodgerBlue(): Color; overload;
// The color Firebrick
function ColorFirebrick(): Color; overload;
// The color FloralWhite
function ColorFloralWhite(): Color; overload;
// The color ForestGreen
function ColorForestGreen(): Color; overload;
// The color Fuchsia
function ColorFuchsia(): Color; overload;
// The color Gainsboro
function ColorGainsboro(): Color; overload;
// The color GhostWhite
function ColorGhostWhite(): Color; overload;
// The color Gold
function ColorGold(): Color; overload;
// The color Goldenrod
function ColorGoldenrod(): Color; overload;
// The color Gray
function ColorGray(): Color; overload;
// The color Green
function ColorGreen(): Color; overload;
// The color GreenYellow
function ColorGreenYellow(): Color; overload;
// The color Grey
function ColorGrey(): Color; overload;
// The color Honeydew
function ColorHoneydew(): Color; overload;
// The color HotPink
function ColorHotPink(): Color; overload;
// The color IndianRed
function ColorIndianRed(): Color; overload;
// The color Indigo
function ColorIndigo(): Color; overload;
// The color Ivory
function ColorIvory(): Color; overload;
// The color Khaki
function ColorKhaki(): Color; overload;
// The color Lavender
function ColorLavender(): Color; overload;
// The color LavenderBlush
function ColorLavenderBlush(): Color; overload;
// The color LawnGreen
function ColorLawnGreen(): Color; overload;
// The color LemonChiffon
function ColorLemonChiffon(): Color; overload;
// The color LightBlue
function ColorLightBlue(): Color; overload;
// The color LightCoral
function ColorLightCoral(): Color; overload;
// The color LightCyan
function ColorLightCyan(): Color; overload;
// The color LightGoldenrodYellow
function ColorLightGoldenrodYellow(): Color; overload;
// The color LightGray
function ColorLightGray(): Color; overload;
// The color LightGreen
function ColorLightGreen(): Color; overload;
// The color Transparent
function ColorLightGrey(): Color; overload;
// The color LightPink
function ColorLightPink(): Color; overload;
// The color LightSalmon
function ColorLightSalmon(): Color; overload;
// The color LightSeaGreen
function ColorLightSeaGreen(): Color; overload;
// The color LightSkyBlue
function ColorLightSkyBlue(): Color; overload;
// The color LightSlateGray
function ColorLightSlateGray(): Color; overload;
// The color LightSteelBlue
function ColorLightSteelBlue(): Color; overload;
// The color LightYellow
function ColorLightYellow(): Color; overload;
// The color Lime
function ColorLime(): Color; overload;
// The color LimeGreen
function ColorLimeGreen(): Color; overload;
// The color Linen
function ColorLinen(): Color; overload;
// The color Magenta
function ColorMagenta(): Color; overload;
// The color Maroon
function ColorMaroon(): Color; overload;
// The color MediumAquamarine
function ColorMediumAquamarine(): Color; overload;
// The color MediumBlue
function ColorMediumBlue(): Color; overload;
// The color MediumOrchid
function ColorMediumOrchid(): Color; overload;
// The color MediumPurple
function ColorMediumPurple(): Color; overload;
// The color MediumSeaGreen
function ColorMediumSeaGreen(): Color; overload;
// The color MediumSlateBlue
function ColorMediumSlateBlue(): Color; overload;
// The color MediumSpringGreen
function ColorMediumSpringGreen(): Color; overload;
// The color MediumTurquoise
function ColorMediumTurquoise(): Color; overload;
// The color MediumVioletRed
function ColorMediumVioletRed(): Color; overload;
// The color MidnightBlue
function ColorMidnightBlue(): Color; overload;
// The color MintCream
function ColorMintCream(): Color; overload;
// The color MistyRose
function ColorMistyRose(): Color; overload;
// The color Moccasin
function ColorMoccasin(): Color; overload;
// The color NavajoWhite
function ColorNavajoWhite(): Color; overload;
// The color Navy
function ColorNavy(): Color; overload;
// The color OldLace
function ColorOldLace(): Color; overload;
// The color Olive
function ColorOlive(): Color; overload;
// The color OliveDrab
function ColorOliveDrab(): Color; overload;
// The color Orange
function ColorOrange(): Color; overload;
// The color OrangeRed
function ColorOrangeRed(): Color; overload;
// The color Orchid
function ColorOrchid(): Color; overload;
// The color PaleGoldenrod
function ColorPaleGoldenrod(): Color; overload;
// The color PaleGreen
function ColorPaleGreen(): Color; overload;
// The color PaleTurquoise
function ColorPaleTurquoise(): Color; overload;
// The color PaleVioletRed
function ColorPaleVioletRed(): Color; overload;
// The color PapayaWhip
function ColorPapayaWhip(): Color; overload;
// The color PeachPuff
function ColorPeachPuff(): Color; overload;
// The color Peru
function ColorPeru(): Color; overload;
// The color Pink
function ColorPink(): Color; overload;
// The color Plum
function ColorPlum(): Color; overload;
// The color PowderBlue
function ColorPowderBlue(): Color; overload;
// The color Purple
function ColorPurple(): Color; overload;
// The color Red
function ColorRed(): Color; overload;
// The color RosyBrown
function ColorRosyBrown(): Color; overload;
// The color RoyalBlue
function ColorRoyalBlue(): Color; overload;
// The color SaddleBrown
function ColorSaddleBrown(): Color; overload;
// The color Salmon
function ColorSalmon(): Color; overload;
// The color SandyBrown
function ColorSandyBrown(): Color; overload;
// The color SeaGreen
function ColorSeaGreen(): Color; overload;
// The color SeaShell
function ColorSeaShell(): Color; overload;
// The color Sienna
function ColorSienna(): Color; overload;
// The color Silver
function ColorSilver(): Color; overload;
// The color SkyBlue
function ColorSkyBlue(): Color; overload;
// The color SlateBlue
function ColorSlateBlue(): Color; overload;
// The color SlateGray
function ColorSlateGray(): Color; overload;
// The color Snow
function ColorSnow(): Color; overload;
// The color SpringGreen
function ColorSpringGreen(): Color; overload;
// The color SteelBlue
function ColorSteelBlue(): Color; overload;
// The color Swinburne Red
function ColorSwinburneRed(): Color; overload;
// The color Tan
function ColorTan(): Color; overload;
// The color Teal
function ColorTeal(): Color; overload;
// The color Thistle
function ColorThistle(): Color; overload;
// returns color to string.
function ColorToString(c: Color): String; overload;
// The color Tomato
function ColorTomato(): Color; overload;
// The color Transparent
function ColorTransparent(): Color; overload;
// The color Turquoise
function ColorTurquoise(): Color; overload;
// The color Violet
function ColorViolet(): Color; overload;
// The color Wheat
function ColorWheat(): Color; overload;
// The color White
function ColorWhite(): Color; overload;
// The color WhiteSmoke
function ColorWhiteSmoke(): Color; overload;
// The color Yellow
function ColorYellow(): Color; overload;
// The color YellowGreen
function ColorYellowGreen(): Color; overload;
// Returns the rectangle of the clip area of the current window
function CurrentClip(): Rectangle; overload;
// Returns the rectangle of the clip area for a window
function CurrentClip(wnd: Window): Rectangle; overload;
// Returns the rectangle of the current clip area for a bitmap
function CurrentClip(bmp: Bitmap): Rectangle; overload;
// Draw a circle in the game.
procedure DrawCircle(clr: Color; x: Single; y: Single; radius: Single); overload;
// Draw a circle in the game.
procedure DrawCircle(clr: Color; const c: Circle); overload;
// Draw a circle onto a destination bitmap.
procedure DrawCircle(clr: Color; const c: Circle; const opts: DrawingOptions); overload;
// Draw a circle onto a destination bitmap.
procedure DrawCircle(clr: Color; x: Single; y: Single; radius: Single; const opts: DrawingOptions); overload;
// Draw a ellipse in the game.
procedure DrawEllipse(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single); overload;
// Draw a ellipse in the game.
procedure DrawEllipse(clr: Color; const rec: Rectangle); overload;
// Draw a ellipse onto a destination bitmap.
procedure DrawEllipse(clr: Color; const rec: Rectangle; const opts: DrawingOptions); overload;
// Draw a ellipse onto a destination bitmap.
procedure DrawEllipse(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single; const opts: DrawingOptions); overload;
// Draw a line in the game.
procedure DrawLine(clr: Color; const fromPt: Point2D; const toPt: Point2D); overload;
// Draw a line in the game.
procedure DrawLine(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single); overload;
// Draw a line in the game.
procedure DrawLine(clr: Color; const l: LineSegment); overload;
// Draw a line onto a destination bitmap.
procedure DrawLine(clr: Color; const l: LineSegment; const opts: DrawingOptions); overload;
// Draw a line in the game from one point to another point.
procedure DrawLine(clr: Color; const fromPt: Point2D; const toPt: Point2D; const opts: DrawingOptions); overload;
// Draw a line with the provided DrawingOptions.
procedure DrawLine(clr: Color; xPosStart: Single; yPosStart: Single; xPosEnd: Single; yPosEnd: Single; const opts: DrawingOptions); overload;
// Draw a pixel in the game.
procedure DrawPixel(clr: Color; const position: Point2D); overload;
// Draw a pixel with options.
procedure DrawPixel(clr: Color; const position: Point2D; const opts: DrawingOptions); overload;
// Draw a pixel in the game.
procedure DrawPixel(clr: Color; x: Single; y: Single); overload;
// Draw a pixel with options.
procedure DrawPixel(clr: Color; x: Single; y: Single; const opts: DrawingOptions); overload;
// Draw a quad in the game.
procedure DrawQuad(clr: Color; const q: Quad); overload;
// Draw a quad in the game.
procedure DrawQuad(clr: Color; const q: Quad; const opts: DrawingOptions); overload;
// Draw a rectangle in the game.
procedure DrawRectangle(clr: Color; x: Single; y: Single; width: Single; height: Single); overload;
// Draw a rectangle in the game.
procedure DrawRectangle(clr: Color; const rect: Rectangle); overload;
// Draw a rectangle onto a destination bitmap.
procedure DrawRectangle(clr: Color; const rect: Rectangle; const opts: DrawingOptions); overload;
// Draw a rectangle onto a destination bitmap.
procedure DrawRectangle(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single; const opts: DrawingOptions); overload;
// Draw a triangle in the game.
procedure DrawTriangle(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single; x3: Single; y3: Single); overload;
// Draw a triangle in the game.
procedure DrawTriangle(clr: Color; const tri: Triangle); overload;
// Draw a triangle onto a destination bitmap.
procedure DrawTriangle(clr: Color; const tri: Triangle; const opts: DrawingOptions); overload;
// Draw a triangle onto a destination bitmap.
procedure DrawTriangle(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single; x3: Single; y3: Single; const opts: DrawingOptions); overload;
// Fill a circle in the game.
procedure FillCircle(clr: Color; x: Single; y: Single; radius: Single); overload;
// Fill a circle in the game.
procedure FillCircle(clr: Color; const c: Circle); overload;
// Fill a circle onto a destination bitmap.
procedure FillCircle(clr: Color; const c: Circle; const opts: DrawingOptions); overload;
// Fill a circle in the game.
procedure FillCircle(clr: Color; const pt: Point2D; radius: Longint); overload;
// Fill a circle at a given point using the passed in drawing options.
procedure FillCircle(clr: Color; const pt: Point2D; radius: Longint; const opts: DrawingOptions); overload;
// Fill a circle onto a destination bitmap.
procedure FillCircle(clr: Color; x: Single; y: Single; radius: Single; const opts: DrawingOptions); overload;
// Fill a ellipse in the game.
procedure FillEllipse(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single); overload;
// Fill a ellipse in the game.
procedure FillEllipse(clr: Color; const rec: Rectangle); overload;
// Fill a ellipse onto a destination bitmap.
procedure FillEllipse(clr: Color; const rec: Rectangle; const opts: DrawingOptions); overload;
// Fill a ellipse onto a destination bitmap.
procedure FillEllipse(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single; const opts: DrawingOptions); overload;
// Fill a quad in the game.
procedure FillQuad(clr: Color; const q: Quad); overload;
// Fill a quad in the game.
procedure FillQuad(clr: Color; const q: Quad; const opts: DrawingOptions); overload;
// Fill a rectangle in the game.
procedure FillRectangle(clr: Color; x: Single; y: Single; width: Single; height: Single); overload;
// Fill a rectangle in the game.
procedure FillRectangle(clr: Color; const rect: Rectangle); overload;
// Fill a rectangle onto a destination bitmap.
procedure FillRectangle(clr: Color; const rect: Rectangle; const opts: DrawingOptions); overload;
// Fill a rectangle onto a destination bitmap.
procedure FillRectangle(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single; const opts: DrawingOptions); overload;
// Fill a triangle in the game.
procedure FillTriangle(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single; x3: Single; y3: Single); overload;
// Fill a triangle in the game.
procedure FillTriangle(clr: Color; const tri: Triangle); overload;
// Fill a triangle onto a destination bitmap.
procedure FillTriangle(clr: Color; const tri: Triangle; const opts: DrawingOptions); overload;
// Fill a triangle onto a destination bitmap.
procedure FillTriangle(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single; x3: Single; y3: Single; const opts: DrawingOptions); overload;
// Returns the color of the pixel at the x,y location on
// the supplied bitmap.
function GetPixel(bmp: Bitmap; x: Single; y: Single): Color; overload;
// Returns the color of the pixel at the x,y location on
// the supplied window.
function GetPixel(wnd: Window; x: Single; y: Single): Color; overload;
// Returns the color of the pixel at the given x,y location.
function GetPixelFromScreen(x: Single; y: Single): Color; overload;
// Get the green value of ``color``.
function GreenOf(c: Color): Byte; overload;
// Returs a color from the HSB input.
function HSBColor(hue: Single; saturation: Single; brightness: Single): Color; overload;
// Gets the hue ``h``, saturation ``s``, and brightness ``b`` values from
// the color.
procedure HSBValuesOf(c: Color; out h: Single; out s: Single; out b: Single); overload;
// Get the hue of the ``color``.
function HueOf(c: Color): Single; overload;
// Returns the number of resolutions in the list of available resolutions.
function NumberOfResolutions(): Longint; overload;
// Opens the graphical window so that it can be drawn onto. You can set the
// icon for this window using `SetIcon`. The window itself is only drawn when
// you call `RefreshScreen`. All windows are opened at 32 bits per pixel. You
// can toggle fullscreen using `ToggleFullScreen`. The window is closed when
// the application terminates.
procedure OpenGraphicsWindow(const caption: String; width: Longint; height: Longint); overload;
// Pop the clip rectangle of the screen.
procedure PopClip(); overload;
// Pop the clipping rectangle of a bitmap.
procedure PopClip(bmp: Bitmap); overload;
// Pop the clipping rectangle of a bitmap.
procedure PopClip(wnd: Window); overload;
// Push a clip rectangle to the current window. This can be undone using PopClip.
procedure PushClip(const r: Rectangle); overload;
// Add the clipping rectangle of a bitmap and uses the intersect between the new rectangle and previous clip.
procedure PushClip(bmp: Bitmap; const r: Rectangle); overload;
// Add the clipping rectangle of a window and uses the intersect between the new rectangle and previous clip.
procedure PushClip(wnd: Window; const r: Rectangle); overload;
// Gets a color given its RGBA components.
function RGBAColor(red: Byte; green: Byte; blue: Byte; alpha: Byte): Color; overload;
// Returns a color from a floating point RBGA value set.
function RGBAFloatColor(r: Single; g: Single; b: Single; a: Single): Color; overload;
// Gets a color given its RGB components.
function RGBColor(red: Byte; green: Byte; blue: Byte): Color; overload;
// Returns a color from a floating point RBG value set.
function RGBFloatColor(r: Single; g: Single; b: Single): Color; overload;
// Creates and returns a random color where R, G, B and A are all randomised.
function RandomColor(): Color; overload;
// Creates and returns a random color where R, G, and B are all randomised, and A is set
// to the passed in value.
function RandomRGBColor(alpha: Byte): Color; overload;
// Get the red value of ``color``.
function RedOf(c: Color): Byte; overload;
// Draws the current drawing to the screen. This must be called to display
// anything to the screen. This will draw all drawing operations, as well
// as the text being entered by the user.
//
// Side Effects:
// - The current drawing is shown on the screen.
procedure RefreshScreen(); overload;
// Refresh with a target FPS. This will delay a period of time that will
// approximately meet the targetted frames per second.
procedure RefreshScreen(TargetFPS: Longint); overload;
// Refresh the display on the passed in window.
procedure RefreshScreen(wnd: Window; targetFPS: Longint); overload;
// Reset the clipping rectangle of the current window.
procedure ResetClip(); overload;
// Reset the clipping rectangle on a window.
procedure ResetClip(wnd: Window); overload;
// Reset the clipping rectangle on a bitmap.
procedure ResetClip(bmp: Bitmap); overload;
// Get the saturation of the ``color``.
function SaturationOf(c: Color): Single; overload;
// Set the clip rectangle of the current window.
procedure SetClip(const r: Rectangle); overload;
// Set the clip rectangle of the bitmap.
procedure SetClip(bmp: Bitmap; const r: Rectangle); overload;
// Set the clip rectangle of a window.
procedure SetClip(wnd: Window; const r: Rectangle); overload;
// Sets the icon for the window. This must be called before openning the
// graphics window. The icon is loaded as a bitmap, though this can be from
// any kind of bitmap file.
procedure SetIcon(const filename: String); overload;
// Shows the SwinGame intro splash screen.
// It would be great if you could include this at the start of
// your game to help us promote the SwinGame API.
procedure ShowSwinGameSplashScreen(); overload;
// Saves the current screen a bitmap file. The file will be saved into the
// current directory.
procedure TakeScreenshot(const basename: String); overload;
// Get the transpareny value of ``color``.
function TransparencyOf(c: Color): Byte; overload;
// Creates a circle from within a cell in a bitmap, uses the larger of the width and
// height.
function BitmapCellCircle(bmp: Bitmap; const pt: Point2D): Circle; overload;
// Creates a circle from within a cell in a bitmap, uses the larger of the width and
// height.
function BitmapCellCircle(bmp: Bitmap; x: Single; y: Single): Circle; overload;
// Creates a circle that will encompass a cell of the passed in bitmap if it
// were drawn at the indicated point, with the specified scale.
function BitmapCellCircle(bmp: Bitmap; const pt: Point2D; scale: Single): Circle; overload;
// Returns the number of columns of cells in the specified bitmap.
function BitmapCellColumns(bmp: Bitmap): Longint; overload;
// Returns the number of cells in the specified bitmap.
function BitmapCellCount(bmp: Bitmap): Longint; overload;
// Returns the height of a cell within the bitmap.
function BitmapCellHeight(bmp: Bitmap): Longint; overload;
// Returns a bounding rectangle for a cell of the bitmap at the origin.
function BitmapCellRectangle(bmp: Bitmap): Rectangle; overload;
// Returns a rectangle for a cell of the bitmap at the indicated point.
function BitmapCellRectangle(x: Single; y: Single; bmp: Bitmap): Rectangle; overload;
// Returns the number of rows of cells in the specified bitmap.
function BitmapCellRows(bmp: Bitmap): Longint; overload;
// Returns the width of a cell within the bitmap.
function BitmapCellWidth(bmp: Bitmap): Longint; overload;
// Creates a circle from within a bitmap, uses the larger of the width and
// height.
function BitmapCircle(bmp: Bitmap; const pt: Point2D): Circle; overload;
// Creates a circle from within a bitmap, uses the larger of the width and
// height.
function BitmapCircle(bmp: Bitmap; x: Single; y: Single): Circle; overload;
// Returns the Filename of the bitmap
function BitmapFilename(bmp: Bitmap): String; overload;
// Returns the height of the entire bitmap.
function BitmapHeight(bmp: Bitmap): Longint; overload;
// Returns the name of the bitmap
function BitmapName(bmp: Bitmap): String; overload;
// Returns the `Bitmap` that has been loaded with the specified name,
// see `LoadBitmapNamed`.
function BitmapNamed(const name: String): Bitmap; overload;
// Returns a bounding rectangle for the bitmap, at the origin.
function BitmapRectangle(bmp: Bitmap): Rectangle; overload;
// Returns a bounding rectangle for the bitmap.
function BitmapRectangle(x: Single; y: Single; bmp: Bitmap): Rectangle; overload;
// Returns a rectangle for the location of the indicated cell within the
// bitmap.
function BitmapRectangleOfCell(src: Bitmap; cell: Longint): Rectangle; overload;
// This is used to define the number of cells in a bitmap, and
// their width and height. The cells are
// traversed in rows so that the format would be [0 - 1 - 2]
// [3 - 4 - 5] etc. The count can be used to restrict which of the
// parts of the bitmap actually contain cells that can be drawn.
procedure BitmapSetCellDetails(bmp: Bitmap; width: Longint; height: Longint; columns: Longint; rows: Longint; count: Longint); overload;
// Returns the width of the entire bitmap.
function BitmapWidth(bmp: Bitmap): Longint; overload;
// Are the two bitmaps of a similar format that they could be used in
// place of each other. This returns true if they have the same cell
// details (count, width, and height).
function BitmapsInterchangable(bmp1: Bitmap; bmp2: Bitmap): Boolean; overload;
// Clears the drawing on the Bitmap to black.
procedure ClearSurface(dest: Bitmap); overload;
// Clear the drawing on the Bitmap to the passed in color.
procedure ClearSurface(dest: Bitmap; toColor: Color); overload;
// Creates a bitmap in memory that is the specified width and height (in pixels).
// The new bitmap is initially transparent and can be used as the target
// for various drawing operations. Once you have drawn the desired image onto
// the bitmap you can call OptimiseBitmap to optimise the surface.
function CreateBitmap(width: Longint; height: Longint): Bitmap; overload;
// Creates a bitmap in memory that is the specified width and height (in pixels).
// The new bitmap is initially transparent and can be used as the target
// for various drawing operations. Once you have drawn the desired image onto
// the bitmap you can call OptimiseBitmap to optimise the surface.
function CreateBitmap(const name: String; width: Longint; height: Longint): Bitmap; overload;
// Draw the passed in bitmap onto the game.
procedure DrawBitmap(src: Bitmap; x: Single; y: Single); overload;
// Draw the named bitmap onto the game.
procedure DrawBitmap(const name: String; x: Single; y: Single); overload;
// Draw the bitmap using the passed in options
procedure DrawBitmap(src: Bitmap; x: Single; y: Single; const opts: DrawingOptions); overload;
// Draw the bitmap using the passed in options
procedure DrawBitmap(const name: String; x: Single; y: Single; const opts: DrawingOptions); overload;
// Draw a cell from a bitmap onto the game.
procedure DrawCell(src: Bitmap; cell: Longint; x: Single; y: Single); overload;
// Draw a cell from a bitmap onto the game.
procedure DrawCell(src: Bitmap; cell: Longint; x: Single; y: Single; const opts: DrawingOptions); overload;
// Frees a loaded bitmap. Use this when you will no longer be drawing the
// bitmap (including within Sprites), and when the program exits.
procedure FreeBitmap(bitmapToFree: Bitmap); overload;
// Determines if SwinGame has a bitmap loaded for the supplied name.
// This checks against all bitmaps loaded, those loaded without a name
// are assigned the filename as a default.
function HasBitmap(const name: String): Boolean; overload;
// Loads a bitmap from file into a Bitmap variable. This can then be drawn to
// the screen. Bitmaps can be of bmp, jpeg, gif, png, etc. Images may also
// contain alpha values, which will be drawn correctly by the API. All
// bitmaps must be freed using the FreeBitmap once you are finished with
// them.
function LoadBitmap(const filename: String): Bitmap; overload;
// Loads and returns a bitmap. The supplied ``filename`` is used to
// locate the Bitmap to load. The supplied ``name`` indicates the
// name to use to refer to this Bitmap in SwinGame. The `Bitmap` can then be
// retrieved by passing this ``name`` to the `BitmapNamed` function.
function LoadBitmapNamed(const name: String; const filename: String): Bitmap; overload;
// Checks if a pixel is drawn at the specified x,y location.
function PixelDrawnAtPoint(bmp: Bitmap; x: Single; y: Single): Boolean; overload;
// Releases all of the bitmaps that have been loaded.
procedure ReleaseAllBitmaps(); overload;
// Releases the SwinGame resources associated with the bitmap of the
// specified ``name``.
procedure ReleaseBitmap(const name: String); overload;
// Save Bitmap to specific directory.
procedure SaveBitmap(src: Bitmap; const filepath: String); overload;
// Setup the passed in bitmap for pixel level collisions.
procedure SetupBitmapForCollisions(src: Bitmap); overload;
// Checks to see if any key has been pressed since the last time
// `ProcessEvents` was called.
function AnyKeyPressed(): Boolean; overload;
// Returns the string that has been read since `StartReadingText` or
// `StartReadingTextWithText` was called.
function EndReadingText(): String; overload;
// Tells the mouse cursor to hide (no longer visible) if it is currently
// showing. Use `ShowMouse` to make the mouse cursor visible again.
procedure HideMouse(); overload;
// Returns true when the key requested is being held down. This is updated
// as part of the `ProcessEvents` call. Use the key codes from `KeyCode`
// to specify the key to be checked.
function KeyDown(key: KeyCode): Boolean; overload;
// The KeyName function returns a string name for a given `KeyCode`. For
// example, CommaKey returns the string 'Comma'. This function could be used
// to display more meaningful key names for configuring game controls, etc.
function KeyName(key: KeyCode): String; overload;
// Returns true if the specified key was released since the last time
// `ProcessEvents` was called. This occurs only once for the key that is
// released and will not return true again until the key is pressed down and
// released again.
function KeyReleased(key: KeyCode): Boolean; overload;
// Returns true when the key requested is just pressed down. This is updated
// as part of the `ProcessEvents` call. Use the key codes from `KeyCode`
// to specify the key to be checked. this will only occur once for that key that is
// pressed and will not return true again until the key is released and presssed down again
function KeyTyped(key: KeyCode): Boolean; overload;
// Returns false when the key requested is being held down. This is updated
// as part of the `ProcessEvents` call. Use the key codes from `KeyCode`
// to specify the key to be checked.
function KeyUp(key: KeyCode): Boolean; overload;
// Returns true if the specified button was clicked since the last time
// `ProcessEvents` was called
function MouseClicked(button: MouseButton): Boolean; overload;
// Returns ``true`` if the specified button is currently pressed down.
function MouseDown(button: MouseButton): Boolean; overload;
// Returns the amount of accumulated mouse movement, since the last time
// `ProcessEvents` was called, as a `Vector`.
function MouseMovement(): Vector; overload;
// Returns the current window position of the mouse as a `Point2D`
function MousePosition(): Point2D; overload;
// Returns The current window position of the mouse as a `Vector`
function MousePositionAsVector(): Vector; overload;
// Returns ``true`` if the mouse is currently visible, ``false`` if not.
function MouseShown(): Boolean; overload;
// Returns ``true`` if the specified button is currently up.
function MouseUp(button: MouseButton): Boolean; overload;
// Returns the amount the mouse wheel was scrolled since the last call
// to `ProcessEvents`. The result is a vector containing the x and y
// amounts scrolled. Scroll left generates a negative x, scroll right a
// positive x. Scroll backward is negative y, scroll forward positive y.
// Note that on MacOS the directions may be inverted by OS settings.
function MouseWheelScroll(): Vector; overload;
// Returns the current x value of the mouse's position.
function MouseX(): Single; overload;
// Returns the current y value of the mouse's position.
function MouseY(): Single; overload;
// Moves the mouse cursor to the specified screen location.
procedure MoveMouse(const point: Point2D); overload;
// Moves the mouse cursor to the specified screen location.
procedure MoveMouse(x: Longint; y: Longint); overload;
// ProcessEvents allows the SwinGame API to react to user interactions. This
// routine checks the current keyboard and mouse states. This routine must
// be called frequently within your game loop to enable user interaction.
//
// Side Effects
// - Reads user interaction events
// - Updates keys down, text input, etc.
procedure ProcessEvents(); overload;
// Checks to see if the user has asked for the application to quit. This value
// is updated by the `ProcessEvents` routine.
function QuitRequested(): Boolean; overload;
// ReadingText indicates if the API is currently reading text from the
// user. Calling StartReadingText will set this to true, and it becomes
// false when the user presses enter or escape. At this point you can
// read the string entered as either ASCII or Unicode.
function ReadingText(): Boolean; overload;
// Tells the mouse cursor to be visible if it was previously hidden with
// by a `HideMouse` or `SetMouseVisible`(False) call.
procedure ShowMouse(); overload;
// Used to explicitly set the mouse cursors visible state (if it is showing
// in the window or not) based on the show parameter.
procedure ShowMouse(show: Boolean); overload;
// Start reading text within an area. Entry is
// completed when the user presses ENTER, and aborted with ESCAPE.
// If the user aborts entry the result is an empty string, and TextEntryCancelled
// will return true. Text entry is updated during `ProcessEvents`, and text is drawn
// to the screen as part of the `RefreshScreen` call.
procedure StartReadingText(textColor: Color; maxLength: Longint; theFont: Font; const area: Rectangle); overload;
// Starts the reading of a string of characters from the user. Entry is
// completed when the user presses ENTER, and aborted with ESCAPE.
// If the user aborts entry the result is an empty string, and TextEntryCancelled will return true.
// Text entry is updated during `ProcessEvents`, and text is drawn to the screen as part
// of the `RefreshScreen` call.
procedure StartReadingText(textColor: Color; maxLength: Longint; theFont: Font; x: Longint; y: Longint); overload;
// The same as `StartReadingText` but with an additional ``text`` parameter
// that is displayed as default text to the user.
procedure StartReadingTextWithText(const text: String; textColor: Color; maxLength: Longint; theFont: Font; const pt: Point2D); overload;
// The same as `StartReadingText` but with an additional ``text`` parameter
// that is displayed as default text to the user.
procedure StartReadingTextWithText(const text: String; textColor: Color; maxLength: Longint; theFont: Font; const area: Rectangle); overload;
// The same as `StartReadingText` but with an additional ``text`` parameter
// that is displayed as default text to the user.
procedure StartReadingTextWithText(const text: String; textColor: Color; maxLength: Longint; theFont: Font; x: Longint; y: Longint); overload;
// The same as `StartReadingTextWithText` but with ``text`` and ``bgColor`` parameter
// that is displayed as default text to the user.
procedure StartReadingTextWithText(const text: String; textColor: Color; backGroundColor: Color; maxLength: Longint; theFont: Font; const area: Rectangle); overload;
// Returns true if the text entry started with `StartReadingText` was cancelled.
function TextEntryCancelled(): Boolean; overload;
// TextReadAsASCII allows you to read the value of the string entered by the
// user as ASCII. See TextReasAsUNICODE, StartReadingText and ReadingText
// for more details.
function TextReadAsASCII(): String; overload;
// Broadcasts a message to all connections (all servers and opened connections).
procedure BroadcastMessage(const aMsg: String); overload;
// Broadcasts a message to all connections to a given server.
procedure BroadcastMessage(const aMsg: String; const name: String); overload;
// Broadcasts a message to all connections to a given server.
procedure BroadcastMessage(const aMsg: String; svr: ServerSocket); overload;
// This procedure checks for any network activity.
// It first check all servers for incomming connections from clients,
// then it checks for any messages received over any of
// the connections SwinGame is managing.
procedure CheckNetworkActivity(); overload;
// Clears all of the messages from a server.
procedure ClearMessages(svr: ServerSocket); overload;
// Clears all of the messages from a connection.
procedure ClearMessages(aConnection: Connection); overload;
// Clears the Messages from a connection or server.
procedure ClearMessages(const name: String); overload;
// Closes All TCP Receiver Sockets
procedure CloseAllConnections(); overload;
// Closes all sockets that have been created.
procedure CloseAllServers(); overload;
// Closes All UDP Listener Sockets
procedure CloseAllUDPSockets(); overload;
// Closes the specified connection.
function CloseConnection(var aConnection: Connection): Boolean; overload;
// Closes the specified connection.
function CloseConnection(const name: String): Boolean; overload;
// If you access a message directly, you need to make sure that it is closed when
// you have finished with its details. This procedure frees the resources
// used by the message.
procedure CloseMessage(msg: Message); overload;
// Closes the specified server socket. This will close all connections to
// the server, as will stop listening for new connections.
function CloseServer(var svr: ServerSocket): Boolean; overload;
// Closes the specified server socket. This will close all connections to
// the server, as will stop listening for new connections.
function CloseServer(const name: String): Boolean; overload;
// Closes the specified Socket, removed it from the Socket Array, and removes
// the identifier from the NamedIndexCollection.
// Refers to UDP Listener Sockets
function CloseUDPSocket(aPort: Word): Boolean; overload;
// Returns the number of connections to a Server socket.
function ConnectionCount(const name: String): Longint; overload;
// Returns the number of connections to a Server socket.
function ConnectionCount(server: ServerSocket): Longint; overload;
// Gets the IP address (an number) of the destination for the connection (found by its name).
function ConnectionIP(const name: String): Longword; overload;
// Gets the IP address (an number) of the destination for the connection.
function ConnectionIP(aConnection: Connection): Longword; overload;
// Returns the connection for the give name, or nil/null if there is no
// connection with that name.
function ConnectionNamed(const name: String): Connection; overload;
// You can use this to check if a connection is currently open.
// A connection may be closed by the remote machine.
function ConnectionOpen(con: Connection): Boolean; overload;
// You can use this to check if a connection is currently open.
// A connection may be closed by the remote machine.
function ConnectionOpen(const name: String): Boolean; overload;
// Gets the Port of the destination for the connectiom
function ConnectionPort(aConnection: Connection): Word; overload;
// Gets the Port of the destination for the connectiom
function ConnectionPort(const name: String): Word; overload;
// Creates a server socket that listens for TCP connections
// on the port given. Returns the server if this succeeds, otherwise
// it returns nil/null.
function CreateServer(const name: String; port: Word): ServerSocket; overload;
// Creates a server socket that listens for connections
// on the port given. Returns the server if this succeeds, otherwise
// it returns nil/null.
function CreateServer(const name: String; port: Word; protocol: ConnectionType): ServerSocket; overload;
// Converts an Integer to a Hex value and returns it as a string.
function DecToHex(aDec: Longword): String; overload;
// Closes the connection and frees resources.
procedure FreeConnection(var aConnection: Connection); overload;
// Frees the server.
procedure FreeServer(var svr: ServerSocket); overload;
// Checks if any messages have been received for any open connections.
// Messages received are added to the connection they were received from.
function HasMessages(): Boolean; overload;
// Returns true if a connection has messages that you can read.
// Use this to control a loop that reads all of the messages from
// a connection.
function HasMessages(con: Connection): Boolean; overload;
// Returns true if a server has messages that you can read.
// Use this to control a loop that reads all of the messages from
// a server.
function HasMessages(svr: ServerSocket): Boolean; overload;
// Returns true if a connection (found via its name) has messages that you can read.
// Use this to control a loop that reads all of the messages from
// a connection.
function HasMessages(const name: String): Boolean; overload;
// Indicates if there is a new connection to any of the servers
// that are currently listening for new clients.
function HasNewConnections(): Boolean; overload;
// Converts a Hex String to an IPV4 Address (0.0.0.0)
function HexStrToIPv4(const aHex: String): String; overload;
// Converts a Hex String to a Decimal Value as a String.
function HexToDecString(const aHex: String): String; overload;
// Converts an IP to a decimal value
function IPv4ToDec(const aIP: String): Longword; overload;
// Converts an integer representation of a ip address to a string representation.
function IPv4ToStr(ip: Longword): String; overload;
// Returns the last connection made to a server socket. When a new client
// has connected to the server, this function can be used to get their
// connection.
function LastConnection(server: ServerSocket): Connection; overload;
// Returns the last connection made to a server socket. When a new client
// has connected to the server, this function can be used to get their
// connection.
function LastConnection(const name: String): Connection; overload;
// Gets the connection used to send the message (TCP only).
function MessageConnection(msg: Message): Connection; overload;
// Gets the number of messages waiting to be read from this connection
function MessageCount(aConnection: Connection): Longint; overload;
// Gets the number of messages waiting to be read from the connection (found via its named)
function MessageCount(const name: String): Longint; overload;
// Gets the number of messages waiting to be read from this connection
function MessageCount(svr: ServerSocket): Longint; overload;
// Gets the data from a Message. This will be a string.
function MessageData(msg: Message): String; overload;
// Gets the host that sent the message.
function MessageHost(msg: Message): String; overload;
// Gets the port that the host sent the message from.
function MessagePort(msg: Message): Word; overload;
// Gets the protocol that was used to send the Message.
function MessageProtocol(msg: Message): ConnectionType; overload;
// Returns the caller's IP.
function MyIP(): String; overload;
// Opens a connection to a server using the IP and port.
// Creates a Connection for the purpose of two way messages.
// Returns a new connection if successful or nil/null if it fails.
function OpenConnection(const host: String; port: Word): Connection; overload;
// Opens a connection to a server using the IP and port.
// Creates a Connection for the purpose of two way messages.
// Returns a new connection if successful or nil/null if it fails.
// This version allows you to name the connection, so that you can
// access it via its name.
function OpenConnection(const name: String; const host: String; port: Word): Connection; overload;
// Opens a connection to a server using the IP and port.
// Creates a Connection for the purpose of two way messages.
// Returns a new connection if successful or nil/null if it fails.
// This version allows you to name the connection, so that you can
// access it via its name.
function OpenConnection(const name: String; const host: String; port: Word; protocol: ConnectionType): Connection; overload;
// Reads the next message that was sent to the connection. You use this
// to read the values that were sent to this connection.
function ReadMessage(aConnection: Connection): Message; overload;
// Reads the next message that was sent to the connection or server (found from its name).
// You use this to read the values that were sent to this connection or server.
function ReadMessage(const name: String): Message; overload;
// Reads the next message from any of the clients that have connected to the server.
function ReadMessage(svr: ServerSocket): Message; overload;
// Reads the data of the next message that was sent to the connection. You use this
// to read the values that were sent to this connection.
function ReadMessageData(aConnection: Connection): String; overload;
// Reads the data of the next message from any of the clients that have connected to the server.
function ReadMessageData(svr: ServerSocket): String; overload;
// Reads the data of the next message that was sent to the connection or server (found from its name).
// You use this to read the values that were sent to this connection or server.
function ReadMessageData(const name: String): String; overload;
// Attempts to recconnect a connection that was closed using the IP and port
// stored in the connection. Finds the connection using its name.
procedure Reconnect(const name: String); overload;
// Attempts to recconnect a connection that was closed using the IP and port
// stored in the connection
procedure Reconnect(aConnection: Connection); overload;
// Releases All resources used by the Networking code.
procedure ReleaseAllConnections(); overload;
// Retrieves the connection at the specified index
function RetreiveConnection(const name: String; idx: Longint): Connection; overload;
// Retrieves the connection at the specified index
function RetreiveConnection(server: ServerSocket; idx: Longint): Connection; overload;
// Sends the message over the provided network connection.
// Returns true if this succeeds, or false if it fails.
function SendMessageTo(const aMsg: String; aConnection: Connection): Boolean; overload;
// Sends the message over the provided network connection (found from its name).
// Returns true if this succeeds, or false if it fails.
function SendMessageTo(const aMsg: String; const name: String): Boolean; overload;
// Indicates if there is a new connection to a server.
function ServerHasNewConnection(const name: String): Boolean; overload;
// Indicates if there is a new connection to a server.
function ServerHasNewConnection(server: ServerSocket): Boolean; overload;
// Returns the Server socket for the give name, or nil/null if there is no
// server with that name.
function ServerNamed(const name: String): ServerSocket; overload;
// Allows you to change the maximum size for a UDP message (sending and receiving)
procedure SetUDPPacketSize(val: Longint); overload;
// Indicates the maximum size of a UDP message.
function UDPPacketSize(): Longint; overload;
// Free the resources used by the HttpResponse.
procedure FreeHttpResponse(var response: HttpResponse); overload;
// Perform a get request for the resourse at the specified host, path and port.
function HttpGet(const url: String; port: Word): HttpResponse; overload;
// Perform a post request to the specified host, with the supplied body.
function HttpPost(const url: String; port: Word; const body: String): HttpResponse; overload;
// Converts the body of an HttpResponse to a string.
function HttpResponseBodyAsString(httpData: HttpResponse): String; overload;
// Returns True if two bitmaps have collided using per pixel testing if required.
// The ``pt1`` and ``pt2`` (`Point2D`) parameters specify the world location of the bitmaps (``bmp1`` and ``bmp2``).
function BitmapCollision(bmp1: Bitmap; const pt1: Point2D; bmp2: Bitmap; const pt2: Point2D): Boolean; overload;
// Returns True if two bitmaps have collided using per pixel testing if required.
// The ``x`` and ``y`` parameters specify the world location of the bitmaps (``bmp1`` and ``bmp2``).
function BitmapCollision(bmp1: Bitmap; x1: Single; y1: Single; bmp2: Bitmap; x2: Single; y2: Single): Boolean; overload;
// Returns True if the specified parts (``part1`` and ``part2`` rectangles) of the two
// bitmaps (``bmp1`` and ``bmpt2``) have collided, using pixel level collision if required.
// The ``pt1`` and ``pt2`` (`Point2D`) parameters specify the world location of the bitmaps (``bmp1`` and ``bmp2``).
function BitmapCollision(bmp1: Bitmap; const pt1: Point2D; const part1: Rectangle; bmp2: Bitmap; const pt2: Point2D; const part2: Rectangle): Boolean; overload;
// Returns True if a point (``pt``) is located within the ``part`` (rectangle) of the bitmap
// ``bmp`` when it is drawn at ``x``,``y``, using pixel level collisions. For bounding box collisions
// use the rectangle collision functions.
// The ``x`` and ``y`` values specify the world location of the bitmap.
// The point ``pt`` needs to be provided in world coordinates.
function BitmapPartPointCollision(bmp: Bitmap; x: Single; y: Single; const part: Rectangle; const pt: Point2D): Boolean; overload;
// Returns True if a point (``ptX``,``ptY``) is located within the ``part`` (rectangle) of the bitmap
// ``bmp`` when it is drawn at ``x``,``y``, using pixel level collisions. For bounding box collisions
// use the rectangle collision functions.
// The ``x`` and ``y`` values specify the world location of the bitmap.
// The ``ptX`` and ``ptY`` needs to be provided in world coordinates.
function BitmapPartPointCollision(bmp: Bitmap; x: Single; y: Single; const part: Rectangle; ptX: Single; ptY: Single): Boolean; overload;
// Returns True if a point (``pt``) is located within the bitmap
// ``bmp`` when it is drawn at ``x``,``y``, using pixel level collisions.
// The ``x`` and ``y`` values specify the world location of the bitmap.
// The point ``pt`` needs to be provided in world coordinates.
function BitmapPointCollision(bmp: Bitmap; x: Single; y: Single; const pt: Point2D): Boolean; overload;
// Returns True if a point (``ptX``,``ptY``) is located within the bitmap
// ``bmp`` when it is drawn at ``x``,``y``, using pixel level collisions.
// The ``x`` and ``y`` values specify the world location of the bitmap.
// The ``ptX`` and ``ptY`` needs to be provided in world coordinates.
function BitmapPointCollision(bmp: Bitmap; x: Single; y: Single; ptX: Single; ptY: Single): Boolean; overload;
// Returns True if the bitmap ``bmp`` has collided with the rectangle
// specified using pixel level testing if required.
// The ``x`` and ``y`` values specify the world location of the bitmap.
// The rectangle ``rect`` needs to be provided in world coordinates.
function BitmapRectCollision(bmp: Bitmap; x: Single; y: Single; const rect: Rectangle): Boolean; overload;
// Returns True if the indicated part of the bitmap has collided with the specified
// rectangle.
function BitmapRectCollision(bmp: Bitmap; const pt: Point2D; const part: Rectangle; const rect: Rectangle): Boolean; overload;
// Returns True if the indicated part of the bitmap has collided with the specified
// rectangle.
function BitmapRectCollision(bmp: Bitmap; x: Single; y: Single; const part: Rectangle; const rect: Rectangle): Boolean; overload;
// Returns True if the bitmap ``bmp`` has collided with the rectangle
// specified using pixel level testing if required.
// The ``x`` and ``y`` values specify the world location of the bitmap.
// The rectangles world position (``rectX`` and ``rectY``) and size
// (``rectWidth`` and ``rectHeight``) need to be provided.
function BitmapRectCollision(bmp: Bitmap; x: Single; y: Single; rectX: Single; rectY: Single; rectWidth: Single; rectHeight: Single): Boolean; overload;
// Returns true if the cell in the specified bitmap has collided with a bitmap.
function CellBitmapCollision(bmp1: Bitmap; cell: Longint; const pt1: Point2D; bmp2: Bitmap; const pt2: Point2D): Boolean; overload;
// Returns true if the cell in the specified bitmap has collided with a part of a bitmap.
function CellBitmapCollision(bmp1: Bitmap; cell: Longint; const pt1: Point2D; bmp2: Bitmap; const pt2: Point2D; const part: Rectangle): Boolean; overload;
// Returns true if the cell in the specified bitmap has collided with a bitmap.
function CellBitmapCollision(bmp1: Bitmap; cell: Longint; x1: Single; y1: Single; bmp2: Bitmap; x2: Single; y2: Single): Boolean; overload;
// Returns true if the cell in the specified bitmap has collided with a part of a bitmap.
function CellBitmapCollision(bmp1: Bitmap; cell: Longint; x1: Single; y1: Single; bmp2: Bitmap; x2: Single; y2: Single; const part: Rectangle): Boolean; overload;
// Returns true if the cells within the two bitmaps have collided at the given points.
function CellCollision(bmp1: Bitmap; cell1: Longint; const pt1: Point2D; bmp2: Bitmap; cell2: Longint; const pt2: Point2D): Boolean; overload;
// Returns true if the cells within the two bitmaps have collided at their specified x,y locations.
function CellCollision(bmp1: Bitmap; cell1: Longint; x1: Single; y1: Single; bmp2: Bitmap; cell2: Longint; x2: Single; y2: Single): Boolean; overload;
// Returns true if the cell of the bitmap has collided with a given rectangle.
function CellRectCollision(bmp: Bitmap; cell: Longint; const pt: Point2D; const rect: Rectangle): Boolean; overload;
// Returns true if the cell of the bitmap has collided with a given rectangle.
function CellRectCollision(bmp: Bitmap; cell: Longint; x: Single; y: Single; const rect: Rectangle): Boolean; overload;
// Returns True if the circles have collided.
function CircleCircleCollision(const c1: Circle; const c2: Circle): Boolean; overload;
// Returns True if the `Sprite` ``s``, represented by a bounding circle, has
// collided with a ``line``. The diameter for the bounding circle is
// based on the sprites width or height value -- whatever is largest.
function CircleLineCollision(s: Sprite; const line: LineSegment): Boolean; overload;
// Returns True if the Circle collised with rectangle ``rect``.
function CircleRectCollision(const c: Circle; const rect: Rectangle): Boolean; overload;
// Returns True if the Circle has collided with the Triangle ``tri``.
function CircleTriangleCollision(const c: Circle; const tri: Triangle): Boolean; overload;
// Perform a physical collidion with a sprite circle bouncing off a
// stationary circle.
procedure CollideCircleCircle(s: Sprite; const c: Circle); overload;
// Perform a physical collision with a circle bouncing off a line.
procedure CollideCircleLine(s: Sprite; const line: LineSegment); overload;
// Perform a physical collision with a sprite as a circle bouncing off
// a stationary rectangle.
procedure CollideCircleRectangle(s: Sprite; const rect: Rectangle); overload;
// Perform a physical collision with a sprite as a circle bouncing off
// a stationary triangle.
procedure CollideCircleTriangle(s: Sprite; const tri: Triangle); overload;
// Perform a physical collision between two circular sprites.
procedure CollideCircles(s1: Sprite; s2: Sprite); overload;
// Returns True if the bounding rectangle of the `Sprite` ``s`` has collided
// with the ``line`` specified.
function RectLineCollision(s: Sprite; const line: LineSegment): Boolean; overload;
// Returns True if the rectangle ``rect`` provided has collided with the
// ``line``.
function RectLineCollision(const rect: Rectangle; const line: LineSegment): Boolean; overload;
// Returns the side of that needs to be checked for collisions given the
// movement velocity.
function SideForCollisionTest(const velocity: Vector): CollisionSide; overload;
// Returns true if the sprite exists at a certain point.
function SpriteAtPoint(s: Sprite; const pt: Point2D): Boolean; overload;
// Determines if the `Sprite` ``s`` has collided with the bitmap ``bmp`` using
// pixel level testing if required.
// The ``pt`` (`Point2D`) value specifies the world location of the bitmap.
function SpriteBitmapCollision(s: Sprite; bmp: Bitmap; const pt: Point2D): Boolean; overload;
// Determines if the `Sprite` ``s`` has collided with the bitmap ``bmp`` using
// pixel level testing if required.
// The ``x`` and ``y`` values specify the world location of the bitmap.
function SpriteBitmapCollision(s: Sprite; bmp: Bitmap; x: Single; y: Single): Boolean; overload;
// Returns ``true`` if the specifed sprites (``s1`` and ``s2``) have
// collided. Will use simple bounding box tests first, and low-level pixel
// tests if needed.
function SpriteCollision(s1: Sprite; s2: Sprite): Boolean; overload;
// Returns true if the sprite has collided with a rectangle.
function SpriteRectCollision(s: Sprite; const r: Rectangle): Boolean; overload;
// Determined if a sprite has collided with a given rectangle. The rectangles
// coordinates are expressed in "world" coordinates.
function SpriteRectCollision(s: Sprite; x: Single; y: Single; width: Single; height: Single): Boolean; overload;
// Returns true if the triangle and the line have collided.
function TriangleLineCollision(const tri: Triangle; const ln: LineSegment): Boolean; overload;
// Returns the application path set within SwinGame. This is the path
// used to determine the location of the game's resources.
function AppPath(): String; overload;
// Returns the path to the file with the passed in name for a given resource
// kind. This checks if the path exists, throwing an exception if the file
// does not exist in the expected locations.
function FilenameToResource(const name: String; kind: ResourceKind): String; overload;
// Returns ``true`` if the resource bundle is loaded.
function HasResourceBundle(const name: String): Boolean; overload;
// Load a resource bundle showing load progress.
procedure LoadResourceBundle(const name: String); overload;
// Load a resource bundle showing load progress.
procedure LoadResourceBundle(const name: String; showProgress: Boolean); overload;
// Load a resource bundle mapping it to a given name, showing progress.
procedure LoadResourceBundleNamed(const name: String; const filename: String; showProgress: Boolean); overload;
// Returns the path to the filename within the game's resources folder.
function PathToResource(const filename: String): String; overload;
// Returns the path to the filename for a given file resource.
function PathToResource(const filename: String; kind: ResourceKind): String; overload;
// Returns the path to the filename that exists within the game's resources folder
// in the indicated sub directory. For example, to get the "level1.txt" file from
// the Resources/levels folder you call this passing in "level1.txt" as the filename
// and "levels" as the subdir.
function PathToResource(const filename: String; const subdir: String): String; overload;
// Returns the path to the filename that exists within the game's resources folder
// in the indicated sub directory of the directory for the given resource kind .
// For example, to get the "background.png" file from "level1" folder in the images folder
// (i.e. Resources/images/level1/background.png) you call this passing in ``background.png`` as the filename
// ``ImageResource`` as the kind and ``level1`` as the subdir.
function PathToResource(const filename: String; kind: ResourceKind; const subdir: String): String; overload;
// Returns the path to a resource based on a base path and a the resource kind.
function PathToResourceWithBase(const path: String; const filename: String): String; overload;
// Returns the path to a resource based on a base path and a the resource kind.
function PathToResourceWithBase(const path: String; const filename: String; kind: ResourceKind): String; overload;
// Using this procedure you can register a callback that is executed
// each time a resource is freed. This is called by different versions of
// SwinGame to keep track of resources and should not be called by user code.
procedure RegisterFreeNotifier(fn: FreeNotifier); overload;
// Release all of the resources loaded by SwinGame.
procedure ReleaseAllResources(); overload;
// Release the resource bundle with the given name.
procedure ReleaseResourceBundle(const name: String); overload;
// Sets the path to the executable. This path is used for locating game
// resources.
procedure SetAppPath(const path: String); overload;
// Sets the path to the executable. This path is used for locating game
// resources.
procedure SetAppPath(const path: String; withExe: Boolean); overload;
// Call the supplied function for all sprites.
procedure CallForAllSprites(fn: SpriteFunction); overload;
// Register a procedure to be called when an events occur on any sprite.
procedure CallOnSpriteEvent(handler: SpriteEventHandler); overload;
// Returns the center point of the passed in Sprite. This is based on the Sprite's
// Position, Width and Height.
function CenterPoint(s: Sprite): Point2D; overload;
// Creates a sprite for the passed in bitmap image. The sprite will use the cell information within the
// sprite if it is animated at a later stage. This version of CreateSprite will initialise the sprite to use
// pixel level collisions, no animations, and have one layer named 'layer1'.
//
// This version of the constructor will assign a default name to the sprite for resource management purposes.
function CreateSprite(layer: Bitmap): Sprite; overload;
// Creates a sprite for the passed in bitmap image. The sprite will use the cell information within the
// sprite if it is animated at a later stage. This version of CreateSprite will initialise the sprite to use
// pixel level collisions, no animation, the layer have name 'layer1'.
function CreateSprite(const name: String; layer: Bitmap): Sprite; overload;
// Creates a sprite. The bitmapName is used to indicate the bitmap the sprite will use, and the
// animationName is used to indicate which AnimationScript to use.
function CreateSprite(const bitmapName: String; const animationName: String): Sprite; overload;
// Creates a sprite for the passed in bitmap image. The sprite will use the cell information within the
// sprite if it is animated at a later stage. This version of CreateSprite will initialise the sprite to use
// pixel level collisions, the specified animation template, the layer have name 'layer1'.
//
// This version of the constructor will assign a default name to the sprite for resource management purposes.
function CreateSprite(layer: Bitmap; ani: AnimationScript): Sprite; overload;
// Creates a sprite for the passed in bitmap image. The sprite will use the cell information within the
// sprite if it is animated at a later stage. This version of CreateSprite will initialise the sprite to use
// pixel level collisions, the specified animation template, the layer have name 'layer1'.
function CreateSprite(const name: String; layer: Bitmap; ani: AnimationScript): Sprite; overload;
// Create a new SpritePack with a given name. This pack can then be
// selected and used to control which sprites are drawn/updated in
// the calls to DrawAllSprites and UpdateAllSprites.
procedure CreateSpritePack(const name: String); overload;
// Returns the name of the currently selected SpritePack.
function CurrentSpritePack(): String; overload;
// Draws all of the sprites in the current Sprite pack. Packs can be
// switched to select between different sets of sprites.
procedure DrawAllSprites(); overload;
// Draws the sprite at its location in the world. This is effected by the
// position of the camera and the sprites current location.
//
// This is the standard routine for drawing sprites to the screen and should be
// used in most cases.
procedure DrawSprite(s: Sprite); overload;
// Draws the sprite at its position in the game offset by a given amount. Only
// use this method when you want to draw the sprite displaced from its location
// in your game. Otherwise you should change the sprite's location and then
// use the standard ''DrawSprite'' routine.
procedure DrawSprite(s: Sprite; const position: Point2D); overload;
// Draws the sprite at its position in the game offset by a given amount. Only
// use this method when you want to draw the sprite displaced from its location
// in your game. Otherwise you should change the sprite's location and then
// use the standard ''DrawSprite'' routine.
procedure DrawSprite(s: Sprite; xOffset: Longint; yOffset: Longint); overload;
// Free the resources associated with a sprite.
procedure FreeSprite(var s: Sprite); overload;
// Determines if SwinGame has a sprite for the supplied name.
// This checks against all sprites, those loaded without a name
// are assigned a default.
function HasSprite(const name: String): Boolean; overload;
// Indicates if a given SpritePack has already been created.
function HasSpritePack(const name: String): Boolean; overload;
// Moves the sprite as indicated by its velocity. You can call this directly ot
// alternatively, this action is performed when the sprite is updated using
// the ''UpdateSprite'' routine.
procedure MoveSprite(s: Sprite); overload;
// Moves the sprite a given distance based on the value passed in rather than
// based on the sprite's velocity. Typically this method is used to apply
// other movement actions to the sprite and the velocity of the sprite is
// used the intended movement of the sprite.
procedure MoveSprite(s: Sprite; const distance: Vector); overload;
// Moves the sprite as indicated by a percentage of its velocity. You can call
// this directly ot alternatively, this action is performed when the sprite is
// updated using the ''UpdateSprite'' routines that require a percentage.
procedure MoveSprite(s: Sprite; pct: Single); overload;
// Moves the sprite a percentage of a given distance based on the value
// passed in rather than based on the sprite's velocity. Typically this
// method is used to apply other movement actions to the sprite and the
// velocity of the sprite is used the intended movement of the sprite.
procedure MoveSprite(s: Sprite; const distance: Vector; pct: Single); overload;
// This method moves a sprite to a given position in the game.
procedure MoveSpriteTo(s: Sprite; x: Longint; y: Longint); overload;
// Releases all of the sprites that have been loaded.
procedure ReleaseAllSprites(); overload;
// Releases the SwinGame resources associated with the sprite of the
// specified ``name``.
procedure ReleaseSprite(const name: String); overload;
// Selects the named SpritePack (if it has been created). The
// selected SpritePack determines which sprites are drawn and updated
// with the DrawAllSprites and UpdateAllSprites code.
procedure SelectSpritePack(const name: String); overload;
// Adds a new layer to the sprite.
function SpriteAddLayer(s: Sprite; newLayer: Bitmap; const layerName: String): Longint; overload;
// Alters the current velocity of the Sprite, adding the passed in vector to the current velocity.
//
// When the Sprite is updated (see ``UpdateSprite``)
// this vector is used to move the Sprite.
procedure SpriteAddToVelocity(s: Sprite; const value: Vector); overload;
// Adds a new kind of value to the Sprite
procedure SpriteAddValue(s: Sprite; const name: String); overload;
// Adds a new kind of value to the Sprite, setting the initial value
// to the value passed in.
procedure SpriteAddValue(s: Sprite; const name: String; initVal: Single); overload;
// Returns the anchor point of the sprite. This is the point around which the sprite rotates.
// This is in sprite coordinates, so as if the Sprite is drawn at 0,0.
function SpriteAnchorPoint(s: Sprite): Point2D; overload;
// Indicates if the sprites animation has ended.
function SpriteAnimationHasEnded(s: Sprite): Boolean; overload;
// Returns the name of the Sprite's current animation.
function SpriteAnimationName(s: Sprite): String; overload;
// Sends the layer specified forward in the visible layer order.
procedure SpriteBringLayerForward(s: Sprite; visibleLayer: Longint); overload;
// Sends the layer specified to the front in the visible layer order.
procedure SpriteBringLayerToFront(s: Sprite; visibleLayer: Longint); overload;
// Register a procedure to call when events occur on the sprite.
procedure SpriteCallOnEvent(s: Sprite; handler: SpriteEventHandler); overload;
// Gets a circle in the bounds of the base layer of the indicated sprite.
function SpriteCircle(s: Sprite): Circle; overload;
// Returns the bitmap used by the Sprite to determine if it has collided with
// other objects in the game.
function SpriteCollisionBitmap(s: Sprite): Bitmap; overload;
// Gets a circle in the bounds of the indicated sprite's collision rectangle.
function SpriteCollisionCircle(s: Sprite): Circle; overload;
// Returns the kind of collision used with this Sprite. This is used when
// determining if the Sprite has collided with other objects in the game.
function SpriteCollisionKind(s: Sprite): CollisionTestKind; overload;
// Returns the collision rectangle for the specified sprite.
function SpriteCollisionRectangle(s: Sprite): Rectangle; overload;
// Returns the current animation cell for an Animated Sprite. The cell is
// updated when the sprite's animation data is updated.
function SpriteCurrentCell(s: Sprite): Longint; overload;
// Returns a rectangle of the current cell within the Sprite's image. This is used
// to determine what part of the bitmap should be used when the Sprite is drawn.
function SpriteCurrentCellRectangle(s: Sprite): Rectangle; overload;
// Returns the X value of the Sprite's velocity.
function SpriteDX(s: Sprite): Single; overload;
// Returns the Y value of the Sprite's velocity.
function SpriteDY(s: Sprite): Single; overload;
// Returns the direction the Sprite is heading in degrees.
function SpriteHeading(s: Sprite): Single; overload;
// The current Height of the sprite (aligned to the Y axis).
function SpriteHeight(s: Sprite): Longint; overload;
// Hide the specified layer of the sprite.
procedure SpriteHideLayer(s: Sprite; const name: String); overload;
// Hide the specified layer of the sprite.
procedure SpriteHideLayer(s: Sprite; id: Longint); overload;
// Returns the bitmap of the indicated layer of the sprite.
function SpriteLayer(s: Sprite; const name: String): Bitmap; overload;
// Returns the bitmap of the indicated layer of the sprite.
function SpriteLayer(s: Sprite; idx: Longint): Bitmap; overload;
// Gets a circle in the bounds of the indicated layer.
function SpriteLayerCircle(s: Sprite; idx: Longint): Circle; overload;
// Gets a circle in the bounds of the indicated layer.
function SpriteLayerCircle(s: Sprite; const name: String): Circle; overload;
// Returns the number of layers within the Sprite.
function SpriteLayerCount(s: Sprite): Longint; overload;
// The height of a given layer of the Sprite (aligned to the Y axis).
function SpriteLayerHeight(s: Sprite; const name: String): Longint; overload;
// The height of a given layer of the Sprite (aligned to the Y axis).
function SpriteLayerHeight(s: Sprite; idx: Longint): Longint; overload;
// Returns the index of the specified layer.
function SpriteLayerIndex(s: Sprite; const name: String): Longint; overload;
// Returns the name of the specified layer.
function SpriteLayerName(s: Sprite; idx: Longint): String; overload;
// Gets the offset of the specified layer.
function SpriteLayerOffset(s: Sprite; const name: String): Point2D; overload;
// Gets the offset of the specified layer.
function SpriteLayerOffset(s: Sprite; idx: Longint): Point2D; overload;
// Gets a rectangle that surrounds the indicated layer.
function SpriteLayerRectangle(s: Sprite; idx: Longint): Rectangle; overload;
// Gets a rectangle that surrounds the indicated layer.
function SpriteLayerRectangle(s: Sprite; const name: String): Rectangle; overload;
// The width of a given layer of the Sprite (aligned to the X axis).
function SpriteLayerWidth(s: Sprite; idx: Longint): Longint; overload;
// The width of a given layer of the Sprite (aligned to the X axis).
function SpriteLayerWidth(s: Sprite; const name: String): Longint; overload;
// Returns a matrix that can be used to transform points into the coordinate space
// of the passed in sprite.
function SpriteLocationMatrix(s: Sprite): Matrix2D; overload;
// This indicates the mass of the Sprite for any of the collide methods from
// Physics. The mass of two colliding sprites will determine the relative
// velocitys after the collision.
function SpriteMass(s: Sprite): Single; overload;
// Indicates if the sprite is moved from its anchor point, or from its top left.
// When this returns true the location of the Sprite will indicate its anchor point.
// When this returns false the location of the Sprite is its top left corner.
function SpriteMoveFromAnchorPoint(s: Sprite): Boolean; overload;
// This procedure starts the sprite moving to the indicated
// destination point, over a specified number of seconds. When the
// sprite arrives it will raise the SpriteArrived event.
procedure SpriteMoveTo(s: Sprite; const pt: Point2D; takingSeconds: Longint); overload;
// Returns the name of the sprite. This name is used for resource management
// and can be used to interact with the sprite in various routines.
function SpriteName(sprt: Sprite): String; overload;
// Returns the `Sprite` with the specified name,
// see `CreateBasicSprite`.
function SpriteNamed(const name: String): Sprite; overload;
// Returns True if the sprite is entirely off the screen.
function SpriteOffscreen(s: Sprite): Boolean; overload;
// Returns True if a pixel of the `Sprite` ``s`` is at the screen location
// specified (``pt``), which is converted to a world location.
function SpriteOnScreenAt(s: Sprite; const pt: Point2D): Boolean; overload;
// Returns True if a pixel of the `Sprite` ``s`` is at the screen location
// specified (``x`` and ``y``) which is converted to a world location.
function SpriteOnScreenAt(s: Sprite; x: Longint; y: Longint): Boolean; overload;
// Returns the Sprite's position.
function SpritePosition(s: Sprite): Point2D; overload;
// Restart the sprite's current animation, this will play a sound if the
// first cell of the animation is associated with a sound effect.
procedure SpriteReplayAnimation(s: Sprite); overload;
// Restart the sprite's current animation, this will play a sound if
// withSound is true and the first cell of the animation is associated with a sound effect.
procedure SpriteReplayAnimation(s: Sprite; withSound: Boolean); overload;
// This indicates the angle of rotation of the Sprite. This will rotate any
// images of the sprite before drawing, which can be very slow. Avoid using
// this method with bitmap based Sprites where possible.
function SpriteRotation(s: Sprite): Single; overload;
// This indicates the scale of the Sprite. This will scale any
// images of the sprite before drawing, which can be very slow. Avoid using
// this method with bitmap based Sprites where possible.
function SpriteScale(s: Sprite): Single; overload;
// Returns the rectangle representing the location of the Sprite on the
// screen.
function SpriteScreenRectangle(s: Sprite): Rectangle; overload;
// Sends the layer specified backward in the visible layer order.
procedure SpriteSendLayerBackward(s: Sprite; visibleLayer: Longint); overload;
// Sends the layer specified to the back in the visible layer order.
procedure SpriteSendLayerToBack(s: Sprite; visibleLayer: Longint); overload;
// Allows you to set the anchor point for the sprite. This is the point around
// which the sprite rotates. This is in sprite coordinates, so as if the Sprite
// is drawn at 0,0.
procedure SpriteSetAnchorPoint(s: Sprite; pt: Point2D); overload;
// Sets the bitmap used by the Sprite to determine if it has collided with
// other objects in the game. By default the CollisionBitmap is set to the
// bitmap from the Sprite's first layer.
procedure SpriteSetCollisionBitmap(s: Sprite; bmp: Bitmap); overload;
// Sets the kind of collision used with this Sprite. This is used when
// determining if the Sprite has collided with other objects in the game.
procedure SpriteSetCollisionKind(s: Sprite; value: CollisionTestKind); overload;
// Sets the X value of the Sprite's velocity.
procedure SpriteSetDX(s: Sprite; value: Single); overload;
// Sets the Y value of the Sprite's velocity.
procedure SpriteSetDY(s: Sprite; value: Single); overload;
// Alters the direction the Sprite is heading without changing the speed.
procedure SpriteSetHeading(s: Sprite; value: Single); overload;
// Sets the offset of the specified layer.
procedure SpriteSetLayerOffset(s: Sprite; idx: Longint; const value: Point2D); overload;
// Sets the offset of the specified layer.
procedure SpriteSetLayerOffset(s: Sprite; const name: String; const value: Point2D); overload;
// Allows you to change the mass of a Sprite.
procedure SpriteSetMass(s: Sprite; value: Single); overload;
// Allows you to indicate if the sprite is moved from its anchor point, or from its
// top left.
// When set to true the location of the Sprite will be its anchor point.
// When set to false the location of the Sprite is its top left corner.
procedure SpriteSetMoveFromAnchorPoint(s: Sprite; value: Boolean); overload;
// Sets the Sprite's position.
procedure SpriteSetPosition(s: Sprite; const value: Point2D); overload;
// Allows you to change the rotation of a Sprite.
procedure SpriteSetRotation(s: Sprite; value: Single); overload;
// Allows you to change the scale of a Sprite.
procedure SpriteSetScale(s: Sprite; value: Single); overload;
// Alters the speed of the Sprite without effecting the direction.
procedure SpriteSetSpeed(s: Sprite; value: Single); overload;
// Assigns a value to the Sprite.
procedure SpriteSetValue(s: Sprite; const name: String; val: Single); overload;
// Assigns a value to the Sprite.
procedure SpriteSetValue(s: Sprite; idx: Longint; val: Single); overload;
// Sets the current velocity of the Sprite. When the Sprite is updated (see ``UpdateSprite``)
// this vector is used to move the Sprite.
procedure SpriteSetVelocity(s: Sprite; const value: Vector); overload;
// Sets the X position of the Sprite.
procedure SpriteSetX(s: Sprite; value: Single); overload;
// Sets the Y position of the Sprite.
procedure SpriteSetY(s: Sprite; value: Single); overload;
// Show the specified layer of the sprite.
function SpriteShowLayer(s: Sprite; id: Longint): Longint; overload;
// Show the specified layer of the sprite.
function SpriteShowLayer(s: Sprite; const name: String): Longint; overload;
// Returns the current speed (distance travelled per update) of the Sprite.
function SpriteSpeed(s: Sprite): Single; overload;
// Start playing an animation from the sprite's animation template.
// This will play a sound effect if the first cell of the animation
// has a sound.
procedure SpriteStartAnimation(s: Sprite; idx: Longint); overload;
// Start playing an animation from the sprite's animation template.
// This will play a sound effect if the first cell of the animation
// has a sound.
procedure SpriteStartAnimation(s: Sprite; const named: String); overload;
// Start playing an animation from the sprite's animation template.
// The withSound parameter determines whether to play a sound effect
// if the first cell of the animation has a sound.
procedure SpriteStartAnimation(s: Sprite; const named: String; withSound: Boolean); overload;
// Start playing an animation from the sprite's animation template.
// The withSound parameter determines whether to play a sound effect
// if the first cell of the animation has a sound.
procedure SpriteStartAnimation(s: Sprite; idx: Longint; withSound: Boolean); overload;
// Removes an event handler from the sprite, stopping events from this
// Sprite calling the indicated method.
procedure SpriteStopCallingOnEvent(s: Sprite; handler: SpriteEventHandler); overload;
// Toggle the visibility of the specified layer of the sprite.
procedure SpriteToggleLayerVisible(s: Sprite; id: Longint); overload;
// Toggle the visibility of the specified layer of the sprite.
procedure SpriteToggleLayerVisible(s: Sprite; const name: String); overload;
// Returns the sprite's value at the index specified
function SpriteValue(s: Sprite; index: Longint): Single; overload;
// Returns the indicated value of the sprite
function SpriteValue(s: Sprite; const name: String): Single; overload;
// Returns the count of sprite's values.
function SpriteValueCount(s: Sprite): Longint; overload;
// Returns the names of all of the values of the sprite
function SpriteValueName(s: Sprite; idx: Longint): String; overload;
// Returns the current velocity of the Sprite. When the Sprite is updated (see ``UpdateSprite``)
// this vector is used to move the Sprite.
function SpriteVelocity(s: Sprite): Vector; overload;
// Returns the index (z-order) of the sprite's layer.
function SpriteVisibleIndexOfLayer(s: Sprite; id: Longint): Longint; overload;
// Returns the index (z-order) of the sprite's layer.
function SpriteVisibleIndexOfLayer(s: Sprite; const name: String): Longint; overload;
// Returns the index of the n'th (idx parameter) visible layer.
function SpriteVisibleLayer(s: Sprite; idx: Longint): Longint; overload;
// Returns the number of layers that are currently visible for the sprite.
function SpriteVisibleLayerCount(s: Sprite): Longint; overload;
// Returns the id of the layer at index `idx` that is currently visible.
// Index 0 is the background, with larger indexes moving toward the foreground.
// This returns -1 if there are no visible layers.
function SpriteVisibleLayerId(s: Sprite; idx: Longint): Longint; overload;
// The current Width of the sprite (aligned to the X axis).
function SpriteWidth(s: Sprite): Longint; overload;
// Returns the X position of the Sprite.
function SpriteX(s: Sprite): Single; overload;
// Returns the Y position of the Sprite.
function SpriteY(s: Sprite): Single; overload;
// Removes an global event handler, stopping events calling the indicated procedure.
procedure StopCallingOnSpriteEvent(handler: SpriteEventHandler); overload;
// Update all of the sprites in the current Sprite pack.
procedure UpdateAllSprites(); overload;
// Update all of the sprites in the current Sprite pack, passing in a
// percentage value to indicate the percentage to update.
procedure UpdateAllSprites(pct: Single); overload;
// Update the position and animation details of the Sprite.
// This will play a sound effect if the new cell of the animation
// has a sound.
procedure UpdateSprite(s: Sprite); overload;
// Update the position and animation details of the Sprite.
// This will play a sound effect if the new cell of the animation
// has a sound and withSound is true.
procedure UpdateSprite(s: Sprite; withSound: Boolean); overload;
// Update the position and animation details of the Sprite by a
// given percentage of a single unit of movement/animation.
// This will play a sound effect if the new cell of the animation
// has a sound.
procedure UpdateSprite(s: Sprite; pct: Single); overload;
// Update the position and animation details of the Sprite by a
// given percentage of a single unit of movement/animation.
// This will play a sound effect if the new cell of the animation
// has a sound and withSound is true.
procedure UpdateSprite(s: Sprite; pct: Single; withSound: Boolean); overload;
// Updates the animation details of the sprite.
// This will play a sound effect if the new cell of the animation
// has a sound.
procedure UpdateSpriteAnimation(s: Sprite); overload;
// Update the animation details of the Sprite.
// This will play a sound effect if the new cell of the animation
// has a sound and withSound is true.
procedure UpdateSpriteAnimation(s: Sprite; withSound: Boolean); overload;
// Update the animation details of the Sprite by a
// given percentage of a single unit of movement/animation.
// This will play a sound effect if the new cell of the animation
// has a sound.
procedure UpdateSpriteAnimation(s: Sprite; pct: Single); overload;
// Update the position and animation details of the Sprite by a
// given percentage of a single unit of movement/animation.
// This will play a sound effect if the new cell of the animation
// has a sound and withSound is true.
procedure UpdateSpriteAnimation(s: Sprite; pct: Single; withSound: Boolean); overload;
// Returns a `Vector` that is the difference in location from the center of
// the sprite ``s`` to the point ``pt``.
function VectorFromCenterSpriteToPoint(s: Sprite; const pt: Point2D): Vector; overload;
// Returns a `Vector` that is the difference in the position of two sprites
// (``s1`` and ``s2``).
function VectorFromTo(s1: Sprite; s2: Sprite): Vector; overload;
//
procedure DrawFramerate(x: Single; y: Single); overload;
// Draws text using a simple bitmap font that is built into SwinGame.
procedure DrawText(const theText: String; textColor: Color; x: Single; y: Single); overload;
// Draws text using a simple bitmap font that is built into SwinGame.
procedure DrawText(const theText: String; textColor: Color; x: Single; y: Single; const opts: DrawingOptions); overload;
// Draws the text at the specified point using the color and font indicated.
procedure DrawText(const theText: String; textColor: Color; const name: String; x: Single; y: Single); overload;
// Draws the text at the specified point using the color and font indicated.
procedure DrawText(const theText: String; textColor: Color; theFont: Font; x: Single; y: Single); overload;
// Draws the text in the specified rectangle using the fore and back colors, and the font indicated.
procedure DrawText(const theText: String; textColor: Color; backColor: Color; theFont: Font; align: FontAlignment; const area: Rectangle); overload;
// Draws the text at the specified x,y location using the color, font, and options indicated.
procedure DrawText(const theText: String; textColor: Color; const name: String; x: Single; y: Single; const opts: DrawingOptions); overload;
// Draws the text in the specified rectangle using the fore and back colors, and the font indicated.
procedure DrawText(const theText: String; textColor: Color; backColor: Color; const name: String; align: FontAlignment; const area: Rectangle); overload;
// Draws the text at the specified x,y location using the color, font, and options indicated.
procedure DrawText(const theText: String; textColor: Color; theFont: Font; x: Single; y: Single; const opts: DrawingOptions); overload;
// Draws theText at the specified point using the color and font indicated.
procedure DrawText(const theText: String; textColor: Color; const name: String; size: Longint; x: Single; y: Single); overload;
// Draws the text in the rectangle using the fore and back colors, font and options indicated.
procedure DrawText(const theText: String; textColor: Color; backColor: Color; theFont: Font; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload;
// Draws the text at the specified x,y location using the color, font, and options indicated.
procedure DrawText(const theText: String; textColor: Color; const name: String; size: Longint; x: Single; y: Single; const opts: DrawingOptions); overload;
// Draws the text in the rectangle using the fore and back colors, font and options indicated.
procedure DrawText(const theText: String; textColor: Color; backColor: Color; const name: String; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload;
// Draws theText in the specified rectangle using the fore and back colors, and the font indicated.
procedure DrawText(const theText: String; textColor: Color; backColor: Color; const name: String; size: Longint; align: FontAlignment; const area: Rectangle); overload;
// Draws the text in the rectangle using the fore and back colors, font and options indicated.
procedure DrawText(const theText: String; textColor: Color; backColor: Color; const name: String; size: Longint; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload;
// Draws the text onto the bitmap using the color and font indicated, then returns the bitmap created.
// Drawing text is a slow operation, and drawing it to a bitmap, then drawing the bitmap to screen is a
// good idea if the text does not change frequently.
function DrawTextToBitmap(font: Font; const str: String; clrFg: Color; backgroundColor: Color): Bitmap; overload;
// Returns the style settings for the font.
function FontFontStyle(font: Font): FontStyle; overload;
// Determines the name that will be used for a font loaded with
// the indicated fontName and size.
function FontNameFor(const fontName: String; size: Longint): String; overload;
// Returns the `Font` that has been loaded with the specified name,
// see `LoadFontNamed`.
function FontNamed(const name: String): Font; overload;
// Returns the `Font` that has been loaded with the specified name,
// and font size using `LoadFont`.
function FontNamed(const name: String; size: Longint): Font; overload;
// Alters the style of the font. This is time consuming, so load
// fonts multiple times and set the style for each if needed.
procedure FontSetStyle(font: Font; value: FontStyle); overload;
// Frees the resources used by the loaded Font.
procedure FreeFont(var fontToFree: Font); overload;
// Determines if SwinGame has a font loaded for the supplied name.
// This checks against all fonts loaded, those loaded without a name
// are assigned the filename as a default.
function HasFont(const name: String): Boolean; overload;
// Loads a font from file with the specified side. Fonts must be freed using
// the FreeFont routine once finished with. Once the font is loaded you
// can set its style using SetFontStyle. Fonts are then used to draw and
// measure text in your programs.
function LoadFont(const fontName: String; size: Longint): Font; overload;
// Loads and returns a font that can be used to draw text. The supplied
// ``filename`` is used to locate the font to load. The supplied ``name`` indicates the
// name to use to refer to this Font in SwinGame. The `Font` can then be
// retrieved by passing this ``name`` to the `FontNamed` function.
function LoadFontNamed(const name: String; const filename: String; size: Longint): Font; overload;
// Releases all of the fonts that have been loaded.
procedure ReleaseAllFonts(); overload;
// Releases the SwinGame resources associated with the font of the
// specified ``name``.
procedure ReleaseFont(const name: String); overload;
// Returns the font alignment for the passed in character (l = left. r = right, c = center).
function TextAlignmentFrom(const str: String): FontAlignment; overload;
// Returns the height (in pixels) of the passed in text and the font it will be drawn with.
function TextHeight(theFont: Font; const theText: String): Longint; overload;
// Returns the width (in pixels) of the passed in text and the font it will be drawn with.
function TextWidth(theFont: Font; const theText: String): Longint; overload;
// Create and return a new Timer. The timer will not be started, and will have
// an initial 'ticks' of 0.
function CreateTimer(): Timer; overload;
// Create and return a new Timer. The timer will not be started, and will have
// an initial 'ticks' of 0.
function CreateTimer(const name: String): Timer; overload;
// Free a created timer.
procedure FreeTimer(var toFree: Timer); overload;
// Pause the timer, getting ticks from a paused timer
// will continue to return the same time.
procedure PauseTimer(const name: String); overload;
// Pause the timer, getting ticks from a paused timer
// will continue to return the same time.
procedure PauseTimer(toPause: Timer); overload;
// Releases all of the timers that have been loaded.
procedure ReleaseAllTimers(); overload;
// Release the resources used by the timer with
// the indicated name.
procedure ReleaseTimer(const name: String); overload;
// Resets the time of a given timer
procedure ResetTimer(const name: String); overload;
// Resets the time of a given timer
procedure ResetTimer(tmr: Timer); overload;
// Resumes a paused timer.
procedure ResumeTimer(const name: String); overload;
// Resumes a paused timer.
procedure ResumeTimer(toUnpause: Timer); overload;
// Start a timer recording the time that has passed.
procedure StartTimer(toStart: Timer); overload;
// Start a timer recording the time that has passed.
procedure StartTimer(const name: String); overload;
// Stop the timer. The time is reset to 0 and you must
// recall start to begin the timer ticking again.
procedure StopTimer(toStop: Timer); overload;
// Stop the timer. The time is reset to 0 and you must
// recall start to begin the timer ticking again.
procedure StopTimer(const name: String); overload;
// Get the timer created with the indicated named.
function TimerNamed(const name: String): Timer; overload;
// Gets the number of ticks (milliseconds) that have passed since the timer
// was started/reset. When paused the timer's ticks will not advance until
// the timer is once again resumed.
function TimerTicks(const name: String): Longword; overload;
// Gets the number of ticks (milliseconds) that have passed since the timer
// was started/reset. When paused the timer's ticks will not advance until
// the timer is once again resumed.
function TimerTicks(toGet: Timer): Longword; overload;
// Returns the calculated framerate averages, highest, and lowest values along with
// the suggested rendering color.
procedure CalculateFramerate(out average: String; out highest: String; out lowest: String; out textColor: Color); overload;
// Puts the process to sleep for a specified number of
// milliseconds. This can be used to add delays into your
// game.
procedure Delay(time: Longword); overload;
// This function can be used to retrieve a message containing the details of
// the last error that occurred in SwinGame.
function ExceptionMessage(): String; overload;
// This function tells you if an error occurred with the last operation in
// SwinGame.
function ExceptionOccured(): Boolean; overload;
// Returns the average framerate for the last 10 frames as an integer.
function GetFramerate(): Longint; overload;
// Gets the number of milliseconds that have passed. This can be used to
// determine timing operations, such as updating the game elements.
function GetTicks(): Longword; overload;
// Generates a random number between 0 and 1.
function Rnd(): Single; overload;
// Generates a random integer up to (but not including) ubound. Effectively,
// the ubound value specifies the number of random values to create.
function Rnd(ubound: Longint): Longint; overload;
// Retrieves a string representing the version of SwinGame that is executing.
// This can be used to check that the version supports the features required
// for your game.
function SwinGameVersion(): String; overload;
// Activate the passed in panel. If shown, the panel will be clickable. This is the default state of a panel.
procedure ActivatePanel(p: Panel); overload;
// Takes an ID and returns the active button
function ActiveRadioButton(const id: String): Region; overload;
// Takes a panel and an ID and returns the active button
function ActiveRadioButton(pnl: Panel; const id: String): Region; overload;
// Takes a radiogroup and returns the active button's index.
function ActiveRadioButtonIndex(const id: String): Longint; overload;
// Takes a radiogroup and returns the active button's index.
function ActiveRadioButtonIndex(pnl: Panel; const id: String): Longint; overload;
// Returns the parent panel of the active textbox
function ActiveTextBoxParent(): Panel; overload;
// Returns the index of the active textbox's region.
function ActiveTextIndex(): Longint; overload;
// Returns true when the region has been clicked.
function ButtonClicked(const name: String): Boolean; overload;
// Returns true when the region has been clicked.
function ButtonClicked(r: Region): Boolean; overload;
// Sets the checkbox state to val given the ID.
procedure CheckboxSetState(const id: String; val: Boolean); overload;
// Sets the checkbox state to val.
procedure CheckboxSetState(r: Region; val: Boolean); overload;
// Sets the checkbox state to val.
procedure CheckboxSetState(pnl: Panel; const id: String; val: Boolean); overload;
// Returns checkbox state of the checkbox with ID from string
function CheckboxState(r: Region): Boolean; overload;
// Returns checkbox state of the checkbox with ID from string
function CheckboxState(const s: String): Boolean; overload;
// Returns checkbox state of the checkbox with ID in a given Panel
function CheckboxState(p: Panel; const s: String): Boolean; overload;
// Deactivate the panel. The panel will become unclickable, it will remain visible if it was already.
procedure DeactivatePanel(p: Panel); overload;
// Deactivates the active textbox
procedure DeactivateTextBox(); overload;
// Gets if the dialog has been cancelled
function DialogCancelled(): Boolean; overload;
// Gets if the dialog has been Completed
function DialogComplete(): Boolean; overload;
// Gets the path of the dialog
function DialogPath(): String; overload;
// Sets the path of the dialog
procedure DialogSetPath(const fullname: String); overload;
// Sets the GUI whether or not to use Vector Drawing
procedure DrawGUIAsVectors(b: Boolean); overload;
// Draw the currently visible panels (For use in the main loop)
procedure DrawInterface(); overload;
// Finishes reading text and stores in the active textbox
procedure FinishReadingText(); overload;
// Disposes of the panel by panel
procedure FreePanel(var pnl: Panel); overload;
// Returns true if any of the panels in the user interface have been clicked.
function GUIClicked(): Boolean; overload;
// Sets the active textbox to the one with the
// indicated name.
procedure GUISetActiveTextbox(const name: String); overload;
// Sets the active textbox from region
procedure GUISetActiveTextbox(r: Region); overload;
// Sets the Background color of the GUI
procedure GUISetBackgroundColor(c: Color); overload;
// Sets the inactive ForeGround color of the GUI
procedure GUISetBackgroundColorInactive(c: Color); overload;
// Sets the ForeGround color of the GUI
procedure GUISetForegroundColor(c: Color); overload;
// Sets the inactive ForeGround color of the GUI
procedure GUISetForegroundColorInactive(c: Color); overload;
// Checks if TextEntry finished, returns true/false
function GUITextEntryComplete(): Boolean; overload;
// Returns if panel is in Index Collection
function HasPanel(const name: String): Boolean; overload;
// Hide the panel, stop drawing it. Panels which are not being draw can not be interacted with by the user.
procedure HidePanel(p: Panel); overload;
// Hide the panel, stop drawing it. Panels which are not being draw can not be interacted with by the user.
procedure HidePanel(const name: String); overload;
// Returns the index of the region of the textbox in which text was changed/added into most recently.
function IndexOfLastUpdatedTextBox(): Longint; overload;
// Returns if anything is currently being dragged
function IsDragging(): Boolean; overload;
// Returns if panel is currently being dragged
function IsDragging(pnl: Panel): Boolean; overload;
// Set text for Label
procedure LabelSetText(r: Region; const newString: String); overload;
// Set text for Label
procedure LabelSetText(const id: String; const newString: String); overload;
// Set text for Label
procedure LabelSetText(pnl: Panel; const id: String; const newString: String); overload;
// Get text From Label
function LabelText(r: Region): String; overload;
// Get text From Label
function LabelText(const id: String): String; overload;
// Get text From Label
function LabelText(pnl: Panel; const id: String): String; overload;
// Returns active item's index from the list
function ListActiveItemIndex(const id: String): Longint; overload;
// Returns active item's index from the list of the region
function ListActiveItemIndex(r: Region): Longint; overload;
// Returns active item's index from the list
function ListActiveItemIndex(pnl: Panel; const id: String): Longint; overload;
// Returns the text of the active item in the list of the region
function ListActiveItemText(r: Region): String; overload;
// Returns the active item text of the List in with ID
function ListActiveItemText(const ID: String): String; overload;
// Returns the active item text of the List in panel, pnl- with ID, ID
function ListActiveItemText(pnl: Panel; const ID: String): String; overload;
// Adds an item to the list by text
procedure ListAddItem(const id: String; const text: String); overload;
// Adds an item to the list by bitmap
procedure ListAddItem(const id: String; img: Bitmap); overload;
// Adds an item to the list by bitmap
procedure ListAddItem(r: Region; img: Bitmap); overload;
// Adds an item to the list by text
procedure ListAddItem(r: Region; const text: String); overload;
// Adds an item to the list by text and Bitmap
procedure ListAddItem(const id: String; img: Bitmap; const text: String); overload;
// Adds an item to the list by text
procedure ListAddItem(pnl: Panel; const id: String; const text: String); overload;
// Adds an item to the list where the items shows a cell of a
// bitmap.
procedure ListAddItem(r: Region; img: Bitmap; cell: Longint); overload;
// Adds an item to the list
procedure ListAddItem(r: Region; img: Bitmap; const text: String); overload;
// Adds an item to the list by bitmap
procedure ListAddItem(pnl: Panel; const id: String; img: Bitmap); overload;
// Adds an item to the list where the items shows a cell of a
// bitmap.
procedure ListAddItem(const id: String; img: Bitmap; cell: Longint); overload;
// Adds an item to the list where the items shows a cell of a
// bitmap and some text.
procedure ListAddItem(const id: String; img: Bitmap; cell: Longint; const text: String); overload;
// Adds an item to the list where the items shows a cell of a
// bitmap and some text.
procedure ListAddItem(r: Region; img: Bitmap; cell: Longint; const text: String); overload;
// Adds an item to the list where the items shows a cell of a
// bitmap.
procedure ListAddItem(pnl: Panel; const id: String; img: Bitmap; cell: Longint); overload;
// Adds an item to the list by text and Bitmap
procedure ListAddItem(pnl: Panel; const id: String; img: Bitmap; const text: String); overload;
// Adds an item to the list where the items shows a cell of a
// bitmap and some text.
procedure ListAddItem(pnl: Panel; const id: String; img: Bitmap; cell: Longint; const text: String); overload;
// Removes all items from the list.
procedure ListClearItems(const id: String); overload;
// Removes all items from the list of the region
procedure ListClearItems(r: Region); overload;
// Removes all items from the list.
procedure ListClearItems(pnl: Panel; const id: String); overload;
// Returns the number of items in the list
function ListItemCount(const id: String): Longint; overload;
// Returns the number of items in the list of the region
function ListItemCount(r: Region): Longint; overload;
// Returns the number of items in the list
function ListItemCount(pnl: Panel; const id: String): Longint; overload;
// Returns the text of the item at index idx from the List of the Region
function ListItemText(r: Region; idx: Longint): String; overload;
// Returns the text of the item at index idx
function ListItemText(const id: String; idx: Longint): String; overload;
// Returns the text of the item at index idx
function ListItemText(pnl: Panel; const id: String; idx: Longint): String; overload;
// Removes the active item from a list
procedure ListRemoveActiveItem(const id: String); overload;
// Removes the active item from a list
procedure ListRemoveActiveItem(r: Region); overload;
// Removes the active item from a list
procedure ListRemoveActiveItem(pnl: Panel; const id: String); overload;
// Removes item at index idx from the list
procedure ListRemoveItem(const id: String; idx: Longint); overload;
// Removes item at index idx from the list
procedure ListRemoveItem(pnl: Panel; const id: String; idx: Longint); overload;
// Set the active item in the list to the item at index idx
procedure ListSetActiveItemIndex(const id: String; idx: Longint); overload;
// Set the active item in the list to the item at index idx
procedure ListSetActiveItemIndex(pnl: Panel; const id: String; idx: Longint); overload;
// Sets the starting point for the list from region
procedure ListSetStartAt(r: Region; idx: Longint); overload;
// Returns the starting point for the list from region
function ListStartAt(r: Region): Longint; overload;
// Loads panel from panel directory with filename
function LoadPanel(const filename: String): Panel; overload;
// maps panel to name in Hash Table.
function LoadPanelNamed(const name: String; const filename: String): Panel; overload;
// Move panel along vector
procedure MovePanel(p: Panel; const mvmt: Vector); overload;
// Creates a new panel
function NewPanel(const pnlName: String): Panel; overload;
// Returns whether panel is active
function PanelActive(pnl: Panel): Boolean; overload;
// Returns the panel at the point passed in. Returns nil if there is no panel.
function PanelAtPoint(const pt: Point2D): Panel; overload;
// Returns the last panel clicked.
function PanelClicked(): Panel; overload;
// Returns true when the panel was clicked.
function PanelClicked(pnl: Panel): Boolean; overload;
// Returns whether or not the passed panel is currently draggable
function PanelDraggable(p: Panel): Boolean; overload;
// Returns panel filename
function PanelFilename(pnl: Panel): String; overload;
// Returns panel h value
function PanelHeight(p: Panel): Longint; overload;
// Returns height of the panel
function PanelHeight(const name: String): Longint; overload;
// Returns the name of the panel
function PanelName(pnl: Panel): String; overload;
// Returns panel with the name name
function PanelNamed(const name: String): Panel; overload;
// Sets panel's draggability to the passed Boolean
procedure PanelSetDraggable(p: Panel; b: Boolean); overload;
// Returns true if panel is currently visible.
function PanelVisible(p: Panel): Boolean; overload;
// Returns the panel's width
function PanelWidth(p: Panel): Longint; overload;
// Returns the panel's width
function PanelWidth(const name: String): Longint; overload;
// Returns panel x value
function PanelX(p: Panel): Single; overload;
// Returns panel y value
function PanelY(p: Panel): Single; overload;
// Returns true if point is in any region within the panel
function PointInRegion(const pt: Point2D; p: Panel): Boolean; overload;
// Returns true if point is in a region with the indicate `kind` of the panel `p`.
function PointInRegion(const pt: Point2D; p: Panel; kind: GUIElementKind): Boolean; overload;
// Returns true when the region is active.
function RegionActive(forRegion: Region): Boolean; overload;
// Returns the region from the panel at the point
function RegionAtPoint(p: Panel; const pt: Point2D): Region; overload;
// Returns the last region clicked on by user.
function RegionClicked(): Region; overload;
// Returns the ID of the last region clicked on by user.
function RegionClickedID(): String; overload;
// Returns the font used for text rendered in this region.
function RegionFont(r: Region): Font; overload;
// Returns the font alignment of text for this region.
function RegionFontAlignment(r: Region): FontAlignment; overload;
// Returns the Region height value
function RegionHeight(r: Region): Longint; overload;
// Returns the ID of the last region clicked on by user.
function RegionID(r: Region): String; overload;
// Returns the region of the textbox in which text was changed/added into most recently.
function RegionOfLastUpdatedTextBox(): Region; overload;
// Returns the Region with the ID passed from the panel passed
function RegionPanel(r: Region): Panel; overload;
// Sets the font for the region
procedure RegionSetFont(r: Region; f: Font); overload;
// Allows the font to be set for a region
procedure RegionSetFontAlignment(r: Region; align: FontAlignment); overload;
// Returns the Region Wdith value
function RegionWidth(r: Region): Longint; overload;
// Returns the Region with the ID passed
function RegionWithID(const ID: String): Region; overload;
// Returns the Region with the ID passed from the panel passed
function RegionWithID(pnl: Panel; const ID: String): Region; overload;
// Returns the Region X value
function RegionX(r: Region): Single; overload;
// Returns the Region Y value
function RegionY(r: Region): Single; overload;
// Registers the callback with the panel, when an event related to this
// region occurs the procedure registered will be called.
procedure RegisterEventCallback(r: Region; callback: GUIEventCallback); overload;
// Disposes of all panels
procedure ReleaseAllPanels(); overload;
// Disposes of the panel by name, removing it from the index collection, setting its dragging to nil, and hiding it first to avoid crashes.
procedure ReleasePanel(const name: String); overload;
// Takes a region and an ID and selects the button
procedure SelectRadioButton(r: Region); overload;
// Takes an ID and returns the active button
procedure SelectRadioButton(const id: String); overload;
// Takes a panel and an ID and selects the button
procedure SelectRadioButton(pnl: Panel; const id: String); overload;
// Sets the region active to Boolean
procedure SetRegionActive(forRegion: Region; b: Boolean); overload;
// Displays an OpenDialog
procedure ShowOpenDialog(); overload;
// Displays an OpenDialog file/folder/both filter
procedure ShowOpenDialog(select: FileDialogSelectType); overload;
// Display the panel on screen at panel's co-ordinates.
procedure ShowPanel(const name: String); overload;
// Display the panel on screen at panel's co-ordinates.
procedure ShowPanel(p: Panel); overload;
// shows dialog panel
procedure ShowPanelDialog(p: Panel); overload;
// Displays a SaveDialog
procedure ShowSaveDialog(); overload;
// Displays a SaveDialog with file/folder/both filter
procedure ShowSaveDialog(select: FileDialogSelectType); overload;
// Gets the textbox text from region
function TextBoxText(r: Region): String; overload;
// Gets the textbox text from region
function TextBoxText(const id: String): String; overload;
// Gets the textbox text from region
function TextBoxText(pnl: Panel; const id: String): String; overload;
// Sets the textbox text from Id
procedure TextboxSetText(const id: String; const s: String); overload;
// Sets the textbox text from region
procedure TextboxSetText(r: Region; single: Single); overload;
// Sets the textbox text from region
procedure TextboxSetText(r: Region; const s: String); overload;
// Sets the textbox text from region
procedure TextboxSetText(const id: String; single: Single); overload;
// Sets the textbox text from region
procedure TextboxSetText(r: Region; i: Longint); overload;
// Sets the textbox text from Id
procedure TextboxSetText(const id: String; i: Longint); overload;
// Sets the textbox text from panel and Id
procedure TextboxSetText(pnl: Panel; const id: String; i: Longint); overload;
// Sets the textbox text from Panel and Id
procedure TextboxSetText(pnl: Panel; const id: String; single: Single); overload;
// Sets the textbox text from Panel and Id
procedure TextboxSetText(pnl: Panel; const id: String; const s: String); overload;
// Activates the panel if deactivated, and deactivates if activated.
procedure ToggleActivatePanel(p: Panel); overload;
// Toggles the state of a checkbox (ticked/unticked)
procedure ToggleCheckboxState(const id: String); overload;
// Toggles the state of a checkbox (ticked/unticked)
procedure ToggleCheckboxState(pnl: Panel; const id: String); overload;
// Toggles the region active state
procedure ToggleRegionActive(forRegion: Region); overload;
// Toggles whether the panel is being shown or not.
procedure ToggleShowPanel(p: Panel); overload;
// UpdateInterface main loop, checks the draggable, checks the region clicked, updates the interface
procedure UpdateInterface(); overload;
// Returns the ArduinoDevice with the indicated name.
function ArduinoDeviceNamed(const name: String): ArduinoDevice; overload;
// Returns true if there is data waiting to be read from the device.
function ArduinoHasData(dev: ArduinoDevice): Boolean; overload;
// Read a Byte from the ArduinoDevice. Has a short
// timeout and returns 0 if no byte is read within the given time.
function ArduinoReadByte(dev: ArduinoDevice): Byte; overload;
// Reads a byte from the ArduinoDevice, with the given timeout in milliseconds.
// Returns 0 if no byte is read within the given time.
function ArduinoReadByte(dev: ArduinoDevice; timeout: Longint): Byte; overload;
// Reads a line of text from the ArduinoDevice. This
// returns an empty string if nothing is read within a
// few milliseconds.
function ArduinoReadLine(dev: ArduinoDevice): String; overload;
// Reads a line of text from the ArduinoDevice, within a
// specified amount of time.
function ArduinoReadLine(dev: ArduinoDevice; timeout: Longint): String; overload;
// Send a byte value to the arduino device.
procedure ArduinoSendByte(dev: ArduinoDevice; value: Byte); overload;
// Send a string value to the arduino device.
procedure ArduinoSendString(dev: ArduinoDevice; const value: String); overload;
// Send a string value to the arduino device, along with a newline
// so the arduino can identify the end of the sent data.
procedure ArduinoSendStringLine(dev: ArduinoDevice; const value: String); overload;
// Creates an Arduino device at the specified port, with
// the indicated baud. The name of the device matches its port.
function CreateArduinoDevice(const port: String; baud: Longint): ArduinoDevice; overload;
// Creates an Arduino device with the given name,
// at the specified port, with the indicated baud.
function CreateArduinoDevice(const name: String; const port: String; baud: Longint): ArduinoDevice; overload;
// Close the connection to the Arduino Device and dispose
// of the resources associated with the Device.
procedure FreeArduinoDevice(var dev: ArduinoDevice); overload;
// Does an ArduinoDevice exist with the indicated name?
function HasArduinoDevice(const name: String): Boolean; overload;
// Release all of the ArduinoDevices
procedure ReleaseAllArduinoDevices(); overload;
// Release the ArduinoDevice with the indicated name.
procedure ReleaseArduinoDevice(const name: String); overload;
// Returns a DrawingOptions with default values.
function OptionDefaults(): DrawingOptions; overload;
// Use this option to draw to a specified Window. Pass dest the Window you want to draw on.
function OptionDrawTo(dest: Window): DrawingOptions; overload;
// Use this option to draw to a Bitmap. Pass dest the Bitmap you want to draw on.
function OptionDrawTo(dest: Bitmap): DrawingOptions; overload;
// Use this option to draw to a Bitmap. Pass dest the Bitmap you want to draw on.
// Pass opts the other options you want use.
function OptionDrawTo(dest: Bitmap; const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to draw to a Bitmap. Pass dest the Bitmap you want to draw on to.
// Pass opts the other options you want use.
function OptionDrawTo(dest: Window; const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to flip an image along its X axis.
function OptionFlipX(): DrawingOptions; overload;
// Use this option to flip an image along its X axis.
// Pass opts the other options you want use.
function OptionFlipX(const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to flow the drawing of an image along both X and Y axis.
function OptionFlipXY(): DrawingOptions; overload;
// Use this option to flow the drawing of an image along both X and Y axis.
// Pass opts the other options you want use.
function OptionFlipXY(const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to flip the drawing of an image along its Y axis.
function OptionFlipY(): DrawingOptions; overload;
// Use this option to flip the drawing of an image along its Y axis.
// Pass opts the other options you want use.
function OptionFlipY(const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to change the width of line drawings.
function OptionLineWidth(width: Longint): DrawingOptions; overload;
// Use this option to change the width of line drawings.
function OptionLineWidth(width: Longint; const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to draw only part of a bitmap.
function OptionPartBmp(const part: Rectangle): DrawingOptions; overload;
// Use this option to draw only part of a bitmap.
// Pass opts the other options you want use.
function OptionPartBmp(const part: Rectangle; const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to draw only a part of a bitmap.
function OptionPartBmp(x: Single; y: Single; w: Single; h: Single): DrawingOptions; overload;
// Use this option to draw only a part of a bitmap.
// Pass opts the other options you want use.
function OptionPartBmp(x: Single; y: Single; w: Single; h: Single; const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to rotate a bitmap around its centre point.
// Pass opts the other options you want use.
function OptionRotateBmp(angle: Single): DrawingOptions; overload;
// Use this option to rotate a bitmap around its centre point.
function OptionRotateBmp(angle: Single; const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to rotate the drawing of a bitmap. This allows you to set the
// anchor point and rotate around that by a number of degrees.
function OptionRotateBmp(angle: Single; anchorX: Single; anchorY: Single): DrawingOptions; overload;
// Use this option to rotate the drawing of a bitmap. This allows you to set the
// anchor point and rotate around that by a number of degrees.
// Pass opts the other options you want use.
function OptionRotateBmp(angle: Single; anchorX: Single; anchorY: Single; const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to scale the drawing of bitmaps. You can scale x and y separately.
function OptionScaleBmp(scaleX: Single; scaleY: Single): DrawingOptions; overload;
// Use this option to scale the drawing of bitmaps. You can scale x and y separately.
// Pass opts the other options you want use.
function OptionScaleBmp(scaleX: Single; scaleY: Single; const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to draw to the screen, ignoring the positon of the camera.
function OptionToScreen(): DrawingOptions; overload;
// Use this option to draw to the screen, ignoring the positon of the camera.
// Pass opts the other options you want use.
function OptionToScreen(const opts: DrawingOptions): DrawingOptions; overload;
// Use this option to draw in World coordinates -- these are affected by the movement of the camera.
function OptionToWorld(): DrawingOptions; overload;
// Use this option to draw in World coordinates -- these are affected by the movement of the camera.
// Pass opts the other options you want use.
function OptionToWorld(const opts: DrawingOptions): DrawingOptions; overload;
// Changes the size of the screen.
procedure ChangeScreenSize(width: Longint; height: Longint); overload;
// Changes the size of the window.
procedure ChangeWindowSize(const name: String; width: Longint; height: Longint); overload;
// Changes the size of the window.
procedure ChangeWindowSize(wind: Window; width: Longint; height: Longint); overload;
// Close a window.
procedure CloseWindow(wind: Window); overload;
// Close a window that you have opened.
procedure CloseWindow(const name: String); overload;
// Is there a window a window with the specified name.
function HasWindow(const name: String): Boolean; overload;
// Move the window to a new Position on the screen.
procedure MoveWindow(wind: Window; x: Longint; y: Longint); overload;
// Move the window to a new Position on the screen.
procedure MoveWindow(const name: String; x: Longint; y: Longint); overload;
// Opens the window so that it can be drawn onto and used to respond to user
// actions. The window itself is only drawn when you call `RefreshScreen`.
//
// The first window opened will be the primary window, closing this window
// will cause SwinGame to indicate the user wants to quit the program.
//
// Unless otherwise specified using `DrawingOptions`, all drawing operations
// will draw onto the current window. This starts as the first window opened
// but can be changed with `SelectWindow`.
function OpenWindow(const caption: String; width: Longint; height: Longint): Window; overload;
// Save screenshot to specific directory.
procedure SaveScreenshot(src: Window; const filepath: String); overload;
// Returns the height of the screen currently displayed.
function ScreenHeight(): Longint; overload;
// Returns the width of the screen currently displayed.
function ScreenWidth(): Longint; overload;
//
procedure SetCurrentWindow(const name: String); overload;
//
procedure SetCurrentWindow(wnd: Window); overload;
// Switches the application to full screen or back from full screen to
// windowed.
//
// Side Effects:
// - The window switched between fullscreen and windowed
procedure ToggleFullScreen(); overload;
// Toggle the Window border mode. This enables you to toggle from a bordered
// window to a borderless window.
procedure ToggleWindowBorder(); overload;
//
function WindowAtIndex(idx: Longint): Window; overload;
// Checks to see if the primary window has been asked to close. You need to handle
// this if you want the game to end when the window is closed. This value
// is updated by the `ProcessEvents` routine.
function WindowCloseRequested(): Boolean; overload;
// Checks to see if the window has been asked to close. You need to handle
// this if you want the game to end when the window is closed. This value
// is updated by the `ProcessEvents` routine.
function WindowCloseRequested(wind: Window): Boolean; overload;
//
function WindowCount(): Longint; overload;
// Returns the height of a window.
function WindowHeight(wind: Window): Longint; overload;
// Returns the height of a window.
function WindowHeight(const name: String): Longint; overload;
// Get the window with the speficied name.
function WindowNamed(const name: String): Window; overload;
// Returns the Position of the window on the desktop.
function WindowPosition(wind: Window): Point2D; overload;
// Returns the Position of the window on the desktop.
function WindowPosition(const name: String): Point2D; overload;
// Returns the width of a window.
function WindowWidth(wind: Window): Longint; overload;
// Returns the width of a window.
function WindowWidth(const name: String): Longint; overload;
// Returns the window that the user has focused on.
function WindowWithFocus(): Window; overload;
// Return the x Position of the window -- the distance from the
// left side of the primary desktop.
function WindowX(wind: Window): Longint; overload;
// Return the x Position of the window -- the distance from the
// left side of the primary desktop.
function WindowX(const name: String): Longint; overload;
// Return the y Position of the window -- the distance from the
// top side of the primary desktop.
function WindowY(const name: String): Longint; overload;
// Return the y Position of the window -- the distance from the
// top side of the primary desktop.
function WindowY(wind: Window): Longint; overload;
procedure LoadDefaultColors();
implementation
procedure LoadDefaultColors();
begin
end;
function AnimationCount(script: AnimationScript): Longint; overload;
begin
result := sgAnimations.AnimationCount(script);
end;
function AnimationCurrentCell(anim: Animation): Longint; overload;
begin
result := sgAnimations.AnimationCurrentCell(anim);
end;
function AnimationCurrentVector(anim: Animation): Vector; overload;
begin
result := sgAnimations.AnimationCurrentVector(anim);
end;
function AnimationEnded(anim: Animation): Boolean; overload;
begin
result := sgAnimations.AnimationEnded(anim);
end;
function AnimationEnteredFrame(anim: Animation): Boolean; overload;
begin
result := sgAnimations.AnimationEnteredFrame(anim);
end;
function AnimationFrameTime(anim: Animation): Single; overload;
begin
result := sgAnimations.AnimationFrameTime(anim);
end;
function AnimationIndex(temp: AnimationScript; const name: String): Longint; overload;
begin
result := sgAnimations.AnimationIndex(temp,name);
end;
function AnimationName(temp: Animation): String; overload;
begin
result := sgAnimations.AnimationName(temp);
end;
function AnimationName(temp: AnimationScript; idx: Longint): String; overload;
begin
result := sgAnimations.AnimationName(temp,idx);
end;
function AnimationScriptName(script: AnimationScript): String; overload;
begin
result := sgAnimations.AnimationScriptName(script);
end;
function AnimationScriptNamed(const name: String): AnimationScript; overload;
begin
result := sgAnimations.AnimationScriptNamed(name);
end;
procedure AssignAnimation(anim: Animation; idx: Longint; script: AnimationScript); overload;
begin
sgAnimations.AssignAnimation(anim,idx,script);
end;
procedure AssignAnimation(anim: Animation; const name: String; script: AnimationScript); overload;
begin
sgAnimations.AssignAnimation(anim,name,script);
end;
procedure AssignAnimation(anim: Animation; const name: String; script: AnimationScript; withSound: Boolean); overload;
begin
sgAnimations.AssignAnimation(anim,name,script,withSound);
end;
procedure AssignAnimation(anim: Animation; idx: Longint; script: AnimationScript; withSound: Boolean); overload;
begin
sgAnimations.AssignAnimation(anim,idx,script,withSound);
end;
function CreateAnimation(const identifier: String; script: AnimationScript): Animation; overload;
begin
result := sgAnimations.CreateAnimation(identifier,script);
end;
function CreateAnimation(identifier: Longint; script: AnimationScript): Animation; overload;
begin
result := sgAnimations.CreateAnimation(identifier,script);
end;
function CreateAnimation(identifier: Longint; script: AnimationScript; withSound: Boolean): Animation; overload;
begin
result := sgAnimations.CreateAnimation(identifier,script,withSound);
end;
function CreateAnimation(const identifier: String; script: AnimationScript; withSound: Boolean): Animation; overload;
begin
result := sgAnimations.CreateAnimation(identifier,script,withSound);
end;
procedure DrawAnimation(ani: Animation; bmp: Bitmap; const pt: Point2D); overload;
begin
sgAnimations.DrawAnimation(ani,bmp,pt);
end;
procedure DrawAnimation(ani: Animation; bmp: Bitmap; const pt: Point2D; const opts: DrawingOptions); overload;
begin
sgAnimations.DrawAnimation(ani,bmp,pt,opts);
end;
procedure DrawAnimation(ani: Animation; bmp: Bitmap; x: Single; y: Single); overload;
begin
sgAnimations.DrawAnimation(ani,bmp,x,y);
end;
procedure DrawAnimation(ani: Animation; bmp: Bitmap; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgAnimations.DrawAnimation(ani,bmp,x,y,opts);
end;
procedure FreeAnimation(var ani: Animation); overload;
begin
sgAnimations.FreeAnimation(ani);
end;
procedure FreeAnimationScript(var scriptToFree: AnimationScript); overload;
begin
sgAnimations.FreeAnimationScript(scriptToFree);
end;
function HasAnimationScript(const name: String): Boolean; overload;
begin
result := sgAnimations.HasAnimationScript(name);
end;
function LoadAnimationScript(const filename: String): AnimationScript; overload;
begin
result := sgAnimations.LoadAnimationScript(filename);
end;
function LoadAnimationScriptNamed(const name: String; const filename: String): AnimationScript; overload;
begin
result := sgAnimations.LoadAnimationScriptNamed(name,filename);
end;
procedure ReleaseAllAnimationScripts(); overload;
begin
sgAnimations.ReleaseAllAnimationScripts();
end;
procedure ReleaseAnimationScript(const name: String); overload;
begin
sgAnimations.ReleaseAnimationScript(name);
end;
procedure RestartAnimation(anim: Animation); overload;
begin
sgAnimations.RestartAnimation(anim);
end;
procedure RestartAnimation(anim: Animation; withSound: Boolean); overload;
begin
sgAnimations.RestartAnimation(anim,withSound);
end;
procedure UpdateAnimation(anim: Animation); overload;
begin
sgAnimations.UpdateAnimation(anim);
end;
procedure UpdateAnimation(anim: Animation; pct: Single); overload;
begin
sgAnimations.UpdateAnimation(anim,pct);
end;
procedure UpdateAnimation(anim: Animation; pct: Single; withSound: Boolean); overload;
begin
sgAnimations.UpdateAnimation(anim,pct,withSound);
end;
function AudioReady(): Boolean; overload;
begin
result := sgAudio.AudioReady();
end;
procedure CloseAudio(); overload;
begin
sgAudio.CloseAudio();
end;
procedure FadeMusicIn(const name: String; ms: Longint); overload;
begin
sgAudio.FadeMusicIn(name,ms);
end;
procedure FadeMusicIn(mus: Music; ms: Longint); overload;
begin
sgAudio.FadeMusicIn(mus,ms);
end;
procedure FadeMusicIn(mus: Music; loops: Longint; ms: Longint); overload;
begin
sgAudio.FadeMusicIn(mus,loops,ms);
end;
procedure FadeMusicIn(const name: String; loops: Longint; ms: Longint); overload;
begin
sgAudio.FadeMusicIn(name,loops,ms);
end;
procedure FadeMusicOut(ms: Longint); overload;
begin
sgAudio.FadeMusicOut(ms);
end;
procedure FreeMusic(var mus: Music); overload;
begin
sgAudio.FreeMusic(mus);
end;
procedure FreeSoundEffect(var effect: SoundEffect); overload;
begin
sgAudio.FreeSoundEffect(effect);
end;
function HasMusic(const name: String): Boolean; overload;
begin
result := sgAudio.HasMusic(name);
end;
function HasSoundEffect(const name: String): Boolean; overload;
begin
result := sgAudio.HasSoundEffect(name);
end;
function LoadMusic(const filename: String): Music; overload;
begin
result := sgAudio.LoadMusic(filename);
end;
function LoadMusicNamed(const name: String; const filename: String): Music; overload;
begin
result := sgAudio.LoadMusicNamed(name,filename);
end;
function LoadSoundEffect(const filename: String): SoundEffect; overload;
begin
result := sgAudio.LoadSoundEffect(filename);
end;
function LoadSoundEffectNamed(const name: String; const filename: String): SoundEffect; overload;
begin
result := sgAudio.LoadSoundEffectNamed(name,filename);
end;
function MusicFilename(mus: Music): String; overload;
begin
result := sgAudio.MusicFilename(mus);
end;
function MusicName(mus: Music): String; overload;
begin
result := sgAudio.MusicName(mus);
end;
function MusicNamed(const name: String): Music; overload;
begin
result := sgAudio.MusicNamed(name);
end;
function MusicPlaying(): Boolean; overload;
begin
result := sgAudio.MusicPlaying();
end;
function MusicVolume(): Single; overload;
begin
result := sgAudio.MusicVolume();
end;
procedure OpenAudio(); overload;
begin
sgAudio.OpenAudio();
end;
procedure PauseMusic(); overload;
begin
sgAudio.PauseMusic();
end;
procedure PlayMusic(const name: String); overload;
begin
sgAudio.PlayMusic(name);
end;
procedure PlayMusic(mus: Music); overload;
begin
sgAudio.PlayMusic(mus);
end;
procedure PlayMusic(mus: Music; loops: Longint); overload;
begin
sgAudio.PlayMusic(mus,loops);
end;
procedure PlayMusic(const name: String; loops: Longint); overload;
begin
sgAudio.PlayMusic(name,loops);
end;
procedure PlaySoundEffect(effect: SoundEffect); overload;
begin
sgAudio.PlaySoundEffect(effect);
end;
procedure PlaySoundEffect(const name: String); overload;
begin
sgAudio.PlaySoundEffect(name);
end;
procedure PlaySoundEffect(effect: SoundEffect; vol: Single); overload;
begin
sgAudio.PlaySoundEffect(effect,vol);
end;
procedure PlaySoundEffect(effect: SoundEffect; loops: Longint); overload;
begin
sgAudio.PlaySoundEffect(effect,loops);
end;
procedure PlaySoundEffect(const name: String; vol: Single); overload;
begin
sgAudio.PlaySoundEffect(name,vol);
end;
procedure PlaySoundEffect(const name: String; loops: Longint); overload;
begin
sgAudio.PlaySoundEffect(name,loops);
end;
procedure PlaySoundEffect(effect: SoundEffect; loops: Longint; vol: Single); overload;
begin
sgAudio.PlaySoundEffect(effect,loops,vol);
end;
procedure PlaySoundEffect(const name: String; loops: Longint; vol: Single); overload;
begin
sgAudio.PlaySoundEffect(name,loops,vol);
end;
procedure ReleaseAllMusic(); overload;
begin
sgAudio.ReleaseAllMusic();
end;
procedure ReleaseAllSoundEffects(); overload;
begin
sgAudio.ReleaseAllSoundEffects();
end;
procedure ReleaseMusic(const name: String); overload;
begin
sgAudio.ReleaseMusic(name);
end;
procedure ReleaseSoundEffect(const name: String); overload;
begin
sgAudio.ReleaseSoundEffect(name);
end;
procedure ResumeMusic(); overload;
begin
sgAudio.ResumeMusic();
end;
procedure SetMusicVolume(value: Single); overload;
begin
sgAudio.SetMusicVolume(value);
end;
function SoundEffectFilename(effect: SoundEffect): String; overload;
begin
result := sgAudio.SoundEffectFilename(effect);
end;
function SoundEffectName(effect: SoundEffect): String; overload;
begin
result := sgAudio.SoundEffectName(effect);
end;
function SoundEffectNamed(const name: String): SoundEffect; overload;
begin
result := sgAudio.SoundEffectNamed(name);
end;
function SoundEffectPlaying(const name: String): Boolean; overload;
begin
result := sgAudio.SoundEffectPlaying(name);
end;
function SoundEffectPlaying(effect: SoundEffect): Boolean; overload;
begin
result := sgAudio.SoundEffectPlaying(effect);
end;
procedure StopMusic(); overload;
begin
sgAudio.StopMusic();
end;
procedure StopSoundEffect(effect: SoundEffect); overload;
begin
sgAudio.StopSoundEffect(effect);
end;
procedure StopSoundEffect(const name: String); overload;
begin
sgAudio.StopSoundEffect(name);
end;
function TryOpenAudio(): Boolean; overload;
begin
result := sgAudio.TryOpenAudio();
end;
function CameraPos(): Point2D; overload;
begin
result := sgCamera.CameraPos();
end;
function CameraX(): Single; overload;
begin
result := sgCamera.CameraX();
end;
function CameraY(): Single; overload;
begin
result := sgCamera.CameraY();
end;
procedure CenterCameraOn(s: Sprite; const offset: Vector); overload;
begin
sgCamera.CenterCameraOn(s,offset);
end;
procedure CenterCameraOn(s: Sprite; offsetX: Single; offsetY: Single); overload;
begin
sgCamera.CenterCameraOn(s,offsetX,offsetY);
end;
procedure MoveCameraBy(const offset: Vector); overload;
begin
sgCamera.MoveCameraBy(offset);
end;
procedure MoveCameraBy(dx: Single; dy: Single); overload;
begin
sgCamera.MoveCameraBy(dx,dy);
end;
procedure MoveCameraTo(const pt: Point2D); overload;
begin
sgCamera.MoveCameraTo(pt);
end;
procedure MoveCameraTo(x: Single; y: Single); overload;
begin
sgCamera.MoveCameraTo(x,y);
end;
function PointOnScreen(const pt: Point2D): Boolean; overload;
begin
result := sgCamera.PointOnScreen(pt);
end;
function RectOnScreen(const rect: Rectangle): Boolean; overload;
begin
result := sgCamera.RectOnScreen(rect);
end;
procedure SetCameraPos(const pt: Point2D); overload;
begin
sgCamera.SetCameraPos(pt);
end;
procedure SetCameraX(x: Single); overload;
begin
sgCamera.SetCameraX(x);
end;
procedure SetCameraY(y: Single); overload;
begin
sgCamera.SetCameraY(y);
end;
function ToScreen(const worldPoint: Point2D): Point2D; overload;
begin
result := sgCamera.ToScreen(worldPoint);
end;
function ToScreen(const rect: Rectangle): Rectangle; overload;
begin
result := sgCamera.ToScreen(rect);
end;
function ToScreenX(worldX: Single): Single; overload;
begin
result := sgCamera.ToScreenX(worldX);
end;
function ToScreenY(worldY: Single): Single; overload;
begin
result := sgCamera.ToScreenY(worldY);
end;
function ToWorld(const screenPoint: Point2D): Point2D; overload;
begin
result := sgCamera.ToWorld(screenPoint);
end;
function ToWorldX(screenX: Single): Single; overload;
begin
result := sgCamera.ToWorldX(screenX);
end;
function ToWorldY(screenY: Single): Single; overload;
begin
result := sgCamera.ToWorldY(screenY);
end;
function AddVectors(const v1: Vector; const v2: Vector): Vector; overload;
begin
result := sgGeometry.AddVectors(v1,v2);
end;
procedure ApplyMatrix(const m: Matrix2D; var tri: Triangle); overload;
begin
sgGeometry.ApplyMatrix(m,tri);
end;
procedure ApplyMatrix(const m: Matrix2D; var quad: Quad); overload;
begin
sgGeometry.ApplyMatrix(m,quad);
end;
function CalculateAngle(const v1: Vector; const v2: Vector): Single; overload;
begin
result := sgGeometry.CalculateAngle(v1,v2);
end;
function CalculateAngle(s1: Sprite; s2: Sprite): Single; overload;
begin
result := sgGeometry.CalculateAngle(s1,s2);
end;
function CalculateAngle(x1: Single; y1: Single; x2: Single; y2: Single): Single; overload;
begin
result := sgGeometry.CalculateAngle(x1,y1,x2,y2);
end;
function CalculateAngleBetween(const pt1: Point2D; const pt2: Point2D): Single; overload;
begin
result := sgGeometry.CalculateAngleBetween(pt1,pt2);
end;
function CenterPoint(const c: Circle): Point2D; overload;
begin
result := sgGeometry.CenterPoint(c);
end;
function CircleAt(x: Single; y: Single; radius: Single): Circle; overload;
begin
result := sgGeometry.CircleAt(x,y,radius);
end;
function CircleAt(const pt: Point2D; radius: Single): Circle; overload;
begin
result := sgGeometry.CircleAt(pt,radius);
end;
function CircleRadius(const c: Circle): Single; overload;
begin
result := sgGeometry.CircleRadius(c);
end;
function CircleX(const c: Circle): Single; overload;
begin
result := sgGeometry.CircleX(c);
end;
function CircleY(const c: Circle): Single; overload;
begin
result := sgGeometry.CircleY(c);
end;
function ClosestPointOnCircle(const fromPt: Point2D; const c: Circle): Point2D; overload;
begin
result := sgGeometry.ClosestPointOnCircle(fromPt,c);
end;
function ClosestPointOnLine(x: Single; y: Single; const line: LineSegment): Point2D; overload;
begin
result := sgGeometry.ClosestPointOnLine(x,y,line);
end;
function ClosestPointOnLine(const fromPt: Point2D; const line: LineSegment): Point2D; overload;
begin
result := sgGeometry.ClosestPointOnLine(fromPt,line);
end;
function ClosestPointOnLineFromCircle(const c: Circle; const line: LineSegment): Point2D; overload;
begin
result := sgGeometry.ClosestPointOnLineFromCircle(c,line);
end;
function ClosestPointOnRectFromCircle(const c: Circle; const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.ClosestPointOnRectFromCircle(c,rect);
end;
function Cosine(angle: Single): Single; overload;
begin
result := sgGeometry.Cosine(angle);
end;
function CreateCircle(x: Single; y: Single; radius: Single): Circle; overload;
begin
result := sgGeometry.CreateCircle(x,y,radius);
end;
function CreateCircle(const pt: Point2D; radius: Single): Circle; overload;
begin
result := sgGeometry.CreateCircle(pt,radius);
end;
function CreateLine(x1: Single; y1: Single; x2: Single; y2: Single): LineSegment; overload;
begin
result := sgGeometry.CreateLine(x1,y1,x2,y2);
end;
function CreateLine(const pt1: Point2D; const pt2: Point2D): LineSegment; overload;
begin
result := sgGeometry.CreateLine(pt1,pt2);
end;
function CreateLineAsVector(const line: LineSegment): Vector; overload;
begin
result := sgGeometry.CreateLineAsVector(line);
end;
function CreateLineFromVector(const mv: Vector): LineSegment; overload;
begin
result := sgGeometry.CreateLineFromVector(mv);
end;
function CreateLineFromVector(const pt: Point2D; const mv: Vector): LineSegment; overload;
begin
result := sgGeometry.CreateLineFromVector(pt,mv);
end;
function CreateLineFromVector(x: Single; y: Single; const mv: Vector): LineSegment; overload;
begin
result := sgGeometry.CreateLineFromVector(x,y,mv);
end;
function CreateRectangle(x: Single; y: Single; w: Single; h: Single): Rectangle; overload;
begin
result := sgGeometry.CreateRectangle(x,y,w,h);
end;
function CreateRectangle(const tri: Triangle): Rectangle; overload;
begin
result := sgGeometry.CreateRectangle(tri);
end;
function CreateRectangle(const line: LineSegment): Rectangle; overload;
begin
result := sgGeometry.CreateRectangle(line);
end;
function CreateRectangle(const c: Circle): Rectangle; overload;
begin
result := sgGeometry.CreateRectangle(c);
end;
function CreateRectangle(const pt1: Point2D; const pt2: Point2D): Rectangle; overload;
begin
result := sgGeometry.CreateRectangle(pt1,pt2);
end;
function CreateRectangle(const pt: Point2D; width: Single; height: Single): Rectangle; overload;
begin
result := sgGeometry.CreateRectangle(pt,width,height);
end;
function CreateTriangle(ax: Single; ay: Single; bx: Single; by: Single; cx: Single; cy: Single): Triangle; overload;
begin
result := sgGeometry.CreateTriangle(ax,ay,bx,by,cx,cy);
end;
function CreateTriangle(const a: Point2D; const b: Point2D; const c: Point2D): Triangle; overload;
begin
result := sgGeometry.CreateTriangle(a,b,c);
end;
function CreateVectorFromAngle(angle: Single; magnitude: Single): Vector; overload;
begin
result := sgGeometry.CreateVectorFromAngle(angle,magnitude);
end;
function CreateVectorFromPointToRect(const pt: Point2D; const rect: Rectangle): Vector; overload;
begin
result := sgGeometry.CreateVectorFromPointToRect(pt,rect);
end;
function CreateVectorFromPointToRect(x: Single; y: Single; const rect: Rectangle): Vector; overload;
begin
result := sgGeometry.CreateVectorFromPointToRect(x,y,rect);
end;
function CreateVectorFromPointToRect(x: Single; y: Single; rectX: Single; rectY: Single; rectWidth: Single; rectHeight: Single): Vector; overload;
begin
result := sgGeometry.CreateVectorFromPointToRect(x,y,rectX,rectY,rectWidth,rectHeight);
end;
function CreateVectorFromPoints(const p1: Point2D; const p2: Point2D): Vector; overload;
begin
result := sgGeometry.CreateVectorFromPoints(p1,p2);
end;
function CreateVectorToPoint(const p1: Point2D): Vector; overload;
begin
result := sgGeometry.CreateVectorToPoint(p1);
end;
function DistantPointOnCircle(const pt: Point2D; const c: Circle): Point2D; overload;
begin
result := sgGeometry.DistantPointOnCircle(pt,c);
end;
function DistantPointOnCircleHeading(const pt: Point2D; const c: Circle; const heading: Vector; out oppositePt: Point2D): Boolean; overload;
begin
result := sgGeometry.DistantPointOnCircleHeading(pt,c,heading,oppositePt);
end;
function DotProduct(const v1: Vector; const v2: Vector): Single; overload;
begin
result := sgGeometry.DotProduct(v1,v2);
end;
procedure FixRectangle(var rect: Rectangle); overload;
begin
sgGeometry.FixRectangle(rect);
end;
procedure FixRectangle(var x: Single; var y: Single; var width: Single; var height: Single); overload;
begin
sgGeometry.FixRectangle(x,y,width,height);
end;
function IdentityMatrix(): Matrix2D; overload;
begin
result := sgGeometry.IdentityMatrix();
end;
function InsetRectangle(const rect: Rectangle; insetAmount: Single): Rectangle; overload;
begin
result := sgGeometry.InsetRectangle(rect,insetAmount);
end;
function Intersection(const rect1: Rectangle; const rect2: Rectangle): Rectangle; overload;
begin
result := sgGeometry.Intersection(rect1,rect2);
end;
function InvertVector(const v: Vector): Vector; overload;
begin
result := sgGeometry.InvertVector(v);
end;
function LimitVector(const v: Vector; limit: Single): Vector; overload;
begin
result := sgGeometry.LimitVector(v,limit);
end;
function LineAsVector(const line: LineSegment): Vector; overload;
begin
result := sgGeometry.LineAsVector(line);
end;
function LineFrom(x1: Single; y1: Single; x2: Single; y2: Single): LineSegment; overload;
begin
result := sgGeometry.LineFrom(x1,y1,x2,y2);
end;
function LineFrom(const pt1: Point2D; const pt2: Point2D): LineSegment; overload;
begin
result := sgGeometry.LineFrom(pt1,pt2);
end;
function LineFromVector(const mv: Vector): LineSegment; overload;
begin
result := sgGeometry.LineFromVector(mv);
end;
function LineFromVector(const pt: Point2D; const mv: Vector): LineSegment; overload;
begin
result := sgGeometry.LineFromVector(pt,mv);
end;
function LineFromVector(x: Single; y: Single; const mv: Vector): LineSegment; overload;
begin
result := sgGeometry.LineFromVector(x,y,mv);
end;
function LineIntersectionPoint(const line1: LineSegment; const line2: LineSegment; out pt: Point2D): Boolean; overload;
begin
result := sgGeometry.LineIntersectionPoint(line1,line2,pt);
end;
function LineIntersectsCircle(const l: LineSegment; const c: Circle): Boolean; overload;
begin
result := sgGeometry.LineIntersectsCircle(l,c);
end;
function LineIntersectsRect(const line: LineSegment; const rect: Rectangle): Boolean; overload;
begin
result := sgGeometry.LineIntersectsRect(line,rect);
end;
function LineMagnitudeSq(const line: LineSegment): Single; overload;
begin
result := sgGeometry.LineMagnitudeSq(line);
end;
function LineMagnitudeSq(x1: Single; y1: Single; x2: Single; y2: Single): Single; overload;
begin
result := sgGeometry.LineMagnitudeSq(x1,y1,x2,y2);
end;
function LineMidPoint(const line: LineSegment): Point2D; overload;
begin
result := sgGeometry.LineMidPoint(line);
end;
function LineNormal(const line: LineSegment): Vector; overload;
begin
result := sgGeometry.LineNormal(line);
end;
function LineSegmentsIntersect(const line1: LineSegment; const line2: LineSegment): Boolean; overload;
begin
result := sgGeometry.LineSegmentsIntersect(line1,line2);
end;
function LineToString(const ln: LineSegment): String; overload;
begin
result := sgGeometry.LineToString(ln);
end;
function MatrixInverse(const m: Matrix2D): Matrix2D; overload;
begin
result := sgGeometry.MatrixInverse(m);
end;
function MatrixMultiply(const m: Matrix2D; const v: Vector): Vector; overload;
begin
result := sgGeometry.MatrixMultiply(m,v);
end;
function MatrixMultiply(const m1: Matrix2D; const m2: Matrix2D): Matrix2D; overload;
begin
result := sgGeometry.MatrixMultiply(m1,m2);
end;
function MatrixToString(const m: Matrix2D): String; overload;
begin
result := sgGeometry.MatrixToString(m);
end;
function PointAdd(const pt1: Point2D; const pt2: Point2D): Point2D; overload;
begin
result := sgGeometry.PointAdd(pt1,pt2);
end;
function PointAt(x: Single; y: Single): Point2D; overload;
begin
result := sgGeometry.PointAt(x,y);
end;
function PointAt(const startPoint: Point2D; const offset: Vector): Point2D; overload;
begin
result := sgGeometry.PointAt(startPoint,offset);
end;
function PointInCircle(const pt: Point2D; const c: Circle): Boolean; overload;
begin
result := sgGeometry.PointInCircle(pt,c);
end;
function PointInCircle(const pt: Point2D; x: Single; y: Single; radius: Single): Boolean; overload;
begin
result := sgGeometry.PointInCircle(pt,x,y,radius);
end;
function PointInCircle(ptX: Single; ptY: Single; cX: Single; cY: Single; radius: Single): Boolean; overload;
begin
result := sgGeometry.PointInCircle(ptX,ptY,cX,cY,radius);
end;
function PointInRect(const pt: Point2D; const rect: Rectangle): Boolean; overload;
begin
result := sgGeometry.PointInRect(pt,rect);
end;
function PointInRect(x: Single; y: Single; const rect: Rectangle): Boolean; overload;
begin
result := sgGeometry.PointInRect(x,y,rect);
end;
function PointInRect(const pt: Point2D; x: Single; y: Single; w: Single; h: Single): Boolean; overload;
begin
result := sgGeometry.PointInRect(pt,x,y,w,h);
end;
function PointInRect(ptX: Single; ptY: Single; x: Single; y: Single; w: Single; h: Single): Boolean; overload;
begin
result := sgGeometry.PointInRect(ptX,ptY,x,y,w,h);
end;
function PointInTriangle(const pt: Point2D; const tri: Triangle): Boolean; overload;
begin
result := sgGeometry.PointInTriangle(pt,tri);
end;
function PointLineDistance(x: Single; y: Single; const line: LineSegment): Single; overload;
begin
result := sgGeometry.PointLineDistance(x,y,line);
end;
function PointLineDistance(const pt: Point2D; const line: LineSegment): Single; overload;
begin
result := sgGeometry.PointLineDistance(pt,line);
end;
function PointOnLine(const pt: Point2D; const line: LineSegment): Boolean; overload;
begin
result := sgGeometry.PointOnLine(pt,line);
end;
function PointOnLine(const pt: Point2D; x: Single; y: Single; endX: Single; endY: Single): Boolean; overload;
begin
result := sgGeometry.PointOnLine(pt,x,y,endX,endY);
end;
function PointOnPoint(const pt1: Point2D; const pt2: Point2D): Boolean; overload;
begin
result := sgGeometry.PointOnPoint(pt1,pt2);
end;
function PointPointDistance(const pt1: Point2D; const pt2: Point2D): Single; overload;
begin
result := sgGeometry.PointPointDistance(pt1,pt2);
end;
function PointToString(const pt: Point2D): String; overload;
begin
result := sgGeometry.PointToString(pt);
end;
function QuadFrom(const rect: Rectangle): Quad; overload;
begin
result := sgGeometry.QuadFrom(rect);
end;
function QuadFrom(xTopLeft: Single; yTopLeft: Single; xTopRight: Single; yTopRight: Single; xBottomLeft: Single; yBottomLeft: Single; xBottomRight: Single; yBottomRight: Single): Quad; overload;
begin
result := sgGeometry.QuadFrom(xTopLeft,yTopLeft,xTopRight,yTopRight,xBottomLeft,yBottomLeft,xBottomRight,yBottomRight);
end;
function RandomScreenPoint(): Point2D; overload;
begin
result := sgGeometry.RandomScreenPoint();
end;
function RayCircleIntersectDistance(const ray_origin: Point2D; const ray_heading: Vector; const c: Circle): Single; overload;
begin
result := sgGeometry.RayCircleIntersectDistance(ray_origin,ray_heading,c);
end;
function RayIntersectionPoint(const fromPt: Point2D; const heading: Vector; const line: LineSegment; out pt: Point2D): Boolean; overload;
begin
result := sgGeometry.RayIntersectionPoint(fromPt,heading,line,pt);
end;
function RectangleAfterMove(const rect: Rectangle; const mv: Vector): Rectangle; overload;
begin
result := sgGeometry.RectangleAfterMove(rect,mv);
end;
function RectangleBottom(const rect: Rectangle): Single; overload;
begin
result := sgGeometry.RectangleBottom(rect);
end;
function RectangleBottomLeft(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleBottomLeft(rect);
end;
function RectangleBottomRight(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleBottomRight(rect);
end;
function RectangleCenter(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleCenter(rect);
end;
function RectangleCenterBottom(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleCenterBottom(rect);
end;
function RectangleCenterLeft(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleCenterLeft(rect);
end;
function RectangleCenterRight(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleCenterRight(rect);
end;
function RectangleCenterTop(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleCenterTop(rect);
end;
function RectangleFrom(x: Single; y: Single; w: Single; h: Single): Rectangle; overload;
begin
result := sgGeometry.RectangleFrom(x,y,w,h);
end;
function RectangleFrom(const tri: Triangle): Rectangle; overload;
begin
result := sgGeometry.RectangleFrom(tri);
end;
function RectangleFrom(const line: LineSegment): Rectangle; overload;
begin
result := sgGeometry.RectangleFrom(line);
end;
function RectangleFrom(const c: Circle): Rectangle; overload;
begin
result := sgGeometry.RectangleFrom(c);
end;
function RectangleFrom(const pt1: Point2D; const pt2: Point2D): Rectangle; overload;
begin
result := sgGeometry.RectangleFrom(pt1,pt2);
end;
function RectangleFrom(const pt: Point2D; width: Single; height: Single): Rectangle; overload;
begin
result := sgGeometry.RectangleFrom(pt,width,height);
end;
function RectangleLeft(const rect: Rectangle): Single; overload;
begin
result := sgGeometry.RectangleLeft(rect);
end;
function RectangleOffset(const rect: Rectangle; const vec: Vector): Rectangle; overload;
begin
result := sgGeometry.RectangleOffset(rect,vec);
end;
function RectangleRight(const rect: Rectangle): Single; overload;
begin
result := sgGeometry.RectangleRight(rect);
end;
function RectangleToString(const rect: Rectangle): String; overload;
begin
result := sgGeometry.RectangleToString(rect);
end;
function RectangleTop(const rect: Rectangle): Single; overload;
begin
result := sgGeometry.RectangleTop(rect);
end;
function RectangleTopLeft(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleTopLeft(rect);
end;
function RectangleTopRight(const rect: Rectangle): Point2D; overload;
begin
result := sgGeometry.RectangleTopRight(rect);
end;
function RectanglesIntersect(const rect1: Rectangle; const rect2: Rectangle): Boolean; overload;
begin
result := sgGeometry.RectanglesIntersect(rect1,rect2);
end;
function RotationMatrix(deg: Single): Matrix2D; overload;
begin
result := sgGeometry.RotationMatrix(deg);
end;
function ScaleMatrix(scale: Single): Matrix2D; overload;
begin
result := sgGeometry.ScaleMatrix(scale);
end;
function ScaleMatrix(const scale: Point2D): Matrix2D; overload;
begin
result := sgGeometry.ScaleMatrix(scale);
end;
function ScaleRotateTranslateMatrix(const scale: Point2D; deg: Single; const translate: Point2D): Matrix2D; overload;
begin
result := sgGeometry.ScaleRotateTranslateMatrix(scale,deg,translate);
end;
procedure SetQuadPoint(var q: Quad; idx: Longint; value: Point2D); overload;
begin
sgGeometry.SetQuadPoint(q,idx,value);
end;
function Sine(angle: Single): Single; overload;
begin
result := sgGeometry.Sine(angle);
end;
function SubtractVectors(const v1: Vector; const v2: Vector): Vector; overload;
begin
result := sgGeometry.SubtractVectors(v1,v2);
end;
function Tangent(angle: Single): Single; overload;
begin
result := sgGeometry.Tangent(angle);
end;
function TangentPoints(const fromPt: Point2D; const c: Circle; out p1: Point2D; out p2: Point2D): Boolean; overload;
begin
result := sgGeometry.TangentPoints(fromPt,c,p1,p2);
end;
function TranslationMatrix(dx: Single; dy: Single): Matrix2D; overload;
begin
result := sgGeometry.TranslationMatrix(dx,dy);
end;
function TranslationMatrix(const pt: Point2D): Matrix2D; overload;
begin
result := sgGeometry.TranslationMatrix(pt);
end;
function TriangleBarycenter(const tri: Triangle): Point2D; overload;
begin
result := sgGeometry.TriangleBarycenter(tri);
end;
function TriangleFrom(ax: Single; ay: Single; bx: Single; by: Single; cx: Single; cy: Single): Triangle; overload;
begin
result := sgGeometry.TriangleFrom(ax,ay,bx,by,cx,cy);
end;
function TriangleFrom(const a: Point2D; const b: Point2D; const c: Point2D): Triangle; overload;
begin
result := sgGeometry.TriangleFrom(a,b,c);
end;
function TriangleRectangleIntersect(const tri: Triangle; const rect: Rectangle): Boolean; overload;
begin
result := sgGeometry.TriangleRectangleIntersect(tri,rect);
end;
function TriangleToString(const tri: Triangle): String; overload;
begin
result := sgGeometry.TriangleToString(tri);
end;
function UnitVector(const v: Vector): Vector; overload;
begin
result := sgGeometry.UnitVector(v);
end;
function VectorAngle(const v: Vector): Single; overload;
begin
result := sgGeometry.VectorAngle(v);
end;
function VectorFromAngle(angle: Single; magnitude: Single): Vector; overload;
begin
result := sgGeometry.VectorFromAngle(angle,magnitude);
end;
function VectorFromPointToRect(const pt: Point2D; const rect: Rectangle): Vector; overload;
begin
result := sgGeometry.VectorFromPointToRect(pt,rect);
end;
function VectorFromPointToRect(x: Single; y: Single; const rect: Rectangle): Vector; overload;
begin
result := sgGeometry.VectorFromPointToRect(x,y,rect);
end;
function VectorFromPointToRect(x: Single; y: Single; rectX: Single; rectY: Single; rectWidth: Single; rectHeight: Single): Vector; overload;
begin
result := sgGeometry.VectorFromPointToRect(x,y,rectX,rectY,rectWidth,rectHeight);
end;
function VectorFromPoints(const p1: Point2D; const p2: Point2D): Vector; overload;
begin
result := sgGeometry.VectorFromPoints(p1,p2);
end;
function VectorInRect(const v: Vector; const rect: Rectangle): Boolean; overload;
begin
result := sgGeometry.VectorInRect(v,rect);
end;
function VectorInRect(const v: Vector; x: Single; y: Single; w: Single; h: Single): Boolean; overload;
begin
result := sgGeometry.VectorInRect(v,x,y,w,h);
end;
function VectorIsZero(const v: Vector): Boolean; overload;
begin
result := sgGeometry.VectorIsZero(v);
end;
function VectorMagnitude(const v: Vector): Single; overload;
begin
result := sgGeometry.VectorMagnitude(v);
end;
function VectorMagnitudeSq(const v: Vector): Single; overload;
begin
result := sgGeometry.VectorMagnitudeSq(v);
end;
function VectorMultiply(const v: Vector; s: Single): Vector; overload;
begin
result := sgGeometry.VectorMultiply(v,s);
end;
function VectorNormal(const v: Vector): Vector; overload;
begin
result := sgGeometry.VectorNormal(v);
end;
function VectorOutOfCircleFromCircle(const src: Circle; const bounds: Circle; const velocity: Vector): Vector; overload;
begin
result := sgGeometry.VectorOutOfCircleFromCircle(src,bounds,velocity);
end;
function VectorOutOfCircleFromPoint(const pt: Point2D; const c: Circle; const velocity: Vector): Vector; overload;
begin
result := sgGeometry.VectorOutOfCircleFromPoint(pt,c,velocity);
end;
function VectorOutOfRectFromCircle(const c: Circle; const rect: Rectangle; const velocity: Vector): Vector; overload;
begin
result := sgGeometry.VectorOutOfRectFromCircle(c,rect,velocity);
end;
function VectorOutOfRectFromPoint(const pt: Point2D; const rect: Rectangle; const velocity: Vector): Vector; overload;
begin
result := sgGeometry.VectorOutOfRectFromPoint(pt,rect,velocity);
end;
function VectorOutOfRectFromRect(const src: Rectangle; const bounds: Rectangle; const velocity: Vector): Vector; overload;
begin
result := sgGeometry.VectorOutOfRectFromRect(src,bounds,velocity);
end;
function VectorTo(x: Single; y: Single): Vector; overload;
begin
result := sgGeometry.VectorTo(x,y);
end;
function VectorTo(x: Single; y: Single; invertY: Boolean): Vector; overload;
begin
result := sgGeometry.VectorTo(x,y,invertY);
end;
function VectorToPoint(const p1: Point2D): Vector; overload;
begin
result := sgGeometry.VectorToPoint(p1);
end;
function VectorToString(const v: Vector): String; overload;
begin
result := sgGeometry.VectorToString(v);
end;
function VectorsEqual(const v1: Vector; const v2: Vector): Boolean; overload;
begin
result := sgGeometry.VectorsEqual(v1,v2);
end;
function VectorsNotEqual(const v1: Vector; const v2: Vector): Boolean; overload;
begin
result := sgGeometry.VectorsNotEqual(v1,v2);
end;
procedure WidestPoints(const c: Circle; const along: Vector; out pt1: Point2D; out pt2: Point2D); overload;
begin
sgGeometry.WidestPoints(c,along,pt1,pt2);
end;
function AvailableResolution(idx: Longint): Resolution; overload;
begin
result := sgGraphics.AvailableResolution(idx);
end;
function BlueOf(c: Color): Byte; overload;
begin
result := sgGraphics.BlueOf(c);
end;
function BrightnessOf(c: Color): Single; overload;
begin
result := sgGraphics.BrightnessOf(c);
end;
procedure ClearScreen(); overload;
begin
sgGraphics.ClearScreen();
end;
procedure ClearScreen(toColor: Color); overload;
begin
sgGraphics.ClearScreen(toColor);
end;
function ColorAliceBlue(): Color; overload;
begin
result := sgGraphics.ColorAliceBlue();
end;
function ColorAntiqueWhite(): Color; overload;
begin
result := sgGraphics.ColorAntiqueWhite();
end;
function ColorAqua(): Color; overload;
begin
result := sgGraphics.ColorAqua();
end;
function ColorAquamarine(): Color; overload;
begin
result := sgGraphics.ColorAquamarine();
end;
function ColorAzure(): Color; overload;
begin
result := sgGraphics.ColorAzure();
end;
function ColorBeige(): Color; overload;
begin
result := sgGraphics.ColorBeige();
end;
function ColorBisque(): Color; overload;
begin
result := sgGraphics.ColorBisque();
end;
function ColorBlack(): Color; overload;
begin
result := sgGraphics.ColorBlack();
end;
function ColorBlanchedAlmond(): Color; overload;
begin
result := sgGraphics.ColorBlanchedAlmond();
end;
function ColorBlue(): Color; overload;
begin
result := sgGraphics.ColorBlue();
end;
function ColorBlueViolet(): Color; overload;
begin
result := sgGraphics.ColorBlueViolet();
end;
function ColorBrightGreen(): Color; overload;
begin
result := sgGraphics.ColorBrightGreen();
end;
function ColorBrown(): Color; overload;
begin
result := sgGraphics.ColorBrown();
end;
function ColorBurlyWood(): Color; overload;
begin
result := sgGraphics.ColorBurlyWood();
end;
function ColorCadetBlue(): Color; overload;
begin
result := sgGraphics.ColorCadetBlue();
end;
function ColorChartreuse(): Color; overload;
begin
result := sgGraphics.ColorChartreuse();
end;
function ColorChocolate(): Color; overload;
begin
result := sgGraphics.ColorChocolate();
end;
procedure ColorComponents(c: Color; out r: Byte; out g: Byte; out b: Byte; out a: Byte); overload;
begin
sgGraphics.ColorComponents(c,r,g,b,a);
end;
function ColorCoral(): Color; overload;
begin
result := sgGraphics.ColorCoral();
end;
function ColorCornflowerBlue(): Color; overload;
begin
result := sgGraphics.ColorCornflowerBlue();
end;
function ColorCornsilk(): Color; overload;
begin
result := sgGraphics.ColorCornsilk();
end;
function ColorCrimson(): Color; overload;
begin
result := sgGraphics.ColorCrimson();
end;
function ColorCyan(): Color; overload;
begin
result := sgGraphics.ColorCyan();
end;
function ColorDarkBlue(): Color; overload;
begin
result := sgGraphics.ColorDarkBlue();
end;
function ColorDarkCyan(): Color; overload;
begin
result := sgGraphics.ColorDarkCyan();
end;
function ColorDarkGoldenrod(): Color; overload;
begin
result := sgGraphics.ColorDarkGoldenrod();
end;
function ColorDarkGray(): Color; overload;
begin
result := sgGraphics.ColorDarkGray();
end;
function ColorDarkGreen(): Color; overload;
begin
result := sgGraphics.ColorDarkGreen();
end;
function ColorDarkKhaki(): Color; overload;
begin
result := sgGraphics.ColorDarkKhaki();
end;
function ColorDarkMagenta(): Color; overload;
begin
result := sgGraphics.ColorDarkMagenta();
end;
function ColorDarkOliveGreen(): Color; overload;
begin
result := sgGraphics.ColorDarkOliveGreen();
end;
function ColorDarkOrange(): Color; overload;
begin
result := sgGraphics.ColorDarkOrange();
end;
function ColorDarkOrchid(): Color; overload;
begin
result := sgGraphics.ColorDarkOrchid();
end;
function ColorDarkRed(): Color; overload;
begin
result := sgGraphics.ColorDarkRed();
end;
function ColorDarkSalmon(): Color; overload;
begin
result := sgGraphics.ColorDarkSalmon();
end;
function ColorDarkSeaGreen(): Color; overload;
begin
result := sgGraphics.ColorDarkSeaGreen();
end;
function ColorDarkSlateBlue(): Color; overload;
begin
result := sgGraphics.ColorDarkSlateBlue();
end;
function ColorDarkSlateGray(): Color; overload;
begin
result := sgGraphics.ColorDarkSlateGray();
end;
function ColorDarkTurquoise(): Color; overload;
begin
result := sgGraphics.ColorDarkTurquoise();
end;
function ColorDarkViolet(): Color; overload;
begin
result := sgGraphics.ColorDarkViolet();
end;
function ColorDeepPink(): Color; overload;
begin
result := sgGraphics.ColorDeepPink();
end;
function ColorDeepSkyBlue(): Color; overload;
begin
result := sgGraphics.ColorDeepSkyBlue();
end;
function ColorDimGray(): Color; overload;
begin
result := sgGraphics.ColorDimGray();
end;
function ColorDodgerBlue(): Color; overload;
begin
result := sgGraphics.ColorDodgerBlue();
end;
function ColorFirebrick(): Color; overload;
begin
result := sgGraphics.ColorFirebrick();
end;
function ColorFloralWhite(): Color; overload;
begin
result := sgGraphics.ColorFloralWhite();
end;
function ColorForestGreen(): Color; overload;
begin
result := sgGraphics.ColorForestGreen();
end;
function ColorFuchsia(): Color; overload;
begin
result := sgGraphics.ColorFuchsia();
end;
function ColorGainsboro(): Color; overload;
begin
result := sgGraphics.ColorGainsboro();
end;
function ColorGhostWhite(): Color; overload;
begin
result := sgGraphics.ColorGhostWhite();
end;
function ColorGold(): Color; overload;
begin
result := sgGraphics.ColorGold();
end;
function ColorGoldenrod(): Color; overload;
begin
result := sgGraphics.ColorGoldenrod();
end;
function ColorGray(): Color; overload;
begin
result := sgGraphics.ColorGray();
end;
function ColorGreen(): Color; overload;
begin
result := sgGraphics.ColorGreen();
end;
function ColorGreenYellow(): Color; overload;
begin
result := sgGraphics.ColorGreenYellow();
end;
function ColorGrey(): Color; overload;
begin
result := sgGraphics.ColorGrey();
end;
function ColorHoneydew(): Color; overload;
begin
result := sgGraphics.ColorHoneydew();
end;
function ColorHotPink(): Color; overload;
begin
result := sgGraphics.ColorHotPink();
end;
function ColorIndianRed(): Color; overload;
begin
result := sgGraphics.ColorIndianRed();
end;
function ColorIndigo(): Color; overload;
begin
result := sgGraphics.ColorIndigo();
end;
function ColorIvory(): Color; overload;
begin
result := sgGraphics.ColorIvory();
end;
function ColorKhaki(): Color; overload;
begin
result := sgGraphics.ColorKhaki();
end;
function ColorLavender(): Color; overload;
begin
result := sgGraphics.ColorLavender();
end;
function ColorLavenderBlush(): Color; overload;
begin
result := sgGraphics.ColorLavenderBlush();
end;
function ColorLawnGreen(): Color; overload;
begin
result := sgGraphics.ColorLawnGreen();
end;
function ColorLemonChiffon(): Color; overload;
begin
result := sgGraphics.ColorLemonChiffon();
end;
function ColorLightBlue(): Color; overload;
begin
result := sgGraphics.ColorLightBlue();
end;
function ColorLightCoral(): Color; overload;
begin
result := sgGraphics.ColorLightCoral();
end;
function ColorLightCyan(): Color; overload;
begin
result := sgGraphics.ColorLightCyan();
end;
function ColorLightGoldenrodYellow(): Color; overload;
begin
result := sgGraphics.ColorLightGoldenrodYellow();
end;
function ColorLightGray(): Color; overload;
begin
result := sgGraphics.ColorLightGray();
end;
function ColorLightGreen(): Color; overload;
begin
result := sgGraphics.ColorLightGreen();
end;
function ColorLightGrey(): Color; overload;
begin
result := sgGraphics.ColorLightGrey();
end;
function ColorLightPink(): Color; overload;
begin
result := sgGraphics.ColorLightPink();
end;
function ColorLightSalmon(): Color; overload;
begin
result := sgGraphics.ColorLightSalmon();
end;
function ColorLightSeaGreen(): Color; overload;
begin
result := sgGraphics.ColorLightSeaGreen();
end;
function ColorLightSkyBlue(): Color; overload;
begin
result := sgGraphics.ColorLightSkyBlue();
end;
function ColorLightSlateGray(): Color; overload;
begin
result := sgGraphics.ColorLightSlateGray();
end;
function ColorLightSteelBlue(): Color; overload;
begin
result := sgGraphics.ColorLightSteelBlue();
end;
function ColorLightYellow(): Color; overload;
begin
result := sgGraphics.ColorLightYellow();
end;
function ColorLime(): Color; overload;
begin
result := sgGraphics.ColorLime();
end;
function ColorLimeGreen(): Color; overload;
begin
result := sgGraphics.ColorLimeGreen();
end;
function ColorLinen(): Color; overload;
begin
result := sgGraphics.ColorLinen();
end;
function ColorMagenta(): Color; overload;
begin
result := sgGraphics.ColorMagenta();
end;
function ColorMaroon(): Color; overload;
begin
result := sgGraphics.ColorMaroon();
end;
function ColorMediumAquamarine(): Color; overload;
begin
result := sgGraphics.ColorMediumAquamarine();
end;
function ColorMediumBlue(): Color; overload;
begin
result := sgGraphics.ColorMediumBlue();
end;
function ColorMediumOrchid(): Color; overload;
begin
result := sgGraphics.ColorMediumOrchid();
end;
function ColorMediumPurple(): Color; overload;
begin
result := sgGraphics.ColorMediumPurple();
end;
function ColorMediumSeaGreen(): Color; overload;
begin
result := sgGraphics.ColorMediumSeaGreen();
end;
function ColorMediumSlateBlue(): Color; overload;
begin
result := sgGraphics.ColorMediumSlateBlue();
end;
function ColorMediumSpringGreen(): Color; overload;
begin
result := sgGraphics.ColorMediumSpringGreen();
end;
function ColorMediumTurquoise(): Color; overload;
begin
result := sgGraphics.ColorMediumTurquoise();
end;
function ColorMediumVioletRed(): Color; overload;
begin
result := sgGraphics.ColorMediumVioletRed();
end;
function ColorMidnightBlue(): Color; overload;
begin
result := sgGraphics.ColorMidnightBlue();
end;
function ColorMintCream(): Color; overload;
begin
result := sgGraphics.ColorMintCream();
end;
function ColorMistyRose(): Color; overload;
begin
result := sgGraphics.ColorMistyRose();
end;
function ColorMoccasin(): Color; overload;
begin
result := sgGraphics.ColorMoccasin();
end;
function ColorNavajoWhite(): Color; overload;
begin
result := sgGraphics.ColorNavajoWhite();
end;
function ColorNavy(): Color; overload;
begin
result := sgGraphics.ColorNavy();
end;
function ColorOldLace(): Color; overload;
begin
result := sgGraphics.ColorOldLace();
end;
function ColorOlive(): Color; overload;
begin
result := sgGraphics.ColorOlive();
end;
function ColorOliveDrab(): Color; overload;
begin
result := sgGraphics.ColorOliveDrab();
end;
function ColorOrange(): Color; overload;
begin
result := sgGraphics.ColorOrange();
end;
function ColorOrangeRed(): Color; overload;
begin
result := sgGraphics.ColorOrangeRed();
end;
function ColorOrchid(): Color; overload;
begin
result := sgGraphics.ColorOrchid();
end;
function ColorPaleGoldenrod(): Color; overload;
begin
result := sgGraphics.ColorPaleGoldenrod();
end;
function ColorPaleGreen(): Color; overload;
begin
result := sgGraphics.ColorPaleGreen();
end;
function ColorPaleTurquoise(): Color; overload;
begin
result := sgGraphics.ColorPaleTurquoise();
end;
function ColorPaleVioletRed(): Color; overload;
begin
result := sgGraphics.ColorPaleVioletRed();
end;
function ColorPapayaWhip(): Color; overload;
begin
result := sgGraphics.ColorPapayaWhip();
end;
function ColorPeachPuff(): Color; overload;
begin
result := sgGraphics.ColorPeachPuff();
end;
function ColorPeru(): Color; overload;
begin
result := sgGraphics.ColorPeru();
end;
function ColorPink(): Color; overload;
begin
result := sgGraphics.ColorPink();
end;
function ColorPlum(): Color; overload;
begin
result := sgGraphics.ColorPlum();
end;
function ColorPowderBlue(): Color; overload;
begin
result := sgGraphics.ColorPowderBlue();
end;
function ColorPurple(): Color; overload;
begin
result := sgGraphics.ColorPurple();
end;
function ColorRed(): Color; overload;
begin
result := sgGraphics.ColorRed();
end;
function ColorRosyBrown(): Color; overload;
begin
result := sgGraphics.ColorRosyBrown();
end;
function ColorRoyalBlue(): Color; overload;
begin
result := sgGraphics.ColorRoyalBlue();
end;
function ColorSaddleBrown(): Color; overload;
begin
result := sgGraphics.ColorSaddleBrown();
end;
function ColorSalmon(): Color; overload;
begin
result := sgGraphics.ColorSalmon();
end;
function ColorSandyBrown(): Color; overload;
begin
result := sgGraphics.ColorSandyBrown();
end;
function ColorSeaGreen(): Color; overload;
begin
result := sgGraphics.ColorSeaGreen();
end;
function ColorSeaShell(): Color; overload;
begin
result := sgGraphics.ColorSeaShell();
end;
function ColorSienna(): Color; overload;
begin
result := sgGraphics.ColorSienna();
end;
function ColorSilver(): Color; overload;
begin
result := sgGraphics.ColorSilver();
end;
function ColorSkyBlue(): Color; overload;
begin
result := sgGraphics.ColorSkyBlue();
end;
function ColorSlateBlue(): Color; overload;
begin
result := sgGraphics.ColorSlateBlue();
end;
function ColorSlateGray(): Color; overload;
begin
result := sgGraphics.ColorSlateGray();
end;
function ColorSnow(): Color; overload;
begin
result := sgGraphics.ColorSnow();
end;
function ColorSpringGreen(): Color; overload;
begin
result := sgGraphics.ColorSpringGreen();
end;
function ColorSteelBlue(): Color; overload;
begin
result := sgGraphics.ColorSteelBlue();
end;
function ColorSwinburneRed(): Color; overload;
begin
result := sgGraphics.ColorSwinburneRed();
end;
function ColorTan(): Color; overload;
begin
result := sgGraphics.ColorTan();
end;
function ColorTeal(): Color; overload;
begin
result := sgGraphics.ColorTeal();
end;
function ColorThistle(): Color; overload;
begin
result := sgGraphics.ColorThistle();
end;
function ColorToString(c: Color): String; overload;
begin
result := sgGraphics.ColorToString(c);
end;
function ColorTomato(): Color; overload;
begin
result := sgGraphics.ColorTomato();
end;
function ColorTransparent(): Color; overload;
begin
result := sgGraphics.ColorTransparent();
end;
function ColorTurquoise(): Color; overload;
begin
result := sgGraphics.ColorTurquoise();
end;
function ColorViolet(): Color; overload;
begin
result := sgGraphics.ColorViolet();
end;
function ColorWheat(): Color; overload;
begin
result := sgGraphics.ColorWheat();
end;
function ColorWhite(): Color; overload;
begin
result := sgGraphics.ColorWhite();
end;
function ColorWhiteSmoke(): Color; overload;
begin
result := sgGraphics.ColorWhiteSmoke();
end;
function ColorYellow(): Color; overload;
begin
result := sgGraphics.ColorYellow();
end;
function ColorYellowGreen(): Color; overload;
begin
result := sgGraphics.ColorYellowGreen();
end;
function CurrentClip(): Rectangle; overload;
begin
result := sgGraphics.CurrentClip();
end;
function CurrentClip(wnd: Window): Rectangle; overload;
begin
result := sgGraphics.CurrentClip(wnd);
end;
function CurrentClip(bmp: Bitmap): Rectangle; overload;
begin
result := sgGraphics.CurrentClip(bmp);
end;
procedure DrawCircle(clr: Color; x: Single; y: Single; radius: Single); overload;
begin
sgGraphics.DrawCircle(clr,x,y,radius);
end;
procedure DrawCircle(clr: Color; const c: Circle); overload;
begin
sgGraphics.DrawCircle(clr,c);
end;
procedure DrawCircle(clr: Color; const c: Circle; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawCircle(clr,c,opts);
end;
procedure DrawCircle(clr: Color; x: Single; y: Single; radius: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawCircle(clr,x,y,radius,opts);
end;
procedure DrawEllipse(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single); overload;
begin
sgGraphics.DrawEllipse(clr,xPos,yPos,width,height);
end;
procedure DrawEllipse(clr: Color; const rec: Rectangle); overload;
begin
sgGraphics.DrawEllipse(clr,rec);
end;
procedure DrawEllipse(clr: Color; const rec: Rectangle; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawEllipse(clr,rec,opts);
end;
procedure DrawEllipse(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawEllipse(clr,xPos,yPos,width,height,opts);
end;
procedure DrawLine(clr: Color; const fromPt: Point2D; const toPt: Point2D); overload;
begin
sgGraphics.DrawLine(clr,fromPt,toPt);
end;
procedure DrawLine(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single); overload;
begin
sgGraphics.DrawLine(clr,x1,y1,x2,y2);
end;
procedure DrawLine(clr: Color; const l: LineSegment); overload;
begin
sgGraphics.DrawLine(clr,l);
end;
procedure DrawLine(clr: Color; const l: LineSegment; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawLine(clr,l,opts);
end;
procedure DrawLine(clr: Color; const fromPt: Point2D; const toPt: Point2D; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawLine(clr,fromPt,toPt,opts);
end;
procedure DrawLine(clr: Color; xPosStart: Single; yPosStart: Single; xPosEnd: Single; yPosEnd: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawLine(clr,xPosStart,yPosStart,xPosEnd,yPosEnd,opts);
end;
procedure DrawPixel(clr: Color; const position: Point2D); overload;
begin
sgGraphics.DrawPixel(clr,position);
end;
procedure DrawPixel(clr: Color; const position: Point2D; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawPixel(clr,position,opts);
end;
procedure DrawPixel(clr: Color; x: Single; y: Single); overload;
begin
sgGraphics.DrawPixel(clr,x,y);
end;
procedure DrawPixel(clr: Color; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawPixel(clr,x,y,opts);
end;
procedure DrawQuad(clr: Color; const q: Quad); overload;
begin
sgGraphics.DrawQuad(clr,q);
end;
procedure DrawQuad(clr: Color; const q: Quad; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawQuad(clr,q,opts);
end;
procedure DrawRectangle(clr: Color; x: Single; y: Single; width: Single; height: Single); overload;
begin
sgGraphics.DrawRectangle(clr,x,y,width,height);
end;
procedure DrawRectangle(clr: Color; const rect: Rectangle); overload;
begin
sgGraphics.DrawRectangle(clr,rect);
end;
procedure DrawRectangle(clr: Color; const rect: Rectangle; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawRectangle(clr,rect,opts);
end;
procedure DrawRectangle(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawRectangle(clr,xPos,yPos,width,height,opts);
end;
procedure DrawTriangle(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single; x3: Single; y3: Single); overload;
begin
sgGraphics.DrawTriangle(clr,x1,y1,x2,y2,x3,y3);
end;
procedure DrawTriangle(clr: Color; const tri: Triangle); overload;
begin
sgGraphics.DrawTriangle(clr,tri);
end;
procedure DrawTriangle(clr: Color; const tri: Triangle; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawTriangle(clr,tri,opts);
end;
procedure DrawTriangle(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single; x3: Single; y3: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.DrawTriangle(clr,x1,y1,x2,y2,x3,y3,opts);
end;
procedure FillCircle(clr: Color; x: Single; y: Single; radius: Single); overload;
begin
sgGraphics.FillCircle(clr,x,y,radius);
end;
procedure FillCircle(clr: Color; const c: Circle); overload;
begin
sgGraphics.FillCircle(clr,c);
end;
procedure FillCircle(clr: Color; const c: Circle; const opts: DrawingOptions); overload;
begin
sgGraphics.FillCircle(clr,c,opts);
end;
procedure FillCircle(clr: Color; const pt: Point2D; radius: Longint); overload;
begin
sgGraphics.FillCircle(clr,pt,radius);
end;
procedure FillCircle(clr: Color; const pt: Point2D; radius: Longint; const opts: DrawingOptions); overload;
begin
sgGraphics.FillCircle(clr,pt,radius,opts);
end;
procedure FillCircle(clr: Color; x: Single; y: Single; radius: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.FillCircle(clr,x,y,radius,opts);
end;
procedure FillEllipse(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single); overload;
begin
sgGraphics.FillEllipse(clr,xPos,yPos,width,height);
end;
procedure FillEllipse(clr: Color; const rec: Rectangle); overload;
begin
sgGraphics.FillEllipse(clr,rec);
end;
procedure FillEllipse(clr: Color; const rec: Rectangle; const opts: DrawingOptions); overload;
begin
sgGraphics.FillEllipse(clr,rec,opts);
end;
procedure FillEllipse(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.FillEllipse(clr,xPos,yPos,width,height,opts);
end;
procedure FillQuad(clr: Color; const q: Quad); overload;
begin
sgGraphics.FillQuad(clr,q);
end;
procedure FillQuad(clr: Color; const q: Quad; const opts: DrawingOptions); overload;
begin
sgGraphics.FillQuad(clr,q,opts);
end;
procedure FillRectangle(clr: Color; x: Single; y: Single; width: Single; height: Single); overload;
begin
sgGraphics.FillRectangle(clr,x,y,width,height);
end;
procedure FillRectangle(clr: Color; const rect: Rectangle); overload;
begin
sgGraphics.FillRectangle(clr,rect);
end;
procedure FillRectangle(clr: Color; const rect: Rectangle; const opts: DrawingOptions); overload;
begin
sgGraphics.FillRectangle(clr,rect,opts);
end;
procedure FillRectangle(clr: Color; xPos: Single; yPos: Single; width: Single; height: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.FillRectangle(clr,xPos,yPos,width,height,opts);
end;
procedure FillTriangle(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single; x3: Single; y3: Single); overload;
begin
sgGraphics.FillTriangle(clr,x1,y1,x2,y2,x3,y3);
end;
procedure FillTriangle(clr: Color; const tri: Triangle); overload;
begin
sgGraphics.FillTriangle(clr,tri);
end;
procedure FillTriangle(clr: Color; const tri: Triangle; const opts: DrawingOptions); overload;
begin
sgGraphics.FillTriangle(clr,tri,opts);
end;
procedure FillTriangle(clr: Color; x1: Single; y1: Single; x2: Single; y2: Single; x3: Single; y3: Single; const opts: DrawingOptions); overload;
begin
sgGraphics.FillTriangle(clr,x1,y1,x2,y2,x3,y3,opts);
end;
function GetPixel(bmp: Bitmap; x: Single; y: Single): Color; overload;
begin
result := sgGraphics.GetPixel(bmp,x,y);
end;
function GetPixel(wnd: Window; x: Single; y: Single): Color; overload;
begin
result := sgGraphics.GetPixel(wnd,x,y);
end;
function GetPixelFromScreen(x: Single; y: Single): Color; overload;
begin
result := sgGraphics.GetPixelFromScreen(x,y);
end;
function GreenOf(c: Color): Byte; overload;
begin
result := sgGraphics.GreenOf(c);
end;
function HSBColor(hue: Single; saturation: Single; brightness: Single): Color; overload;
begin
result := sgGraphics.HSBColor(hue,saturation,brightness);
end;
procedure HSBValuesOf(c: Color; out h: Single; out s: Single; out b: Single); overload;
begin
sgGraphics.HSBValuesOf(c,h,s,b);
end;
function HueOf(c: Color): Single; overload;
begin
result := sgGraphics.HueOf(c);
end;
function NumberOfResolutions(): Longint; overload;
begin
result := sgGraphics.NumberOfResolutions();
end;
procedure OpenGraphicsWindow(const caption: String; width: Longint; height: Longint); overload;
begin
sgGraphics.OpenGraphicsWindow(caption,width,height);
end;
procedure PopClip(); overload;
begin
sgGraphics.PopClip();
end;
procedure PopClip(bmp: Bitmap); overload;
begin
sgGraphics.PopClip(bmp);
end;
procedure PopClip(wnd: Window); overload;
begin
sgGraphics.PopClip(wnd);
end;
procedure PushClip(const r: Rectangle); overload;
begin
sgGraphics.PushClip(r);
end;
procedure PushClip(bmp: Bitmap; const r: Rectangle); overload;
begin
sgGraphics.PushClip(bmp,r);
end;
procedure PushClip(wnd: Window; const r: Rectangle); overload;
begin
sgGraphics.PushClip(wnd,r);
end;
function RGBAColor(red: Byte; green: Byte; blue: Byte; alpha: Byte): Color; overload;
begin
result := sgGraphics.RGBAColor(red,green,blue,alpha);
end;
function RGBAFloatColor(r: Single; g: Single; b: Single; a: Single): Color; overload;
begin
result := sgGraphics.RGBAFloatColor(r,g,b,a);
end;
function RGBColor(red: Byte; green: Byte; blue: Byte): Color; overload;
begin
result := sgGraphics.RGBColor(red,green,blue);
end;
function RGBFloatColor(r: Single; g: Single; b: Single): Color; overload;
begin
result := sgGraphics.RGBFloatColor(r,g,b);
end;
function RandomColor(): Color; overload;
begin
result := sgGraphics.RandomColor();
end;
function RandomRGBColor(alpha: Byte): Color; overload;
begin
result := sgGraphics.RandomRGBColor(alpha);
end;
function RedOf(c: Color): Byte; overload;
begin
result := sgGraphics.RedOf(c);
end;
procedure RefreshScreen(); overload;
begin
sgGraphics.RefreshScreen();
end;
procedure RefreshScreen(TargetFPS: Longint); overload;
begin
sgGraphics.RefreshScreen(TargetFPS);
end;
procedure RefreshScreen(wnd: Window; targetFPS: Longint); overload;
begin
sgGraphics.RefreshScreen(wnd,targetFPS);
end;
procedure ResetClip(); overload;
begin
sgGraphics.ResetClip();
end;
procedure ResetClip(wnd: Window); overload;
begin
sgGraphics.ResetClip(wnd);
end;
procedure ResetClip(bmp: Bitmap); overload;
begin
sgGraphics.ResetClip(bmp);
end;
function SaturationOf(c: Color): Single; overload;
begin
result := sgGraphics.SaturationOf(c);
end;
procedure SetClip(const r: Rectangle); overload;
begin
sgGraphics.SetClip(r);
end;
procedure SetClip(bmp: Bitmap; const r: Rectangle); overload;
begin
sgGraphics.SetClip(bmp,r);
end;
procedure SetClip(wnd: Window; const r: Rectangle); overload;
begin
sgGraphics.SetClip(wnd,r);
end;
procedure SetIcon(const filename: String); overload;
begin
sgGraphics.SetIcon(filename);
end;
procedure ShowSwinGameSplashScreen(); overload;
begin
sgGraphics.ShowSwinGameSplashScreen();
end;
procedure TakeScreenshot(const basename: String); overload;
begin
sgGraphics.TakeScreenshot(basename);
end;
function TransparencyOf(c: Color): Byte; overload;
begin
result := sgGraphics.TransparencyOf(c);
end;
function BitmapCellCircle(bmp: Bitmap; const pt: Point2D): Circle; overload;
begin
result := sgImages.BitmapCellCircle(bmp,pt);
end;
function BitmapCellCircle(bmp: Bitmap; x: Single; y: Single): Circle; overload;
begin
result := sgImages.BitmapCellCircle(bmp,x,y);
end;
function BitmapCellCircle(bmp: Bitmap; const pt: Point2D; scale: Single): Circle; overload;
begin
result := sgImages.BitmapCellCircle(bmp,pt,scale);
end;
function BitmapCellColumns(bmp: Bitmap): Longint; overload;
begin
result := sgImages.BitmapCellColumns(bmp);
end;
function BitmapCellCount(bmp: Bitmap): Longint; overload;
begin
result := sgImages.BitmapCellCount(bmp);
end;
function BitmapCellHeight(bmp: Bitmap): Longint; overload;
begin
result := sgImages.BitmapCellHeight(bmp);
end;
function BitmapCellRectangle(bmp: Bitmap): Rectangle; overload;
begin
result := sgImages.BitmapCellRectangle(bmp);
end;
function BitmapCellRectangle(x: Single; y: Single; bmp: Bitmap): Rectangle; overload;
begin
result := sgImages.BitmapCellRectangle(x,y,bmp);
end;
function BitmapCellRows(bmp: Bitmap): Longint; overload;
begin
result := sgImages.BitmapCellRows(bmp);
end;
function BitmapCellWidth(bmp: Bitmap): Longint; overload;
begin
result := sgImages.BitmapCellWidth(bmp);
end;
function BitmapCircle(bmp: Bitmap; const pt: Point2D): Circle; overload;
begin
result := sgImages.BitmapCircle(bmp,pt);
end;
function BitmapCircle(bmp: Bitmap; x: Single; y: Single): Circle; overload;
begin
result := sgImages.BitmapCircle(bmp,x,y);
end;
function BitmapFilename(bmp: Bitmap): String; overload;
begin
result := sgImages.BitmapFilename(bmp);
end;
function BitmapHeight(bmp: Bitmap): Longint; overload;
begin
result := sgImages.BitmapHeight(bmp);
end;
function BitmapName(bmp: Bitmap): String; overload;
begin
result := sgImages.BitmapName(bmp);
end;
function BitmapNamed(const name: String): Bitmap; overload;
begin
result := sgImages.BitmapNamed(name);
end;
function BitmapRectangle(bmp: Bitmap): Rectangle; overload;
begin
result := sgImages.BitmapRectangle(bmp);
end;
function BitmapRectangle(x: Single; y: Single; bmp: Bitmap): Rectangle; overload;
begin
result := sgImages.BitmapRectangle(x,y,bmp);
end;
function BitmapRectangleOfCell(src: Bitmap; cell: Longint): Rectangle; overload;
begin
result := sgImages.BitmapRectangleOfCell(src,cell);
end;
procedure BitmapSetCellDetails(bmp: Bitmap; width: Longint; height: Longint; columns: Longint; rows: Longint; count: Longint); overload;
begin
sgImages.BitmapSetCellDetails(bmp,width,height,columns,rows,count);
end;
function BitmapWidth(bmp: Bitmap): Longint; overload;
begin
result := sgImages.BitmapWidth(bmp);
end;
function BitmapsInterchangable(bmp1: Bitmap; bmp2: Bitmap): Boolean; overload;
begin
result := sgImages.BitmapsInterchangable(bmp1,bmp2);
end;
procedure ClearSurface(dest: Bitmap); overload;
begin
sgImages.ClearSurface(dest);
end;
procedure ClearSurface(dest: Bitmap; toColor: Color); overload;
begin
sgImages.ClearSurface(dest,toColor);
end;
function CreateBitmap(width: Longint; height: Longint): Bitmap; overload;
begin
result := sgImages.CreateBitmap(width,height);
end;
function CreateBitmap(const name: String; width: Longint; height: Longint): Bitmap; overload;
begin
result := sgImages.CreateBitmap(name,width,height);
end;
procedure DrawBitmap(src: Bitmap; x: Single; y: Single); overload;
begin
sgImages.DrawBitmap(src,x,y);
end;
procedure DrawBitmap(const name: String; x: Single; y: Single); overload;
begin
sgImages.DrawBitmap(name,x,y);
end;
procedure DrawBitmap(src: Bitmap; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgImages.DrawBitmap(src,x,y,opts);
end;
procedure DrawBitmap(const name: String; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgImages.DrawBitmap(name,x,y,opts);
end;
procedure DrawCell(src: Bitmap; cell: Longint; x: Single; y: Single); overload;
begin
sgImages.DrawCell(src,cell,x,y);
end;
procedure DrawCell(src: Bitmap; cell: Longint; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgImages.DrawCell(src,cell,x,y,opts);
end;
procedure FreeBitmap(bitmapToFree: Bitmap); overload;
begin
sgImages.FreeBitmap(bitmapToFree);
end;
function HasBitmap(const name: String): Boolean; overload;
begin
result := sgImages.HasBitmap(name);
end;
function LoadBitmap(const filename: String): Bitmap; overload;
begin
result := sgImages.LoadBitmap(filename);
end;
function LoadBitmapNamed(const name: String; const filename: String): Bitmap; overload;
begin
result := sgImages.LoadBitmapNamed(name,filename);
end;
function PixelDrawnAtPoint(bmp: Bitmap; x: Single; y: Single): Boolean; overload;
begin
result := sgImages.PixelDrawnAtPoint(bmp,x,y);
end;
procedure ReleaseAllBitmaps(); overload;
begin
sgImages.ReleaseAllBitmaps();
end;
procedure ReleaseBitmap(const name: String); overload;
begin
sgImages.ReleaseBitmap(name);
end;
procedure SaveBitmap(src: Bitmap; const filepath: String); overload;
begin
sgImages.SaveBitmap(src,filepath);
end;
procedure SetupBitmapForCollisions(src: Bitmap); overload;
begin
sgImages.SetupBitmapForCollisions(src);
end;
function AnyKeyPressed(): Boolean; overload;
begin
result := sgInput.AnyKeyPressed();
end;
function EndReadingText(): String; overload;
begin
result := sgInput.EndReadingText();
end;
procedure HideMouse(); overload;
begin
sgInput.HideMouse();
end;
function KeyDown(key: KeyCode): Boolean; overload;
begin
result := sgInput.KeyDown(key);
end;
function KeyName(key: KeyCode): String; overload;
begin
result := sgInput.KeyName(key);
end;
function KeyReleased(key: KeyCode): Boolean; overload;
begin
result := sgInput.KeyReleased(key);
end;
function KeyTyped(key: KeyCode): Boolean; overload;
begin
result := sgInput.KeyTyped(key);
end;
function KeyUp(key: KeyCode): Boolean; overload;
begin
result := sgInput.KeyUp(key);
end;
function MouseClicked(button: MouseButton): Boolean; overload;
begin
result := sgInput.MouseClicked(button);
end;
function MouseDown(button: MouseButton): Boolean; overload;
begin
result := sgInput.MouseDown(button);
end;
function MouseMovement(): Vector; overload;
begin
result := sgInput.MouseMovement();
end;
function MousePosition(): Point2D; overload;
begin
result := sgInput.MousePosition();
end;
function MousePositionAsVector(): Vector; overload;
begin
result := sgInput.MousePositionAsVector();
end;
function MouseShown(): Boolean; overload;
begin
result := sgInput.MouseShown();
end;
function MouseUp(button: MouseButton): Boolean; overload;
begin
result := sgInput.MouseUp(button);
end;
function MouseWheelScroll(): Vector; overload;
begin
result := sgInput.MouseWheelScroll();
end;
function MouseX(): Single; overload;
begin
result := sgInput.MouseX();
end;
function MouseY(): Single; overload;
begin
result := sgInput.MouseY();
end;
procedure MoveMouse(const point: Point2D); overload;
begin
sgInput.MoveMouse(point);
end;
procedure MoveMouse(x: Longint; y: Longint); overload;
begin
sgInput.MoveMouse(x,y);
end;
procedure ProcessEvents(); overload;
begin
sgInput.ProcessEvents();
end;
function QuitRequested(): Boolean; overload;
begin
result := sgInput.QuitRequested();
end;
function ReadingText(): Boolean; overload;
begin
result := sgInput.ReadingText();
end;
procedure ShowMouse(); overload;
begin
sgInput.ShowMouse();
end;
procedure ShowMouse(show: Boolean); overload;
begin
sgInput.ShowMouse(show);
end;
procedure StartReadingText(textColor: Color; maxLength: Longint; theFont: Font; const area: Rectangle); overload;
begin
sgInput.StartReadingText(textColor,maxLength,theFont,area);
end;
procedure StartReadingText(textColor: Color; maxLength: Longint; theFont: Font; x: Longint; y: Longint); overload;
begin
sgInput.StartReadingText(textColor,maxLength,theFont,x,y);
end;
procedure StartReadingTextWithText(const text: String; textColor: Color; maxLength: Longint; theFont: Font; const pt: Point2D); overload;
begin
sgInput.StartReadingTextWithText(text,textColor,maxLength,theFont,pt);
end;
procedure StartReadingTextWithText(const text: String; textColor: Color; maxLength: Longint; theFont: Font; const area: Rectangle); overload;
begin
sgInput.StartReadingTextWithText(text,textColor,maxLength,theFont,area);
end;
procedure StartReadingTextWithText(const text: String; textColor: Color; maxLength: Longint; theFont: Font; x: Longint; y: Longint); overload;
begin
sgInput.StartReadingTextWithText(text,textColor,maxLength,theFont,x,y);
end;
procedure StartReadingTextWithText(const text: String; textColor: Color; backGroundColor: Color; maxLength: Longint; theFont: Font; const area: Rectangle); overload;
begin
sgInput.StartReadingTextWithText(text,textColor,backGroundColor,maxLength,theFont,area);
end;
function TextEntryCancelled(): Boolean; overload;
begin
result := sgInput.TextEntryCancelled();
end;
function TextReadAsASCII(): String; overload;
begin
result := sgInput.TextReadAsASCII();
end;
procedure BroadcastMessage(const aMsg: String); overload;
begin
sgNetworking.BroadcastMessage(aMsg);
end;
procedure BroadcastMessage(const aMsg: String; const name: String); overload;
begin
sgNetworking.BroadcastMessage(aMsg,name);
end;
procedure BroadcastMessage(const aMsg: String; svr: ServerSocket); overload;
begin
sgNetworking.BroadcastMessage(aMsg,svr);
end;
procedure CheckNetworkActivity(); overload;
begin
sgNetworking.CheckNetworkActivity();
end;
procedure ClearMessages(svr: ServerSocket); overload;
begin
sgNetworking.ClearMessages(svr);
end;
procedure ClearMessages(aConnection: Connection); overload;
begin
sgNetworking.ClearMessages(aConnection);
end;
procedure ClearMessages(const name: String); overload;
begin
sgNetworking.ClearMessages(name);
end;
procedure CloseAllConnections(); overload;
begin
sgNetworking.CloseAllConnections();
end;
procedure CloseAllServers(); overload;
begin
sgNetworking.CloseAllServers();
end;
procedure CloseAllUDPSockets(); overload;
begin
sgNetworking.CloseAllUDPSockets();
end;
function CloseConnection(var aConnection: Connection): Boolean; overload;
begin
result := sgNetworking.CloseConnection(aConnection);
end;
function CloseConnection(const name: String): Boolean; overload;
begin
result := sgNetworking.CloseConnection(name);
end;
procedure CloseMessage(msg: Message); overload;
begin
sgNetworking.CloseMessage(msg);
end;
function CloseServer(var svr: ServerSocket): Boolean; overload;
begin
result := sgNetworking.CloseServer(svr);
end;
function CloseServer(const name: String): Boolean; overload;
begin
result := sgNetworking.CloseServer(name);
end;
function CloseUDPSocket(aPort: Word): Boolean; overload;
begin
result := sgNetworking.CloseUDPSocket(aPort);
end;
function ConnectionCount(const name: String): Longint; overload;
begin
result := sgNetworking.ConnectionCount(name);
end;
function ConnectionCount(server: ServerSocket): Longint; overload;
begin
result := sgNetworking.ConnectionCount(server);
end;
function ConnectionIP(const name: String): Longword; overload;
begin
result := sgNetworking.ConnectionIP(name);
end;
function ConnectionIP(aConnection: Connection): Longword; overload;
begin
result := sgNetworking.ConnectionIP(aConnection);
end;
function ConnectionNamed(const name: String): Connection; overload;
begin
result := sgNetworking.ConnectionNamed(name);
end;
function ConnectionOpen(con: Connection): Boolean; overload;
begin
result := sgNetworking.ConnectionOpen(con);
end;
function ConnectionOpen(const name: String): Boolean; overload;
begin
result := sgNetworking.ConnectionOpen(name);
end;
function ConnectionPort(aConnection: Connection): Word; overload;
begin
result := sgNetworking.ConnectionPort(aConnection);
end;
function ConnectionPort(const name: String): Word; overload;
begin
result := sgNetworking.ConnectionPort(name);
end;
function CreateServer(const name: String; port: Word): ServerSocket; overload;
begin
result := sgNetworking.CreateServer(name,port);
end;
function CreateServer(const name: String; port: Word; protocol: ConnectionType): ServerSocket; overload;
begin
result := sgNetworking.CreateServer(name,port,protocol);
end;
function DecToHex(aDec: Longword): String; overload;
begin
result := sgNetworking.DecToHex(aDec);
end;
procedure FreeConnection(var aConnection: Connection); overload;
begin
sgNetworking.FreeConnection(aConnection);
end;
procedure FreeServer(var svr: ServerSocket); overload;
begin
sgNetworking.FreeServer(svr);
end;
function HasMessages(): Boolean; overload;
begin
result := sgNetworking.HasMessages();
end;
function HasMessages(con: Connection): Boolean; overload;
begin
result := sgNetworking.HasMessages(con);
end;
function HasMessages(svr: ServerSocket): Boolean; overload;
begin
result := sgNetworking.HasMessages(svr);
end;
function HasMessages(const name: String): Boolean; overload;
begin
result := sgNetworking.HasMessages(name);
end;
function HasNewConnections(): Boolean; overload;
begin
result := sgNetworking.HasNewConnections();
end;
function HexStrToIPv4(const aHex: String): String; overload;
begin
result := sgNetworking.HexStrToIPv4(aHex);
end;
function HexToDecString(const aHex: String): String; overload;
begin
result := sgNetworking.HexToDecString(aHex);
end;
function IPv4ToDec(const aIP: String): Longword; overload;
begin
result := sgNetworking.IPv4ToDec(aIP);
end;
function IPv4ToStr(ip: Longword): String; overload;
begin
result := sgNetworking.IPv4ToStr(ip);
end;
function LastConnection(server: ServerSocket): Connection; overload;
begin
result := sgNetworking.LastConnection(server);
end;
function LastConnection(const name: String): Connection; overload;
begin
result := sgNetworking.LastConnection(name);
end;
function MessageConnection(msg: Message): Connection; overload;
begin
result := sgNetworking.MessageConnection(msg);
end;
function MessageCount(aConnection: Connection): Longint; overload;
begin
result := sgNetworking.MessageCount(aConnection);
end;
function MessageCount(const name: String): Longint; overload;
begin
result := sgNetworking.MessageCount(name);
end;
function MessageCount(svr: ServerSocket): Longint; overload;
begin
result := sgNetworking.MessageCount(svr);
end;
function MessageData(msg: Message): String; overload;
begin
result := sgNetworking.MessageData(msg);
end;
function MessageHost(msg: Message): String; overload;
begin
result := sgNetworking.MessageHost(msg);
end;
function MessagePort(msg: Message): Word; overload;
begin
result := sgNetworking.MessagePort(msg);
end;
function MessageProtocol(msg: Message): ConnectionType; overload;
begin
result := sgNetworking.MessageProtocol(msg);
end;
function MyIP(): String; overload;
begin
result := sgNetworking.MyIP();
end;
function OpenConnection(const host: String; port: Word): Connection; overload;
begin
result := sgNetworking.OpenConnection(host,port);
end;
function OpenConnection(const name: String; const host: String; port: Word): Connection; overload;
begin
result := sgNetworking.OpenConnection(name,host,port);
end;
function OpenConnection(const name: String; const host: String; port: Word; protocol: ConnectionType): Connection; overload;
begin
result := sgNetworking.OpenConnection(name,host,port,protocol);
end;
function ReadMessage(aConnection: Connection): Message; overload;
begin
result := sgNetworking.ReadMessage(aConnection);
end;
function ReadMessage(const name: String): Message; overload;
begin
result := sgNetworking.ReadMessage(name);
end;
function ReadMessage(svr: ServerSocket): Message; overload;
begin
result := sgNetworking.ReadMessage(svr);
end;
function ReadMessageData(aConnection: Connection): String; overload;
begin
result := sgNetworking.ReadMessageData(aConnection);
end;
function ReadMessageData(svr: ServerSocket): String; overload;
begin
result := sgNetworking.ReadMessageData(svr);
end;
function ReadMessageData(const name: String): String; overload;
begin
result := sgNetworking.ReadMessageData(name);
end;
procedure Reconnect(const name: String); overload;
begin
sgNetworking.Reconnect(name);
end;
procedure Reconnect(aConnection: Connection); overload;
begin
sgNetworking.Reconnect(aConnection);
end;
procedure ReleaseAllConnections(); overload;
begin
sgNetworking.ReleaseAllConnections();
end;
function RetreiveConnection(const name: String; idx: Longint): Connection; overload;
begin
result := sgNetworking.RetreiveConnection(name,idx);
end;
function RetreiveConnection(server: ServerSocket; idx: Longint): Connection; overload;
begin
result := sgNetworking.RetreiveConnection(server,idx);
end;
function SendMessageTo(const aMsg: String; aConnection: Connection): Boolean; overload;
begin
result := sgNetworking.SendMessageTo(aMsg,aConnection);
end;
function SendMessageTo(const aMsg: String; const name: String): Boolean; overload;
begin
result := sgNetworking.SendMessageTo(aMsg,name);
end;
function ServerHasNewConnection(const name: String): Boolean; overload;
begin
result := sgNetworking.ServerHasNewConnection(name);
end;
function ServerHasNewConnection(server: ServerSocket): Boolean; overload;
begin
result := sgNetworking.ServerHasNewConnection(server);
end;
function ServerNamed(const name: String): ServerSocket; overload;
begin
result := sgNetworking.ServerNamed(name);
end;
procedure SetUDPPacketSize(val: Longint); overload;
begin
sgNetworking.SetUDPPacketSize(val);
end;
function UDPPacketSize(): Longint; overload;
begin
result := sgNetworking.UDPPacketSize();
end;
procedure FreeHttpResponse(var response: HttpResponse); overload;
begin
sgWeb.FreeHttpResponse(response);
end;
function HttpGet(const url: String; port: Word): HttpResponse; overload;
begin
result := sgWeb.HttpGet(url,port);
end;
function HttpPost(const url: String; port: Word; const body: String): HttpResponse; overload;
begin
result := sgWeb.HttpPost(url,port,body);
end;
function HttpResponseBodyAsString(httpData: HttpResponse): String; overload;
begin
result := sgWeb.HttpResponseBodyAsString(httpData);
end;
function BitmapCollision(bmp1: Bitmap; const pt1: Point2D; bmp2: Bitmap; const pt2: Point2D): Boolean; overload;
begin
result := sgPhysics.BitmapCollision(bmp1,pt1,bmp2,pt2);
end;
function BitmapCollision(bmp1: Bitmap; x1: Single; y1: Single; bmp2: Bitmap; x2: Single; y2: Single): Boolean; overload;
begin
result := sgPhysics.BitmapCollision(bmp1,x1,y1,bmp2,x2,y2);
end;
function BitmapCollision(bmp1: Bitmap; const pt1: Point2D; const part1: Rectangle; bmp2: Bitmap; const pt2: Point2D; const part2: Rectangle): Boolean; overload;
begin
result := sgPhysics.BitmapCollision(bmp1,pt1,part1,bmp2,pt2,part2);
end;
function BitmapPartPointCollision(bmp: Bitmap; x: Single; y: Single; const part: Rectangle; const pt: Point2D): Boolean; overload;
begin
result := sgPhysics.BitmapPartPointCollision(bmp,x,y,part,pt);
end;
function BitmapPartPointCollision(bmp: Bitmap; x: Single; y: Single; const part: Rectangle; ptX: Single; ptY: Single): Boolean; overload;
begin
result := sgPhysics.BitmapPartPointCollision(bmp,x,y,part,ptX,ptY);
end;
function BitmapPointCollision(bmp: Bitmap; x: Single; y: Single; const pt: Point2D): Boolean; overload;
begin
result := sgPhysics.BitmapPointCollision(bmp,x,y,pt);
end;
function BitmapPointCollision(bmp: Bitmap; x: Single; y: Single; ptX: Single; ptY: Single): Boolean; overload;
begin
result := sgPhysics.BitmapPointCollision(bmp,x,y,ptX,ptY);
end;
function BitmapRectCollision(bmp: Bitmap; x: Single; y: Single; const rect: Rectangle): Boolean; overload;
begin
result := sgPhysics.BitmapRectCollision(bmp,x,y,rect);
end;
function BitmapRectCollision(bmp: Bitmap; const pt: Point2D; const part: Rectangle; const rect: Rectangle): Boolean; overload;
begin
result := sgPhysics.BitmapRectCollision(bmp,pt,part,rect);
end;
function BitmapRectCollision(bmp: Bitmap; x: Single; y: Single; const part: Rectangle; const rect: Rectangle): Boolean; overload;
begin
result := sgPhysics.BitmapRectCollision(bmp,x,y,part,rect);
end;
function BitmapRectCollision(bmp: Bitmap; x: Single; y: Single; rectX: Single; rectY: Single; rectWidth: Single; rectHeight: Single): Boolean; overload;
begin
result := sgPhysics.BitmapRectCollision(bmp,x,y,rectX,rectY,rectWidth,rectHeight);
end;
function CellBitmapCollision(bmp1: Bitmap; cell: Longint; const pt1: Point2D; bmp2: Bitmap; const pt2: Point2D): Boolean; overload;
begin
result := sgPhysics.CellBitmapCollision(bmp1,cell,pt1,bmp2,pt2);
end;
function CellBitmapCollision(bmp1: Bitmap; cell: Longint; const pt1: Point2D; bmp2: Bitmap; const pt2: Point2D; const part: Rectangle): Boolean; overload;
begin
result := sgPhysics.CellBitmapCollision(bmp1,cell,pt1,bmp2,pt2,part);
end;
function CellBitmapCollision(bmp1: Bitmap; cell: Longint; x1: Single; y1: Single; bmp2: Bitmap; x2: Single; y2: Single): Boolean; overload;
begin
result := sgPhysics.CellBitmapCollision(bmp1,cell,x1,y1,bmp2,x2,y2);
end;
function CellBitmapCollision(bmp1: Bitmap; cell: Longint; x1: Single; y1: Single; bmp2: Bitmap; x2: Single; y2: Single; const part: Rectangle): Boolean; overload;
begin
result := sgPhysics.CellBitmapCollision(bmp1,cell,x1,y1,bmp2,x2,y2,part);
end;
function CellCollision(bmp1: Bitmap; cell1: Longint; const pt1: Point2D; bmp2: Bitmap; cell2: Longint; const pt2: Point2D): Boolean; overload;
begin
result := sgPhysics.CellCollision(bmp1,cell1,pt1,bmp2,cell2,pt2);
end;
function CellCollision(bmp1: Bitmap; cell1: Longint; x1: Single; y1: Single; bmp2: Bitmap; cell2: Longint; x2: Single; y2: Single): Boolean; overload;
begin
result := sgPhysics.CellCollision(bmp1,cell1,x1,y1,bmp2,cell2,x2,y2);
end;
function CellRectCollision(bmp: Bitmap; cell: Longint; const pt: Point2D; const rect: Rectangle): Boolean; overload;
begin
result := sgPhysics.CellRectCollision(bmp,cell,pt,rect);
end;
function CellRectCollision(bmp: Bitmap; cell: Longint; x: Single; y: Single; const rect: Rectangle): Boolean; overload;
begin
result := sgPhysics.CellRectCollision(bmp,cell,x,y,rect);
end;
function CircleCircleCollision(const c1: Circle; const c2: Circle): Boolean; overload;
begin
result := sgPhysics.CircleCircleCollision(c1,c2);
end;
function CircleLineCollision(s: Sprite; const line: LineSegment): Boolean; overload;
begin
result := sgPhysics.CircleLineCollision(s,line);
end;
function CircleRectCollision(const c: Circle; const rect: Rectangle): Boolean; overload;
begin
result := sgPhysics.CircleRectCollision(c,rect);
end;
function CircleTriangleCollision(const c: Circle; const tri: Triangle): Boolean; overload;
begin
result := sgPhysics.CircleTriangleCollision(c,tri);
end;
procedure CollideCircleCircle(s: Sprite; const c: Circle); overload;
begin
sgPhysics.CollideCircleCircle(s,c);
end;
procedure CollideCircleLine(s: Sprite; const line: LineSegment); overload;
begin
sgPhysics.CollideCircleLine(s,line);
end;
procedure CollideCircleRectangle(s: Sprite; const rect: Rectangle); overload;
begin
sgPhysics.CollideCircleRectangle(s,rect);
end;
procedure CollideCircleTriangle(s: Sprite; const tri: Triangle); overload;
begin
sgPhysics.CollideCircleTriangle(s,tri);
end;
procedure CollideCircles(s1: Sprite; s2: Sprite); overload;
begin
sgPhysics.CollideCircles(s1,s2);
end;
function RectLineCollision(s: Sprite; const line: LineSegment): Boolean; overload;
begin
result := sgPhysics.RectLineCollision(s,line);
end;
function RectLineCollision(const rect: Rectangle; const line: LineSegment): Boolean; overload;
begin
result := sgPhysics.RectLineCollision(rect,line);
end;
function SideForCollisionTest(const velocity: Vector): CollisionSide; overload;
begin
result := sgPhysics.SideForCollisionTest(velocity);
end;
function SpriteAtPoint(s: Sprite; const pt: Point2D): Boolean; overload;
begin
result := sgPhysics.SpriteAtPoint(s,pt);
end;
function SpriteBitmapCollision(s: Sprite; bmp: Bitmap; const pt: Point2D): Boolean; overload;
begin
result := sgPhysics.SpriteBitmapCollision(s,bmp,pt);
end;
function SpriteBitmapCollision(s: Sprite; bmp: Bitmap; x: Single; y: Single): Boolean; overload;
begin
result := sgPhysics.SpriteBitmapCollision(s,bmp,x,y);
end;
function SpriteCollision(s1: Sprite; s2: Sprite): Boolean; overload;
begin
result := sgPhysics.SpriteCollision(s1,s2);
end;
function SpriteRectCollision(s: Sprite; const r: Rectangle): Boolean; overload;
begin
result := sgPhysics.SpriteRectCollision(s,r);
end;
function SpriteRectCollision(s: Sprite; x: Single; y: Single; width: Single; height: Single): Boolean; overload;
begin
result := sgPhysics.SpriteRectCollision(s,x,y,width,height);
end;
function TriangleLineCollision(const tri: Triangle; const ln: LineSegment): Boolean; overload;
begin
result := sgPhysics.TriangleLineCollision(tri,ln);
end;
function AppPath(): String; overload;
begin
result := sgResources.AppPath();
end;
function FilenameToResource(const name: String; kind: ResourceKind): String; overload;
begin
result := sgResources.FilenameToResource(name,kind);
end;
function HasResourceBundle(const name: String): Boolean; overload;
begin
result := sgResources.HasResourceBundle(name);
end;
procedure LoadResourceBundle(const name: String); overload;
begin
sgResources.LoadResourceBundle(name);
end;
procedure LoadResourceBundle(const name: String; showProgress: Boolean); overload;
begin
sgResources.LoadResourceBundle(name,showProgress);
end;
procedure LoadResourceBundleNamed(const name: String; const filename: String; showProgress: Boolean); overload;
begin
sgResources.LoadResourceBundleNamed(name,filename,showProgress);
end;
function PathToResource(const filename: String): String; overload;
begin
result := sgResources.PathToResource(filename);
end;
function PathToResource(const filename: String; kind: ResourceKind): String; overload;
begin
result := sgResources.PathToResource(filename,kind);
end;
function PathToResource(const filename: String; const subdir: String): String; overload;
begin
result := sgResources.PathToResource(filename,subdir);
end;
function PathToResource(const filename: String; kind: ResourceKind; const subdir: String): String; overload;
begin
result := sgResources.PathToResource(filename,kind,subdir);
end;
function PathToResourceWithBase(const path: String; const filename: String): String; overload;
begin
result := sgResources.PathToResourceWithBase(path,filename);
end;
function PathToResourceWithBase(const path: String; const filename: String; kind: ResourceKind): String; overload;
begin
result := sgResources.PathToResourceWithBase(path,filename,kind);
end;
procedure RegisterFreeNotifier(fn: FreeNotifier); overload;
begin
sgResources.RegisterFreeNotifier(fn);
end;
procedure ReleaseAllResources(); overload;
begin
sgResources.ReleaseAllResources();
end;
procedure ReleaseResourceBundle(const name: String); overload;
begin
sgResources.ReleaseResourceBundle(name);
end;
procedure SetAppPath(const path: String); overload;
begin
sgResources.SetAppPath(path);
end;
procedure SetAppPath(const path: String; withExe: Boolean); overload;
begin
sgResources.SetAppPath(path,withExe);
end;
procedure CallForAllSprites(fn: SpriteFunction); overload;
begin
sgSprites.CallForAllSprites(fn);
end;
procedure CallOnSpriteEvent(handler: SpriteEventHandler); overload;
begin
sgSprites.CallOnSpriteEvent(handler);
end;
function CenterPoint(s: Sprite): Point2D; overload;
begin
result := sgSprites.CenterPoint(s);
end;
function CreateSprite(layer: Bitmap): Sprite; overload;
begin
result := sgSprites.CreateSprite(layer);
end;
function CreateSprite(const name: String; layer: Bitmap): Sprite; overload;
begin
result := sgSprites.CreateSprite(name,layer);
end;
function CreateSprite(const bitmapName: String; const animationName: String): Sprite; overload;
begin
result := sgSprites.CreateSprite(bitmapName,animationName);
end;
function CreateSprite(layer: Bitmap; ani: AnimationScript): Sprite; overload;
begin
result := sgSprites.CreateSprite(layer,ani);
end;
function CreateSprite(const name: String; layer: Bitmap; ani: AnimationScript): Sprite; overload;
begin
result := sgSprites.CreateSprite(name,layer,ani);
end;
procedure CreateSpritePack(const name: String); overload;
begin
sgSprites.CreateSpritePack(name);
end;
function CurrentSpritePack(): String; overload;
begin
result := sgSprites.CurrentSpritePack();
end;
procedure DrawAllSprites(); overload;
begin
sgSprites.DrawAllSprites();
end;
procedure DrawSprite(s: Sprite); overload;
begin
sgSprites.DrawSprite(s);
end;
procedure DrawSprite(s: Sprite; const position: Point2D); overload;
begin
sgSprites.DrawSprite(s,position);
end;
procedure DrawSprite(s: Sprite; xOffset: Longint; yOffset: Longint); overload;
begin
sgSprites.DrawSprite(s,xOffset,yOffset);
end;
procedure FreeSprite(var s: Sprite); overload;
begin
sgSprites.FreeSprite(s);
end;
function HasSprite(const name: String): Boolean; overload;
begin
result := sgSprites.HasSprite(name);
end;
function HasSpritePack(const name: String): Boolean; overload;
begin
result := sgSprites.HasSpritePack(name);
end;
procedure MoveSprite(s: Sprite); overload;
begin
sgSprites.MoveSprite(s);
end;
procedure MoveSprite(s: Sprite; const distance: Vector); overload;
begin
sgSprites.MoveSprite(s,distance);
end;
procedure MoveSprite(s: Sprite; pct: Single); overload;
begin
sgSprites.MoveSprite(s,pct);
end;
procedure MoveSprite(s: Sprite; const distance: Vector; pct: Single); overload;
begin
sgSprites.MoveSprite(s,distance,pct);
end;
procedure MoveSpriteTo(s: Sprite; x: Longint; y: Longint); overload;
begin
sgSprites.MoveSpriteTo(s,x,y);
end;
procedure ReleaseAllSprites(); overload;
begin
sgSprites.ReleaseAllSprites();
end;
procedure ReleaseSprite(const name: String); overload;
begin
sgSprites.ReleaseSprite(name);
end;
procedure SelectSpritePack(const name: String); overload;
begin
sgSprites.SelectSpritePack(name);
end;
function SpriteAddLayer(s: Sprite; newLayer: Bitmap; const layerName: String): Longint; overload;
begin
result := sgSprites.SpriteAddLayer(s,newLayer,layerName);
end;
procedure SpriteAddToVelocity(s: Sprite; const value: Vector); overload;
begin
sgSprites.SpriteAddToVelocity(s,value);
end;
procedure SpriteAddValue(s: Sprite; const name: String); overload;
begin
sgSprites.SpriteAddValue(s,name);
end;
procedure SpriteAddValue(s: Sprite; const name: String; initVal: Single); overload;
begin
sgSprites.SpriteAddValue(s,name,initVal);
end;
function SpriteAnchorPoint(s: Sprite): Point2D; overload;
begin
result := sgSprites.SpriteAnchorPoint(s);
end;
function SpriteAnimationHasEnded(s: Sprite): Boolean; overload;
begin
result := sgSprites.SpriteAnimationHasEnded(s);
end;
function SpriteAnimationName(s: Sprite): String; overload;
begin
result := sgSprites.SpriteAnimationName(s);
end;
procedure SpriteBringLayerForward(s: Sprite; visibleLayer: Longint); overload;
begin
sgSprites.SpriteBringLayerForward(s,visibleLayer);
end;
procedure SpriteBringLayerToFront(s: Sprite; visibleLayer: Longint); overload;
begin
sgSprites.SpriteBringLayerToFront(s,visibleLayer);
end;
procedure SpriteCallOnEvent(s: Sprite; handler: SpriteEventHandler); overload;
begin
sgSprites.SpriteCallOnEvent(s,handler);
end;
function SpriteCircle(s: Sprite): Circle; overload;
begin
result := sgSprites.SpriteCircle(s);
end;
function SpriteCollisionBitmap(s: Sprite): Bitmap; overload;
begin
result := sgSprites.SpriteCollisionBitmap(s);
end;
function SpriteCollisionCircle(s: Sprite): Circle; overload;
begin
result := sgSprites.SpriteCollisionCircle(s);
end;
function SpriteCollisionKind(s: Sprite): CollisionTestKind; overload;
begin
result := sgSprites.SpriteCollisionKind(s);
end;
function SpriteCollisionRectangle(s: Sprite): Rectangle; overload;
begin
result := sgSprites.SpriteCollisionRectangle(s);
end;
function SpriteCurrentCell(s: Sprite): Longint; overload;
begin
result := sgSprites.SpriteCurrentCell(s);
end;
function SpriteCurrentCellRectangle(s: Sprite): Rectangle; overload;
begin
result := sgSprites.SpriteCurrentCellRectangle(s);
end;
function SpriteDX(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteDX(s);
end;
function SpriteDY(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteDY(s);
end;
function SpriteHeading(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteHeading(s);
end;
function SpriteHeight(s: Sprite): Longint; overload;
begin
result := sgSprites.SpriteHeight(s);
end;
procedure SpriteHideLayer(s: Sprite; const name: String); overload;
begin
sgSprites.SpriteHideLayer(s,name);
end;
procedure SpriteHideLayer(s: Sprite; id: Longint); overload;
begin
sgSprites.SpriteHideLayer(s,id);
end;
function SpriteLayer(s: Sprite; const name: String): Bitmap; overload;
begin
result := sgSprites.SpriteLayer(s,name);
end;
function SpriteLayer(s: Sprite; idx: Longint): Bitmap; overload;
begin
result := sgSprites.SpriteLayer(s,idx);
end;
function SpriteLayerCircle(s: Sprite; idx: Longint): Circle; overload;
begin
result := sgSprites.SpriteLayerCircle(s,idx);
end;
function SpriteLayerCircle(s: Sprite; const name: String): Circle; overload;
begin
result := sgSprites.SpriteLayerCircle(s,name);
end;
function SpriteLayerCount(s: Sprite): Longint; overload;
begin
result := sgSprites.SpriteLayerCount(s);
end;
function SpriteLayerHeight(s: Sprite; const name: String): Longint; overload;
begin
result := sgSprites.SpriteLayerHeight(s,name);
end;
function SpriteLayerHeight(s: Sprite; idx: Longint): Longint; overload;
begin
result := sgSprites.SpriteLayerHeight(s,idx);
end;
function SpriteLayerIndex(s: Sprite; const name: String): Longint; overload;
begin
result := sgSprites.SpriteLayerIndex(s,name);
end;
function SpriteLayerName(s: Sprite; idx: Longint): String; overload;
begin
result := sgSprites.SpriteLayerName(s,idx);
end;
function SpriteLayerOffset(s: Sprite; const name: String): Point2D; overload;
begin
result := sgSprites.SpriteLayerOffset(s,name);
end;
function SpriteLayerOffset(s: Sprite; idx: Longint): Point2D; overload;
begin
result := sgSprites.SpriteLayerOffset(s,idx);
end;
function SpriteLayerRectangle(s: Sprite; idx: Longint): Rectangle; overload;
begin
result := sgSprites.SpriteLayerRectangle(s,idx);
end;
function SpriteLayerRectangle(s: Sprite; const name: String): Rectangle; overload;
begin
result := sgSprites.SpriteLayerRectangle(s,name);
end;
function SpriteLayerWidth(s: Sprite; idx: Longint): Longint; overload;
begin
result := sgSprites.SpriteLayerWidth(s,idx);
end;
function SpriteLayerWidth(s: Sprite; const name: String): Longint; overload;
begin
result := sgSprites.SpriteLayerWidth(s,name);
end;
function SpriteLocationMatrix(s: Sprite): Matrix2D; overload;
begin
result := sgSprites.SpriteLocationMatrix(s);
end;
function SpriteMass(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteMass(s);
end;
function SpriteMoveFromAnchorPoint(s: Sprite): Boolean; overload;
begin
result := sgSprites.SpriteMoveFromAnchorPoint(s);
end;
procedure SpriteMoveTo(s: Sprite; const pt: Point2D; takingSeconds: Longint); overload;
begin
sgSprites.SpriteMoveTo(s,pt,takingSeconds);
end;
function SpriteName(sprt: Sprite): String; overload;
begin
result := sgSprites.SpriteName(sprt);
end;
function SpriteNamed(const name: String): Sprite; overload;
begin
result := sgSprites.SpriteNamed(name);
end;
function SpriteOffscreen(s: Sprite): Boolean; overload;
begin
result := sgSprites.SpriteOffscreen(s);
end;
function SpriteOnScreenAt(s: Sprite; const pt: Point2D): Boolean; overload;
begin
result := sgSprites.SpriteOnScreenAt(s,pt);
end;
function SpriteOnScreenAt(s: Sprite; x: Longint; y: Longint): Boolean; overload;
begin
result := sgSprites.SpriteOnScreenAt(s,x,y);
end;
function SpritePosition(s: Sprite): Point2D; overload;
begin
result := sgSprites.SpritePosition(s);
end;
procedure SpriteReplayAnimation(s: Sprite); overload;
begin
sgSprites.SpriteReplayAnimation(s);
end;
procedure SpriteReplayAnimation(s: Sprite; withSound: Boolean); overload;
begin
sgSprites.SpriteReplayAnimation(s,withSound);
end;
function SpriteRotation(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteRotation(s);
end;
function SpriteScale(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteScale(s);
end;
function SpriteScreenRectangle(s: Sprite): Rectangle; overload;
begin
result := sgSprites.SpriteScreenRectangle(s);
end;
procedure SpriteSendLayerBackward(s: Sprite; visibleLayer: Longint); overload;
begin
sgSprites.SpriteSendLayerBackward(s,visibleLayer);
end;
procedure SpriteSendLayerToBack(s: Sprite; visibleLayer: Longint); overload;
begin
sgSprites.SpriteSendLayerToBack(s,visibleLayer);
end;
procedure SpriteSetAnchorPoint(s: Sprite; pt: Point2D); overload;
begin
sgSprites.SpriteSetAnchorPoint(s,pt);
end;
procedure SpriteSetCollisionBitmap(s: Sprite; bmp: Bitmap); overload;
begin
sgSprites.SpriteSetCollisionBitmap(s,bmp);
end;
procedure SpriteSetCollisionKind(s: Sprite; value: CollisionTestKind); overload;
begin
sgSprites.SpriteSetCollisionKind(s,value);
end;
procedure SpriteSetDX(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetDX(s,value);
end;
procedure SpriteSetDY(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetDY(s,value);
end;
procedure SpriteSetHeading(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetHeading(s,value);
end;
procedure SpriteSetLayerOffset(s: Sprite; idx: Longint; const value: Point2D); overload;
begin
sgSprites.SpriteSetLayerOffset(s,idx,value);
end;
procedure SpriteSetLayerOffset(s: Sprite; const name: String; const value: Point2D); overload;
begin
sgSprites.SpriteSetLayerOffset(s,name,value);
end;
procedure SpriteSetMass(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetMass(s,value);
end;
procedure SpriteSetMoveFromAnchorPoint(s: Sprite; value: Boolean); overload;
begin
sgSprites.SpriteSetMoveFromAnchorPoint(s,value);
end;
procedure SpriteSetPosition(s: Sprite; const value: Point2D); overload;
begin
sgSprites.SpriteSetPosition(s,value);
end;
procedure SpriteSetRotation(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetRotation(s,value);
end;
procedure SpriteSetScale(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetScale(s,value);
end;
procedure SpriteSetSpeed(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetSpeed(s,value);
end;
procedure SpriteSetValue(s: Sprite; const name: String; val: Single); overload;
begin
sgSprites.SpriteSetValue(s,name,val);
end;
procedure SpriteSetValue(s: Sprite; idx: Longint; val: Single); overload;
begin
sgSprites.SpriteSetValue(s,idx,val);
end;
procedure SpriteSetVelocity(s: Sprite; const value: Vector); overload;
begin
sgSprites.SpriteSetVelocity(s,value);
end;
procedure SpriteSetX(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetX(s,value);
end;
procedure SpriteSetY(s: Sprite; value: Single); overload;
begin
sgSprites.SpriteSetY(s,value);
end;
function SpriteShowLayer(s: Sprite; id: Longint): Longint; overload;
begin
result := sgSprites.SpriteShowLayer(s,id);
end;
function SpriteShowLayer(s: Sprite; const name: String): Longint; overload;
begin
result := sgSprites.SpriteShowLayer(s,name);
end;
function SpriteSpeed(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteSpeed(s);
end;
procedure SpriteStartAnimation(s: Sprite; idx: Longint); overload;
begin
sgSprites.SpriteStartAnimation(s,idx);
end;
procedure SpriteStartAnimation(s: Sprite; const named: String); overload;
begin
sgSprites.SpriteStartAnimation(s,named);
end;
procedure SpriteStartAnimation(s: Sprite; const named: String; withSound: Boolean); overload;
begin
sgSprites.SpriteStartAnimation(s,named,withSound);
end;
procedure SpriteStartAnimation(s: Sprite; idx: Longint; withSound: Boolean); overload;
begin
sgSprites.SpriteStartAnimation(s,idx,withSound);
end;
procedure SpriteStopCallingOnEvent(s: Sprite; handler: SpriteEventHandler); overload;
begin
sgSprites.SpriteStopCallingOnEvent(s,handler);
end;
procedure SpriteToggleLayerVisible(s: Sprite; id: Longint); overload;
begin
sgSprites.SpriteToggleLayerVisible(s,id);
end;
procedure SpriteToggleLayerVisible(s: Sprite; const name: String); overload;
begin
sgSprites.SpriteToggleLayerVisible(s,name);
end;
function SpriteValue(s: Sprite; index: Longint): Single; overload;
begin
result := sgSprites.SpriteValue(s,index);
end;
function SpriteValue(s: Sprite; const name: String): Single; overload;
begin
result := sgSprites.SpriteValue(s,name);
end;
function SpriteValueCount(s: Sprite): Longint; overload;
begin
result := sgSprites.SpriteValueCount(s);
end;
function SpriteValueName(s: Sprite; idx: Longint): String; overload;
begin
result := sgSprites.SpriteValueName(s,idx);
end;
function SpriteVelocity(s: Sprite): Vector; overload;
begin
result := sgSprites.SpriteVelocity(s);
end;
function SpriteVisibleIndexOfLayer(s: Sprite; id: Longint): Longint; overload;
begin
result := sgSprites.SpriteVisibleIndexOfLayer(s,id);
end;
function SpriteVisibleIndexOfLayer(s: Sprite; const name: String): Longint; overload;
begin
result := sgSprites.SpriteVisibleIndexOfLayer(s,name);
end;
function SpriteVisibleLayer(s: Sprite; idx: Longint): Longint; overload;
begin
result := sgSprites.SpriteVisibleLayer(s,idx);
end;
function SpriteVisibleLayerCount(s: Sprite): Longint; overload;
begin
result := sgSprites.SpriteVisibleLayerCount(s);
end;
function SpriteVisibleLayerId(s: Sprite; idx: Longint): Longint; overload;
begin
result := sgSprites.SpriteVisibleLayerId(s,idx);
end;
function SpriteWidth(s: Sprite): Longint; overload;
begin
result := sgSprites.SpriteWidth(s);
end;
function SpriteX(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteX(s);
end;
function SpriteY(s: Sprite): Single; overload;
begin
result := sgSprites.SpriteY(s);
end;
procedure StopCallingOnSpriteEvent(handler: SpriteEventHandler); overload;
begin
sgSprites.StopCallingOnSpriteEvent(handler);
end;
procedure UpdateAllSprites(); overload;
begin
sgSprites.UpdateAllSprites();
end;
procedure UpdateAllSprites(pct: Single); overload;
begin
sgSprites.UpdateAllSprites(pct);
end;
procedure UpdateSprite(s: Sprite); overload;
begin
sgSprites.UpdateSprite(s);
end;
procedure UpdateSprite(s: Sprite; withSound: Boolean); overload;
begin
sgSprites.UpdateSprite(s,withSound);
end;
procedure UpdateSprite(s: Sprite; pct: Single); overload;
begin
sgSprites.UpdateSprite(s,pct);
end;
procedure UpdateSprite(s: Sprite; pct: Single; withSound: Boolean); overload;
begin
sgSprites.UpdateSprite(s,pct,withSound);
end;
procedure UpdateSpriteAnimation(s: Sprite); overload;
begin
sgSprites.UpdateSpriteAnimation(s);
end;
procedure UpdateSpriteAnimation(s: Sprite; withSound: Boolean); overload;
begin
sgSprites.UpdateSpriteAnimation(s,withSound);
end;
procedure UpdateSpriteAnimation(s: Sprite; pct: Single); overload;
begin
sgSprites.UpdateSpriteAnimation(s,pct);
end;
procedure UpdateSpriteAnimation(s: Sprite; pct: Single; withSound: Boolean); overload;
begin
sgSprites.UpdateSpriteAnimation(s,pct,withSound);
end;
function VectorFromCenterSpriteToPoint(s: Sprite; const pt: Point2D): Vector; overload;
begin
result := sgSprites.VectorFromCenterSpriteToPoint(s,pt);
end;
function VectorFromTo(s1: Sprite; s2: Sprite): Vector; overload;
begin
result := sgSprites.VectorFromTo(s1,s2);
end;
procedure DrawFramerate(x: Single; y: Single); overload;
begin
sgText.DrawFramerate(x,y);
end;
procedure DrawText(const theText: String; textColor: Color; x: Single; y: Single); overload;
begin
sgText.DrawText(theText,textColor,x,y);
end;
procedure DrawText(const theText: String; textColor: Color; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgText.DrawText(theText,textColor,x,y,opts);
end;
procedure DrawText(const theText: String; textColor: Color; const name: String; x: Single; y: Single); overload;
begin
sgText.DrawText(theText,textColor,name,x,y);
end;
procedure DrawText(const theText: String; textColor: Color; theFont: Font; x: Single; y: Single); overload;
begin
sgText.DrawText(theText,textColor,theFont,x,y);
end;
procedure DrawText(const theText: String; textColor: Color; backColor: Color; theFont: Font; align: FontAlignment; const area: Rectangle); overload;
begin
sgText.DrawText(theText,textColor,backColor,theFont,align,area);
end;
procedure DrawText(const theText: String; textColor: Color; const name: String; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgText.DrawText(theText,textColor,name,x,y,opts);
end;
procedure DrawText(const theText: String; textColor: Color; backColor: Color; const name: String; align: FontAlignment; const area: Rectangle); overload;
begin
sgText.DrawText(theText,textColor,backColor,name,align,area);
end;
procedure DrawText(const theText: String; textColor: Color; theFont: Font; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgText.DrawText(theText,textColor,theFont,x,y,opts);
end;
procedure DrawText(const theText: String; textColor: Color; const name: String; size: Longint; x: Single; y: Single); overload;
begin
sgText.DrawText(theText,textColor,name,size,x,y);
end;
procedure DrawText(const theText: String; textColor: Color; backColor: Color; theFont: Font; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload;
begin
sgText.DrawText(theText,textColor,backColor,theFont,align,area,opts);
end;
procedure DrawText(const theText: String; textColor: Color; const name: String; size: Longint; x: Single; y: Single; const opts: DrawingOptions); overload;
begin
sgText.DrawText(theText,textColor,name,size,x,y,opts);
end;
procedure DrawText(const theText: String; textColor: Color; backColor: Color; const name: String; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload;
begin
sgText.DrawText(theText,textColor,backColor,name,align,area,opts);
end;
procedure DrawText(const theText: String; textColor: Color; backColor: Color; const name: String; size: Longint; align: FontAlignment; const area: Rectangle); overload;
begin
sgText.DrawText(theText,textColor,backColor,name,size,align,area);
end;
procedure DrawText(const theText: String; textColor: Color; backColor: Color; const name: String; size: Longint; align: FontAlignment; const area: Rectangle; const opts: DrawingOptions); overload;
begin
sgText.DrawText(theText,textColor,backColor,name,size,align,area,opts);
end;
function DrawTextToBitmap(font: Font; const str: String; clrFg: Color; backgroundColor: Color): Bitmap; overload;
begin
result := sgText.DrawTextToBitmap(font,str,clrFg,backgroundColor);
end;
function FontFontStyle(font: Font): FontStyle; overload;
begin
result := sgText.FontFontStyle(font);
end;
function FontNameFor(const fontName: String; size: Longint): String; overload;
begin
result := sgText.FontNameFor(fontName,size);
end;
function FontNamed(const name: String): Font; overload;
begin
result := sgText.FontNamed(name);
end;
function FontNamed(const name: String; size: Longint): Font; overload;
begin
result := sgText.FontNamed(name,size);
end;
procedure FontSetStyle(font: Font; value: FontStyle); overload;
begin
sgText.FontSetStyle(font,value);
end;
procedure FreeFont(var fontToFree: Font); overload;
begin
sgText.FreeFont(fontToFree);
end;
function HasFont(const name: String): Boolean; overload;
begin
result := sgText.HasFont(name);
end;
function LoadFont(const fontName: String; size: Longint): Font; overload;
begin
result := sgText.LoadFont(fontName,size);
end;
function LoadFontNamed(const name: String; const filename: String; size: Longint): Font; overload;
begin
result := sgText.LoadFontNamed(name,filename,size);
end;
procedure ReleaseAllFonts(); overload;
begin
sgText.ReleaseAllFonts();
end;
procedure ReleaseFont(const name: String); overload;
begin
sgText.ReleaseFont(name);
end;
function TextAlignmentFrom(const str: String): FontAlignment; overload;
begin
result := sgText.TextAlignmentFrom(str);
end;
function TextHeight(theFont: Font; const theText: String): Longint; overload;
begin
result := sgText.TextHeight(theFont,theText);
end;
function TextWidth(theFont: Font; const theText: String): Longint; overload;
begin
result := sgText.TextWidth(theFont,theText);
end;
function CreateTimer(): Timer; overload;
begin
result := sgTimers.CreateTimer();
end;
function CreateTimer(const name: String): Timer; overload;
begin
result := sgTimers.CreateTimer(name);
end;
procedure FreeTimer(var toFree: Timer); overload;
begin
sgTimers.FreeTimer(toFree);
end;
procedure PauseTimer(const name: String); overload;
begin
sgTimers.PauseTimer(name);
end;
procedure PauseTimer(toPause: Timer); overload;
begin
sgTimers.PauseTimer(toPause);
end;
procedure ReleaseAllTimers(); overload;
begin
sgTimers.ReleaseAllTimers();
end;
procedure ReleaseTimer(const name: String); overload;
begin
sgTimers.ReleaseTimer(name);
end;
procedure ResetTimer(const name: String); overload;
begin
sgTimers.ResetTimer(name);
end;
procedure ResetTimer(tmr: Timer); overload;
begin
sgTimers.ResetTimer(tmr);
end;
procedure ResumeTimer(const name: String); overload;
begin
sgTimers.ResumeTimer(name);
end;
procedure ResumeTimer(toUnpause: Timer); overload;
begin
sgTimers.ResumeTimer(toUnpause);
end;
procedure StartTimer(toStart: Timer); overload;
begin
sgTimers.StartTimer(toStart);
end;
procedure StartTimer(const name: String); overload;
begin
sgTimers.StartTimer(name);
end;
procedure StopTimer(toStop: Timer); overload;
begin
sgTimers.StopTimer(toStop);
end;
procedure StopTimer(const name: String); overload;
begin
sgTimers.StopTimer(name);
end;
function TimerNamed(const name: String): Timer; overload;
begin
result := sgTimers.TimerNamed(name);
end;
function TimerTicks(const name: String): Longword; overload;
begin
result := sgTimers.TimerTicks(name);
end;
function TimerTicks(toGet: Timer): Longword; overload;
begin
result := sgTimers.TimerTicks(toGet);
end;
procedure CalculateFramerate(out average: String; out highest: String; out lowest: String; out textColor: Color); overload;
begin
sgUtils.CalculateFramerate(average,highest,lowest,textColor);
end;
procedure Delay(time: Longword); overload;
begin
sgUtils.Delay(time);
end;
function ExceptionMessage(): String; overload;
begin
result := sgUtils.ExceptionMessage();
end;
function ExceptionOccured(): Boolean; overload;
begin
result := sgUtils.ExceptionOccured();
end;
function GetFramerate(): Longint; overload;
begin
result := sgUtils.GetFramerate();
end;
function GetTicks(): Longword; overload;
begin
result := sgUtils.GetTicks();
end;
function Rnd(): Single; overload;
begin
result := sgUtils.Rnd();
end;
function Rnd(ubound: Longint): Longint; overload;
begin
result := sgUtils.Rnd(ubound);
end;
function SwinGameVersion(): String; overload;
begin
result := sgUtils.SwinGameVersion();
end;
procedure ActivatePanel(p: Panel); overload;
begin
sgUserInterface.ActivatePanel(p);
end;
function ActiveRadioButton(const id: String): Region; overload;
begin
result := sgUserInterface.ActiveRadioButton(id);
end;
function ActiveRadioButton(pnl: Panel; const id: String): Region; overload;
begin
result := sgUserInterface.ActiveRadioButton(pnl,id);
end;
function ActiveRadioButtonIndex(const id: String): Longint; overload;
begin
result := sgUserInterface.ActiveRadioButtonIndex(id);
end;
function ActiveRadioButtonIndex(pnl: Panel; const id: String): Longint; overload;
begin
result := sgUserInterface.ActiveRadioButtonIndex(pnl,id);
end;
function ActiveTextBoxParent(): Panel; overload;
begin
result := sgUserInterface.ActiveTextBoxParent();
end;
function ActiveTextIndex(): Longint; overload;
begin
result := sgUserInterface.ActiveTextIndex();
end;
function ButtonClicked(const name: String): Boolean; overload;
begin
result := sgUserInterface.ButtonClicked(name);
end;
function ButtonClicked(r: Region): Boolean; overload;
begin
result := sgUserInterface.ButtonClicked(r);
end;
procedure CheckboxSetState(const id: String; val: Boolean); overload;
begin
sgUserInterface.CheckboxSetState(id,val);
end;
procedure CheckboxSetState(r: Region; val: Boolean); overload;
begin
sgUserInterface.CheckboxSetState(r,val);
end;
procedure CheckboxSetState(pnl: Panel; const id: String; val: Boolean); overload;
begin
sgUserInterface.CheckboxSetState(pnl,id,val);
end;
function CheckboxState(r: Region): Boolean; overload;
begin
result := sgUserInterface.CheckboxState(r);
end;
function CheckboxState(const s: String): Boolean; overload;
begin
result := sgUserInterface.CheckboxState(s);
end;
function CheckboxState(p: Panel; const s: String): Boolean; overload;
begin
result := sgUserInterface.CheckboxState(p,s);
end;
procedure DeactivatePanel(p: Panel); overload;
begin
sgUserInterface.DeactivatePanel(p);
end;
procedure DeactivateTextBox(); overload;
begin
sgUserInterface.DeactivateTextBox();
end;
function DialogCancelled(): Boolean; overload;
begin
result := sgUserInterface.DialogCancelled();
end;
function DialogComplete(): Boolean; overload;
begin
result := sgUserInterface.DialogComplete();
end;
function DialogPath(): String; overload;
begin
result := sgUserInterface.DialogPath();
end;
procedure DialogSetPath(const fullname: String); overload;
begin
sgUserInterface.DialogSetPath(fullname);
end;
procedure DrawGUIAsVectors(b: Boolean); overload;
begin
sgUserInterface.DrawGUIAsVectors(b);
end;
procedure DrawInterface(); overload;
begin
sgUserInterface.DrawInterface();
end;
procedure FinishReadingText(); overload;
begin
sgUserInterface.FinishReadingText();
end;
procedure FreePanel(var pnl: Panel); overload;
begin
sgUserInterface.FreePanel(pnl);
end;
function GUIClicked(): Boolean; overload;
begin
result := sgUserInterface.GUIClicked();
end;
procedure GUISetActiveTextbox(const name: String); overload;
begin
sgUserInterface.GUISetActiveTextbox(name);
end;
procedure GUISetActiveTextbox(r: Region); overload;
begin
sgUserInterface.GUISetActiveTextbox(r);
end;
procedure GUISetBackgroundColor(c: Color); overload;
begin
sgUserInterface.GUISetBackgroundColor(c);
end;
procedure GUISetBackgroundColorInactive(c: Color); overload;
begin
sgUserInterface.GUISetBackgroundColorInactive(c);
end;
procedure GUISetForegroundColor(c: Color); overload;
begin
sgUserInterface.GUISetForegroundColor(c);
end;
procedure GUISetForegroundColorInactive(c: Color); overload;
begin
sgUserInterface.GUISetForegroundColorInactive(c);
end;
function GUITextEntryComplete(): Boolean; overload;
begin
result := sgUserInterface.GUITextEntryComplete();
end;
function HasPanel(const name: String): Boolean; overload;
begin
result := sgUserInterface.HasPanel(name);
end;
procedure HidePanel(p: Panel); overload;
begin
sgUserInterface.HidePanel(p);
end;
procedure HidePanel(const name: String); overload;
begin
sgUserInterface.HidePanel(name);
end;
function IndexOfLastUpdatedTextBox(): Longint; overload;
begin
result := sgUserInterface.IndexOfLastUpdatedTextBox();
end;
function IsDragging(): Boolean; overload;
begin
result := sgUserInterface.IsDragging();
end;
function IsDragging(pnl: Panel): Boolean; overload;
begin
result := sgUserInterface.IsDragging(pnl);
end;
procedure LabelSetText(r: Region; const newString: String); overload;
begin
sgUserInterface.LabelSetText(r,newString);
end;
procedure LabelSetText(const id: String; const newString: String); overload;
begin
sgUserInterface.LabelSetText(id,newString);
end;
procedure LabelSetText(pnl: Panel; const id: String; const newString: String); overload;
begin
sgUserInterface.LabelSetText(pnl,id,newString);
end;
function LabelText(r: Region): String; overload;
begin
result := sgUserInterface.LabelText(r);
end;
function LabelText(const id: String): String; overload;
begin
result := sgUserInterface.LabelText(id);
end;
function LabelText(pnl: Panel; const id: String): String; overload;
begin
result := sgUserInterface.LabelText(pnl,id);
end;
function ListActiveItemIndex(const id: String): Longint; overload;
begin
result := sgUserInterface.ListActiveItemIndex(id);
end;
function ListActiveItemIndex(r: Region): Longint; overload;
begin
result := sgUserInterface.ListActiveItemIndex(r);
end;
function ListActiveItemIndex(pnl: Panel; const id: String): Longint; overload;
begin
result := sgUserInterface.ListActiveItemIndex(pnl,id);
end;
function ListActiveItemText(r: Region): String; overload;
begin
result := sgUserInterface.ListActiveItemText(r);
end;
function ListActiveItemText(const ID: String): String; overload;
begin
result := sgUserInterface.ListActiveItemText(ID);
end;
function ListActiveItemText(pnl: Panel; const ID: String): String; overload;
begin
result := sgUserInterface.ListActiveItemText(pnl,ID);
end;
procedure ListAddItem(const id: String; const text: String); overload;
begin
sgUserInterface.ListAddItem(id,text);
end;
procedure ListAddItem(const id: String; img: Bitmap); overload;
begin
sgUserInterface.ListAddItem(id,img);
end;
procedure ListAddItem(r: Region; img: Bitmap); overload;
begin
sgUserInterface.ListAddItem(r,img);
end;
procedure ListAddItem(r: Region; const text: String); overload;
begin
sgUserInterface.ListAddItem(r,text);
end;
procedure ListAddItem(const id: String; img: Bitmap; const text: String); overload;
begin
sgUserInterface.ListAddItem(id,img,text);
end;
procedure ListAddItem(pnl: Panel; const id: String; const text: String); overload;
begin
sgUserInterface.ListAddItem(pnl,id,text);
end;
procedure ListAddItem(r: Region; img: Bitmap; cell: Longint); overload;
begin
sgUserInterface.ListAddItem(r,img,cell);
end;
procedure ListAddItem(r: Region; img: Bitmap; const text: String); overload;
begin
sgUserInterface.ListAddItem(r,img,text);
end;
procedure ListAddItem(pnl: Panel; const id: String; img: Bitmap); overload;
begin
sgUserInterface.ListAddItem(pnl,id,img);
end;
procedure ListAddItem(const id: String; img: Bitmap; cell: Longint); overload;
begin
sgUserInterface.ListAddItem(id,img,cell);
end;
procedure ListAddItem(const id: String; img: Bitmap; cell: Longint; const text: String); overload;
begin
sgUserInterface.ListAddItem(id,img,cell,text);
end;
procedure ListAddItem(r: Region; img: Bitmap; cell: Longint; const text: String); overload;
begin
sgUserInterface.ListAddItem(r,img,cell,text);
end;
procedure ListAddItem(pnl: Panel; const id: String; img: Bitmap; cell: Longint); overload;
begin
sgUserInterface.ListAddItem(pnl,id,img,cell);
end;
procedure ListAddItem(pnl: Panel; const id: String; img: Bitmap; const text: String); overload;
begin
sgUserInterface.ListAddItem(pnl,id,img,text);
end;
procedure ListAddItem(pnl: Panel; const id: String; img: Bitmap; cell: Longint; const text: String); overload;
begin
sgUserInterface.ListAddItem(pnl,id,img,cell,text);
end;
procedure ListClearItems(const id: String); overload;
begin
sgUserInterface.ListClearItems(id);
end;
procedure ListClearItems(r: Region); overload;
begin
sgUserInterface.ListClearItems(r);
end;
procedure ListClearItems(pnl: Panel; const id: String); overload;
begin
sgUserInterface.ListClearItems(pnl,id);
end;
function ListItemCount(const id: String): Longint; overload;
begin
result := sgUserInterface.ListItemCount(id);
end;
function ListItemCount(r: Region): Longint; overload;
begin
result := sgUserInterface.ListItemCount(r);
end;
function ListItemCount(pnl: Panel; const id: String): Longint; overload;
begin
result := sgUserInterface.ListItemCount(pnl,id);
end;
function ListItemText(r: Region; idx: Longint): String; overload;
begin
result := sgUserInterface.ListItemText(r,idx);
end;
function ListItemText(const id: String; idx: Longint): String; overload;
begin
result := sgUserInterface.ListItemText(id,idx);
end;
function ListItemText(pnl: Panel; const id: String; idx: Longint): String; overload;
begin
result := sgUserInterface.ListItemText(pnl,id,idx);
end;
procedure ListRemoveActiveItem(const id: String); overload;
begin
sgUserInterface.ListRemoveActiveItem(id);
end;
procedure ListRemoveActiveItem(r: Region); overload;
begin
sgUserInterface.ListRemoveActiveItem(r);
end;
procedure ListRemoveActiveItem(pnl: Panel; const id: String); overload;
begin
sgUserInterface.ListRemoveActiveItem(pnl,id);
end;
procedure ListRemoveItem(const id: String; idx: Longint); overload;
begin
sgUserInterface.ListRemoveItem(id,idx);
end;
procedure ListRemoveItem(pnl: Panel; const id: String; idx: Longint); overload;
begin
sgUserInterface.ListRemoveItem(pnl,id,idx);
end;
procedure ListSetActiveItemIndex(const id: String; idx: Longint); overload;
begin
sgUserInterface.ListSetActiveItemIndex(id,idx);
end;
procedure ListSetActiveItemIndex(pnl: Panel; const id: String; idx: Longint); overload;
begin
sgUserInterface.ListSetActiveItemIndex(pnl,id,idx);
end;
procedure ListSetStartAt(r: Region; idx: Longint); overload;
begin
sgUserInterface.ListSetStartAt(r,idx);
end;
function ListStartAt(r: Region): Longint; overload;
begin
result := sgUserInterface.ListStartAt(r);
end;
function LoadPanel(const filename: String): Panel; overload;
begin
result := sgUserInterface.LoadPanel(filename);
end;
function LoadPanelNamed(const name: String; const filename: String): Panel; overload;
begin
result := sgUserInterface.LoadPanelNamed(name,filename);
end;
procedure MovePanel(p: Panel; const mvmt: Vector); overload;
begin
sgUserInterface.MovePanel(p,mvmt);
end;
function NewPanel(const pnlName: String): Panel; overload;
begin
result := sgUserInterface.NewPanel(pnlName);
end;
function PanelActive(pnl: Panel): Boolean; overload;
begin
result := sgUserInterface.PanelActive(pnl);
end;
function PanelAtPoint(const pt: Point2D): Panel; overload;
begin
result := sgUserInterface.PanelAtPoint(pt);
end;
function PanelClicked(): Panel; overload;
begin
result := sgUserInterface.PanelClicked();
end;
function PanelClicked(pnl: Panel): Boolean; overload;
begin
result := sgUserInterface.PanelClicked(pnl);
end;
function PanelDraggable(p: Panel): Boolean; overload;
begin
result := sgUserInterface.PanelDraggable(p);
end;
function PanelFilename(pnl: Panel): String; overload;
begin
result := sgUserInterface.PanelFilename(pnl);
end;
function PanelHeight(p: Panel): Longint; overload;
begin
result := sgUserInterface.PanelHeight(p);
end;
function PanelHeight(const name: String): Longint; overload;
begin
result := sgUserInterface.PanelHeight(name);
end;
function PanelName(pnl: Panel): String; overload;
begin
result := sgUserInterface.PanelName(pnl);
end;
function PanelNamed(const name: String): Panel; overload;
begin
result := sgUserInterface.PanelNamed(name);
end;
procedure PanelSetDraggable(p: Panel; b: Boolean); overload;
begin
sgUserInterface.PanelSetDraggable(p,b);
end;
function PanelVisible(p: Panel): Boolean; overload;
begin
result := sgUserInterface.PanelVisible(p);
end;
function PanelWidth(p: Panel): Longint; overload;
begin
result := sgUserInterface.PanelWidth(p);
end;
function PanelWidth(const name: String): Longint; overload;
begin
result := sgUserInterface.PanelWidth(name);
end;
function PanelX(p: Panel): Single; overload;
begin
result := sgUserInterface.PanelX(p);
end;
function PanelY(p: Panel): Single; overload;
begin
result := sgUserInterface.PanelY(p);
end;
function PointInRegion(const pt: Point2D; p: Panel): Boolean; overload;
begin
result := sgUserInterface.PointInRegion(pt,p);
end;
function PointInRegion(const pt: Point2D; p: Panel; kind: GUIElementKind): Boolean; overload;
begin
result := sgUserInterface.PointInRegion(pt,p,kind);
end;
function RegionActive(forRegion: Region): Boolean; overload;
begin
result := sgUserInterface.RegionActive(forRegion);
end;
function RegionAtPoint(p: Panel; const pt: Point2D): Region; overload;
begin
result := sgUserInterface.RegionAtPoint(p,pt);
end;
function RegionClicked(): Region; overload;
begin
result := sgUserInterface.RegionClicked();
end;
function RegionClickedID(): String; overload;
begin
result := sgUserInterface.RegionClickedID();
end;
function RegionFont(r: Region): Font; overload;
begin
result := sgUserInterface.RegionFont(r);
end;
function RegionFontAlignment(r: Region): FontAlignment; overload;
begin
result := sgUserInterface.RegionFontAlignment(r);
end;
function RegionHeight(r: Region): Longint; overload;
begin
result := sgUserInterface.RegionHeight(r);
end;
function RegionID(r: Region): String; overload;
begin
result := sgUserInterface.RegionID(r);
end;
function RegionOfLastUpdatedTextBox(): Region; overload;
begin
result := sgUserInterface.RegionOfLastUpdatedTextBox();
end;
function RegionPanel(r: Region): Panel; overload;
begin
result := sgUserInterface.RegionPanel(r);
end;
procedure RegionSetFont(r: Region; f: Font); overload;
begin
sgUserInterface.RegionSetFont(r,f);
end;
procedure RegionSetFontAlignment(r: Region; align: FontAlignment); overload;
begin
sgUserInterface.RegionSetFontAlignment(r,align);
end;
function RegionWidth(r: Region): Longint; overload;
begin
result := sgUserInterface.RegionWidth(r);
end;
function RegionWithID(const ID: String): Region; overload;
begin
result := sgUserInterface.RegionWithID(ID);
end;
function RegionWithID(pnl: Panel; const ID: String): Region; overload;
begin
result := sgUserInterface.RegionWithID(pnl,ID);
end;
function RegionX(r: Region): Single; overload;
begin
result := sgUserInterface.RegionX(r);
end;
function RegionY(r: Region): Single; overload;
begin
result := sgUserInterface.RegionY(r);
end;
procedure RegisterEventCallback(r: Region; callback: GUIEventCallback); overload;
begin
sgUserInterface.RegisterEventCallback(r,callback);
end;
procedure ReleaseAllPanels(); overload;
begin
sgUserInterface.ReleaseAllPanels();
end;
procedure ReleasePanel(const name: String); overload;
begin
sgUserInterface.ReleasePanel(name);
end;
procedure SelectRadioButton(r: Region); overload;
begin
sgUserInterface.SelectRadioButton(r);
end;
procedure SelectRadioButton(const id: String); overload;
begin
sgUserInterface.SelectRadioButton(id);
end;
procedure SelectRadioButton(pnl: Panel; const id: String); overload;
begin
sgUserInterface.SelectRadioButton(pnl,id);
end;
procedure SetRegionActive(forRegion: Region; b: Boolean); overload;
begin
sgUserInterface.SetRegionActive(forRegion,b);
end;
procedure ShowOpenDialog(); overload;
begin
sgUserInterface.ShowOpenDialog();
end;
procedure ShowOpenDialog(select: FileDialogSelectType); overload;
begin
sgUserInterface.ShowOpenDialog(select);
end;
procedure ShowPanel(const name: String); overload;
begin
sgUserInterface.ShowPanel(name);
end;
procedure ShowPanel(p: Panel); overload;
begin
sgUserInterface.ShowPanel(p);
end;
procedure ShowPanelDialog(p: Panel); overload;
begin
sgUserInterface.ShowPanelDialog(p);
end;
procedure ShowSaveDialog(); overload;
begin
sgUserInterface.ShowSaveDialog();
end;
procedure ShowSaveDialog(select: FileDialogSelectType); overload;
begin
sgUserInterface.ShowSaveDialog(select);
end;
function TextBoxText(r: Region): String; overload;
begin
result := sgUserInterface.TextBoxText(r);
end;
function TextBoxText(const id: String): String; overload;
begin
result := sgUserInterface.TextBoxText(id);
end;
function TextBoxText(pnl: Panel; const id: String): String; overload;
begin
result := sgUserInterface.TextBoxText(pnl,id);
end;
procedure TextboxSetText(const id: String; const s: String); overload;
begin
sgUserInterface.TextboxSetText(id,s);
end;
procedure TextboxSetText(r: Region; single: Single); overload;
begin
sgUserInterface.TextboxSetText(r,single);
end;
procedure TextboxSetText(r: Region; const s: String); overload;
begin
sgUserInterface.TextboxSetText(r,s);
end;
procedure TextboxSetText(const id: String; single: Single); overload;
begin
sgUserInterface.TextboxSetText(id,single);
end;
procedure TextboxSetText(r: Region; i: Longint); overload;
begin
sgUserInterface.TextboxSetText(r,i);
end;
procedure TextboxSetText(const id: String; i: Longint); overload;
begin
sgUserInterface.TextboxSetText(id,i);
end;
procedure TextboxSetText(pnl: Panel; const id: String; i: Longint); overload;
begin
sgUserInterface.TextboxSetText(pnl,id,i);
end;
procedure TextboxSetText(pnl: Panel; const id: String; single: Single); overload;
begin
sgUserInterface.TextboxSetText(pnl,id,single);
end;
procedure TextboxSetText(pnl: Panel; const id: String; const s: String); overload;
begin
sgUserInterface.TextboxSetText(pnl,id,s);
end;
procedure ToggleActivatePanel(p: Panel); overload;
begin
sgUserInterface.ToggleActivatePanel(p);
end;
procedure ToggleCheckboxState(const id: String); overload;
begin
sgUserInterface.ToggleCheckboxState(id);
end;
procedure ToggleCheckboxState(pnl: Panel; const id: String); overload;
begin
sgUserInterface.ToggleCheckboxState(pnl,id);
end;
procedure ToggleRegionActive(forRegion: Region); overload;
begin
sgUserInterface.ToggleRegionActive(forRegion);
end;
procedure ToggleShowPanel(p: Panel); overload;
begin
sgUserInterface.ToggleShowPanel(p);
end;
procedure UpdateInterface(); overload;
begin
sgUserInterface.UpdateInterface();
end;
function ArduinoDeviceNamed(const name: String): ArduinoDevice; overload;
begin
result := sgArduino.ArduinoDeviceNamed(name);
end;
function ArduinoHasData(dev: ArduinoDevice): Boolean; overload;
begin
result := sgArduino.ArduinoHasData(dev);
end;
function ArduinoReadByte(dev: ArduinoDevice): Byte; overload;
begin
result := sgArduino.ArduinoReadByte(dev);
end;
function ArduinoReadByte(dev: ArduinoDevice; timeout: Longint): Byte; overload;
begin
result := sgArduino.ArduinoReadByte(dev,timeout);
end;
function ArduinoReadLine(dev: ArduinoDevice): String; overload;
begin
result := sgArduino.ArduinoReadLine(dev);
end;
function ArduinoReadLine(dev: ArduinoDevice; timeout: Longint): String; overload;
begin
result := sgArduino.ArduinoReadLine(dev,timeout);
end;
procedure ArduinoSendByte(dev: ArduinoDevice; value: Byte); overload;
begin
sgArduino.ArduinoSendByte(dev,value);
end;
procedure ArduinoSendString(dev: ArduinoDevice; const value: String); overload;
begin
sgArduino.ArduinoSendString(dev,value);
end;
procedure ArduinoSendStringLine(dev: ArduinoDevice; const value: String); overload;
begin
sgArduino.ArduinoSendStringLine(dev,value);
end;
function CreateArduinoDevice(const port: String; baud: Longint): ArduinoDevice; overload;
begin
result := sgArduino.CreateArduinoDevice(port,baud);
end;
function CreateArduinoDevice(const name: String; const port: String; baud: Longint): ArduinoDevice; overload;
begin
result := sgArduino.CreateArduinoDevice(name,port,baud);
end;
procedure FreeArduinoDevice(var dev: ArduinoDevice); overload;
begin
sgArduino.FreeArduinoDevice(dev);
end;
function HasArduinoDevice(const name: String): Boolean; overload;
begin
result := sgArduino.HasArduinoDevice(name);
end;
procedure ReleaseAllArduinoDevices(); overload;
begin
sgArduino.ReleaseAllArduinoDevices();
end;
procedure ReleaseArduinoDevice(const name: String); overload;
begin
sgArduino.ReleaseArduinoDevice(name);
end;
function OptionDefaults(): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionDefaults();
end;
function OptionDrawTo(dest: Window): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionDrawTo(dest);
end;
function OptionDrawTo(dest: Bitmap): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionDrawTo(dest);
end;
function OptionDrawTo(dest: Bitmap; const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionDrawTo(dest,opts);
end;
function OptionDrawTo(dest: Window; const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionDrawTo(dest,opts);
end;
function OptionFlipX(): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionFlipX();
end;
function OptionFlipX(const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionFlipX(opts);
end;
function OptionFlipXY(): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionFlipXY();
end;
function OptionFlipXY(const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionFlipXY(opts);
end;
function OptionFlipY(): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionFlipY();
end;
function OptionFlipY(const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionFlipY(opts);
end;
function OptionLineWidth(width: Longint): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionLineWidth(width);
end;
function OptionLineWidth(width: Longint; const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionLineWidth(width,opts);
end;
function OptionPartBmp(const part: Rectangle): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionPartBmp(part);
end;
function OptionPartBmp(const part: Rectangle; const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionPartBmp(part,opts);
end;
function OptionPartBmp(x: Single; y: Single; w: Single; h: Single): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionPartBmp(x,y,w,h);
end;
function OptionPartBmp(x: Single; y: Single; w: Single; h: Single; const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionPartBmp(x,y,w,h,opts);
end;
function OptionRotateBmp(angle: Single): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionRotateBmp(angle);
end;
function OptionRotateBmp(angle: Single; const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionRotateBmp(angle,opts);
end;
function OptionRotateBmp(angle: Single; anchorX: Single; anchorY: Single): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionRotateBmp(angle,anchorX,anchorY);
end;
function OptionRotateBmp(angle: Single; anchorX: Single; anchorY: Single; const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionRotateBmp(angle,anchorX,anchorY,opts);
end;
function OptionScaleBmp(scaleX: Single; scaleY: Single): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionScaleBmp(scaleX,scaleY);
end;
function OptionScaleBmp(scaleX: Single; scaleY: Single; const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionScaleBmp(scaleX,scaleY,opts);
end;
function OptionToScreen(): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionToScreen();
end;
function OptionToScreen(const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionToScreen(opts);
end;
function OptionToWorld(): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionToWorld();
end;
function OptionToWorld(const opts: DrawingOptions): DrawingOptions; overload;
begin
result := sgDrawingOptions.OptionToWorld(opts);
end;
procedure ChangeScreenSize(width: Longint; height: Longint); overload;
begin
sgWindowManager.ChangeScreenSize(width,height);
end;
procedure ChangeWindowSize(const name: String; width: Longint; height: Longint); overload;
begin
sgWindowManager.ChangeWindowSize(name,width,height);
end;
procedure ChangeWindowSize(wind: Window; width: Longint; height: Longint); overload;
begin
sgWindowManager.ChangeWindowSize(wind,width,height);
end;
procedure CloseWindow(wind: Window); overload;
begin
sgWindowManager.CloseWindow(wind);
end;
procedure CloseWindow(const name: String); overload;
begin
sgWindowManager.CloseWindow(name);
end;
function HasWindow(const name: String): Boolean; overload;
begin
result := sgWindowManager.HasWindow(name);
end;
procedure MoveWindow(wind: Window; x: Longint; y: Longint); overload;
begin
sgWindowManager.MoveWindow(wind,x,y);
end;
procedure MoveWindow(const name: String; x: Longint; y: Longint); overload;
begin
sgWindowManager.MoveWindow(name,x,y);
end;
function OpenWindow(const caption: String; width: Longint; height: Longint): Window; overload;
begin
result := sgWindowManager.OpenWindow(caption,width,height);
end;
procedure SaveScreenshot(src: Window; const filepath: String); overload;
begin
sgWindowManager.SaveScreenshot(src,filepath);
end;
function ScreenHeight(): Longint; overload;
begin
result := sgWindowManager.ScreenHeight();
end;
function ScreenWidth(): Longint; overload;
begin
result := sgWindowManager.ScreenWidth();
end;
procedure SetCurrentWindow(const name: String); overload;
begin
sgWindowManager.SetCurrentWindow(name);
end;
procedure SetCurrentWindow(wnd: Window); overload;
begin
sgWindowManager.SetCurrentWindow(wnd);
end;
procedure ToggleFullScreen(); overload;
begin
sgWindowManager.ToggleFullScreen();
end;
procedure ToggleWindowBorder(); overload;
begin
sgWindowManager.ToggleWindowBorder();
end;
function WindowAtIndex(idx: Longint): Window; overload;
begin
result := sgWindowManager.WindowAtIndex(idx);
end;
function WindowCloseRequested(): Boolean; overload;
begin
result := sgWindowManager.WindowCloseRequested();
end;
function WindowCloseRequested(wind: Window): Boolean; overload;
begin
result := sgWindowManager.WindowCloseRequested(wind);
end;
function WindowCount(): Longint; overload;
begin
result := sgWindowManager.WindowCount();
end;
function WindowHeight(wind: Window): Longint; overload;
begin
result := sgWindowManager.WindowHeight(wind);
end;
function WindowHeight(const name: String): Longint; overload;
begin
result := sgWindowManager.WindowHeight(name);
end;
function WindowNamed(const name: String): Window; overload;
begin
result := sgWindowManager.WindowNamed(name);
end;
function WindowPosition(wind: Window): Point2D; overload;
begin
result := sgWindowManager.WindowPosition(wind);
end;
function WindowPosition(const name: String): Point2D; overload;
begin
result := sgWindowManager.WindowPosition(name);
end;
function WindowWidth(wind: Window): Longint; overload;
begin
result := sgWindowManager.WindowWidth(wind);
end;
function WindowWidth(const name: String): Longint; overload;
begin
result := sgWindowManager.WindowWidth(name);
end;
function WindowWithFocus(): Window; overload;
begin
result := sgWindowManager.WindowWithFocus();
end;
function WindowX(wind: Window): Longint; overload;
begin
result := sgWindowManager.WindowX(wind);
end;
function WindowX(const name: String): Longint; overload;
begin
result := sgWindowManager.WindowX(name);
end;
function WindowY(const name: String): Longint; overload;
begin
result := sgWindowManager.WindowY(name);
end;
function WindowY(wind: Window): Longint; overload;
begin
result := sgWindowManager.WindowY(wind);
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFv8Accessor;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes, uCEFv8Types;
type
TCefV8AccessorOwn = class(TCefBaseRefCountedOwn, ICefV8Accessor)
protected
function Get(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; var exception: ustring): Boolean; virtual;
function Put(const name: ustring; const obj, value: ICefv8Value; var exception: ustring): Boolean; virtual;
public
constructor Create; virtual;
end;
TCefFastV8Accessor = class(TCefV8AccessorOwn)
protected
FGetter: TCefV8AccessorGetterProc;
FSetter: TCefV8AccessorSetterProc;
function Get(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; var exception: ustring): Boolean; override;
function Put(const name: ustring; const obj, value: ICefv8Value; var exception: ustring): Boolean; override;
public
constructor Create(const getter: TCefV8AccessorGetterProc; const setter: TCefV8AccessorSetterProc); reintroduce;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFv8Value;
function cef_v8_accessor_get(self: PCefV8Accessor; const name: PCefString; obj: PCefv8Value; out retval: PCefv8Value; exception: PCefString): Integer; stdcall;
var
ret : ICefv8Value;
TempExcept : ustring;
begin
TempExcept := CefString(exception);
Result := Ord(TCefV8AccessorOwn(CefGetObject(self)).Get(CefString(name), TCefv8ValueRef.UnWrap(obj), ret, TempExcept));
retval := CefGetData(ret);
exception^ := CefString(TempExcept);
end;
function cef_v8_accessor_put(self: PCefV8Accessor; const name: PCefString; obj: PCefv8Value; value: PCefv8Value; exception: PCefString): Integer; stdcall;
var
TempExcept : ustring;
begin
TempExcept := CefString(exception);
Result := Ord(TCefV8AccessorOwn(CefGetObject(self)).Put(CefString(name), TCefv8ValueRef.UnWrap(obj), TCefv8ValueRef.UnWrap(value), TempExcept));
exception^ := CefString(TempExcept);
end;
// TCefV8AccessorOwn
constructor TCefV8AccessorOwn.Create;
begin
inherited CreateData(SizeOf(TCefV8Accessor));
PCefV8Accessor(FData)^.get := cef_v8_accessor_get;
PCefV8Accessor(FData)^.put := cef_v8_accessor_put;
end;
function TCefV8AccessorOwn.Get(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; var exception: ustring): Boolean;
begin
Result := False;
end;
function TCefV8AccessorOwn.Put(const name: ustring; const obj, value: ICefv8Value; var exception: ustring): Boolean;
begin
Result := False;
end;
// TCefFastV8Accessor
constructor TCefFastV8Accessor.Create(const getter: TCefV8AccessorGetterProc; const setter: TCefV8AccessorSetterProc);
begin
FGetter := getter;
FSetter := setter;
end;
function TCefFastV8Accessor.Get(const name: ustring; const obj: ICefv8Value; out retval: ICefv8Value; var exception: ustring): Boolean;
begin
if Assigned(FGetter) then
Result := FGetter(name, obj, retval, exception)
else
Result := False;
end;
function TCefFastV8Accessor.Put(const name: ustring; const obj, value: ICefv8Value; var exception: ustring): Boolean;
begin
if Assigned(FSetter) then
Result := FSetter(name, obj, value, exception)
else
Result := False;
end;
end.
|
unit MyCat.BackEnd.Generics.HeartBeatConnection;
interface
uses
System.SysUtils, MyCat.BackEnd.Interfaces;
// 结构的容器的声明模版
{$I DGLCfg.inc_h}
type
THeartBeatConnection = record
private
FTimeOutTimestamp: Int64;
FConnection: IBackEndConnection;
public
constructor Create(const Connection: IBackEndConnection);
property TimeOutTimestamp: Int64 read FTimeOutTimestamp;
property Connection: IBackEndConnection read FConnection;
end;
_KeyType = Int64;
_ValueType = THeartBeatConnection;
const
_NULL_Value: _ValueType = (FTimeOutTimestamp: (0); FConnection: (nil));
{$DEFINE _DGL_NotHashFunction}
{$DEFINE _DGL_Compare} // 是否需要比较函数,可选
function _IsEqual(const A, B: _ValueType): boolean;
{$IFDEF _DGL_Inline} inline;
{$ENDIF} // result:=(a=b);
function _IsLess(const A, B: _ValueType): boolean;
{$IFDEF _DGL_Inline} inline;
{$ENDIF} // result:=(a<b); 默认排序准则
{$I Map.inc_h} // "类"模版的声明文件
{$I HashMap.inc_h} // "类"模版的声明文件
type
IHeartBeatConnectionIterator = _IIterator;
IHeartBeatConnectionContainer = _IContainer;
IHeartBeatConnectionSerialContainer = _ISerialContainer;
IHeartBeatConnectionVector = _IVector;
IHeartBeatConnectionList = _IList;
IHeartBeatConnectionDeque = _IDeque;
IHeartBeatConnectionStack = _IStack;
IHeartBeatConnectionQueue = _IQueue;
IHeartBeatConnectionPriorityQueue = _IPriorityQueue;
IHeartBeatConnectionSet = _ISet;
IHeartBeatConnectionMultiSet = _IMultiSet;
IHeartBeatConnectionMapIterator = _IMapIterator;
IHeartBeatConnectionMap = _IMap;
IHeartBeatConnectionMultiMap = _IMultiMap;
THeartBeatConnectionHashMap = _THashMap;
THeartBeatConnectionHashMultiMap = _THashMultiMap;
implementation
uses
MyCat.Util;
{$I Map.inc_pas} // "类"模版的实现文件
{$I HashMap.inc_pas} // "类"模版的实现文件
function _IsEqual(const A, B: _ValueType): boolean;
begin
Result := (A.FTimeOutTimestamp = B.FTimeOutTimestamp) and
(A.FConnection = B.FConnection);
end;
function _IsLess(const A, B: _ValueType): boolean;
begin
Result := A.FTimeOutTimestamp < B.FTimeOutTimestamp;
end;
{ THeartBeatConnection }
constructor THeartBeatConnection.Create(const Connection: IBackEndConnection);
begin
FTimeOutTimestamp := TTimeUtil.CurrentTimeMillis + 20 * 1000;
FConnection := Connection;
end;
end.
|
unit uImageListUtils;
interface
uses
Winapi.Windows,
Winapi.CommCtrl,
Vcl.Graphics,
Vcl.Controls,
Vcl.ImgList;
type
// Descendant of regular TImageList
TSIImageList = class(TImageList)
protected
procedure DoDraw(Index: Integer; Canvas: TCanvas; X, Y: Integer;
Style: Cardinal; Enabled: Boolean = True); override;
end;
procedure CreateSpecialImageList(ASource, ADest: TCustomImageList;
ABrightness, AContrast, AGrayscale, AAlpha: Single);
implementation
procedure CreateSpecialImageList(ASource, ADest: TCustomImageList;
ABrightness, AContrast, AGrayscale, AAlpha: Single);
type
PBGRA = ^TBGRA;
TBGRA = packed record
B, G, R, A: Byte;
end;
TByteLUT = array [Byte] of Byte;
function ByteRound(const Value: Single): Byte; inline;
begin
if Value < 0 then
Result := 0
else if Value > 255 then
Result := 255
else
Result := Round(Value);
end;
procedure GetLinearLUT(var LUT: TByteLUT; X1, Y1, X2, Y2: Integer);
var
X, DX, DY: Integer;
begin
DX := X2 - X1;
DY := Y2 - Y1;
for X := 0 to 255 do
LUT[X] := ByteRound((X - X1) * DY / DX + Y1);
end;
function GetBrightnessContrastLUT(var LUT: TByteLUT; const Brightness, Contrast: Single): Boolean;
var
B, C: Integer;
X1, Y1, X2, Y2: Integer;
begin
X1 := 0;
Y1 := 0;
X2 := 255;
Y2 := 255;
B := Round(Brightness * 255);
C := Round(Contrast * 127);
if C >= 0 then
begin
Inc(X1, C);
Dec(X2, C);
Dec(X1, B);
Dec(X2, B);
end
else
begin
Dec(Y1, C);
Inc(Y2, C);
Inc(Y1, B);
Inc(Y2, B);
end;
GetLinearLUT(LUT, X1, Y1, X2, Y2);
Result := (B <> 0) or (C <> 0);
end;
var
LImageInfo: TImageInfo;
LDibInfo: TDibSection;
I, L: Integer;
P: PBGRA;
R, G, B, A: Byte;
LUT: TByteLUT;
LHasLUT: Boolean;
begin
if (ASource = nil) or (ASource.ColorDepth <> cd32bit) then
Exit;
ADest.ColorDepth := cd32bit;
ADest.Assign(ASource);
ADest.Masked := False;
FillChar(LImageInfo, SizeOf(LImageInfo), 0);
ImageList_GetImageInfo(ADest.Handle, 0, LImageInfo);
FillChar(LDibInfo, SizeOf(LDibInfo), 0);
GetObject(LImageInfo.hbmImage, SizeOf(LDibInfo), @LDibInfo);
P := LDibInfo.dsBm.bmBits;
LHasLUT := GetBrightnessContrastLUT(LUT, ABrightness, AContrast);
for I := 0 to LDibInfo.dsBm.bmHeight * LDibInfo.dsBm.bmWidth - 1 do
begin
A := P.A;
R := MulDiv(P.R, $FF, A);
G := MulDiv(P.G, $FF, A);
B := MulDiv(P.B, $FF, A);
if LHasLUT then
begin
R := LUT[R];
G := LUT[G];
B := LUT[B];
end;
if AGrayscale > 0 then
begin
L := (R * 61 + G * 174 + B * 21) shr 8;
if AGrayscale >= 1 then
begin
R := L;
G := L;
B := L;
end
else
begin
R := ByteRound(R + (L - R) * AGrayscale);
G := ByteRound(G + (L - G) * AGrayscale);
B := ByteRound(B + (L - B) * AGrayscale);
end;
end;
if AAlpha <> 1 then
begin
A := ByteRound(A * AAlpha);
P.A := A;
end;
P.R := MulDiv(R, A, $FF);
P.G := MulDiv(G, A, $FF);
P.B := MulDiv(B, A, $FF);
Inc(P);
end;
end;
procedure TSIImageList.DoDraw(Index: Integer; Canvas: TCanvas; X, Y: Integer;
Style: Cardinal; Enabled: Boolean);
var
Options: TImageListDrawParams;
function GetRGBColor(Value: TColor): Cardinal;
begin
Result := ColorToRGB(Value);
case Result of
clNone: Result := CLR_NONE;
clDefault: Result := CLR_DEFAULT;
end;
end;
begin
if Enabled or (ColorDepth <> cd32Bit) then
inherited
else if HandleAllocated then
begin
FillChar(Options, SizeOf(Options), 0);
Options.cbSize := SizeOf(Options);
Options.himl := Self.Handle;
Options.i := Index;
Options.hdcDst := Canvas.Handle;
Options.x := X;
Options.y := Y;
Options.cx := 0;
Options.cy := 0;
Options.xBitmap := 0;
Options.yBitmap := 0;
Options.rgbBk := GetRGBColor(BkColor);
Options.rgbFg := GetRGBColor(BlendColor);
Options.fStyle := Style;
Options.fState := ILS_SATURATE; // Grayscale for 32bit images
ImageList_DrawIndirect(@Options);
end;
end;
end.
|
{..............................................................................}
{ Summary Demo the use of Integrated Library Manager and Model Type Manager }
{ interfaces to extract data associated with each interface }
{ }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Function BooleanToString (Value : LongBool) : String;
Begin
Result := 'True';
If Value = True Then Result := 'True'
Else Result := 'False';
End;
{..............................................................................}
{..............................................................................}
Procedure ReportIntegratedLibraryManager;
Var
I,J,K : Integer;
IntMan : IIntegratedLibraryManager;
FileName : TDynamicString;
ReportDocument : IServerDocument;
doc : IDocument;
Part : IPart;
Imp : IComponentImplementation;
Param : IParameter;
CompLoc : WideString;
DataLoc : WideString;
TopLevelLoc : WideString;
MyDummy : WideString;
a : WideString;
WS : IWorkspace;
Prj : IProject;
IntLibReport : TStringList;
FilePath : WideString;
Begin
WS := GetWorkspace;
If WS = Nil Then Exit;
Prj := WS.DM_FocusedProject;
If Prj = Nil Then Exit;
// Compile the project to fetch the connectivity
// information for the design.
Prj.DM_Compile;
// Get current schematic document.
Doc := WS.DM_FocusedDocument;
If Doc.DM_DocumentKind <> 'SCH' Then
Begin
ShowWarning('This is not a schematic document');
Exit;
End;
If Doc.DM_PartCount = 0 Then
Begin
ShowWarning('This schematic document has no schematic components(Parts)' + #13 +
'Thus a Integrated Library report will not be generated');
Exit;
End;
IntMan := IntegratedLibraryManager;
If IntMan = Nil Then Exit;
IntLibReport := TStringList.Create;
//Using the integrated library manager ...
IntLibReport.Add('Integrated Library Interface information:');
IntLibReport.Add('=========================================');
IntLibReport.Add('');
For i := 0 to Doc.DM_PartCount -1 do
Begin
Part := Doc.DM_Parts(i);
MyDummy := Part.DM_LogicalDesignator;
// CompLoc will be a full path to the sch library. This could be an internal vfs path if the component
// is in an integrated library. The Dummy variable will be the int lib in that case. Dummy will be the top level library
// if you like.
CompLoc := IntMan.GetComponentLocation(Part.DM_SourceLibraryName, Part.DM_LibraryReference, TopLevelLoc);
IntLibReport.Add(' Designator: ' + Part.DM_LogicalDesignator);
IntLibReport.Add(' Lib Reference: ' + Part.DM_LibraryReference);
IntLibReport.Add(' Component Location: ' + CompLoc);
IntLibReport.Add(' Top Level Location: ' + TopLevelLoc);
For j := 0 to Part.DM_ImplementationCount - 1 do
Begin
// Implementations for the part
Imp := Part.DM_Implementations(j);
If Imp <> Nil Then
Begin
a := Imp.DM_ModelName;
IntLibReport.Add(' ' + 'Model Name : ' + a);
IntLibReport.Add(' ' + 'Description: ' + Imp.DM_Description);
IntLibReport.Add(' ' + 'Type : ' + Imp.DM_ModelType);
IntLibReport.Add('');
// parameter count
If Imp.DM_ParameterCount > 0 Then
Begin
For k := 0 to Imp.DM_ParameterCount - 1 do
Begin
Param := Imp.DM_Parameters(k);
IntLibReport.Add(' ' + 'Parameter Name: ' + Param.DM_Name);
IntLibReport.Add(' ' + 'Parameter Object Kind: ' + Param.DM_ObjectKindString);
IntLibReport.Add(' ' + 'Parameter Value: ' + Param.DM_Value);
IntLibReport.Add('');
End;
End
Else
IntLibReport.Add('No parameters for this implementation');
// datafile count
For k := 0 to Imp.DM_DatafileCount - 1 do
Begin
If Imp.DM_IntegratedModel Then
DataLoc := IntegratedLibraryManager.GetComponentDatafileLocation(k,
Imp.DM_ModelName,
Imp.DM_ModelType,
Part.DM_LibraryReference,
CompLoc,
TopLevelLoc)
Else
DataLoc := IntegratedLibraryManager.FindDatafileInStandardLibs(Imp.DM_DatafileEntity(k),
Imp.DM_DatafileKind(k),
Imp.DM_DatafileLocation(k),
True,
TopLevelLoc);
IntLibReport.Add(' Data File Location: ' + DataLoc);
IntLibReport.Add(' Top Level Location: ' + TopLevelLoc);
End;
End;
IntLibReport.Add(' +++++++++++++++++++++++++++++++++++');
End;
IntLibReport.Add(' ******************************************');
End;
IntLibReport.Add('');
FilePath := ExtractFilePath(Doc.DM_FullPath);
FileName := FilePath + '\IntLibrary_Report.Txt';
IntLibReport.SaveToFile(FileName);
Prj.DM_AddSourceDocument(FileName);
ReportDocument := Client.OpenDocument('Text', FileName);
If ReportDocument <> Nil Then
Client.ShowDocument(ReportDocument);
End;
{..............................................................................}
{..............................................................................}
Procedure ReportModelTypeManager;
Var
I,J : Integer;
ReportDocument : IServerDocument;
ModelTypeMan : IModelTypeManager;
ModelType : IModelType;
ModelDatafileType : IModelDatafileType;
WS : IWorkspace;
Prj : IProject;
Doc : IDocument;
ModelTypeReport : TStringList;
FilePath : WideString;
FileName : WideString;
Begin
WS := GetWorkspace;
If WS = Nil Then Exit;
Prj := WS.DM_FocusedProject;
If Prj = Nil Then Exit;
// Compile the project to fetch the connectivity
// information for the design.
Prj.DM_Compile;
// Get current schematic document.
Doc := WS.DM_FocusedDocument;
If Doc = Nil Then Exit;
//Gets the acccess to the interfaces of the ModelTypeManager in DXP.
ModelTypeMan := ModelTypeManager;
If ModelTypeMan = Nil Then Exit;
ModelTypeReport := TStringList.Create;
ModelTypeReport.Add('Model Types information: ');
ModelTypeReport.Add('======================');
ModelTypeReport.Add('');
For i := 0 To ModelTypeMan.ModelTypeCount -1 do
Begin
ModelType := ModelTypeMan.ModelTypes[i];
ModelTypeReport.Add(' Model Type Name: ' + ModelType.Name);
ModelTypeReport.Add(' Model Type Description: ' + ModelType.Description);
ModelTypeReport.Add(' Port Descriptor: ' + ModelType.PortDescriptor);
ModelTypeReport.Add('');
End;
ModelTypeReport.Add('');
ModelTypeReport.Add('Model Datafile Types: ');
ModelTypeReport.Add('=====================');
For j := 0 To ModelTypeMan.ModelDatafileTypeCount - 1 do
Begin
ModelDatafileType := ModelTypeMan.ModelDatafileTypes[j];
ModelTypeReport.Add(' Model Datafile Kind: ' + ModelDatafileType.FileKind);
ModelTypeReport.Add(' Model Datafile Ext Filter: ' + ModelDatafileType.ExtensionFilter);
ModelTypeReport.Add(' Model Datafile Description: ' + ModelDatafileType.Description);
ModelTypeReport.Add(' Model Datafile Entity Type: ' + ModelDatafileType.EntityType);
ModelTypeReport.Add('');
End;
FilePath := ExtractFilePath(Doc.DM_FullPath);
FileName := FilePath + '\ModelType_Report.Txt';;
ModelTypeReport.SaveToFile(FileName);
Prj.DM_AddSourceDocument(FileName);
ReportDocument := Client.OpenDocument('Text', FileName);
If ReportDocument <> Nil Then
Client.ShowDocument(ReportDocument);
End;
{..............................................................................}
{..............................................................................}
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Compiler.Interfaces;
interface
uses
System.Classes,
Spring.Collections,
VSoft.CancellationToken,
DPM.Core.Types;
{$SCOPEDENUMS ON}
type
TCompilerVerbosity = (Quiet, Minimal, Normal, Detailed, Diagnostic);
ICompiler = interface
['{4A56BA53-6ACD-4A5D-8D55-B921D6CDC8A0}']
function GetCompilerVersion : TCompilerVersion;
function GetPlatform : TDPMPlatform;
function GetConfiguration : string;
procedure SetConfiguration(const value : string);
function GetSearchPaths : IList<string>;
procedure SetSearchPaths(const value : IList<string> );
function GetBPLOutput : string;
procedure SetBPLOutput(const value : string);
function GetLibOutput : string;
procedure SetLibOutput(const value : string);
function GetVerbosity : TCompilerVerbosity;
procedure SetVerbosity(const value : TCompilerVerbosity);
function GetCompilerOutput : TStrings;
function BuildProject(const cancellationToken : ICancellationToken; const projectFile : string; const configName : string; const packageVersion : TPackageVersion; const forDesign : boolean = false) : boolean;
property CompilerVersion : TCompilerVersion read GetCompilerVersion;
property Configuration : string read GetConfiguration write SetConfiguration;
property Platform : TDPMPlatform read GetPlatform;
property Verbosity : TCompilerVerbosity read GetVerbosity write SetVerbosity;
property BPLOutputDir : string read GetBPLOutput write SetBPLOutput;
property LibOutputDir : string read GetLibOutput write SetLibOutput;
property CompilerOutput : TStrings read GetCompilerOutput;
end;
//inject
ICompilerEnvironmentProvider = interface
['{54814318-551F-4F53-B0FB-66AC0E430DB7}']
function GetRsVarsFilePath(const compilerVersion : TCompilerVersion) : string;
end;
//inject
ICompilerFactory = interface
['{3405435B-5D3A-409A-AFB7-FEFA0EA07060}']
function CreateCompiler(const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : ICompiler;
end;
implementation
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 171332
////////////////////////////////////////////////////////////////////////////////
unit android.media.ImageReader;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.view.Surface,
android.media.Image,
Androidapi.JNI.os;
type
JImageReader_OnImageAvailableListener = interface; // merged
JImageReader = interface;
JImageReaderClass = interface(JObjectClass)
['{441FB785-703C-4281-8161-3166C506FBB9}']
function acquireLatestImage : JImage; cdecl; // ()Landroid/media/Image; A: $1
function acquireNextImage : JImage; cdecl; // ()Landroid/media/Image; A: $1
function getHeight : Integer; cdecl; // ()I A: $1
function getImageFormat : Integer; cdecl; // ()I A: $1
function getMaxImages : Integer; cdecl; // ()I A: $1
function getSurface : JSurface; cdecl; // ()Landroid/view/Surface; A: $1
function getWidth : Integer; cdecl; // ()I A: $1
function newInstance(width : Integer; height : Integer; format : Integer; maxImages : Integer) : JImageReader; cdecl;// (IIII)Landroid/media/ImageReader; A: $9
procedure close ; cdecl; // ()V A: $1
procedure setOnImageAvailableListener(listener : JImageReader_OnImageAvailableListener; handler : JHandler) ; cdecl;// (Landroid/media/ImageReader$OnImageAvailableListener;Landroid/os/Handler;)V A: $1
end;
[JavaSignature('android/media/ImageReader$OnImageAvailableListener')]
JImageReader = interface(JObject)
['{35FEC17E-F0B6-4B07-8518-2426E1CCD9C5}']
function acquireLatestImage : JImage; cdecl; // ()Landroid/media/Image; A: $1
function acquireNextImage : JImage; cdecl; // ()Landroid/media/Image; A: $1
function getHeight : Integer; cdecl; // ()I A: $1
function getImageFormat : Integer; cdecl; // ()I A: $1
function getMaxImages : Integer; cdecl; // ()I A: $1
function getSurface : JSurface; cdecl; // ()Landroid/view/Surface; A: $1
function getWidth : Integer; cdecl; // ()I A: $1
procedure close ; cdecl; // ()V A: $1
procedure setOnImageAvailableListener(listener : JImageReader_OnImageAvailableListener; handler : JHandler) ; cdecl;// (Landroid/media/ImageReader$OnImageAvailableListener;Landroid/os/Handler;)V A: $1
end;
TJImageReader = class(TJavaGenericImport<JImageReaderClass, JImageReader>)
end;
// Merged from: .\android.media.ImageReader_OnImageAvailableListener.pas
JImageReader_OnImageAvailableListenerClass = interface(JObjectClass)
['{361EF202-7862-42AF-915C-C890DDBFD442}']
procedure onImageAvailable(JImageReaderparam0 : JImageReader) ; cdecl; // (Landroid/media/ImageReader;)V A: $401
end;
[JavaSignature('android/media/ImageReader_OnImageAvailableListener')]
JImageReader_OnImageAvailableListener = interface(JObject)
['{C972F320-A54B-49AF-8E59-773DA1B21A2C}']
procedure onImageAvailable(JImageReaderparam0 : JImageReader) ; cdecl; // (Landroid/media/ImageReader;)V A: $401
end;
TJImageReader_OnImageAvailableListener = class(TJavaGenericImport<JImageReader_OnImageAvailableListenerClass, JImageReader_OnImageAvailableListener>)
end;
implementation
end.
|
unit uParentListRefreshThread;
interface
uses
Classes, uParentList;
type
TParentListRefreshThread = class(TThread)
private
{ Private declarations }
MyParentList: TParentList;
protected
procedure Execute; override;
procedure MakeRefresh;
public
procedure Start(ParentList: TParentList);
end;
implementation
{ Important: Methods and properties of objects in VCL can only be used in a
method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure ParentListRefresh.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ ParentListRefresh }
procedure TParentListRefreshThread.Start(ParentList: TParentList);
begin
MyParentList := ParentList;
Execute;
end;
procedure TParentListRefreshThread.Execute;
begin
Synchronize(MakeRefresh);
end;
procedure TParentListRefreshThread.MakeRefresh;
begin
MyParentList.SubListRefresh;
end;
end.
|
unit Nullpobug.Example.Spring4d.RemoteMathService;
interface
implementation
uses
Nullpobug.Example.Spring4d.ServiceLocator
, Nullpobug.Example.Spring4d.MathServiceIntf
, Nullpobug.Example.Spring4d.MathResource
;
type
TRemoteMathServiceImpl = class(TInterfacedObject, IMathService)
private
FMathResource: IMathResource;
public
constructor Create;
function Add(A, B: integer): Integer;
function Multiply(A, B: integer): Integer;
function Name: String;
end;
{ TRemoteMathServiceImpl }
constructor TRemoteMathServiceImpl.Create;
begin
FMathResource := GetIMathResource;
end;
function TRemoteMathServiceImpl.Add(A, B: Integer): Integer;
begin
Result := FMathResource.Add(A, B);
end;
function TRemoteMathServiceImpl.Multiply(A, B: Integer): Integer;
begin
Result := FMathResource.Multiply(A, B);
end;
function TRemoteMathServiceImpl.Name: String;
begin
Result := ToString;
end;
procedure RegisterRemoteMathService;
begin
ServiceLocator.RegisterComponent<TRemoteMathServiceImpl>.Implements<IMathService>;
ServiceLocator.Build;
end;
initialization
RegisterRemoteMathService;
end.
|
unit u_Main;
interface
uses
Winapi.OpenGL,
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
Vcl.Controls,
Vcl.Forms,
Vcl.Graphics,
GLTexture,
GLTextureFormat,
GLScene,
GLMaterial,
GLCoordinates,
GLCrossPlatform,
GLWin32Viewer,
GLBaseClasses,
GLObjects,
GLAsyncTimer,
GLFileTGA;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDblClick(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
public
scn: TGLScene;
dc_clock: TGLDummyCube;
plane:array[0..3] of TGLPlane;
mvp: TGLMemoryViewer;
cam: TGLCamera;
matlib: TGLMaterialLibrary;
timer: TGLAsyncTimer;
procedure doRender();
procedure vpMouseMove(Sender:TObject; Shift:TShiftState; X,Y:Integer);
procedure onTimer(Sender: TObject);
end;
const
mat_name: array[0..3] of string = ('Fon','Hour','Min','Sec');
mat_tex: array[0..3] of string = ('Fon.tga','Hour.tga','Min.tga','Sec.tga');
plane_sz: array[0..3] of array[0..1] of single =
((1,1), (0.3,0.6), (0.35,0.7), (0.4,0.8));
var
Form1: TForm1;
mdx,mdy: Integer;
dw: integer = 256;
dh: integer = 256;
bf: TBlendFunction = (BlendOp: AC_SRC_OVER; BlendFlags: 0;
SourceConstantAlpha: 255; AlphaFormat: AC_SRC_ALPHA);
implementation
{$R *.dfm}
//
// FormCreate
//
procedure TForm1.FormCreate;
var
i: integer;
begin
clientWidth := dw;
clientHeight := dh;
scn := TGLScene.Create(self);
dc_clock := TGLDummyCube.CreateAsChild(scn.Objects);
cam := TGLCamera.CreateAsChild(scn.Objects);
cam.TargetObject := dc_clock;
cam.Position.Z := 2;
cam.NearPlaneBias := 0.1;
mvp := TGLMemoryViewer.Create(self);
mvp.Buffer.BackgroundColor := 0;
mvp.Buffer.BackgroundAlpha := 0;
mvp.Width := dw;
mvp.Height := dh;
mvp.Camera := cam;
OnMouseMove := vpMouseMove;
matlib := TGLMaterialLibrary.Create(self);
for i := 0 to high(plane) do begin
with matlib.AddTextureMaterial(mat_name[i], mat_tex[i]).Material do begin
BlendingMode := bmTransparency;
FaceCulling := fcNoCull;
MaterialOptions := [moNoLighting];
Texture.FilteringQuality := tfAnisotropic;
end;
plane[i] := TGLPlane.CreateAsChild(dc_clock);
with plane[i] do begin
Material.MaterialLibrary := matlib;
Material.LibMaterialName := mat_name[i];
Width := plane_sz[i][0];
Height := plane_sz[i][1];
Position.Z := i * 0.01;
end;
end;
timer := TGLAsyncTimer.Create(self);
timer.Interval := 100;
timer.Enabled := true;
timer.OnTimer := onTimer;
timer.OnTimer(timer);
SetWindowLong(Handle, GWL_EXSTYLE,
GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYERED);
end;
//
// vpMouseMove
//
procedure TForm1.vpMouseMove;
begin
if Shift = [ssLeft] then
cam.MoveAroundTarget(mdy-y, mdx-x);
mdx := x;
mdy := y;
doRender();
end;
//
// onMove
//
procedure TForm1.FormMouseDown;
begin
if Shift = [ssRight,ssLeft] then
begin
ReleaseCapture;
SendMessage(Handle, WM_SYSCOMMAND, 61458, 0);
end;
end;
//
// onTimer
//
procedure TForm1.onTimer;
var
Present: TDateTime;
Hour,Min,Sec,MSec: Word;
begin
Present := Now;
DecodeTime(Present, Hour, Min, Sec, MSec);
plane[3].RollAngle := -6 * sec;
plane[2].RollAngle := -(6 * Min) - (sec / 20);
plane[1].RollAngle := -(30 * (Hour mod 12)) - (Min / 2);
doRender();
end;
//
// doRender
//
procedure TForm1.doRender;
procedure UpdWnd(bmp: TBitmap);
var
p1,p2: TPoint;
sz: TSize;
begin
p1 := Point(Left, Top);
p2 := Point(0, 0);
sz.cx := bmp.width;
sz.cy := bmp.height;
UpdateLayeredWindow(Handle, GetDC(0), @p1, @sz,
bmp.Canvas.Handle, @p2, 0, @bf, ULW_ALPHA);
bmp.Free;
end;
begin
mvp.Render;
updwnd(mvp.Buffer.CreateSnapShotBitmap);
end;
//
// DblClick
//
procedure TForm1.FormDblClick;
begin
close;
end;
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 104105
////////////////////////////////////////////////////////////////////////////////
unit android.provider.ContactsContract_DeletedContactsColumns;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JContactsContract_DeletedContactsColumns = interface;
JContactsContract_DeletedContactsColumnsClass = interface(JObjectClass)
['{2F89CFD8-7D7A-4297-9C8A-35A86FA37A66}']
function _GetCONTACT_DELETED_TIMESTAMP : JString; cdecl; // A: $19
function _GetCONTACT_ID : JString; cdecl; // A: $19
property CONTACT_DELETED_TIMESTAMP : JString read _GetCONTACT_DELETED_TIMESTAMP;// Ljava/lang/String; A: $19
property CONTACT_ID : JString read _GetCONTACT_ID; // Ljava/lang/String; A: $19
end;
[JavaSignature('android/provider/ContactsContract_DeletedContactsColumns')]
JContactsContract_DeletedContactsColumns = interface(JObject)
['{BCC1B7BA-F4B3-492C-AE4D-BF0C9381D950}']
end;
TJContactsContract_DeletedContactsColumns = class(TJavaGenericImport<JContactsContract_DeletedContactsColumnsClass, JContactsContract_DeletedContactsColumns>)
end;
const
TJContactsContract_DeletedContactsColumnsCONTACT_DELETED_TIMESTAMP = 'contact_deleted_timestamp';
TJContactsContract_DeletedContactsColumnsCONTACT_ID = 'contact_id';
implementation
end.
|
unit Dfm2Text.Libs.Converts;
interface
uses
System.SysUtils,
System.Classes;
/// <summary> Returns true if <c>DFM</c> file is in a binary format </summary>
function IsDFMBinary(FileName: string): Boolean;
/// <summary> Convert a binary <c>DFM</c> file to a text <c>DFM</c> file </summary>
function Dfm2Txt(Src, Dest: string): Boolean;
/// <summary> Convert a text <c>DFM</c> file to a binary <c>DFM</c> file </summary>
function Txt2Dfm(Src, Dest: string): Boolean;
/// <summary> Open a binary <c>DFM</c> file as a text stream </summary>
function DfmFile2Stream(const Src: string; Dest: TStream): Boolean;
implementation
function IsDFMBinary(FileName: string): Boolean;
var
F: TFileStream;
B: Byte;
begin
B := 0;
F := TFileStream.Create(FileName, fmOpenRead);
try
F.Read(B, 1);
Result := B = $FF;
finally
F.Free();
end;
end;
function Dfm2Txt(Src, Dest: string): Boolean;
var
SrcS, DestS: TFileStream;
begin
Result := False;
if SameFileName(Src, Dest) then
raise Exception.Create('Error converting dfm file to binary!. ' +
'The source file and destination file names are the same.');
SrcS := TFileStream.Create(Src, fmOpenRead);
DestS := TFileStream.Create(Dest, fmCreate);
try
ObjectResourceToText(SrcS, DestS);
if FileExists(Src) and FileExists(Dest) then
Result := True
else
Result := False;
finally
SrcS.Free();
DestS.Free();
end;
end;
function Txt2Dfm(Src, Dest: string): Boolean;
var
SrcS, DestS: TFileStream;
begin
Result := False;
if SameFileName(Src, Dest) then
raise Exception.Create('Error converting dfm file to binary!. ' +
'The source file and destination file names are the same.');
SrcS := TFileStream.Create(Src, fmOpenRead);
DestS := TFileStream.Create(Dest, fmCreate);
try
ObjectTextToResource(SrcS, DestS);
if FileExists(Src) and FileExists(Dest) then
Result := True
else
Result := False;
finally
SrcS.Free();
DestS.Free();
end;
end;
function DfmFile2Stream(const Src: string; Dest: TStream): Boolean;
var
SrcS: TFileStream;
begin
SrcS := TFileStream.Create(Src, fmOpenRead or fmShareDenyWrite);
try
ObjectResourceToText(SrcS, Dest);
Result := True;
finally
SrcS.Free();
end;
end;
end.
|
UNIT uStrList;
INTERFACE
TYPE
TStrList = CLASS(TObject)
PRIVATE
vList : ARRAY OF STRING;
PUBLIC
Count : Integer;
CONSTRUCTOR Create;
PROCEDURE Clear;
PROCEDURE Add(Text:STRING);
PROCEDURE Replace(Index: Integer; Input: String);
FUNCTION Strings(Index:Integer) : STRING;
END;
IMPLEMENTATION
PROCEDURE TStrList.Replace(Index: Integer; Input: String);
BEGIN
vList[Index] := Input;
END;
CONSTRUCTOR TStrList.Create;
BEGIN
Count:=0;
SetLength(vList,Count+1);
END;
procedure TStrList.Clear;
var
i: Integer;
begin
For i := 0 to Count-1 do
vList[i] := '';
Count := 0;
end;
PROCEDURE TStrList.Add(Text:STRING);
BEGIN
SetLength(vList,Count+1);
vList[Count]:=Text;
Inc(Count);
END;
FUNCTION TStrList.Strings(Index:Integer) : STRING;
BEGIN
Result:=vList[Index];
END;
END.
|
unit ShowImage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ipPlacemnt, ipHTMLHelp;
type
TfmShowImage = class(TipHTMLHelpForm)
Image: TImage;
Placement: TipFormPlacement;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
class procedure ShowInfo(const FN: string);
class function GetPicSize(const FN: string; var Sz: TSize): boolean;
class procedure HideInfo;
end;
implementation
{$R *.dfm}
uses
JPEG, GIFImage, PNGImage;
var
fmShowImage: TfmShowImage;
{ TfmShowImage }
class procedure TfmShowImage.HideInfo;
begin
if fmShowImage<>nil then fmShowImage.Close;
end;
class procedure TfmShowImage.ShowInfo(const FN: string);
begin
if fmShowImage=nil then fmShowImage:=TfmShowImage.Create(Application);
with fmShowImage do begin
Image.Picture.LoadFromFile(FN);
ClientWidth:=Image.Width;
ClientHeight:=Image.Height;
Show;
end;
end;
class function TfmShowImage.GetPicSize(const FN: string; var Sz: TSize): boolean;
begin
Result:=FALSE;
with TfmShowImage.Create(Application) do try
try
Image.Picture.LoadFromFile(FN);
except
Exit;
end;
Sz.cx:=Image.Width;
Sz.cy:=Image.Height;
Result:=TRUE;
finally
Free;
end;
end;
procedure TfmShowImage.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
fmShowImage:=nil;
end;
initialization
fmShowImage:=nil;
end.
|
unit camfeatures;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
Grids, StdCtrls, IniPropStorage, SdpoVideo4L2, VideoDev2;
type
{ TFCamFeatures }
TFCamFeatures = class(TForm)
BFeatureValueSet: TButton;
BSave: TButton;
BLoad: TButton;
EditFeatureValue: TEdit;
IniPropStorage: TIniPropStorage;
LabelFeature: TLabel;
SBFeatureValue: TScrollBar;
SGVideoControls: TStringGrid;
procedure BFeatureValueSetClick(Sender: TObject);
procedure BLoadClick(Sender: TObject);
procedure BSaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SBFeatureValueChange(Sender: TObject);
procedure SGVideoControlsSelectCell(Sender: TObject; aCol, aRow: Integer;
var CanSelect: Boolean);
private
procedure RefreshFeatures;
function SafeGetFeatureValue(i: LongWord): LongWord;
procedure SetCurFeatureValue(newvalue: dword);
{ private declarations }
public
Video: TSdpoVideo4L2;
curFeatureIdx: integer;
updatingHeader: integer;
end;
var
FCamFeatures: TFCamFeatures;
implementation
uses main;
{ TFCamFeatures }
function TFCamFeatures.SafeGetFeatureValue(i: LongWord): LongWord;
begin
if (Video.UserControls[i].flags and (V4L2_CTRL_FLAG_DISABLED or
V4L2_CTRL_FLAG_READ_ONLY or
V4L2_CTRL_FLAG_INACTIVE)) = 0 then begin
result := Video.GetFeatureValue(Video.UserControls[i].id);
end else begin
result := 0;
end;
end;
procedure TFCamFeatures.FormShow(Sender: TObject);
var i: integer;
begin
// Fill the string grid with the available features
for i := 0 to length(Video.UserControls) - 1 do begin
SGVideoControls.InsertColRow(false, i + 1);
//SGVideoControls.Objects[0, i + 1] := Tobject(@Video.UserControls[i]);
SGVideoControls.Cells[0, i + 1] := pchar(@Video.UserControls[i].name[0]) ;
SGVideoControls.Cells[1, i + 1] := inttostr(SafeGetFeatureValue(i));
//SGVideoControls.Cells[2, i + 1] := inttostr(Video.UserControls[i].id - V4L2_CID_BASE);
SGVideoControls.Cells[2, i + 1] := inttostr(Video.UserControls[i].minimum);
SGVideoControls.Cells[3, i + 1] := inttostr(Video.UserControls[i].maximum);
SGVideoControls.Cells[4, i + 1] := inttostr(Video.UserControls[i].flags);
end;
// Init the current selected feature
curFeatureIdx := SGVideoControls.Selection.Top - 1;
if curFeatureIdx < 0 then exit;
RefreshFeatures();
end;
procedure TFCamFeatures.BFeatureValueSetClick(Sender: TObject);
var newvalue: integer;
begin
if curFeatureIdx < 0 then exit;
newvalue := SafeGetFeatureValue(curFeatureIdx);
newvalue := StrToIntDef(EditFeatureValue.Text, newvalue);
SetCurFeatureValue(newvalue);
end;
procedure TFCamFeatures.BLoadClick(Sender: TObject);
var i: integer;
value: dword;
begin
for i := 0 to length(Video.UserControls) - 1 do begin
value := IniPropStorage.ReadInteger(inttostr(Video.UserControls[i].id),
SafeGetFeatureValue(i));
Video.TrySetFeatureValue(Video.UserControls[i].id, value);
end;
RefreshFeatures();
end;
procedure TFCamFeatures.BSaveClick(Sender: TObject);
var i: integer;
begin
for i := 0 to length(Video.UserControls) - 1 do begin
IniPropStorage.WriteInteger(inttostr(Video.UserControls[i].id),
SafeGetFeatureValue(i));
end;
end;
//V4L2_CTRL_FLAG_DISABLED = $0001;
//V4L2_CTRL_FLAG_GRABBED = $0002;
//V4L2_CTRL_FLAG_READ_ONLY = $0004;
//V4L2_CTRL_FLAG_UPDATE = $0008;
//V4L2_CTRL_FLAG_INACTIVE = $0010;
//V4L2_CTRL_FLAG_SLIDER = $0020;
procedure TFCamFeatures.SetCurFeatureValue(newvalue: dword);
begin
if curFeatureIdx < 0 then exit;
// Discard change events because is an internal update
if updatingHeader > 0 then exit;
// Beware of feastures that are read only, disabled or inactive
if (Video.UserControls[curFeatureIdx].flags and (V4L2_CTRL_FLAG_DISABLED or
V4L2_CTRL_FLAG_READ_ONLY or
V4L2_CTRL_FLAG_INACTIVE)) = 0 then begin
Video.SetFeatureValue(Video.UserControls[curFeatureIdx].id, newvalue);
end;
RefreshFeatures();
end;
procedure TFCamFeatures.SBFeatureValueChange(Sender: TObject);
begin
SetCurFeatureValue(SBFeatureValue.Position);
end;
procedure TFCamFeatures.RefreshFeatures;
var i: integer;
value: dword;
begin
// Refresh the values column
for i := 0 to length(Video.UserControls) - 1 do begin
SGVideoControls.Cells[1, i + 1] := inttostr(SafeGetFeatureValue(i));
end;
if curFeatureIdx < 0 then exit;
// Update the edit header
LabelFeature.Caption := pchar(@Video.UserControls[curFeatureIdx].name[0]);
value := SafeGetFeatureValue(curFeatureIdx);
EditFeatureValue.Text := inttostr(value);
// Discard change events while doing it
updatingHeader := 1;
SBFeatureValue.Min := Video.UserControls[curFeatureIdx].minimum;
SBFeatureValue.Max := Video.UserControls[curFeatureIdx].maximum;
SBFeatureValue.Position := value;
updatingHeader := 0;
end;
procedure TFCamFeatures.FormCreate(Sender: TObject);
begin
IniPropStorage.IniFileName := FMain.IniPropStorage.IniFileName;
end;
procedure TFCamFeatures.SGVideoControlsSelectCell(Sender: TObject; aCol,
aRow: Integer; var CanSelect: Boolean);
begin
curFeatureIdx := aRow - 1;
if aRow = 0 then exit;
RefreshFeatures();
end;
initialization
{$I camfeatures.lrs}
end.
|
unit LrProject;
interface
uses
SysUtils, Classes,
LrTreeData, LrDocument;
type
TLrProjectItem = class(TLrTreeNode)
private
FSource: string;
FImageIndex: Integer;
protected
function GetDisplayName: string; override;
function GetFolderPath: string;
function GetProjectItem(inIndex: Integer): TLrProjectItem;
procedure SetImageIndex(const Value: Integer);
procedure SetSource(const Value: string);
public
function FindBySource(const inSource: string): TLrProjectItem;
function GetParentItem: TLrProjectItem;
function GenerateUniqueSource(const inSource: string): string;
property FolderPath: string read GetFolderPath;
property ParentItem: TLrProjectItem read GetParentItem;
property ProjectItems[inIndex: Integer]: TLrProjectItem
read GetProjectItem; default;
published
property ImageIndex: Integer read FImageIndex write SetImageIndex;
property Source: string read FSource write SetSource;
end;
//
TLrFolderItem = class(TLrProjectItem);
//
TLrProject = class(TLrDocument)
private
FItems: TLrProjectItem;
protected
procedure CreateItems; virtual;
procedure ItemsChange(inSender: TObject);
procedure SaveItem(inSender: TLrTreeLeaf; inIndex: Integer;
var inAllow: Boolean); virtual;
procedure SetItems(const Value: TLrProjectItem);
public
constructor Create; override;
destructor Destroy; override;
procedure LoadFromFile(const inFilename: string); virtual;
procedure SaveToFile(const inFilename: string); virtual;
published
property Items: TLrProjectItem read FItems write SetItems;
end;
implementation
uses
LrUtils;
{ TLrProjecItem }
function TLrProjectItem.GetProjectItem(inIndex: Integer): TLrProjectItem;
begin
Result := TLrProjectItem(Items[inIndex]);
end;
function TLrProjectItem.GetDisplayName: string;
begin
Result := inherited GetDisplayName;
if Result = '' then
Result := ExtractFileName(Source);
end;
procedure TLrProjectItem.SetImageIndex(const Value: Integer);
begin
FImageIndex := Value;
Change;
end;
procedure TLrProjectItem.SetSource(const Value: string);
begin
if Source <> Value then
begin
FSource := Value;
Change;
end;
end;
function TLrProjectItem.FindBySource(const inSource: string): TLrProjectItem;
var
i: Integer;
begin
Result := nil;
if inSource <> '' then
if Source = inSource then
Result := Self
else
for i := 0 to Pred(Count) do
if Items[i] is TLrProjectItem then
begin
Result := TLrProjectItem(Items[i]).FindBySource(inSource);
if Result <> nil then
break;
end;
end;
function TLrProjectItem.GenerateUniqueSource(const inSource: string): string;
var
i: Integer;
begin
if FindBySource(inSource) = nil then
Result := inSource
else begin
i := 0;
repeat
Inc(i);
Result := inSource + IntToStr(i);
until FindBySource(Result) = nil;
end;
end;
function TLrProjectItem.GetFolderPath: string;
var
item: TLrTreeLeaf;
begin
Result := '';
item := Self;
while (item <> nil) do
begin
if item is TLrFolderItem then
Result := IncludeTrailingBackslash(TLrFolderItem(item).Source) + Result;
item := item.Parent;
end;
end;
{ TLrProject }
constructor TLrProject.Create;
begin
inherited;
CreateItems;
Items.OnChange := ItemsChange;
Items.OnSaveItem := SaveItem;
end;
destructor TLrProject.Destroy;
begin
Items.Free;
inherited;
end;
function TLrProjectItem.GetParentItem: TLrProjectItem;
begin
Result := TLrProjectItem(Parent);
end;
procedure TLrProject.CreateItems;
begin
FItems := TLrProjectItem.Create;
end;
procedure TLrProject.SetItems(const Value: TLrProjectItem);
begin
FItems.Assign(Value);
end;
procedure TLrProject.ItemsChange(inSender: TObject);
begin
Modify;
end;
procedure TLrProject.LoadFromFile(const inFilename: string);
begin
Items.LoadFromFile(inFilename);
end;
procedure TLrProject.SaveToFile(const inFilename: string);
begin
Items.SaveToFile(inFilename);
end;
procedure TLrProject.SaveItem(inSender: TLrTreeLeaf; inIndex: Integer;
var inAllow: Boolean);
begin
inAllow := true;
end;
initialization
RegisterClass(TLrProjectItem);
RegisterClass(TLrFolderItem);
end.
|
(*
* SDL 1.3 FreePascal header for iPhone
* Pre-Alpha
*
* Used SDL header from Hedgewars project (http://www.hedgewars.org) and JEDI-SDL and modified to
* fit just the needs for SDL with iPhone and updated to the latest ("stable") version (Rev. 5483)
*
* Warning: Still incomplete!!!
*
* © Johannes Stein, 2010
* License: MPL
*
*)
unit SDL13_iOS;
{$I jedi-sdl.inc}
{$mode delphi}
{$H+}
{$ALIGN ON}
//{$link libgcc.a}
//{$linklib gcc}
{$link libSDL_iOS.a}
{$linkframework AudioToolbox}
{$linkframework QuartzCore}
{$linkframework OpenGLES}
{$linkframework CoreGraphics}
{$linkframework UIKit}
{$linkframework Foundation}
{$linkframework CoreAudio}
{$PASCALMAINNAME SDL_main}
interface
const
SDL_SWSURFACE = $00000000;
SDL_HWSURFACE = $00000001;
SDL_SRCALPHA = $00010000;
// Begin SDL.h (Constants)
SDL_INIT_TIMER = $00000001;
SDL_INIT_AUDIO = $00000010;
SDL_INIT_VIDEO = $00000020;
SDL_INIT_JOYSTICK = $00000200;
SDL_INIT_HAPTIC = $00001000;
SDL_INIT_NOPARACHUTE = $00100000;
SDL_INIT_EVENTTHREAD = $01000000;
SDL_INIT_EVERYTHING = $0000FFFF;
// End SDL.h
// Begin SDL_video.h (Constants)
SDL_WINDOW_FULLSCREEN = $00000001; //**< fullscreen window */
SDL_WINDOW_OPENGL = $00000002; //**< window usable with OpenGL context */
SDL_WINDOW_SHOWN = $00000004; //**< window is visible */
SDL_WINDOW_HIDDEN = $00000008; //**< window is not visible */
SDL_WINDOW_BORDERLESS = $00000010; //**< no window decoration */
SDL_WINDOW_RESIZABLE = $00000020; //**< window can be resized */
SDL_WINDOW_MINIMIZED = $00000040; //**< window is minimized */
SDL_WINDOW_MAXIMIZED = $00000080; //**< window is maximized */
SDL_WINDOW_INPUT_GRABBED = $00000100; //**< window has grabbed input focus */
SDL_WINDOW_INPUT_FOCUS = $00000200; //**< window has input focus */
SDL_WINDOW_MOUSE_FOCUS = $00000400; //**< window has mouse focus */
SDL_WINDOW_FOREIGN = $00000800; //**< window not created by SDL */
// End SDL_video.h
// SDL_types.h constants
SDL_PRESSED = $01;
{$EXTERNALSYM SDL_PRESSED}
SDL_RELEASED = $00;
{$EXTERNALSYM SDL_RELEASED}
//SDL_mouse.h constants
{ Used as a mask when testing buttons in buttonstate
Button 1: Left mouse button
Button 2: Middle mouse button
Button 3: Right mouse button
Button 4: Mouse Wheel Up
Button 5: Mouse Wheel Down
}
SDL_BUTTON_LEFT = 1;
{$EXTERNALSYM SDL_BUTTON_LEFT}
SDL_BUTTON_MIDDLE = 2;
{$EXTERNALSYM SDL_BUTTON_MIDDLE}
SDL_BUTTON_RIGHT = 3;
{$EXTERNALSYM SDL_BUTTON_RIGHT}
SDL_BUTTON_WHEELUP = 4;
{$EXTERNALSYM SDL_BUTTON_WHEELUP}
SDL_BUTTON_WHEELDOWN = 5;
{$EXTERNALSYM SDL_BUTTON_WHEELDOWN}
SDL_BUTTON_LMASK = SDL_PRESSED shl (SDL_BUTTON_LEFT - 1);
{$EXTERNALSYM SDL_BUTTON_LMASK}
SDL_BUTTON_MMASK = SDL_PRESSED shl (SDL_BUTTON_MIDDLE - 1);
{$EXTERNALSYM SDL_BUTTON_MMASK}
SDL_BUTTON_RMask = SDL_PRESSED shl (SDL_BUTTON_RIGHT - 1);
{$EXTERNALSYM SDL_BUTTON_RMask}
SDL_APPINPUTFOCUS = 2;
{*begin SDL_Event binding*}
SDL_NOEVENT = 0; //**< Unused (do not remove) */
SDL_WINDOWEVENT = 1; //**< Window state change */
SDL_KEYDOWN = 2; //**< Keys pressed */
SDL_KEYUP = 3; //**< Keys released */
SDL_TEXTEDITING = 4; //**< Keyboard text editing (composition) */
SDL_TEXTINPUT = 5; //**< Keyboard text input */
SDL_MOUSEMOTION = 6; //**< Mouse moved */
SDL_MOUSEBUTTONDOWN = 7; //**< Mouse button pressed */
SDL_MOUSEBUTTONUP = 8; //**< Mouse button released */
SDL_MOUSEWHEEL = 9; //**< Mouse wheel motion */
SDL_JOYAXISMOTION = 10; //**< Joystick axis motion */
SDL_JOYBALLMOTION = 11; //**< Joystick trackball motion */
SDL_JOYHATMOTION = 12; //**< Joystick hat position change */
SDL_JOYBUTTONDOWN = 13; //**< Joystick button pressed */
SDL_JOYBUTTONUP = 14; //**< Joystick button released */
SDL_QUITEV = 15; //**< User-requested quit */
SDL_SYSWMEVENT = 16; //**< System specific event */
SDL_PROXIMITYIN = 17; //**< Proximity In event */
SDL_PROXIMITYOUT = 18; //**< Proximity Out event */
SDL_EVENT_RESERVED1 = 19; //**< Reserved for future use... */
SDL_EVENT_RESERVED2 = 20; //**< Reserved for future use... */
SDL_EVENT_RESERVED3 = 21; //**< Reserved for future use... */
//** Events ::SDL_USEREVENT through ::SDL_MAXEVENTS-1 are for your use */
SDL_USEREVENT = 24;
(**
* This last event is only for bounding internal arrays
* It is the number of bits in the event mask datatype -- Uint32
*)
SDL_NUMEVENTS = 32;
{*end SDL_Event binding*}
SDL_ASYNCBLIT = $08000000;
SDL_ANYFORMAT = $10000000;
SDL_HWPALETTE = $00200000;
SDL_DOUBLEBUF = $00400000;
SDL_FULLSCREEN = $00800000;
SDL_HWACCEL = $08000000;
SDL_SRCCOLORKEY = $00020000;
SDL_RLEACCEL = $08000000;
SDL_NOFRAME = $02000000;
SDL_OPENGL = $04000000;
SDL_RESIZABLE = $01000000;
{$IFDEF ENDIAN_LITTLE}
RMask = $000000FF;
GMask = $0000FF00;
BMask = $00FF0000;
AMask = $FF000000;
{$ELSE}
RMask = $FF000000;
GMask = $00FF0000;
BMask = $0000FF00;
AMask = $000000FF;
{$ENDIF}
(*// SDL_WindowFlags (enum)
SDL_WINDOW_FULLSCREEN = $00000001; //*< fullscreen window, implies borderless */
SDL_WINDOW_OPENGL = $00000002; //*< window usable with OpenGL context */
SDL_WINDOW_SHOWN = $00000004; //*< window is visible */
SDL_WINDOW_BORDERLESS = $00000008; //*< no window decoration */
SDL_WINDOW_RESIZABLE = $00000010; //*< window can be resized */
SDL_WINDOW_MINIMIZED = $00000020; //*< window is minimized */
SDL_WINDOW_MAXIMIZED = $00000040; //*< window is maximized */
SDL_WINDOW_INPUT_GRABBED = $00000100; //*< window has grabbed input focus */
SDL_WINDOW_INPUT_FOCUS = $00000200; //*< window has input focus */
SDL_WINDOW_MOUSE_FOCUS = $00000400; //*< window has mouse focus */
SDL_WINDOW_FOREIGN = $00000800; //*< window not created by SDL */
SDL_RENDERER_SINGLEBUFFER = $00000001; //*< Render directly to the window, if possible */
SDL_RENDERER_PRESENTCOPY = $00000002; //*< Present uses a copy from back buffer to the front buffer */
SDL_RENDERER_PRESENTFLIP2 = $00000004; //*< Present uses a flip, swapping back buffer and front buffer */
SDL_RENDERER_PRESENTFLIP3 = $00000008; //*< Present uses a flip, rotating between two back buffers and a front buffer */
SDL_RENDERER_PRESENTDISCARD = $00000010; //*< Present leaves the contents of the backbuffer undefined */
SDL_RENDERER_PRESENTVSYNC = $00000020; //*< Present is synchronized with the refresh rate */
SDL_RENDERER_ACCELERATED = $00000040; //*< The renderer uses hardware acceleration */
// Begin SDL_blendmode.h
SDL_BLENDMODE_NONE = $00000000; //*< No blending */
SDL_BLENDMODE_MASK = $00000001; //*< dst = A ? src : dst (alpha is mask) */
SDL_BLENDMODE_BLEND = $00000002; //*< dst = (src * A) + (dst * (1-A)) */
SDL_BLENDMODE_ADD = $00000004; //*< dst = (src * A) + dst */
SDL_BLENDMODE_MOD = $00000008; //*< dst = src * dst */
// End SDL_blendmode.h
*)
// Pixel stuff
SDL_PIXELTYPE_UNKNOWN = 0;
SDL_PIXELTYPE_INDEX1 = 1;
SDL_PIXELTYPE_INDEX4 = 2;
SDL_PIXELTYPE_INDEX8 = 3;
SDL_PIXELTYPE_PACKED8 = 4;
SDL_PIXELTYPE_PACKED16 = 5;
SDL_PIXELTYPE_PACKED32 = 6;
SDL_PIXELTYPE_ARRAYU8 = 7;
SDL_PIXELTYPE_ARRAYU16 = 8;
SDL_PIXELTYPE_ARRAYU32 = 9;
SDL_PIXELTYPE_ARRAYF16 = 10;
SDL_PIXELTYPE_ARRAYF32 = 11;
//* Bitmap pixel order, high bit -> low bit. */
SDL_BITMAPORDER_NONE = 0;
SDL_BITMAPORDER_4321 = 1;
SDL_BITMAPORDER_1234 = 2;
//* Packed component order, high bit -> low bit. */
SDL_PACKEDORDER_NONE = 0;
SDL_PACKEDORDER_XRGB = 1;
SDL_PACKEDORDER_RGBX = 2;
SDL_PACKEDORDER_ARGB = 3;
SDL_PACKEDORDER_RGBA = 4;
SDL_PACKEDORDER_XBGR = 5;
SDL_PACKEDORDER_BGRX = 6;
SDL_PACKEDORDER_ABGR = 7;
SDL_PACKEDORDER_BGRA = 8;
//* Array component order, low byte -> high byte. */
SDL_ARRAYORDER_NONE = 0;
SDL_ARRAYORDER_RGB = 1;
SDL_ARRAYORDER_RGBA = 2;
SDL_ARRAYORDER_ARGB = 3;
SDL_ARRAYORDER_BGR = 4;
SDL_ARRAYORDER_BGRA = 5;
SDL_ARRAYORDER_ABGR = 6;
//* Packed component layout. */
SDL_PACKEDLAYOUT_NONE = 0;
SDL_PACKEDLAYOUT_332 = 1;
SDL_PACKEDLAYOUT_4444 = 2;
SDL_PACKEDLAYOUT_1555 = 3;
SDL_PACKEDLAYOUT_5551 = 4;
SDL_PACKEDLAYOUT_565 = 5;
SDL_PACKEDLAYOUT_8888 = 6;
SDL_PACKEDLAYOUT_2101010 = 7;
SDL_PACKEDLAYOUT_1010102 = 8;
//SDL_PIXELFORMAT_ABGR8888 = ((1 shl 31) or ((SDL_PIXELTYPE_PACKED32) shl 24) or ((SDL_PACKEDORDER_ABGR) shl 20) or ((SDL_PACKEDLAYOUT_8888) shl 16) or ((32) shl 8) or ((4) shl 0));
// see: SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ABGR, SDL_PACKEDLAYOUT_8888, 32, 4),
// Pixelformat macros
{$define SDL_PIXELFORMAT_ABGR8888:=SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ABGR, SDL_PACKEDLAYOUT_8888, 32, 4)}
type
THandle = Cardinal;
//SDL_types.h types
// Basic data types
SDL_Bool = (SDL_FALSE, SDL_TRUE);
TSDL_Bool = SDL_Bool;
PUInt8Array = ^TUInt8Array;
PUInt8 = ^UInt8;
UInt8 = Byte;
{$EXTERNALSYM UInt8}
TUInt8Array = array [0..MAXINT shr 1] of UInt8;
PUInt16 = ^UInt16;
UInt16 = word;
{$EXTERNALSYM UInt16}
PSInt16 = ^SInt16;
SInt16 = smallint;
{$EXTERNALSYM SInt16}
PUInt32 = ^UInt32;
UInt32 = Cardinal;
{$EXTERNALSYM UInt32}
SInt32 = Integer;
{$EXTERNALSYM SInt32}
PInt = ^Integer;
PShortInt = ^ShortInt;
PUInt64 = ^UInt64;
UInt64 = record
hi: UInt32;
lo: UInt32;
end;
{$EXTERNALSYM UInt64}
PSInt64 = ^SInt64;
SInt64 = record
hi: UInt32;
lo: UInt32;
end;
{$EXTERNALSYM SInt64}
// Begin SDL_rect.h (Types)
PSDL_Rect = ^TSDL_Rect;
TSDL_Rect = record
x, y, w, h: LongInt;
end;
PSDL_Point = ^TSDL_Point;
TSDL_Point = record
x: Integer;
y: Integer;
end;
// End SDL_rect.h
PSDL_PixelFormat = ^TSDL_PixelFormat;
TSDL_PixelFormat = record
palette: Pointer;
BitsPerPixel : Byte;
BytesPerPixel: Byte;
Rloss : Byte;
Gloss : Byte;
Bloss : Byte;
Aloss : Byte;
Rshift: Byte;
Gshift: Byte;
Bshift: Byte;
Ashift: Byte;
RMask : UInt32;
GMask : UInt32;
BMask : UInt32;
AMask : UInt32;
colorkey: UInt32;
alpha : Byte;
end;
PSDL_Surface = ^TSDL_Surface;
TSDL_Surface = record
flags: UInt32; // Read-only
format: PSDL_PixelFormat; // Read-only
w, h: Integer; // Read-only
pitch: Integer; // Read-only
pixels: Pointer; // Read-write
userdata: Pointer; // Read-write
locked: Integer; // Read-only
lock_data: Pointer; // Read-only
// clipping information:
clip_rect: TSDL_Rect; // Read-only
map: Pointer; // PSDL_BlitMap; // Private
// format version, bumped at every change to invalidate blit maps
format_version: Cardinal; // Private
refcount: Integer;
end;
PSDL_Color = ^TSDL_Color;
TSDL_Color = record
case byte of
0: ( r: Byte;
g: Byte;
b: Byte;
unused: Byte;
);
1: ( value: Longword);
end;
PSDL_RWops = ^TSDL_RWops;
TSeek = function( context: PSDL_RWops; offset: LongInt; whence: LongInt ): LongInt; cdecl;
TRead = function( context: PSDL_RWops; Ptr: Pointer; size: LongInt; maxnum : LongInt ): LongInt; cdecl;
TWrite = function( context: PSDL_RWops; Ptr: Pointer; size: LongInt; num: LongInt ): LongInt; cdecl;
TClose = function( context: PSDL_RWops ): LongInt; cdecl;
TStdio = record
autoclose: LongInt;
fp: pointer;
end;
TMem = record
base: PByte;
here: PByte;
stop: PByte;
end;
TUnknown = record
data1: Pointer;
end;
TSDL_RWops = record
seek: TSeek;
read: TRead;
write: TWrite;
close: TClose;
type_: Longword;
case Byte of
0: (stdio: TStdio);
1: (mem: TMem);
2: (unknown: TUnknown);
end;
TSDL_KeySym = record
scancode: Byte;
sym: Longword;
modifier: Longword;
unicode: Word;
end;
{* SDL_Event type definition *}
TSDL_WindowEvent = record
type_: byte;
gain: byte;
state: byte;
windowID: LongInt;
data1, data2: LongInt;
end;
// implement SDL_TextEditingEvent + SDL_TextInputEvent for sdl13
TSDL_MouseMotionEvent = record
type_: byte;
which: byte;
state: byte;
windowID: LongInt;
x, y, xrel, yrel : LongInt;
pressure, pressure_max, pressure_min,
rotation, tilt, cursor: LongInt;
end;
TSDL_KeyboardEvent = record
type_: Byte;
windowID: LongInt;
which: Byte;
state: Byte;
keysym: TSDL_KeySym;
end;
TSDL_MouseButtonEvent = record
_type,
which,
button,
state: byte;
windowID: LongInt;
x, y: LongInt;
end;
TSDL_MouseWheelEvent = record
type_: Byte;
windowID: LongInt;
which: Byte;
x, y: LongInt;
end;
TSDL_JoyAxisEvent = record
type_: Byte;
which: Byte;
axis: Byte;
value: LongInt;
end;
TSDL_JoyBallEvent = record
type_: Byte;
which: Byte;
ball: Byte;
xrel, yrel: LongInt;
end;
TSDL_JoyHatEvent = record
type_: Byte;
which: Byte;
hat: Byte;
value: Byte;
end;
TSDL_JoyButtonEvent = record
type_: Byte;
which: Byte;
button: Byte;
state: Byte;
end;
TSDL_QuitEvent = record
type_: Byte;
end;
PSDL_Event = ^TSDL_Event;
TSDL_Event = record
case Byte of
SDL_NOEVENT: (type_: byte);
SDL_WINDOWEVENT: (active: TSDL_WindowEvent);
SDL_KEYDOWN,
SDL_KEYUP: (key: TSDL_KeyboardEvent);
SDL_TEXTEDITING,
SDL_TEXTINPUT: (txtin: byte);
SDL_MOUSEMOTION: (motion: TSDL_MouseMotionEvent);
SDL_MOUSEBUTTONDOWN,
SDL_MOUSEBUTTONUP: (button: TSDL_MouseButtonEvent);
SDL_MOUSEWHEEL: (wheel: TSDL_MouseWheelEvent);
SDL_JOYAXISMOTION: (jaxis: TSDL_JoyAxisEvent);
SDL_JOYHATMOTION: (jhat: TSDL_JoyHatEvent);
SDL_JOYBALLMOTION: (jball: TSDL_JoyBallEvent);
SDL_JOYBUTTONDOWN,
SDL_JOYBUTTONUP: (jbutton: TSDL_JoyButtonEvent);
SDL_QUITEV: (quit: TSDL_QuitEvent);
end;
PByteArray = ^TByteArray;
TByteArray = array[0..65535] of Byte;
PLongWordArray = ^TLongWordArray;
TLongWordArray = array[0..16383] of LongWord;
PSDL_Thread = Pointer;
PSDL_mutex = Pointer;
(*
TSDL_ArrayByteOrder = ( // array component order, low byte -> high byte
SDL_ARRAYORDER_NONE,
SDL_ARRAYORDER_RGB,
SDL_ARRAYORDER_RGBA,
SDL_ARRAYORDER_ARGB,
SDL_ARRAYORDER_BGR,
SDL_ARRAYORDER_BGRA,
SDL_ARRAYORDER_ABGR
);*)
// Joystick/Controller support
PSDL_Joystick = ^TSDL_Joystick;
TSDL_Joystick = record
end;
// Begin SDL_blendmode.h
TSDL_BlendMode = (
SDL_BLENDMODE_NONE = $00000000, //**< No blending */
SDL_BLENDMODE_BLEND = $00000001, //**< dst = (src * A) + (dst * (1-A)) */
SDL_BLENDMODE_ADD = $00000002, //**< dst = (src * A) + dst */
SDL_BLENDMODE_MOD = $00000004 //**< dst = src * dst */
);
// End SDL_blendmode.h
// Begin SDL_video.h (Types)
PSDL_DisplayMode = ^TSDL_DisplayMode;
TSDL_DisplayMode = record
format: UInt32;
w: Integer;
h: Integer;
refresh_rate: Integer;
driverdata: Pointer;
end;
PSDL_Window = Pointer;
TSDL_WindowEventID = (
SDL_WINDOWEVENT_NONE, //**< Never used */
SDL_WINDOWEVENT_SHOWN, //**< Window has been shown */
SDL_WINDOWEVENT_HIDDEN, //**< Window has been hidden */
SDL_WINDOWEVENT_EXPOSED, //**< Window has been exposed and should be redrawn */
SDL_WINDOWEVENT_MOVED, //**< Window has been moved to data1, data2 */
SDL_WINDOWEVENT_RESIZED, //**< Window has been resized to data1xdata2 */
SDL_WINDOWEVENT_SIZE_CHANGED, //**< The window size has changed, either as a result of an API call or through the system or user changing the window size. */
SDL_WINDOWEVENT_MINIMIZED, //**< Window has been minimized */
SDL_WINDOWEVENT_MAXIMIZED, //**< Window has been maximized */
SDL_WINDOWEVENT_RESTORED, //**< Window has been restored to normal size and position */
SDL_WINDOWEVENT_ENTER, //**< Window has gained mouse focus */
SDL_WINDOWEVENT_LEAVE, //**< Window has lost mouse focus */
SDL_WINDOWEVENT_FOCUS_GAINED, //**< Window has gained keyboard focus */
SDL_WINDOWEVENT_FOCUS_LOST, //**< Window has lost keyboard focus */
SDL_WINDOWEVENT_CLOSE //**< The window manager requests that the window be closed */
);
PSDL_GLContext = Pointer;
TSDL_GLattr =
(
SDL_GL_RED_SIZE,
SDL_GL_GREEN_SIZE,
SDL_GL_BLUE_SIZE,
SDL_GL_ALPHA_SIZE,
SDL_GL_BUFFER_SIZE,
SDL_GL_DOUBLEBUFFER,
SDL_GL_DEPTH_SIZE,
SDL_GL_STENCIL_SIZE,
SDL_GL_ACCUM_RED_SIZE,
SDL_GL_ACCUM_GREEN_SIZE,
SDL_GL_ACCUM_BLUE_SIZE,
SDL_GL_ACCUM_ALPHA_SIZE,
SDL_GL_STEREO,
SDL_GL_MULTISAMPLEBUFFERS,
SDL_GL_MULTISAMPLESAMPLES,
SDL_GL_ACCELERATED_VISUAL,
SDL_GL_RETAINED_BACKING,
SDL_GL_CONTEXT_MAJOR_VERSION,
SDL_GL_CONTEXT_MINOR_VERSION
);
// End SDL_video.h
// Begin SDL_render.h (Types)
PSDL_RendererInfo = ^TSDL_RendererInfo;
TSDL_RendererInfo = record
name: PChar; //**< The name of the renderer */
flags: UInt32; //**< Supported ::SDL_RendererFlags */
num_texture_formats: UInt32; //**< The number of available texture formats */
texture_formats: array[0..16] of UInt32; //**< The available texture formats */
max_texture_width: Integer; //**< The maximimum texture width */
max_texture_height: Integer; //**< The maximimum texture height */
end;
PSDL_Renderer = Pointer;
PSDL_Texture = Pointer;
TSDL_RendererFlags = (
SDL_RENDERER_SOFTWARE = $00000001, //**< The renderer is a software fallback */
SDL_RENDERER_ACCELERATED = $00000002, //**< The renderer uses hardware acceleration */
SDL_RENDERER_PRESENTVSYNC = $00000004 //**< Present is synchronized with the refresh rate */
);
TSDL_TextureAccess = (
SDL_TEXTUREACCESS_STATIC, //**< Changes rarely, not lockable */
SDL_TEXTUREACCESS_STREAMING //**< Changes frequently, lockable */
);
TSDL_TextureModulate = (
SDL_TEXTUREMODULATE_NONE = $00000000, //**< No modulation */
SDL_TEXTUREMODULATE_COLOR = $00000001, //**< srcC = srcC * color */
SDL_TEXTUREMODULATE_ALPHA = $00000002 //**< srcA = srcA * alpha */
);
// End SDL_render.h
// Begin SDL.h (Prototypes)
function SDL_Init(flags: UInt32): Integer; cdecl; external;
function SDL_InitSubSystem(flags: UInt32): Integer; cdecl; external;
procedure SDL_QuitSubSystem(flags: UInt32); cdecl; external;
function SDL_WasInit(flags: UInt32): Uint32; cdecl; external;
procedure SDL_Quit; cdecl; external;
// End SDL.h
// Begin SDL_main.h
function SDL_RegisterApp(name: PChar; style: UInt32; hInst: Pointer): Integer; cdecl; external;
procedure SDL_UnregisterApp(); cdecl; external;
// End SDL_main.h
function SDL_VideoDriverName(var namebuf; maxlen: LongInt): PChar; cdecl; external;
procedure SDL_EnableUNICODE(enable: LongInt); cdecl; external;
procedure SDL_Delay(msec: Longword); cdecl; external;
function SDL_GetTicks: Longword; cdecl; external;
function SDL_MustLock(Surface: PSDL_Surface): Boolean;
function SDL_LockSurface(Surface: PSDL_Surface): LongInt; cdecl; external;
procedure SDL_UnlockSurface(Surface: PSDL_Surface); cdecl; external;
function SDL_GetError: PChar; cdecl; external;
function SDL_SetVideoMode(width, height, bpp: LongInt; flags: Longword): PSDL_Surface; cdecl; external;
function SDL_CreateRGBSurface(flags: Longword; Width, Height, Depth: LongInt; RMask, GMask, BMask, AMask: Longword): PSDL_Surface; cdecl; external;
function SDL_CreateRGBSurfaceFrom(pixels: Pointer; width, height, depth, pitch: LongInt; RMask, GMask, BMask, AMask: Longword): PSDL_Surface; cdecl; external;
procedure SDL_FreeSurface(Surface: PSDL_Surface); cdecl; external;
function SDL_SetColorKey(surface: PSDL_Surface; flag, key: Longword): LongInt; cdecl; external;
function SDL_SetAlpha(surface: PSDL_Surface; flag, key: Longword): LongInt; cdecl; external;
function SDL_ConvertSurface(src: PSDL_Surface; fmt: PSDL_PixelFormat; flags: LongInt): PSDL_Surface; cdecl; external;
function SDL_UpperBlit(src: PSDL_Surface; srcrect: PSDL_Rect; dst: PSDL_Surface; dstrect: PSDL_Rect): LongInt; cdecl; external;
function SDL_FillRect(dst: PSDL_Surface; dstrect: PSDL_Rect; color: Longword): LongInt; cdecl; external;
procedure SDL_UpdateRect(Screen: PSDL_Surface; x, y: LongInt; w, h: Longword); cdecl; external;
function SDL_Flip(Screen: PSDL_Surface): LongInt; cdecl; external;
procedure SDL_GetRGB(pixel: Longword; fmt: PSDL_PixelFormat; r, g, b: PByte); cdecl; external;
function SDL_MapRGB(format: PSDL_PixelFormat; r, g, b: Byte): Longword; cdecl; external;
function SDL_MapRGBA(format: PSDL_PixelFormat; r, g, b, a: Byte): Longword; cdecl; external;
function SDL_DisplayFormat(Surface: PSDL_Surface): PSDL_Surface; cdecl; external;
function SDL_DisplayFormatAlpha(Surface: PSDL_Surface): PSDL_Surface; cdecl; external;
function SDL_RWFromFile(filename, mode: PChar): PSDL_RWops; cdecl; external;
function SDL_LoadBMP_RW(src: PSDL_RWops; freesrc: Integer): PSDL_Surface; cdecl; external;
function SDL_SaveBMP_RW(surface: PSDL_Surface; dst: PSDL_RWops; freedst: LongInt): LongInt; cdecl; external;
// Begin SDL_clipboard.h
function SDL_SetClipboardText(const text: PChar): Integer; cdecl; external;
function SDL_GetClipboardText(): PChar; cdecl; external;
function SDL_HasClipboardText(): TSDL_Bool; cdecl; external;
// End SDL_clipboard.h
// Begin SDL_video.h (Prototypes)
function SDL_GetNumVideoDrivers(): Integer; cdecl; external;
function SDL_GetVideoDriver(index: Integer): PChar; cdecl; external;
function SDL_VideoInit(const driver_name: PChar): Integer; cdecl; external;
procedure SDL_VideoQuit(); cdecl; external;
function SDL_GetCurrentVideoDriver(): PChar; cdecl; external;
function SDL_GetNumVideoDisplays(): Integer; cdecl; external;
function SDL_GetDisplayBounds(displayIndex: Integer; rect: PSDL_Rect): Integer; cdecl; external;
function SDL_GetNumDisplayModes(displayIndex: Integer): Integer; cdecl; external;
function SDL_GetDisplayMode(displayIndex: Integer; modeIndex: Integer; mode: PSDL_DisplayMode): Integer; cdecl; external;
function SDL_GetDesktopDisplayMode(displayIndex: Integer; mode: PSDL_DisplayMode): Integer; cdecl; external;
function SDL_GetCurrentDisplayMode(displayIndex: Integer; mode: PSDL_DisplayMode): Integer; cdecl; external;
function SDL_GetClosestDisplayMode(displayIndex: Integer; const mode: PSDL_DisplayMode; closest: PSDL_DisplayMode): PSDL_DisplayMode; cdecl; external;
function SDL_GetWindowDisplay(window: PSDL_Window): Integer; cdecl; external;
function SDL_SetWindowDisplayMode(window: PSDL_Window; const mode: PSDL_DisplayMode): Integer; cdecl; external;
function SDL_GetWindowDisplayMode(window: PSDL_Window; mode: PSDL_DisplayMode): Integer; cdecl; external;
function SDL_GetWindowPixelFormat(window: PSDL_Window): UInt32; cdecl; external;
function SDL_CreateWindow(const title: PChar; x: Integer; y: Integer; w: Integer; h: Integer; flags: UInt32): PSDL_Window; cdecl; external;
function SDL_CreateWindowFrom(const data: Pointer): PSDL_Window; cdecl; external;
function SDL_GetWindowID(window: PSDL_Window): UInt32; cdecl; external;
function SDL_GetWindowFromID(id: UInt32): PSDL_Window; cdecl; external;
function SDL_GetWindowFlags(window: PSDL_Window): UInt32; cdecl; external;
procedure SDL_SetWindowTitle(window: PSDL_Window; const title: PChar); cdecl; external;
function SDL_GetWindowTitle(window: PSDL_Window): PChar; cdecl; external;
procedure SDL_SetWindowIcon(window: PSDL_Window; icon: PSDL_Surface); cdecl; external;
procedure SDL_SetWindowData(window: PSDL_Window; const name: PChar; userdata: Pointer); cdecl; external;
function SDL_GetWindowData(window: PSDL_Window; const name: PChar): Pointer; cdecl; external;
procedure SDL_SetWindowPosition(window: PSDL_Window; x: Integer; y: Integer); cdecl; external;
procedure SDL_GetWindowPosition(window: PSDL_Window; var x: Integer; var y: Integer); cdecl; external;
procedure SDL_SetWindowSize(window: PSDL_Window; w: Integer; h: Integer); cdecl; external;
procedure SDL_GetWindowSize(window: PSDL_Window; var w: Integer; var h: Integer); cdecl; external;
procedure SDL_ShowWindow(window: PSDL_Window); cdecl; external;
procedure SDL_HideWindow(window: PSDL_Window); cdecl; external;
procedure SDL_RaiseWindow(window: PSDL_Window); cdecl; external;
procedure SDL_MaximizeWindow(window: PSDL_Window); cdecl; external;
procedure SDL_MinimizeWindow(window: PSDL_Window); cdecl; external;
procedure SDL_RestoreWindow(window: PSDL_Window); cdecl; external;
function SDL_SetWindowFullscreen(window: PSDL_Window; fullscreen: TSDL_Bool): Integer; cdecl; external;
function SDL_GetWindowSurface(window: PSDL_Window): PSDL_Surface; cdecl; external;
function SDL_UpdateWindowSurface(window: PSDL_Window): Integer; cdecl; external;
function SDL_UpdateWindowSurfaceRects(window: PSDL_Window; rects: PSDL_Rect; numrects: Integer): Integer; cdecl; external;
procedure SDL_SetWindowGrab(window: PSDL_Window; grabbed: TSDL_bool); cdecl; external;
function SDL_GetWindowGrab(window: PSDL_Window): TSDL_bool; cdecl; external;
function SDL_SetWindowBrightness(window: PSDL_Window; brightness: Single): Integer; cdecl; external;
function SDL_GetWindowBrightness(window: PSDL_Window): Single; cdecl; external;
function SDL_SetWindowGammaRamp(window: PSDL_Window; const red: PUInt16; const green: PUInt16; const blue: PUInt16): Integer; cdecl; external;
function SDL_GetWindowGammaRamp(window: PSDL_Window; var red: UInt16; var green: UInt16; var blue: UInt16): Integer; cdecl; external;
procedure SDL_DestroyWindow(window: PSDL_Window); cdecl; external;
function SDL_IsScreenSaverEnabled(): TSDL_Bool; cdecl; external;
procedure SDL_EnableScreenSaver(); cdecl; external;
procedure SDL_DisableScreenSaver(); cdecl; external;
//OpenGL support functions
function SDL_GL_LoadLibrary(const path: PChar): Integer; cdecl; external;
function SDL_GL_GetProcAddress(const proc: PChar): Pointer; cdecl; external;
procedure SDL_GL_UnloadLibrary(); cdecl; external;
function SDL_GL_ExtensionSupported(const extension: PChar): TSDL_Bool; cdecl; external;
function SDL_GL_SetAttribute(attr: TSDL_GLattr; value: Integer): Integer; cdecl; external;
function SDL_GL_GetAttribute(attr: TSDL_GLattr; var value: Integer): Integer; cdecl; external;
function SDL_GL_CreateContext(window: PSDL_Window): PSDL_GLContext; cdecl; external;
function SDL_GL_MakeCurrent(window: PSDL_Window; context: PSDL_GLContext): Integer; cdecl; external;
function SDL_GL_SetSwapInterval(interval: Integer): Integer; cdecl; external;
function SDL_GL_GetSwapInterval(): Integer; cdecl; external;
procedure SDL_GL_SwapWindow(window: PSDL_Window); cdecl; external;
procedure SDL_GL_DeleteContext(context: PSDL_GLContext); cdecl; external;
procedure SDL_GL_SwapBuffers(); cdecl; external;
// End SDL_video.h
// Begin SDL_render.h (Prototypes)
function SDL_GetNumRenderDrivers(): Integer; cdecl; external;
function SDL_GetRenderDriverInfo(index: Integer; var info: TSDL_RendererInfo): Integer; cdecl; external;
function SDL_CreateRenderer(window: PSDL_Window; index: Integer; flags: UInt32): PSDL_Renderer; cdecl; external;
function SDL_CreateSoftwareRenderer(surface: PSDL_Surface): PSDL_Renderer; cdecl; external;
function SDL_GetRenderer(window: PSDL_Window): PSDL_Renderer; cdecl; external;
function SDL_GetRendererInfo(renderer: PSDL_Renderer; var info: TSDL_RendererInfo): Integer; cdecl; external;
function SDL_CreateTexture(renderer: PSDL_Renderer; format: UInt32; access: Integer; w: Integer; h: Integer): PSDL_Texture; cdecl; external;
function SDL_CreateTextureFromSurface(renderer: PSDL_Renderer; surface: PSDL_Surface): PSDL_Texture; cdecl; external;
function SDL_QueryTexture(texture: PSDL_Texture; var format: UInt32; var access: Integer; var w: Integer; var h: Integer): Integer; cdecl; external;
function SDL_SetTextureColorMod(texture: PSDL_Texture; r: UInt8; g: UInt8; b: UInt8): Integer; cdecl; external;
function SDL_GetTextureColorMod(texture: PSDL_Texture; var r: UInt8; var g: UInt8; var b: UInt8): Integer; cdecl; external;
function SDL_SetTextureAlphaMod(texture: PSDL_Texture; alpha: UInt8): Integer; cdecl; external;
function SDL_GetTextureAlphaMod(texture: PSDL_Texture; var alpha: UInt8): Integer; cdecl; external;
function SDL_SetTextureBlendMode(texture: PSDL_Texture; blendMode: TSDL_BlendMode): Integer; cdecl; external;
function SDL_GetTextureBlendMode(texture: PSDL_Texture; var blendMode: TSDL_BlendMode): Integer; cdecl; external;
function SDL_UpdateTexture(texture: PSDL_Texture; const rect: PSDL_Rect; const pixels: Pointer; pitch: Integer): Integer; cdecl; external;
function SDL_LockTexture(texture: PSDL_Texture; const rect: PSDL_Rect; var pixels: Pointer; var pitch: Integer): Integer; cdecl; external;
procedure SDL_UnlockTexture(texture: PSDL_Texture); cdecl; external;
function SDL_RenderSetViewport(renderer: PSDL_Renderer; const rect: PSDL_Rect): Integer; cdecl; external;
procedure SDL_RenderGetViewport(renderer: PSDL_Renderer; var rect: TSDL_Rect); cdecl; external;
function SDL_SetRenderDrawColor(renderer: PSDL_Renderer; r: UInt8; g: UInt8; b: UInt8; a: UInt8): Integer; cdecl; external;
function SDL_GetRenderDrawColor(renderer: PSDL_Renderer; var r: UInt8; var g: UInt8; var b: UInt8; var a: UInt8): Integer; cdecl; external;
function SDL_SetRenderDrawBlendMode(renderer: PSDL_Renderer; blendMode: TSDL_BlendMode): Integer; cdecl; external;
function SDL_GetRenderDrawBlendMode(renderer: PSDL_Renderer; var blendMode: TSDL_BlendMode): Integer; cdecl; external;
function SDL_RenderClear(renderer: PSDL_Renderer): Integer; cdecl; external;
function SDL_RenderDrawPoint(renderer: PSDL_Renderer; x: Integer; y: Integer): Integer; cdecl; external;
function SDL_RenderDrawPoints(renderer: PSDL_Renderer; const points: PSDL_Point; count: Integer): Integer; cdecl; external;
function SDL_RenderDrawLine(renderer: PSDL_Renderer; x1: Integer; y1: Integer; x2: Integer; y2: Integer): Integer; cdecl; external;
function SDL_RenderDrawLines(renderer: PSDL_Renderer; const points: PSDL_Point; count: Integer): Integer; cdecl; external;
function SDL_RenderDrawRect(renderer: PSDL_Renderer; const rect: PSDL_Rect): Integer; cdecl; external;
function SDL_RenderDrawRects(renderer: PSDL_Renderer; const rects: PSDL_Rect; count: Integer): Integer; cdecl; external;
function SDL_RenderFillRect(renderer: PSDL_Renderer; const rect: PSDL_Rect): Integer; cdecl; external;
function SDL_RenderFillRects(renderer: PSDL_Renderer; const rects: PSDL_Rect; count: Integer): Integer; cdecl; external;
function SDL_RenderCopy(renderer: PSDL_Renderer; texture: PSDL_Texture; const srcrect: PSDL_Rect; const dstrect: PSDL_Rect): Integer; cdecl; external;
function SDL_RenderReadPixels(renderer: PSDL_Renderer; const rect: PSDL_Rect; format: UInt32; pixels: Pointer; pitch: Integer): Integer; cdecl; external;
procedure SDL_RenderPresent(renderer: PSDL_Renderer); cdecl; external;
procedure SDL_DestroyTexture(texture: PSDL_Texture); cdecl; external;
procedure SDL_DestroyRenderer(renderer: PSDL_Renderer); cdecl; external;
// End SDL_render.h
function SDL_SelectMouse(index: LongInt): LongInt; cdecl; external;
function SDL_GetRelativeMouseState(index: Integer; var x: Integer; var y: Integer): UInt8; cdecl; external;
function SDL_GetNumMice: LongInt; cdecl; external;
function SDL_PixelFormatEnumToMasks(format: UInt32; bpp: PInteger; Rmask: PUInt32; Gmask: PUInt32; Bmask: PUInt32; Amask: PUInt32): TSDL_Bool; cdecl; external;
function SDL_GetKeyState(numkeys: PLongInt): PByteArray; cdecl; external name 'SDL_GetKeyboardState';
function SDL_GetMouseState(var x: Integer; var y: Integer): UInt8; cdecl; external;
function SDL_GetKeyName(key: Longword): PChar; cdecl; external;
procedure SDL_WarpMouse(x, y: Word); cdecl; external;
procedure SDL_PumpEvents; cdecl; external;
function SDL_PollEvent(event: PSDL_Event): Integer; cdecl; external;
function SDL_WaitEvent(event: PSDL_Event): Integer; cdecl; external;
function SDL_ShowCursor(toggle: LongInt): LongInt; cdecl; external;
procedure SDL_WM_SetCaption(title: PChar; icon: PChar); cdecl; external;
function SDL_WM_ToggleFullScreen(surface: PSDL_Surface): LongInt; cdecl; external;
function SDL_CreateMutex: PSDL_mutex; cdecl; external;
procedure SDL_DestroyMutex(mutex: PSDL_mutex); cdecl; external;
function SDL_LockMutex(mutex: PSDL_mutex): LongInt; cdecl; external name 'SDL_mutexP';
function SDL_UnlockMutex(mutex: PSDL_mutex): LongInt; cdecl; external name 'SDL_mutexV';
function SDL_NumJoysticks: LongInt; cdecl; external;
function SDL_JoystickName(idx: LongInt): PChar; cdecl; external;
function SDL_JoystickOpen(idx: LongInt): PSDL_Joystick; cdecl; external;
function SDL_JoystickOpened(idx: LongInt): LongInt; cdecl; external;
function SDL_JoystickIndex(joy: PSDL_Joystick): LongInt; cdecl; external;
function SDL_JoystickNumAxes(joy: PSDL_Joystick): LongInt; cdecl; external;
function SDL_JoystickNumBalls(joy: PSDL_Joystick): LongInt; cdecl; external;
function SDL_JoystickNumHats(joy: PSDL_Joystick): LongInt; cdecl; external;
function SDL_JoystickNumButtons(joy: PSDL_Joystick): LongInt; cdecl; external;
procedure SDL_JoystickUpdate; cdecl; external;
function SDL_JoystickEventState(state: LongInt): LongInt; cdecl; external;
function SDL_JoystickGetAxis(joy: PSDL_Joystick; axis: LongInt): LongInt; cdecl; external;
function SDL_JoystickGetBall(joy: PSDL_Joystick; ball: LongInt; dx: PInteger; dy: PInteger): Word; cdecl; external;
function SDL_JoystickGetHat(joy: PSDL_Joystick; hat: LongInt): Byte; cdecl; external;
function SDL_JoystickGetButton(joy: PSDL_Joystick; button: LongInt): Byte; cdecl; external;
procedure SDL_JoystickClose(joy: PSDL_Joystick); cdecl; external;
function SDL_LoadBMP(filename: PChar): PSDL_Surface;
function SDL_SaveBMP(surface: PSDL_Surface; filename: PChar): Integer;
function SDL_Define_PixelFormat(type_, order, layout, bits, bytes: UInt32): UInt32;
// Begin SDL_rect.h (Prototypes)
function SDL_RectEmpty(rect: TSDL_Rect): Boolean;
function SDL_RectEquals(rectA, rectB: TSDL_Rect): Boolean;
function SDL_HasIntersection(const A: PSDL_Rect; const B: PSDL_Rect): TSDL_Bool; cdecl; external;
function SDL_IntersectRect(const A: PSDL_Rect; const B: PSDL_Rect; var rResult: TSDL_Rect): TSDL_Bool; cdecl; external;
procedure SDL_UnionRect(const A: PSDL_Rect; const B: PSDL_Rect; var rResult: TSDL_Rect); cdecl; external;
function SDL_EnclosePoints(const points: PSDL_Point; count: Integer; const clip: PSDL_Rect; var rResult : TSDL_Rect): TSDL_Bool; cdecl; external;
function SDL_IntersectRectAndLine(const rect: PSDL_Rect; X1: PInteger; Y1: PInteger; X2: PInteger; Y2: PInteger): TSDL_Bool; cdecl; external;
// End SDL_rect.h
implementation
function SDL_MustLock(Surface: PSDL_Surface): Boolean;
begin
Result := ((surface^.flags and SDL_RLEACCEL) <> 0)
end;
function SDL_LoadBMP(filename: PChar): PSDL_Surface;
begin
Result := SDL_LoadBMP_RW(SDL_RWFromFile(filename, 'rb'), 1);
end;
function SDL_SaveBMP(surface: PSDL_Surface; filename: PChar): Integer;
begin
Result := SDL_SaveBMP_RW(surface, SDL_RWFromFile(filename, 'wb'), 1);
end;
function SDL_Define_PixelFormat(type_, order, layout, bits, bytes: UInt32): UInt32;
begin
Result := ((1 shl 31) or ((type_) shl 24) or ((order) shl 20) or ((layout) shl 16) or ((bits) shl 8) or ((bytes) shl 0));
end;
function SDL_RectEmpty(rect: TSDL_Rect): Boolean;
begin
if (rect.w <= 0) or (rect.h <= 0) then Result := true
else Result := false;
end;
function SDL_RectEquals(rectA, rectB: TSDL_Rect): Boolean;
begin
if (rectA.x = rectB.x) and (rectA.y = rectB.y) and (rectA.w = rectB.w) and (rectA.h = rectB.h) then Result := true
else Result := false;
end;
end.
|
unit ufrmDisplayLastTransactionNo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, ActnList , System.Actions,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage,
cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore,
cxDateUtils, Vcl.Menus, ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC;
type
TfrmDisplayLastTransactionNo = class(TfrmMasterBrowse)
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
private
procedure ParseHeaderGrid();
procedure ParseDataGrid();
public
{ Public declarations }
end;
var
frmDisplayLastTransactionNo: TfrmDisplayLastTransactionNo;
implementation
uses uAppUtils;
const
_kol_Pos_Code : Integer = 0;
_kol_Last_trans : Integer = 1;
_kol_count_no : Integer = 2;
_kol_Active : Integer = 3;
{$R *.dfm}
procedure TfrmDisplayLastTransactionNo.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDisplayLastTransactionNo.FormCreate(Sender: TObject);
begin
inherited;
lblHeader.Caption := 'DISPLAY LAST TRANSACTION NO.';
end;
procedure TfrmDisplayLastTransactionNo.FormDestroy(Sender: TObject);
begin
inherited;
frmDisplayLastTransactionNo := nil;
end;
procedure TfrmDisplayLastTransactionNo.FormShow(Sender: TObject);
begin
inherited;
ParseDataGrid;
// HapusBarisKosong(strgGrid,1);
end;
procedure TfrmDisplayLastTransactionNo.ParseDataGrid;
var
sSql : string;
i : Integer;
begin
ParseHeaderGrid;
// i:=0;
ssql:= ' select setuppos_terminal_code'
+ ' ,trim(substr(setuppos_no_transaksi,1,11)||setuppos_counter_no) notran'
+ ' ,setuppos_counter_no'
+ ' ,setuppos_is_active '
+ ' from setuppos '
// + ' where setuppos_date = ' + TAppUtils.QuotD(cGetServerTime)
+ ' and setuppos_unt_id = ' + IntToStr(MasterNewUnit);
{
with cOpenQuery(sSql) do
begin
while not eof do
begin
i := i + 1 ;
with strgGrid do
begin
RowCount := RowCount + 2;
Cells[_kol_Pos_Code,i] := Fields[0].AsString;
Cells[_kol_Last_trans,i] := Fields[1].AsString;;
Alignments[_kol_Pos_Code,i] := taCenter;
Cells[_kol_count_no,i] := IntToStr(Fields[2].AsInteger);
Alignments[_kol_count_no,i] := taCenter;
Cells[_kol_Active,i] := IntToStr(Fields[3].AsInteger);
Alignments[_kol_Active,i] := taCenter;
end;
Next;
end;
end;
}
end;
procedure TfrmDisplayLastTransactionNo.ParseHeaderGrid;
begin
{
with strgGrid do
begin
Clear;
ColCount := 4;
RowCount := 2;
Cells[0,0] := 'POS CODE';
Cells[1,0] := 'LAST TRANSACTION NO.';
Cells[2,0] := 'LAST COUNTER NO.';
Cells[3,0] := 'ACTIVE/NON ACTIVE';
FixedRows := 1;
AutoSize := true;
end;
}
end;
procedure TfrmDisplayLastTransactionNo.actRefreshExecute(Sender: TObject);
begin
inherited;
ParseDataGrid;
// HapusBarisKosong(strgGrid,1);
end;
end.
|
unit docs.graphics;
interface
uses
Horse,
Horse.GBSwagger;
procedure registry();
implementation
uses schemas.classes;
procedure registry();
begin
Swagger
.Path('graficos/anos')
.Tag('Graficos')
.get('anos que possuem registro de produção', 'anos que possuem registro de produção')
.AddResponse(200)
.Schema(TGraphicsYear)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('graficos/comunidades')
.Tag('Graficos')
.get('comunidade que tem registro de produção', 'comunidade que tem registro de produção em determinado ano')
.AddParamQuery('ano', 'ano')
.Schema(SWAG_STRING)
.&End
.AddResponse(200)
.Schema(TGraphicCommunity)
.isArray(true)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
end;
end.
|
unit pofilestest;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testregistry, mpofiles;
type
TPoFileProt = class(TPoFile); // get access to protected methods
{ TTestPofiles }
TTestPofiles= class(TTestCase)
private
PoFile: TPoFileProt;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConstructor;
procedure TestUpdateCountOnEmptyFile;
procedure TestLoadOkSimpleFile;
procedure TestLoadOkComplexFile;
procedure TestSaveOkSimpleFile;
procedure TestSaveOkComplexFile;
procedure TestOkFlagsFile;
procedure TestFuzzies;
procedure TestOkCommentedFile;
end;
implementation
procedure TTestPofiles.SetUp;
begin
PoFile := TPoFileProt.Create;
end;
procedure TTestPofiles.TearDown;
begin
freeandnil(PoFile);
end;
procedure TTestPofiles.TestConstructor;
begin
AssertEquals('Count:', 0, PoFile.Count);
AssertEquals('ErrorCount', -1, PoFile.ErrorCount);
AssertEquals('AmbiguousCount', -1, PoFile.AmbiguousCount);
AssertEquals('FuzzyCount', -1, PoFile.FuzzyCount);
AssertEquals('EmptyMsgidCount', -1, PoFile.EmptyMsgidCount);
AssertEquals('EmptyMsgstgrCount', -1, PoFile.EmptyMsgstrCount);
AssertEquals('PrevMsgidCount', -1, PoFile.PrevMsgidCount);
AssertEquals('MissingReferenceCount', -1, PoFile.MissingReferenceCount);
AssertEquals('DuplicateReferenceCount', -1, PoFile.DuplicateReferenceCount);
AssertEquals('DuplicateMsgidCount', -1, PoFile.DuplicateMsgidCount);
AssertEquals('DuplicateMsgstrCount', -1, PoFile.DuplicateMsgstrCount);
end;
procedure TTestPofiles.TestUpdateCountOnEmptyFile;
begin
PoFile.UpdateCounts;
AssertEquals('Count:', 0, PoFile.Count);
AssertEquals('ErrorCount', -1, PoFile.ErrorCount);
AssertEquals('AmbiguousCount', 0, PoFile.AmbiguousCount);
AssertEquals('FuzzyCount', 0, PoFile.FuzzyCount);
AssertEquals('EmptyMsgidCount', 0, PoFile.EmptyMsgidCount);
AssertEquals('EmptyMsgstgrCount', 0, PoFile.EmptyMsgstrCount);
AssertEquals('PrevMsgidCount', 0, PoFile.PrevMsgidCount);
AssertEquals('MissingReferenceCount', 0, PoFile.MissingReferenceCount);
AssertEquals('DuplicateReferenceCount', 0, PoFile.DuplicateReferenceCount);
AssertEquals('DuplicateMsgidCount', 0, PoFile.DuplicateMsgidCount);
AssertEquals('DuplicateMsgstrCount', 0, PoFile.DuplicateMsgstrCount);
end;
procedure TTestPofiles.TestLoadOkSimpleFile;
begin
AssertEquals('Count:', 0, PoFile.Count);
AssertEquals('ErrorCount', -1, PoFile.ErrorCount);
PoFile.Filename := 'ok_simple.po.test';
AssertEquals('Count:', 7, PoFile.Count);
AssertEquals('ErrorCount', 0, PoFile.ErrorCount);
PoFile.UpdateCounts;
AssertEquals('AmbiguousCount', 0, PoFile.AmbiguousCount);
AssertEquals('FuzzyCount', 0, PoFile.FuzzyCount);
AssertEquals('EmptyMsgidCount', 0, PoFile.EmptyMsgidCount);
AssertEquals('EmptyMsgstgrCount', 6, PoFile.EmptyMsgstrCount);
AssertEquals('PrevMsgidCount', 0, PoFile.PrevMsgidCount);
AssertEquals('MissingReferenceCount', 0, PoFile.MissingReferenceCount);
AssertEquals('DuplicateReferenceCount', 0, PoFile.DuplicateReferenceCount);
AssertEquals('DuplicateMsgidCount', 0, PoFile.DuplicateMsgidCount);
AssertEquals('DuplicateMsgstrCount', 0, PoFile.DuplicateMsgstrCount);
end;
procedure TTestPofiles.TestLoadOkComplexFile;
var
sl: TStrings;
begin
AssertEquals('Count:', 0, PoFile.Count);
AssertEquals('ErrorCount', -1, PoFile.ErrorCount);
PoFile.Filename := 'ok_complex.po.test';
AssertEquals('Count:', 6, PoFile.Count);
AssertEquals('ErrorCount', 0, PoFile.ErrorCount);
PoFile.UpdateCounts;
AssertEquals('AmbiguousCount', 0, PoFile.AmbiguousCount);
AssertEquals('FuzzyCount', 3, PoFile.FuzzyCount);
AssertEquals('EmptyMsgidCount', 0, PoFile.EmptyMsgidCount);
AssertEquals('EmptyMsgstgrCount', 0, PoFile.EmptyMsgstrCount);
AssertEquals('PrevMsgidCount', 2, PoFile.PrevMsgidCount);
AssertEquals('MissingReferenceCount', 0, PoFile.MissingReferenceCount);
AssertEquals('DuplicateReferenceCount', 0, PoFile.DuplicateReferenceCount);
AssertEquals('DuplicateMsgidCount', 0, PoFile.DuplicateMsgidCount);
AssertEquals('DuplicateMsgstrCount', 0, PoFile.DuplicateMsgstrCount);
sl := TStringList.create;
try
sl.add('');
sl.add('-Broker\n');
sl.add('-Security\n');
AssertEquals('Altmsg', sl.text, PoFile[2].prevmsgid.text);
AssertTrue('Altmsgid[2]', PoFile[2].prevmsgid.Equals(sl));
finally
freeandnil(sl);
end;
PoFile.SaveToFile('out.po');
end;
procedure TTestPofiles.TestSaveOkSimpleFile;
const
tempfilename = 'ok_simple_saved.po';
var
source: TStrings;
copy: TStrings;
begin
PoFile.Filename := 'ok_simple.po.test';
AssertEquals('Count:', 7, PoFile.Count);
PoFile.SaveToFile(tempfilename);
copy := TStringList.create;
try
source := TStringList.create;
try
copy.loadFromFile(tempfilename);
source.loadFromFile('ok_simple.po.test');
// get rid of trailing empty lines
while copy[copy.count-1] = '' do
copy.delete(copy.count-1);
while source[source.count-1] = '' do
source.delete(source.count-1);
AssertTrue('copy = source', copy.Equals(source));
finally
source.free;
end;
finally
copy.free;
deletefile(tempfilename);
end;
end;
procedure TTestPofiles.TestSaveOkComplexFile;
const
tempfilename = 'ok_complex.po';
var
source: TStrings;
copy: TStrings;
begin
PoFile.Filename := tempfilename + '.test';
AssertEquals('Count:', 6, PoFile.Count);
PoFile.SaveToFile(tempfilename);
copy := TStringList.create;
try
source := TStringList.create;
try
copy.loadFromFile(tempfilename);
source.loadFromFile(tempfilename + '.test');
// get rid of trailing empty lines
while copy[copy.count-1] = '' do
copy.delete(copy.count-1);
while source[source.count-1] = '' do
source.delete(source.count-1);
AssertTrue('copy = source', copy.Equals(source));
finally
source.free;
end;
finally
copy.free;
deletefile(tempfilename);
end;
end;
procedure TTestPofiles.TestOkFlagsFile;
const
tempfilename = 'ok_flags.po';
var
source: TStrings;
copy: TStrings;
i: integer;
begin
PoFile.Filename := 'ok_flags.po.test';
AssertEquals('Count:', 6, PoFile.Count);
AssertEquals('ErrorCount', 0, PoFile.ErrorCount);
PoFile.UpdateCounts;
AssertEquals('AmbiguousCount', 0, PoFile.AmbiguousCount);
AssertEquals('FuzzyCount', 4, PoFile.FuzzyCount);
AssertEquals('EmptyMsgidCount', 0, PoFile.EmptyMsgidCount);
AssertEquals('EmptyMsgstgrCount', 0, PoFile.EmptyMsgstrCount);
AssertEquals('PrevMsgidCount', 2, PoFile.PrevMsgidCount);
AssertEquals('MissingReferenceCount', 0, PoFile.MissingReferenceCount);
AssertEquals('DuplicateReferenceCount', 0, PoFile.DuplicateReferenceCount);
AssertEquals('DuplicateMsgidCount', 0, PoFile.DuplicateMsgidCount);
AssertEquals('DuplicateMsgstrCount', 0, PoFile.DuplicateMsgstrCount);
PoFile.SaveToFile(tempfilename);
copy := TStringList.create;
try
source := TStringList.create;
try
copy.loadFromFile(tempfilename);
source.loadFromFile(tempfilename+ '.test');
// get rid of trailing empty lines
while copy[copy.count-1] = '' do
copy.delete(copy.count-1);
while source[source.count-1] = '' do
source.delete(source.count-1);
AssertEquals('source.count', source.count, copy.count);
for i := 0 to source.count-1 do
AssertEquals(Format('line %d', [i]), source[i], copy[i]);
finally
source.free;
end;
finally
copy.free;
deletefile(tempfilename);
end;
end;
procedure TTestPofiles.TestFuzzies;
const
tempfilename = 'ok_flags.po';
var
i: integer;
begin
PoFile.Filename := 'ok_flags.po.test';
AssertEquals('Count:', 6, PoFile.Count);
AssertEquals('ErrorCount', 0, PoFile.ErrorCount);
PoFile.UpdateCounts;
AssertEquals('AmbiguousCount', 0, PoFile.AmbiguousCount);
AssertEquals('FuzzyCount', 4, PoFile.FuzzyCount);
AssertEquals('EmptyMsgidCount', 0, PoFile.EmptyMsgidCount);
AssertEquals('EmptyMsgstgrCount', 0, PoFile.EmptyMsgstrCount);
AssertEquals('PrevMsgidCount', 2, PoFile.PrevMsgidCount);
AssertEquals('MissingReferenceCount', 0, PoFile.MissingReferenceCount);
AssertEquals('DuplicateReferenceCount', 0, PoFile.DuplicateReferenceCount);
AssertEquals('DuplicateMsgidCount', 0, PoFile.DuplicateMsgidCount);
AssertEquals('DuplicateMsgstrCount', 0, PoFile.DuplicateMsgstrCount);
for i := 1 to PoFile.count-1 do
if PoFile[i].isFuzzy then
PoFile[i].isFuzzy := false;
PoFile.UpdateCounts;
AssertEquals('AmbiguousCount', 0, PoFile.AmbiguousCount);
AssertEquals('FuzzyCount', 0, PoFile.FuzzyCount);
AssertEquals('EmptyMsgidCount', 0, PoFile.EmptyMsgidCount);
AssertEquals('EmptyMsgstgrCount', 0, PoFile.EmptyMsgstrCount);
AssertEquals('PrevMsgidCount', 2, PoFile.PrevMsgidCount);
AssertEquals('MissingReferenceCount', 0, PoFile.MissingReferenceCount);
AssertEquals('DuplicateReferenceCount', 0, PoFile.DuplicateReferenceCount);
AssertEquals('DuplicateMsgidCount', 0, PoFile.DuplicateMsgidCount);
AssertEquals('DuplicateMsgstrCount', 0, PoFile.DuplicateMsgstrCount);
//PoFile.SaveToFile(tempfilename);
end;
procedure TTestPofiles.TestOkCommentedFile;
const
tempfilename = 'ok_commented.po';
var
source: TStrings;
copy: TStrings;
i: integer;
src: string;
begin
PoFile.Filename := tempfilename + '.test';
AssertEquals('Count:', 6, PoFile.Count);
AssertEquals('ErrorCount', 0, PoFile.ErrorCount);
PoFile.UpdateCounts;
AssertEquals('AmbiguousCount', 0, PoFile.AmbiguousCount);
AssertEquals('FuzzyCount', 3, PoFile.FuzzyCount);
AssertEquals('EmptyMsgidCount', 0, PoFile.EmptyMsgidCount);
AssertEquals('EmptyMsgstgrCount', 0, PoFile.EmptyMsgstrCount);
AssertEquals('PrevMsgidCount', 2, PoFile.PrevMsgidCount);
AssertEquals('MissingReferenceCount', 0, PoFile.MissingReferenceCount);
AssertEquals('DuplicateReferenceCount', 0, PoFile.DuplicateReferenceCount);
AssertEquals('DuplicateMsgidCount', 0, PoFile.DuplicateMsgidCount);
AssertEquals('DuplicateMsgstrCount', 0, PoFile.DuplicateMsgstrCount);
PoFile.SaveToFile(tempfilename); // compare files!
copy := TStringList.create;
try
source := TStringList.create;
try
copy.loadFromFile(tempfilename);
source.loadFromFile(tempfilename+ '.test');
// get rid of trailing empty lines
while copy[copy.count-1] = '' do
copy.delete(copy.count-1);
while source[source.count-1] = '' do
source.delete(source.count-1);
AssertEquals('source.count', source.count, copy.count);
for i := 0 to source.count-1 do begin
src := source[i];
if src = '#' then src := '# ';
AssertEquals(Format('line %d', [i]), src, copy[i]);
end;
finally
source.free;
end;
finally
copy.free;
deletefile(tempfilename);
end;
end;
initialization
RegisterTest(TTestPofiles);
end.
|
unit Unit1;
interface
uses
Winapi.OpenGL,
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
//GLS
GLTexture,
GLWin32Viewer,
GLScene,
GLVectorTypes,
GLVectorFileObjects,
GLFile3ds,
GLObjects,
GLMaterial,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses,
GLRenderContextInfo;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLMaterialLibrary1: TGLMaterialLibrary;
ButtonCube: TButton;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
GLFreeForm: TGLFreeForm;
GLDummyCube1: TGLDummyCube;
procedure ButtonCubeClick(Sender: TObject);
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLDirectOpenGL1Render(var rci: TGLRenderContextInfo);
private
FOldX,
FOldY : Integer;
procedure CreateCube;
public
end;
var
Form1: TForm1;
type
TFaceProperties = Record
Normal3f : TVector3f;
Vertices : Array[0..3] of TVector3f;
TexCoords : Array[0..3] of TVector2f;
FaceIndex : Array[0..5] of Integer;
Material : String;
end;
const
CCubeConstruct : array[0..5] of TFaceProperties =
(
( // Front Face
Vertices : (
(X:-1;Y:-1;Z:1),
(X:1;Y:-1;Z:1),
(X:1;Y:1;Z:1),
(X:-1;Y:1;Z:1)
);
TexCoords : (
(X:0;Y:0),
(X:1;Y:0),
(X:1;Y:1),
(X:0;Y:1)
);
FaceIndex : (0, 1, 2, 2, 3, 0);
Material : 'LibMaterial';
),
( // Back Face
Vertices : (
(X:-1;Y:-1;Z:-1),
(X:-1;Y:1;Z:-1),
(X:1;Y:1;Z:-1),
(X:1;Y:-1;Z:-1)
);
TexCoords : (
(X:1;Y:0),
(X:1;Y:1),
(X:0;Y:1),
(X:0;Y:0)
);
FaceIndex : (4, 5, 6, 6, 7, 4);
Material : 'LibMaterial1';
),
( // Top Face
Vertices : (
(X:-1;Y:1;Z:-1),
(X:-1;Y:1;Z:1),
(X:1;Y:1;Z:1),
(X:1;Y:1;Z:-1)
);
TexCoords : (
(X:0;Y:1),
(X:0;Y:0),
(X:1;Y:0),
(X:1;Y:1)
);
FaceIndex : (8, 9, 10, 10, 11, 8);
Material : 'LibMaterial2';
),
( // Bottom Face
Vertices : (
(X:-1;Y:-1;Z:-1),
(X:1;Y:-1;Z:-1),
(X:1;Y:-1;Z:1),
(X:-1;Y:-1;Z:1)
);
TexCoords : (
(X:1;Y: 1),
(X:0;Y:1),
(X:0;Y:0),
(X:1;Y:0)
);
FaceIndex : (12, 13, 14, 14, 15, 12);
Material : 'LibMaterial3';
),
( // Right Face
Vertices : (
(X:1;Y:-1;Z:-1),
(X:1;Y:1;Z:-1),
(X:1;Y:1;Z:1),
(X:1;Y:-1;Z:1)
);
TexCoords : (
(X:1;Y:0),
(X:1;Y:1),
(X:0;Y:1),
(X:0;Y:0)
);
FaceIndex : (16, 17, 18, 18, 19, 16);
Material : 'LibMaterial4';
),
( // Right Face
Vertices : (
(X:-1;Y:-1;Z:-1),
(X:-1;Y:-1;Z:1),
(X:-1;Y:1;Z:1),
(X:-1;Y:1;Z:-1)
);
TexCoords : (
(X:0;Y:0),
(X:1;Y:0),
(X:1;Y:1),
(X:0;Y:1)
);
FaceIndex : (20, 21, 22, 22, 23, 20);
Material : 'LibMaterial5';
)
);
implementation
uses GLVectorLists, JPEG;
{$R *.dfm}
procedure TForm1.ButtonCubeClick(Sender: TObject);
begin
CreateCube;
end;
procedure TForm1.CreateCube;
var
lMeshObj : TMeshObject;
lFaceGroup : TFGVertexIndexList;
i, j : Integer;
begin
{Create Mesh Object}
lMeshObj := TMeshObject.CreateOwned(GLFreeForm.MeshObjects);
lMeshObj.Mode := momFaceGroups;
for i := Low(CCubeConstruct) to High(CCubeConstruct) do
begin
{Add the vertices}
for j := Low(CCubeConstruct[i].Vertices) to High(CCubeConstruct[i].Vertices) do
lMeshObj.Vertices.Add(CCubeConstruct[i].Vertices[j]);
{Add texture coordinates}
for j := Low(CCubeConstruct[i].TexCoords) to High(CCubeConstruct[i].TexCoords) do
lMeshObj.TexCoords.Add(CCubeConstruct[i].TexCoords[j]);
lFaceGroup := TFGVertexIndexList.CreateOwned(lMeshObj.FaceGroups);
for j := Low(CCubeConstruct[i].FaceIndex) to High(CCubeConstruct[i].FaceIndex) do
lFaceGroup.Add(CCubeConstruct[i].FaceIndex[j]);
lFaceGroup.MaterialName := CCubeConstruct[i].Material;
end;
GLFreeForm.StructureChanged;
GLSceneViewer1.RecreateWnd;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
FOldX := X;
FOldY := Y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then
begin
GLCamera1.MoveAroundTarget(FOldY - Y, FOldX - X);
FOldX := X;
FOldY := Y;
end;
end;
procedure TForm1.GLDirectOpenGL1Render(var rci: TGLRenderContextInfo);
begin
glBegin(GL_QUADS);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f( 1.0, -1.0, 1.0);
glVertex3f( 1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, 1.0);
glEnd();
end;
end.
|
{
Copyright (c) 2020 Adrian Siekierka
Based on a reconstruction of code from ZZT,
Copyright 1991 Epic MegaGames, used with permission.
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.
}
{$I-}
unit ZVideo;
interface
type
TVideoLine = string[80];
TScreenCopyLine = string[200];
var
VideoEightColor: boolean;
VideoMonochrome: boolean;
VideoBlinkMask: byte;
function VideoConfigure: boolean;
procedure VideoWriteText(x, y, color: byte; text: TVideoLine);
procedure VideoInstall(borderColor: integer);
procedure VideoUninstall;
procedure VideoShowCursor;
procedure VideoHideCursor;
procedure VideoSetBorderColor(value: integer);
procedure VideoSetBlink(value: boolean);
procedure VideoMove(x, y, chars: integer; data: pointer; toVideo: boolean);
procedure VideoInvert(x1, y1, x2, y2: integer);
implementation
uses Dos, PC98;
{$I VIDCONST.INC}
procedure VideoWriteText(x, y, color: byte; text: TVideoLine);
var
attr: word;
i, offset: integer;
begin
offset := (y * 80 + x) * 2;
if ((color and $70) shr 4) = (color and $0F) then begin
{ Same color. }
attr := ATTR_MAP[color and $70];
for i := 1 to Length(text) do begin
MemW[$A000:offset] := $0020;
MemW[$A200:offset] := attr;
Inc(offset, 2);
end;
end else begin
attr := ATTR_MAP[color and $7F] or (((color and $80) shr 6) and VideoBlinkMask);
for i := 1 to Length(text) do begin
MemW[$A000:offset] := CP437_MAP[Ord(text[i])];
MemW[$A200:offset] := attr;
Inc(offset, 2);
end;
end;
end;
function VideoConfigure: boolean;
begin
VideoConfigure := True;
end;
procedure VideoInstall(borderColor: integer);
var
regs: Registers;
begin
{ TODO }
ClrScr;
end;
procedure VideoUninstall;
var
regs: Registers;
begin
{ TODO }
ClrScr;
end;
procedure VideoShowCursor;
var
regs: Registers;
begin
regs.AH := $11;
Intr($18, regs);
end;
procedure VideoHideCursor;
var
regs: Registers;
begin
regs.AH := $12;
Intr($18, regs);
end;
procedure VideoSetBorderColor(value: integer);
begin
{ TODO }
end;
{ TODO: This doesn't update existing characters. }
procedure VideoSetBlink(value: boolean);
begin
if value then
VideoBlinkMask := $FF
else
VideoBlinkMask := $00;
end;
procedure VideoMove(x, y, chars: integer; data: pointer; toVideo: boolean);
var
offset: integer;
begin
offset := (y * 80 + x) * 2;
if toVideo then begin
Move(data^, Ptr($A000, offset)^, chars * 2);
Move(Ptr(Seg(data^), Ofs(data^) + (chars * 2))^, Ptr($A200, offset)^, chars * 2);
end else begin
Move(Ptr($A000, offset)^, data^, chars * 2);
Move(Ptr($A200, offset)^, Ptr(Seg(data^), Ofs(data^) + (chars * 2))^, chars * 2);
end
end;
procedure VideoInvert(x1, y1, x2, y2: integer);
var
ix, iy, offset: integer;
begin
if x2 < x1 then begin
ix := x1;
x1 := x2;
x2 := ix;
end;
if y2 < y1 then begin
ix := y1;
y1 := y2;
y2 := ix;
end;
for iy := y1 to y2 do begin
offset := ((iy * 80) + x1) shl 1;
for ix := x1 to x2 do begin
MemW[$A200:offset] := MemW[$A200:offset] xor $04;
Inc(offset, 2);
end;
end;
end;
begin
VideoEightColor := true;
VideoMonochrome := false;
VideoBlinkMask := $FF;
SetCBreak(false);
end.
|
unit FornecedorProduto;
interface
uses
Fornecedor, DBXJSONReflect, RTTI, DBXPlatform;
type
TDoubleInterceptor = class(TJSONInterceptor)
public
function StringConverter(Data: TObject; Field: string): string; override;
procedure StringReverter(Data: TObject; Field: string; Arg: string); override;
end;
TFornecedorProduto = class
private
FFornecedor: TFornecedor;
[JSONReflect(ctString, rtString, TDoubleInterceptor, nil, true)]
FPrecoCompra: Currency;
public
property Fornecedor: TFornecedor read FFornecedor write FFornecedor;
property PrecoCompra: Currency read FPrecoCompra write FPrecoCompra;
constructor Create; overload;
constructor Create(Fornecedor: TFornecedor; PrecoCompra: Currency); overload;
end;
implementation
{ TFornecedorProduto }
constructor TFornecedorProduto.Create;
begin
end;
constructor TFornecedorProduto.Create(Fornecedor: TFornecedor; PrecoCompra: Currency);
begin
Self.Fornecedor := Fornecedor;
Self.FPrecoCompra := PrecoCompra;
end;
{ TDoubleInterceptor }
function TDoubleInterceptor.StringConverter(Data: TObject; Field: string): string;
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := LRttiContext.GetType(Data.ClassType).GetField(Field).GetValue(Data).AsType<Double>;
Result := TDBXPlatform.JsonFloat(LValue);
end;
procedure TDoubleInterceptor.StringReverter(Data: TObject; Field, Arg: string);
var
LRttiContext: TRttiContext;
LValue: Double;
begin
LValue := TDBXPlatform.JsonToFloat(Arg);
LRttiContext.GetType(Data.ClassType).GetField(Field).SetValue(Data, TValue.From<Double>(LValue));
end;
end.
|
unit uFrmDadosProduto;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmDadosMasterDetailBase, ComCtrls, StdCtrls, Buttons, ExtCtrls, Grids,
DBGrids, Produto, TipoProduto, DBClient, uProdutoDAOClient, Mask,
Spin, uEstoqueDAOClient, Estoque, DB, FornecedorProduto,
Generics.Collections, Fornecedor, uFramePesquisaTipoProduto, Validade,
DXPCurrencyEdit, RxToolEdit, RxCurrEdit;
type
TFrmDadosProduto = class(TFrmDadosMasterDetailBase)
tbsFornecedores: TTabSheet;
grdFornecedores: TDBGrid;
Label1: TLabel;
edtCodigo: TEdit;
Label4: TLabel;
edtCodigoBarras: TEdit;
dsFornecedores: TDataSource;
cdsFornecedores: TClientDataSet;
cdsFornecedoresCODIGO_FORNECEDOR: TStringField;
cdsFornecedoresNOME_FORNECEDOR: TStringField;
cdsFornecedoresPRECO_COMPRA: TCurrencyField;
bbtGerarCodigoBarras: TBitBtn;
Label2: TLabel;
edtDescricao: TEdit;
Label5: TLabel;
gbEstoque: TGroupBox;
Label6: TLabel;
sedQuantidadeEstoque: TSpinEdit;
FramePesquisaTipoProduto: TFramePesquisaTipoProduto;
tbsValidades: TTabSheet;
grdValidades: TDBGrid;
Panel1: TPanel;
dsValidades: TDataSource;
cdsValidades: TClientDataSet;
cdsValidadesDATA: TDateTimeField;
Label3: TLabel;
sedEstoqueMinimo: TSpinEdit;
Label7: TLabel;
edtEndereco: TEdit;
cedPrecoVenda: TCurrencyEdit;
Label8: TLabel;
cedMargemLucro: TCurrencyEdit;
GroupBox1: TGroupBox;
Label9: TLabel;
cedDescontoMaximoValor: TCurrencyEdit;
Label10: TLabel;
cedDescontoMaximoPercentual: TCurrencyEdit;
Label11: TLabel;
Label12: TLabel;
procedure sbtNovoClick(Sender: TObject);
procedure sbtEditarClick(Sender: TObject);
procedure sbtExcluirClick(Sender: TObject);
procedure bbtGerarCodigoBarrasClick(Sender: TObject);
procedure edtCodigoBarrasExit(Sender: TObject);
procedure cedMargemLucroExit(Sender: TObject);
procedure cdsFornecedoresAfterPost(DataSet: TDataSet);
procedure cedPrecoVendaExit(Sender: TObject);
private
{ Private declarations }
DAOClient: TProdutoDAOClient;
DAOClientEstoque: TEstoqueDAOClient;
QuantidadeAnterior: Integer;
function MaiorPrecoCompra: Currency;
procedure CalculaPrecoVendaComMargemLucro;
procedure CalculaMargemLucro;
protected
procedure OnCreate; override;
procedure OnDestroy; override;
procedure OnSave; override;
procedure OnShow; override;
public
{ Public declarations }
Produto: TProduto;
end;
var
FrmDadosProduto: TFrmDadosProduto;
implementation
uses MensagensUtils, TypesUtils, StringUtils, uFrmDadosFornecedorProduto,
ufrmDadosValidade;
{$R *.dfm}
{ TFrmDadosProduto }
procedure TFrmDadosProduto.bbtGerarCodigoBarrasClick(Sender: TObject);
begin
inherited;
edtCodigoBarras.Text := DAOClient.NextCodigoBarras;
end;
procedure TFrmDadosProduto.CalculaMargemLucro;
var
precoCompra: Currency;
begin
if cedPrecoVenda.Value > 0 then
begin
precoCompra := MaiorPrecoCompra;
cedMargemLucro.Value := (100 * (cedPrecoVenda.Value - precoCompra)) / precoCompra;
end;
end;
procedure TFrmDadosProduto.CalculaPrecoVendaComMargemLucro;
var
precoCompra: Currency;
begin
if (cedMargemLucro.Value > 0) and (cedPrecoVenda.Value = 0) and not(cdsFornecedores.IsEmpty) then
begin
precoCompra := MaiorPrecoCompra;
cedPrecoVenda.Value := precoCompra + (precoCompra * (cedMargemLucro.Value / 100));
end;
end;
procedure TFrmDadosProduto.cdsFornecedoresAfterPost(DataSet: TDataSet);
begin
inherited;
CalculaPrecoVendaComMargemLucro;
end;
procedure TFrmDadosProduto.cedMargemLucroExit(Sender: TObject);
begin
inherited;
CalculaPrecoVendaComMargemLucro;
end;
procedure TFrmDadosProduto.cedPrecoVendaExit(Sender: TObject);
begin
inherited;
CalculaMargemLucro;
end;
procedure TFrmDadosProduto.edtCodigoBarrasExit(Sender: TObject);
begin
inherited;
if (Operacao = opInsert) and (edtCodigoBarras.Text <> '') and (DAOClient.ExisteCodigoBarras(edtCodigoBarras.Text)) then
begin
Atencao('Já existe um produto cadastrado com este código de barras.');
edtCodigoBarras.SetFocus;
end;
end;
function TFrmDadosProduto.MaiorPrecoCompra: Currency;
begin
cdsFornecedores.DisableControls;
cdsFornecedores.IndexFieldNames := 'PRECO_COMPRA';
cdsFornecedores.Last;
Result := cdsFornecedoresPRECO_COMPRA.AsCurrency;
cdsFornecedores.IndexFieldNames := 'CODIGO_FORNECEDOR';
cdsFornecedores.EnableControls;
end;
procedure TFrmDadosProduto.OnCreate;
begin
inherited;
SetCamposObrigatorios([edtDescricao, FramePesquisaTipoProduto.edtCodigoTipoProduto]);
DAOClient := TProdutoDAOClient.Create(DBXConnection);
DAOClientEstoque := TEstoqueDAOClient.Create(DBXConnection);
end;
procedure TFrmDadosProduto.OnDestroy;
begin
inherited;
DAOClient.Free;
DAOClientEstoque.Free;
end;
procedure TFrmDadosProduto.OnSave;
var
cds: TClientDataSet;
Produto: TProduto;
begin
inherited;
cds := TClientDataSet(Owner.FindComponent('cdsCrud'));
Produto := TProduto.Create(edtCodigo.Text,
TTipoProduto.Create(FramePesquisaTipoProduto.edtCodigoTipoProduto.Text,
FramePesquisaTipoProduto.edtDescricaoTipoProduto.Text),
edtDescricao.Text,
edtCodigoBarras.Text,
cedPrecoVenda.Value,
sedEstoqueMinimo.Value,
nil,
nil,
edtEndereco.Text,
cedMargemLucro.Value,
cedDescontoMaximoValor.Value,
cedDescontoMaximoPercentual.Value);
cdsFornecedores.DisableControls;
cdsFornecedores.First;
Produto.Fornecedores := TList<TFornecedorProduto>.Create;
while not(cdsFornecedores.Eof) do
begin
Produto.Fornecedores.Add(TFornecedorProduto.Create(TFornecedor.Create(cdsFornecedoresCODIGO_FORNECEDOR.AsString,
cdsFornecedoresNOME_FORNECEDOR.AsString,
''),
cdsFornecedoresPRECO_COMPRA.AsCurrency));
cdsFornecedores.Next;
end;
cdsFornecedores.EnableControls;
cdsValidades.DisableControls;
cdsValidades.First;
Produto.Validades := TList<TValidade>.Create;
while not(cdsValidades.Eof) do
begin
Produto.Validades.Add(TValidade.Create(cdsValidadesDATA.AsDateTime));
cdsValidades.Next;
end;
cdsValidades.EnableControls;
if (Operacao = opInsert) then
begin
edtCodigo.Text := DAOClient.NextCodigo;
Produto.Codigo := edtCodigo.Text;
if (DAOClient.Insert(Produto)) then
DAOClientEstoque.Insert(TEstoque.Create(TProduto.Create(edtCodigo.Text), sedQuantidadeEstoque.Value))
else
Erro('Ocorreu algum erro durante a inclusão.');
cds.Append;
cds.FieldByName('CODIGO').AsString := edtCodigo.Text;
cds.FieldByName('DESCRICAO').AsString := edtDescricao.Text;
cds.FieldByName('CODIGO_TIPO_PRODUTO').AsString := FramePesquisaTipoProduto.edtCodigoTipoProduto.Text;
cds.FieldByName('DESCRICAO_TIPO_PRODUTO').AsString := FramePesquisaTipoProduto.edtDescricaoTipoProduto.Text;
cds.FieldByName('CODIGO_BARRAS').AsString := edtCodigoBarras.Text;
cds.FieldByName('MARGEM_LUCRO').AsCurrency := cedMargemLucro.Value;
cds.FieldByName('PRECO_VENDA').AsCurrency := cedPrecoVenda.Value;
cds.FieldByName('DESCONTO_MAXIMO_VALOR').AsCurrency := cedDescontoMaximoValor.Value;
cds.FieldByName('DESCONTO_MAXIMO_PERCENTUAL').AsCurrency := cedDescontoMaximoPercentual.Value;
cds.FieldByName('QUANTIDADE').AsInteger := sedQuantidadeEstoque.Value;
cds.FieldByName('ESTOQUE_MINIMO').AsInteger := sedEstoqueMinimo.Value;
cds.FieldByName('ENDERECO').AsString := edtEndereco.Text;
cds.Post;
if chbContinuarIncluindo.Checked then
begin
cdsFornecedores.EmptyDataSet;
cdsValidades.EmptyDataSet;
end;
end
else
begin
if (DAOClient.Update(Produto)) then
begin
if (QuantidadeAnterior <> sedQuantidadeEstoque.Value) then
DAOClientEstoque.Update(TEstoque.Create(TProduto.Create(edtCodigo.Text), sedQuantidadeEstoque.Value));
end
else
Erro('Ocorreu algum erro durante a alteração.');
cds.Edit;
cds.FieldByName('CODIGO').AsString := edtCodigo.Text;
cds.FieldByName('DESCRICAO').AsString := edtDescricao.Text;
cds.FieldByName('CODIGO_TIPO_PRODUTO').AsString := FramePesquisaTipoProduto.edtCodigoTipoProduto.Text;
cds.FieldByName('DESCRICAO_TIPO_PRODUTO').AsString := FramePesquisaTipoProduto.edtDescricaoTipoProduto.Text;
cds.FieldByName('CODIGO_BARRAS').AsString := edtCodigoBarras.Text;
cds.FieldByName('MARGEM_LUCRO').AsCurrency := cedMargemLucro.Value;
cds.FieldByName('PRECO_VENDA').AsCurrency := cedPrecoVenda.Value;
cds.FieldByName('DESCONTO_MAXIMO_VALOR').AsCurrency := cedDescontoMaximoValor.Value;
cds.FieldByName('DESCONTO_MAXIMO_PERCENTUAL').AsCurrency := cedDescontoMaximoPercentual.Value;
cds.FieldByName('QUANTIDADE').AsInteger := sedQuantidadeEstoque.Value;
cds.FieldByName('ESTOQUE_MINIMO').AsInteger := sedEstoqueMinimo.Value;
cds.FieldByName('ENDERECO').AsString := edtEndereco.Text;
cds.Post;
end;
end;
procedure TFrmDadosProduto.OnShow;
var
Fornecedor: TFornecedorProduto;
Validade: TValidade;
begin
inherited;
cdsFornecedores.CreateDataSet;
cdsValidades.CreateDataSet;
if (Assigned(Produto)) then
begin
try
edtCodigo.Text := Produto.Codigo;
edtDescricao.Text := Produto.Descricao;
FramePesquisaTipoProduto.edtCodigoTipoProduto.Text := Produto.TipoProduto.Codigo;
FramePesquisaTipoProduto.edtDescricaoTipoProduto.Text := Produto.TipoProduto.Descricao;
edtCodigoBarras.Text := Produto.CodigoBarras;
cedMargemLucro.Value := Produto.MargemLucro;
cedPrecoVenda.Value := Produto.PrecoVenda;
edtEndereco.Text := Produto.Endereco;
cedDescontoMaximoValor.Value := Produto.DescontoMaximoValor;
cedDescontoMaximoPercentual.Value := Produto.DescontoMaximoPercentual;
sedEstoqueMinimo.Value := Produto.EstoqueMinimo;
sedQuantidadeEstoque.Value := Produto.QuantidadeEstoque;
QuantidadeAnterior := Produto.QuantidadeEstoque;
for Fornecedor in DAOClient.ListFornecedoresByProduto(Produto.Codigo) do
begin
cdsFornecedores.Append;
cdsFornecedoresCODIGO_FORNECEDOR.AsString := Fornecedor.Fornecedor.Codigo;
cdsFornecedoresNOME_FORNECEDOR.AsString := Fornecedor.Fornecedor.Nome;
cdsFornecedoresPRECO_COMPRA.AsCurrency := Fornecedor.PrecoCompra;
cdsFornecedores.Post;
end;
cdsFornecedores.First;
for Validade in DAOClient.ListValidadesByProduto(Produto.Codigo) do
begin
cdsValidades.Append;
cdsValidadesDATA.AsDateTime := Validade.Data;
cdsValidades.Post;
end;
cdsValidades.First;
finally
Produto.Free;
end;
end;
end;
procedure TFrmDadosProduto.sbtNovoClick(Sender: TObject);
var
fFornecedor: TFrmDadosFornecedorProduto;
fValidade: TFrmDadosValidade;
begin
inherited;
case pgcDetail.ActivePageIndex of
0: begin
fFornecedor := TFrmDadosFornecedorProduto.Create(Self);
try
fFornecedor.Operacao := opInsert;
fFornecedor.ShowModal;
finally
fFornecedor.Free;
end;
end;
1: begin
fValidade := TFrmDadosValidade.Create(Self);
try
fValidade.Operacao := opInsert;
fValidade.ShowModal;
finally
fValidade.Free;
end;
end;
end;
end;
procedure TFrmDadosProduto.sbtEditarClick(Sender: TObject);
var
fFornecedor: TFrmDadosFornecedorProduto;
fValidade: TFrmDadosValidade;
begin
inherited;
case pgcDetail.ActivePageIndex of
0: begin
fFornecedor := TFrmDadosFornecedorProduto.Create(Self);
try
fFornecedor.FornecedorProduto := TFornecedorProduto.Create;
fFornecedor.FornecedorProduto.Fornecedor := TFornecedor.Create;
fFornecedor.FornecedorProduto.Fornecedor.Codigo := cdsFornecedoresCODIGO_FORNECEDOR.AsString;
fFornecedor.FornecedorProduto.Fornecedor.Nome := cdsFornecedoresNOME_FORNECEDOR.AsString;
fFornecedor.FornecedorProduto.PrecoCompra := cdsFornecedoresPRECO_COMPRA.AsCurrency;
fFornecedor.Operacao := opEdit;
fFornecedor.ShowModal;
finally
fFornecedor.Free;
end;
end;
1: begin
fValidade := TFrmDadosValidade.Create(Self);
try
fValidade.Validade := TValidade.Create;
fValidade.Validade.Data := cdsValidadesDATA.AsDateTime;
fValidade.Operacao := opEdit;
fValidade.ShowModal;
finally
fValidade.Free;
end;
end;
end;
end;
procedure TFrmDadosProduto.sbtExcluirClick(Sender: TObject);
begin
inherited;
case pgcDetail.ActivePageIndex of
0: cdsFornecedores.Delete;
1: cdsValidades.Delete;
end;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.AddInOptionsFrame;
interface
{$I 'DPMIDE.inc'}
uses
Winapi.Windows,
Winapi.Messages,
System.Variants,
System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.CheckLst,
Vcl.Buttons, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.StdCtrls,
{$IFDEF USEIMAGECOLLECTION }
Vcl.VirtualImageList,
Vcl.ImageCollection,
{$ELSE}
Vcl.Imaging.pngimage,
{$ENDIF}
DPM.Core.Logging,
DPM.Core.Configuration.Interfaces,
DPM.IDE.Options, Vcl.Samples.Spin, Vcl.ImgList, Vcl.ActnList, System.Actions, System.ImageList;
{$WARN SYMBOL_PLATFORM OFF}
type
TDPMOptionsFrame = class(TFrame)
Panel1 : TPanel;
dpmOptionsActionList : TActionList;
Panel2 : TPanel;
Panel3 : TPanel;
lvSources : TListView;
Label1 : TLabel;
txtName : TEdit;
Label2 : TLabel;
lblPackageSources: TLabel;
Label3 : TLabel;
txtPackageCacheLocation : TButtonedEdit;
txtUri : TButtonedEdit;
actAddSource : TAction;
actRemoveSource : TAction;
actMoveSourceUp : TAction;
actMoveSourceDown : TAction;
btnAdd: TSpeedButton;
btnRemove: TSpeedButton;
btnUp: TSpeedButton;
btnDown: TSpeedButton;
Label5 : TLabel;
Label6 : TLabel;
txtUserName : TEdit;
txtPassword : TEdit;
FolderSelectDialog : TFileOpenDialog;
cboSourceType : TComboBox;
Label8 : TLabel;
pgOptions: TPageControl;
tsSources: TTabSheet;
tsIDEOptions: TTabSheet;
Label4: TLabel;
cboLogLevel: TComboBox;
Label7: TLabel;
chkShowForRestore: TCheckBox;
chkShowForInstall: TCheckBox;
chkShowForUninstall: TCheckBox;
chkAutoClose: TCheckBox;
spAutoCloseDelay: TSpinEdit;
Label9: TLabel;
pnlIDEOptions: TPanel;
Label10: TLabel;
chkShowOnProjectTree: TCheckBox;
Label11: TLabel;
procedure lvSourcesSelectItem(Sender : TObject; Item : TListItem; Selected : Boolean);
procedure txtNameChange(Sender : TObject);
procedure txtUriChange(Sender : TObject);
procedure actAddSourceExecute(Sender : TObject);
procedure actRemoveSourceExecute(Sender : TObject);
procedure dpmOptionsActionListUpdate(Action : TBasicAction; var Handled : Boolean);
procedure actMoveSourceUpExecute(Sender : TObject);
procedure actMoveSourceDownExecute(Sender : TObject);
procedure txtUserNameChange(Sender : TObject);
procedure txtPasswordChange(Sender : TObject);
procedure txtPackageCacheLocationRightButtonClick(Sender : TObject);
procedure txtUriRightButtonClick(Sender : TObject);
procedure cboSourceTypeChange(Sender : TObject);
procedure chkAutoCloseClick(Sender: TObject);
private
{ Private declarations }
FConfigFile : string;
FConfigManager : IConfigurationManager;
FConfiguration : IConfiguration;
FLogger : ILogger;
FIDEOptions : IDPMIDEOptions;
{$IFDEF USEIMAGECOLLECTION }
FImageList : TVirtualImageList;
FImageCollection : TImageCollection;
{$ELSE}
FImageList : TImageList;
{$ENDIF}
protected
procedure ExchangeItems(const a, b : Integer);
procedure LoadImages;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
{ Public declarations }
procedure LoadSettings;
procedure SaveSettings;
procedure Configure(const manager : IConfigurationManager; const ideOptions : IDPMIDEOptions; const logger : ILogger; const configFile : string = '');
function Validate : boolean;
end;
//Note not using virtual mode on list view as it doesn't do checkboxes???
implementation
uses
Winapi.CommCtrl,
System.SysUtils,
System.TypInfo,
VSoft.Uri,
DPM.Core.Types,
DPM.Core.Configuration.Classes,
DPM.Core.Utils.Config,
DPM.Core.Utils.Enum;
{$R *.dfm}
const
cPackageSources = 'DPM Package Sources';
cNoPackageSources = cPackageSources + ' - click [+] to create one.' ;
{ TDPMOptionsFrame }
procedure TDPMOptionsFrame.actAddSourceExecute(Sender : TObject);
var
newItem : TListItem;
begin
cboSourceType.ItemIndex := 0; //TODO : change this to default to DPMServer/Https when we have a server.
newItem := lvSources.Items.Add;
newItem.Caption := 'New Source';
newItem.Checked := true;
newItem.SubItems.Add(''); //uri
newItem.SubItems.Add(cboSourceType.Items[cboSourceType.ItemIndex]);
newItem.SubItems.Add(''); //username
newItem.SubItems.Add(''); //password
lvSources.ItemIndex := newItem.Index;
lblPackageSources.Caption := cPackageSources;
end;
procedure TDPMOptionsFrame.actMoveSourceDownExecute(Sender : TObject);
var
selected : TListItem;
begin
selected := lvSources.Selected;
if selected = nil then
exit;
ExchangeItems(selected.Index, selected.Index + 1);
lvSources.ItemIndex := selected.Index + 1;
end;
procedure TDPMOptionsFrame.ExchangeItems(const a, b : Integer);
var
tmpItem : TListItem;
begin
lvSources.Items.BeginUpdate;
try
tmpItem := lvSources.Items.Add;
tmpItem.Assign(lvSources.Items[a]);
lvSources.Items.Item[a].Assign(lvSources.Items.Item[b]);
lvSources.Items.Item[b].Assign(tmpItem);
tmpItem.Free;
finally
lvSources.Items.EndUpdate;
end;
end;
procedure TDPMOptionsFrame.actMoveSourceUpExecute(Sender : TObject);
var
selected : TListItem;
begin
selected := lvSources.Selected;
if selected = nil then
exit;
ExchangeItems(selected.Index, selected.Index - 1);
lvSources.ItemIndex := selected.Index - 1;
end;
procedure TDPMOptionsFrame.actRemoveSourceExecute(Sender : TObject);
var
selectedItem : TListItem;
begin
selectedItem := lvSources.Selected;
if selectedItem <> nil then
lvSources.DeleteSelected;
if lvSources.Items.Count = 0 then
lblPackageSources.Caption := cNoPackageSources;
end;
procedure TDPMOptionsFrame.cboSourceTypeChange(Sender : TObject);
var
item : TListItem;
begin
item := lvSources.Selected;
if item <> nil then
item.SubItems[1] := cboSourceType.Items[cboSourceType.ItemIndex];
end;
procedure TDPMOptionsFrame.chkAutoCloseClick(Sender: TObject);
begin
spAutoCloseDelay.Enabled := chkAutoClose.Checked;
end;
constructor TDPMOptionsFrame.Create(AOwner : TComponent);
begin
inherited;
{$IFDEF USEIMAGECOLLECTION } //10.4 or later
FImageList := TVirtualImageList.Create(Self);
FImageCollection := TImageCollection.Create(Self);
{$ELSE}
FImageList := TImageList.Create(Self);
{$ENDIF}
pgOptions.ActivePageIndex := 0;
LoadImages;
end;
destructor TDPMOptionsFrame.Destroy;
begin
inherited;
end;
procedure TDPMOptionsFrame.dpmOptionsActionListUpdate(Action : TBasicAction; var Handled : Boolean);
var
selected : TListItem;
begin
selected := lvSources.Selected;
actRemoveSource.Enabled := selected <> nil;
actMoveSourceUp.Enabled := (selected <> nil) and (selected.Index > 0);
actMoveSourceDown.Enabled := (selected <> nil) and (lvSources.Items.Count > 1) and (selected.Index < lvSources.Items.Count - 1);
end;
procedure TDPMOptionsFrame.LoadSettings;
var
sourceConfig : ISourceConfig;
item : TListItem;
begin
FConfigManager.EnsureDefaultConfig; //make sure we have a default config file.
if FConfigFile = '' then
FConfigFile := TConfigUtils.GetDefaultConfigFileName;
FConfiguration := FConfigManager.LoadConfig(FConfigFile);
txtPackageCacheLocation.Text := FConfiguration.PackageCacheLocation;
lvSources.Clear;
if FConfiguration.Sources.Any then
begin
lblPackageSources.Caption := cPackageSources;
for sourceConfig in FConfiguration.Sources do
begin
item := lvSources.Items.Add;
item.Caption := sourceConfig.Name;
item.Checked := sourceConfig.IsEnabled;
item.SubItems.Add(sourceConfig.Source);
item.SubItems.Add(TEnumUtils.EnumToString<TSourceType>(sourceConfig.SourceType));
item.SubItems.Add(sourceConfig.UserName);
item.SubItems.Add(sourceConfig.Password);
end;
end
else
lblPackageSources.Caption := cNoPackageSources;
cboLogLevel.ItemIndex := Ord(FIDEOptions.LogVerbosity);
chkShowForRestore.Checked := FIDEOptions.ShowLogForRestore;
chkShowForInstall.Checked := FIDEOptions.ShowLogForInstall;
chkShowForUninstall.Checked := FIDEOptions.ShowLogForUninstall;
chkAutoClose.Checked := FIDEOptions.AutoCloseLogOnSuccess;
spAutoCloseDelay.Value := FIDEOptions.AutoCloseLogDelaySeconds;
spAutoCloseDelay.Enabled := chkAutoClose.Checked;
chkShowOnProjectTree.Checked := FIDEOptions.AddDPMToProjectTree;
end;
procedure TDPMOptionsFrame.lvSourcesSelectItem(Sender : TObject; Item : TListItem; Selected : Boolean);
begin
if Selected then
begin
txtName.Text := Item.Caption;
if item.SubItems.Count > 0 then
txtUri.Text := item.SubItems[0]
else
txtUri.Text := '';
if item.SubItems.Count > 1 then
cboSourceType.ItemIndex := cboSourceType.Items.IndexOf(item.SubItems[1]);
if item.SubItems.Count > 2 then
txtUserName.Text := item.SubItems[2]
else
txtUserName.Text := '';
if item.SubItems.Count > 3 then
txtPassword.Text := item.SubItems[3]
else
txtPassword.Text := '';
end;
end;
procedure TDPMOptionsFrame.SaveSettings;
var
i : Integer;
sourceConfig : ISourceConfig;
item : TListItem;
begin
FConfiguration.PackageCacheLocation := txtPackageCacheLocation.Text;
FConfiguration.Sources.Clear;
lvSources.HandleNeeded; //without this, lvSources.Items.Count will be 0 if the frame was never viewed
for i := 0 to lvSources.Items.Count - 1 do
begin
item := lvSources.Items[i];
sourceConfig := TSourceConfig.Create(FLogger);
sourceConfig.Name := item.Caption;
sourceConfig.IsEnabled := item.Checked;
if item.SubItems.Count > 0 then
sourceConfig.Source := item.SubItems[0];
if item.SubItems.Count > 1 then
sourceConfig.SourceType := TEnumUtils.StringToEnum<TSourceType>(item.SubItems[1]);
if item.SubItems.Count > 2 then
sourceConfig.UserName := item.SubItems[2];
if item.SubItems.Count > 3 then
sourceConfig.Password := item.SubItems[3];
FConfiguration.Sources.Add(sourceConfig);
end;
FConfigManager.SaveConfig(FConfiguration);
FIDEOptions.LogVerbosity := TVerbosity(cboLogLevel.ItemIndex);
FIDEOptions.ShowLogForRestore := chkShowForRestore.Checked;
FIDEOptions.ShowLogForInstall := chkShowForInstall.Checked;
FIDEOptions.ShowLogForUninstall := chkShowForUninstall.Checked;
FIDEOptions.AutoCloseLogOnSuccess := chkAutoClose.Checked;
FIDEOptions.AutoCloseLogDelaySeconds := spAutoCloseDelay.Value;
FIDEOptions.AddDPMToProjectTree := chkShowOnProjectTree.Checked;
FIDEOptions.SaveToFile();
FLogger.Verbosity := FIDEOptions.LogVerbosity;
end;
procedure TDPMOptionsFrame.Configure(const manager : IConfigurationManager; const ideOptions : IDPMIDEOptions; const logger : ILogger; const configFile : string);
begin
FConfigManager := manager;
FConfigFile := configFile;
FIDEOptions := ideOptions;
FLogger := logger;
end;
procedure TDPMOptionsFrame.txtNameChange(Sender : TObject);
var
item : TListItem;
begin
item := lvSources.Selected;
if item <> nil then
item.Caption := txtName.Text;
end;
procedure TDPMOptionsFrame.txtPackageCacheLocationRightButtonClick(Sender : TObject);
begin
FolderSelectDialog.Title := 'Select Package Cache Folder';
FolderSelectDialog.DefaultFolder := txtPackageCacheLocation.Text;
if FolderSelectDialog.Execute then
txtPackageCacheLocation.Text := FolderSelectDialog.FileName;
end;
procedure TDPMOptionsFrame.txtPasswordChange(Sender : TObject);
var
item : TListItem;
begin
item := lvSources.Selected;
if item <> nil then
item.SubItems[3] := txtPassword.Text;
end;
procedure TDPMOptionsFrame.txtUriChange(Sender : TObject);
var
item : TListItem;
begin
item := lvSources.Selected;
if item <> nil then
item.SubItems[0] := txtUri.Text;
end;
procedure TDPMOptionsFrame.txtUriRightButtonClick(Sender : TObject);
begin
FolderSelectDialog.Title := 'Select Package Source Folder';
FolderSelectDialog.DefaultFolder := txtUri.Text;
if FolderSelectDialog.Execute then
txtUri.Text := FolderSelectDialog.FileName;
end;
procedure TDPMOptionsFrame.txtUserNameChange(Sender : TObject);
var
item : TListItem;
begin
item := lvSources.Selected;
if item <> nil then
item.SubItems[2] := txtUserName.Text;
end;
function TDPMOptionsFrame.Validate : boolean;
var
i, j : Integer;
enabledCount : integer;
sErrorMessage : string;
nameList : TStringList;
uriList : TStringList;
sName : string;
sUri : string;
uri : IUri;
sourceType : string;
begin
enabledCount := 0;
nameList := TStringList.Create;
uriList := TStringList.Create;
try
lvSources.HandleNeeded; //without this, lvSources.Items.Count will be 0 if the frame was never viewed
for i := 0 to lvSources.Items.Count - 1 do
begin
if lvSources.Items[i].Checked then
Inc(enabledCount);
sName := lvSources.Items[i].Caption;
if nameList.IndexOf(sName) > -1 then
sErrorMessage := sErrorMessage + 'Duplicate Source Name [' + sName + ']' + #13#10;
nameList.Add(sName);
if (lvSources.Items[i].SubItems.Count > 0) then
sUri := lvSources.Items[i].SubItems[0]
else
sUri := '';
if (lvSources.Items[i].SubItems.Count > 1) then
sourceType := lvSources.Items[i].SubItems[1]
else
sourceType := 'Folder';
if sUri = '' then
sErrorMessage := sErrorMessage + 'No Uri for Source [' + sName + ']' + #13#10
else
begin
j := uriList.IndexOfName(sUri);
if j > -1 then
begin
//duplicate uri, check if the type is the same.
if SameText(sourceType, uriList.ValueFromIndex[j]) then
sErrorMessage := sErrorMessage + 'Duplicate Uri/type [' + sName + ']' + #13#10;
end;
uriList.Add(sUri + '=' + sourceType);
try
uri := TUriFactory.Parse(sUri);
// if not (uri.IsFile or uri.IsUnc) then
// begin
// sErrorMessage := sErrorMessage + 'only folder uri type is supported at the moment' + #13#10;
// end;
except
on e : Exception do
begin
sErrorMessage := sErrorMessage + 'Invalid Uri for Source [' + sName + '] : ' + e.Message + #13#10;
end;
end;
end;
end;
finally
nameList.Free;
uriList.Free;
end;
if enabledCount = 0 then
sErrorMessage := sErrorMessage + 'At least 1 source must be defined and enabled!';
result := sErrorMessage = '';
if not result then
begin
sErrorMessage := 'DPM Package Manage Options Validation Errors:' + #13#10#13#10 + sErrorMessage;
ShowMessage(sErrorMessage);
end;
end;
procedure TDPMOptionsFrame.LoadImages;
const
suffixes : array[0..3] of string = ('_16', '_24', '_32','_48');
{$IFNDEF USEBUTTONIMAGELIST}
var
tmpBmp : TBitmap;
{$ENDIF}
{$IF CompilerVersion < 34.0} //10.2 or earlier
procedure AddImage(const AResourceName : string);
var
png : TPngImage;
bmp: TBitmap;
begin
png := TPngImage.Create;
bmp:=TBitmap.Create;
try
png.LoadFromResourceName(HInstance, AResourceName);
png.AssignTo(bmp);
bmp.AlphaFormat:=afIgnored;
ImageList_Add(FImageList.Handle, bmp.Handle, 0);
finally
bmp.Free;
png.Free;
end;
end;
{$IFEND}
begin
{$IFNDEF USEIMAGECOLLECTION} //10.2 or earlier
AddImage('ADD_PACKAGE_16');
AddImage('REMOVE_PACKAGE_16');
AddImage('MOVE_UP_16');
AddImage('MOVE_DOWN_16');
AddImage('OPEN_16');
{$ELSE}
FImageCollection.Add('add',HInstance,'ADD_PACKAGE', suffixes);
FImageCollection.Add('remove',HInstance,'REMOVE_PACKAGE', suffixes);
FImageCollection.Add('move_up',HInstance,'MOVE_UP', suffixes);
FImageCollection.Add('move_down',HInstance,'MOVE_DOWN', suffixes);
FImageCollection.Add('open',HInstance,'OPEN', suffixes);
FImageList.AutoFill := true;
FImageList.PreserveItems := true;
FImageList.ImageCollection := FImageCollection;
{$ENDIF}
actAddSource.ImageIndex := 0;
actRemoveSource.ImageIndex := 1;
actMoveSourceUp.ImageIndex := 2;
actMoveSourceDown.Index := 3;
dpmOptionsActionList.Images := FImageList;
txtPackageCacheLocation.RightButton.ImageIndex := 4;
txtPackageCacheLocation.Images := FImageList;
btnAdd.Caption := '';
btnRemove.Caption := '';
btnUp.Caption := '';
btnDown.Caption := '';
{$IFDEF USEBUTTONIMAGELIST}
btnAdd.ImageIndex := 0;
btnAdd.Images := FImageList;
btnRemove.ImageIndex := 1;
btnRemove.Images := FImageList;
btnUp.ImageIndex := 2;
btnUp.Images := FImageList;
btnDown.ImageIndex := 3;
btnDown.Images := FImageList;
{$ELSE}
tmpBmp := TBitmap.Create;
try
tmpBmp.SetSize(16,16);
FImageList.GetBitmap(0, tmpBmp); //Add
btnAdd.Glyph.Assign(tmpBmp);
tmpBmp.SetSize(0,0); //clear it
tmpBmp.SetSize(16,16);
FImageList.GetBitmap(1, tmpBmp); //remove
btnRemove.Glyph.Assign(tmpBmp);
tmpBmp.SetSize(0,0);
tmpBmp.SetSize(16,16);
FImageList.GetBitmap(2, tmpBmp); //up
btnUp.Glyph.Assign(tmpBmp);
tmpBmp.SetSize(0,0);
tmpBmp.SetSize(16,16);
FImageList.GetBitmap(3, tmpBmp); //down
btnDown.Glyph.Assign(tmpBmp);
finally
tmpBmp.Free;
end;
{$ENDIF}
end;
end.
|
namespace SharedUI.Shared;
{$IF ECHOES}
uses
System.Windows,
System.Windows.Controls;
type
MainWindow = public partial class(System.Windows.Window)
public
constructor withController(aController: MainWindowController);
begin
DataContext := aController;
InitializeComponent();
end;
private
property controller: MainWindowController read DataContext as MainWindowController;
//
// Forward actions to the controller
//
method CalculateResult_Click(aSender: Object; e: RoutedEventArgs);
begin
controller.calculateResult(aSender);
end;
end;
{$ENDIF}
end. |
unit uFinLancamentoList;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
BrowseConfig, Db, Menus,DBTables, StdCtrls, ExtCtrls, Buttons, ComCtrls,
uFinQuitacaoFch, uFinQuitacaoToolBarMover, uFinQuitacaoMoverHelp, Mask,
checklst, dxBar, uParentList, dxDBGrid, dxGrClms, dxDBGridPrint,
dxBarExtDBItems, dxBarExtItems, dxCntner, dxTL, dxDateEdit, uFinLancamentoQrp, dxDBCGrid,
ImgList, dxDBTLCl, dxDBCtrl, ADODB, PowerADOQuery,
RCADOQuery, SuperComboADO, dxEditor, dxExEdtr, dxEdLib, dxPSCore,
dxPSdxTLLnk, dxPSdxDBCtrlLnk, dxPSdxDBGrLnk, siComp, siLangRT, DateBox;
type
TFinLancamentoList = class(TParentList)
pnlQuitaMulti: TPanel;
efjdsfkhsdjfhnsjdkalfskda: TPanel;
Panel6: TPanel;
pnlQuitCmd: TPanel;
pnlBrwQuitMulti: TPanel;
Panel3: TPanel;
wfsldkfiosdufciosuyixch: TPanel;
btQuitaMulti: TSpeedButton;
btCancelaMulti: TSpeedButton;
quAQuitar: TRCADOQuery;
dsAQuitar: TDataSource;
lblTotalAQuitar: TLabel;
lblTotalQuitado: TLabel;
lblLines: TLabel;
quAQuitarLancamentoTipo: TStringField;
quAQuitarPessoa: TStringField;
quAQuitarDataVencimento: TDateTimeField;
quAQuitarValorNominal: TFloatField;
quAQuitarValorAQuitar: TFloatField;
quAQuitarIDLancamento: TIntegerField;
quAQuitarTotalQuitado: TFloatField;
quBrowseS: TStringField;
quBrowseV: TStringField;
quBrowseQ: TStringField;
quBrowseSac: TIntegerField;
CorConfirmado: TPanel;
CorVencido: TPanel;
CorQuitado: TPanel;
CorCancelado: TPanel;
CorJuridico: TPanel;
quBrowseDataVencimento: TDateTimeField;
quBrowseSituacao: TIntegerField;
quBrowsePrevisao: TBooleanField;
quBrowseIDLancamento: TIntegerField;
quBrowseLancamentoTipo: TStringField;
quBrowseDataLancamento: TDateTimeField;
quBrowseDataInicioQuitacao: TDateTimeField;
quBrowseDataFimQuitacao: TDateTimeField;
quBrowsePagando: TBooleanField;
quBrowseValorNominal: TFloatField;
quBrowseTotalQuitado: TFloatField;
quBrowseDesdobramentoTipo: TStringField;
quBrowseNumDesdobramento: TStringField;
quBrowseDocumentoTipo: TStringField;
quBrowseNumDocumento: TStringField;
quBrowseSigla: TStringField;
trmGO: TTimer;
lblTotal: TLabel;
quBrowseDataEmissao: TDateTimeField;
cmbData: TComboBox;
Label2: TLabel;
Label3: TLabel;
Label1: TLabel;
cmbSituacao: TComboBox;
btTodasPessoas: TButton;
scPessoa: TSuperComboADO;
pnlEmpresa: TPanel;
Splitter2: TSplitter;
lvEmpresa: TListView;
btSelEmpresa: TSpeedButton;
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
quBrowseIDEmpresa: TIntegerField;
quBrowseCodigoEmpresa: TStringField;
quBrowseEmpresa: TStringField;
quBrowsePessoa: TStringField;
brwGridDataVencimento: TdxDBGridDateColumn;
brwGridIDLancamento: TdxDBGridMaskColumn;
brwGridPessoa: TdxDBGridMaskColumn;
brwGridLancamentoTipo: TdxDBGridMaskColumn;
brwGridDataLancamento: TdxDBGridDateColumn;
brwGridDataInicioQuitacao: TdxDBGridDateColumn;
brwGridDataFimQuitacao: TdxDBGridDateColumn;
brwGridValorNominal: TdxDBGridMaskColumn;
brwGridTotalQuitado: TdxDBGridMaskColumn;
brwGridDesdobramentoTipo: TdxDBGridMaskColumn;
brwGridNumDesdobramento: TdxDBGridMaskColumn;
brwGridDocumentoTipo: TdxDBGridMaskColumn;
brwGridNumDocumento: TdxDBGridMaskColumn;
brwGridDataEmissao: TdxDBGridDateColumn;
brwGridCodigoEmpresa: TdxDBGridMaskColumn;
brwGridEmpresa: TdxDBGridMaskColumn;
bbQuita: TdxBarButton;
bbQuitaMulti: TdxBarButton;
bbHistorico: TdxBarButton;
quBrowseMeioQuit: TStringField;
quBrowseDocQuit: TStringField;
brwGridMeioQuit: TdxDBGridMaskColumn;
bsImprime: TdxBarSubItem;
bbImprimeLancamento: TdxBarButton;
grdAQuitar: TdxDBCGrid;
grdAQuitarLancamentoTipo: TdxDBGridMaskColumn;
grdAQuitarPessoa: TdxDBGridMaskColumn;
grdAQuitarDataVencimento: TdxDBGridDateColumn;
grdAQuitarValorNominal: TdxDBGridMaskColumn;
grdAQuitarValorAQuitar: TdxDBGridMaskColumn;
grdAQuitarTotalQuitado: TdxDBGridMaskColumn;
brwGridSac: TdxDBGridImageColumn;
brwGridHistorico: TdxDBGridBlobColumn;
quBrowseAQuitar: TFloatField;
brwGridAQuitar: TdxDBGridMaskColumn;
quBrowseHistorico: TStringField;
quBrowseDiscountValue: TFloatField;
brwGridDiscountDate: TdxDBGridMaskColumn;
brwGridDiscountValue: TdxDBGridMaskColumn;
quBrowseDiscountDate: TDateTimeField;
quBrowseFrequency: TStringField;
brwGridFrequency: TdxDBGridMaskColumn;
quBrowseLancamentoType: TIntegerField;
quBrowseIDLancamentoParent: TIntegerField;
imgLancType: TdxImageEdit;
quBrowseIDPessoa: TIntegerField;
quBrowseIDCashRegMov: TIntegerField;
brwGridIDCashRegMov: TdxDBGridMaskColumn;
quBrowseTotalJuros: TBCDField;
brwGridTotalJuros: TdxDBGridColumn;
quBrowseCheckNumber: TStringField;
quBrowseCustomerDocument: TStringField;
quBrowseCustomerName: TStringField;
quBrowseCustomerPhone: TStringField;
quBrowseBanco: TStringField;
brwGridCheckNumber: TdxDBGridMaskColumn;
brwGridCustomerDocument: TdxDBGridMaskColumn;
brwGridCustomerName: TdxDBGridMaskColumn;
brwGridCustomerPhone: TdxDBGridMaskColumn;
brwGridBanco: TdxDBGridMaskColumn;
quBrowseNumero: TStringField;
brwGridNumero: TdxDBGridMaskColumn;
dbFim: TDateBox;
dbInicio: TDateBox;
btnTaxes: TdxBarButton;
quBrowseCostCenter: TStringField;
brwGridCostCenter: TdxDBGridColumn;
cbxShowDue: TCheckBox;
quBrowseIDPreSale: TIntegerField;
lbAmount: TLabel;
edtAmount: TEdit;
quBrowseSaleCode: TStringField;
quBrowseInvoiceCode: TStringField;
brwGridSaleCode: TdxDBGridColumn;
brwGridInvoiceCode: TdxDBGridColumn;
btnLoan: TdxBarButton;
bbImprimeBoleto: TdxBarButton;
bbExportarBoleto: TdxBarButton;
quBrowseSystemUser: TStringField;
brwGridSystemUser: TdxDBGridMaskColumn;
quBrowseTipoMeioPag: TIntegerField;
procedure quAQuitarAfterOpen(DataSet: TDataSet);
procedure FormCreate(Sender: TObject);
procedure btCancelaMultiClick(Sender: TObject);
procedure btQuitaMultiClick(Sender: TObject);
procedure quBrowseAfterOpen(DataSet: TDataSet);
procedure CommandClick(Sender: TObject);
procedure brwGridDblClick(Sender: TObject);
procedure quBrowseCalcFields(DataSet: TDataSet);
procedure trmGOTimer(Sender: TObject);
procedure dbInicioChange(Sender: TObject);
procedure btTodasPessoasClick(Sender: TObject);
procedure cmbSituacaoChange(Sender: TObject);
procedure scPessoaSelectItem(Sender: TObject);
procedure btSelEmpresaClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure lvEmpresaClick(Sender: TObject);
procedure bbQuitaClick(Sender: TObject);
procedure bbQuitaMultiClick(Sender: TObject);
procedure bbHistoricoClick(Sender: TObject);
procedure bbListaImprimeClick(Sender: TObject);
procedure bbImprimeLancamentoClick(Sender: TObject);
procedure brwGridCustomDraw(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; ANode: TdxTreeListNode; AColumn: TdxDBTreeListColumn;
const AText: String; AFont: TFont; var AColor: TColor; ASelected,
AFocused: Boolean; var ADone: Boolean);
procedure imgLancTypeChange(Sender: TObject);
procedure btnTaxesClick(Sender: TObject);
procedure edtAmountKeyPress(Sender: TObject; var Key: Char);
procedure btnLoanClick(Sender: TObject);
procedure bbImprimeBoletoClick(Sender: TObject);
procedure bbExportarBoletoClick(Sender: TObject);
private
//Translation
sReceive,
sRecMult,
sLines,
sTotalPaid,
sTotalRecv,
sTotalToBePaid,
sTotalToBerecv,
sRecords,
sWith,
sBetween,
sAnd,
sCompany : String;
Tot, TotAQuitar, TotQuitado: Currency;
FinQuitacaoFch : TFinQuitacaoFch;
FinQuitacaoToolBarMover: TFinQuitacaoToolBarMover;
OriginalAQuitarHeight: Integer;
OriginalBrowseHeight: Integer;
function OnTestDelete: Boolean; override;
procedure OnAfterDeleteItem; override;
procedure OnAfterRestoreItem; override;
procedure OnAfterStart; override;
procedure FchCreate;
procedure AjustaAAQuitarHeight;
function ValidateLancamento : Boolean;
public
FinQuitacaoMoverHelp: TFinQuitacaoMoverHelp;
function ListParamRefresh : integer; override;
procedure IncluiSelecionado;
procedure IncluiVisao;
procedure ExcluiSelecionado;
procedure ExcluiTodos;
protected
Pagando: Boolean;
Realizado: Boolean;
LancType: Integer;
end;
implementation
{$R *.DFM}
uses uDM, uMsgBox, uFinChoicerFrm, uSystemTypes, uFinLancamentoFch,
uFinLancamentoCalc, uDateTimeFunctions, uMsgConstant, uDMGlobal,
uFinTaxComper, uCharFunctions, uNumericFunctions, uFinEmprestimoFrm,
uFrmPrintBoleto, uFrmExportBoleto;
procedure TFinLancamentoList.OnAfterRestoreItem;
begin
case quBrowseLancamentoType.AsInteger of
FIN_LANCAMENTO_PARENT: UpdateStatusChildren(quBrowseIDLancamento.AsString);
FIN_LANCAMENTO_CHILD : UpdateStatusParent(quBrowseIDLancamento.AsString,
quBrowseIDLancamentoParent.AsString);
end;
end;
procedure TFinLancamentoList.OnAfterDeleteItem;
begin
//Delete ou Restore disbersements
case quBrowseLancamentoType.AsInteger of
FIN_LANCAMENTO_PARENT: UpdateStatusChildren(quBrowseIDLancamento.AsString);
FIN_LANCAMENTO_CHILD:
begin
UpdateStatusParent(quBrowseIDLancamento.AsString,
quBrowseIDLancamentoParent.AsString);
UpdateTotalDisbursement(quBrowseIDLancamentoParent.AsString);
end;
end;
end;
function TFinLancamentoList.ListParamRefresh : Integer;
var
InicioStr, FimStr, ShowDue: String;
i: integer;
Todos: Boolean;
begin
// Testa se das datas de período são válidas
if not TestDate(dbInicio.Text) then
begin
MsgBox(MSG_CRT_NO_VALID_INIDATE, vbCritical + vbOkOnly);
dbInicio.SetFocus;
Exit;
end;
if not TestDate(dbFim.Text) then
begin
MsgBox(MSG_CRT_NO_VALID_FIMDATE, vbCritical + vbOkOnly);
dbFim.SetFocus;
Exit;
end;
// Filtro por situacao
case cmbSituacao.ItemIndex of
0:// Aberto
WhereBasicFilter[3] := '(L.Situacao IN (1, 5) AND (IsNull((L.ValorNominal - L.TotalQuitado),0) <> 0))';
1:// Parte Quitado
WhereBasicFilter[3] := '((L.Situacao = 5) AND (IsNull((L.ValorNominal - L.TotalQuitado),0) <> 0))';
2:// Quitado e Conta da loja quitado pelo MR
WhereBasicFilter[3] := '((L.Situacao = 2) OR (MP.Tipo = 9 AND ((L.ValorNominal - L.TotalQuitado) = 0)))';
3:// Cancelados
WhereBasicFilter[3] := '((L.Situacao = 4) AND (IsNull((L.ValorNominal - L.TotalQuitado),0) <> 0))';
4:// Todos
WhereBasicFilter[3] := '';
end;
// altera qual o filtro por data
InicioStr := Chr(39) + FormatDateTime('mm/dd/yyyy', dbInicio.Date) + Chr(39);
FimStr := Chr(39) + FormatDateTime('mm/dd/yyyy', dbFim.Date + 1) + Chr(39);
case cmbData.ItemIndex of
0: // Data de Lançamento
WhereBasicFilter[4] := ' DataLancamento >= ' + InicioStr + ' AND DataLancamento < ' + FimStr;
1: // Data de Emissão
WhereBasicFilter[4] := ' DataEmissao >= ' + InicioStr + ' AND DataEmissao < ' + FimStr;
2: // Data de Vencimento
begin
if cbxShowDue.Checked then
ShowDue := ' OR (DataVencimento < GetDate() AND L.TotalQuitado < L.ValorNominal) ';
WhereBasicFilter[4] := ' (((DataVencimento >= ' + InicioStr + ' AND DataVencimento < ' + FimStr + ') ' +
' OR (DateAdd(day, -1*LAT.DueDateShift, L.DataVencimento) >= ' + InicioStr + ' AND DateAdd(day, -1*LAT.DueDateShift, L.DataVencimento) < ' + FimStr + ') ) ' + ShowDue + ')';
end;
3: // Data de Início da Quitação
WhereBasicFilter[4] := ' DataInicioQuitacao >= ' + InicioStr + ' AND DataInicioQuitacao < ' + FimStr;
4: // Data de Fim da Quitação
WhereBasicFilter[4] := ' DataFimQuitacao >= ' + InicioStr + ' AND DataFimQuitacao < ' + FimStr;
5: // Data de Pagamento
WhereBasicFilter[4] := ' DataFimQuitacao >= ' + InicioStr + ' AND DataFimQuitacao < ' + FimStr;
end;
// Altera o filtro por pessoa
if scPessoa.LookUpValue = '' then
WhereBasicFilter[5] := ''
else
WhereBasicFilter[5] := ' L.IDPessoa = ' + scPessoa.LookUpValue;
// Aplica o filtro de empresas
WhereBasicFilter[6] := '';
Todos := True;
with lvEmpresa do
for i := 0 to Items.Count - 1 do
begin
Todos := Todos AND Items[i].Checked;
if Items[i].Checked then
begin
if WhereBasicFilter[6] <> '' then
WhereBasicFilter[6] := WhereBasicFilter[6] + ' OR '
else
WhereBasicFilter[6] := WhereBasicFilter[6] + ' ( ';
WhereBasicFilter[6] := WhereBasicFilter[6] + 'L.IDEmpresa = ' + Items[i].SubItems[0];
end;
end;
if WhereBasicFilter[6] <> '' then
WhereBasicFilter[6] := WhereBasicFilter[6] + ' ) ';
if Todos then
WhereBasicFilter[6] := '';
if imgLancType.Text = '0' then
WhereBasicFilter[7] := '((IsNull(L.LancamentoType,0) = 0) OR (L.LancamentoType = 2))'
else
WhereBasicFilter[7] := 'L.LancamentoType = 1';
if (edtAmount.Text <> '') and (MyStrToCurrency(edtAmount.Text) <> 0) then
begin
WhereBasicFilter[8] := 'L.ValorNominal = ' + MyFormatCur(MyStrToCurrency(edtAmount.Text), '.');
WhereBasicFilter[3] := '';
WhereBasicFilter[4] := '';
WhereBasicFilter[5] := '';
WhereBasicFilter[6] := '';
end
else
WhereBasicFilter[8] := '';
ListRefresh;
trmGo.Enabled := False;
pnlExecutaAviso.ParentColor := True;
DesligaAviso;
end;
function TFinLancamentoList.OnTestDelete: Boolean;
begin
// Testa se o lancamento já esta quitado
if quBrowseTotalQuitado.AsCurrency <> 0 then
begin
MsgBox(MSG_CRT_NO_DEL_RECORD_DETAIL, vbCritical + vbOkOnly );
Result := False;
end
else
Result := True;
end;
procedure TFinLancamentoList.OnAfterStart;
begin
// Controla o modo de abertura do Browse
// A Browse esta configurado para nao abrir automaticamente
dbInicio.Date := InicioMes(Date());
dbFim.Date := FimMes(Date());
cmbData.ItemIndex := 2;
btTodasPessoasClick(nil);
if DM.TaxInCost then
btnTaxes.Visible := ivAlways
else
btnTaxes.Visible := ivNever;
if Trim(MyParametro) = 'ContasAReceber' then
begin
Pagando := False;
Realizado := False;
cmbSituacao.Visible := True;
cmbSituacao.ItemIndex := 0;
WhereBasicFilter[1] := 'L.Pagando = 0';
bbQuita.Visible := ivAlways;
bbQuitaMulti.Visible := ivAlways;
bbQuita.Caption := sReceive;
bbQuitaMulti.Caption := sRecMult;
HelpContext := 17;
end
else if Trim(MyParametro) = 'ContasRecebidas' then
begin
Pagando := False;
Realizado := True;
cmbSituacao.Visible := False;
WhereBasicFilter[1] := 'L.Pagando = 0';
WhereBasicFilter[2] := 'L.Situacao = ' + IntToStr(DM.SitQuitado);
bbQuita.Visible := ivNever;
bbQuitaMulti.Visible := ivNever;
HelpContext := 17;
end
else if Trim(MyParametro) = 'ContasAPagar' then
begin
Pagando := True;
Realizado := False;
cmbSituacao.Visible := True;
cmbSituacao.ItemIndex := 0;
WhereBasicFilter[1] := 'L.Pagando = 1';
bbQuita.Visible := ivAlways;
bbQuitaMulti.Visible := ivAlways;
HelpContext := 14;
end
else if Trim(MyParametro) = 'ContasPagas' then
begin
Pagando := True;
Realizado := True;
cmbSituacao.Visible := False;
WhereBasicFilter[1] := 'L.Pagando = 1';
WhereBasicFilter[2] := 'L.Situacao = ' + IntToStr(DM.SitQuitado);
bbQuita.Visible := ivNever;
bbQuitaMulti.Visible := ivNever;
HelpContext := 14;
end;
btSelEmpresaClick(nil);
end;
procedure TFinLancamentoList.AjustaAAQuitarHeight;
var
NewHeight: Integer;
begin
// Controla o tamanho da lista na tela
if quAQuitar.RecordCount > 3 then
begin
NewHeight := (quAQuitar.RecordCount - 3) * 15;
if NewHeight < (OriginalBrowseHeight * 0.20) then
begin
pnlQuitaMulti.Height := NewHeight + OriginalAQuitarHeight;
end
else
begin
// Pega o proximo multiplo que pode chegar e aplica
pnlQuitaMulti.Height := Trunc((OriginalBrowseHeight * 0.20) / 15) * 15 + OriginalAQuitarHeight;
end
end
else
begin
pnlQuitaMulti.Height := OriginalAQuitarHeight;
end;
end;
procedure TFinLancamentoList.quAQuitarAfterOpen(DataSet: TDataSet);
var
TotalAQuitar, TotalQuitado: Currency;
BO: TBookMarkStr;
begin
inherited;
btTodasPessoasClick(nil);
with quAQuitar do
begin
DisableControls;
TotalAQuitar := 0;
TotalQuitado := 0;
BO := BookMark;
First;
While not EOF do
begin
TotalAQuitar := TotalAQuitar + quAQuitarValorAQuitar.AsCurrency;
TotalQuitado := TotalQuitado + quAQuitarTotalQuitado.AsCurrency;
Next;
end;
BookMark := BO;
EnableControls;
end;
lblLines.Caption := sLines + IntToStr(quAQuitar.RecordCount);
lblTotalQuitado.Caption := FloatToStrF(TotalQuitado, ffCurrency, 20, 2);
lblTotalAQuitar.Caption := FloatToStrF(TotalAQuitar, ffCurrency, 20, 2);
end;
procedure TFinLancamentoList.IncluiSelecionado;
var
BMB, BMQ: TBookMarkStr;
RequeryAQuitar: Boolean;
i: integer;
begin
try
// Guardo onde estava
BMB := quBrowse.BookMark;
BMQ := quAQuitar.BookMark;
// Deligo os controles, para performace
quBrowse.DisableControls;
quAQuitar.DisableControls;
RequeryAQuitar := False;
// Intero pelas linhas selecionadas
for i := 0 to brwGrid.SelectedCount -1 do
begin
quBrowse.BookMark := brwGrid.SelectedRows[i];
// Se não exitir na tabela de AQuitar, incluo
if not (quAquitar.Locate('IDLancamento', quBrowse.FieldByName('IDLancamento').AsString, [])) then
if (quBrowse.FieldByName('Situacao').AsInteger <> 2) and (ValidateLancamento) then
begin
InsereAQuitar(quBrowse.FieldByName('IDLancamento').AsInteger, False);
RequeryAQuitar := True;
end;
end;
// Se houve alteracao no lista de AQuitar dou o refresh
if RequeryAQuitar then
quAQuitar.Requery
else
quAQuitar.BookMark := BMQ;
AjustaAAQuitarHeight;
finally
quBrowse.BookMark := BMB;
quBrowse.EnableControls;
quAQuitar.EnableControls;
end;
end;
procedure TFinLancamentoList.IncluiVisao;
var
SQL: String;
BO: TBookMarkStr;
begin
DeleteAQuitar(-1);
with quBrowse do
begin
DisableControls;
BO := BookMark;
If not Active then
Open;
First;
while NOT EOF do
begin
if quBrowse.FieldByName('Situacao').AsInteger <> 2 then
InsereAQuitar(FieldByName('IDLancamento').AsInteger, False);
Next;
end;
BookMark := BO;
EnableControls;
end;
quAQuitar.Requery;
AjustaAAQuitarHeight;
end;
procedure TFinLancamentoList.ExcluiSelecionado;
begin
DeleteAQuitar(quAQuitarIDLancamento.AsInteger);
quAQuitar.Requery;
AjustaAAQuitarHeight;
end;
procedure TFinLancamentoList.ExcluiTodos;
begin
DeleteAQuitar(-1);
quAQuitar.Requery;
AjustaAAQuitarHeight;
end;
procedure TFinLancamentoList.FchCreate;
begin
// Caso necessario cria a ficha de pagamento.
if brwForm = Nil then
begin
brwForm := TFinLancamentoFch.Create(Self);
TFinLancamentoFch(brwForm).setPagando(Pagando);
end;
TFinLancamentoFch(brwForm).setLancType(LancType);
end;
procedure TFinLancamentoList.FormCreate(Sender: TObject);
var
ListItem: TListItem;
begin
inherited;
OriginalAQuitarHeight := pnlQuitaMulti.Height;
OriginalBrowseHeight := pnlBrowse.Height;
// Caheia em variaveis as constantes que seram testadas nos laços
// de paint do Grid
DM.CreateLancSituacao;
// Preenche o check list box de empresas
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Text := 'SELECT E.IDEmpresa, E.Empresa FROM #Sis_EmpresaP EP JOIN Sis_Empresa E ON (EP.IDEmpresaP = E.IDEmpresa) WHERE E.Desativado = 0 AND E.Hidden = 0';
Open;
First;
lvEmpresa.Items.Clear;
while not EOF do
begin
ListItem := lvEmpresa.Items.Add;
ListItem.Caption := Fields[1].AsString;
ListItem.Checked := True;
ListItem.SubItems.Add(Fields[0].AsString);
Next;
end;
Close;
end;
bbImprimeLancamento.Enabled := (DMGlobal.IDLanguage = LANG_PORTUGUESE);
//Translate
case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sReceive := 'Receive';
sRecMult := 'Receive multiple';
sLines := 'Lines: ';
sTotalPaid := 'Total paid: ';
sTotalRecv := 'Total received: ';
sTotalToBePaid := 'Total to be paid: ';
sTotalToBeRecv := 'Total to be received: ';
sRecords := 'Records ';
sWith := ' with ';
sBetween := ' between ';
sAnd := ' and ';
sCompany := '. Company: ';
end;
LANG_PORTUGUESE :
begin
sReceive := 'Recebido';
sRecMult := 'Recebimento Múltiplo';
sLines := 'Linhas: ';
sTotalPaid := 'Total pago: ';
sTotalRecv := 'Total recebido: ';
sTotalToBePaid := 'Total a pagar: ';
sTotalToBeRecv := 'Total a receber: ';
sRecords := 'Registros ';
sWith := ' com ';
sBetween := ' entre ';
sAnd := ' e ';
sCompany := '. Empresa: ';
end;
LANG_SPANISH :
begin
sReceive := 'Recibido';
sRecMult := 'Recibimento Múltiple';
sLines := 'Líneas: ';
sTotalPaid := 'Total pagado: ';
sTotalRecv := 'Total recibido: ';
sTotalToBePaid := 'Total a pagar: ';
sTotalToBeRecv := 'Total a reciber: ';
sRecords := 'Registros ';
sWith := ' com ';
sBetween := ' entre ';
sAnd := ' y ';
sCompany := '. Empresa: ';
end;
end;
end;
procedure TFinLancamentoList.btCancelaMultiClick(Sender: TObject);
begin
inherited;
// Some com o panel de multi quitacao
pnlQuitaMulti.Visible := False;
// Religa os botões de quitacao
bbQuita.Visible := ivAlways;
bbQuitaMulti.Visible := ivAlways;
// Some com o Mover
FinQuitacaoToolBarMover.Close;
// Limpa a tabela temporaria
DeleteAQuitar(-1);
end;
procedure TFinLancamentoList.btQuitaMultiClick(Sender: TObject);
var
ID1, ID2: String;
function CanPayMultiple:Boolean;
var Entity : String;
begin
Result := True;
if not quAQuitar.Active then
Exit;
with quAQuitar do
Try
DisableControls;
First;
Entity := quAQuitarPessoa.AsString;
while not(EOF) do
if Entity <> quAQuitarPessoa.AsString then
begin
Result := False;
Break;
Exit;
end
else
Next;
finally
EnableControls;
end;
end;
begin
inherited;
{
//So pode pagar se for Entity do mesmo type
if not CanPayMultiple then
begin
MsgBox(MSG_INF_NOT_PAY_DIFFER_ENTITY, vbInformation + vbOkOnly);
Exit;
end;
}
// Abre a ficha de pagamento.
if FinQuitacaoFch = nil then
FinQuitacaoFch := TFinQuitacaoFch.Create(Self);
// Seta o parametro que vai ser passado para a ficha
if Self.Pagando then
FinQuitacaoFch.Param := 'Pagando=1'
else
FinQuitacaoFch.Param := 'Pagando=0';
if FinQuitacaoFch.Start(btInc, nil, False, ID1, ID2, '', MyUserRights, nil) then
begin
ListRefresh;
btCancelaMultiClick(nil);
end;
end;
procedure TFinLancamentoList.quBrowseAfterOpen(DataSet: TDataSet);
begin
inherited;
// caso alguma linha do browse seja alterada, o lista deverá refletir estas
// modificaoes.
// So se estiver durante uma quitacao multipla
if pnlQuitaMulti.Visible then
quAQuitar.Requery;
with quBrowse do
begin
DisableControls;
First;
Tot := 0;
TotQuitado := 0;
TotAQuitar := 0;
while not EOF do
begin
Tot := Tot + quBrowseValorNominal.AsCurrency;
TotAQuitar := TotAQuitar + (quBrowseValorNominal.AsCurrency) - (quBrowseTotalQuitado.AsCurrency);
TotQuitado := TotQuitado + quBrowseTotalQuitado.AsCurrency;
Next;
end;
First;
EnableControls;
end;
if Realizado then
begin
if Pagando then
lblTotal.Caption := sTotalPaid + FloatToStrF(TotQuitado, ffCurrency, 20, 2)
else
lblTotal.Caption := sTotalRecv + FloatToStrF(TotQuitado, ffCurrency, 20, 2);
end
else
begin
if Pagando then
lblTotal.Caption := sTotalToBePaid + FloatToStrF(TotAQuitar, ffCurrency, 20, 2)
else
lblTotal.Caption := sTotalToBerecv + FloatToStrF(TotAQuitar, ffCurrency, 20, 2);
end;
end;
procedure TFinLancamentoList.CommandClick(Sender: TObject);
var
pCommand : TBtnCommandType;
iRes : integer;
begin
pCommand := TBtnCommandType(TComponent(Sender).Tag);
case pCommand of
btInc : begin
with TFinchoicerFrm.Create(Self) do
iRes := Start(CHOICE_DOCUMENT_TYPE);
Case iRes of
-1 : exit;
1 : LancType := FIN_LANCAMENTO_SINGLE; //Fin Lancamento
2 : LancType := FIN_LANCAMENTO_PARENT; //Fin Lancamento Parent
end;
end;
btAlt : begin
LancType := quBrowseLancamentoType.AsInteger;
end;
btExc : begin
if not quBrowse.FieldByName('IDPreSale').IsNull then
begin
MsgBox(MSG_CRT_NO_DEL_SYSTEM_PAYMENT, vbCritical + vbOKOnly);
Exit;
end;
end;
end;
// Coloca se necessario a ficha de lancamento na memoria
FchCreate;
inherited;
end;
procedure TFinLancamentoList.brwGridDblClick(Sender: TObject);
begin
LancType := quBrowseLancamentoType.AsInteger;
FchCreate;
inherited;
end;
procedure TFinLancamentoList.quBrowseCalcFields(DataSet: TDataSet);
var
PorraCase: Integer;
begin
inherited;
{
Situações (quBrowseSituacao)
1 - Aberto
2 - Quitado
3 - Juridico
4 - Cancelado
5 - Parte quitado
Sub-situação (quBrowseSAC)
0 - Aberto
1 - Confirmado
2 - Vencido
3 - Quitado
4 - Parte quitado
5 - Juridico
6 - Cancelado
}
//Tratamento para conta da loja
if (quBrowseTipoMeioPag.AsInteger = 9) and (quBrowseAQuitar.AsCurrency = 0) then
PorraCase := DM.SitQuitado
else
PorraCase := quBrowseSituacao.AsInteger;
if PorraCase = DM.SitCancelado then
quBrowseSac.AsInteger := 6
else if PorraCase = DM.SitJuridico then
quBrowseSac.AsInteger := 5
else if (PorraCase = DM.SitQuitado) then
quBrowseSac.AsInteger := 3
else if PorraCase = DM.SitParteQuitado then
quBrowseSac.AsInteger := 4
else if quBrowseDataVencimento.AsDateTime < Now then
quBrowseSac.AsInteger := 2
else if quBrowsePrevisao.AsBoolean then
quBrowseSac.AsInteger := 0
else
quBrowseSac.AsInteger := 1;
if imgLancType.Text <> '0' then
quBrowseSac.AsInteger := -1;
end;
procedure TFinLancamentoList.trmGOTimer(Sender: TObject);
begin
inherited;
if pnlExecutaAviso.ParentColor then
pnlExecutaAviso.Color := clMaroon
else
pnlExecutaAviso.ParentColor := True;
end;
procedure TFinLancamentoList.dbInicioChange(Sender: TObject);
begin
inherited;
trmGo.Enabled := True;
end;
procedure TFinLancamentoList.btTodasPessoasClick(Sender: TObject);
begin
inherited;
trmGo.Enabled := True;
scPessoa.LookUpValue := '';
end;
procedure TFinLancamentoList.cmbSituacaoChange(Sender: TObject);
begin
inherited;
trmGo.Enabled := True;
end;
procedure TFinLancamentoList.scPessoaSelectItem(Sender: TObject);
begin
inherited;
trmGo.Enabled := True;
end;
procedure TFinLancamentoList.btSelEmpresaClick(Sender: TObject);
begin
inherited;
if btSelEmpresa.Down then
pnlEmpresa.Width := 150
else
pnlEmpresa.Width := 1;
end;
procedure TFinLancamentoList.Button1Click(Sender: TObject);
var
i: integer;
begin
inherited;
trmGo.Enabled := True;
// Marca todas as empresas
with lvEmpresa do
for i := 0 to Items.Count - 1 do
Items[i].Checked := True;
end;
procedure TFinLancamentoList.Button2Click(Sender: TObject);
var
i: integer;
begin
inherited;
trmGo.Enabled := True;
// Desmarca todas as empresas
with lvEmpresa do
for i := 0 to Items.Count - 1 do
Items[i].Checked := False;
end;
procedure TFinLancamentoList.lvEmpresaClick(Sender: TObject);
begin
inherited;
trmGo.Enabled := True;
end;
procedure TFinLancamentoList.bbQuitaClick(Sender: TObject);
var
ID1, ID2: String;
begin
inherited;
if (not OnBeforePay) then
Exit;
if (not ValidateLancamento) then
begin
MsgBox(MSG_CRT_SA_PAYMENT, vbCritical + vbOkOnly);
Exit;
end;
// Os lancamentos a serem quitados são passados para a ficha de quitacao
// atraves da tabela temporaria #AQuitar.
// Tenta criar a Tabela Temporária no Server
// se não conseguir e porque ela já existe.
try
CreateAQuitar;
except
// Como existe esvazia a tabela temporaria, exvazia-a.
DeleteAQuitar(-1);
end;
//Se o documento tiver mais de uma parte
if quBrowseIDLancamentoParent.AsInteger <> 0 then
begin
if MsgBox(MSG_QST_DOC_SPLITED_PAY_ALL + #13#10, vbQuestion + vbYesNo) = vbYes then
InsereAQuitar(quBrowse.FieldByName('IDLancamentoParent').AsInteger, True)
else
InsereAQuitar(quBrowse.FieldByName('IDLancamento').AsInteger, False);
end
else
// Inclui o registro selecionado na tabela temporária.
InsereAQuitar(quBrowse.FieldByName('IDLancamento').AsInteger, False);
// Caso necessario cria a ficha de pagamento.
if FinQuitacaoFch = Nil then
FinQuitacaoFch := TFinQuitacaoFch.Create(Self);
// Seta o parametro que vai ser passado para a ficha
if Self.Pagando then
FinQuitacaoFch.Param := 'Pagando=1'
else
FinQuitacaoFch.Param := 'Pagando=0';
// Abre a ficha de pagamento.
if FinQuitacaoFch.Start(btInc, nil, False, ID1, ID2, '', MyUserRights, nil) then
begin
ListRefresh;
end;
OnAfterPay;
end;
procedure TFinLancamentoList.bbQuitaMultiClick(Sender: TObject);
var
PID1, PID2: String;
begin
inherited;
if pnlQuitaMulti.Visible then
Exit;
// Os lancamentos a serem quitados são passados para a ficha de quitacao
// atraves da tabela temporaria #AQuitar.
// Abre o help do mover
if FinQuitacaoMoverHelp = Nil then
FinQuitacaoMoverHelp := TFinQuitacaoMoverHelp.Create(Self);
FinQuitacaoMoverHelp.ShowModal;
bbQuita.Visible := ivNever;
// Some com os botoes de quitacao - Access Vialotion
//bbQuitaMulti.Visible := ivNever;
// Abre a Toolbar do Mover
if FinQuitacaoToolBarMover = Nil then
FinQuitacaoToolBarMover := TFinQuitacaoToolBarMover.Create(Self);
FinQuitacaoToolBarMover.Show;
// Mostra o Panel de MultiQuitacao
pnlQuitaMulti.Visible := True;
// Tenta criar a Tabela Temporária no Server
// se não conseguir e porque ela já existe.
try
CreateAQuitar;
except
// Como existe esvazia a tabela temporaria.
DeleteAQuitar(-1);
end;
// Liga o grid e o Total
quAQuitar.Close;
quAQuitar.Open;
end;
procedure TFinLancamentoList.bbHistoricoClick(Sender: TObject);
begin
inherited;
brwGrid.ColumnByFieldName('LancamentoTipo').Visible := not bbHistorico.Down;
if bbHistorico.Down then
brwGrid.Options := brwGrid.Options + [egoPreview]
else
brwGrid.Options := brwGrid.Options - [egoPreview];
end;
procedure TFinLancamentoList.bbListaImprimeClick(Sender: TObject);
var
i: Integer;
ListaDeEmpresas: String;
begin
// Ajusta os Multiplos totais dos lancamentos
with dxDBGridPrint.CustomTot do
begin
Clear;
if Pagando then
begin
Add('Total');
Add(FloatToStrF(Tot, ffCurrency, 20, 2));
Add(sTotalPaid);
Add(FloatToStrF(TotQuitado, ffCurrency, 20, 2));
Add(sTotalToBePaid);
Add(FloatToStrF(TotAQuitar, ffCurrency, 20, 2));
end
else
begin
Add('Total');
Add(FloatToStrF(Tot, ffCurrency, 20, 2));
Add(sTotalRecv);
Add(FloatToStrF(TotQuitado, ffCurrency, 20, 2));
Add(sTotalToBeRecv);
Add(FloatToStrF(TotAQuitar, ffCurrency, 20, 2));
end;
end;
MyReportFilter := sRecords +
LowerCase(cmbSituacao.text) +
sWith +
LowerCase(cmbData.text) +
sBetween +
FormatDateTime('mm/dd/yyyy', dbInicio.Date) +
sAnd +
FormatDateTime('mm/dd/yyyy', dbFim.Date) +
sCompany;
with lvEmpresa do
for i := 0 to Items.Count - 1 do
if Items[i].Checked then
begin
if ListaDeEmpresas <> '' then
ListaDeEmpresas := ListaDeEmpresas + ', ';
ListaDeEmpresas := ListaDeEmpresas + Items[i].Caption;
end;
MyReportFilter := MyReportFilter + ListaDeEmpresas;
// Ajusta o filtro
with dxDBGridPrint do
begin
FilterText := MyReportFilter;
end;
inherited;
end;
procedure TFinLancamentoList.bbImprimeLancamentoClick(Sender: TObject);
var
Where, sTitle: String;
i: integer;
begin
inherited;
// Imprime os lancamentos em formato detalhado
if brwGrid.SelectedCount = 0 then
begin
MsgBox(MSG_CRT_NO_RECORD, vbCritical + vbOkOnly);
Exit;
end;
// Monta a clausula where com as quitacaoes selecionadas
with brwGrid, brwGrid.datasource.dataset do
begin
DisableControls;
for i:= 0 to SelectedCount-1 do
begin
BookMark := SelectedRows[i];
if Where <> '' then
Where := Where + ' OR '
else
Where := 'WHERE ';
Where := Where + '(IDLancamento = ' + FieldByName('IDLancamento').asString + ')';
end;
EnableControls;
end;
// Realiza a impressao dos cheques
if Pagando then
sTitle := 'Comprovante de Pagamento';
with TFinLancamentoQrp.Create(self) do
begin
Start(Where, sTitle);
Free;
end;
end;
procedure TFinLancamentoList.brwGridCustomDraw(Sender: TObject;
ACanvas: TCanvas; ARect: TRect; ANode: TdxTreeListNode;
AColumn: TdxDBTreeListColumn; const AText: String; AFont: TFont;
var AColor: TColor; ASelected, AFocused: Boolean; var ADone: Boolean);
var
G: TdxDBGrid;
begin
// inherited;
if ANode.HasChildren then Exit;
G := Sender as TdxDBGrid;
if not ASelected then
begin
if ANode.Values[brwGridDiscountValue.Index] <> null then
AColor := $00F0F0FF
else
begin
if (not (egoPreview in G.Options)) AND (ANode.Index mod 2 = 0) then
AColor := clWindow
else
AColor := $00EEEEEE;
end;
end;
if ANode.Selected then
begin
AColor := G.HighlightColor;
AFont.Color := $00EEEEEE;
end;
end;
procedure TFinLancamentoList.imgLancTypeChange(Sender: TObject);
begin
inherited;
trmGo.Enabled := True;
if imgLancType.Text = '0' then
begin
bbQuita.Visible := ivAlways;
bbQuitaMulti.Visible := ivAlways;
brwGridLancamentoTipo.Visible := True;
cmbSituacao.Enabled := True;
end
else
begin
bbQuita.Visible := ivNever;
bbQuitaMulti.Visible := ivNever;
brwGridLancamentoTipo.Visible := False;
cmbSituacao.ItemIndex := 3;
cmbSituacao.Enabled := False;
end;
ListParamRefresh;
end;
procedure TFinLancamentoList.btnTaxesClick(Sender: TObject);
begin
inherited;
with TFinTaxComper.Create(Self) do
Start;
end;
procedure TFinLancamentoList.edtAmountKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := ValidateCurrency(Key);
end;
procedure TFinLancamentoList.btnLoanClick(Sender: TObject);
begin
inherited;
with TFinEmprestimoFrm.Create(Self) do
try
Start;
finally
Free;
end
end;
procedure TFinLancamentoList.bbImprimeBoletoClick(Sender: TObject);
var
i: Integer;
begin
inherited;
// Imprime os boletos dos lançamentos selecionados
if brwGrid.SelectedCount = 0 then
begin
MsgBox(MSG_CRT_NO_RECORD, vbCritical + vbOkOnly);
Exit;
end;
// Faz a chamada do objeto de impressão para cada lançamento
with brwGrid, brwGrid.datasource.dataset do
try
DisableControls;
for i := 0 to Pred(SelectedCount) do
begin
BookMark := SelectedRows[i];
with TFrmPrintBoleto.Create(Self) do
Start(quBrowseIDLancamento.AsInteger);
end;
finally
EnableControls;
end;
end;
procedure TFinLancamentoList.bbExportarBoletoClick(Sender: TObject);
var
i: Integer;
LancamentoList: array of Integer;
begin
inherited;
// Imprime os boletos dos lançamentos selecionados
if brwGrid.SelectedCount = 0 then
begin
MsgBox(MSG_CRT_NO_RECORD, vbCritical + vbOkOnly);
Exit;
end;
// Faz a chamada do objeto de impressão para cada lançamento
with brwGrid, brwGrid.datasource.dataset do
try
DisableControls;
SetLength(LancamentoList, SelectedCount);
for i := 0 to Pred(SelectedCount) do
begin
BookMark := SelectedRows[i];
LancamentoList[i] := quBrowseIDLancamento.AsInteger;
end;
with TFrmExportBoleto.Create(Self) do
Start(LancamentoList);
finally
EnableControls;
end;
end;
function TFinLancamentoList.ValidateLancamento: Boolean;
begin
Result := (quBrowseTipoMeioPag.AsInteger <> 9);
end;
Initialization
RegisterClass(TFinLancamentoList);
end.
|
unit libutils;
interface
type
TStrArray = array of string;
TCommandChain = array of TStrArray;
function is_int( s: string ): boolean;
procedure push( var a: TStrArray; s: String );
procedure push( var a: TCommandChain; s: TStrArray );
function str_split( str: string; delimiter: string ): TStrArray;
function preg_match( str: string; pattern: string ): boolean;
implementation
uses oldregexpr, strings;
function is_int( s: string ): boolean;
var i: integer;
begin
if s = '' then exit( false );
for i := 1 to length( s ) do
begin
case s[i] of
'0'..'9': begin
end else exit( false );
end;
end;
exit( true );
end;
procedure push( var a: tstrarray; s: string );
var len: integer;
begin
len := length( a );
setlength( a, len + 1 );
a[ len ] := s;
end;
procedure push( var a: TCommandChain; s: TStrArray );
var len: integer;
begin
len := length( a );
setLength( a, len + 1 );
a[ len ] := s;
end;
function str_split( str: string; delimiter: string ): TStrArray;
var out: TStrArray;
i: integer;
n: integer;
item: string;
dlen: integer;
begin
n := length( str );
i := 1;
item := '';
dlen := length( delimiter );
while i <= n do begin
if copy( str, i, dlen ) = delimiter then
begin
push( out, item );
item := '';
i := i + dlen - 1;
end else
begin
item := concat( item, str[i] );
end;
inc( i );
end;
push( out, item );
exit( out );
end;
function preg_match( str: string; pattern: string ): boolean;
var initok: boolean;
r: tregexprengine;
index,
len: longint;
p: pchar;
p1: pchar;
begin
p := stralloc( length( pattern ) + 1 );
strpcopy( p, pattern );
initok := GenerateRegExprEngine( p, [ ref_caseinsensitive ], r );
if not initok then
begin
DestroyregExprEngine( r );
strdispose( p );
exit( false );
end;
p1 := stralloc( length( str ) + 1 );
strpcopy( p1, str );
if not(RegExprPos( r, p1, index, len ) ) then
begin
DestroyregExprEngine( r );
strdispose( p );
strdispose( p1 );
exit( false );
end else
begin
DestroyregExprEngine( r );
strdispose( p );
strdispose( p1 );
exit( true );
end;
end;
end. |
unit uLogger;
interface
uses
System.Classes,
System.SysUtils,
System.SyncObjs,
Winapi.Windows,
uConfiguration,
uMemory;
{$DEFINE _EVENTLOG}
type
TLogger = class(TObject)
private
{$IFDEF EVENTLOG}
FFile: TFileStream;
SW: TStreamWriter;
FSync: TCriticalSection;
{$ENDIF}
public
constructor Create;
destructor Destroy; override;
class function Instance: TLogger;
procedure Message(Value: string);
end;
procedure EventLog(Message: string); overload;
procedure EventLog(Ex: Exception); overload;
implementation
var
Logger: TLogger = nil;
procedure EventLog(Ex: Exception);
var
Msg, Stack: String;
Inner: Exception;
begin
Inner := Ex;
Msg := '';
while Inner <> nil do
begin
if Msg <> '' then
Msg := Msg + sLineBreak;
Msg := Msg + Inner.Message;
if (Msg <> '') and (Msg[Length(Msg)] > '.') then
Msg := Msg + '.';
Stack := Inner.StackTrace;
if Stack <> '' then
begin
if Msg <> '' then
Msg := Msg + sLineBreak + sLineBreak;
Msg := Msg + Stack + sLineBreak;
end;
Inner := Inner.InnerException;
end;
EventLog(Msg);
end;
procedure EventLog(Message: string);
begin
{$IFDEF EVENTLOG}
TLogger.Instance.Message(Message);
{$ENDIF}
end;
{ TLogger }
constructor TLogger.Create;
begin
{$IFDEF EVENTLOG}
FSync := TCriticalSection.Create;
SW := nil;
try
FFile := TFileStream.Create(GetAppDataDirectory + '\EventLog' + FormatDateTime('yyyy-mm-dd-HH-MM-SS', Now) + '.txt', fmCreate);
SW := TStreamWriter.Create(FFile);
except
on e: Exception do
MessageBox(0, PChar(e.Message), PChar('ERROR!'), MB_OK + MB_ICONERROR);
end;
{$ENDIF EVENTLOG}
end;
destructor TLogger.Destroy;
begin
{$IFDEF EVENTLOG}
F(SW);
F(FFile);
F(FSync);
{$ENDIF EVENTLOG}
inherited;
end;
class function TLogger.Instance: TLogger;
begin
if Logger = nil then
Logger := TLogger.Create;
Result := Logger;
end;
procedure TLogger.Message(Value: string);
begin
{$IFDEF EVENTLOG}
FSync.Enter;
try
Value := Value + #13#10;
SW.Write(Value);
finally
FSync.Leave;
end;
{$ENDIF EVENTLOG}
end;
initialization
finalization
F(Logger);
end.
|
unit FdefDac2;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses windows,classes,sysutils,
util1,Gdos,dtf0,descac1,spk0,blocInf0,debug0,Mtag0;
{ Définition de la structure d'un fichier Elphy/Dac2
Un fichier DAC2 commence par typeHeaderDac2: le mot clé permet d'identifier le
type de fichier. TailleInfo donne la taille totale du bloc d'info qui précède les
données.
On trouve ensuite plusieurs sous-blocs qui commencent tous par un enregistrement
de type typeHeaderDac2 (id+taille).
Le premier bloc est appelé 'MAIN' et contient typeInfoDac2
Ensuite, on pourra trouver zéro ou plusieurs blocs. Par exemple, un bloc 'STIM'
et un bloc 'USER INFO' .
}
const
signatureDAC2='DAC2/GS/2000';
signatureDAC2Seq='DAC2SEQ';
signatureDAC2main='MAIN';
type
typeHeaderDac2=object
id:string[15]; {garder 15 comme pour Acquis1}
tailleInfo:integer;
procedure init(taille:integer);
procedure init2(ident:AnsiString;taille:integer);
procedure write(var f:file);overload;
procedure write(f:TfileStream);overload;
procedure UWrite(var f:file);overload;
procedure UWrite(f:TfileStream);overload;
end;
TAdcChannel=record { 27 octets }
uY:string[10];
Dyu,Y0u:double;
end;
{Bloc écrit avant chaque séquence
On n'écrit que les infos correspondant au nombre de voies.
Après adcChannel, on pourra ajouter des info mais le déplacement ne sera pas
fixe.
}
typeInfoSeqDAC2=
object
id:string[7]; {'DAC2SEQ'}
tailleInfo:integer;
nbvoie:byte;
nbpt:integer;
tpData:typeTypeG;
postSeqI:integer;
uX:string[10];
Dxu,x0u:double;
adcChannel:array[1..16] of TAdcChannel; { 49 octets + nbvoie*27 }
procedure init(nbvoie1:integer);
procedure write(var f:file);overload;
procedure write(f:TfileStream);overload;
function seqSize:integer;
function dataSize:integer;
end;
typeInfoDAC2=
object
id:string[15]; {garder 15 comme pour Acquis1}
tailleInfo:integer;
nbvoie:byte;
nbpt:integer;
tpData:typeTypeG;
uX:string[10];
Dxu,x0u:double;
adcChannel:array[1..16] of TAdcChannel;
preseqI,postSeqI:integer;
continu:boolean;
VariableEp:boolean;
WithTags:boolean;
TagShift:byte;
procedure init(taille:integer);
procedure write(var f:file);overload;
procedure write(f:TfileStream);overload;
procedure setInfoSeq(var infoSeq:typeInfoSeqDAC2);
function controleOK:boolean;
end;
PinfoDac2=^TypeInfoDac2;
procedure SaveArrayAsDac2File(st:AnsiString;var tb;NbPt1,NbV1:integer;tp:typetypeG);overload;
procedure SaveArrayAsDac2File(st:AnsiString;var tb;NbPt1:integer;tp:typetypeG);overload;
implementation
{************************ Méthodes de TypeHeaderDAC2 ***********************}
procedure TypeHeaderDAC2.init(taille:integer);
begin
fillchar(id,sizeof(id),0);
id:=signatureDAC2;
tailleInfo:=taille;
end;
procedure TypeHeaderDAC2.init2(ident:AnsiString;taille:integer);
begin
fillchar(id,sizeof(id),0);
id:=ident;
tailleInfo:=taille;
end;
procedure TypeHeaderDAC2.write(var f:file);
var
res:integer;
begin
blockWrite(f,self,sizeof(TypeHeaderDAC2),res);
end;
procedure TypeHeaderDAC2.write(f:TfileStream);
var
res:intG;
begin
f.write(self,sizeof(TypeHeaderDAC2));
end;
procedure typeHeaderDac2.UWrite(var f:file);
var
header:typeHeaderDac2;{header fichier}
res:integer;
begin
seek(f,0);
blockread(f,header,sizeof(header),res);
header.tailleInfo:=header.tailleInfo+tailleInfo;
seek(f,0);
blockwrite(f,header,sizeof(header),res);
seek(f,fileSize(f));
blockwrite(f,self,sizeof(TypeHeaderDAC2),res);
end;
procedure typeHeaderDac2.UWrite(f:TfileStream);
var
header:typeHeaderDac2;{header fichier}
res:integer;
begin
f.position:=0;
f.read(header,sizeof(header));
header.tailleInfo:=header.tailleInfo+tailleInfo;
f.Position:=0;
f.write(header,sizeof(header));
f.Position:=f.size;
f.write(self,sizeof(TypeHeaderDAC2));
end;
{************************ Méthodes de TypeInfoDAC2 ***********************}
procedure TypeInfoDAC2.init(taille:integer);
var
i:integer;
begin
fillchar(id,sizeof(TypeInfoDAC2),0);
id:=signatureDac2Main;
tailleInfo:=taille;
nbvoie:=1;
nbpt:=1000;
uX:='';
Dxu:=1;
x0u:=0;
for i:=1 to 16 do
with adcChannel[i] do
begin
y0u:=0;
dyu:=1;
uy:='';
end;
continu:=false;
preseqI:=0;
postSeqI:=0;
tpData:=G_smallint;
end;
procedure TypeInfoDAC2.write(var f:file);
var
res:integer;
begin
blockWrite(f,self,sizeof(TypeInfoDAC2),res);
end;
procedure TypeInfoDAC2.write(f:TfileStream);
begin
f.Write(self,sizeof(TypeInfoDAC2));
end;
procedure TypeInfoDAC2.setInfoSeq(var infoSeq:typeInfoSeqDAC2);
var
i:integer;
begin
infoSeq.init(nbvoie);
infoSeq.nbvoie:=nbvoie;
infoSeq.tpData:=tpData;
infoSeq.postSeqI:=postSeqI;
infoSeq.ux:=ux;
infoSeq.dxu:=dxu;
infoSeq.x0u:=x0u;
for i:=1 to nbvoie do
infoSeq.adcChannel[i]:=adcChannel[i];
end;
function typeInfoDac2.controleOK:boolean;
var
i:integer;
begin
result:=false;
if (nbvoie<0) or (nbvoie>16) then
begin
messageCentral('Anomalous number of channels: '+Istr(nbvoie));
exit;
end;
if not (tpData in [G_word, G_smallint,G_longint,G_single]) then
begin
messageCentral('Unrecognized number type '+Istr(byte(tpData)));
exit;
end;
if dxu<=0 then
begin
messageCentral('Anomalous X-scale parameters' );
exit;
end;
for i:=1 to nbvoie do
if adcChannel[i].Dyu=0 then
begin
messageCentral('Anomalous Y-scale parameters');
exit;
end;
result:=true;
end;
{******************** Méthodes de typeInfoSeqDAC2 *************************}
procedure typeInfoSeqDAC2.init(nbvoie1:integer);
var
i:integer;
begin
id:=signatureDAC2Seq;
tailleInfo:=sizeof(TypeInfoSeqDAC2)-sizeof(TadcChannel)*(16-nbvoie1);
nbvoie:=nbvoie1;
nbpt:=1000;
uX:='';
Dxu:=1;
x0u:=0;
for i:=1 to 16 do
with adcChannel[i] do
begin
y0u:=0;
dyu:=1;
uy:='';
end;
postSeqI:=0;
tpData:=G_smallint;
end;
procedure typeInfoSeqDAC2.write(var f:file);
var
res:integer;
begin
blockWrite(f,self,tailleInfo,res);
end;
procedure typeInfoSeqDAC2.write(f:TfileStream);
begin
f.Write(self,tailleInfo);
end;
function typeInfoSeqDAC2.DataSize:integer;
begin
result:=nbpt*nbvoie*tailleTypeG[tpData];
end;
function typeInfoSeqDAC2.seqSize:integer;
begin
result:=tailleInfo+dataSize+postSeqI;
end;
procedure SaveArrayAsDac2File(st:AnsiString;var tb;NbPt1,nbV1:integer;tp:typetypeG);
var
res:integer;
header:typeInfoDac2;
headerDac2:typeHeaderDac2;
infoseq:typeInfoSeqDAC2;
tailleTot:integer;
f:TfileStream;
begin
tailleTot:=sizeof(headerDac2)+sizeof(header);
HeaderDac2.init(tailleTot);
header.init(sizeof(typeInfoDac2));
InfoSeq.init(NbV1);
with header do
begin
nbVoie:=nbV1;
nbPt:=nbPt1 div nbV1;
preSeqI:=sizeof(typeInfoSeqDac2)-(16-NbV1)*sizeof(TadcChannel);
tpData:=tp;
end;
f:=nil;
try
f:=TfileStream.create(st,fmCreate);
headerDac2.write(f);
header.write(f);
header.setInfoSeq(infoSeq);
infoseq.write(f);
f.Write(tb,nbPt1*tailleTypeG[tp]);
f.Free;
except
f.free;
end;
end;
procedure SaveArrayAsDac2File(st:AnsiString;var tb;NbPt1:integer;tp:typetypeG);
begin
SaveArrayAsDac2File(st,tb,NbPt1,1,tp);
end;
end.
|
Unit Figures;
interface
uses Graph, Stack;
type
PFigureStack = ^TFigureStack;
TFigureStack = object (TStack)
p: Real;
constructor Init(p0: Real);
procedure Tick;
destructor Done; virtual;
end;
PFigure=^TFigure;
TFigure = object (TStackable)
x, y, vx, vy: Integer;
constructor Init(x0, y0: Integer; vx0, vy0: Integer);
procedure Show; virtual;
procedure Hide; virtual;
procedure Tick;
function InScreen(): Boolean; virtual;
destructor Done; virtual;
end;
PCircle=^TCircle;
TCircle = object (TFigure)
R: Integer;
constructor Init(x0, y0: Integer; vx0, vy0: Integer; R0: Integer);
procedure Show; virtual;
procedure Hide; virtual;
function InScreen(): Boolean; virtual;
destructor Done; virtual;
end;
PSquare=^TSquare;
TSquare = object (TFigure)
Side: Integer;
constructor Init(x0, y0: Integer; vx0, vy0: Integer; Side0: Integer);
procedure Show; virtual;
procedure Hide; virtual;
function InScreen(): Boolean; virtual;
destructor Done; virtual;
end;
implementation
{Реализация методов класса TFigureStack}
constructor TFigureStack.Init(p0: Real);
begin
inherited Init;
Randomize;
p:= p0;
end;
procedure TFigureStack.Tick;
Var f: PFigure;
tmp: PFigureStack;
ux, uy: Integer;
begin
If not Empty Then begin
f:= PFigure(Pop);
f^.Tick;
Tick;
Push(f);
end;
If Random<p Then begin
ux:= 5 + Random(7);
If Random(2) = 0 Then ux:= -ux;
uy:= 5 + Random(7);
If Random(2) = 0 Then uy:= -uy;
If Random(2)=0 Then Begin
f:= New(PCircle, Init( GetMaxX div 2, GetMaxY div 2, ux, uy, 5));
End
Else Begin
f:= New(PSquare, Init( GetMaxX div 2 - 2, GetMaxY div 2 - 2, ux, uy, 5));
End;
f^.Show;
Push(f);
end;
tmp:= New (PFigureStack, Init(0));
While not Empty Do Begin
f:= PFigure(Pop());
If f^.InScreen Then Begin
tmp^.Push(f);
End
Else Begin
Dispose(f, Done);
End;
End;
While not tmp^.Empty Do Begin
Push(tmp^.Pop());
End;
Dispose(tmp, Done);
end;
destructor TFigureStack.Done;
begin
inherited;
end;
{Реализация методов класса TFigure}
constructor TFigure.Init(x0, y0: Integer; vx0, vy0: Integer);
begin
Inherited Init;
x:= x0; y:= y0;
vx:= vx0; vy:= vy0;
end;
procedure TFigure.Show;
begin
RunError(211);
end;
procedure TFigure.Hide;
begin
RunError(211);
end;
procedure TFigure.Tick;
begin
Hide;
x:= x+vx;
y:= y+vy;
Show;
end;
function TFigure.InScreen(): Boolean;
begin
RunError(211);
end;
destructor TFigure.Done;
begin
end;
{Реализация методов класса TCircle}
constructor TCircle.Init(x0, y0: Integer; vx0, vy0: Integer; R0: Integer);
begin
inherited Init(x0, y0, vx0, vy0);
R:= R0;
end;
procedure TCircle.Show;
begin
Circle(x, y, R);
end;
procedure TCircle.Hide;
var t: Word;
begin
t:= GetColor;
SetColor(GetBkColor());
Circle(x, y, R);
SetColor(t);
end;
function TCircle.InScreen(): Boolean;
begin
InScreen:= (x>=R) and (y>=R) and (x+R<=GetMaxX) and (y+R<=GetMaxY);
end;
destructor TCircle.Done;
begin
Hide();
end;
{Реализация методов класса TSquare}
constructor TSquare.Init(x0, y0: Integer; vx0, vy0: Integer; Side0: Integer);
begin
inherited Init(x0, y0, vx0, vy0);
Side:= Side0;
end;
procedure TSquare.Show;
begin
Rectangle(x, y, x+Side, y+Side);
end;
procedure TSquare.Hide;
var t: Word;
begin
t:= GetColor;
SetColor(GetBkColor());
Rectangle(x, y, x+Side, y+Side);
SetColor(t);
end;
function TSquare.InScreen(): Boolean;
begin
InScreen:= (x>=0) and (y>=0) and (x+Side<=GetMaxX) and (y+Side<=GetMaxY);
end;
destructor TSquare.Done;
begin
Hide();
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFWorkScheduler;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
WinApi.Windows, WinApi.Messages, System.Classes, Vcl.Controls, Vcl.Graphics, Vcl.Forms,
{$ELSE}
Windows, Messages, Classes, Controls, Graphics, Forms,
{$ENDIF}
uCEFTypes, uCEFInterfaces, uCEFLibFunctions, uCEFMiscFunctions, uCEFConstants;
const
TIMER_NIDEVENT = 1;
TIMER_DEPLETEWORK_CYCLES = 10;
TIMER_DEPLETEWORK_DELAY = 50;
type
TCEFWorkScheduler = class(TComponent)
protected
FCompHandle : HWND;
FDepleteWorkCycles : cardinal;
FDepleteWorkDelay : cardinal;
FTimerPending : boolean;
FIsActive : boolean;
FReentrancyDetected : boolean;
FStopped : boolean;
procedure WndProc(var aMessage: TMessage);
function SendCompMessage(aMsg, wParam : cardinal; lParam : integer) : boolean;
procedure CreateTimer(const delay_ms : int64);
procedure TimerTimeout;
procedure DoWork;
procedure ScheduleWork(const delay_ms : int64);
procedure DoMessageLoopWork;
function PerformMessageLoopWork : boolean;
procedure DestroyTimer;
procedure DeallocateWindowHandle;
procedure DepleteWork;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AfterConstruction; override;
procedure ScheduleMessagePumpWork(const delay_ms : int64);
procedure StopScheduler;
property IsTimerPending : boolean read FTimerPending;
published
property DepleteWorkCycles : cardinal read FDepleteWorkCycles write FDepleteWorkCycles default TIMER_DEPLETEWORK_CYCLES;
property DepleteWorkDelay : cardinal read FDepleteWorkDelay write FDepleteWorkDelay default TIMER_DEPLETEWORK_DELAY;
end;
implementation
uses
{$IFDEF DELPHI16_UP}
System.SysUtils, System.Math,
{$ELSE}
SysUtils, Math,
{$ENDIF}
uCEFApplication;
constructor TCEFWorkScheduler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCompHandle := 0;
FTimerPending := False;
FIsActive := False;
FReentrancyDetected := False;
FStopped := False;
FDepleteWorkCycles := TIMER_DEPLETEWORK_CYCLES;
FDepleteWorkDelay := TIMER_DEPLETEWORK_DELAY;
end;
destructor TCEFWorkScheduler.Destroy;
begin
DestroyTimer;
DeallocateWindowHandle;
inherited Destroy;
end;
procedure TCEFWorkScheduler.AfterConstruction;
begin
inherited AfterConstruction;
if not(csDesigning in ComponentState) then
FCompHandle := AllocateHWnd(WndProc);
end;
procedure TCEFWorkScheduler.WndProc(var aMessage: TMessage);
begin
case aMessage.Msg of
WM_TIMER : TimerTimeout;
CEF_PUMPHAVEWORK : ScheduleWork(aMessage.lParam);
else aMessage.Result := DefWindowProc(FCompHandle, aMessage.Msg, aMessage.WParam, aMessage.LParam);
end;
end;
function TCEFWorkScheduler.SendCompMessage(aMsg, wParam : cardinal; lParam : integer) : boolean;
begin
Result := not(FStopped) and (FCompHandle <> 0) and PostMessage(FCompHandle, aMsg, wParam, lParam);
end;
procedure TCEFWorkScheduler.CreateTimer(const delay_ms : int64);
begin
if not(FTimerPending) and
not(FStopped) and
(delay_ms > 0) and
(SetTimer(FCompHandle, TIMER_NIDEVENT, cardinal(delay_ms), nil) <> 0) then
FTimerPending := True;
end;
procedure TCEFWorkScheduler.DestroyTimer;
begin
if FTimerPending and KillTimer(FCompHandle, TIMER_NIDEVENT) then FTimerPending := False;
end;
procedure TCEFWorkScheduler.DeallocateWindowHandle;
begin
if (FCompHandle <> 0) then
begin
DeallocateHWnd(FCompHandle);
FCompHandle := 0;
end;
end;
procedure TCEFWorkScheduler.DepleteWork;
var
i : cardinal;
begin
i := FDepleteWorkCycles;
while (i > 0) do
begin
DoMessageLoopWork;
Sleep(FDepleteWorkDelay);
dec(i);
end;
end;
procedure TCEFWorkScheduler.ScheduleMessagePumpWork(const delay_ms : int64);
begin
SendCompMessage(CEF_PUMPHAVEWORK, 0, LPARAM(delay_ms));
end;
procedure TCEFWorkScheduler.StopScheduler;
begin
FStopped := True;
DestroyTimer;
DepleteWork;
DeallocateWindowHandle;
end;
procedure TCEFWorkScheduler.TimerTimeout;
begin
if not(FStopped) then
begin
DestroyTimer;
DoWork;
end;
end;
procedure TCEFWorkScheduler.DoWork;
var
TempWasReentrant : boolean;
begin
TempWasReentrant := PerformMessageLoopWork;
if TempWasReentrant then
ScheduleMessagePumpWork(0)
else
if not(IsTimerPending) then
ScheduleMessagePumpWork(CEF_TIMER_DELAY_PLACEHOLDER);
end;
procedure TCEFWorkScheduler.ScheduleWork(const delay_ms : int64);
begin
if FStopped or
((delay_ms = CEF_TIMER_DELAY_PLACEHOLDER) and IsTimerPending) then
exit;
DestroyTimer;
if (delay_ms <= 0) then
DoWork
else
if (delay_ms > CEF_TIMER_MAXDELAY) then
CreateTimer(CEF_TIMER_MAXDELAY)
else
CreateTimer(delay_ms);
end;
procedure TCEFWorkScheduler.DoMessageLoopWork;
begin
if (GlobalCEFApp <> nil) then GlobalCEFApp.DoMessageLoopWork;
end;
function TCEFWorkScheduler.PerformMessageLoopWork : boolean;
begin
Result := False;
if FIsActive then
begin
FReentrancyDetected := True;
exit;
end;
FReentrancyDetected := False;
FIsActive := True;
DoMessageLoopWork;
FIsActive := False;
Result := FReentrancyDetected;
end;
end.
|
unit MT5.Api;
interface
uses
System.SysUtils, System.Generics.Collections,
MT5.Connect, MT5.RetCode, MT5.Auth, MT5.Order,
MT5.Position, MT5.History, MT5.Deal, MT5.User;
type
TMTApi = class
private
{ private declarations }
FMTConnect: TMTConnect;
FAgent: string;
FIsCrypt: Boolean;
protected
{ protected declarations }
public
{ public declarations }
constructor Create(const AAgent: string = 'WebAPI'; AIsCrypt: Boolean = True);
destructor Destroy; override;
function Connect(AIp: string; APort: Word; ATimeout: Integer; ALogin: string; APassword: string): TMTRetCodeType;
procedure Disconnect;
// ORDER
function OrderGet(ATicket: string; out AOrder: TMTOrder): TMTRetCodeType;
function OrderGetPage(ALogin, AOffset, ATotal: Integer; out AOrdersCollection: TArray<TMTOrder>): TMTRetCodeType;
function OrderGetTotal(ALogin: Integer; out ATotal: Integer): TMTRetCodeType;
// POSITION
function PositionGet(ALogin: Integer; ASymbol: string; out APosition: TMTPosition): TMTRetCodeType;
function PositionGetPage(ALogin, AOffset, ATotal: Integer; out APositionsCollection: TArray<TMTPosition>): TMTRetCodeType;
function PositionGetTotal(ALogin: Integer; out ATotal: Integer): TMTRetCodeType;
// HISTORY
function HistoryGet(ATicket: string; out AHistory: TMTOrder): TMTRetCodeType;
function HistoryGetPage(ALogin, AFrom, ATo, AOffset, ATotal: Integer; out AHistorysCollection: TArray<TMTOrder>): TMTRetCodeType;
function HistoryGetTotal(ALogin, AFrom, ATo: Integer; out ATotal: Integer): TMTRetCodeType;
// DEAL
function DealGet(ATicket: string; out ADeal: TMTDeal): TMTRetCodeType;
function DealGetPage(ALogin, AFrom, ATo, AOffset, ATotal: Integer; out ADealsCollection: TArray<TMTDeal>): TMTRetCodeType;
function DealGetTotal(ALogin, AFrom, ATo: Integer; out ATotal: Integer): TMTRetCodeType;
//
function UserGet(ALogin: Int64; out AUser: TMTUser): TMTRetCodeType;
end;
implementation
{ TMTApi }
function TMTApi.Connect(AIp: string; APort: Word; ATimeout: Integer; ALogin, APassword: string): TMTRetCodeType;
var
LConnectionCode: TMTRetCodeType;
LAuthCode: TMTRetCodeType;
LAuthProtocol: TMTAuthProtocol;
LCryptRand: string;
begin
Result := TMTRetCodeType.MT_RET_ERROR;
FMTConnect := TMTConnect.Create(AIp, APort, ATimeout);
LConnectionCode := FMTConnect.Connect;
if LConnectionCode <> TMTRetCodeType.MT_RET_OK then
Exit(LConnectionCode);
LAuthProtocol := TMTAuthProtocol.Create(FMTConnect, FAgent);
try
LCryptRand := '';
LAuthCode := LAuthProtocol.Auth(ALogin, APassword, FIsCrypt, LCryptRand);
if LAuthCode <> TMTRetCodeType.MT_RET_OK then
begin
FMTConnect.Disconnect;
Exit(LAuthCode);
end;
if FIsCrypt then
FMTConnect.SetCryptRand(LCryptRand, APassword);
Result := LAuthCode;
finally
LAuthProtocol.Free;
end;
end;
constructor TMTApi.Create(const AAgent: string; AIsCrypt: Boolean);
begin
FMTConnect := nil;
FAgent := AAgent;
FIsCrypt := FIsCrypt;
end;
function TMTApi.DealGet(ATicket: string; out ADeal: TMTDeal): TMTRetCodeType;
var
LDealProtocol: TMTDealProtocol;
begin
LDealProtocol := TMTDealProtocol.Create(FMTConnect);
try
Result := LDealProtocol.DealGet(ATicket, ADeal);
finally
LDealProtocol.Free;
end;
end;
function TMTApi.DealGetPage(ALogin, AFrom, ATo, AOffset, ATotal: Integer; out ADealsCollection: TArray<TMTDeal>): TMTRetCodeType;
var
LDealProtocol: TMTDealProtocol;
begin
LDealProtocol := TMTDealProtocol.Create(FMTConnect);
try
Result := LDealProtocol.DealGetPage(ALogin, AFrom, ATo, AOffset, ATotal, ADealsCollection);
finally
LDealProtocol.Free;
end;
end;
function TMTApi.DealGetTotal(ALogin, AFrom, ATo: Integer; out ATotal: Integer): TMTRetCodeType;
var
LDealProtocol: TMTDealProtocol;
begin
LDealProtocol := TMTDealProtocol.Create(FMTConnect);
try
Result := LDealProtocol.DealGetTotal(ALogin, AFrom, ATo, ATotal);
finally
LDealProtocol.Free;
end;
end;
destructor TMTApi.Destroy;
begin
if FMTConnect <> nil then
FMTConnect.Free;
inherited;
end;
procedure TMTApi.Disconnect;
begin
if FMTConnect <> nil then
FMTConnect.Disconnect;
end;
function TMTApi.HistoryGet(ATicket: string; out AHistory: TMTOrder): TMTRetCodeType;
var
LHistoryProtocol: TMTHistoryProtocol;
begin
LHistoryProtocol := TMTHistoryProtocol.Create(FMTConnect);
try
Result := LHistoryProtocol.HistoryGet(ATicket, AHistory);
finally
LHistoryProtocol.Free;
end;
end;
function TMTApi.HistoryGetPage(ALogin, AFrom, ATo, AOffset, ATotal: Integer; out AHistorysCollection: TArray<TMTOrder>): TMTRetCodeType;
var
LHistoryProtocol: TMTHistoryProtocol;
begin
LHistoryProtocol := TMTHistoryProtocol.Create(FMTConnect);
try
Result := LHistoryProtocol.HistoryGetPage(ALogin, AFrom, ATo, AOffset, ATotal, AHistorysCollection);
finally
LHistoryProtocol.Free;
end;
end;
function TMTApi.HistoryGetTotal(ALogin, AFrom, ATo: Integer; out ATotal: Integer): TMTRetCodeType;
var
LHistoryProtocol: TMTHistoryProtocol;
begin
LHistoryProtocol := TMTHistoryProtocol.Create(FMTConnect);
try
Result := LHistoryProtocol.HistoryGetTotal(ALogin, AFrom, ATo, ATotal);
finally
LHistoryProtocol.Free;
end;
end;
function TMTApi.OrderGet(ATicket: string; out AOrder: TMTOrder): TMTRetCodeType;
var
LOrderProtocol: TMTOrderProtocol;
begin
LOrderProtocol := TMTOrderProtocol.Create(FMTConnect);
try
Result := LOrderProtocol.OrderGet(ATicket, AOrder);
finally
LOrderProtocol.Free;
end;
end;
function TMTApi.OrderGetPage(ALogin, AOffset, ATotal: Integer; out AOrdersCollection: TArray<TMTOrder>): TMTRetCodeType;
var
LOrderProtocol: TMTOrderProtocol;
begin
LOrderProtocol := TMTOrderProtocol.Create(FMTConnect);
try
Result := LOrderProtocol.OrderGetPage(ALogin, AOffset, ATotal, AOrdersCollection);
finally
LOrderProtocol.Free;
end;
end;
function TMTApi.OrderGetTotal(ALogin: Integer; out ATotal: Integer): TMTRetCodeType;
var
LOrderProtocol: TMTOrderProtocol;
begin
LOrderProtocol := TMTOrderProtocol.Create(FMTConnect);
try
Result := LOrderProtocol.OrderGetTotal(ALogin, ATotal);
finally
LOrderProtocol.Free;
end;
end;
function TMTApi.PositionGet(ALogin: Integer; ASymbol: string; out APosition: TMTPosition): TMTRetCodeType;
var
LPositionProtocol: TMTPositionProtocol;
begin
LPositionProtocol := TMTPositionProtocol.Create(FMTConnect);
try
Result := LPositionProtocol.PositionGet(ALogin, ASymbol, APosition);
finally
LPositionProtocol.Free;
end;
end;
function TMTApi.PositionGetPage(ALogin, AOffset, ATotal: Integer; out APositionsCollection: TArray<TMTPosition>): TMTRetCodeType;
var
LPositionProtocol: TMTPositionProtocol;
begin
LPositionProtocol := TMTPositionProtocol.Create(FMTConnect);
try
Result := LPositionProtocol.PositionGetPage(ALogin, AOffset, ATotal, APositionsCollection);
finally
LPositionProtocol.Free;
end;
end;
function TMTApi.PositionGetTotal(ALogin: Integer; out ATotal: Integer): TMTRetCodeType;
var
LPositionProtocol: TMTPositionProtocol;
begin
LPositionProtocol := TMTPositionProtocol.Create(FMTConnect);
try
Result := LPositionProtocol.PositionGetTotal(ALogin, ATotal);
finally
LPositionProtocol.Free;
end;
end;
function TMTApi.UserGet(ALogin: Int64; out AUser: TMTUser): TMTRetCodeType;
var
LUserProtocol: TMTUserProtocol;
begin
LUserProtocol := TMTUserProtocol.Create(FMTConnect);
try
Result := LUserProtocol.Get(ALogin, AUser);
finally
LUserProtocol.Free;
end;
end;
end.
|
{
JoinMe! is an IRC server based on the RFC 1459 mIRC client & Bahamut server commands/replies
Copyright 2001(02) by Elias Konstadinidis
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
}
unit IRCSystemBotInterface;
{
IRCSystemBotInterface unit
(c) 9-7-2001
}
interface
uses
Windows;
const
// Bot Options
BOTOPT_OPERATOR = 1;
BOTOPT_VISIBLE = 2;
type
// Message structure
PIRCBotMessage = ^TIRCBotMessage;
TIRCBotMessage = record
size : integer;
Name : PChar;
User : PChar;
Host : PChar;
Command : PChar;
Params : PChar;
IsNumericCommand : boolean;
HasPrefix : boolean;
NameIsServer : boolean;
end;
// Bot procedure call
TBotsndMsgProc = procedure(cMsg : PChar; IRCBotMessage : PIRCBotMessage; SocketID:DWord); stdcall;
// Bot Init record
TBotIdentifyData = record
pBotName : PChar;
pBotPass : PChar;
BotOptions : cardinal;
Icon : HICON;
end;
// Dll exported functions
TFuncBotIdentify = function(var BotIdentifyData:TBotIdentifyData): boolean; stdcall;
{BotIdentify function}
TFuncBotConnect = function(SendMessageProc : TBotsndMsgProc;
SocketID:DWord): boolean; stdcall; {BotConnect function}
TFuncBotMessage = procedure(const IRCBotMessage : TIRCBotMessage;
cMsg : PChar); stdcall; {BotMessage function}
TFuncBotDisconnect = procedure; stdcall; {BotDisconnect function}
TFuncBotFinalization = procedure; stdcall; {BotFinalization function}
TFuncBotConfig = procedure; stdcall; {BotConfig function}
implementation
end.
|
{===============================================================================
RadiantGaugesForm Unit
Radiant Shapes - Demo Source Unit
Copyright © 2012-2014 by Raize Software, Inc. All Rights Reserved.
Modification History
------------------------------------------------------------------------------
1.0 (29 Oct 2014)
* Initial release.
===============================================================================}
unit RadiantGaugesForm;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Graphics,
FMX.Controls,
FMX.Controls.Presentation,
FMX.Forms,
FMX.Dialogs,
FMX.StdCtrls,
FMX.Ani,
FMX.Objects,
FMX.Layouts,
Radiant.Shapes;
type
TfrmGauges = class(TForm)
secFacePlate: TRadiantSectorRing;
trpNeedle: TRadiantTrapezoid;
chkAnimate: TCheckBox;
aniNeedleAngle: TFloatAnimation;
cirBackground: TRadiantCircle;
lytGauge1: TLayout;
lytGauge2: TLayout;
sectGreen: TRadiantSector;
sectYellow: TRadiantSector;
sectRed: TRadiantSector;
RadiantTrapezoid1: TRadiantTrapezoid;
RadiantCircle1: TRadiantCircle;
lytGauge3: TLayout;
sect180: TRadiantSector;
sect157: TRadiantSector;
sect112: TRadiantSector;
sect67: TRadiantSector;
sect0: TRadiantSector;
sect22: TRadiantSector;
sect135: TRadiantSector;
sect90: TRadiantSector;
sect45: TRadiantSector;
sectFrame: TRadiantSector;
RadiantCircle2: TRadiantCircle;
RadiantPointer1: TRadiantPointer;
trkGauge2: TTrackBar;
trkGauge3: TTrackBar;
trkGauge1: TTrackBar;
RadiantRing1: TRadiantRing;
lytGauge4: TLayout;
RadiantSector1: TRadiantSector;
RadiantSector2: TRadiantSector;
RadiantSector3: TRadiantSector;
RadiantSector4: TRadiantSector;
RadiantSector5: TRadiantSector;
RadiantSector6: TRadiantSector;
RadiantSector7: TRadiantSector;
RadiantSector8: TRadiantSector;
RadiantSector9: TRadiantSector;
RadiantMarker2: TRadiantMarker;
trkGauge4: TTrackBar;
RadiantSector10: TRadiantSector;
RadiantSector0: TRadiantSector;
RadiantSector11: TRadiantSector;
FloatAnimation1: TFloatAnimation;
FloatAnimation2: TFloatAnimation;
FloatAnimation3: TFloatAnimation;
procedure chkAnimateChange(Sender: TObject);
procedure trkGauge2Change(Sender: TObject);
procedure trkGauge3Change(Sender: TObject);
procedure trkGauge1Change(Sender: TObject);
procedure trkGauge4Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmGauges: TfrmGauges;
implementation
{$R *.fmx}
procedure TfrmGauges.chkAnimateChange(Sender: TObject);
var
Animate: Boolean;
begin
Animate := chkAnimate.IsChecked;
aniNeedleAngle.Enabled := Animate;
FloatAnimation1.Enabled := Animate;
FloatAnimation2.Enabled := Animate;
FloatAnimation3.Enabled := Animate;
if not Animate then
begin
trkGauge1Change( nil );
trkGauge2Change( nil );
trkGauge3Change( nil );
trkGauge4Change( nil );
end;
end;
procedure TfrmGauges.trkGauge1Change(Sender: TObject);
begin
trpNeedle.RotationAngle := trkGauge1.Value;
end;
procedure TfrmGauges.trkGauge2Change(Sender: TObject);
begin
RadiantTrapezoid1.RotationAngle := trkGauge2.Value;
end;
procedure TfrmGauges.trkGauge3Change(Sender: TObject);
begin
RadiantPointer1.RotationAngle := trkGauge3.Value;
end;
procedure TfrmGauges.trkGauge4Change(Sender: TObject);
begin
RadiantMarker2.RotationAngle := trkGauge4.Value;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fCodeTemplateInsert;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, SynEditTypes;
type
TfmCTInsert = class;
TCTNotifyEvent = procedure(Sender: TfmCTInsert; ItemSelected:boolean; Item:string) of object;
TfmCTInsert = class(TForm)
lbCT: TListBox;
procedure FormDeactivate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lbCTDblClick(Sender: TObject);
procedure lbCTKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lbCTDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
private
str :TStringList;
MaxLStrLen :integer;
MaxRStrLen :integer;
FClosing :boolean;
fOnCTSelect: TCTNotifyEvent;
fSavedCaretPosition: TBufferCoord;
procedure SelectItem;
procedure Cancel;
function GetSelectedItem(Index:integer):string;
public
procedure InitItems;
procedure AddItem(Completion, Comment:string);
function GetWinWidth:integer;
property OnCTSelect: TCTNotifyEvent read fOnCTSelect write fOnCTSelect;
property SavedCaretPosition: TBufferCoord read fSavedCaretPosition write fSavedCaretPosition;
end;
var
fmCTInsert: TfmCTInsert;
implementation
uses
fMain;
{$R *.DFM}
const
ITEM_SEPARATOR = #09;
L_MARGIN = 4;
MIDDLE_SPACE = 20;
R_MARGIN = 20;
MAX_WIDTH = 400;
////////////////////////////////////////////////////////////////////////////////////////////
// Public functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.InitItems;
begin
str.BeginUpdate;
end;
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.AddItem(Completion, Comment:string);
var
W1, W2 :integer;
begin
str.Add(Completion+ITEM_SEPARATOR+Comment);
W1:=lbCT.Canvas.TextWidth(Completion);
W2:=lbCT.Canvas.TextWidth(Comment);
if (MaxLStrLen<W1) then MaxLStrLen:=W1;
if (MaxRStrLen<W2) then MaxRStrLen:=W2;
end;
//------------------------------------------------------------------------------------------
function TfmCTInsert.GetWinWidth:integer;
begin
result:=L_MARGIN+MaxLStrLen+MIDDLE_SPACE+MaxRStrLen+R_MARGIN;
if result>MAX_WIDTH then
result:=MAX_WIDTH;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function TfmCTInsert.GetSelectedItem(Index:integer):string;
begin
if (Index>-1) and (Index<lbCT.Items.Count) then
result:=Copy(lbCT.Items[Index],1,Pos(ITEM_SEPARATOR,lbCT.Items[Index])-1)
else
result:='';
end;
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.SelectItem;
begin
if Assigned(fOnCTSelect) then
OnCTSelect(SELF, TRUE, GetSelectedItem(lbCT.ItemIndex));
Close;
end;
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.Cancel;
begin
if Assigned(fOnCTSelect) then
OnCTSelect(SELF, FALSE, '');
Close;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// ListBox events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.lbCTDblClick(Sender: TObject);
begin
SelectItem;
end;
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.lbCTKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_RETURN:
SelectItem;
VK_ESCAPE:
Cancel;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.lbCTDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
s :string;
s1, s2 :string;
bEnd :integer;
l_pos :integer;
begin
s:=TListBox(Control).Items[Index];
bEnd:=Pos(ITEM_SEPARATOR,s);
s1:=Copy(s,1,bEnd-1);
s2:=Copy(s,bEnd+1,Length(s));
with TListBox(Control).Canvas do begin
FillRect(Rect);
l_pos:=L_MARGIN;
Font.Style:=[fsBold];
TextOut(l_pos, Rect.top, s1);
Font.Style:=[];
TextOut(l_pos+MaxLStrLen+MIDDLE_SPACE, Rect.top, s2);
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.FormCreate(Sender: TObject);
begin
str:=TStringList.Create;
lbCT.ItemHeight:=fmMain.DefaultlbItemHeight;
end;
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.FormShow(Sender: TObject);
begin
str.Sort;
str.EndUpdate;
lbCT.Items.Assign(str);
lbCT.ItemIndex:=0;
FClosing:=FALSE;
if (lbCT.Items.Count=1) then
SelectItem;
end;
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.FormDeactivate(Sender: TObject);
begin
if not FClosing then
Cancel;
end;
//------------------------------------------------------------------------------------------
procedure TfmCTInsert.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FClosing:=TRUE;
str.Free;
Action:=caFree;
end;
//------------------------------------------------------------------------------------------
end.
|
//******************************************************************************
//* Проект "Горводоканал" *
//* Форма коментариев к договорам *
//* Выполнил: Перчак А.Л. 2010г *
//******************************************************************************
unit uReestr_Comments;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxTextEdit, cxCalendar, Placemnt,
ActnList, cxGridTableView, ImgList, dxBar, dxBarExtItems, cxGridLevel,
cxGridCustomTableView, cxGridDBTableView, cxClasses, cxControls,
cxGridCustomView, cxGrid, dxStatusBar, IBase, uReestr_DM, uConsts, uCommon_Funcs,
uCommon_Messages, uReestr_Comments_AE;
type
Tfrm_comments = class(TForm)
StatusBar: TdxStatusBar;
Grid_Comment: TcxGrid;
Grid_CommentDBView: TcxGridDBTableView;
Comment: TcxGridDBColumn;
Grid_CommentLevel: TcxGridLevel;
BarManager: TdxBarManager;
AddButton: TdxBarLargeButton;
EditButton: TdxBarLargeButton;
DeleteButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
ExitButton: TdxBarLargeButton;
SelectButton: TdxBarLargeButton;
Search_BarEdit: TdxBarEdit;
PopupImageList: TImageList;
LargeImages: TImageList;
DisabledLargeImages: TImageList;
Styles: TcxStyleRepository;
BackGround: TcxStyle;
FocusedRecord: TcxStyle;
Header: TcxStyle;
DesabledRecord: TcxStyle;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
DevExpress_Style: TcxGridTableViewStyleSheet;
Contracts_ActionList: TActionList;
FilterAction: TAction;
FormStorage: TFormStorage;
Date_comment: TcxGridDBColumn;
ins_act: TAction;
upd_act: TAction;
del_act: TAction;
ref_act: TAction;
exit_act: TAction;
procedure exit_actExecute(Sender: TObject);
procedure ins_actExecute(Sender: TObject);
procedure upd_actExecute(Sender: TObject);
procedure del_actExecute(Sender: TObject);
procedure ref_actExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormIniLanguage;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
DM : TfrmReestr_DM;
public
is_admin: Boolean;
PLanguageIndex : Byte;
id_dog :int64;
aHandle : TISC_DB_HANDLE;
end;
var
frm_comments: Tfrm_comments;
implementation
{$R *.dfm}
procedure Tfrm_comments.FormIniLanguage;
begin
PLanguageIndex:= uCommon_Funcs.bsLanguageIndex();
//кэпшн формы
Caption:= uConsts.bs_CommentDiss[PLanguageIndex];
//названия кнопок
AddButton.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex];
EditButton.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex];
DeleteButton.Caption := uConsts.bs_DeleteBtn_Caption[PLanguageIndex];
RefreshButton.Caption := uConsts.bs_RefreshBtn_Caption[PLanguageIndex];
SelectButton.Caption := uConsts.bs_SelectBtn_Caption[PLanguageIndex];
ExitButton.Caption := uConsts.bs_ExitBtn_Caption[PLanguageIndex];
Date_comment.Caption := uConsts.bs_DateOrd[PLanguageIndex];
Comment.Caption := uConsts.bs_CommentDiss[PLanguageIndex];
Search_BarEdit.Caption := uConsts.bs_SearchBtn_Caption[PLanguageIndex];
//статусбар
StatusBar.Panels[0].Text:= uConsts.bs_InsertBtn_ShortCut[PLanguageIndex] + uConsts.bs_InsertBtn_Caption[PLanguageIndex];
StatusBar.Panels[1].Text:= uConsts.bs_EditBtn_ShortCut[PLanguageIndex] + uConsts.bs_EditBtn_Caption[PLanguageIndex];
StatusBar.Panels[2].Text:= uConsts.bs_DeleteBtn_ShortCut[PLanguageIndex] + uConsts.bs_DeleteBtn_Caption[PLanguageIndex];
StatusBar.Panels[3].Text:= uConsts.bs_RefreshBtn_ShortCut[PLanguageIndex] + uConsts.bs_RefreshBtn_Caption[PLanguageIndex];
StatusBar.Panels[4].Text:= uConsts.bs_ExitBtn_ShortCut[PLanguageIndex] + uConsts.bs_ExitBtn_Caption[PLanguageIndex];
end;
procedure Tfrm_comments.exit_actExecute(Sender: TObject);
begin
close;
end;
procedure Tfrm_comments.ins_actExecute(Sender: TObject);
var
ViewForm : Tfrm_comments_ae;
New_id_Locator : integer;
begin
ViewForm := Tfrm_comments_ae.create(self, PLanguageIndex);
ViewForm.ShowModal;
If ViewForm.ModalResult=mrOk then
Begin
DM.WriteTransaction.StartTransaction;
DM.StProc.StoredProcName := 'bs_DT_DOG_COMMENTS_INS';
DM.StProc.Prepare;
DM.StProc.ParamByName('id_dog').Asint64 := Id_dog;
DM.StProc.ParamByName('date_comment').Asdate := date;
DM.StProc.ParamByName('comment_text').AsString := ViewForm.Memo1.Text;
DM.StProc.ExecProc;
try
DM.WriteTransaction.Commit;
New_id_Locator:=DM.StProc.ParamByName('id_dog_comments').AsInt64;
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
DM.WriteTransaction.Rollback;
end;
end;
DM.DataSet.CloseOpen(True);
DM.DataSet.Locate('id_dog_comments',New_id_Locator,[] );
End;
ViewForm.Free;
end;
procedure Tfrm_comments.upd_actExecute(Sender: TObject);
var
ViewForm : Tfrm_comments_ae;
New_id_Locator : integer;
begin
if Grid_CommentDBView.DataController.RecordCount=0 then exit;
ViewForm := Tfrm_comments_ae.create(self, PLanguageIndex);
ViewForm.Memo1.Text:= Dm.Dataset['comment_text'];
ViewForm.ShowModal;
If ViewForm.ModalResult=mrOk then
Begin
DM.WriteTransaction.StartTransaction;
DM.StProc.StoredProcName := 'bs_DT_DOG_COMMENTS_UPD';
DM.StProc.Prepare;
DM.StProc.ParamByName('id_dog_comments').Asint64 := Dm.Dataset['id_dog_comments'];
DM.StProc.ParamByName('id_dog').Asint64 := Id_dog;
DM.StProc.ParamByName('date_comment').Asdate := date;
DM.StProc.ParamByName('comment_text').AsString := ViewForm.Memo1.Text;
DM.StProc.ExecProc;
try
DM.WriteTransaction.Commit;
New_id_Locator:=DM.StProc.ParamByName('id_dog_comments').AsInt64;
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
DM.WriteTransaction.Rollback;
end;
end;
DM.DataSet.CloseOpen(True);
DM.DataSet.Locate('id_dog_comments',New_id_Locator,[] );
End;
ViewForm.Free;
end;
procedure Tfrm_comments.del_actExecute(Sender: TObject);
var
i:byte;
begin
if Grid_CommentDBView.DataController.RecordCount=0 then exit;
i:= uCommon_Messages.bsShowMessage(uConsts.bs_Confirmation_Caption[PLanguageIndex], uConsts.bs_DeletePromt[PLanguageIndex], mtConfirmation, [mbYes, mbNo]);
if ((i = 7) or (i= 2)) then exit;
DM.WriteTransaction.StartTransaction;
DM.StProc.StoredProcName := 'bs_DT_DOG_COMMENTS_DEL';
DM.StProc.Prepare;
DM.StProc.ParamByName('id_dog_comments').Asint64 := Dm.Dataset['id_dog_comments'];;
DM.StProc.ExecProc;
try
DM.WriteTransaction.Commit;
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
DM.WriteTransaction.Rollback;
end;
end;
DM.DataSet.CloseOpen(True);
end;
procedure Tfrm_comments.ref_actExecute(Sender: TObject);
var
id_Locator : Int64;
begin
{ IF GridDBView.DataController.RecordCount=0 then exit;
Screen.Cursor := crHourGlass;
id_Locator := DM.DataSet['id_dog_comment'];
DM.DataSet.CloseOpen(True);
DM.DataSet.Locate('id_dog_comment', id_Locator ,[] );
Screen.Cursor := crDefault;}
end;
procedure Tfrm_comments.FormClose(Sender: TObject;
var
Action: TCloseAction);
begin
FormStorage.SaveFormPlacement;
if FormStyle = fsMDIChild then action:=caFree;
Dm.Free;
end;
procedure Tfrm_comments.FormCreate(Sender: TObject);
begin
FormStorage.RestoreFormPlacement;
FormIniLanguage;
end;
procedure Tfrm_comments.FormShow(Sender: TObject);
begin
Dm := TfrmReestr_DM.Create(Self);
DM.DB.Handle := aHandle;
DM.DB.Connected := True;
DM.ReadTransaction.StartTransaction;
Grid_CommentDBView.DataController.DataSource := DM.DataSource;
DM.DataSet.Close;
DM.DataSet.SQLs.SelectSQL.Text := 'Select * From bs_dt_dog_comments_sel(:id_dog)';
DM.DataSet.ParamByName('ID_DOG').AsInt64 := id_dog;
DM.DataSet.Open;
end;
end.
|
unit uConverter;
interface
uses
DBXJSON, DBXJSONReflect, System.SysUtils, REST.Json;
type
TConverte = class
public
class function ObjectToJSON<T: class>(aObject: T): TJSONValue;
class function JSONToObject<T: class>(aJSON: TJSONValue): T;
class procedure DestroiObj<T: class>(aObject: T);
end;
implementation
{ TConverte }
class procedure TConverte.DestroiObj<T>(aObject: T);
begin
if Assigned(aObject) then
FreeAndNil(aObject);
end;
class function TConverte.JSONToObject<T>(aJSON: TJSONValue): T;
var
UnMarshal: TJSONUnMarshal;
begin
if aJSON is TJSONNull then
Exit(nil);
UnMarshal := TJSONUnMarshal.Create;
Result := T(UnMarshal.Unmarshal(aJSON));
UnMarshal.Free
end;
class function TConverte.ObjectToJSON<T>(aObject: T): TJSONValue;
var
Marshal: TJSONMarshal;
begin
if Assigned(aObject) then
begin
Marshal := TJSONMarshal.Create(TJSONConverter.Create);
Result := Marshal.Marshal(aObject);
Marshal.Free;
end
else
Exit(TJSONNull.Create);
end;
end.
|
unit uMarkerDrawer;
{
*****************************************************************************
* This file is part of Multiple Acronym Math and Audio Plot - MAAPlot *
* *
* See the file COPYING. *
* for details about the copyright. *
* *
* 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. *
* *
* MAAplot for Lazarus/fpc *
* (C) 2014 Stefan Junghans *
*****************************************************************************
}
{$mode objfpc}{$H+}
//{$DEFINE GTK2}
interface
uses
Classes, SysUtils, useriesmarkers, Graphics, uPlotSeries, uPlotUtils, uPlotDataTypes, IntfGraphics, FPimage,
math, GraphType, GraphUtil, GraphMath; //uPlotOverrides, uIntfImageDrawingUtils
type
// TODO: Marker doesNOT need OwnerContainer - rome this !?
{ TMarkerDrawer }
{ TMarkerDrawer_Bitmap }
TMarkerDrawer_Bitmap = class(TMarkerDrawer)
private
FMarkerImage: TLazIntfImage;
FMarkerBmp: TBitmap;
FReadOutImage: TLazIntfImage;
FReadoutBmp: TBitmap;
function DrawTriangle(ADiameter: Integer; AAngle: Extended; AFPColor: TFPColor; AFilled: Boolean; AFlip: Boolean; out OriginShift: TPoint): TRect;
//function DrawLine(AStartPt, AEndPt: TPoint; ADiameter: Integer; AAngle: Extended; AFPColor: TFPColor; AFilled: Boolean; out OriginShift: TPoint): TRect; // Aangle not needed
function DrawLine(AStartPt, AEndPt: TPoint; ADiameter: Integer; AFPColor: TFPColor; AFilled: Boolean; out OriginShift: TPoint): TRect; // Aangle not needed
//function DrawCircle(ADiameter: Integer; AAngle: Extended; AFPColor: TFPColor; AFilled: Boolean; out OriginShift: TPoint): TRect;
procedure DrawReadout(AMarker: TMarker; AFPColor: TFPColor; ABackGndFPColor: TFPColor);
protected
public
constructor Create(AOwnerContainer: TMarkerContainer);override;
destructor Destroy; override;
procedure DrawMarker(AMarker: TMarker; ABitMap: TBitmap; IsGlobalImage: Boolean);override;
end;
implementation
uses uPlotAxis;
{ TMarkerDrawer }
function TMarkerDrawer_Bitmap.DrawTriangle(ADiameter: Integer; AAngle: Extended; AFPColor: TFPColor; AFilled: Boolean; AFlip: Boolean; out OriginShift: TPoint): TRect;
var
vPointArray: array of TPoint;
vFillArray: array of TPoint;
vFillPt: TPoint;
//Pt: TPoint;
vCanvas: TCanvas;
vCol, vRow: Integer;
vFPColor: TFPColor;
vColor: TColor;
vLoopFill: Integer;
vHue, vLight, vSat: byte;
vNewLight: byte;
vBackgroundColor: TColor;
vDestRect: TRect;
vDistance: Integer;
begin
// TODO:
// --> use directly the image
vColor:=FPColorToTColor(AFPColor);
vBackgroundColor := clCream;
if vColor = vBackgroundColor then vBackgroundColor := clWhite;
IF (not odd(ADiameter)) then ADiameter:=ADiameter+1;
IF FMarkerBmp <> nil THEN FMarkerBmp.Free;
FMarkerBmp := TBitmap.Create;
FMarkerBmp.PixelFormat:=pf32bit;
FMarkerBmp.SetSize(2*ADiameter, 2*ADiameter); //FMarkerBmp.SetSize(ADiameter, ADiameter);
vCanvas := FMarkerBmp.Canvas;
vCanvas.Brush.Color:=vBackgroundColor;
vCanvas.FillRect(0,0,2*ADiameter-1, 2*ADiameter-1); //vCanvas.FillRect(0,0,ADiameter-1, ADiameter-1);
begin
// set pen properties
vCanvas.Pen.Color := vColor;
//Canvas.Pen.Width := (ADiameter DIV 8) + 1;
vCanvas.Pen.Width := 1;
vCanvas.Pen.Mode := pmCopy;
vCanvas.Pen.EndCap:=pecRound;
vCanvas.Pen.JoinStyle:=pjsRound;
vCanvas.Brush.Style := bsClear;
setlength(vFillArray, 0);
setlength(vPointArray, 3); //
vPointArray[0].X := ADiameter; // 1 - 2
vPointArray[0].Y := ADiameter; // \ /
// // 0
IF AFlip then AAngle:=AAngle-180;
IF AAngle = 0 THEN begin
vPointArray[1].X := vPointArray[0].X - (ADiameter DIV 2); // cos 30°
vPointArray[1].Y := vPointArray[0].Y - ADiameter +1; // sin 60° is 0,86 not 1 so we are 14% high
vPointArray[2].X := vPointArray[0].X + (ADiameter DIV 2) -1; // cos 30°
vPointArray[2].Y := vPointArray[0].Y - ADiameter +1;
//vCanvas.Polygon(vPointArray); // other overloaded funcs available
IF (not AFilled) or AFilled THEN begin // always draw border ?
vCanvas.Line(vPointArray[0].X, vPointArray[0].Y, vPointArray[1].X, vPointArray[1].Y);
vCanvas.Line(vPointArray[0].X, vPointArray[0].Y, vPointArray[2].X, vPointArray[2].Y);
vCanvas.Line(vPointArray[1].X, vPointArray[1].Y, vPointArray[2].X, vPointArray[2].Y);
end;
IF AFilled then begin
ColorToHLS(vColor, vHue, vLight, vSat);
for vLoopFill:= 0 to ADiameter-1 do begin
vNewLight:= min( vLight + round((255-vLight) *2 / ADiameter * abs(abs(vLoopFill-(ADiameter DIV 2)) - (ADiameter DIV 2)) ), 255);
vCanvas.Pen.Color := HLStoColor(vHue, vNewLight, vSat);
vCanvas.Line(vPointArray[0].X, vPointArray[0].Y, vPointArray[1].X + vLoopFill , vPointArray[1].Y );
end;
end;
end
ELSE begin
vPointArray[1] := LineEndPoint(vPointArray[0], (AAngle+120)*16, ADiameter);
vPointArray[2] := LineEndPoint(vPointArray[0], (AAngle+60)*16, ADiameter);
//vCanvas.Polygon(vPointArray); // other overloaded funcs available
//IF (not AFilled) THEN begin
IF (not AFilled) or AFilled THEN begin
vCanvas.Line(vPointArray[0].X, vPointArray[0].Y, vPointArray[1].X, vPointArray[1].Y);
vCanvas.Line(vPointArray[0].X, vPointArray[0].Y, vPointArray[2].X, vPointArray[2].Y);
vCanvas.Line(vPointArray[1].X, vPointArray[1].Y, vPointArray[2].X, vPointArray[2].Y);
end;
IF AFilled then begin
// color
ColorToHLS(vColor, vHue, vLight, vSat);
// endpoints
vDistance := trunc( Distance(vPointArray[1], vPointArray[2]) + 1);
for vLoopFill := 1 to vDistance-1 do begin
vFillPt := LineEndPoint(vPointArray[1], AAngle*16, vLoopFill);
if ( (length(vFillArray) > 0) and (vFillPt <> vFillArray[length(vFillArray)-1]) ) OR (length(vFillArray)=0) then begin
setlength(vFillArray, length(vFillArray) +1);
vFillArray[length(vFillArray)-1] := vFillPt;
end;
end;
// fill
for vLoopFill:= 0 to length(vFillArray)-1 do begin
vNewLight:= min( vLight + round((255-vLight) *2 / ADiameter * abs(abs(vLoopFill-(length(vFillArray) DIV 2)) - (length(vFillArray) DIV 2)) ), 255);
vCanvas.Pen.Color := HLStoColor(vHue, vNewLight, vSat);
vCanvas.Line(vPointArray[0].X, vPointArray[0].Y, vFillArray[vLoopFill].X , vFillArray[vLoopFill].Y );
end;
end;
end;
end;
// make transparent
IF FMarkerImage <> nil then FMarkerImage.Free;
FMarkerImage := FMarkerBmp.CreateIntfImage;
for vRow:=0 to FMarkerImage.Height-1 do
for vCol:=0 to FMarkerImage.Width-1 do begin
vFPColor := FMarkerImage.Colors[vCol, vRow];
if FPColorToTColor(vFPColor) = vBackgroundColor then
vFPColor.alpha := alphaTransparent
else vFPColor.alpha := AFPColor.alpha; // $7FFF;
FMarkerImage.Colors[vCol, vRow] := vFPColor;
end;
FMarkerBmp.LoadFromIntfImage(FMarkerImage);
// positions
vDestRect.Left := MinIntValue([ vPointArray[0].X, vPointArray[1].X, vPointArray[2].X ]);
vDestRect.Right := MaxIntValue([ vPointArray[0].X, vPointArray[1].X, vPointArray[2].X ]) +1; // +1? see line style
vDestRect.Top := MinIntValue([ vPointArray[0].Y, vPointArray[1].Y, vPointArray[2].Y ]) ;
vDestRect.Bottom := MaxIntValue([ vPointArray[0].Y, vPointArray[1].Y, vPointArray[2].Y ]) +1;
Result := vDestRect;
OriginShift.X := vPointArray[0].X - vDestRect.Left;
OriginShift.Y := vPointArray[0].Y - vDestRect.Top;
//FMarkerBmp.SaveToFile('test.bmp');
setlength(vFillArray, 0);
setlength(vPointArray, 0);
end;
//function TMarkerDrawer_Bitmap.DrawLine(AStartPt, AEndPt: TPoint;
// ADiameter: Integer; AAngle: Extended; AFPColor: TFPColor;
// AFilled: Boolean; out OriginShift: TPoint): TRect;
function TMarkerDrawer_Bitmap.DrawLine(AStartPt, AEndPt: TPoint;
ADiameter: Integer; AFPColor: TFPColor;
AFilled: Boolean; out OriginShift: TPoint): TRect;
var
vWidth, vHeight: Integer;
vNormalAngle: Extended;
vNextStartPoint: TPoint;
vDrawStartPt: TPoint;
vPointArrayStart: array of TPoint;
vEndPointShift: TPoint;
//vFillArray: array of TPoint;
//vFillPt: TPoint;
//Pt: TPoint;
vCanvas: TCanvas;
vCol, vRow: Integer;
vFPColor: TFPColor;
vColor: TColor;
vLoopFill: Integer;
vHue, vLight, vSat: byte;
vNewLight: byte;
vBackgroundColor: TColor;
vDestRect: TRect;
//vDistance: Integer;
begin
vColor:=FPColorToTColor(AFPColor);
vDrawStartPt := Point(ADiameter DIV 2, ADiameter DIV 2);
vEndPointShift.X := AEndPt.X - AStartPt.X;
vEndPointShift.Y := AEndPt.Y - AStartPt.Y;
vWidth := abs(vEndPointShift.X) + ADiameter; // 1;
vHeight := abs(vEndPointShift.Y) + ADiameter; // 1;
if (vEndPointShift.X < 0) then vDrawStartPt.X := vDrawStartPt.X - vEndPointShift.X;
if (vEndPointShift.Y < 0) then vDrawStartPt.Y := vDrawStartPt.Y - vEndPointShift.Y;
vBackgroundColor := clCream;
if vColor = vBackgroundColor then vBackgroundColor := clWhite;
IF (not odd(ADiameter)) then ADiameter:=ADiameter+1;
IF FMarkerBmp <> nil THEN FMarkerBmp.Free;
FMarkerBmp := TBitmap.Create;
FMarkerBmp.PixelFormat:=pf32bit;
FMarkerBmp.SetSize(vWidth, vHeight); //FMarkerBmp.SetSize(ADiameter, ADiameter);
vCanvas := FMarkerBmp.Canvas;
vCanvas.Brush.Color:=vBackgroundColor;
vCanvas.FillRect(0,0,vWidth-1, vHeight-1); //vCanvas.FillRect(0,0,ADiameter-1, ADiameter-1);
// check angle and additional points
IF ADiameter = 1 THEN BEGIN
setlength(vPointArrayStart, 1);
//setlength(vPointArrayEnd, 1);
vPointArrayStart[0] := AStartPt;
vPointArrayStart[0].X := vPointArrayStart[0].X + (ADiameter DIV 2);
vPointArrayStart[0].Y := vPointArrayStart[0].Y + (ADiameter DIV 2);
//vPointArrayEnd[0] := AEndPt;
END ELSE
IF ADiameter > 1 THEN BEGIN
if vWidth = ADiameter then vNormalAngle:=0 else
vNormalAngle := (arctan( (vHeight-ADiameter) / (vWidth-ADiameter) ) + Pi()/2) * 180 / Pi();
for vLoopFill := -(ADiameter DIV 2) to (ADiameter DIV 2) do begin
//vNextStartPoint := LineEndPoint(Point(ADiameter DIV 2, ADiameter DIV 2), vNormalAngle*16, vLoopFill);
vNextStartPoint := LineEndPoint(vDrawStartPt, vNormalAngle*16, vLoopFill);
if length(vPointArrayStart) = 0 then begin
SetLength(vPointArrayStart,1);
vPointArrayStart[0] := vNextStartPoint;
end else
if (vNextStartPoint <> vPointArrayStart[length(vPointArrayStart)-1]) then begin
SetLength(vPointArrayStart,length(vPointArrayStart)+1);
vPointArrayStart[length(vPointArrayStart)-1] := vNextStartPoint;
end;
end;
END;
ColorToHLS(vColor, vHue, vLight, vSat);
// draw the lines
for vLoopFill:= 0 to length(vPointArrayStart)-1 do begin
vNewLight:= min( vLight + round((255-vLight) *2 / ADiameter * abs(abs(vLoopFill-(length(vPointArrayStart) DIV 2)) - (length(vPointArrayStart) DIV 2)) ), 255);
vCanvas.Pen.Color := HLStoColor(vHue, vNewLight, vSat);
vCanvas.Line(vPointArrayStart[vLoopFill].X, vPointArrayStart[vLoopFill].Y,
vPointArrayStart[vLoopFill].X + vEndPointShift.X, vPointArrayStart[vLoopFill].Y + vEndPointShift.Y);
end;
// make transparent
IF FMarkerImage <> nil then FMarkerImage.Free;
FMarkerImage := FMarkerBmp.CreateIntfImage;
for vRow:=0 to FMarkerImage.Height-1 do
for vCol:=0 to FMarkerImage.Width-1 do begin
vFPColor := FMarkerImage.Colors[vCol, vRow];
if FPColorToTColor(vFPColor) = vBackgroundColor then
vFPColor.alpha := alphaTransparent
else vFPColor.alpha := AFPColor.alpha; // $7FFF;
FMarkerImage.Colors[vCol, vRow] := vFPColor;
end;
FMarkerBmp.LoadFromIntfImage(FMarkerImage);
// positions
vDestRect.Left := MinIntValue([ vPointArrayStart[0].X, vPointArrayStart[Length(vPointArrayStart)-1].X,
vPointArrayStart[0].X + vEndPointShift.X, vPointArrayStart[Length(vPointArrayStart)-1].X + vEndPointShift.X]);
vDestRect.Right := MaxIntValue([ vPointArrayStart[0].X, vPointArrayStart[Length(vPointArrayStart)-1].X,
vPointArrayStart[0].X + vEndPointShift.X, vPointArrayStart[Length(vPointArrayStart)-1].X + vEndPointShift.X]) +1;
vDestRect.Top := MinIntValue([ vPointArrayStart[0].Y, vPointArrayStart[Length(vPointArrayStart)-1].Y,
vPointArrayStart[0].Y + vEndPointShift.Y, vPointArrayStart[Length(vPointArrayStart)-1].Y + vEndPointShift.Y]) ;
vDestRect.Bottom := MaxIntValue([ vPointArrayStart[0].Y, vPointArrayStart[Length(vPointArrayStart)-1].Y,
vPointArrayStart[0].Y + vEndPointShift.Y, vPointArrayStart[Length(vPointArrayStart)-1].Y + vEndPointShift.Y]) +1;
// attention: +1 because of CopyRect width calculation: Right - left = width
// this is wrong because (right-left) = width +1
// windows widgetset has this bug (feature ?) so Delphi VCL has it and Lazarus also
// --> solution: we add +1 for right and top
Result := vDestRect;
OriginShift.X := vDrawStartPt.X - vDestRect.Left - AStartPt.X ;
OriginShift.Y := vDrawStartPt.Y - vDestRect.Top - AStartPt.Y ;
end;
procedure TMarkerDrawer_Bitmap.DrawReadout(AMarker: TMarker; AFPColor: TFPColor; ABackGndFPColor: TFPColor);
var
vColor: TColor;
vFPColor: TFPColor;
vRow, vCol: Integer;
vMaxWidth, vWidth: Integer;
vHeight: Integer;
vLineY: Integer;
vText: string;
vXYValue: TXYValue;
vZValue: Extended;
vError: Integer;
vBackgroundColor: TColor;
{$IFDEF GTK2}
vTempCol: Word;
vTempTextCol: TFPColor;
{$ENDIF}
const
cBORDER = 2;
cLINESPREAD = 1; //1.1;
cWIDTH = 200;
cHEIGHT = 140;
begin
vColor:=FPColorToTColor(AFPColor);
{$IFDEF GTK2}
vTempTextCol := AFPColor;
vTempCol := vTempTextCol.blue;
vTempTextCol.blue := vTempTextCol.red;
vTempTextCol.red := vTempCol;
vColor:=FPColorToTColor(vTempTextCol);
{$ENDIF}
if ABackGndFPColor = AFPColor then begin
if ABackGndFPColor.red < $FFFF then ABackGndFPColor.red := (ABackGndFPColor.red + 1) else
ABackGndFPColor.red := (ABackGndFPColor.red - 1);
end;
vBackgroundColor := FPColorToTColor(ABackGndFPColor);
IF FReadoutBmp <> nil THEN FReadoutBmp.Free;
FReadoutBmp := TBitmap.Create;
FReadoutBmp.PixelFormat:=pf32bit;
FReadoutBmp.SetSize(cWIDTH, cHEIGHT); // dynamic ? known before ?
FReadoutBmp.Canvas.Brush.Color := vBackgroundColor;
FReadoutBmp.Canvas.FillRect(0,0,cWIDTH-1, cHEIGHT-1);
//FReadoutBmp.Canvas.AntialiasingMode:=amOff;
FReadoutBmp.Canvas.Font.Quality:=fqNonAntialiased;
FReadoutBmp.Canvas.Font.Color := vColor; // vColor;
//FReadoutBmp.Canvas.Font.Name:='Sans Serif';
//FReadoutBmp.Canvas.Font.Name:='Monospace';
FReadoutBmp.Canvas.Font.Name:='Arial';
FReadoutBmp.Canvas.Font.Size:=8;
//FReadoutBmp.Canvas.Font.Style:=[fsBold];
FReadoutBmp.Canvas.Brush.Style:=bsClear;
// line 1 ..........................
vText := '';
vLineY := cBORDER;
vMaxWidth:=0;
if AMarker.VisualParams.ShowIdent then vText := vText + 'MKR';
if AMarker.VisualParams.ShowIndex then vText := vText + '<' + IntToStr(AMarker.OwnerContainer.MarkerIndex[AMarker]) + '>';
if AMarker.VisualParams.ShowMode then begin
vText := vText + cMARKER_MODE_NAMES[AMarker.MarkerMode]
end;
if vText <> '' then begin
FReadoutBmp.Canvas.TextOut(cBORDER, vLineY , vText);
vWidth:=FReadoutBmp.Canvas.TextWidth(vText);
vHeight:=FReadoutBmp.Canvas.TextHeight(vText);
vMaxWidth:=max(vMaxWidth, vWidth);
vLineY := vLineY + round(vHeight * cLINESPREAD);
end;
// line 2,X ..........................
vText:='';
// TODO: error handling
if AMarker.VisualParams.XReadout OR AMarker.VisualParams.YReadout OR AMarker.VisualParams.ZReadout then
vError := AMarker.GetValue(vXYValue, vZValue);
if AMarker.VisualParams.XReadout then begin
vText := vText + 'X: ';
if mroValues in AMarker.VisualParams.ReadoutItems then begin
vText := vText + FormatNumber(vXYValue.X, TPlotAxis(AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[TXYPlotSeries(AMarker.OwnerContainer.OwnerSeries).XAxis]).NumberFormat);
end;
if mroUnits in AMarker.VisualParams.ReadoutItems then begin
vText := vText + AMarker.OwnerContainer.OwnerSeries.UnitString[TXYPlotSeries(AMarker.OwnerContainer.OwnerSeries).XAxis];
end;
if vText <> '' then begin
FReadoutBmp.Canvas.TextOut(cBORDER, vLineY , vText);
vWidth:=FReadoutBmp.Canvas.TextWidth(vText);
vHeight:=FReadoutBmp.Canvas.TextHeight(vText);
vMaxWidth:=max(vMaxWidth, vWidth);
vLineY := vLineY + round(vHeight * cLINESPREAD);
end;
end;
// line 3,Y ..........................
vText:='';
if AMarker.VisualParams.YReadout then begin
vText := vText + 'Y: ';
if mroValues in AMarker.VisualParams.ReadoutItems then begin
vText := vText + FormatNumber(vXYValue.Y, TPlotAxis(AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[TXYPlotSeries(AMarker.OwnerContainer.OwnerSeries).YAxis]).NumberFormat);
end;
if mroUnits in AMarker.VisualParams.ReadoutItems then begin
vText := vText + AMarker.OwnerContainer.OwnerSeries.UnitString[TXYPlotSeries(AMarker.OwnerContainer.OwnerSeries).YAxis];
end;
if vText <> '' then begin
FReadoutBmp.Canvas.TextOut(cBORDER, vLineY , vText);
vWidth:=FReadoutBmp.Canvas.TextWidth(vText);
vHeight:=FReadoutBmp.Canvas.TextHeight(vText);
vMaxWidth:=max(vMaxWidth, vWidth);
vLineY := vLineY + round(vHeight * cLINESPREAD);
end;
end;
// line 4,Z ..........................
vText:='';
if AMarker.VisualParams.ZReadout and (AMarker.OwnerContainer.OwnerSeries is TXYZPlotSeries) then begin
vText := vText + 'Z: ';
if mroValues in AMarker.VisualParams.ReadoutItems then begin
vText := vText + FormatNumber(vZValue, TPlotAxis(AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[TXYZPlotSeries(AMarker.OwnerContainer.OwnerSeries).ZAxis]).NumberFormat);
end;
if mroUnits in AMarker.VisualParams.ReadoutItems then begin
vText := vText + AMarker.OwnerContainer.OwnerSeries.UnitString[TXYZPlotSeries(AMarker.OwnerContainer.OwnerSeries).ZAxis];
end;
if vText <> '' then begin
FReadoutBmp.Canvas.TextOut(cBORDER, vLineY , vText);
vWidth:=FReadoutBmp.Canvas.TextWidth(vText);
vHeight:=FReadoutBmp.Canvas.TextHeight(vText);
vMaxWidth:=max(vMaxWidth, vWidth);
vLineY := vLineY + round(vHeight * cLINESPREAD);
end;
end;
// set BMP size
vHeight := vLineY + cBORDER;
vWidth := vMaxWidth + 2 * cBORDER;
FReadoutBmp.SetSize(vWidth, vHeight);
// convert to transparent // TODO: how can we use this with aliased fonts ?
IF FReadOutImage <> nil then FReadOutImage.Free;
FReadOutImage := FReadoutBmp.CreateIntfImage;
for vRow := 0 to FReadOutImage.Height-1 do
for vCol := 0 to FReadOutImage.Width-1 do begin
vFPColor := FReadOutImage.Colors[vCol, vRow];
if FPColorToTColor(vFPColor) = vBackgroundColor then begin
vFPColor.alpha := ABackGndFPColor.alpha;
FReadOutImage.Colors[vCol, vRow] := vFPColor;
end;
end;
FReadoutBmp.LoadFromIntfImage(FReadOutImage);
end;
constructor TMarkerDrawer_Bitmap.Create(AOwnerContainer: TMarkerContainer);
begin
Inherited Create(AOwnerContainer);
end;
destructor TMarkerDrawer_Bitmap.Destroy;
begin
IF FMarkerBmp <> nil THEN FMarkerBmp.Free;
IF FReadoutBmp <> nil THEN FReadoutBmp.Free;
IF FMarkerImage <> nil THEN FreeAndNil(FMarkerImage);
IF FReadOutImage <> nil THEN FreeAndNil(FReadOutImage);
inherited Destroy;
end;
procedure TMarkerDrawer_Bitmap.DrawMarker(AMarker: TMarker; ABitMap: TBitmap; IsGlobalImage: Boolean);
var
vTargetPt, vLineEndPt: TPoint;
vXYValue: TXYValue;
vXYLineEndValue: TXYValue;
vZValue: Extended;
vZLineEndValue: Extended;
vMarkerRect: TRect;
vDestRect: TRect;
vOriginShift: TPoint;
vVisualParams: TMarkerVisualParams;
vFPColor, vBackGndFPColor: TFPColor;
vError: Integer;
vAngle: Extended;
begin
//writeln('drawmarker');
vVisualParams := AMarker.VisualParams;
// marker
vError := AMarker.GetValue(vXYValue, vZValue);
if vError <> c_SUCCESS then exit;
vAngle := vVisualParams.StyleParams.DrawAngle;
vError := XYToScreen(AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[TPlotSeries(AMarker.OwnerContainer.OwnerSeries).XAxis], AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[TPlotSeries(AMarker.OwnerContainer.OwnerSeries).YAxis], vXYValue.X, vXYValue.Y, vTargetPt);
if vError <> c_SUCCESS then exit;
if (not IsGlobalImage) then
PlotImageCoordsToFrameRectCoords(AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[AMarker.OwnerContainer.OwnerSeries.OwnerAxis].OwnerPlotRect, vTargetPt);
IF msTriangle in vVisualParams.StyleParams.MarkShapes THEN begin // TODO: flip for MinPeak marker
vFPColor := TColorToFPColor(vVisualParams.StyleParams.Color);
vFPColor.alpha := vVisualParams.StyleParams.Alpha;
vMarkerRect := DrawTriangle(vVisualParams.StyleParams.Diameter, vAngle, vFPColor, true, AMarker.GetFlip, vOriginShift);
with vDestRect do begin
Left:= vTargetPt.X - vOriginShift.X;
Right:= vTargetPt.X + (vMarkerRect.Right - vMarkerRect.Left) - vOriginShift.X;
Top:= vTargetPt.Y - vOriginShift.Y;
Bottom:= vTargetPt.Y + (vMarkerRect.Bottom - vMarkerRect.Top) - vOriginShift.Y;
end;
ABitMap.Canvas.CopyRect(vDestRect, FMarkerBmp.Canvas, vMarkerRect);
end;
// TODO: circle
IF msLine in vVisualParams.StyleParams.MarkShapes THEN begin // TODO: flip for MinPeak marker
vFPColor := TColorToFPColor(vVisualParams.StyleParams.Color); // outside
vFPColor.alpha := vVisualParams.StyleParams.Alpha; // outside
vError := AMarker.GetLineEndValue(vXYLineEndValue, vZLineEndValue);
XYToScreen(AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[TPlotSeries(AMarker.OwnerContainer.OwnerSeries).XAxis], AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[TPlotSeries(AMarker.OwnerContainer.OwnerSeries).YAxis], vXYLineEndValue.X, vXYLineEndValue.Y, vLineEndPt);
if (not IsGlobalImage) then
PlotImageCoordsToFrameRectCoords(AMarker.OwnerContainer.OwnerSeries.OwnerPlot.Axis[AMarker.OwnerContainer.OwnerSeries.OwnerAxis].OwnerPlotRect, vLineEndPt);
vMarkerRect := DrawLine(vTargetPt, vLineEndPt, vVisualParams.StyleParams.LineWidth, vFPColor, true, vOriginShift);
with vDestRect do begin
Left:= - vOriginShift.X;
Right:= Left + (vMarkerRect.Right - vMarkerRect.Left);
Top:= - vOriginShift.Y;
Bottom:= Top + (vMarkerRect.Bottom - vMarkerRect.Top);
end;
ABitMap.Canvas.CopyRect(vDestRect, FMarkerBmp.Canvas, vMarkerRect);
end;
// readout
vBackGndFPColor := TColorToFPColor(vVisualParams.StyleParams.BackGndColor); // outside
vBackGndFPColor.alpha := vVisualParams.StyleParams.BackGndAlpha; // outside
DrawReadout(AMarker, vFPColor, vBackGndFPColor); // TODO: readout color and alpha in GUI
// readout
vDestRect.Left := vTargetPt.X + 4;
vDestRect.Right:= vDestRect.Left + FReadoutBmp.Width;
vDestRect.Top:= vTargetPt.Y;
vDestRect.Bottom:= vDestRect.Top + FReadoutBmp.Height;
ABitMap.Canvas.CopyRect(vDestRect, FReadoutBmp.Canvas, bounds(0,0,FReadoutBmp.Width,FReadoutBmp.Height));
end;
end.
|
unit ArchiveSaveUnit;
interface
uses
System.Classes, System.SysUtils, System.Zip, System.Generics.Collections,
ArchiveNodeInterface, System.Types;
type
TActivity = (aSaveArchive, aSaveDescriptions, aMove);
TDescriptionWriting = (dwAll, dwModel);
TProgressEvent = Procedure (Sender: TObject; Fraction: double) of object;
EArchiveException = class(Exception);
TArchiveSaver = class(TObject)
private
const
Indent = ' ';
var
FOnProgress: TProgressEvent;
FZipFile: TZipFile;
FCurrentZipFile: TZipFile;
FRootNodes: TArchiveNodeList;
FBaseNode: IArchiveNodeInterface;
FDescriptions: TStringList;
FCurrentDescriptions: TStringList;
FActivity: TActivity;
FMaxProgress: double;
FProgress: double;
FBigFiles: TStringList;
FRootZipFileName: string;
FDiskFileName: string;
FRootDirectory: string;
FWhatToWrite: TDescriptionWriting;
procedure HandleNode(Node: IArchiveNodeInterface; Prefix: string);
procedure ArchiveNode(Node: IArchiveNodeInterface; Prefix: string);
function GetArchivePath(Node: IArchiveNodeInterface): string;
procedure WriteDescription(Prefix, Text: string; MaxLineLength: integer);
procedure CalculateMaxProgress;
procedure CountNodeProgress(Node: IArchiveNodeInterface);
procedure DoOnProgress(Node: IArchiveNodeInterface);
function GetFileSize(FileName: string): Int64;
public
constructor Create;
destructor Destroy; override;
procedure SaveArchive(ZipFileName: string);
procedure MoveFilesToArchive(DirectoryName: string);
procedure WriteFileDescriptions(TextFileName: string;
WhatToWrite: TDescriptionWriting);
property RootNodes: TArchiveNodeList read FRootNodes write FRootNodes;
property OnProgress: TProgressEvent read FOnProgress write FOnProgress;
property SkippedFiles: TStringList read FBigFiles;
end;
implementation
uses
System.IOUtils;
var FourGigaBytes: Int64;
{ TArchiveSaver }
procedure TArchiveSaver.CalculateMaxProgress;
var
NodeIndex: Integer;
ANode: IArchiveNodeInterface;
begin
FMaxProgress := 0;
for NodeIndex := 0 to RootNodes.Count - 1 do
begin
ANode := RootNodes[NodeIndex] ;
CountNodeProgress(ANode);
end;
end;
procedure TArchiveSaver.CountNodeProgress(Node: IArchiveNodeInterface);
var
FileName: string;
ChildIndex: Integer;
// AFileSize: Int64;
begin
case FActivity of
aSaveArchive, aMove:
begin
if Node.NodeType = ntFile then
begin
FileName := Node.NodeText;
FMaxProgress := FMaxProgress + GetFileSize(FileName);
end;
end;
aSaveDescriptions:
begin
FMaxProgress := FMaxProgress + 1;
end;
else
Assert(False);
end;
for ChildIndex := 0 to Node.Count - 1 do
begin
CountNodeProgress(Node.Children[ChildIndex]);
end;
end;
constructor TArchiveSaver.Create;
begin
FBigFiles := TStringList.Create;
end;
destructor TArchiveSaver.Destroy;
begin
FBigFiles.Free;
inherited;
end;
procedure TArchiveSaver.DoOnProgress(Node: IArchiveNodeInterface);
var
FileName: string;
begin
if Assigned(FOnProgress) and (FMaxProgress <> 0) then
begin
case FActivity of
aSaveArchive, aMove:
begin
if Node.NodeType = ntFile then
begin
FileName := Node.NodeText;
FProgress := FProgress + GetFileSize(FileName);
end;
end;
aSaveDescriptions:
begin
FProgress := FProgress + 1;
end;
else
Assert(False);
end;
FOnProgress(self, FProgress/FMaxProgress);
end;
end;
function TArchiveSaver.GetArchivePath(Node: IArchiveNodeInterface): string;
var
ParentNode: IArchiveNodeInterface;
function ContinuePath: boolean;
begin
result := ParentNode <> nil;
if result then
begin
if FActivity = aSaveArchive then
begin
result := (ParentNode <> FBaseNode)
and (ParentNode.NodeType <> ntArchiveRoot);
end
else
begin
result := (ParentNode.NodeType <> ntArchiveRoot);
end;
end;
end;
begin
result := '';
ParentNode := Node.ParentNode;
while ContinuePath do
begin
if result = '' then
begin
result := ParentNode.NodeText;
end
else
begin
result := ParentNode.NodeText + '\' + result;
end;
ParentNode := ParentNode.ParentNode;
end;
end;
procedure TArchiveSaver.HandleNode(Node: IArchiveNodeInterface; Prefix: string);
var
ChildIndex: Integer;
ChildNode: IArchiveNodeInterface;
LocalZipFile: TZipFile;
ArchiveFileName: string;
DiskFileName: string;
FileStream: TFileStream;
CategoryNode: IArchiveNodeInterface;
EmptyData: TBytes;
LocalDescriptions: TStringList;
begin
if Node.NodeType = ntFile then
begin
ArchiveNode(Node, Prefix);
end
else
begin
LocalZipFile := nil;
ArchiveFileName := '';
if (Node.Count > 0)
and (Node.NodeType in [ntModel, ntCategoryCompressed]) then
begin
case FActivity of
aSaveArchive:
begin
LocalZipFile := TZipFile.Create;
FCurrentZipFile := LocalZipFile;
end;
aSaveDescriptions:
begin
LocalDescriptions := TStringList.Create;
FCurrentDescriptions := LocalDescriptions;
end;
aMove: ; // do nothing
else
Assert(False);
end;
if Node.NodeType in [ntModel, ntFolder] then
begin
CategoryNode := Node.ParentNode;
end
else
begin
CategoryNode := Node;
end;
ArchiveFileName := IncludeTrailingPathDelimiter(GetArchivePath(Node))
+ IncludeTrailingPathDelimiter(Node.NodeText) ;
case FActivity of
aSaveArchive:
begin
if CategoryNode.NodeText = StrModelOutputFiles then
begin
SetLength(EmptyData, 0);
FZipFile.Add(EmptyData, ArchiveFileName);
end;
end;
aSaveDescriptions:
begin
if (FWhatToWrite = dwAll) or (Node.NodeType = ntModel) then
begin
FCurrentDescriptions.Add('');
if FWhatToWrite = dwAll then
begin
FCurrentDescriptions.Add(Prefix + ArchiveFileName);
FCurrentDescriptions.Add(Prefix + Indent + 'Description:');
FCurrentDescriptions.Add(Prefix + Indent + '-----------');
end
else
begin
FCurrentDescriptions.Add(Prefix + Node.NodeText);
FCurrentDescriptions.Add(Prefix + Indent + '-----------');
end;
WriteDescription(Prefix + Indent, Node.Description, 80);
if (FWhatToWrite = dwAll) and (Node.Count > 0)
and (Node.Children[0].NodeType = ntFile) then
begin
FCurrentDescriptions.Add('');
FCurrentDescriptions.Add(Prefix + Indent + 'Files:');
FCurrentDescriptions.Add(Prefix + Indent + '-----');
end;
end;
end;
aMove: ; // do nothing
else
Assert(False);
end;
ArchiveFileName := IncludeTrailingPathDelimiter(GetArchivePath(Node)) + Node.NodeText + '.zip';
if FActivity = aSaveArchive then
begin
DiskFileName := TPath.GetTempFileName;
LocalZipFile.Open(DiskFileName, zmWrite);
FDiskFileName := ArchiveFileName;
end
else
begin
FDiskFileName := FRootZipFileName;
end;
FBaseNode := Node;
end
else
begin
LocalZipFile := nil;
LocalDescriptions := nil;
FDiskFileName := FRootZipFileName;
end;
try
for ChildIndex := 0 to Node.Count - 1 do
begin
ChildNode := Node.Children[ChildIndex];
HandleNode(ChildNode, Prefix + Indent);
end;
finally
case FActivity of
aSaveArchive:
begin
if LocalZipFile <> nil then
begin
try
LocalZipFile.Close;
LocalZipFile.Free;
FCurrentZipFile := FZipFile;
FileStream := TFile.OpenRead(DiskFileName);
try
if Assigned(FOnProgress) then
begin
FMaxProgress := FMaxProgress + FileStream.Size;
// FOnProgress(self, FProgress/FMaxProgress);
end;
if FileStream.Size >= FourGigaBytes then
begin
raise EArchiveException.Create(Format(
'Error creating %s. File is greater than four gigabytes in size',
[ArchiveFileName]));
end
else
begin
FZipFile.Add(FileStream, ArchiveFileName);
end;
if Assigned(FOnProgress) then
begin
FProgress := FProgress + FileStream.Size;
FOnProgress(self, FProgress/FMaxProgress);
end;
finally
FileStream.Free;
end;
finally
TFile.Delete(DiskFileName);
end;
FBaseNode := nil;
end;
end;
aSaveDescriptions:
begin
if LocalDescriptions <> nil then
begin
FCurrentDescriptions := FDescriptions;
FDescriptions.AddStrings(LocalDescriptions);
FreeAndNil(LocalDescriptions);
end;
end;
aMove: ; // do nothing
else
Assert(False);
end;
end;
end;
DoOnProgress(Node);
end;
procedure TArchiveSaver.MoveFilesToArchive(DirectoryName: string);
var
NodeIndex: Integer;
ANode: IArchiveNodeInterface;
CurDir: string;
FreeSpace: Int64;
begin
FActivity := aMove;
FRootDirectory := IncludeTrailingPathDelimiter(DirectoryName);
TDirectory.GetFiles(FRootDirectory);
if not TDirectory.IsEmpty(FRootDirectory) then
begin
raise EArchiveException.Create('The archive directory must be empty');
end;
CalculateMaxProgress;
if Assigned (FOnProgress) then
begin
FProgress := 0
end;
CurDir := GetCurrentDir;
try
SetCurrentDir(DirectoryName);
FreeSpace := DiskFree(0);
if FreeSpace < FMaxProgress then
begin
raise EArchiveException.Create(Format(
'Not enough free disk space. Required disk space = %d',
[FMaxProgress]));
end;
finally
SetCurrentDir(CurDir);
end;
for NodeIndex := 0 to RootNodes.Count - 1 do
begin
ANode := RootNodes[NodeIndex] ;
HandleNode(ANode, Indent);
end;
end;
procedure TArchiveSaver.ArchiveNode(Node: IArchiveNodeInterface; Prefix: string);
var
FullPath: string;
ArchivePath: string;
FileStream: TFileStream;
ArchiveFileName: string;
ArchiveDirectory: string;
begin
ArchivePath := GetArchivePath(Node);
if ArchivePath <> '' then
begin
ArchivePath := IncludeTrailingPathDelimiter(ArchivePath);
end;
FullPath := Node.NodeText;
if TFile.Exists(FullPath) then
begin
if Pos(Node.ModelDirectory, FullPath) = 1 then
begin
ArchivePath := ArchivePath
+ ExtractRelativePath(Node.ModelDirectory, FullPath)
end
else
begin
ArchivePath := ArchivePath + ExtractFileName(FullPath);
end;
if ExtractFileExt(ArchivePath) = ArchiveExt then
begin
ArchivePath := ChangeFileExt(ArchivePath, '');
end;
case FActivity of
aSaveArchive:
begin
FileStream := TFile.OpenRead(FullPath);
try
if FileStream.Size >= FourGigabytes then
begin
// FBigFiles.Add(Format('"%0:s" "%1:s"', [FullPath, ArchivePath]))
FBigFiles.Add(Format('"%0:s" "%1:s" in "%2:s"', [FullPath, ArchivePath, FDiskFileName]));
end
else
begin
FCurrentZipFile.Add(FileStream, ArchivePath);
end;
finally
FileStream.Free;
end;
end;
aSaveDescriptions:
begin
if FWhatToWrite = dwAll then
begin
WriteDescription(Prefix, ArchivePath + ':', 80);
WriteDescription(Prefix + Indent, Node.Description, 80);
FCurrentDescriptions.Add('');
end;
// FCurrentDescriptions.Add(Prefix + ArchivePath + ': ' + Node.Description)
end;
aMove:
begin
// copy file
ArchiveFileName := FRootDirectory + ArchivePath;
ArchiveDirectory := ExtractFileDir(ArchiveFileName);
if not TDirectory.Exists(ArchiveDirectory) then
begin
TDirectory.CreateDirectory(ArchiveDirectory);
end;
if TFile.Exists(ArchiveFileName) then
begin
raise EArchiveException.Create(Format(
'Cannot move %0:s to %1:s because a file by that name is already exists in that location',
[FullPath, ArchiveFileName]));
end;
TFile.Copy(FullPath, ArchiveFileName);
end
else
Assert(False);
end;
end
else
begin
raise EArchiveError.Create(Format(
'The file %0:s under %1:s does not exist', [FullPath, ArchivePath]));
end;
end;
procedure TArchiveSaver.SaveArchive(ZipFileName: string);
var
NodeIndex: Integer;
ANode: IArchiveNodeInterface;
begin
FBigFiles.Clear;
FActivity := aSaveArchive;
if Assigned (FOnProgress) then
begin
CalculateMaxProgress;
FProgress := 0
end;
FZipFile := TZipFile.Create;
try
FCurrentZipFile := FZipFile;
FRootZipFileName := ZipFileName;
FZipFile.Open(ZipFileName, zmWrite);
try
for NodeIndex := 0 to RootNodes.Count - 1 do
begin
ANode := RootNodes[NodeIndex] ;
HandleNode(ANode, Indent);
end;
finally
FZipFile.Close;
end;
finally
FreeAndNil(FZipFile);
end;
end;
procedure TArchiveSaver.WriteDescription(Prefix, Text: string;
MaxLineLength: integer);
var
IntList: TList<Integer>;
CharIndex: Integer;
StartIndex: Integer;
PrefixLength: Integer;
TextToWrite: string;
Lines: TStringList;
LineIndex: Integer;
begin
Lines := TStringList.Create;
IntList := TList<Integer>.Create;
try
Lines.Text := Text;
for LineIndex := 0 to Lines.Count - 1 do
begin
Text := Lines[LineIndex];
IntList.Clear;
for CharIndex := 1 to Length(Text) do
begin
if Text[CharIndex] = ' ' then
begin
IntList.Add(CharIndex)
end;
end;
IntList.Add(Length(Text)+1);
StartIndex := 1;
PrefixLength := Length(Prefix);
for CharIndex := 1 to IntList.Count - 1 do
begin
if PrefixLength + IntList[CharIndex] - StartIndex > MaxLineLength then
begin
TextToWrite := Copy(Text, StartIndex, IntList[CharIndex-1]-StartIndex);
FCurrentDescriptions.Add(Prefix + TextToWrite);
StartIndex := IntList[CharIndex-1]+1;
end;
end;
TextToWrite := Copy(Text, StartIndex, MaxInt);
FCurrentDescriptions.Add(Prefix + TextToWrite);
end;
// FCurrentDescriptions.Add('');
finally
IntList.Free;
Lines.Free;
end;
end;
procedure TArchiveSaver.WriteFileDescriptions(TextFileName: string;
WhatToWrite: TDescriptionWriting);
var
NodeIndex: Integer;
ANode: IArchiveNodeInterface;
begin
FActivity := aSaveDescriptions;
FWhatToWrite := WhatToWrite;
if Assigned (FOnProgress) then
begin
CalculateMaxProgress;
FProgress := 0;
end;
FDescriptions := TStringList.Create;
try
FCurrentDescriptions := FDescriptions;
FDescriptions.Add(Indent + 'Files:');
FDescriptions.Add(Indent + '-----');
for NodeIndex := 0 to RootNodes.Count - 1 do
begin
ANode := RootNodes[NodeIndex] ;
HandleNode(ANode, Indent);
end;
FDescriptions.SaveToFile(TextFileName);
finally
FreeAndNil(FDescriptions);
end;
end;
function TArchiveSaver.GetFileSize(FileName: string): Int64;
var
FileStream: TFileStream;
begin
if TFile.Exists(FileName) then
begin
FileStream := TFile.OpenRead(FileName);
try
result := FileStream.Size;
finally
FileStream.Free;
end;
end
else
begin
result := 0;
end;
end;
initialization
FourGigaBytes := 1024*1024;
FourGigaBytes := FourGigaBytes*1024*4;
end.
|
unit uFchMargem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaiDeFichasBrowse, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxEdit, DB, cxDBData, dxPSGlbl, dxPSUtl, dxPSEngn, dxPrnPg,
dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider, dxPSFillPatterns,
dxPSEdgePatterns, cxGridCustomPopupMenu, cxGridPopupMenu, dxPSCore,
dxPScxGridLnk, FormConfig, ADODB, PowerADOQuery, siComp, siLangRT,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
ComCtrls, StdCtrls, Buttons, LblEffct, ExtCtrls, Mask, DBCtrls;
type
TFchMargem = class(TbrwFrmParentBrw)
quFormIDMargemTable: TIntegerField;
quFormMargemTable: TStringField;
quBrowseIDMargemTableRange: TIntegerField;
quBrowseIDMargemTable: TIntegerField;
quBrowseMinValue: TBCDField;
quBrowseMaxValue: TBCDField;
quBrowsePercentage: TFloatField;
edtMargemName: TDBEdit;
Label35: TLabel;
lbRoundName: TLabel;
grdBrowseDBMinValue: TcxGridDBColumn;
grdBrowseDBMaxValue: TcxGridDBColumn;
grdBrowseDBPercentage: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FchMargem: TFchMargem;
implementation
uses uFchMargemRange, uDM, uMsgBox, uMsgConstant;
{$R *.dfm}
procedure TFchMargem.FormCreate(Sender: TObject);
begin
inherited;
brwForm := TFchMargemRange.Create(Self);
end;
procedure TFchMargem.btRemoveClick(Sender: TObject);
begin
inherited;
if MsgBox(MSG_QST_DELETE, vbYesNo + vbQuestion) = vbYes then
begin
try
with DM.quFreeSQL do
begin
Close; // Verificar vazio
SQL.Text := 'Delete from MargemTableRange where IDMargemTableRange ='+InttoStr(quBrowseIDMargemTableRange.AsInteger);
ExecSQL;
Close;
end;
BrowseRefresh('');
except
MsgBox(MSG_CRT_NOT_DEL_PURCHASE, vbCritical + vbOkOnly);
end;
end;
end;
end.
|
unit Sport;
interface
uses
SysUtils, DB, Classes;
type
TSport = class(TObject)
private
FDescription: String;
FGoalie: Boolean;
FId: String;
FName: String;
FOrigin: String;
FPlayers: Integer;
public
property Description: String read FDescription;
property Goalie: Boolean read FGoalie;
property Id: String read FId;
property Name: String read FName;
property Origin: String read FOrigin;
property Players: Integer read FPlayers;
end;
TSports = class(TObject)
private
FItems: TList;
function GetCount: Integer;
function GetItem(i: Integer): TSport;
procedure ClearItems;
public
constructor Create;
destructor Destroy; override;
// Load sports from a dataset
procedure LoadDatabase(dataset: TDataset);
// Load sports from stringtable resource
procedure LoadStringTable(base: Integer = 0);
// Load sports from a text stream, standalone file or file resource
procedure LoadTextStream(stream: TStream);
procedure LoadTextFile(const fileName: String);
procedure LoadTextResource(
const resourceName: String;
const resourceType: String = 'SPORT');
// Load sports from a JSON stream, standalone file or file resource
procedure LoadJsonStream(stream: TStream);
procedure LoadJsonFile(const fileName: String);
procedure LoadJsonResource(
const resourceName: String;
const resourceType: String = 'SPORT');
// Load sports from a XML stream, standalone file or file resource
procedure LoadXmlStream(stream: TStream);
procedure LoadXmlFile(const fileName: String);
procedure LoadXmlResource(
const resourceName: String;
const resourceType: String = 'SPORT');
// Load sports from a INI stream, standalone file or file resource
procedure LoadIniStream(stream: TStream);
procedure LoadIniFile(const fileName: String);
procedure LoadIniResource(
const resourceName: String;
const resourceType: String = 'SPORT');
property Count: Integer read GetCount;
property Items[i: Integer]: TSport read GetItem; default;
end;
implementation
uses
System.IniFiles,
System.Json,
Xml.XMLIntf,
Xml.XmlDoc,
NtBase,
NtLocalization;
constructor TSports.Create;
begin
inherited;
FItems := TList.Create;
end;
destructor TSports.Destroy;
begin
ClearItems;
FItems.Free;
inherited;
end;
procedure TSports.ClearItems;
begin
while FItems.Count > 0 do
begin
TSport(FItems[0]).Free;
FItems.Delete(0);
end;
end;
function TSports.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TSports.GetItem(i: Integer): TSport;
begin
Result := FItems[i];
end;
procedure TSports.LoadDatabase(dataset: TDataset);
const
NAME_C = 'Name';
PLAYERS_C = 'FieldPlayers';
GOALIE_C = 'Goalie';
ORIGIN_C = 'Origin';
DESCRIPTION_C = 'Description';
var
item: TSport;
begin
ClearItems;
while not dataset.Eof do
begin
item := TSport.Create;
item.FName := dataset.FieldByName(NAME_C).AsString;
item.FPlayers := dataset.FieldByName(PLAYERS_C).AsInteger;
item.FGoalie := dataset.FieldByName(GOALIE_C).AsBoolean;
item.FOrigin := dataset.FieldByName(ORIGIN_C).AsString;
item.FDescription := dataset.FieldByName(DESCRIPTION_C).AsString;
FItems.Add(item);
dataset.Next;
end;
end;
procedure TSports.LoadStringTable(base: Integer);
var
current: Integer;
function GetString(item: Integer): String;
begin
Result := LoadStr(base + 10*current + item);
end;
const
NAME_C = 0;
PLAYERS_C = 1;
GOALIE_C = 2;
ORIGIN_C = 3;
DESCRIPTION_C = 4;
var
item: TSport;
begin
ClearItems;
current := 0;
// Reads country properties until find an empty string (i.e. no resource string value)
while GetString(NAME_C) <> '' do
begin
item := TSport.Create;
item.FName := GetString(NAME_C);
item.FPlayers := StrToIntDef(GetString(PLAYERS_C), 0);
item.FGoalie := GetString(GOALIE_C) <> '0';
item.FOrigin := GetString(ORIGIN_C);
item.FDescription := GetString(DESCRIPTION_C);
FItems.Add(item);
Inc(current);
end;
end;
// Text
procedure TSports.LoadTextStream(stream: TStream);
function IsEof: Boolean;
begin
Result := stream.Position >= stream.Size;
end;
function GetString: String;
var
c: AnsiChar;
utf8: RawByteString;
begin
utf8 := '';
repeat
stream.Read(c, 1);
if not (c in [#9, #10, #13]) then
utf8 := utf8 + c;
until IsEof or (c = #9) or (c = #10);
Result := Utf8ToString(utf8);
end;
function GetInteger: Integer;
begin
Result := StrToIntDef(GetString, 0);
end;
var
header: RawByteString;
item: TSport;
begin
ClearItems;
SetLength(header, 3);
stream.Read(header[1], 3);
if header <> #$EF#$BB#$BF then
raise Exception.Create('Not valid UTF-8');
try
while not IsEof do
begin
item := TSport.Create;
item.FId := GetString;
item.FName := GetString;
item.FPlayers := GetInteger;
item.FGoalie := GetInteger > 0;
item.FOrigin := GetString;
item.FDescription := GetString;
FItems.Add(item);
end;
finally
stream.Free;
end;
end;
procedure TSports.LoadTextFile(const fileName: String);
begin
LoadTextStream(TFileStream.Create(fileName, fmOpenRead));
end;
procedure TSports.LoadTextResource(const resourceName: String; const resourceType: String);
begin
LoadTextStream(TNtResources.GetResourceStream(PChar(resourceType), PChar(resourceName)));
end;
// JSON
procedure TSports.LoadJsonStream(stream: TStream);
var
jsonItem: TJSONValue;
function GetString(const name: String): String;
begin
Result := jsonItem.GetValue<String>(name);
end;
function GetInteger(const name: String): Integer;
begin
Result := jsonItem.GetValue<Integer>(name);
end;
function GetBoolean(const name: String): Boolean;
begin
Result := jsonItem.GetValue<Boolean>(name);
end;
var
item: TSport;
bytes: TArray<Byte>;
json: TJSONArray;
begin
ClearItems;
SetLength(bytes, stream.Size);
stream.Read(bytes, Length(bytes));
json := TJSONObject.ParseJSONValue(bytes, 0) as TJSONArray;
try
for jsonItem in json do
begin
item := TSport.Create;
item.FId := GetString('id');
item.FName := GetString('name');
item.FPlayers := GetInteger('fieldplayers');
item.FGoalie := GetBoolean('goalie');
item.FOrigin := GetString('origin');
item.FDescription := GetString('description');
FItems.Add(item);
end;
finally
json.Free;
stream.Free;
end;
end;
procedure TSports.LoadJsonResource(const resourceName: String; const resourceType: String);
begin
LoadJsonStream(TNtResources.GetResourceStream(PChar(resourceType), PChar(resourceName)));
end;
procedure TSports.LoadJsonFile(const fileName: String);
begin
LoadJsonStream(TFileStream.Create(fileName, fmOpenRead));
end;
// XML
procedure TSports.LoadXmlStream(stream: TStream);
var
xmlItem: IXMLNode;
function GetString(const name: String): String;
begin
Result := xmlItem.Attributes[name];
end;
function GetInteger(const name: String): Integer;
begin
Result := xmlItem.Attributes[name];
end;
function GetBoolean(const name: String): Boolean;
begin
Result := xmlItem.Attributes[name];
end;
var
i: Integer;
item: TSport;
document: TXMLDocument;
sports: IXMLNode;
begin
ClearItems;
document := TXMLDocument.Create(nil);
try
document.LoadFromStream(stream);
sports := document.ChildNodes.FindNode('sports');
for i := 0 to sports.ChildNodes.Count - 1 do
begin
xmlItem := sports.ChildNodes[i];
item := TSport.Create;
item.FId := GetString('id');
item.FName := GetString('name');
item.FPlayers := GetInteger('fieldplayers');
item.FGoalie := GetBoolean('goalie');
item.FOrigin := GetString('origin');
item.FDescription := xmlItem.ChildNodes.FindNode('description').Text;
FItems.Add(item);
end;
finally
document.Free;
stream.Free;
end;
end;
procedure TSports.LoadXmlResource(const resourceName: String; const resourceType: String);
begin
LoadXmlStream(TNtResources.GetResourceStream(PChar(resourceType), PChar(resourceName)));
end;
procedure TSports.LoadXmlFile(const fileName: String);
begin
LoadXmlStream(TFileStream.Create(fileName, fmOpenRead));
end;
// INI
procedure TSports.LoadIniStream(stream: TStream);
var
section: String;
iniFile: TMemIniFile;
function GetString(const name: String): String;
begin
Result := iniFile.ReadString(section, name, '');
end;
function GetInteger(const name: String): Integer;
begin
Result := StrToIntDef(GetString(name), 0);
end;
function GetBoolean(const name: String): Boolean;
begin
Result := GetInteger(name) = 1;
end;
var
i: Integer;
item: TSport;
stringList, sections: TStringList;
begin
ClearItems;
iniFile := TMemIniFile.Create('');
stringList := TStringList.Create;
sections := TStringList.Create;
try
stringList.LoadFromStream(stream);
iniFile.SetStrings(stringList);
iniFile.ReadSections(sections);
for i := 0 to sections.Count - 1 do
begin
section := sections[i];
item := TSport.Create;
item.FId := section;
item.FName := GetString('name');
item.FPlayers := GetInteger('fieldplayers');
item.FGoalie := GetBoolean('goalie');
item.FOrigin := GetString('origin');
item.FDescription := GetString('description');
FItems.Add(item);
end;
finally
sections.Free;
stringList.Free;
iniFile.Free;
stream.Free;
end;
end;
procedure TSports.LoadIniResource(const resourceName: String; const resourceType: String);
begin
LoadIniStream(TNtResources.GetResourceStream(PChar(resourceType), PChar(resourceName)));
end;
procedure TSports.LoadIniFile(const fileName: String);
begin
LoadIniStream(TFileStream.Create(fileName, fmOpenRead));
end;
end.
|
(* A barrel, may contain items when broken apart. This is an entity instead of
an item because it may tranform into a trap or another entity when attacked *)
unit barrel;
{$mode objfpc}{$H+}
interface
uses
SysUtils, map, items, ale_tankard, leather_armour1, cloth_armour1, wine_flask;
(* Create a barrel *)
procedure createBarrel(uniqueid, npcx, npcy: smallint);
(* Take a turn *)
procedure takeTurn(id, spx, spy: smallint);
(* Barrel breaks open *)
procedure breakBarrel(x, y: smallint);
implementation
uses
entities, globalutils;
procedure createBarrel(uniqueid, npcx, npcy: smallint);
begin
// Add a Barrel to the list of creatures
entities.listLength := length(entities.entityList);
SetLength(entities.entityList, entities.listLength + 1);
with entities.entityList[entities.listLength] do
begin
npcID := uniqueid;
race := 'barrel';
description := 'a sealed, wooden barrel';
glyph := '8';
maxHP := randomRange(1, 3);
currentHP := maxHP;
attack := 0;
defense := 0;
weaponDice := 0;
weaponAdds := 0;
xpReward := maxHP;
visionRange := 1;
NPCsize := 1;
trackingTurns := 0;
moveCount := 0;
targetX := 0;
targetY := 0;
inView := False;
blocks := True;
discovered := False;
weaponEquipped := False;
armourEquipped := False;
isDead := False;
abilityTriggered := False;
stsDrunk := False;
stsPoison := False;
tmrDrunk := 0;
tmrPoison := 0;
posX := npcx;
posY := npcy;
end;
(* Occupy tile *)
map.occupy(npcx, npcy);
end;
procedure takeTurn(id, spx, spy: smallint);
begin
entities.moveNPC(id, spx, spy);
end;
procedure breakBarrel(x, y: smallint);
var
percentage: smallint;
begin
percentage := randomRange(1, 100);
(* Create a new entry in item list and add item details *)
Inc(items.itemAmount);
SetLength(items.itemList, items.itemAmount);
if (percentage <= 40) then
(* Drop an item - Flask of Wine *)
createWineFlask(itemAmount, x, y)
else if (percentage > 40) and (percentage < 80) then
(* Drop an item - Ale Tankard *)
createAleTankard(itemAmount, x, y)
else if (percentage >= 80) and (percentage <= 90) then
(* Drop an item - Cloth armour*)
createClothArmour(itemAmount, x, y)
else
(* Drop an item - Leather armour*)
createLeatherArmour(itemAmount, x, y);
end;
end.
|
Unit ClassWatchAdd;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Windows, Messages, SysUtils,
Variants, Classes, Graphics,
Controls, Forms, Dialogs, ExtCtrls,
StdCtrls, ComCtrls, ClassWatch, Generics.Collections;
Type
TClassWatchAddFrm = Class (TForm)
MainPanel: TPanel;
CancelButton: TButton;
OkButton: TButton;
FilterPositionRadioGroup: TRadioGroup;
GroupBox1: TGroupBox;
ClassListView: TListView;
procedure OkButtonClick(Sender: TObject);
procedure ClassListViewData(Sender: TObject; Item: TListItem);
procedure CancelButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure ClassListViewCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
Private
FBeginning : Boolean;
FSelectedClass : TWatchableClass;
FCancelled : Boolean;
FWatchList : TList<TWatchableClass>;
Public
Property Beginning : Boolean Read FBeginning;
Property SelectedClass : TWatchableClass Read FSelectedClass;
Property Cancelled : Boolean Read FCancelled;
end;
Implementation
{$R *.dfm}
Uses
Utils;
Procedure TClassWatchAddFrm.CancelButtonClick(Sender: TObject);
begin
Close;
end;
Procedure TClassWatchAddFrm.ClassListViewCustomDrawItem(Sender: TCustomListView;
Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean);
Var
L : TListView;
wc : TWatchableClass;
begin
L := (Sender As TListVIew);
wc := FWatchList[Item.Index];
If wc.Registered Then
L.Canvas.Font.Color := clGray
Else L.Canvas.Font.Color := clBlack;
DefaultDraw := True;
end;
Procedure TClassWatchAddFrm.ClassListViewData(Sender: TObject; Item: TListItem);
Var
wc : TWatchableClass;
begin
With Item Do
begin
wc := FWatchList[Index];
Caption := wc.Name;
If wc.UpperFIlter Then
SubItems.Add('upper')
Else SubItems.Add('lower');
SubItems.Add(wc.GUid);
end;
end;
Procedure TClassWatchAddFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
Var
wc : TWatchableClass;
begin
For wc In FWatchList Do
wc.Free;
FWatchList.Free;
end;
Procedure TClassWatchAddFrm.FormCreate(Sender: TObject);
Var
err : Cardinal;
begin
FCancelled := True;
FSelectedClass := Nil;
FWatchList := TList<TWatchableClass>.Create;
err := TWatchableClass.Enumerate(FWatchList);
If err = ERROR_SUCCESS Then
ClassListVIew.Items.Count := FWatchList.Count
Else Utils.WinErrorMessage('Failed to enumerate watchable classes', err);
end;
Procedure TClassWatchAddFrm.OkButtonClick(Sender: TObject);
Var
L : TListItem;
begin
L := ClassListView.Selected;
If Assigned(L) Then
begin
FSelectedClass := FWatchList[L.Index];
If (Not FSelectedClass.Registered) Then
begin
FCancelled := False;
FBeginning := (FilterPositionRadioGroup.ItemIndex = 0);
FWatchList.Delete(L.Index);
Close;
end
Else WarningMessage('The selected class must not be watched already');
end
Else WarningMessage('No class selected');
end;
End.
|
{******************************************************************************}
{ }
{ Delphi OPENSSL Library }
{ Copyright (c) 2016 Luca Minuti }
{ https://bitbucket.org/lminuti/delphi-openssl }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit SSLDemo.MainFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.StdCtrls, Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
type
TMainFrame = class(TFrame)
edtTextToCrypt: TEdit;
lblTextToCrypt: TLabel;
lblCertPath: TLabel;
edtCertFile: TEdit;
btnCryptWithKey: TButton;
lblPriv: TLabel;
edtPriv: TEdit;
btnDecryptWithKey: TButton;
Label1: TLabel;
edtPub: TEdit;
btnCryptWithCert: TButton;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
btnGenerateSampleFile: TButton;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
edtP7MTestFile: TEdit;
Label11: TLabel;
BtnGenerateKeyPairs: TButton;
Label12: TLabel;
Label13: TLabel;
procedure btnCryptWithKeyClick(Sender: TObject);
procedure btnDecryptWithKeyClick(Sender: TObject);
procedure btnCryptWithCertClick(Sender: TObject);
procedure btnGenerateSampleFileClick(Sender: TObject);
procedure BtnGenerateKeyPairsClick(Sender: TObject);
private
procedure PassphraseReader(Sender: TObject; var Passphrase: string);
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
OpenSSL.RSAUtils;
{ TMainForm }
procedure TMainFrame.btnCryptWithKeyClick(Sender: TObject);
var
RSAUtil: TRSAUtil;
begin
RSAUtil := TRSAUtil.Create;
try
RSAUtil.PublicKey.LoadFromFile(edtPub.Text);
RSAUtil.PublicEncrypt(edtTextToCrypt.Text, edtTextToCrypt.Text + '.keycry');
finally
RSAUtil.Free;
end;
end;
procedure TMainFrame.btnDecryptWithKeyClick(Sender: TObject);
var
RSAUtil: TRSAUtil;
begin
RSAUtil := TRSAUtil.Create;
try
RSAUtil.PrivateKey.OnNeedPassphrase := PassphraseReader;
RSAUtil.PrivateKey.LoadFromFile(edtPriv.Text);
RSAUtil.PrivateDecrypt(edtTextToCrypt.Text + '.keycry', edtTextToCrypt.Text + '.certdecry.txt');
finally
RSAUtil.Free;
end;
end;
procedure TMainFrame.btnCryptWithCertClick(Sender: TObject);
var
RSAUtil: TRSAUtil;
Cerificate: TX509Cerificate;
begin
RSAUtil := TRSAUtil.Create;
try
Cerificate := TX509Cerificate.Create;
try
Cerificate.LoadFromFile(edtCertFile.Text);
RSAUtil.PublicKey.LoadFromCertificate(Cerificate);
RSAUtil.PublicEncrypt(edtTextToCrypt.Text, edtTextToCrypt.Text + '.certcry');
finally
Cerificate.Free;
end;
finally
RSAUtil.Free;
end;
end;
procedure TMainFrame.btnGenerateSampleFileClick(Sender: TObject);
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Text := 'Hello, world!';
SL.SaveToFile(edtTextToCrypt.Text, TEncoding.Unicode);
finally
SL.Free;
end;
end;
constructor TMainFrame.Create(AOwner: TComponent);
var
TestFolder: string;
begin
inherited;
TestFolder := StringReplace(ExtractFilePath(ParamStr(0)), 'Samples' + PathDelim + 'SSLDemo', 'TestData', [rfReplaceAll, rfIgnoreCase]);
edtCertFile.Text := TestFolder + 'publiccert.pem';
edtPriv.Text := TestFolder + 'privatekey.pem';
edtPub.Text := TestFolder + 'publickey.pem';
edtTextToCrypt.Text := TestFolder + 'test.txt';
edtP7MTestFile.Text := TestFolder + 'TestPKCS7.pdf.p7m';
end;
procedure TMainFrame.PassphraseReader(Sender: TObject; var Passphrase: string);
begin
Passphrase := InputBox(Name, 'Passphrase', '');
end;
procedure TMainFrame.BtnGenerateKeyPairsClick(Sender: TObject);
var
KeyPair: TRSAKeyPair;
begin
KeyPair := TRSAKeyPair.Create;
try
KeyPair.GenerateKey;
KeyPair.PrivateKey.SaveToFile(edtPriv.Text);
KeyPair.PublicKey.SaveToFile(edtPub.Text);
finally
KeyPair.Free;
end;
end;
end.
|
unit cpuid;
interface
uses windows, sysutils;
const
{ Error flags }
ERR_NOERROR = 0;
ERR_CPUIDNOTSUPPORTED = (-1);
ERR_EXECUTIONLEVELNOTSUPPORTED = (-2);
ERR_BADINFOSTRUCTURE = (-3);
{ Return value identifiers }
VAL_NOVALUE = 0;
{ CPUID EFLAGS Id bit }
CPUIDID_BIT = $200000;
{ Default Benchmark delay }
BENCHMARK_DELAY = 500;
{ Processor flags (temporary - for future SMP support) }
USE_DEFAULT = 0;
{ CPUID execution levels }
CPUID_MAXLEVEL : DWORD = $0;
CPUID_VENDORSIGNATURE : DWORD = $0;
CPUID_CPUSIGNATURE : DWORD = $1;
CPUID_CPUFEATURESET : DWORD = $1;
CPUID_CACHETLB : DWORD = $2;
CPUID_CPUSERIALNUMBER : DWORD = $3;
CPUID_MAXLEVELEX : DWORD = $80000000;
CPUID_CPUSIGNATUREEX : DWORD = $80000001;
CPUID_CPUMARKETNAME1 : DWORD = $80000002;
CPUID_CPUMARKETNAME2 : DWORD = $80000003;
CPUID_CPUMARKETNAME3 : DWORD = $80000004;
CPUID_LEVEL1CACHETLB : DWORD = $80000005;
CPUID_LEVEL2CACHETLB : DWORD = $80000006;
{ CPUID result indexes }
EAX = 1;
EBX = 2;
ECX = 3;
EDX = 4;
{ Standard feature set flags }
SFS_FPU = 0;
SFS_VME = 1;
SFS_DE = 2;
SFS_PSE = 3;
SFS_TSC = 4;
SFS_MSR = 5;
SFS_PAE = 6;
SFS_MCE = 7;
SFS_CX8 = 8;
SFS_APIC = 9;
SFS_SEP = 11;
SFS_MTRR = 12;
SFS_PGE = 13;
SFS_MCA = 14;
SFS_CMOV = 15;
SFS_PAT = 16;
SFS_PSE36 = 17;
SFS_SERIAL = 18;
SFS_CLFLUSH = 19;
SFS_DTS = 21;
SFS_ACPI = 22;
SFS_MMX = 23;
SFS_XSR = 24;
SFS_SIMD = 25;
SFS_SIMD2 = 26;
SFS_SS = 27;
SFS_TM = 29;
{ Extended feature set flags (duplicates removed) }
EFS_EXMMXA = 22; { AMD Specific }
EFS_EXMMXC = 24; { Cyrix Specific }
EFS_3DNOW = 31;
EFS_EX3DNOW = 30;
{ Processor family values }
CPU_486CLASS = 4;
CPU_PENTIUMCLASS = 5;
CPU_PENTIUMIICLASS = 6;
CPU_PENTIUMIVCLASS = 15;
{ Pentium III-specific model }
CPU_PENTIUMIIIMODEL = 7;
{ Processor type values }
CPU_OVERDRIVE = 1;
{ Extended Cache Levels }
CACHE_LEVEL1 = 0;
CACHE_LEVEL2 = 1;
{ Brand ID Identifiers }
BRAND_UNSUPPORTED = 0;
BRAND_CELERON = 1;
BRAND_PENTIUMIII = 2;
BRAND_PENTIUMIIIXEON = 3;
BRAND_PENTIUMIV = 8;
{ Extended Model & Family Indicator }
EXTENDED_FIELDS = $f;
{ Normalised processor speeds }
MAX_SPEEDS = 47;
CPUSPEEDS: array[0..MAX_SPEEDS - 1] of Integer = (
25, 33, 60, 66, 75, 82, 90, 100, 110, 116, 120, 133, 150, 166, 180,
188, 200, 225, 233, 266, 300, 333, 350, 366, 400, 415, 433, 450, 466, 500,
533, 550, 600, 650, 667, 700, 733, 750, 800, 833, 850, 866, 900, 933, 950,
966, 1000);
{ Speeds below this value use the CPUSPEEDS_LO array, above uses CPUSPEEDS_HI }
SPEED_LO_THRESHOLD = 300;
{ Possible normalised unit values for speeds < SPEED_LO_THRESHOLD }
MAX_SPEEDS_LO = 15;
CPUSPEEDS_LO: array[0..MAX_SPEEDS_LO - 1] of Integer = (
0, 10, 16, 20, 25, 33, 40, 50, 60, 66, 75, 80, 82, 88, 90);
{ Possible normalised unit values for speeds >= SPEED_LO_THRESHOLD }
MAX_SPEEDS_HI = 5;
CPUSPEEDS_HI: array[0..MAX_SPEEDS_HI - 1] of Integer = (0, 33, 50, 66, 100);
type
TCPUIDResult = packed record
EAX: Cardinal;
EBX: Cardinal;
ECX: Cardinal;
EDX: Cardinal;
end;
TVendor = array[0..11] of char;
function GetCPUSerialNumberRaw: DWord;
function GetCPUSerialNumber: String;
function GetHDDSerialNumber: DWord;
function GetCPUVendor: TVendor; assembler; register;
function GetCPUCount: byte;
function GetCPUIDSupport: Boolean;
var
CPUID_LastError: LongInt;
CPUID_Level: Cardinal;
implementation
function GetCPUCount: byte;
var
si: TSystemInfo;
begin
GetSystemInfo(si);
Result := si.dwNumberOfProcessors;
end;
function GetCPUVendor: TVendor; assembler; register;
asm
PUSH EBX {Save affected register}
PUSH EDI
MOV EDI,EAX {@Result (TVendor)}
MOV EAX,0
DW $A20F {CPUID Command}
MOV EAX,EBX
XCHG EBX,ECX {save ECX result}
MOV ECX,4
@1:
STOSB
SHR EAX,8
LOOP @1
MOV EAX,EDX
MOV ECX,4
@2:
STOSB
SHR EAX,8
LOOP @2
MOV EAX,EBX
MOV ECX,4
@3:
STOSB
SHR EAX,8
LOOP @3
POP EDI {Restore registers}
POP EBX
end;
function GetCPUIDSupport: Boolean;
{ Returns TRUE if the CPU supports the CPUID instruction, FALSE otherwise }
asm
PUSHFD
POP EAX
MOV EDX, EAX
XOR EAX, CPUIDID_BIT
PUSH EAX
POPFD
PUSHFD
POP EAX
XOR EAX, EDX
JZ @exit
MOV AL, TRUE
@exit:
end; //------------
function ExecuteCPUID: TCPUIDResult; assembler;
{ Executes the CPUID instruction at the required level }
asm
PUSH EBX
PUSH EDI
MOV EDI, EAX
MOV EAX, CPUID_LEVEL
DW $A20F
STOSD
MOV EAX, EBX
STOSD
MOV EAX, ECX
STOSD
MOV EAX, EDX
STOSD
POP EDI
POP EBX
end; //------------
function GetMaxCPUIDLevel: LongInt;
{ Returns the maximum supported standard CPUID level }
var
Signature: TCPUIDResult;
begin
if (GetCPUIDSupport) then begin
CPUID_Level := CPUID_MAXLEVEL;
Signature := ExecuteCPUID;
Result := Signature.EAX;
end else begin
CPUID_LastError := ERR_CPUIDNOTSUPPORTED;
Result := VAL_NOVALUE;
end;
end; //------------
function GetMaxExCPUIDLevel: Cardinal;
{ Returns the maximum supported extended CPUID level }
var
Signature: TCPUIDResult;
begin
if (GetCPUIDSupport) then begin
CPUID_LEVEL := CPUID_MAXLEVELEX;
Signature := ExecuteCPUID;
Result := Signature.EAX;
end else begin
CPUID_LastError := ERR_CPUIDNOTSUPPORTED;
Result := VAL_NOVALUE;
end;
end; //------------
function GetMaxExCPUIDLevelI: LongInt;
{ Returns a normal longint representing the maximum extended CPUID level }
var
MaxLevel: Cardinal;
begin
MaxLevel := GetMaxExCPUIDLevel;
if ((MaxLevel and not(CPUID_MAXLEVELEX)) >= 8) then
Result := 0
else
Result := (MaxLevel and not(CPUID_MAXLEVELEX));
end;
function ExecuteCPUIDEx(AExecutionLevel: Cardinal; AIterations: Byte; var AResult: TCPUIDResult): Boolean;
{ Verifies whether the CPUID instruction is supported at the required level and and if it is
then it is executed the number of times specified by AIterations }
var
Iteration: Byte;
begin
if not(GetCPUIDSupport) then begin
CPUID_LastError := ERR_CPUIDNOTSUPPORTED;
Result := FALSE;
Exit;
end;
if (LongInt(AExecutionLevel) > GetMaxCPUIDLevel) and (AExecutionLevel > GetMaxExCPUIDLevel) then begin
CPUID_LastError := ERR_EXECUTIONLEVELNOTSUPPORTED;
Result := FALSE;
Exit;
end;
// Execute the CPUID instruction
CPUID_LEVEL := AExecutionLevel;
for Iteration := 1 to AIterations do
AResult := ExecuteCPUID;
CPUID_LastError := ERR_NOERROR;
Result := TRUE;
end;
function GetCPUSerialNumber: String;
{ Returns the processor serial number (Intel PIII only)
Based on code submitted by Pierrick Lucas }
function SplitToNibble(ANumber: String): String;
{ Formats 8-digit number into 4-digit nibbles XXXX-XXXX }
begin
Result := Copy(ANumber, 0, 4) + '-' + Copy(ANumber, 5, 4);
end;
var
SerialNumber: TCPUIDResult;
begin
Result := '';
if (ExecuteCPUIDEx(CPUID_CPUSIGNATURE, 1, SerialNumber)) then begin
Result := SplitToNibble(IntToHex(SerialNumber.EAX, 8)) + '-';
if (ExecuteCPUIDEx(CPUID_CPUSIGNATURE, 1, SerialNumber)) then begin
Result := Result + SplitToNibble(IntToHex(SerialNumber.EDX, 8)) + '-';
Result := Result + SplitToNibble(IntToHex(SerialNumber.ECX, 8));
end else
Result := '';
end else
Result := '';
end; //------------
function GetCPUSerialNumberRaw: DWord;
{ Returns the processor serial number (Intel PIII+) only without formatting }
var
SerialNumber: TCPUIDResult;
begin
Result := 0;
if (ExecuteCPUIDEx(CPUID_CPUSIGNATURE, 1, SerialNumber)) then begin
if (ExecuteCPUIDEx(CPUID_CPUSIGNATURE, 1, SerialNumber)) then begin
Result := SerialNumber.EDX+SerialNumber.EAX;
end else
Result := 0;
end else
Result := 0;
end; //------------
function GetHDDSerialNumber: DWord;
var
SerialNum : dword;
a, b : dword;
Buffer : array [0..255] of char;
begin
if GetVolumeInformation('c:\', Buffer, SizeOf(Buffer), @SerialNum, a, b, nil, 0) then
Result := SerialNum
else
if GetVolumeInformation('d:\', Buffer, SizeOf(Buffer), @SerialNum, a, b, nil, 0) then
Result := SerialNum
else
Result := 0;
end; //------------
end.
|
unit uDBShellUtils;
interface
uses
Winapi.Windows,
Vcl.Graphics,
Vcl.Forms,
Dmitry.Utils.Files,
acWorkRes,
UnitDBFileDialogs,
uResourceUtils,
uTranslate,
uShellUtils,
uMemory,
uShellIntegration;
function GetIconForFile(Ico: TIcon; out IcoTempName: string; out Language: Integer): Boolean;
implementation
function GetIconForFile(Ico: TIcon; out IcoTempName: string; out Language: Integer): Boolean;
var
LoadIconDLG: DBOpenDialog;
FN: string;
Index: Integer;
Update: DWORD;
function FindIconEx(FileName: string; Index: Integer): Boolean;
var
ResIcoNameW: PWideChar;
begin
Result := False;
Update := BeginUpdateResourceW(PChar(FileName), False, False);
if Update = 0 then
Exit;
try
Language := GetIconLanguage(Update, index);
ResIcoNameW := GetNameIcon(Update, index);
SaveIconGroupResourceW(Update, ResIcoNameW, Language, PWideChar(IcoTempName))
finally
EndUpdateResourceW(Update, True);
end;
Result := True;
end;
begin
Result := False;
Ico.Assign(nil);
LoadIconDLG := DBOpenDialog.Create;
try
LoadIconDLG.Filter := TA('All supported formats|*.exe;*.ico;*.dll;*.ocx;*.scr|Icons (*.ico)|*.ico|Executable files (*.exe)|*.exe|Dll files (*.dll)|*.dll', 'System');
if LoadIconDLG.Execute then
begin
FN := LoadIconDLG.FileName;
if GetEXT(FN) = 'ICO' then
Ico.LoadFromFile(FN);
if (GetEXT(FN) = 'EXE') or (GetEXT(FN) = 'DLL') or (GetEXT(FN) = 'OCX') or (GetEXT(FN) = 'SCR') then
begin
if ChangeIconDialog(Application.Handle, FN, index) then
begin
IcoTempName := uShellUtils.GetTempFileName;
FindIconEx(FN, Index);
Ico.LoadFromFile(IcoTempName);
DeleteFile(PChar(IcoTempName));
end;
end;
Result := not Ico.Empty;
end;
finally
F(LoadIconDLG);
end;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Menus, Vcl.ExtDlgs;
type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
File1: TMenuItem;
Print1: TMenuItem;
RichEdit1: TRichEdit;
Save1: TMenuItem;
PrintDialog1: TPrintDialog;
FontDialog1: TFontDialog;
Font1: TMenuItem;
Format1: TMenuItem;
Quit1: TMenuItem;
Edit1: TMenuItem;
Undo1: TMenuItem;
N1: TMenuItem;
Cut1: TMenuItem;
Copy1: TMenuItem;
Paste1: TMenuItem;
Delete1: TMenuItem;
N2: TMenuItem;
Found1: TMenuItem;
Replace1: TMenuItem;
SelectAll1: TMenuItem;
N3: TMenuItem;
FindDialog1: TFindDialog;
ReplaceDialog1: TReplaceDialog;
SaveDialog1: TSaveDialog;
procedure Print1Click(Sender: TObject);
procedure Save1Click(Sender: TObject);
procedure Font1Click(Sender: TObject);
procedure Undo1Click(Sender: TObject);
procedure Cut1Click(Sender: TObject);
procedure Copy1Click(Sender: TObject);
procedure Paste1Click(Sender: TObject);
procedure Delete1Click(Sender: TObject);
procedure SelectAll1Click(Sender: TObject);
procedure Found1Click(Sender: TObject);
procedure FindDialog1Find(Sender: TObject);
procedure ReplaceDialog1Replace(Sender: TObject);
procedure Replace1Click(Sender: TObject);
procedure Quit1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FindDialog1Find(Sender: TObject);
var
FoundAt: LongInt;
StartPos, ToEnd: Integer;
mySearchTypes: TSearchTypes;
myFindOptions: TFindOptions;
begin
mySearchTypes := [];
with RichEdit1 do
begin
if frMatchCase in FindDialog1.Options then
mySearchTypes := mySearchTypes + [stMatchCase];
if frWholeWord in FindDialog1.Options then
mySearchTypes := mySearchTypes + [stWholeWord];
if SelLength <> 0 then
StartPos := SelStart + SelLength
else
StartPos := 0;
ToEnd := Length(Text) - StartPos;
FoundAt := FindText(FindDialog1.FindText, StartPos, ToEnd, mySearchTypes);
if FoundAt <> -1 then
begin
SetFocus;
SelStart := FoundAt;
SelLength := Length(FindDialog1.FindText);
end
else
Beep;
end;
end;
procedure TForm1.Font1Click(Sender: TObject);
begin
FontDialog1.Font.Name := RichEdit1.SelAttributes.Name;
FontDialog1.Font.Color := RichEdit1.SelAttributes.Color;
FontDialog1.Font.Charset := RichEdit1.SelAttributes.Charset;
FontDialog1.Font.Size := RichEdit1.SelAttributes.Size;
FontDialog1.Font.Style := RichEdit1.SelAttributes.Style;
if not FontDialog1.Execute then
exit;
RichEdit1.SelAttributes.Name := FontDialog1.Font.Name;
RichEdit1.SelAttributes.Color := FontDialog1.Font.Color;
RichEdit1.SelAttributes.Charset := FontDialog1.Font.Charset;
RichEdit1.SelAttributes.Size := FontDialog1.Font.Size;
RichEdit1.SelAttributes.Style := FontDialog1.Font.Style;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TForm1.Found1Click(Sender: TObject);
begin
FindDialog1.Position := Point(RichEdit1.Left + RichEdit1.Width,
RichEdit1.Top);
FindDialog1.Execute;
end;
procedure TForm1.Replace1Click(Sender: TObject);
begin
ReplaceDialog1.Execute;
end;
procedure TForm1.SelectAll1Click(Sender: TObject);
begin
RichEdit1.SelectAll;
end;
procedure TForm1.Undo1Click(Sender: TObject);
begin
RichEdit1.Undo;
end;
procedure TForm1.Cut1Click(Sender: TObject);
begin
RichEdit1.CutToClipboard;
end;
procedure TForm1.Copy1Click(Sender: TObject);
begin
RichEdit1.CopyToClipboard;
end;
procedure TForm1.Paste1Click(Sender: TObject);
begin
RichEdit1.PasteFromClipboard;
end;
procedure TForm1.Delete1Click(Sender: TObject);
begin
RichEdit1.ClearSelection;
end;
procedure TForm1.Print1Click(Sender: TObject);
begin
if PrintDialog1.Execute then
RichEdit1.Print('');
end;
procedure TForm1.Quit1Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.ReplaceDialog1Replace(Sender: TObject);
var
SelPos: Integer;
begin
with TReplaceDialog(Sender) do
begin
SelPos := Pos(FindText, RichEdit1.Lines.Text);
if SelPos > 0 then
begin
RichEdit1.SelStart := SelPos - 1;
RichEdit1.SelLength := Length(FindText);
RichEdit1.SelText := ReplaceText;
end
else
MessageDlg(Concat('Could not find "', FindText, '" in RichEdit1.'),
mtError, [mbOK], 0);
end;
end;
procedure TForm1.Save1Click(Sender: TObject);
begin
if SaveDialog1.Execute then
RichEdit1.Lines.SaveToFile(SaveDialog1.FileName + '.rtf');
end;
end.
|
unit jo9_ostatki_add;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridLevel, cxGrid, dxBar,
ExtCtrls, cxGridBandedTableView, cxMaskEdit, cxDropDownEdit, cxCalendar,
StdCtrls, cxContainer, cxTextEdit, cxCurrencyEdit, cxMemo,
cxLookAndFeelPainters, cxButtons, DB, FIBDataSet, pFIBDataSet, ActnList,
FIBQuery, pFIBQuery, pFIBStoredProc, cxButtonEdit, cxRadioGroup, cxCheckBox,
cxHyperLinkEdit, tagTypes, IBase, jo9_ostatki;
type
TSchRecord = packed record
_id_Sch : integer;
_Num_Sch : string;
_Name_Sch : string;
end;
TSchArray = array of TSchRecord;
Tjo9_ostatki_add_Form = class(TForm)
Panel: TPanel;
Bevel1: TBevel;
Label6: TLabel;
Label2: TLabel;
Label5: TLabel;
Label1: TLabel;
Label3: TLabel;
MainPanel: TPanel;
dxBarDockControl1: TdxBarDockControl;
Grid: TcxGrid;
TableView: TcxGridTableView;
id_Ost_Smet_Column: TcxGridColumn;
id_Dog_Column: TcxGridColumn;
Tip_Dog_Column: TcxGridColumn;
Reg_Num_Column: TcxGridColumn;
Kod_Dog_Column: TcxGridColumn;
Num_Sch_Column: TcxGridColumn;
id_S_Column: TcxGridColumn;
id_R_Column: TcxGridColumn;
id_St_Column: TcxGridColumn;
kod_S_Column: TcxGridColumn;
kod_R_Column: TcxGridColumn;
kod_St_Column: TcxGridColumn;
kod_Kekv_Column: TcxGridColumn;
Summa_Column: TcxGridColumn;
Name_S_Column: TcxGridColumn;
Name_R_Column: TcxGridColumn;
Name_St_Column: TcxGridColumn;
id_Sch_Column: TcxGridColumn;
Name_Sch_Column: TcxGridColumn;
State_Column: TcxGridColumn;
Can_Edit_Column: TcxGridColumn;
Edited_Column: TcxGridColumn;
Name_Shablon_Column: TcxGridColumn;
id_Kekv_Column: TcxGridColumn;
Name_Kekv_Column: TcxGridColumn;
id_CustomerColumn: TcxGridColumn;
GridLevel: TcxGridLevel;
NumDoc: TcxTextEdit;
DateDoc: TcxDateEdit;
NoteMemo: TcxMemo;
Panel2: TPanel;
St_Label: TLabel;
Label17: TLabel;
Label16: TLabel;
R_Label: TLabel;
S_Label: TLabel;
Label15: TLabel;
Label4: TLabel;
Sch_Label: TLabel;
Label7: TLabel;
Kekv_Label: TLabel;
ApplyButton: TcxButton;
CancelButton: TcxButton;
SchGrid: TcxGrid;
SchTableView: TcxGridTableView;
id_Sch_Column2: TcxGridColumn;
Num_Sch_Column2: TcxGridColumn;
Name_Sch_Column2: TcxGridColumn;
SchGridLevel: TcxGridLevel;
RadioGroup: TcxRadioGroup;
DateMove: TcxDateEdit;
SumDoc: TcxCurrencyEdit;
StyleRepository: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
cxStyle17: TcxStyle;
cxStyle18: TcxStyle;
cxStyle19: TcxStyle;
cxStyle20: TcxStyle;
cxStyle21: TcxStyle;
cxStyle22: TcxStyle;
cxStyle23: TcxStyle;
cxStyle24: TcxStyle;
cxStyle25: TcxStyle;
cxStyle26: TcxStyle;
cxStyle27: TcxStyle;
cxStyle28: TcxStyle;
GridTableViewStyleSheet: TcxGridTableViewStyleSheet;
GridBandedTableViewStyleSheet: TcxGridBandedTableViewStyleSheet;
BarManager: TdxBarManager;
AddDog: TdxBarButton;
CloneButton: TdxBarButton;
DelDog: TdxBarButton;
dxBarButton1: TdxBarButton;
DataSet: TpFIBDataSet;
ActionList: TActionList;
Action2: TAction;
Action1: TAction;
StoredProc: TpFIBStoredProc;
procedure CancelButtonClick(Sender: TObject);
procedure AddDogClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure TableViewFocusedRecordChanged(Sender: TcxCustomGridTableView;
APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure SchTableViewDblClick(Sender: TObject);
procedure Num_Sch_ColumnPropertiesCloseUp(Sender: TObject);
procedure SchTableViewKeyPress(Sender: TObject; var Key: Char);
procedure Num_Sch_ColumnPropertiesPopup(Sender: TObject);
procedure ApplyButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure DelDogClick(Sender: TObject);
procedure TableViewEditValueChanged(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem);
procedure kod_S_ColumnPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure SumDocKeyPress(Sender: TObject; var Key: Char);
procedure NumDocKeyPress(Sender: TObject; var Key: Char);
procedure DateDocKeyPress(Sender: TObject; var Key: Char);
procedure NoteMemoKeyPress(Sender: TObject; var Key: Char);
procedure CloneButtonClick(Sender: TObject);
procedure Action2Execute(Sender: TObject);
procedure DateMoveKeyPress(Sender: TObject; var Key: Char);
procedure CheckCanMove;
procedure TableViewFocusedItemChanged(Sender: TcxCustomGridTableView;
APrevFocusedItem, AFocusedItem: TcxCustomGridTableItem);
procedure TableViewCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure Reg_Num_ColumnPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure kod_Kekv_ColumnPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure TableViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Action1Execute(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
public
Database : TISC_DB_HANDLE;
ReadTransaction : TISC_TR_HANDLE;
WriteTransaction : TISC_TR_HANDLE;
Apply : boolean;
State : string;
Res : TResProc;
id_Customer : integer;
id_Doc : integer;
Date_Doc : TDate;
DelArray : TIntArray; // array of deleted records
SYS_Info : Pjo9_SYS_INFO;
CanEditArray : TIntArray;
procedure SaveDoc;
procedure SetLabels;
destructor Destroy; override;
end;
var
jo9_ostatki_add_Form : Tjo9_ostatki_add_Form; // For Add
jo9_ostatki_add_Form2 : Tjo9_ostatki_add_Form; // For Edit
implementation
uses Input_Sum, globalspr, Math, DogLoaderUnit, LoadDogManedger, tagLibUnit;
{$R *.dfm}
procedure Tjo9_ostatki_add_Form.CheckCanMove;
var
k : integer;
begin
if State <> 'Move' then begin
Num_Sch_Column.Options.Editing := True;
Exit;
end;
k := TableView.DataController.FocusedRecordIndex;
if k < 0 then Exit;
Num_Sch_Column.Options.Editing := TableView.DataController.Values[k, 20];
end;
function CheckExtended(s : string; Key : Char; Decimal : integer; Position : byte) : boolean;
var
k : integer;
begin
Result := False;
if Key in [#8, #9, #13] then Result := True
else if Key = #44 then Result := ((Pos(#44, s) = 0) and (Length(s) - Position <= Decimal))
else if Key = #45 then Result := Position = 0
else if Key in ['0'..'9'] then begin
k := Pos(#44, s);
if (k = 0) or (Position < k) then Result := True
else Result := (Length(s) - k < 2);
end;
end;
procedure Tjo9_ostatki_add_Form.CancelButtonClick(Sender: TObject);
begin
if fsModal in FormState then ModalResult := mrCancel
else Close;
end;
procedure Tjo9_ostatki_add_Form.FormCreate(Sender: TObject);
begin
id_Ost_Smet_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
id_Dog_Column.DataBinding.ValueTypeClass := TcxStringValueType;
Kod_Dog_Column.DataBinding.ValueTypeClass := TcxStringValueType;
id_S_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
id_St_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
id_R_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
Summa_Column.DataBinding.ValueTypeClass := TcxCurrencyValueType;
kod_S_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
kod_R_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
kod_St_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
kod_Kekv_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
Name_S_Column.DataBinding.ValueTypeClass := TcxStringValueType;
Name_R_Column.DataBinding.ValueTypeClass := TcxStringValueType;
Name_St_Column.DataBinding.ValueTypeClass := TcxStringValueType;
Tip_Dog_Column.DataBinding.ValueTypeClass := TcxStringValueType;
Reg_Num_Column.DataBinding.ValueTypeClass := TcxStringValueType;
id_Sch_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
Num_Sch_Column.DataBinding.ValueTypeClass := TcxStringValueType;
Name_Sch_Column.DataBinding.ValueTypeClass := TcxStringValueType;
id_Kekv_Column.DataBinding.ValueTypeClass := TcxIntegerValueType;
Name_Kekv_Column.DataBinding.ValueTypeClass := TcxStringValueType;
id_CustomerColumn.DataBinding.ValueTypeClass := TcxIntegerValueType;
id_Sch_Column2.DataBinding.ValueTypeClass := TcxIntegerValueType;
Num_Sch_Column2.DataBinding.ValueTypeClass := TcxStringValueType;
Name_Sch_Column2.DataBinding.ValueTypeClass := TcxStringValueType;
State_Column.DataBinding.ValueTypeClass := TcxStringValueType;
Can_Edit_Column.DataBinding.ValueTypeClass := TcxBooleanValueType;
Edited_Column.DataBinding.ValueTypeClass := TcxBooleanValueType;
Name_Shablon_Column.DataBinding.ValueTypeClass := TcxStringValueType;
Sch_Label.Caption := '';
S_Label.Caption := '';
R_Label.Caption := '';
St_Label.Caption := '';
Kekv_Label.Caption := '';
end;
procedure Tjo9_ostatki_add_Form.AddDogClick(Sender: TObject);
var
S : TInput_Sum_Form;
c : currency;
Sum : currency;
Res : TDogResult;
input : TDogInput;
i : integer;
FocusRec : integer;
begin
if Length(SYS_INFO^._Native_Sch^) = 0 then begin
ShowMessage('Відсутні доступні рахунки');
Exit;
end;
c := 0;
with TableView.DataController do begin
for i := 0 to RecordCount - 1 do if not VarIsNull(Values[i, 13]) then c := c + Values[i, 13];
end;
S := TInput_Sum_Form.Create(Self);
S.ShowExtras := False;
S.SumEdit.Value := SumDoc.Value - c;
if S.ShowModal <> mrOk then Exit;
Sum := S.SumEdit.Value;
input.Owner := Self;
input.DBHandle := Database;
input.ReadTrans := ReadTransaction;
input.WriteTrans := WriteTransaction;
input.FormStyle := fsNormal;
input.Summa := Sum;
input.id_Group := TagTypes.SYS_ID_GROUP_DOG_V;
input.id_Group_add := TagTypes.SYS_ID_GROUP_DOG_A;
input.shablon_data.bUse := True;
input.shablon_data.num := NumDoc.Text;
if DateDoc.Text <> '' then input.shablon_data.date_dog := DateDoc.Date;
input.shablon_data.note := NoteMemo.Text;
input.shablon_data.summa := Sum;
input.filter.bUseFilter := True;
res := DogLoaderUnit.ShowDogMain(Input);
if res.ModalResult <> mrOk then Exit;
with TableView.DataController do begin
for i := 0 to RecordCount - 1 do
if Values[i, 25] <> res.id_customer then begin
ShowMessage('Неможливо додати договор!' + #13 + 'Документ повинен містити договори лише одного контрагента!');
Exit;
end;
end;
FocusRec := -1;
if Length(res.Smets) > 0 then begin
for i := 0 to Length(res.Smets) - 1 do begin
with TableView.DataController do begin
FocusRec := RecordCount;
RecordCount := RecordCount + 1;
Values[RecordCount - 1, 0] := -1;
Values[RecordCount - 1, 1] := res.id_dog;
Values[RecordCount - 1, 2] := res.name_tip_dog;
Values[RecordCount - 1, 3] := res.regest_num;
Values[RecordCount - 1, 4] := res.kod_dog;
Values[RecordCount - 1, 5] := SYS_INFO^._Native_Sch^[0]._Num_Sch;
Values[RecordCount - 1, 6] := res.Smets[i].NumSmeta;
Values[RecordCount - 1, 7] := res.Smets[i].NumRazd;
Values[RecordCount - 1, 8] := res.Smets[i].NumStat;
Values[RecordCount - 1, 23] := res.Smets[i].NumKekv;
Values[RecordCount - 1, 13] := res.Smets[i].NSumma;
Values[RecordCount - 1, 17] := SYS_INFO^._Native_Sch^[0]._id_Sch;
Values[RecordCount - 1, 18] := SYS_INFO^._Native_Sch^[0]._Name_Sch;
Values[RecordCount - 1, 22] := res.name_shablon;
Values[RecordCount - 1, 25] := res.id_customer;
DataSet.SelectSQL.Text := 'select SMETA_TITLE, SMETA_KOD from PUB_SPR_SMETA_INFO(' + IntToStr(res.Smets[i].NumSmeta) + ')';
DataSet.Open;
Values[RecordCount - 1, 9] := DataSet['SMETA_KOD'];
Values[RecordCount - 1, 14] := DataSet['SMETA_TITLE'];
DataSet.Close;
DataSet.SelectSQL.Text := 'select RAZD_ST_NUM, RAZD_ST_TITLE from PUB_SPR_RAZD_ST_INFO(' + IntToStr(res.Smets[i].NumRazd) + ')';
DataSet.Open;
Values[RecordCount - 1, 10] := DataSet['RAZD_ST_NUM'];
Values[RecordCount - 1, 15] := DataSet['RAZD_ST_TITLE'];
DataSet.Close;
DataSet.SelectSQL.Text := 'select RAZD_ST_NUM, RAZD_ST_TITLE from PUB_SPR_RAZD_ST_INFO(' + IntToStr(res.Smets[i].NumStat) + ')';
DataSet.Open;
Values[RecordCount - 1, 11] := DataSet['RAZD_ST_NUM'];
Values[RecordCount - 1, 16] := DataSet['RAZD_ST_TITLE'];
DataSet.Close;
DataSet.SelectSQL.Text := 'select KEKV_CODE, KEKV_TITLE from PUB_GET_KEKV_INFO(' + IntToStr(res.Smets[i].NumKekv)
+ ',' + QuotedStr(DateToStr(SYS_INFO^._Period_Beg)) + ')';
DataSet.Open;
Values[RecordCount - 1, 12] := DataSet['KEKV_CODE'];
Values[RecordCount - 1, 24] := DataSet['KEKV_TITLE'];
DataSet.Close;
Values[RecordCount - 1, 19] := 'ADD';
end;
end;
end
else begin
with TableView.DataController do begin
FocusRec := RecordCount;
RecordCount := RecordCount + 1;
Values[RecordCount - 1, 0] := -1;
Values[RecordCount - 1, 1] := res.id_dog;
Values[RecordCount - 1, 2] := res.name_tip_dog;
Values[RecordCount - 1, 3] := res.regest_num;
Values[RecordCount - 1, 4] := res.kod_dog;
Values[RecordCount - 1, 5] := SYS_INFO^._Native_Sch^[0]._Num_Sch;
Values[RecordCount - 1, 6] := -1;
Values[RecordCount - 1, 7] := -1;
Values[RecordCount - 1, 8] := -1;
Values[RecordCount - 1, 13] := Sum;
Values[RecordCount - 1, 17] := SYS_INFO^._Native_Sch^[0]._id_Sch;
Values[RecordCount - 1, 18] := SYS_INFO^._Native_Sch^[0]._Name_Sch;
Values[RecordCount - 1, 22] := res.name_shablon;
Values[RecordCount - 1, 25] := res.id_customer;
Values[RecordCount - 1, 9] := null;
Values[RecordCount - 1, 14] := '';
Values[RecordCount - 1, 10] := null;
Values[RecordCount - 1, 15] := '';
Values[RecordCount - 1, 11] := null;
Values[RecordCount - 1, 16] := '';
Values[RecordCount - 1, 12] := null;
Values[RecordCount - 1, 23] := -1;
Values[RecordCount - 1, 24] := '';
Values[RecordCount - 1, 19] := 'ADD';
end;
TableView.Controller.EditingController.EditingItem := TableView.Items[8];
end;
if FocusRec >= 0 then TableView.DataController.FocusedRecordIndex := FocusRec;
end;
procedure Tjo9_ostatki_add_Form.TableViewFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
begin
SetLabels;
CheckCanMove;
end;
procedure Tjo9_ostatki_add_Form.SchTableViewDblClick(Sender: TObject);
var
k : integer;
begin
k := SchTableView.DataController.FocusedRecordIndex;
if k < 0 then Exit;
Apply := True;
TableView.Controller.EditingController.HideEdit(True);
end;
procedure Tjo9_ostatki_add_Form.Num_Sch_ColumnPropertiesCloseUp(
Sender: TObject);
var
k : integer;
begin
if not Apply then Exit;
k := SchTableView.ViewData.DataController.FocusedRecordIndex;
with TableView.DataController do begin
if Values[FocusedRecordIndex, 17] = SchTableView.DataController.Values[k, 0] then Exit;
Values[FocusedRecordIndex, 17] := SchTableView.DataController.Values[k, 0];
Values[FocusedRecordIndex, 5] := SchTableView.DataController.Values[k, 1];
Values[FocusedRecordIndex, 18] := SchTableView.DataController.Values[k, 2];
Values[FocusedRecordIndex, 21] := True;
SetLabels;
if Values[FocusedRecordIndex, 19] <> 'ADD' then begin
SetLength(DelArray, Length(DelArray) + 1);
DelArray[Length(DelArray) - 1] := Values[FocusedRecordIndex, 0];
Values[FocusedRecordIndex, 19] := 'ADD';
end;
end;
end;
procedure Tjo9_ostatki_add_Form.SchTableViewKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #27 {Esc} then TableView.Controller.EditingController.HideEdit(False)
else if Key = #13 {Enter} then begin
if SchTableView.DataController.FocusedRecordIndex < 0 then Exit;
Apply := True;
TableView.Controller.EditingController.HideEdit(True);
end;
end;
procedure Tjo9_ostatki_add_Form.Num_Sch_ColumnPropertiesPopup(
Sender: TObject);
var
k : integer;
Key : integer;
begin
Apply := False;
k := TableView.DataController.FocusedRecordIndex;
Key := -1;
if not VarIsNull(TableView.DataController.Values[k, 17]) then Key := TableView.DataController.Values[k, 17];
SchTableView.DataController.FocusedRecordIndex := SchTableView.DataController.FindRecordIndexByText(0, 0, IntToStr(Key), False, False, True);
end;
procedure Tjo9_ostatki_add_Form.ApplyButtonClick(Sender: TObject);
var
i : integer;
Flag : boolean;
begin
if TableView.DataController.RecordCount = 0 then begin
ShowMessage('Неможливо зберегти порожній документ!');
Exit;
end;
if NumDoc.Text = '' then begin
ShowMessage('Ви не ввели номер документу!');
NumDoc.SetFocus;
Exit;
end;
if DateDoc.Text = '' then begin
ShowMessage('Ви не ввели дату документу!');
DateDoc.SetFocus;
Exit;
end;
if NoteMemo.Text = '' then begin
ShowMessage('Ви не ввели підставу документу!');
NoteMemo.SetFocus;
Exit;
end;
if TableView.DataController.Summary.FooterSummaryValues[1] <> SumDoc.Value then begin
ShowMessage('Сума ' + QuotedStr(CurrToStr(TableView.DataController.Summary.FooterSummaryValues[1]))
+ ' не дорівнює сумі документа ' + QuotedStr(SumDoc.Text) + '!');
SumDoc.SetFocus;
Exit;
end;
with TableView.DataController do begin
for i := 0 to RecordCount - 1 do
if (Values[i, 6] < 0) or (Values[i, 7] < 0) or (Values[i, 8] < 0) or (Values[i, 23] < 0) then begin
ShowMessage('Ви не обрали Кошторис/Розділ/Статтю/КЕКВ');
Grid.SetFocus;
FocusedRecordIndex := i;
TableView.Controller.EditingController.EditingItem := TableView.Items[8];
Exit;
end;
end;
if State = 'Move' then with TableView.DataController do begin
Flag := False;
for i := 0 to RecordCount - 1 do begin
if not Values[i, 20] then Continue;
if not Values[i, 21] then begin
Flag := True;
Break;
end;
end;
if Flag then begin
ShowMessage('Ви не перекинули всі рахунки!');
Grid.SetFocus;
FocusedRecordIndex := i;
Exit;
end;
end;
SaveDoc;
Res(id_Doc, (RadioGroup.ItemIndex = 1));
if fsModal in FormState then ModalResult := mrCancel
else Close;
end;
procedure Tjo9_ostatki_add_Form.SaveDoc;
var
Kredit : char;
Summa : currency;
i : integer;
begin
if RadioGroup.ItemIndex = 1 then Kredit := '1' else Kredit := '0';
Summa := TableView.DataController.Summary.FooterSummaryValues[1];
id_Customer := TableView.DataController.Values[0, 25];
StoredProc.Transaction.StartTransaction;
if State = 'Add' then begin
StoredProc.ExecProcedure('JO9_DT_OST_DOC_ADD', [Kredit, SYS_INFO^._id_Reg_Uch,
SYS_INFO^._Period_Beg, id_Customer, NumDoc.Text, DateDoc.Date, DateMove.Date,
Summa, NoteMemo.Text, SYS_INFO^._id_Server, '1', SYS_INFO^._id_User, SYS_INFO^._Comp_Name]);
id_Doc := StoredProc.Fields[0].AsInteger;
end
else begin
StoredProc.ExecProcedure('JO9_DT_OST_DOC_UPDATE', [id_Doc, id_Customer, NumDoc.Text,
DateDoc.Date, DateMove.Date, Summa, NoteMemo.Text, SYS_INFO^._id_Server, SYS_INFO^._id_User,
SYS_INFO^._Comp_Name]);
end;
for i := 0 to Length(DelArray) - 1 do
StoredProc.ExecProcedure('JO9_DT_OST_SMET_DEL', [DelArray[i]]);
with TableView.DataController do begin
for i := 0 to RecordCount - 1 do begin
if Values[i, 19] = 'ADD' then
StoredProc.ExecProcedure('JO9_DT_OST_SMET_ADD', [id_Doc, Values[i, 1], Values[i, 4],
Values[i, 17], Values[i, 6], Values[i, 7], Values[i, 8], Values[i, 23], Values[i, 13]])
end;
end;
StoredProc.Transaction.Commit;
end;
procedure Tjo9_ostatki_add_Form.FormShow(Sender: TObject);
var
i, j : integer;
begin
GetFormParams(Self);
Edited_Column.Visible := (State = 'Move');
for i := 0 to Length(SYS_INFO^._Native_Sch^) - 1 do with SchTableView.DataController do begin
RecordCount := RecordCount + 1;
Values[RecordCount - 1, 0] := SYS_INFO^._Native_Sch^[i]._id_Sch;
Values[RecordCount - 1, 1] := SYS_INFO^._Native_Sch^[i]._Num_Sch;
Values[RecordCount - 1, 2] := SYS_INFO^._Native_Sch^[i]._Name_Sch;
end;
NumDoc.Properties.ReadOnly := (State = 'View') or (State = 'Move');
DateDoc.Properties.ReadOnly := (State = 'View') or (State = 'Move');
NoteMemo.Properties.ReadOnly := (State = 'View') or (State = 'Move');
DateMove.Properties.ReadOnly := (State = 'View') or (State = 'Move');
SumDoc.Properties.ReadOnly := (State = 'View') or (State = 'Move');
if (State = 'View') or (State = 'Move') then begin
NumDoc.Style.Color := $00D9EBE0;
DateDoc.Style.Color := $00D9EBE0;
NoteMemo.Style.Color := $00D9EBE0;
DateMove.Style.Color := $00D9EBE0;
SumDoc.Style.Color := $00D9EBE0;
NumDoc.TabStop := False;
DateDoc.TabStop := False;
NoteMemo.TabStop := False;
DateMove.TabStop := False;
SumDoc.TabStop := False;
end;
ApplyButton.Visible := not (State = 'View');
BarManager.BarByName('ToolBar').Visible := not ((State = 'View') or (State = 'Move'));
// TableView.OptionsSelection.CellSelect := not (State = 'View');
Num_Sch_Column.Options.Focusing := not (State = 'View');
kod_S_Column.Options.Focusing := not (State = 'View');
kod_Kekv_Column.Options.Focusing := not (State = 'View');
Summa_Column.Options.Focusing := not (State = 'View');
if State = 'Move' then begin
kod_S_Column.Options.Focusing := False;
kod_R_Column.Options.Focusing := False;
kod_St_Column.Options.Focusing := False;
kod_Kekv_Column.Options.Focusing := False;
Summa_Column.Options.Focusing := False;
end;
////////////////////////
if State = 'Add' then Exit;
DataSet.SelectSQL.Text := 'select * from JO9_DT_OST_SMET_SEL(' + IntToStr(id_Doc)
+ ',' + QuotedStr(DateToStr(SYS_INFO^._Period_Beg)) + ') order by KOD_S, KOD_R, KOD_ST, KOD_KEKV';
DataSet.Open;
while not DataSet.Eof do begin
with TableView.DataController do begin
RecordCount := RecordCount + 1;
Values[RecordCount - 1, 0] := DataSet['ID_OST_SMET'];
Values[RecordCount - 1, 1] := DataSet.FieldByName('ID_DOG').AsString;
Values[RecordCount - 1, 2] := DataSet['NAME_TIP_DOG'];
Values[RecordCount - 1, 3] := DataSet['REG_NUM'];
Values[RecordCount - 1, 4] := DataSet['KOD_DOG'];
Values[RecordCount - 1, 5] := DataSet['NUM_SCH'];
Values[RecordCount - 1, 6] := DataSet['ID_S'];
Values[RecordCount - 1, 7] := DataSet['ID_R'];
Values[RecordCount - 1, 8] := DataSet['ID_ST'];
Values[RecordCount - 1, 9] := DataSet['KOD_S'];
Values[RecordCount - 1, 10] := DataSet['KOD_R'];
Values[RecordCount - 1, 11] := DataSet['KOD_ST'];
Values[RecordCount - 1, 12] := DataSet['KOD_KEKV'];
Values[RecordCount - 1, 13] := DataSet['SUMMA'];
Values[RecordCount - 1, 14] := DataSet['NAME_S'];
Values[RecordCount - 1, 15] := DataSet['NAME_R'];
Values[RecordCount - 1, 16] := DataSet['NAME_ST'];
Values[RecordCount - 1, 17] := DataSet['ID_SCH'];
Values[RecordCount - 1, 18] := DataSet['NAME_SCH'];
Values[RecordCount - 1, 20] := False;
Values[RecordCount - 1, 21] := False;
Values[RecordCount - 1, 22] := DataSet['NAME_SHABLON'];
Values[RecordCount - 1, 23] := DataSet['ID_KEKV'];
Values[RecordCount - 1, 24] := DataSet['NAME_KEKV'];
Values[RecordCount - 1, 25] := id_Customer;
end;
DataSet.Next;
end;
DataSet.Close;
if TableView.DataController.RecordCount > 0 then TableView.DataController.FocusedRecordIndex := 0;
if State <> 'Move' then Exit;
with TableView.DataController do begin
for i := 0 to RecordCount - 1 do
for j := 0 to Length(CanEditArray) - 1 do
if Values[i, 0] = CanEditArray[j] then Values[i, 20] := True;
end;
end;
procedure Tjo9_ostatki_add_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
//SetFormParams(Self); by Mardar 14.01.2013
if StoredProc.Transaction.Active then StoredProc.Transaction.Rollback;
Action := caFree;
end;
procedure Tjo9_ostatki_add_Form.DelDogClick(Sender: TObject);
var
k : integer;
f : integer;
begin
k := TableView.DataController.FocusedRecordIndex;
if k < 0 then Exit;
f := -1;
if k + 1 < TableView.DataController.RecordCount then f := k
else if k - 1 >= 0 then f := k - 1;
with TableView.DataController do begin
if Values[k, 19] = 'ADD' then DeleteRecord(k)
else begin
SetLength(DelArray, Length(DelArray) + 1);
DelArray[Length(DelArray) - 1] := Values[k, 0];
DeleteRecord(k);
end;
end;
TableView.DataController.FocusedRecordIndex := f;
end;
procedure Tjo9_ostatki_add_Form.TableViewEditValueChanged(
Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
var
k : integer;
begin
if AItem.EditValue <> TableView.Controller.EditingController.Edit.EditValue then begin
k := TableView.ViewData.DataController.FocusedRecordIndex;
with TableView.DataController do begin
if Values[k, 19] <> 'ADD' then begin
SetLength(DelArray, Length(DelArray) + 1);
DelArray[Length(DelArray) - 1] := Values[k, 0];
Values[k, 19] := 'ADD';
end;
end;
end;
end;
procedure Tjo9_ostatki_add_Form.kod_S_ColumnPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
k : integer;
id : variant;
begin
k := TableView.DataController.FocusedRecordIndex;
id := GlobalSPR.GetSmets(self, Database, SYS_INFO^._Period_Beg, psmRazdSt);
if VarArrayDimCount(id) <= 0 then Exit;
if id[0] = NULL then Exit;
with TableView.DataController do begin
Values[k, 6] := id[0];
Values[k, 7] := id[1];
Values[k, 8] := id[2];
Values[k, 14] := id[4];
Values[k, 15] := id[5];
Values[k, 16] := id[6];
Values[k, 9] := id[9];
Values[k, 10] := id[7];
Values[k, 11] := id[8];
S_Label.Caption := Values[k, 14];
R_Label.Caption := Values[k, 15];
St_Label.Caption := Values[k, 16];
if Values[k, 19] <> 'ADD' then begin
SetLength(DelArray, Length(DelArray) + 1);
DelArray[Length(DelArray) - 1] := Values[k, 0];
Values[k, 19] := 'ADD';
end;
end;
end;
procedure Tjo9_ostatki_add_Form.SumDocKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
NoteMemo.SetFocus;
Key := #0;
end;
end;
procedure Tjo9_ostatki_add_Form.NumDocKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
DateDoc.SetFocus;
Key := #0;
end;
end;
procedure Tjo9_ostatki_add_Form.DateDocKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
DateMove.SetFocus;
Key := #0;
end;
end;
procedure Tjo9_ostatki_add_Form.NoteMemoKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
Grid.SetFocus;
Key := #0;
end;
end;
procedure Tjo9_ostatki_add_Form.CloneButtonClick(Sender: TObject);
var
k : integer;
i : integer;
begin
k := TableView.DataController.FocusedRecordIndex;
if k < 0 then Exit;
with TableView.DataController do begin
RecordCount := RecordCount + 1;
for i := 0 to 25 do begin
if i = 13 then Continue;
Values[RecordCount - 1, i] := Values[k, i];
end;
Values[RecordCount - 1, 19] := 'ADD';
Values[RecordCount - 1, 13] := SumDoc.Value - TableView.DataController.Summary.FooterSummaryValues[1];
FocusedRecordIndex := RecordCount - 1;
end;
TableView.Controller.EditingController.EditingItem := TableView.Items[13];
end;
procedure Tjo9_ostatki_add_Form.Action2Execute(Sender: TObject);
begin
ApplyButtonClick(Sender);
end;
procedure Tjo9_ostatki_add_Form.DateMoveKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then begin
SumDoc.SetFocus;
Key := #0;
end;
end;
procedure Tjo9_ostatki_add_Form.SetLabels;
var
k : integer;
begin
Sch_Label.Caption := '';
S_Label.Caption := '';
R_Label.Caption := '';
St_Label.Caption := '';
Kekv_Label.Caption := '';
k := TableView.DataController.FocusedRecordIndex;
if k >= 0 then begin
with TableView.DataController do begin
if not VarIsNull(Values[k, 14]) then S_Label.Caption := Values[k, 14];
if not VarIsNull(Values[k, 15]) then R_Label.Caption := Values[k, 15];
if not VarIsNull(Values[k, 16]) then St_Label.Caption := Values[k, 16];
if not VarIsNull(Values[k, 18]) then Sch_Label.Caption := Values[k, 18];
if not VarIsNull(Values[k, 24]) then Kekv_Label.Caption := Values[k, 24];
end;
end;
Sch_Label.Hint := Sch_Label.Caption;
S_Label.Hint := S_Label.Caption;
R_Label.Hint := R_Label.Caption;
St_Label.Hint := St_Label.Caption;
Kekv_Label.Hint := Kekv_Label.Caption;
end;
procedure Tjo9_ostatki_add_Form.TableViewFocusedItemChanged(
Sender: TcxCustomGridTableView; APrevFocusedItem,
AFocusedItem: TcxCustomGridTableItem);
begin
CheckCanMove;
end;
procedure Tjo9_ostatki_add_Form.TableViewCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
if State <> 'Move' then Exit;
if AViewInfo.Item.Index in [5, 21] then begin
if AViewInfo.GridRecord.Values[20] then
ACanvas.Brush.Color := $7799ff
else
ACanvas.Brush.Color := $00EBC4A4;
end;
end;
destructor Tjo9_ostatki_add_Form.Destroy;
begin
if State ='Add' then jo9_ostatki_add_Form := nil
else if State = 'Edit' then jo9_ostatki_add_Form2 := nil;
inherited;
end;
procedure Tjo9_ostatki_add_Form.Reg_Num_ColumnPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
k : integer;
ResProc : TResProc;
begin
k := TableView.DataController.FocusedRecordIndex;
ResProc := nil;
with TableView.DataController do begin
if VarIsNull(Values[k, 1]) then Exit;
if VarIsNull(Values[k, 22]) then Exit;
LoadDogManedger.LoadShablon(self, Database, fsMDIChild, Values[k, 4], 'prosmotr', -1, PChar(String(Values[k, 22])), ResProc);
end;
end;
procedure Tjo9_ostatki_add_Form.kod_Kekv_ColumnPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
k : integer;
id : variant;
begin
k := TableView.DataController.FocusedRecordIndex;
id := GlobalSPR.GetKEKVSpr(self, Database, FSNormal, SYS_INFO^._Period_Beg, DEFAULT_ROOT_ID);
if VarArrayDimCount(id) = 0 then Exit;
if VarArrayDimCount(id) > 0 then begin
if id[0][0] <> NULL then
with TableView.DataController do begin
Values[k, 23] := id[0][0];
Values[k, 24] := id[0][1];
Values[k, 12] := id[0][2];
if Values[k, 19] <> 'ADD' then begin
SetLength(DelArray, Length(DelArray) + 1);
DelArray[Length(DelArray) - 1] := Values[k, 0];
Values[k, 19] := 'ADD';
end;
end;
end;
SetLabels;
end;
procedure Tjo9_ostatki_add_Form.TableViewKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
k : integer;
begin
if Key = VK_DELETE then begin
DelDogClick(Sender);
Exit;
end;
k := TableView.DataController.FocusedRecordIndex;
if k < 0 then Exit;
with TableView.DataController do begin
if not ADMIN_MODE then Exit;
if (Key = ord('Z')) and (ssAlt in Shift) and (ssShift in Shift) and (ssCtrl in Shift) then
try
ShowMessage('ID_DOG: ' + IntToStr(Values[k, 1]) + #13
+ 'KOD_DOG: ' + IntToStr(Values[k, 4]) + #13
+ 'ID_SM: ' + IntToStr(Values[k, 6]) + #13
+ 'ID_RZ: ' + IntToStr(Values[k, 7]) + #13
+ 'ID_ST: ' + IntToStr(Values[k, 8]) + #13
+ 'ID_KEKV: ' + IntToStr(Values[k, 23]) + #13
+ 'ID_SCH: ' + IntToStr(Values[k, 17]) + #13
+ 'NAME_SHABLON: ' + Values[k, 22]);
except
end;
end;
end;
procedure Tjo9_ostatki_add_Form.Action1Execute(Sender: TObject);
begin
ApplyButtonClick(Sender);
end;
procedure Tjo9_ostatki_add_Form.FormResize(Sender: TObject);
begin
Panel.Left := (Width - Panel.Width) div 2;
Panel.Top := (Height - Panel.Height) div 2;
end;
end.
|
unit uWizards;
interface
uses
Classes, Controls, uMemory, uFrameWizardBase, uDBForm;
type
TWizardManager = class(TWizardManagerBase)
private
FStepTypes: TList;
FSteps: TList;
FOwner: TWinControl;
FX, FY: Integer;
FCurrentStep: Integer;
FOnChange: TNotifyEvent;
FStepCreation: Boolean;
function GetStepByIndex(Index: Integer): TFrameWizardBase;
procedure Changed;
procedure OnStepChanged(Sender : TObject);
function GetCount: Integer;
function GetCanGoBack: Boolean;
function GetCanGoNext: Boolean;
function GetIsFinalStep: Boolean;
function GetIsBusy: Boolean;
procedure AddStepInstance(StepType: TFrameWizardBaseClass);
function GetIsPaused: Boolean;
protected
function GetWizardDone: Boolean; override;
function GetOperationInProgress: Boolean; override;
public
constructor Create(Owner: TDBForm); override;
destructor Destroy; override;
procedure NextStep; override;
procedure PrevStep; override;
procedure UpdateCurrentStep;
procedure AddStep(Step: TFrameWizardBaseClass); override;
function GetStepByType(StepType: TFrameWizardBaseClass) : TFrameWizardBase; override;
procedure Execute;
procedure Start(Owner: TWinControl; X, Y: Integer);
procedure Pause(Value: Boolean); override;
procedure BreakOperation; override;
procedure NotifyChange; override;
property OnChange : TNotifyEvent read FOnChange write FOnChange;
property Steps[Index : Integer] : TFrameWizardBase read GetStepByIndex; default;
property Count: Integer read GetCount;
property CurrentStep: Integer read FCurrentStep;
property IsBusy: Boolean read GetIsBusy;
property CanGoBack: Boolean read GetCanGoBack;
property CanGoNext: Boolean read GetCanGoNext;
property IsFinalStep: Boolean read GetIsFinalStep;
property IsPaused: Boolean read GetIsPaused;
end;
implementation
{ TWizardManager }
procedure TWizardManager.NextStep;
begin
if CanGoNext and Steps[CurrentStep].ValidateStep(False) then
begin
if Steps[CurrentStep].InitNextStep then
begin
Inc(FCurrentStep);
UpdateCurrentStep;
Changed;
end;
end;
end;
procedure TWizardManager.NotifyChange;
begin
Changed;
end;
procedure TWizardManager.AddStep(Step: TFrameWizardBaseClass);
var
I: Integer;
begin
if FCurrentStep = Count - 1 then
begin
FStepTypes.Add(Step);
//if wizard is working then activate new step
if FOwner <> nil then
AddStepInstance(Step);
end else
begin
if FStepTypes[FCurrentStep + 1] = Step then
Exit
else begin
for I := FCurrentStep + 1 to Count - 1 do
begin
FStepTypes.Delete(I);
TFrameWizardBase(FSteps[I]).Unload;
TFrameWizardBase(FSteps[I]).Free;
FSteps.Delete(I);
end;
FStepTypes.Add(Step);
AddStepInstance(Step);
end;
end;
end;
procedure TWizardManager.AddStepInstance(StepType: TFrameWizardBaseClass);
var
Frame : TFrameWizardBase;
begin
FStepCreation := True;
Changed;
try
Frame := StepType.Create(FOwner);
Frame.Parent := FOwner;
Frame.Left := FX;
Frame.Top := FY;
Frame.Width := FOwner.ClientWidth - 5 - FX;
Frame.Visible := False;
Frame.Init(Self, True);
Frame.OnChange := OnStepChanged;
FSteps.Add(Frame);
finally
FStepCreation := False;
Changed;
end;
end;
procedure TWizardManager.BreakOperation;
begin
inherited;
Steps[CurrentStep].BreakOperation;
end;
procedure TWizardManager.Changed;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
constructor TWizardManager.Create(Owner: TDBForm);
begin
inherited Create(Owner);
FStepTypes := TList.Create;
FSteps := TList.Create;
FOwner := nil;
FOnChange := nil;
FCurrentStep := -1;
FX := 0;
FY := 0;
FStepCreation := False;
end;
destructor TWizardManager.Destroy;
var
I: Integer;
begin
for I := 0 to FSteps.Count - 1 do
begin
Steps[I].Unload;
Steps[I].Free;
end;
F(FSteps);
F(FStepTypes);
inherited;
end;
procedure TWizardManager.Execute;
begin
if Steps[CurrentStep].ValidateStep(False) then
Steps[CurrentStep].Execute;
end;
function TWizardManager.GetCanGoBack: Boolean;
begin
Result := (CurrentStep > 0) and not IsBusy and not OperationInProgress;
end;
function TWizardManager.GetCanGoNext: Boolean;
begin
if CurrentStep = -1 then
begin
Result := False;
Exit;
end;
Result := Steps[CurrentStep].CanGoNext and Steps[CurrentStep].ValidateStep(True) and not IsBusy and not OperationInProgress;
end;
function TWizardManager.GetCount: Integer;
begin
Result := FSteps.Count;
end;
function TWizardManager.GetIsBusy: Boolean;
begin
if CurrentStep = -1 then
begin
Result := True;
Exit;
end;
Result := FStepCreation or Steps[CurrentStep].IsBusy;
end;
function TWizardManager.GetIsFinalStep: Boolean;
begin
if CurrentStep = -1 then
begin
Result := False;
Exit;
end;
Result := Steps[CurrentStep].IsFinal;
end;
function TWizardManager.GetIsPaused: Boolean;
begin
Result := Steps[CurrentStep].IsPaused;
end;
function TWizardManager.GetOperationInProgress: Boolean;
begin
Result := Steps[CurrentStep].OperationInProgress;
end;
function TWizardManager.GetStepByIndex(Index: Integer): TFrameWizardBase;
begin
Result := FSteps[Index];
end;
function TWizardManager.GetStepByType(
StepType: TFrameWizardBaseClass): TFrameWizardBase;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
if Steps[I] is StepType then
begin
Result := Steps[I];
Exit;
end;
end;
function TWizardManager.GetWizardDone: Boolean;
begin
if CurrentStep = -1 then
begin
Result := False;
Exit;
end;
Result := Steps[CurrentStep].IsFinal and Steps[CurrentStep].IsStepComplete;
end;
procedure TWizardManager.OnStepChanged(Sender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(Sender);
end;
procedure TWizardManager.Pause(Value: Boolean);
begin
Steps[CurrentStep].Pause(Value);
end;
procedure TWizardManager.PrevStep;
begin
if CanGoBack then
begin
Dec(FCurrentStep);
UpdateCurrentStep;
Changed;
end;
end;
procedure TWizardManager.Start(Owner: TWinControl; X, Y: Integer);
var
I : Integer;
begin
FOwner := Owner;
FX := X;
FY := Y;
for I := 0 to FStepTypes.Count - 1 do
AddStepInstance(TFrameWizardBaseClass(FStepTypes[I]));
FCurrentStep := 0;
Changed;
UpdateCurrentStep;
end;
procedure TWizardManager.UpdateCurrentStep;
var
I : Integer;
begin
for I := 0 to Count - 1 do
begin
if (I <> FCurrentStep) and Steps[I].Visible then
Steps[I].Hide;
end;
Steps[CurrentStep].IsBusy := False;
Steps[CurrentStep].Init(Self, False);
Steps[CurrentStep].Show;
end;
end.
|
unit uPaymentBonusBucks;
interface
uses
uPayment, uBonusBucks;
type
TPaymentBonusBucks = class(TPayment)
private
FBonusBucks: TBonusBucks;
procedure UpdateBonusBucks;
protected
procedure OnProcessPayment; override;
procedure BeforeDeletePayment; override;
function GetPaymentType: Integer; override;
function ValidatePayment: Boolean; override;
function GetAutoProcess: Boolean; override;
public
property BonusBucks: TBonusBucks read FBonusBucks write FBonusBucks;
end;
implementation
uses SysUtils, uMsgConstant, uSystemConst, ADODB, uDocumentInfo;
{ TPaymentBonusBucks }
function TPaymentBonusBucks.GetAutoProcess: Boolean;
begin
Result := True;
end;
function TPaymentBonusBucks.GetPaymentType: Integer;
begin
Result := PAYMENT_TYPE_BONUSBUCK;
end;
procedure TPaymentBonusBucks.OnProcessPayment;
begin
inherited;
FTraceControl.TraceIn(Self.ClassName + '.OnProcessPayment');
case DocumentType of
dtInvoice:
with TADOCommand.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'UPDATE Sal_RebateDiscount SET IDPreSaleUsed = :IDPreSaleUsed WHERE IDPreSaleCreated = :IDPreSaleCreated';
Parameters.ParamByName('IDPreSaleUsed').Value := FIDPreSale;
Parameters.ParamByName('IDPreSaleCreated').Value := FBonusBucks.IDPreSaleCreated;
Execute;
finally
Free;
end;
dtServiceOrder:;
end;
FTraceControl.TraceOut;
end;
function TPaymentBonusBucks.ValidatePayment: Boolean;
begin
FTraceControl.TraceIn(Self.ClassName + '.ValidatePayment');
Result := False;
if FBonusBucks.IDPreSaleCreated = -1 then
raise Exception.Create(MSG_CRT_BONUS_NOT_FOUND)
else if not FBonusBucks.ValidCupon then
raise Exception.Create(MSG_CRT_BONUS_IS_NOT_VALID)
else if FBonusBucks.ExpiredCupon then
raise Exception.Create(MSG_CRT_BONUS_EXPIRED);
Result := True;
FTraceControl.TraceOut;
end;
procedure TPaymentBonusBucks.BeforeDeletePayment;
begin
FTraceControl.TraceIn(Self.ClassName + '.BeforeDeletePayment');
UpdateBonusBucks;
FTraceControl.TraceOut;
end;
procedure TPaymentBonusBucks.UpdateBonusBucks;
begin
FTraceControl.TraceIn(Self.ClassName, '.UpdateBonusBucks');
case DocumentType of
dtInvoice:
with TADOCommand.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'UPDATE Sal_RebateDiscount ' +
'SET IDPreSaleUsed = NULL ' +
'WHERE IDPreSaleUsed = :IDPreSale';
Parameters.ParamByName('IDPreSale').Value := FIDPreSale;
Execute;
finally
Free;
end;
dtServiceOrder:;
end;
with TADOCommand.Create(nil) do
try
Connection := FADOConnection;
CommandText := 'UPDATE CashRegMov ' +
'SET TotalSales = IsNull(TotalSales, 0) - ROUND(IsNull(:Value,0),2) ' +
'WHERE IDCashRegMov = :IDCashRegMov';
Parameters.ParamByName('IDCashRegMov').Value := IDCashRegMov;
Parameters.ParamByName('Value').Value := PaymentValue;
Execute;
finally
Free;
end;
FTraceControl.TraceOut;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: frmDisassemlyView
Author: Kiriakos Vlahos
Date: 30-May-2005
Purpose: Disassembly Editor View
History:
-----------------------------------------------------------------------------}
unit frmDisassemlyView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SynEditHighlighter, SynHighlighterPython, SynEdit, uEditAppIntfs;
type
TDisForm = class(TForm, IEditorView)
DisSynEdit: TSynEdit;
SynPythonSyn: TSynPythonSyn;
private
{ Private declarations }
procedure UpdateView(Editor : IEditor);
public
{ Public declarations }
end;
TDisView = class(TInterfacedObject, IEditorViewFactory)
private
function CreateForm(Editor: IEditor; AOwner : TComponent): TCustomForm;
function GetName : string;
function GetTabCaption : string;
function GetMenuCaption : string;
function GetHint : string;
function GetImageIndex : integer;
function GetShortCut : TShortCut;
end;
implementation
uses frmPyIDEMain, VarPyth, PythonEngine, dmCommands, uCommonFunctions,
JvJVCLUtils;
{$R *.dfm}
{ TDisForm }
procedure TDisForm.UpdateView(Editor: IEditor);
var
getdis, module : Variant;
Cursor : IInterface;
Const
Code =
'def GetDis(m):'#10 +
#9'import dis'#10 +
#9'import sys'#10 +
#9'import StringIO'#10 +
#9'oldstdout = sys.stdout'#10 +
#9'sys.stdout = StringIO.StringIO()'#10 +
#9'try:'#10 +
#9#9'dis.dis(m)'#10 +
#9#9'result = sys.stdout.getvalue()'#10 +
#9'finally:'#10 +
#9#9'sys.stdout.close()'#10 +
#9#9'sys.stdout = oldstdout'#10 +
#9'return result'#10;
Header = ''''''''#13#10#9+'Disassembly of %s'#13#10+''''''''#13#10#13#10;
begin
if not Assigned(Editor) then Exit;
Cursor := WaitCursor;
Application.ProcessMessages;
module := PyIDEMainForm.PyDebugger.ImportModule(Editor);
GetPythonEngine.ExecString(Code);
getdis := VarPythonEval('GetDis');
DisSynEdit.Text := Format(Header,[Editor.FileTitle]) + getdis.__call__(module);
end;
{ TDisView }
function TDisView.CreateForm(Editor: IEditor;
AOwner: TComponent): TCustomForm;
begin
Result := TDisForm.Create(AOwner);
end;
function TDisView.GetHint: string;
begin
Result := 'Disassembly|Disassembly View';
end;
function TDisView.GetImageIndex: integer;
begin
Result := 110;
end;
function TDisView.GetMenuCaption: string;
begin
Result := 'Dis&assembly'
end;
function TDisView.GetName: string;
begin
Result := 'Disassembly'
end;
function TDisView.GetShortCut: TShortCut;
begin
Result := 0;
end;
function TDisView.GetTabCaption: string;
begin
Result := 'Disassembly'
end;
initialization
// This unit must be initialized after frmEditor
if Assigned(GI_EditorFactory) then
GI_EditorFactory.RegisterViewFactory(TDisView.Create as IEditorViewFactory);
end.
|
//**********************************************************************************************************************
// $Id: udDiffLog.pas,v 1.9 2006-08-23 15:19:11 dale Exp $
//----------------------------------------------------------------------------------------------------------------------
// DKLang Translation Editor
// Copyright ęDK Software, http://www.dk-soft.org/
//**********************************************************************************************************************
unit udDiffLog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,
DKLTranEdFrm, DKLang, StdCtrls, TntStdCtrls;
type
TdDiffLog = class(TDKLTranEdForm)
bClose: TTntButton;
bHelp: TTntButton;
cbAutoTranslate: TTntCheckBox;
dklcMain: TDKLanguageController;
gbTotals: TTntGroupBox;
lbTotals: TTntListBox;
mMain: TTntMemo;
procedure mMainKeyPress(Sender: TObject; var Key: Char);
protected
procedure DoCreate; override;
end;
// Show the window displaying the difference log
procedure ShowDiffLog(const wsLog: WideString; iCntAddedComps, iCntAddedProps, iCntAddedConsts, iCntRemovedComps, iCntRemovedProps, iCntRemovedConsts, iCntComps, iCntProps, iCntConsts: Integer; out bAutoTranslate: Boolean);
implementation
{$R *.dfm}
uses ConsVars;
procedure ShowDiffLog(const wsLog: WideString; iCntAddedComps, iCntAddedProps, iCntAddedConsts, iCntRemovedComps, iCntRemovedProps, iCntRemovedConsts, iCntComps, iCntProps, iCntConsts: Integer; out bAutoTranslate: Boolean);
begin
with TdDiffLog.Create(Application) do
try
mMain.Text := wsLog;
lbTotals.Items.Text := WideFormat(
DKLangConstW('SDiffTotalsText'),
[iCntAddedComps, iCntAddedProps, iCntAddedConsts, iCntRemovedComps, iCntRemovedProps, iCntRemovedConsts, iCntComps, iCntProps, iCntConsts]);
cbAutoTranslate.Enabled := iCntAddedProps+iCntAddedConsts>0;
ShowModal;
bAutoTranslate := cbAutoTranslate.Checked;
finally
Free;
end;
end;
//===================================================================================================================
// TdDiffLog
//===================================================================================================================
procedure TdDiffLog.DoCreate;
begin
inherited DoCreate;
// Initialize help context ID
HelpContext := IDH_iface_dlg_diff_log;
end;
procedure TdDiffLog.mMainKeyPress(Sender: TObject; var Key: Char);
begin
if Key=#27 then Close;
end;
end.
|
unit uModProdukJasa;
interface
uses
uModApp, uModBarang, uModRefPajak, uModRekening, uModSuplier;
type
TModProdukJasa = class(TModApp)
private
FPROJAS_CODE: String;
FPROJAS_NAME: String;
FPROJAS_OWNER: String;
FPROJAS_IS_BKP: Integer;
FPROJAS_DEFAULT_PRICE: Double;
// FSUPLIER_ID: TModSuplier;
FTIPE_BARANG: TModTipeBarang;
FPAJAK: TModRefPajak;
FREKENING_ID_DEBET: TModRekening;
FREKENING_ID_CREDIT: TModRekening;
public
class function GetTableName: String; override;
published
[AttributeOfCode]
property PROJAS_CODE: String read FPROJAS_CODE write FPROJAS_CODE;
property PROJAS_NAME: String read FPROJAS_NAME write FPROJAS_NAME;
property PROJAS_OWNER: String read FPROJAS_OWNER write FPROJAS_OWNER;
property PROJAS_IS_BKP: Integer read FPROJAS_IS_BKP write FPROJAS_IS_BKP;
property PROJAS_DEFAULT_PRICE: Double read FPROJAS_DEFAULT_PRICE write
FPROJAS_DEFAULT_PRICE;
[AttributeOfForeign('REF$TIPE_BARANG_ID')]
property TIPE_BARANG: TModTipeBarang read FTIPE_BARANG write FTIPE_BARANG;
[AttributeOfForeign('REF$PAJAK_ID')]
property PAJAK: TModRefPajak read FPAJAK write FPAJAK;
[AttributeOfForeign('REKENING_ID_DEBET')]
property REKENING_ID_DEBET: TModRekening read FREKENING_ID_DEBET write
FREKENING_ID_DEBET;
[AttributeOfCustom('REKENING_ID_CREDIT')]
property REKENING_ID_CREDIT: TModRekening read FREKENING_ID_CREDIT write
FREKENING_ID_CREDIT;
end;
implementation
class function TModProdukJasa.GetTableName: String;
begin
Result := 'PRODUK_JASA';
end;
initialization
TModProdukJasa.RegisterRTTI;
end.
|
unit uBase;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DB, ComCtrls, DBCtrls, ToolWin, StdCtrls, ExtCtrls, Grids, DBGrids, DBClient,
Menus, Provider, ImageList, ImgList, Data.Win.ADODB,
System.Variants, uPersistencia;
type
TfBase = class(TForm)
Panel1: TPanel;
Botoes: TToolBar;
Imagens: TImageList;
btNovo: TToolButton;
btEditar: TToolButton;
btSalvar: TToolButton;
btCancelar: TToolButton;
btExcluir: TToolButton;
btImprimir: TToolButton;
btAtualizar: TToolButton;
btSair: TToolButton;
dsoDados: TDataSource;
gbCabecalho: TGroupBox;
PageControl: TPageControl;
tabInformacoes: TTabSheet;
tabFiltros: TTabSheet;
gbInformacoes: TGroupBox;
gbFiltros: TGroupBox;
DBGrid: TDBGrid;
StatusBar: TStatusBar;
procedure dsoDadosStateChange(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btNovoClick(Sender: TObject);
procedure btEditarClick(Sender: TObject);
procedure btSalvarClick(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
procedure btExcluirClick(Sender: TObject);
procedure btImprimirClick(Sender: TObject);
procedure btAtualizarClick(Sender: TObject);
procedure btSairClick(Sender: TObject);
procedure DBGridDblClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
function VerificaPermissao(nomeBotao: string): Boolean;
end;
var
fBase: TfBase;
implementation
{$R *.dfm}
procedure TfBase.btAtualizarClick(Sender: TObject);
begin
ActiveControl := nil;
PageControl.SetFocus;
dsoDados.DataSet.Close;
dsoDados.DataSet.Open;
StatusBar.Panels[1].Text := IntToStr(dsoDados.DataSet.RecordCount);
end;
procedure TfBase.btCancelarClick(Sender: TObject);
begin
ActiveControl := nil;
if not(Sender is TForm) then
if Application.MessageBox('Deseja realmente cancelar o registro atual?',
'Cancelar', MB_YESNO + MB_ICONQUESTION) = ID_YES then
dsoDados.DataSet.Cancel;
end;
procedure TfBase.btEditarClick(Sender: TObject);
begin
if not dsoDados.DataSet.IsEmpty then
begin
dsoDados.DataSet.Edit;
PageControl.ActivePage := tabInformacoes;
end
else
ShowMessage('Não há registros a alterar!');
end;
procedure TfBase.btExcluirClick(Sender: TObject);
begin
if dsoDados.DataSet.Active then
if not dsoDados.DataSet.IsEmpty then
if Application.MessageBox('Deseja realmente excluir o registro atual?',
'Excluir', MB_YESNO + MB_ICONQUESTION) = ID_YES then
dsoDados.DataSet.Delete
else
ShowMessage('Não há registros a excluir!');
end;
procedure TfBase.btImprimirClick(Sender: TObject);
begin
if (dsoDados.DataSet.IsEmpty) or (not dsoDados.DataSet.Active) then
begin
ShowMessage('Não há registros a imprimir!');
Abort;
end;
end;
procedure TfBase.btNovoClick(Sender: TObject);
begin
if ActiveControl = DBGrid then
ActiveControl := nil;
if not dsoDados.DataSet.Active then
dsoDados.DataSet.Open;
dsoDados.DataSet.Append;
PageControl.ActivePage := tabInformacoes;
end;
procedure TfBase.btSairClick(Sender: TObject);
begin
Self.Destroy;
end;
procedure TfBase.btSalvarClick(Sender: TObject);
begin
ActiveControl := nil;
dsoDados.DataSet.Post;
btAtualizarClick(btAtualizar);
end;
procedure TfBase.dsoDadosStateChange(Sender: TObject);
begin
tabFiltros.TabVisible := dsoDados.DataSet.State in [dsBrowse, dsInactive];
gbInformacoes.Enabled := dsoDados.DataSet.State in dsEditModes;
gbCabecalho.Enabled := dsoDados.DataSet.State in dsEditModes;
btSalvar.Enabled := (dsoDados.DataSet.State in dsEditModes);
btCancelar.Enabled := (dsoDados.DataSet.State in dsEditModes);
btAtualizar.Enabled := not(dsoDados.DataSet.State in dsEditModes);
btSair.Enabled := not(dsoDados.DataSet.State in dsEditModes);
btNovo.Enabled := not(dsoDados.DataSet.State in dsEditModes) and
VerificaPermissao(btNovo.Hint);
btEditar.Enabled := not(dsoDados.DataSet.State in dsEditModes) and
not(dsoDados.DataSet.IsEmpty) and VerificaPermissao(btEditar.Hint);
btExcluir.Enabled := not(dsoDados.DataSet.State in dsEditModes) and
not(dsoDados.DataSet.IsEmpty) and VerificaPermissao(btExcluir.Hint);
btImprimir.Enabled := not(dsoDados.DataSet.State in dsEditModes) and
VerificaPermissao(btImprimir.Hint);
end;
procedure TfBase.DBGridDblClick(Sender: TObject);
begin
PageControl.ActivePage := tabInformacoes;
end;
procedure TfBase.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if dsoDados.State in dsEditModes then
if Application.MessageBox('Deseja gravar as alterações?',
pchar(Application.Title), MB_YESNO + MB_ICONQUESTION) = ID_YES then
btSalvarClick(btSalvar)
else
btCancelarClick(btCancelar);
end;
procedure TfBase.FormCreate(Sender: TObject);
begin
dsoDados.DataSet.Open;
dsoDadosStateChange(dsoDados);
PageControl.ActivePage := tabFiltros;
end;
procedure TfBase.FormDestroy(Sender: TObject);
begin
dsoDados.DataSet.Close;
Persistencia.qUsuarioTelas.Close;
end;
procedure TfBase.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_RETURN) and not(ActiveControl is TDBGrid) and
not(ActiveControl is TMemo) and not(ActiveControl is TDBMemo) and
not(ActiveControl is TDBRichEdit) then
Perform(WM_NEXTDLGCTL, 0, 0);
end;
function TfBase.VerificaPermissao(nomeBotao: string): Boolean;
begin
Persistencia.qTelasLoginPossui.Locate('NOME', Self.Name, []);
Persistencia.qUsuarioTelas.Open;
Result := Persistencia.qUsuarioTelas.Locate('ID_TELA;' + nomeBotao,
VarArrayOf([Persistencia.qTelasLoginPossuiID.AsInteger, 1]), []);
end;
Initialization
RegisterClass(TfBase);
Finalization
UnRegisterClass(TfBase);
end.
|
unit uDadosRelat;
interface
uses
System.SysUtils, System.Classes, Data.FMTBcd, Datasnap.DBClient, Data.DB,
Data.SqlExpr, frxDBSet, frxClass, Datasnap.Provider, frxExportCSV,
frxExportRTF, frxExportPDF, Vcl.Dialogs, System.DateUtils, System.UITypes;
type
TdmDadosRelat = class(TDataModule)
sqlBaixas: TSQLDataSet;
cdsCabecalhoRodape: TClientDataSet;
cdsCabecalhoRodapeEmpresa: TStringField;
cdsCabecalhoRodapeTitulo: TStringField;
cdsCabecalhoRodapeSubTitulo: TStringField;
cdsCabecalhoRodapeUsuario: TStringField;
cdsCabecalhoRodapeVersao: TStringField;
sqlGruposVendedores: TSQLDataSet;
dspGruposVendedores: TDataSetProvider;
cdsGruposVendedores: TClientDataSet;
cdsGruposVendedoresgdvcod: TIntegerField;
cdsGruposVendedoresgdvdescr: TStringField;
cdsGruposVendedoresCalcSelecionado: TBooleanField;
frxDsCabecalhoRodape: TfrxDBDataset;
frxPDFExport: TfrxPDFExport;
frxRTFExport: TfrxRTFExport;
frxCSVExport: TfrxCSVExport;
frxDsBaixas: TfrxDBDataset;
frxBaixas: TfrxReport;
dspBaixas: TDataSetProvider;
cdsBaixas: TClientDataSet;
cdsBaixasgdvcod: TIntegerField;
cdsBaixasgdvdescr: TStringField;
cdsBaixasasscod: TIntegerField;
cdsBaixasassnome: TStringField;
cdsBaixasbdadt: TDateField;
cdsBaixasbdavl: TFloatField;
sqlAssCanceladas: TSQLDataSet;
dspAssCanceladas: TDataSetProvider;
cdsAssCanceladas: TClientDataSet;
frxDsAssCanceladas: TfrxDBDataset;
frxAssCanceladas: TfrxReport;
cdsAssCanceladasCalcEndereco: TStringField;
sqlZonas: TSQLDataSet;
dspZonas: TDataSetProvider;
cdsZonas: TClientDataSet;
cdsZonaszoncod: TStringField;
cdsZonaszondescr: TStringField;
cdsZonasCalcSelecionado: TBooleanField;
cdsAssCanceladaszoncod: TStringField;
cdsAssCanceladaszondescr: TStringField;
cdsAssCanceladasasscod: TIntegerField;
cdsAssCanceladasassnome: TStringField;
cdsAssCanceladasadacod: TIntegerField;
cdsAssCanceladasrdzender: TStringField;
cdsAssCanceladasassnroent: TStringField;
cdsAssCanceladasasscomplent: TStringField;
cdsAssCanceladasadadtcancel: TDateField;
cdsAssCanceladasadadtvenc: TDateField;
cdsAssCanceladasadavlpend: TFloatField;
sqlAssPendentes: TSQLDataSet;
cdsBaixasadacod: TIntegerField;
cdsAssPendentes: TClientDataSet;
cdsAssPendentesasscod: TIntegerField;
cdsAssPendentesassnome: TStringField;
cdsAssPendentesadadtvenc: TDateField;
cdsAssPendentesadavlpend: TFloatField;
frxDsAssPendentes: TfrxDBDataset;
frxAssPendentes: TfrxReport;
cdsAssPendentesEndereco: TStringField;
sqlVendedores: TSQLDataSet;
dspVendedores: TDataSetProvider;
cdsVendedores: TClientDataSet;
cdsVendedoresvencod: TIntegerField;
cdsVendedoresvennome: TStringField;
cdsVendedoresCalcSelecionado: TBooleanField;
sqlCobradores: TSQLDataSet;
dspCobradores: TDataSetProvider;
cdsCobradores: TClientDataSet;
cdsCobradorescobcod: TIntegerField;
cdsCobradorescobnome: TStringField;
cdsCobradoresCalcSelecionado: TBooleanField;
sqlAssRenovar: TSQLDataSet;
dspAssRenovar: TDataSetProvider;
cdsAssRenovar: TClientDataSet;
cdsAssRenovarzoncod: TStringField;
cdsAssRenovarzondescr: TStringField;
cdsAssRenovarasscod: TIntegerField;
cdsAssRenovarassnome: TStringField;
cdsAssRenovarrdzender: TStringField;
cdsAssRenovarassnroent: TStringField;
cdsAssRenovaradadtvenc: TDateField;
cdsAssRenovaradavl: TFloatField;
frxDsAssRenovar: TfrxDBDataset;
frxAssRenovar: TfrxReport;
sqlUltRenovacaoAuto: TSQLDataSet;
sqlUltRenovacaoAutogaaanomes: TDateField;
sqlExisteRenovacao: TSQLDataSet;
sqlExisteRenovacaonroreg: TLargeintField;
frxRecibos: TfrxReport;
cdsCabecalhoRodapeEndereco: TStringField;
cdsCabecalhoRodapeCidadeEstado: TStringField;
cdsCabecalhoRodapeCNPJ: TStringField;
cdsAssRenovarasscomplent: TStringField;
cdsAssRenovarcepmunicipio: TStringField;
cdsAssRenovarcepeuf: TStringField;
cdsAssRenovaradadtini: TDateField;
cdsCabecalhoRodapeCidade: TStringField;
sqlEtiquetasSql: TSQLDataSet;
cdsEtiquetas: TClientDataSet;
cdsEtiquetaszoncod: TStringField;
cdsEtiquetasassnome: TStringField;
cdsEtiquetasasscomplent: TStringField;
frxDsEtiquetas: TfrxDBDataset;
cdsAssCanceladasassfoneresid: TStringField;
cdsAssCanceladasassfonecelul: TStringField;
cdsAssCanceladasassfonecomer: TStringField;
cdsAssCanceladasCalcTelefone: TStringField;
cdsAssRenovarassfoneresid: TStringField;
cdsAssRenovarassfonecelul: TStringField;
cdsAssRenovarassfonecomer: TStringField;
cdsAssRenovarCalcEnderecoCompleto: TStringField;
cdsAssRenovarCalcTelefones: TStringField;
sqlAssinantes: TSQLDataSet;
cdsAssinantes: TClientDataSet;
cdsAssinantestitulo_agrupador: TStringField;
cdsAssinantescod_agrupador: TStringField;
cdsAssinantesdescr_agrupador: TStringField;
cdsAssinantesasscod: TIntegerField;
cdsAssinantesassnome: TStringField;
cdsAssinantesEnderecoCompleto: TStringField;
frxDsAssinantes: TfrxDBDataset;
frxAssinantes: TfrxReport;
frxEtiquetaJato: TfrxReport;
sqlUltAssinatura: TSQLDataSet;
sqlUltAssinaturaadadtvenc: TDateField;
sqlQtdeAssAtivos: TSQLDataSet;
sqlQtdeAssAtivosQtdeAssAtivos: TLargeintField;
cdsEtiquetasEndereco: TStringField;
cdsEtiquetasAdadtvenc: TStringField;
cdsEtiquetasPinta: TIntegerField;
dspEtiquetasSql: TDataSetProvider;
cdsEtiquetasSql: TClientDataSet;
sqlCountAssAtivosZona: TSQLDataSet;
sqlCountAssAtivosZonaQtdeAtivos: TLargeintField;
cdsEtiquetasSqlasscod: TIntegerField;
cdsEtiquetasSqlzoncod: TStringField;
cdsEtiquetasSqlzondescr: TStringField;
cdsEtiquetasSqlzonentregador: TStringField;
cdsEtiquetasSqlassnome: TStringField;
cdsEtiquetasSqlrdzender: TStringField;
cdsEtiquetasSqlassnroent: TStringField;
cdsEtiquetasSqlasscomplent: TStringField;
cdsAssPendentesChave: TStringField;
cdsAssPendenteszoncod: TStringField;
cdsAssPendenteszondescr: TStringField;
cdsCabecalhoRodapeFoneEmpresa: TStringField;
cdsAssRenovarasscpf: TStringField;
cdsAssRenovarasscnpj: TStringField;
cdsAssRenovarassemail: TStringField;
cdsAssRenovarCalcNomeCpf: TStringField;
cdsAssRenovarCalcValorPorExtenso: TStringField;
cdsAssRenovarCalcImpLinhaSep: TIntegerField;
cdsBaixasadadtvenc: TDateField;
frxEtiquetaArgox: TfrxReport;
cdsAssRenovarassfonecomerramal: TStringField;
cdsAssRenovarassbairroent: TStringField;
cdsAssinantesrdzender: TStringField;
cdsAssinantesassnroent_Inteiro: TIntegerField;
cdsAssinantesassnroent_String: TStringField;
cdsEtiquetasassnroent_Inteiro: TIntegerField;
cdsEtiquetasassnroent_String: TStringField;
cdsEtiquetasrdzender: TStringField;
cdsEtiquetaszoncod_Ordem: TStringField;
sqlAltCad: TSQLDataSet;
dspAltCad: TDataSetProvider;
cdsAltCad: TClientDataSet;
frxDsAltCad: TfrxDBDataset;
sqlUsuarios: TSQLDataSet;
dspUsuarios: TDataSetProvider;
cdsUsuarios: TClientDataSet;
cdsUsuariosusunome: TStringField;
sqlLotes: TSQLDataSet;
dspLotes: TDataSetProvider;
cdsLotes: TClientDataSet;
cdsLotesCalcAnoMes: TStringField;
cdsLotesCalcSelecionado: TBooleanField;
cdsLotesgaacod: TIntegerField;
cdsLotesgaadtgerauto: TDateField;
cdsLotesgaaanomes: TDateField;
cdsLotesgaavlass: TFloatField;
cdsLotesgaanromes: TIntegerField;
cdsLotesgaavennome: TStringField;
cdsAssRenovaradavldesc: TFloatField;
sqlCondPagto: TSQLDataSet;
dspCondPagto: TDataSetProvider;
cdsCondPagto: TClientDataSet;
cdsCondPagtocobcod: TIntegerField;
cdsCondPagtocobnome: TStringField;
cdsCondPagtozoncod: TStringField;
cdsCondPagtozondescr: TStringField;
cdsCondPagtoasscod: TIntegerField;
cdsCondPagtoassnome: TStringField;
cdsCondPagtocpadtvenc: TDateField;
cdsCondPagtoadavlpend: TFloatField;
frxDsCondPagto: TfrxDBDataset;
frxCondPagto: TfrxReport;
cdsCondPagtocpavl: TFloatField;
cdsCondPagtoAux: TClientDataSet;
cdsCondPagtoAuxcobcod: TIntegerField;
cdsCondPagtoAuxcobnome: TStringField;
cdsCondPagtoAuxzondescr: TStringField;
cdsCondPagtoAuxasscod: TIntegerField;
cdsCondPagtoAuxassnome: TStringField;
cdsCondPagtoAuxcpadtvenc: TDateField;
cdsCondPagtoAuxcpavl: TFloatField;
cdsCondPagtoAuxadavlpend: TFloatField;
cdsCondPagtoAuxzoncod: TStringField;
cdsEtiquetasasscomplent_Inteiro: TIntegerField;
sqlHistAltAss: TSQLDataSet;
dspHistAltAss: TDataSetProvider;
cdsHistAltAss: TClientDataSet;
cdsHistAltAsshmadthr: TSQLTimeStampField;
cdsHistAltAssusunome: TStringField;
cdsHistAltAsshmadescr: TMemoField;
frxDsHistAltAss: TfrxDBDataset;
frxHistAltAss: TfrxReport;
cdsHistAltAssasscod: TIntegerField;
cdsHistAltAssassnome: TStringField;
cdsAltCadhmadthr: TSQLTimeStampField;
cdsAltCadusunome: TStringField;
cdsAltCadasscod: TIntegerField;
cdsAltCadassnome: TStringField;
cdsAltCadhmadescr: TMemoField;
frxAltCad: TfrxReport;
cdsUsuariosusucod: TLargeintField;
cdsAltCadhmaseq: TIntegerField;
cdsHistAltAsshmaseq: TIntegerField;
cdsCondPagtoAuxadavldesc: TFloatField;
cdsCondPagtoAuxcpanroparc: TIntegerField;
cdsCondPagtoadavldesc: TFloatField;
cdsCondPagtocpanroparc: TIntegerField;
sqlDescontos: TSQLDataSet;
dspDescontos: TDataSetProvider;
cdsDescontos: TClientDataSet;
frxDsDescontos: TfrxDBDataset;
cdsDescontosasscod: TIntegerField;
cdsDescontosassnome: TStringField;
cdsDescontosadacod: TIntegerField;
cdsDescontosadadtini: TDateField;
cdsDescontosadadtvenc: TDateField;
cdsDescontosadavl: TFloatField;
cdsDescontosadavldesc: TFloatField;
frxDescontos: TfrxReport;
sqlCortesias: TSQLDataSet;
dspCortesias: TDataSetProvider;
cdsCortesias: TClientDataSet;
frxDsCortesias: TfrxDBDataset;
cdsCortesiasasscod: TIntegerField;
cdsCortesiasassnome: TStringField;
cdsCortesiasadacod: TIntegerField;
cdsCortesiasadadtini: TDateField;
cdsCortesiasadadtvenc: TDateField;
cdsCortesiasadavl: TFloatField;
frxCortesias: TfrxReport;
procedure cdsAssCanceladasCalcFields(DataSet: TDataSet);
procedure DataModuleCreate(Sender: TObject);
procedure cdsAssRenovarCalcFields(DataSet: TDataSet);
procedure cdsEtiquetasCalcFields(DataSet: TDataSet);
procedure cdsLotesCalcFields(DataSet: TDataSet);
private
{ Private declarations }
function GetSqlWhereGruposVendedores: String;
function GetSqlWhereZonas: String;
function GetSqlWhereVendedores: String;
function GetSqlWhereCobradores: String;
public
{ Public declarations }
Year: array[0..5] of integer;
procedure MarcarDesmarcarGruposVendedores(AMarcar: Boolean);
procedure MarcarDesmarcarZonas(AMarcar: Boolean);
procedure MarcarDesmarcarVendedores(AMarcar: Boolean);
procedure MarcarDesmarcarCobradores(AMarcar: Boolean);
procedure CarregarUsuarios(AUsucodDefault: Integer; APermitirSelecaoNula: Boolean);
procedure CarregarGruposVendedores;
procedure CarregarVendedores;
procedure CarregarCobradores;
procedure CarregarZonas;
procedure ConfigurarCabecalhoRodape(ATitulo, ASubTitulo: String);
procedure CarregarLotesRenovacaoAuto;
procedure ShowReportBaixas(ADataInicialBaixa, ADataFinalBaixa: TDateTime);
procedure ShowReportAssinaturasCanceladas(ADataInicialCancel, ADataFinalCancel: TDateTime);
procedure ShowReportAssinaturasRenovar(ATipoRelat: integer; ADataInicialVenc, ADataFinalVenc: TDateTime; ATipoSelecao: Integer; AGaacod: Integer; AGaaanomes: TDateTime; AGaanromes: Integer);
procedure ShowReportAssinaturasPendentes(AAgrupamento: Integer; ADataInicialBaixa, ADataFinalBaixa: TDateTime);
procedure ShowReportAssinantes(AAgrupamento: Integer);
procedure ShowReportEtiquetas(ATipoImpressora: Integer; AConsideraImprimirEtiqueta: Boolean; ASomenteAssinatesAtivos: Boolean);
procedure ShowReportAlteracaoCadastro(AUsucod: Integer; ADataInicialAlt, ADataFinalAlt: TDate);
procedure ShowReportCondicoesPagto(ADataInicial, ADataFinal: TDate);
procedure ShowReportAlteracoesAssinante(AAsscod: Integer; ADataInicialAlt, ADataFinalAlt: TDate);
procedure ShowReportDescontos(ADataInicial, ADataFinal: TDate);
procedure ShowReportCortesias;
function GetUltAnoMesRenovacaoAuto: TDate;
end;
var
dmDadosRelat: TdmDadosRelat;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses uConexao, uDadosEmpresa, uPrincipal, uUsuario, uDadosGlobal, uMensagem;
{$R *.dfm}
{ TdmDadosRelat }
procedure TdmDadosRelat.CarregarCobradores;
begin
cdsCobradores.Close;
cdsCobradores.Open;
cdsCobradores.Filtered := false;
end;
procedure TdmDadosRelat.CarregarGruposVendedores;
begin
cdsGruposVendedores.Close;
cdsGruposVendedores.Open;
cdsGruposVendedores.Filtered := false;
end;
procedure TdmDadosRelat.CarregarLotesRenovacaoAuto;
begin
cdsLotes.Close;
cdsLotes.Open;
cdsLotes.First;
// Por default deixa marcado sempre a última geração automáca realizada.
cdsLotes.Edit;
cdsLotesCalcSelecionado.Value := true;
cdsLotes.Post;
end;
procedure TdmDadosRelat.CarregarUsuarios(AUsucodDefault: Integer; APermitirSelecaoNula: Boolean);
var
SQL: String;
begin
SQL :=
'select usucod, usunome ' +
' from tblusu ' +
' UNION ' +
'select distinct 0 as usucod, '' '' as usunome ' +
' from tblusu ';
if APermitirSelecaoNula then
SQL := SQL + ' where 1=1 '
else
SQL := SQL + ' where 1=2 ';
SQL := SQL + ' order by usunome ';
sqlUsuarios.Close;
sqlUsuarios.CommandText := SQL;
cdsUsuarios.Close;
cdsUsuarios.Open;
if not cdsUsuarios.Locate('usucod', AUsucodDefault, []) then
cdsUsuarios.First;
end;
procedure TdmDadosRelat.CarregarVendedores;
begin
cdsVendedores.Close;
cdsVendedores.Open;
cdsVendedores.Filtered := false;
end;
procedure TdmDadosRelat.CarregarZonas;
begin
cdsZonas.Close;
cdsZonas.Open;
cdsZonas.Filtered := false;
end;
procedure TdmDadosRelat.cdsAssCanceladasCalcFields(DataSet: TDataSet);
begin
// Faz a montagem do endereço completo do assinante
cdsAssCanceladasCalcEndereco.AsString := dmDadosGlobal.FormataEndereco(cdsAssCanceladasrdzender.AsString, cdsAssCanceladasassnroent.AsString, cdsAssCanceladasasscomplent.AsString);
// Telefone
if (trim(cdsAssCanceladasCalcTelefone.AsString) = EmptyStr) and (trim(cdsAssCanceladasassfoneresid.AsString) <> EmptyStr) then
cdsAssCanceladasCalcTelefone.AsString := trim(cdsAssCanceladasassfoneresid.AsString);
if (trim(cdsAssCanceladasCalcTelefone.AsString) = EmptyStr) and (trim(cdsAssCanceladasassfonecelul.AsString) <> EmptyStr) then
cdsAssCanceladasCalcTelefone.AsString := trim(cdsAssCanceladasassfonecelul.AsString);
if (trim(cdsAssCanceladasCalcTelefone.AsString) = EmptyStr) and (trim(cdsAssCanceladasassfonecomer.AsString) <> EmptyStr) then
cdsAssCanceladasCalcTelefone.AsString := trim(cdsAssCanceladasassfonecomer.AsString);
end;
procedure TdmDadosRelat.cdsAssRenovarCalcFields(DataSet: TDataSet);
var
Telefones: String;
begin
// Nome do assinante + Código Assinante + CPF ou CNPF
cdsAssRenovarCalcNomeCpf.AsString := trim(cdsAssRenovarasscod.AsString);
cdsAssRenovarCalcNomeCpf.AsString := cdsAssRenovarCalcNomeCpf.AsString + ' - ' + trim(cdsAssRenovarassnome.AsString);
if ((cdsAssRenovarasscpf.AsString) <> EmptyStr) or ((cdsAssRenovarasscnpj.AsString) <> EmptyStr) then
begin
if trim(cdsAssRenovarasscnpj.AsString) <> EmptyStr then
cdsAssRenovarCalcNomeCpf.AsString := cdsAssRenovarCalcNomeCpf.AsString + ' - CNPJ: ' + cdsAssRenovarasscnpj.AsString
else
if trim(cdsAssRenovarasscpf.AsString) <> EmptyStr then
cdsAssRenovarCalcNomeCpf.AsString := cdsAssRenovarCalcNomeCpf.AsString + ' - CPF: ' + cdsAssRenovarasscpf.AsString;
end;
// Endereço completo
cdsAssRenovarCalcEnderecoCompleto.AsString := dmDadosGlobal.FormataEndereco(cdsAssRenovarrdzender.AsString, cdsAssRenovarassnroent.AsString, cdsAssRenovarasscomplent.AsString);
// ---------------------------------------------------------------------------
// Concatena os telfones residencial e celular do assinante para mostrar no recibo.
// ---------------------------------------------------------------------------
if trim(cdsAssRenovarassfoneresid.AsString) <> EmptyStr then
Telefones := trim(cdsAssRenovarassfoneresid.AsString);
if trim(cdsAssRenovarassfonecelul.AsString) <> EmptyStr then
if Telefones = EmptyStr then
Telefones := trim(cdsAssRenovarassfonecelul.AsString)
else
Telefones := Telefones + ', ' + trim(cdsAssRenovarassfonecelul.AsString);
if trim(cdsAssRenovarassfonecomer.AsString) <> EmptyStr then
begin
if Telefones = EmptyStr then
Telefones := trim(cdsAssRenovarassfonecomer.AsString)
else
Telefones := Telefones + ', ' + trim(cdsAssRenovarassfonecomer.AsString);
if trim(cdsAssRenovarassfonecomerramal.AsString) <> EmptyStr then
Telefones := Telefones + ' r.' + trim(cdsAssRenovarassfonecomerramal.AsString);
end;
cdsAssRenovarCalcTelefones.AsString := Telefones;
// Valor por extenso da assinatura
cdsAssRenovarCalcValorPorExtenso.AsString := dmDadosGlobal.PadL(dmDadosGlobal.ValorPorExtenso(cdsAssRenovaradavl.Value), 150, '*');
end;
procedure TdmDadosRelat.cdsEtiquetasCalcFields(DataSet: TDataSet);
begin
// Os campos calculados estão no while do CDS dentro da função mesmo.
end;
procedure TdmDadosRelat.cdsLotesCalcFields(DataSet: TDataSet);
begin
cdsLotesCalcAnoMes.AsString := FormatDateTime('mm', cdsLotesgaaanomes.Value) +
' / ' + FormatDateTime('yyyy', cdsLotesgaaanomes.Value);
end;
procedure TdmDadosRelat.ConfigurarCabecalhoRodape(ATitulo, ASubTitulo: String);
begin
cdsCabecalhoRodape.Close;
cdsCabecalhoRodape.CreateDataSet;
cdsCabecalhoRodape.Open;
cdsCabecalhoRodape.Append;
cdsCabecalhoRodapeCNPJ.AsString := trim(dmDadosEmpresa.cdsTblempempcnpj.AsString);
cdsCabecalhoRodapeEmpresa.AsString := trim(dmDadosEmpresa.cdsTblempemprazaosocial.AsString);
// Endereço completo
cdsCabecalhoRodapeEndereco.AsString := dmDadosGlobal.FormataEndereco(dmDadosEmpresa.cdsTblempempender.AsString, dmDadosEmpresa.cdsTblempempnro.AsString);
// Apenas a Cidade
cdsCabecalhoRodapeCidade.AsString := dmDadosGlobal.ConvertePrimeiraLetraMaiuscula(trim(dmDadosEmpresa.sqlTblcepcepmunicipio.AsString));
// Bairro, Cidade e Estado
cdsCabecalhoRodapeCidadeEstado.AsString := dmDadosGlobal.ConvertePrimeiraLetraMaiuscula(trim(dmDadosEmpresa.sqlTblcepcepmunicipio.AsString)) + ' - ' + trim(dmDadosEmpresa.sqlTblcepcepeuf.AsString);
if (trim(dmDadosEmpresa.cdsTblempempbairro.AsString) <> EmptyStr) and (trim(dmDadosEmpresa.cdsTblempempbairro.AsString) <> '.') then
cdsCabecalhoRodapeCidadeEstado.AsString := 'Bairro ' + trim(dmDadosEmpresa.cdsTblempempbairro.AsString) + ' - ' + cdsCabecalhoRodapeCidadeEstado.AsString;
// Telefone da empresa
cdsCabecalhoRodapeFoneEmpresa.AsString := trim(dmDadosEmpresa.cdsTblempempfone.AsString);
cdsCabecalhoRodapeTitulo.AsString := ATitulo;
cdsCabecalhoRodapeSubTitulo.AsString := ASubTitulo;
cdsCabecalhoRodapeUsuario.AsString := 'Usuário: ' + trim(dmUsuario.cdsUsuariousunome.AsString);
cdsCabecalhoRodapeVersao.AsString := 'Versão ' + frmPrincipal.GetVersaoPrograma;
cdsCabecalhoRodape.Post;
end;
procedure TdmDadosRelat.DataModuleCreate(Sender: TObject);
var
I, x: Integer;
AnoAtual: integer;
AnoInicial: integer;
AnoFinal: integer;
begin
AnoAtual := YearOf(dmDadosGlobal.GetDataHoraBanco);
AnoInicial := AnoAtual - 1;
AnoFinal := AnoInicial + 5;
x := 0;
for I := AnoInicial to AnoFinal do
begin
Year[x] := i;
Inc(x);
end;
end;
function TdmDadosRelat.GetSqlWhereCobradores: String;
begin
Result := '';
cdsCobradores.Filtered := false;
cdsCobradores.DisableControls;
try
cdsCobradores.First;
while not cdsCobradores.Eof do
begin
if cdsCobradoresCalcSelecionado.Value = true then
begin
if Result = EmptyStr then
Result := IntToStr(cdsCobradorescobcod.AsInteger)
else
Result := Result + ', ' + IntToStr(cdsCobradorescobcod.AsInteger);
end;
cdsCobradores.Next;
end;
finally
cdsCobradores.First;
cdsCobradores.EnableControls;
end;
end;
function TdmDadosRelat.GetSqlWhereGruposVendedores: String;
begin
Result := '';
cdsGruposVendedores.Filtered := false;
cdsGruposVendedores.DisableControls;
try
cdsGruposVendedores.First;
while not cdsGruposVendedores.Eof do
begin
if cdsGruposVendedoresCalcSelecionado.Value = true then
begin
if Result = EmptyStr then
Result := IntToStr(cdsGruposVendedoresgdvcod.AsInteger)
else
Result := Result + ', ' + IntToStr(cdsGruposVendedoresgdvcod.AsInteger);
end;
cdsGruposVendedores.Next;
end;
finally
cdsGruposVendedores.First;
cdsGruposVendedores.EnableControls;
end;
end;
function TdmDadosRelat.GetSqlWhereVendedores: String;
begin
Result := '';
cdsVendedores.Filtered := false;
cdsVendedores.DisableControls;
try
cdsVendedores.First;
while not cdsVendedores.Eof do
begin
if cdsVendedoresCalcSelecionado.Value = true then
begin
if Result = EmptyStr then
Result := IntToStr(cdsVendedoresvencod.AsInteger)
else
Result := Result + ', ' + IntToStr(cdsVendedoresvencod.AsInteger);
end;
cdsVendedores.Next;
end;
finally
cdsVendedores.First;
cdsVendedores.EnableControls;
end;
end;
function TdmDadosRelat.GetSqlWhereZonas: String;
begin
Result := '';
cdsZonas.Filtered := false;
cdsZonas.DisableControls;
try
cdsZonas.First;
while not cdsZonas.Eof do
begin
if cdsZonasCalcSelecionado.Value = true then
begin
if Result = EmptyStr then
Result := '"' + trim(cdsZonaszoncod.AsString) + '"'
else
Result := Result + ', "' + trim(cdsZonaszoncod.AsString) + '"'
end;
cdsZonas.Next;
end;
finally
cdsZonas.First;
cdsZonas.EnableControls;
end;
end;
function TdmDadosRelat.GetUltAnoMesRenovacaoAuto: TDate;
begin
sqlUltRenovacaoAuto.Close;
sqlUltRenovacaoAuto.Open;
try
if sqlUltRenovacaoAuto.Eof then
Result := 0
else
Result := sqlUltRenovacaoAutogaaanomes.AsDateTime;
finally
sqlUltRenovacaoAuto.Close;
end;
end;
procedure TdmDadosRelat.MarcarDesmarcarCobradores(AMarcar: Boolean);
begin
cdsCobradores.DisableControls;
try
cdsCobradores.First;
while not cdsCobradores.Eof do
begin
cdsCobradores.Edit;
cdsCobradoresCalcSelecionado.Value := AMarcar;
cdsCobradores.Post;
cdsCobradores.Next;
end;
finally
cdsCobradores.First;
cdsCobradores.EnableControls;
end;
end;
procedure TdmDadosRelat.MarcarDesmarcarGruposVendedores(AMarcar: Boolean);
begin
cdsGruposVendedores.DisableControls;
try
cdsGruposVendedores.First;
while not cdsGruposVendedores.Eof do
begin
cdsGruposVendedores.Edit;
cdsGruposVendedoresCalcSelecionado.Value := AMarcar;
cdsGruposVendedores.Post;
cdsGruposVendedores.Next;
end;
finally
cdsGruposVendedores.First;
cdsGruposVendedores.EnableControls;
end;
end;
procedure TdmDadosRelat.MarcarDesmarcarVendedores(AMarcar: Boolean);
begin
cdsVendedores.DisableControls;
try
cdsVendedores.First;
while not cdsVendedores.Eof do
begin
cdsVendedores.Edit;
cdsVendedoresCalcSelecionado.Value := AMarcar;
cdsVendedores.Post;
cdsVendedores.Next;
end;
finally
cdsVendedores.First;
cdsVendedores.EnableControls;
end;
end;
procedure TdmDadosRelat.MarcarDesmarcarZonas(AMarcar: Boolean);
begin
cdsZonas.DisableControls;
try
cdsZonas.First;
while not cdsZonas.Eof do
begin
cdsZonas.Edit;
cdsZonasCalcSelecionado.Value := AMarcar;
cdsZonas.Post;
cdsZonas.Next;
end;
finally
cdsZonas.First;
cdsZonas.EnableControls;
end;
end;
procedure TdmDadosRelat.ShowReportAlteracaoCadastro(AUsucod: Integer; ADataInicialAlt, ADataFinalAlt: TDate);
var
SubTitulo: String;
Titulo: String;
DataHoraIni: String;
DataHoraFim: String;
begin
// ---------------------------------------------------------------------------
// Validações
// ---------------------------------------------------------------------------
if AUsucod = 0 then
raise Exception.Create('Usuário não foi selecionado.');
if ADataInicialAlt = 0 then
raise Exception.Create('Data inicial não é válida.');
if ADataFinalAlt = 0 then
raise Exception.Create('Data final não é válida.');
if ADataInicialAlt > ADataFinalAlt then
raise Exception.Create('Data inicial não pode ser maior que data final.');
// Tenho que fazer esta jogada pois a coluna do banco de dados é um DateTime,
// e nãso apenas Date.
DataHoraIni := FormatDateTime('yyyy-mm-dd', ADataInicialAlt) + ' 00:00:00';
DataHoraFim := FormatDateTime('yyyy-mm-dd', ADataFinalAlt) + ' 23:59:59';
sqlAltCad.Close;
sqlAltCad.ParamByName('usucod').AsInteger := AUsucod;
sqlAltCad.ParamByName('hmadthrini').AsString := DataHoraIni;
sqlAltCad.ParamByName('hmadthrfim').AsString := DataHoraFim;
cdsAltCad.Close;
cdsAltCad.Open;
if cdsAltCad.RecordCount = 0 then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
Titulo := 'Histórico de Alterações de Cadastros';
SubTitulo := 'Usuário: ' + trim(cdsAltCadusunome.Value) + ' - Período: ' + FormatDateTime('dd/mm/yyyy', ADataInicialAlt) + ' até ' + FormatDateTime('dd/mm/yyyy', ADataFinalAlt);
ConfigurarCabecalhoRodape(Titulo, SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxAltCad.ShowReport;
end;
procedure TdmDadosRelat.ShowReportAlteracoesAssinante(AAsscod: Integer;
ADataInicialAlt, ADataFinalAlt: TDate);
var
SubTitulo: String;
Titulo: String;
DataHoraIni: String;
DataHoraFim: String;
begin
// ---------------------------------------------------------------------------
// Validações
// ---------------------------------------------------------------------------
if AAsscod = 0 then
raise Exception.Create('Assinante não foi selecionado.');
if ADataInicialAlt = 0 then
raise Exception.Create('Data inicial não é válida.');
if ADataFinalAlt = 0 then
raise Exception.Create('Data final não é válida.');
if ADataInicialAlt > ADataFinalAlt then
raise Exception.Create('Data inicial não pode ser maior que data final.');
// Tenho que fazer esta jogada pois a coluna do banco de dados é um DateTime,
// e nãso apenas Date.
DataHoraIni := FormatDateTime('yyyy-mm-dd', ADataInicialAlt) + ' 00:00:00';
DataHoraFim := FormatDateTime('yyyy-mm-dd', ADataFinalAlt) + ' 23:59:59';
sqlHistAltAss.Close;
sqlHistAltAss.ParamByName('asscod').AsInteger := AAsscod;
sqlHistAltAss.ParamByName('hmadthrini').AsString := DataHoraIni;
sqlHistAltAss.ParamByName('hmadthrfim').AsString := DataHoraFim;
cdsHistAltAss.Close;
cdsHistAltAss.Open;
if cdsHistAltAss.RecordCount = 0 then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
Titulo := 'Histórico de Alterações do Assinante';
SubTitulo := 'Assinante: ' + trim(cdsHistAltAssasscod.AsString) + '-' + trim(cdsHistAltAssassnome.AsString) + ' - Período: ' + FormatDateTime('dd/mm/yyyy', ADataInicialAlt) + ' até ' + FormatDateTime('dd/mm/yyyy', ADataFinalAlt);
ConfigurarCabecalhoRodape(Titulo, SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxHistAltAss.ShowReport;
end;
procedure TdmDadosRelat.ShowReportAssinantes(AAgrupamento: Integer);
var
SQL: String;
Where: String;
TituloSeparador: String;
SubTitulo: String;
FieldNameCodigo: String;
FieldNameDescr: String;
begin
// ---------------------------------------------------------------------------
// Montagem e execução do SQL
// ---------------------------------------------------------------------------
case AAgrupamento of
0: // Zona
begin
SubTitulo := 'Relação de todos os assinantes ativos separado por zonas';
TituloSeparador := 'Zona';
FieldNameCodigo := 'zoncod';
FieldNameDescr := 'zondescr';
SQL :=
'select tblzon.zoncod, ' +
' tblzon.zondescr, ';
Where := GetSqlWhereZonas;
if Where = EmptyStr then
raise Exception.Create('Pelo menos uma zona deve ser selecionada.');
Where := ' and tblzon.zoncod in (' + Where + ')';
end;
1: // Vendedor
begin
SubTitulo := 'Relação de todos os assinantes ativos separado por vendedores';
TituloSeparador := 'Vendedor';
FieldNameCodigo := 'vencod';
FieldNameDescr := 'vennome';
SQL :=
'select tblven.vencod, ' +
' tblven.vennome, ';
Where := GetSqlWhereVendedores;
if Where = EmptyStr then
raise Exception.Create('Pelo menos um vendedor deve ser selecionado.');
Where := ' and tblven.vencod in (' + Where + ')';
end;
2: // Grupo Vendedor
begin
SubTitulo := 'Relação de todos os assinantes ativos separado por Grupos de Vendedores';
TituloSeparador := 'Grupo Vendedor';
FieldNameCodigo := 'gdvcod';
FieldNameDescr := 'gdvdescr';
SQL :=
'select tblgdv.gdvcod, ' +
' tblgdv.gdvdescr, ';
Where := GetSqlWhereGruposVendedores;
if Where = EmptyStr then
raise Exception.Create('Pelo menos um grupo de vendedores deve ser selecionado.');
Where := ' and tblgdv.gdvcod in (' + Where + ')';
end;
3: // Cobrador
begin
SubTitulo := 'Relação de todos os assinantes ativos separado por Cobradores';
TituloSeparador := 'Cobrador';
FieldNameCodigo := 'cobcod';
FieldNameDescr := 'cobnome';
SQL :=
'select tblcob.cobcod, ' +
' tblcob.cobnome, ';
Where := GetSqlWhereCobradores;
if Where = EmptyStr then
raise Exception.Create('Pelo menos um cobrador deve ser selecionado.');
Where := ' and tblcob.cobcod in (' + Where + ')';
end;
end;
SQL := SQL +
' tblass.asscod, tblass.assnome, tblass.rdzcod, tblrdz.rdzender, tblass.assnroent, ' +
' tblass.asscomplent ' +
' from tblass, tblven, tblgdv, tblcob, tblrdz, tblzon ' +
'where tblass.vencod = tblven.vencod ' +
' and tblven.gdvcod = tblgdv.gdvcod ' +
' and tblass.cobcod = tblcob.cobcod ' +
' and tblass.rdzcod = tblrdz.rdzcod ' +
' and tblrdz.zoncod = tblzon.zoncod ' +
' and tblass.assstatus = 0 ' +
Where;
cdsAssinantes.Close;
cdsAssinantes.CreateDataSet;
cdsAssinantes.Open;
sqlAssinantes.Close;
sqlAssinantes.CommandText := SQL;
sqlAssinantes.Open;
while not sqlAssinantes.Eof do
begin
cdsAssinantes.Append;
cdsAssinantestitulo_agrupador.AsString := TituloSeparador;
cdsAssinantescod_agrupador.AsString := sqlAssinantes.FieldByName(FieldNameCodigo).AsString;
cdsAssinantesdescr_agrupador.AsString := trim(cdsAssinantescod_agrupador.AsString) + ' - ' + trim(sqlAssinantes.FieldByName(FieldNameDescr).AsString);
cdsAssinantesasscod.AsInteger := sqlAssinantes.FieldByName('asscod').AsInteger;
cdsAssinantesassnome.AsString := sqlAssinantes.FieldByName('assnome').AsString;
cdsAssinantesrdzender.AsString := sqlAssinantes.FieldByName('rdzender').AsString;
cdsAssinantesassnroent_Inteiro.AsInteger := StrToInt(dmDadosGlobal.GetSoNumeros(sqlAssinantes.FieldByName('assnroent').AsString, '0'));
cdsAssinantesassnroent_String.AsString := dmDadosGlobal.GetSoLetras(sqlAssinantes.FieldByName('assnroent').AsString);
// Monta o endereço completo
cdsAssinantesEnderecoCompleto.AsString := dmDadosGlobal.FormataEndereco(sqlAssinantes.FieldByName('rdzender').AsString, sqlAssinantes.FieldByName('assnroent').AsString, sqlAssinantes.FieldByName('asscomplent').AsString);
cdsAssinantes.Post;
sqlAssinantes.Next;
end;
cdsAssinantes.First;
// Ordenação do ClientDataSet
cdsAssinantes.IndexFieldNames := 'titulo_agrupador;cod_agrupador;rdzender;assnroent_Inteiro;assnroent_String;assnome';
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
ConfigurarCabecalhoRodape('Relação de Assinaturas', SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxAssinantes.ShowReport;
end;
procedure TdmDadosRelat.ShowReportAssinaturasCanceladas(ADataInicialCancel,
ADataFinalCancel: TDateTime);
var
SQL: String;
Where: String;
SubTitulo: String;
begin
// ---------------------------------------------------------------------------
// Validações
// ---------------------------------------------------------------------------
if ADataInicialCancel = 0 then
raise Exception.Create('Data inicial não é válida.');
if ADataFinalCancel = 0 then
raise Exception.Create('Data final não é válida.');
if ADataInicialCancel > ADataFinalCancel then
raise Exception.Create('Data inicial não pode ser maior que data final.');
// ---------------------------------------------------------------------------
// Montagem e execução do SQL
// ---------------------------------------------------------------------------
SQL :=
'select tblzon.zoncod, tblzon.zondescr, tblass.asscod, tblass.assnome, ' +
' tblass.assfoneresid, tblass.assfonecelul, tblass.assfonecomer, ' +
' tblada.adacod, tblrdz.rdzender, tblass.assnroent, tblass.asscomplent, ' +
' tblada.adadtcancel, tblada.adadtvenc, tblada.adavlpend ' +
' from tblass, tblada, tblrdz, tblzon ' +
' where tblass.asscod = tblada.asscod ' +
' and tblass.rdzcod = tblrdz.rdzcod ' +
' and tblrdz.zoncod = tblzon.zoncod ' +
' and tblada.adacancel = "S" ' +
' and tblada.adadtcancel between "' + FormatDateTime('yyyy-mm-dd', ADataInicialCancel) + '" and "' + FormatDateTime('yyyy-mm-dd', ADataFinalCancel) + '" ';
Where := GetSqlWhereZonas;
if Where = EmptyStr then
raise Exception.Create('Pelo menos uma zona deve ser selecionada.');
SQL := SQL +
' and tblzon.zoncod in (' + Where + ')' +
' order by tblzon.zoncod, tblass.assnome';
sqlAssCanceladas.Close;
sqlAssCanceladas.CommandText := SQL;
cdsAssCanceladas.Close;
cdsAssCanceladas.Open;
if cdsAssCanceladas.RecordCount = 0 then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
SubTitulo := 'Período de cancelamento das assinaturas: ' + FormatDateTime('dd/mm/yyyy', ADataInicialCancel) + ' até ' + FormatDateTime('dd/mm/yyyy', ADataFinalCancel);
ConfigurarCabecalhoRodape('Assinaturas Canceladas', SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxAssCanceladas.ShowReport;
end;
procedure TdmDadosRelat.ShowReportAssinaturasPendentes(AAgrupamento: Integer;
ADataInicialBaixa, ADataFinalBaixa: TDateTime);
var
SQL: String;
Where: String;
WhereZonas: String;
SubTitulo: String;
TituloSeparador: String;
FieldNameCodigo: String;
FieldNameDescr: String;
begin
// ---------------------------------------------------------------------------
// Validações
// ---------------------------------------------------------------------------
if ADataInicialBaixa = 0 then
raise Exception.Create('Data inicial não é válida.');
if ADataFinalBaixa = 0 then
raise Exception.Create('Data final não é válida.');
if ADataInicialBaixa > ADataFinalBaixa then
raise Exception.Create('Data inicial não pode ser maior que data final.');
// ---------------------------------------------------------------------------
// Montagem e execução do SQL
// ---------------------------------------------------------------------------
case AAgrupamento of
0: // Vendedor
begin
TituloSeparador := 'Vendedor:';
FieldNameCodigo := 'vencod';
FieldNameDescr := 'vennome';
SQL :=
'select tblven.vencod, ' +
' tblven.vennome, ';
Where := GetSqlWhereVendedores;
if Where = EmptyStr then
raise Exception.Create('Pelo menos um vendedor deve ser selecionado.');
Where := ' and tblven.vencod in (' + Where + ')';
end;
1: // Grupo Vendedor
begin
TituloSeparador := 'Grupo Vendedor:';
FieldNameCodigo := 'gdvcod';
FieldNameDescr := 'gdvdescr';
SQL :=
'select tblgdv.gdvcod, ' +
' tblgdv.gdvdescr, ';
Where := GetSqlWhereGruposVendedores;
if Where = EmptyStr then
raise Exception.Create('Pelo menos um grupo de vendedores deve ser selecionado.');
Where := ' and tblgdv.gdvcod in (' + Where + ')';
end;
2: // Cobrador
begin
TituloSeparador := 'Cobrador:';
FieldNameCodigo := 'cobcod';
FieldNameDescr := 'cobnome';
SQL :=
'select tblcob.cobcod, ' +
' tblcob.cobnome, ';
Where := GetSqlWhereCobradores;
if Where = EmptyStr then
raise Exception.Create('Pelo menos um cobrador deve ser selecionado.');
Where := ' and tblcob.cobcod in (' + Where + ')';
end;
end;
WhereZonas := GetSqlWhereZonas;
if WhereZonas = EmptyStr then
raise Exception.Create('Pelo menos um zona deve ser selecionada.');
WhereZonas := ' and tblzon.zoncod in (' + WhereZonas + ')';
SQL := SQL +
' tblzon.zoncod, tblzon.zondescr, ' +
' tblass.asscod, tblass.assnome, tblrdz.rdzender, tblass.assnroent, ' +
' tblada.adadtvenc, tblada.adavlpend ' +
' from tblass, tblada, tblven, tblgdv, tblcob, tblrdz, tblzon ' +
'where tblass.asscod = tblada.asscod ' +
' and tblass.vencod = tblven.vencod ' +
' and tblven.gdvcod = tblgdv.gdvcod ' +
' and tblass.cobcod = tblcob.cobcod ' +
' and tblass.rdzcod = tblrdz.rdzcod ' +
' and tblrdz.zoncod = tblzon.zoncod ' +
' and tblada.adadtvenc between "' + FormatDateTime('yyyy-mm-dd', ADataInicialBaixa) + '" and "' + FormatDateTime('yyyy-mm-dd', ADataFinalBaixa) + '" ' +
' and tblass.assstatus = 0 ' +
' and tblada.adavlpend > 0 ' +
' and tblada.adacancel = ' + QuotedStr('N') +
' and tblada.adacortesia = ' + QuotedStr('N') +
Where +
WhereZonas +
' order by 1, tblzon.zoncod, tblass.assnome ';
cdsAssPendentes.Close;
cdsAssPendentes.CreateDataSet;
cdsAssPendentes.Open;
sqlAssPendentes.Close;
sqlAssPendentes.CommandText := SQL;
sqlAssPendentes.Open;
while not sqlAssPendentes.Eof do
begin
cdsAssPendentes.Append;
cdsAssPendentesChave.AsString := TituloSeparador + ' ' + trim(sqlAssPendentes.FieldByName(FieldNameCodigo).AsString) + ' - ' + trim(sqlAssPendentes.FieldByName(FieldNameDescr).AsString);
cdsAssPendenteszoncod.AsString := sqlAssPendentes.FieldByName('zoncod').AsString;
cdsAssPendenteszondescr.AsString := sqlAssPendentes.FieldByName('zondescr').AsString;
cdsAssPendentesasscod.AsInteger := sqlAssPendentes.FieldByName('asscod').AsInteger;
cdsAssPendentesassnome.AsString := sqlAssPendentes.FieldByName('assnome').AsString;
// Monta o endereço completo
cdsAssPendentesEndereco.AsString := dmDadosGlobal.FormataEndereco(sqlAssPendentes.FieldByName('rdzender').AsString, sqlAssPendentes.FieldByName('assnroent').AsString);
cdsAssPendentesadadtvenc.AsDateTime := sqlAssPendentes.FieldByName('adadtvenc').AsDateTime;
cdsAssPendentesadavlpend.AsFloat := sqlAssPendentes.FieldByName('adavlpend').AsFloat;
cdsAssPendentes.Post;
sqlAssPendentes.Next;
end;
cdsAssPendentes.First;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
SubTitulo := 'Período de vencimento: ' + FormatDateTime('dd/mm/yyyy', ADataInicialBaixa) + ' até ' + FormatDateTime('dd/mm/yyyy', ADataFinalBaixa);
ConfigurarCabecalhoRodape('Assinaturas Pendentes', SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxAssPendentes.ShowReport;
end;
procedure TdmDadosRelat.ShowReportAssinaturasRenovar(ATipoRelat: integer; ADataInicialVenc, ADataFinalVenc: TDateTime; ATipoSelecao: Integer; AGaacod: Integer; AGaaanomes: TDateTime; AGaanromes: Integer);
var
SQL: String;
SubTitulo: String;
i: integer;
begin
// ---------------------------------------------------------------------------
// Validações
// ---------------------------------------------------------------------------
if ATipoSelecao = 1 then
begin
if ADataInicialVenc = 0 then
raise Exception.Create('Data inicial não é válida.');
if ADataFinalVenc = 0 then
raise Exception.Create('Data final não é válida.');
if ADataInicialVenc > ADataFinalVenc then
raise Exception.Create('Data inicial não pode ser maior que data final.');
end;
// ---------------------------------------------------------------------------
// Montagem do SQL
// ---------------------------------------------------------------------------
SQL :=
'select tblzon.zoncod, tblzon.zondescr, tblass.asscod, tblass.assnome, ' +
' tblass.asscpf, tblass.asscnpj, tblass.assemail, ' +
' tblass.assfoneresid, tblass.assfonecelul, tblass.assfonecomer, ' +
' tblass.assfonecomerramal, tblrdz.rdzender, tblass.assnroent, ' +
' tblass.asscomplent, tblass.assbairroent, tblcep.cepmunicipio, tblcep.cepeuf, ' +
' tblada.adadtini, tblada.adadtvenc, tblada.adavl, tblada.adavl, tblada.adavldesc ' +
' from tblass, tblcep, tblrdz, tblzon, tblada ' +
' where tblass.rdzcod = tblrdz.rdzcod ' +
' and tblrdz.zoncod = tblzon.zoncod ' +
' and tblass.asscod= tblada.asscod ' +
' and tblass.cepcepent = tblcep.cepcep ' +
' and tblass.assstatus = 0 ' +
' and tblada.adacancel = "N" ';
if ATipoSelecao = 0 then
SQL := SQL + ' and tblada.gaacod = ' + IntToStr(AGaacod)
else
SQL := SQL + ' and tblada.adadtvenc between "' + FormatDateTime('yyyy-mm-dd', ADataInicialVenc) + '" and "' + FormatDateTime('yyyy-mm-dd', ADataFinalVenc) + '" ';
SQL := SQL +
' order by tblzon.zoncod, tblada.adadtvenc, tblass.assnome ';
// and tblass.asscod = 1
sqlAssRenovar.Close;
sqlAssRenovar.CommandText := SQL;
cdsAssRenovar.Close;
cdsAssRenovar.Open;
i := 0;
while not cdsAssRenovar.Eof do
begin
inc(i);
cdsAssRenovar.Edit;
if ((i mod 2) = 0) then
cdsAssRenovarCalcImpLinhaSep.Value := 0
else
cdsAssRenovarCalcImpLinhaSep.Value := 1;
cdsAssRenovar.Post;
cdsAssRenovar.Next;
end;
cdsAssRenovar.First;
if cdsAssRenovar.RecordCount = 0 then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
SubTitulo := '';
if ATipoSelecao = 0 then
begin
SubTitulo := 'Lote nro.: ' + IntToStr(AGaacod) + ' - ';
ADataInicialVenc := IncMonth(AGaaanomes, AGaanromes);
ADataInicialVenc := EncodeDate(YearOf(ADataInicialVenc), MonthOf(ADataInicialVenc), DayOf(ADataInicialVenc));
ADataFinalVenc := EncodeDate(YearOf(ADataInicialVenc), MonthOf(ADataInicialVenc), DayOf(EndOfTheMonth(ADataInicialVenc)));
end;
SubTitulo := SubTitulo + 'Período de vencimento: ' + FormatDateTime('dd/mm/yyyy', ADataInicialVenc) + ' até ' + FormatDateTime('dd/mm/yyyy', ADataFinalVenc);
ConfigurarCabecalhoRodape('Assinaturas à Renovar', SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
if ATipoRelat = 0 then
frxRecibos.ShowReport
else
frxAssRenovar.ShowReport;
end;
procedure TdmDadosRelat.ShowReportBaixas(ADataInicialBaixa,
ADataFinalBaixa: TDateTime);
var
SQL: String;
Where: String;
SubTitulo: String;
begin
// ---------------------------------------------------------------------------
// Validações
// ---------------------------------------------------------------------------
if ADataInicialBaixa = 0 then
raise Exception.Create('Data inicial não é válida.');
if ADataFinalBaixa = 0 then
raise Exception.Create('Data final não é válida.');
if ADataInicialBaixa > ADataFinalBaixa then
raise Exception.Create('Data inicial não pode ser maior que data final.');
// ---------------------------------------------------------------------------
// Montagem e execução do SQL
// ---------------------------------------------------------------------------
SQL :=
'select tblgdv.gdvcod, tblgdv.gdvdescr, tblass.asscod, tblass.assnome, ' +
' tblbda.adacod, tblbda.bdadt, tblada.adadtvenc, tblbda.bdavl ' +
' from tblass, tblven, tblgdv, tblada, tblbda ' +
' where tblass.vencod = tblven.vencod ' +
' and tblven.gdvcod = tblgdv.gdvcod ' +
' and tblass.asscod = tblada.asscod ' +
' and tblada.asscod = tblbda.asscod ' +
' and tblada.adacod = tblbda.adacod ' +
' and tblbda.bdadt between "' + FormatDateTime('yyyy-mm-dd', ADataInicialBaixa) + '" and "' + FormatDateTime('yyyy-mm-dd', ADataFinalBaixa) + '" ';
Where := GetSqlWhereGruposVendedores;
if Where = EmptyStr then
raise Exception.Create('Pelo menos um grupo de vendedores deve ser selecionado.');
SQL := SQL + ' and tblgdv.gdvcod in (' + Where + ')';
SQL := SQL + ' order by tblgdv.gdvcod, tblbda.bdadt, tblass.assnome';
sqlBaixas.Close;
sqlBaixas.CommandText := SQL;
cdsBaixas.Close;
cdsBaixas.Open;
if cdsBaixas.RecordCount = 0 then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
SubTitulo := 'Período das baixas: ' + FormatDateTime('dd/mm/yyyy', ADataInicialBaixa) + ' até ' + FormatDateTime('dd/mm/yyyy', ADataFinalBaixa);
ConfigurarCabecalhoRodape('Baixas Realizadas', SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxBaixas.ShowReport;
end;
procedure TdmDadosRelat.ShowReportCondicoesPagto(ADataInicial,
ADataFinal: TDate);
var
SQL: String;
Where: String;
SubTitulo: String;
ChaveAtual, ChaveAnterior: string;
begin
// ---------------------------------------------------------------------------
// Validações
// ---------------------------------------------------------------------------
if ADataInicial = 0 then
raise Exception.Create('Data inicial não é válida.');
if ADataFinal = 0 then
raise Exception.Create('Data final não é válida.');
if ADataInicial > ADataFinal then
raise Exception.Create('Data inicial não pode ser maior que data final.');
Where := GetSqlWhereCobradores;
if Where = EmptyStr then
raise Exception.Create('Pelo menos um cobrador deve ser selecionado.');
// ---------------------------------------------------------------------------
// Montagem e execução do SQL
// ---------------------------------------------------------------------------
SQL :=
'select tblass.cobcod, tblcob.cobnome, tblrdz.zoncod, tblzon.zondescr, ' +
' tblass.asscod, tblass.assnome, tblada.adavldesc, tblcpa.cpanroparc, ' +
' tblcpa.cpadtvenc, tblcpa.cpavl, tblada.adavlpend ' +
' from tblass, tblcob, tblrdz, tblzon, tblada, tblcpa ' +
' where tblass.cobcod = tblcob.cobcod ' +
' and tblass.rdzcod = tblrdz.rdzcod ' +
' and tblrdz.zoncod = tblzon.zoncod ' +
' and tblass.asscod = tblada.asscod ' +
' and tblada.asscod = tblcpa.asscod ' +
' and tblada.adacod= tblcpa.adacod ' +
' and tblada.adacancel = ' + QuotedStr('N') +
' and tblada.adacortesia = ' + QuotedStr('N') +
' and tblada.adavlpend > 0 ' +
' and tblcpa.cpadtvenc between "' + FormatDateTime('yyyy-mm-dd', ADataInicial) + '" and "' + FormatDateTime('yyyy-mm-dd', ADataFinal) + '" ';
SQL := SQL +
' and tblcob.cobcod in (' + Where + ') ' +
' order by tblcob.cobnome, tblrdz.zoncod, tblass.assnome, tblcpa.cpadtvenc ';
sqlCondPagto.Close;
sqlCondPagto.CommandText := SQL;
cdsCondPagto.Close;
cdsCondPagto.Open;
if cdsCondPagto.RecordCount = 0 then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
cdsCondPagtoAux.Close;
cdsCondPagtoAux.CreateDataSet;
cdsCondPagtoAux.Open;
ChaveAnterior := '';
cdsCondPagto.First;
while not cdsCondPagto.Eof do
begin
ChaveAtual := cdsCondPagtocobcod.AsString + cdsCondPagtozoncod.AsString + cdsCondPagtoasscod.AsString;
if ChaveAnterior = ChaveAtual then
begin
cdsCondPagtoAux.AppendRecord([
cdsCondPagtocobcod.Value,
cdsCondPagtocobnome.Value,
cdsCondPagtozoncod.Value,
cdsCondPagtozondescr.Value,
'',
'',
'',
cdsCondPagtocpanroparc.Value,
cdsCondPagtocpadtvenc.Value,
cdsCondPagtocpavl.Value,
'']);
end
else
begin
cdsCondPagtoAux.AppendRecord([
cdsCondPagtocobcod.Value,
cdsCondPagtocobnome.Value,
cdsCondPagtozoncod.Value,
cdsCondPagtozondescr.Value,
cdsCondPagtoasscod.Value,
cdsCondPagtoassnome.Value,
cdsCondPagtoadavldesc.Value,
cdsCondPagtocpanroparc.Value,
cdsCondPagtocpadtvenc.Value,
cdsCondPagtocpavl.Value,
cdsCondPagtoadavlpend.Value]);
end;
ChaveAnterior := cdsCondPagtocobcod.AsString + cdsCondPagtozoncod.AsString + cdsCondPagtoasscod.AsString;
cdsCondPagto.Next;
end;
cdsCondPagtoAux.First;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
SubTitulo := 'Período de vencimento das parcelas: ' + FormatDateTime('dd/mm/yyyy', ADataInicial) + ' até ' + FormatDateTime('dd/mm/yyyy', ADataFinal);
ConfigurarCabecalhoRodape('Condições de Pagamento', SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxCondPagto.ShowReport;
end;
procedure TdmDadosRelat.ShowReportCortesias;
begin
cdsCortesias.Close;
cdsCortesias.Open;
if cdsCortesias.RecordCount = 0 then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
ConfigurarCabecalhoRodape('Assinaturas Cortesias', '');
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxCortesias.ShowReport;
end;
procedure TdmDadosRelat.ShowReportDescontos(ADataInicial, ADataFinal: TDate);
var
SubTitulo: String;
begin
// ---------------------------------------------------------------------------
// Validações
// ---------------------------------------------------------------------------
if ADataInicial = 0 then
raise Exception.Create('Data inicial não é válida.');
if ADataFinal = 0 then
raise Exception.Create('Data final não é válida.');
if ADataInicial > ADataFinal then
raise Exception.Create('Data inicial não pode ser maior que data final.');
sqlDescontos.Close;
sqlDescontos.ParamByName('adadtini1').AsDate := ADataInicial;
sqlDescontos.ParamByName('adadtini2').AsDate := ADataFinal;
cdsDescontos.Close;
cdsDescontos.Open;
if cdsDescontos.RecordCount = 0 then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
// ---------------------------------------------------------------------------
// Configuração do Cabeçalho e rodapé
// ---------------------------------------------------------------------------
SubTitulo := 'Assinaturas renovadas no Período de: ' + FormatDateTime('dd/mm/yyyy', ADataInicial) + ' até ' + FormatDateTime('dd/mm/yyyy', ADataFinal);
ConfigurarCabecalhoRodape('Descontos Realizados', SubTitulo);
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
frxDescontos.ShowReport;
end;
procedure TdmDadosRelat.ShowReportEtiquetas(ATipoImpressora: Integer; AConsideraImprimirEtiqueta: Boolean;
ASomenteAssinatesAtivos: Boolean);
var
SQL: String;
Where: String;
StrDataVencimentoAss: String;
ZoncodAnt: String;
ZondescrAnt: String;
EntregadorAnt: String;
begin
// ---------------------------------------------------------------------------
// Montagem e execução do SQL
// ---------------------------------------------------------------------------
SQL :=
'select tblass.asscod, tblzon.zoncod, tblzon.zondescr, tblzon.zonentregador, ' +
' tblass.assnome, ' +
' tblrdz.rdzender, tblass.assnroent, tblass.asscomplent ' +
' from tblass, tblrdz, tblzon ' +
' where tblass.rdzcod = tblrdz.rdzcod ' +
' and tblrdz.zoncod = tblzon.zoncod ';
if AConsideraImprimirEtiqueta then
SQL := SQL + ' and tblass.assimpretiq = "S" ';
if ASomenteAssinatesAtivos then
SQL := SQL + ' and tblass.assstatus = 0 '; // Ativos
Where := GetSqlWhereZonas;
if Where = EmptyStr then
raise Exception.Create('Pelo menos uma zona deve ser selecionada.');
SQL := SQL +
' and tblzon.zoncod in (' + Where + ')' +
' order by tblzon.zoncod, tblrdz.rdzender, tblass.assnroent, tblass.assnome';
TfrmMensagem.MostrarMesagem('Aguarde, gerando etiquetas...');
try
sqlEtiquetasSql.Close;
sqlEtiquetasSql.CommandText := SQL;
cdsEtiquetasSql.Close;
cdsEtiquetasSql.Open;
if cdsEtiquetasSql.Eof then
begin
MessageDlg('Não existem resultados para serem mostrados.', mtInformation, [mbok], 0);
exit;
end;
cdsEtiquetas.Close;
cdsEtiquetas.CreateDataSet;
cdsEtiquetas.Open;
ZoncodAnt := cdsEtiquetasSqlzoncod.AsString;
ZondescrAnt := cdsEtiquetasSqlzondescr.AsString;
EntregadorAnt := cdsEtiquetasSqlzonentregador.AsString;
while not cdsEtiquetasSql.Eof do
begin
// Faz etiqueta da zona anterior
if ZoncodAnt <> cdsEtiquetasSqlzoncod.AsString then
begin
sqlCountAssAtivosZona.Close;
sqlCountAssAtivosZona.ParamByName('zoncod').AsString := ZoncodAnt;
sqlCountAssAtivosZona.Open;
cdsEtiquetas.Append;
cdsEtiquetasPinta.AsInteger := 1;
cdsEtiquetaszoncod.AsString := '';
cdsEtiquetaszoncod_Ordem.AsString := ZoncodAnt;
cdsEtiquetasassnome.AsString := ZoncodAnt + ' - ' + ZondescrAnt;
cdsEtiquetasEndereco.AsString := EntregadorAnt;
cdsEtiquetasasscomplent.AsString := FormatFloat('0', sqlCountAssAtivosZonaQtdeAtivos.AsInteger) + ' ASSINANTES ATIVOS';
cdsEtiquetasAdadtvenc.AsString := '';
cdsEtiquetasrdzender.AsString := 'XXXXX';
cdsEtiquetasassnroent_Inteiro.AsInteger := 99999;
cdsEtiquetasassnroent_String.AsString := '99999';
cdsEtiquetasasscomplent_Inteiro.Value := 99999;
cdsEtiquetas.Post;
ZoncodAnt := cdsEtiquetasSqlzoncod.AsString;
ZondescrAnt := cdsEtiquetasSqlzondescr.AsString;
EntregadorAnt := cdsEtiquetasSqlzonentregador.AsString;
end;
// Busca a data de vencimento da última assinatura do assinante.
sqlUltAssinatura.Close;
sqlUltAssinatura.ParamByName('asscod').AsInteger := cdsEtiquetasSqlasscod.AsInteger;
sqlUltAssinatura.Open;
if not sqlUltAssinatura.Eof then
StrDataVencimentoAss := 'VENC: ' + FormatDateTime('dd/mm/yyyy', sqlUltAssinaturaadadtvenc.AsDateTime)
else
StrDataVencimentoAss := '';
cdsEtiquetas.Append;
cdsEtiquetasPinta.AsInteger := 0;
cdsEtiquetaszoncod.AsString := cdsEtiquetasSqlzoncod.AsString;
cdsEtiquetaszoncod_Ordem.AsString := cdsEtiquetasSqlzoncod.AsString;
cdsEtiquetasassnome.AsString := cdsEtiquetasSqlassnome.AsString;
cdsEtiquetasEndereco.AsString := dmDadosGlobal.FormataEndereco(cdsEtiquetasSqlrdzender.AsString, cdsEtiquetasSqlassnroent.AsString);
cdsEtiquetasasscomplent.AsString := copy(trim(cdsEtiquetasSqlasscomplent.AsString), 1, 25);
cdsEtiquetasAdadtvenc.AsString := StrDataVencimentoAss;
cdsEtiquetasrdzender.AsString := trim(cdsEtiquetasSqlrdzender.AsString);
cdsEtiquetasassnroent_Inteiro.AsInteger := StrToInt(dmDadosGlobal.GetSoNumeros(cdsEtiquetasSqlassnroent.AsString, '0'));
cdsEtiquetasassnroent_String.AsString := dmDadosGlobal.GetSoLetras(cdsEtiquetasSqlassnroent.AsString);
cdsEtiquetasasscomplent_Inteiro.Value := StrToInt(dmDadosGlobal.GetPrimeirosNumeroComplementoEndereco(cdsEtiquetasSqlasscomplent.AsString, '0'));
cdsEtiquetas.Post;
// Faz a última etiqueta da última zona
if cdsEtiquetasSql.RecNo = cdsEtiquetasSql.RecordCount then
begin
sqlCountAssAtivosZona.Close;
sqlCountAssAtivosZona.ParamByName('zoncod').AsString := cdsEtiquetasSqlzoncod.AsString;
sqlCountAssAtivosZona.Open;
cdsEtiquetas.Append;
cdsEtiquetasPinta.AsInteger := 1;
cdsEtiquetaszoncod.AsString := '';
cdsEtiquetaszoncod_Ordem.AsString := cdsEtiquetasSqlzoncod.AsString;
cdsEtiquetasassnome.AsString := cdsEtiquetasSqlzoncod.AsString + ' - ' + cdsEtiquetasSqlzondescr.AsString;
cdsEtiquetasEndereco.AsString := cdsEtiquetasSqlzonentregador.AsString;
cdsEtiquetasasscomplent.AsString := FormatFloat('0', sqlCountAssAtivosZonaQtdeAtivos.AsInteger) + ' ASSINANTES ATIVOS';
cdsEtiquetasAdadtvenc.AsString := '';
cdsEtiquetasrdzender.AsString := 'XXXXX';
cdsEtiquetasassnroent_Inteiro.AsInteger := 99999;
cdsEtiquetasassnroent_String.AsString := '99999';
cdsEtiquetasasscomplent_Inteiro.Value := 99999;
cdsEtiquetas.Post;
end;
cdsEtiquetasSql.Next;
end;
cdsEtiquetas.First;
finally
TfrmMensagem.MostrarMesagem;
end;
// Ordenação do ClientDataSet
cdsEtiquetas.IndexFieldNames := 'zoncod_Ordem;rdzender;assnroent_Inteiro;assnroent_String;asscomplent_Inteiro;assnome';
// ---------------------------------------------------------------------------
// Mostra o relatório na tela
// ---------------------------------------------------------------------------
if ATipoImpressora = 0 then // Jato de tinta
frxEtiquetaJato.ShowReport
else
frxEtiquetaArgox.ShowReport;
end;
end.
|
unit localizar;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, StdCtrls, JsEdit1, ExtCtrls,
DB, func, FireDAC.Comp.Client;
type
TForm7 = class(TForm)
DBGrid1: TDBGrid;
Edit1: TEdit;
Label1: TLabel;
Timer1: TTimer;
DataSource1: TDataSource;
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
procedure DBGrid1KeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure DBGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Timer1Timer(Sender: TObject);
procedure Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
dataset : TFDTable;
procura : String;
procedure acertarTamanhoDBGRID();
procedure abredataSetContasPagar();
procedure reabredataSetContasPagar();
procedure deletaContasPagar();
procedure deletaEntrada();
procedure deletaTranferencia();
procedure deletaContasReceber();
function buscaCodbar() : String;
{ Private declarations }
public
query, query1 : TFDQuery;
deletar:boolean;
ordem, campoLocate, keyLocate, retLocalizar : string;
retorno:string;
esconde:string;
tabela : string;
formulario : tForm;
campos : string;
condicao:string;
editlocaliza:boolean;
cod: JsEdit;
campolocaliza : string;
usarBuscaProdutoCodigoSeq : boolean;
editalvel:boolean;
end;
var
Form7: TForm7;
implementation
uses protetor, StrUtils;
{$R *.dfm}
function TForm7.buscaCodbar() : String;
begin
Result := DBGrid1.DataSource.DataSet.FieldByName('cod').AsString;
query1.Close;
query1.SQL.Text := 'select codbar from produto where cod = :cod';
query1.ParamByName('cod').AsString := StrNum(Result);
query1.Open;
if StrNum(query1.FieldByName('codbar').AsString) <> '0' then
begin
Result := StrNum(query1.FieldByName('codbar').AsString);
query1.Close;
exit;
end;
query1.Close;
query1.SQL.Text := 'select codbar from codbar where cod = :cod';
query1.ParamByName('cod').AsString := StrNum(Result);
query1.Open;
if not query1.IsEmpty then Result := StrNum(query1.FieldByName('codbar').AsString);
query1.Close;
end;
procedure TForm7.deletaContasReceber();
var
ren : integer;
begin
{ if dm.IBQuery1.IsEmpty then exit;
if UpperCase(tabela) <> 'CONTASRECEBER' then exit;
if not VerificaAcesso_Se_Nao_tiver_Nenhum_bloqueio_true_senao_false then
begin
WWMessage('Somente um Usuário Autorizado Pode Cancelar Esta Conta.',mtError,[mbok],clYellow,true,false,clRed);
exit;
end;
if messageDlg('Deseja Excluir '+dm.IBQuery1.fieldbyname('historico').AsString +' ?', mtConfirmation, [mbyes, mbNo], 0) = mrYes then
begin
ren := dm.IBQuery1.RecNo;
dm.IBQuery1.DisableControls;
try
dm.IBselect.SQL.Clear;
dm.IBselect.SQL.Add('delete from contasreceber where cod ='+dm.IBQuery1.fieldbyname('cod').AsString) ;
try
dm.IBselect.ExecSQL;
dm.IBselect.Transaction.Commit;
dm.IBQuery1.Close;
dm.IBQuery1.Open;
dm.IBQuery1.MoveBy(ren - 1);
except
dm.IBQuery1.Transaction.Rollback;
dm.IBQuery1.Close;
exit;
end;
finally
dm.IBQuery1.EnableControls;
end;
end;
}end;
procedure TForm7.deletaTranferencia();
begin
{ if dm.IBQuery1.IsEmpty then exit;
if not funcoes.Contido('TRANSFERENCIA',UpperCase(tabela)) then exit;
if messageDlg('Confirma Exclusão Desta Transferência?', mtConfirmation, [mbyes, mbNo], 0) = mrYes then
begin
dm.IBQuery2.Close;
dm.IBQuery2.SQL.Clear;
if dm.IBQuery1.FieldByName('destino').AsInteger = 1 then dm.IBQuery2.SQL.Add('update produto set quant = quant - :q, deposito = deposito + :q where cod='+dm.IBQuery1.fieldbyname('cod').AsString)
else dm.IBQuery2.SQL.Add('update produto set quant = quant + :q, deposito = deposito - :q where cod='+dm.IBQuery1.fieldbyname('cod').AsString);
dm.IBQuery2.ParamByName('q').AsCurrency := dm.IBQuery1.fieldbyname('quant').AsCurrency;
dm.IBQuery2.ExecSQL;
dm.IBQuery2.Close;
dm.IBQuery2.SQL.Clear;
dm.IBQuery2.SQL.Add('delete from transferencia where documento='+dm.IBQuery1.fieldbyname('documento').AsString);
try
dm.IBQuery2.ExecSQL;
dm.IBQuery2.Transaction.Commit;
dm.IBQuery1.Close;
dm.IBQuery1.Open;
except
dm.IBQuery2.Transaction.Rollback;
ShowMessage('Ocorreu um Erro Inesperado. Tente Novamente!');
end;
end;
}end;
procedure TForm7.deletaEntrada();
var
val, temp : String;
begin
{ if dm.IBQuery1.IsEmpty then exit;
if (UpperCase(tabela) <> 'ENTRADA') then exit;
if messageDlg('Confirma Exclusão Desta Entrada?', mtConfirmation, [mbyes, mbNo], 0) = mrYes then
begin
val := dm.IBQuery1.fieldbyname('nota').AsString;
dm.IBQuery3.Close;
dm.IBQuery3.SQL.Clear;
dm.IBQuery3.SQL.Add('select quant, cod, destino from item_entrada where nota = '+ val);
dm.IBQuery3.Open;
while not dm.IBQuery3.Eof do
begin
if dm.IBQuery3.FieldByName('destino').AsInteger = 1 then temp := 'quant'
else temp := 'deposito';
dm.IBQuery4.Close;
dm.IBQuery4.SQL.Clear;
dm.IBQuery4.SQL.Add('update produto set '+ temp +' = '+ temp +' - :qu where cod = :cod');
dm.IBQuery4.ParamByName('qu').AsCurrency := dm.IBQuery3.fieldbyname('quant').AsCurrency;
dm.IBQuery4.ParamByName('cod').AsString := dm.IBQuery3.fieldbyname('cod').AsString;
dm.IBQuery4.ExecSQL;
dm.IBQuery3.Next;
end;
dm.IBQuery4.Close;
dm.IBQuery4.SQL.Clear;
dm.IBQuery4.SQL.Add('delete from entrada where nota = :nota');
dm.IBQuery4.ParamByName('nota').AsString := val;
dm.IBQuery4.ExecSQL;
dm.IBQuery4.Close;
dm.IBQuery4.SQL.Clear;
dm.IBQuery4.SQL.Add('delete from item_entrada where nota = :nota');
dm.IBQuery4.ParamByName('nota').AsString := val;
dm.IBQuery4.ExecSQL;
dm.IBQuery4.Transaction.Commit;
dm.IBQuery1.Close;
dm.IBQuery1.Open;
end;
}end;
procedure TForm7.deletaContasPagar();
var
ren : integer;
begin
{ if UpperCase(tabela) <> 'CONTASPAGAR' then exit;
if dataset.IsEmpty then exit;
if not VerificaAcesso_Se_Nao_tiver_Nenhum_bloqueio_true_senao_false then
begin
WWMessage('Somente um Usuário Autorizado Pode Cancelar Esta Conta.',mtError,[mbok],clYellow,true,false,clRed);
exit;
end;
if messageDlg('Deseja Excluir?', mtConfirmation, [mbyes, mbNo], 0) = mrYes then
begin
try
dataset.DisableControls;
ren := dataset.RecNo;
dm.IBQuery2.Close;
dm.IBQuery2.SQL.Clear;
dm.IBQuery2.SQL.Add('delete from contaspagar where (codgru = :gru) and (documento = :doc) and vencimento = :data');
dm.IBQuery2.ParamByName('gru').AsString := dataset.fieldbyname('codgru').AsString;
dm.IBQuery2.ParamByName('doc').AsString := dataset.fieldbyname('documento').AsString;
dm.IBQuery2.ParamByName('data').AsDateTime := dataset.fieldbyname('vencimento').AsDateTime;
Try
dm.IBQuery2.ExecSQL;
dm.IBQuery2.Transaction.Commit;
reabredataSetContasPagar();
dataset.MoveBy(ren - 1);
except
end;
finally
dataset.EnableControls;
end;
end;
}end;
procedure TForm7.abredataSetContasPagar();
begin
{ dataset := TFDTable.Create(self);
dataset.Database := dm.bd;
dataset.TableName := UpperCase(tabela);
dataset.Active := TRUE;
dataset.Filter := '(pago = 0)';
dataset.Filtered := true;
dataset.IndexName := 'CONTASPAGAR_IDX2'; //INDICE VENCIMENTO
dataset.First;
dataset.FieldByName('fornec').Visible := false;
dataset.FieldByName('usuario').Visible := false;
dataset.FieldByName('pago').Visible := false;
dataset.FieldByName('total').Visible := false;
dataset.FieldByName('valor').Index := 4;
//dataset.FieldByName('valor').ReadOnly := true;
//dataset.FieldByName('vencimento').ReadOnly := true;
funcoes.FormataCampos(TFDQuery(dataset), 2, '', 2);
dm.ds.DataSet := dataset;
}end;
procedure TForm7.reabredataSetContasPagar();
begin
{ dataset.Active := false;
dataset.Active := true;
dataset.Filter := '(pago = 0)';
dataset.Filtered := true;
dataset.IndexName := 'CONTASPAGAR_IDX1'; //INDICE VENCIMENTO
dataset.FieldByName('fornec').Visible := false;
dataset.FieldByName('usuario').Visible := false;
dataset.FieldByName('pago').Visible := false;
dataset.FieldByName('total').Visible := false;
dataset.FieldByName('valor').Index := 4;
//dataset.FieldByName('valor').ReadOnly := true;
//dataset.FieldByName('vencimento').ReadOnly := true;
funcoes.FormataCampos(TFDQuery(dataset), 2, '', 2);
//dm.ds.DataSet := dataset;
}end;
procedure TForm7.acertarTamanhoDBGRID();
var
i, acc : integer;
begin
acc := 0;
for i:=0 to DBGrid1.Columns.Count-1 do
begin
//showme
acc := acc + DBGrid1.Columns[i].Width;
end;
self.Width := acc + 10;
DBGrid1.Width := acc;
//if acc < 299 then self.Width:=acc+10;
end;
procedure TForm7.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if key = #27 then Close;
if key = #13 then
begin
if tabela = 'contaspagar' then
begin
if Edit1.Text = '' then
begin
dataset.Filtered := false;
dataset.Filter := '(pago = 0)';
dataset.Filtered := true;
exit;
end;
// dataset.IndexDefs.Add('indice', 'data', [ixDescending]);
dataset.Filtered := false;
dataset.Filter :='(pago = 0) and (' + campolocaliza + ' like ' + QuotedStr('%' + Edit1.Text + '%') + ')';
dataset.Filtered := true;
exit;
end;
Query.SQL.Clear;
if ordem = '' then
begin
if condicao <> '' then Query.SQL.Add('select '+campos+' from '+tabela+' '+condicao +' and ('+campolocaliza+' like upper('+ QuotedStr('%'+Edit1.Text+'%')+')) ')
else query.SQL.Add('select '+campos+' from '+tabela+' where ('+campolocaliza+' like upper('+ QuotedStr('%'+Edit1.Text+'%')+')) ');
end
else
begin
if condicao <> '' then Query.SQL.Add('select '+campos+' from '+tabela+' '+condicao +' and ('+campolocaliza+' like upper('+ QuotedStr('%'+Edit1.Text+'%')+')) order by '+ordem)
else Query.SQL.Add('select '+campos+' from '+tabela+' where ('+campolocaliza+' like upper('+ QuotedStr('%'+Edit1.Text+'%')+')) order by '+ordem)
end;
if Query.SQL.GetText <> '' then
begin
Query.Open;
if Query.IsEmpty then exit
else
begin
FormataCampos(Query,2,'',2);
DBGrid1.SetFocus;
end;
end;
if esconde <> '' then Query.FieldByName(esconde).Visible:=false;
{ dm.IBQuery1.SQL.Clear;
dm.IBQuery1.SQL.Add('select '+campos+' from '+tabela+' where '+campolocaliza+' like upper('+ QuotedStr('%'+Edit1.Text+'%')+') order by '+campolocaliza);
dm.IBQuery1.Open;
DBGrid1.SetFocus;
} end;
end;
procedure TForm7.DBGrid1KeyPress(Sender: TObject; var Key: Char);
var i:integer;
var acc, mm:string;
begin
key := UpCase(key);
if (tabela = 'contaspagar') and (not Contido(key, #27 + #13)) then
begin
//sai pq não tem o que fazer aqui
exit;
end;
if (key = #32) and Contido('PRODUTO', UpperCase(tabela)) then
begin
if (DBGrid1.SelectedField.DisplayName = 'COD') then acc := 'Informe o Código:'
else acc := 'Selecionar por:';
acc := dialogo('normal',0,''+ #8 + #13+ #27,0,false,'','Control For Windows',acc,'');
if acc = '*' then exit;
if ((DBGrid1.SelectedField.DisplayName = 'COD') and (usarBuscaProdutoCodigoSeq)) then
begin
if not Query.Locate('cod', acc, []) then ShowMessage('Código ' + acc + ' Não Encontrado');
exit;
end;
query1.Close;
//dm.IBQuery3.SQL.Add('select p.cod, nome, p.codbar from produto p join codbarras c on ((c.cod = p.cod)) where (p.codbar like '+QuotedStr('%'+ acc +'%')+') or (nome like '+ QuotedStr('%'+acc+'%') +') or ((c.codbar like '+QuotedStr('%'+ acc +'%')+') and (c.cod = p.cod))');
if UpperCase(tabela) = 'PRODUTO P' then query1.SQL.Text := ('select p.cod, nome, p.codbar from produto p left join codbarras c on (c.cod = p.cod) '+ IfThen(condicao = '','where', condicao + ' and ') +' (nome like '+QuotedStr('%'+ acc +'%')+') order by nome')
else query1.SQL.Text := ('select p.cod, nome, p.codbar, p.p_venda from produto p left join codbarras c on (c.cod = p.cod) '+ IfThen(condicao = '','where', condicao + ' and ') +' (p.codbar like '+QuotedStr('%'+ acc +'%')+') or (nome like '+QuotedStr('%'+ acc +'%')+') or (c.codbar like '+QuotedStr('%'+ acc +'%')+') order by nome');
query1.Open;
if query1.IsEmpty then
begin
query1.Close;
ShowMessage(acc + ' Não Encontrado');
exit;
end;
mm := busca(query1, acc,'COD NOME CODBAR', 'cod' , '');
if mm = '' then exit;
Query.Locate('cod',mm,[loPartialKey]);
end;
if (key = #32) and (UpperCase(tabela) = 'CLIENTE') then
begin
acc := dialogo('normal',0,''+ #8 + #13+ #27,0,false,'','Control For Windows','Selecionar por:','');
if acc = '*' then exit;
query.Close;
query.SQL.Clear;
query.SQL.Add('select cod,nome, telres from cliente where (nome like '+ QuotedStr('%'+acc+'%') +') or (telres like ' + QuotedStr('%'+acc+'%') +') or (telcom like '+ QuotedStr('%'+acc+'%') +') or (cnpj like '+ QuotedStr('%'+acc+'%') +') ORDER BY NOME');
query.Open;
if query.IsEmpty then
begin
query.Close;
ShowMessage(acc + ' Não Encontrado');
exit;
end;
mm := busca(query, acc,'NOME TELRES TELCOM BAIRRO', 'cod' , '');
if mm = '' then exit;
query.Locate('cod',mm,[loPartialKey]);
end;
if ((ord(key))>=65) and (((ord(key)))<=95) then
begin
if procura = '' then procura := UpperCase(key)
else procura := procura + UpperCase(key);
Timer1.Enabled := false;
if procura <> '' then
begin
Timer1.Enabled := true;
end;
Query.Locate(campolocaliza,procura,[loCaseInsensitive, loPartialKey]);
end;
if key=#13 then
begin
i:=0;
acc:='';
if UpperCase(retorno) = 'CODBAR' then
begin
retLocalizar := buscaCodbar;
Query.Close;
Close;
exit;
end;
retLocalizar := Query.fieldbyname(retorno).AsString;
{ if formulario = form8 then form8.cod.Text := DBGrid1.SelectedField.Value
else if formulario = form4 then form4.cod.Text := DBGrid1.SelectedField.Value
else if formulario = funcoes then
begin
if not(editalvel) then
begin
if retorno<>'' then
begin
if StrToInt(funcoes.ContaChar(retorno,','))>0 then
begin
acc:=acc+dm.IBQuery1.FieldByName(copy(retorno,1,pos(',',retorno)-1)).AsString;
acc:=acc+'-';
acc:= acc+dm.IBQuery1.FieldByName(copy(retorno,pos(',',retorno)+1,length(retorno))).AsString;
funcoes.retornoLocalizar:= acc;
end
else
begin
funcoes.retornoLocalizar:= dm.IBQuery1.fieldbyname(retorno).AsString;
end;
end;
end;
end;
}
if retorno<>'' then
begin
Close;
Query.Close;
end;
end;
if (key=#27) and (Edit1.Visible) then Edit1.SetFocus;
if (key=#27) and not(Edit1.Visible) then close;
end;
procedure TForm7.FormShow(Sender: TObject);
var
i, acc : integer;
begin
i:=0;
acc:=0;
DBGrid1.Width := self.Width - 10;
Query.Close;
Query.SQL.Clear;
DataSource1.DataSet := query;
//DBGrid1.DataSource := dm.ds;
//dm.ds.DataSet := Query;
{if UpperCase(tabela) = 'CONTASPAGAR' then
begin
abredataSetContasPagar();
acertarTamanhoDBGRID();
self.Height := 400;
DBGrid1.Height := 340;
exit;
end;
}
If not Edit1.Visible then
begin
Edit1.Text :='';
if tabela = 'produto' then begin
condicao := ' where (left(nome, 1) <> ''_'') and ((desativado <> ''1'')or (desativado is null) )';
end;
if ordem='' then query.SQL.Add('select '+campos+' from '+tabela+' order by '+campolocaliza)
else query.SQL.Add('select '+campos+' from '+tabela+' '+condicao +' order by '+ordem);
query.Open;
DBGrid1.DataSource.DataSet := query;
FormataCampos(query,2,'',2);
if esconde<>'' then query.FieldByName(esconde).Visible:=false;
for i:=0 to DBGrid1.Columns.Count-1 do
begin
acc := acc + DBGrid1.Columns[i].Width;
end;
if acc < 299 then self.Width:=acc+10;
end
else
begin
Edit1.SetFocus;
if ordem='' then query.SQL.Add('select '+campos+' from '+tabela+' order by '+campolocaliza+' asc')
else query.SQL.Add('select '+campos+' from '+tabela+' '+condicao +' order by '+ordem);
query.Open;
DBGrid1.DataSource.DataSet := query;
FormataCampos(query,2,'',2);
end;
// if (tabela = 'orcamento') or (tabela = 'compra') or (tabela = 'entrada') then query.Last;
if trim(campoLocate) <> '' then
begin
if (campoLocate = 'cod') and (trim(keyLocate) <> '') then
if DBGrid1.DataSource.DataSet.Locate(campoLocate, keyLocate, []) then DBGrid1.SetFocus;
end;
if UpperCase(tabela) = 'CONTASRECEBER' then
begin
acertarTamanhoDBGRID();
self.Height := 400;
DBGrid1.Height := 340;
end;
redimensionaTelaDbgrid(dbgrid1);
if UpperCase(tabela) = 'CLIENTE' then
begin
self.Height := screen.Height - trunc(Screen.Height * 0.15);
end;
end;
procedure TForm7.FormCreate(Sender: TObject);
begin
campolocaliza := 'nome';
usarBuscaProdutoCodigoSeq := false;
end;
procedure TForm7.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if DBGrid1.DataSource.DataSet.RecNo mod 2 = 0 then
begin
if not(Odd(DBGrid1.DataSource.DataSet.RecNo)) then // Se não for par
if not (gdSelected in State) then Begin // Se o estado da célula não é selecionado
with DBGrid1 do Begin
with Canvas do Begin
// Brush.Color := HexToTColor('F5F5F5'); // Cor da célula
//Brush.Color := HexToTColor('7093DB'); // Cor da célula
//Brush.Color := HexToTColor('81DAF5');
FillRect (Rect); // Pinta a célula
End; // with Canvas
DefaultDrawDataCell (Rect, Column.Field, State) // Reescreve o valor que vem do banco
End // With DBGrid1
End // if not (gdSelected in State)
end;
end;
procedure TForm7.FormClose(Sender: TObject; var Action: TCloseAction);
begin
query.Close;
if tabela = 'contaspagar' then
begin
if dataset.Transaction.Active then dataset.Transaction.Commit;
dataset.Free;
end;
end;
procedure TForm7.DBGrid1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if deletar then
begin
if key=46 then
begin
deletaEntrada();
deletaTranferencia();
deletaContasReceber();
deletaContasPagar();
end;
end;
end;
procedure TForm7.Timer1Timer(Sender: TObject);
begin
procura := '';
Timer1.Enabled := false;
end;
procedure TForm7.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (key = 40) or (key = 34) then DBGrid1.SetFocus;
end;
procedure TForm7.DBGrid1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
cod : string;
begin
if (DBGrid1.DataSource.DataSet.RecNo = 1) and (key = 38) and (Edit1.Visible) then edit1.SetFocus;
if (UpperCase(tabela) = 'PRODUTO') then
begin
if (ssCtrl in Shift) and (chr(Key) in ['P', 'p']) then
begin
DBGrid1.DataSource.DataSet.DisableControls;
cod := DBGrid1.DataSource.DataSet.fieldbyname('cod').AsString;
//funcoes.IMP_CODBAR(cod);
DBGrid1.DataSource.DataSet.Open;
FormataCampos(TFDQuery(DBGrid1.DataSource.DataSet), 2,'ESTOQUE',3);
DBGrid1.DataSource.DataSet.Locate('cod', cod, []);
DBGrid1.DataSource.DataSet.EnableControls;
end;
end;
end;
end.
|
unit TestLogger;
interface
uses
DPM.Core.Types,
DPM.Core.Logging;
type
TTestLogger = class(TInterfacedObject, ILogger)
protected
procedure Debug(const data: string);
procedure Error(const data: string);
procedure Information(const data: string; const important : boolean = false);
procedure Success(const data: string; const important : boolean = false);
procedure Verbose(const data: string; const important : boolean = false);
procedure Warning(const data: string; const important : boolean = false);
procedure Clear;
procedure NewLine;
function GetVerbosity : TVerbosity;
procedure SetVerbosity(const value : TVerbosity);
end;
implementation
{ TTestLogger }
procedure TTestLogger.Clear;
begin
end;
procedure TTestLogger.Debug(const data: string);
begin
end;
procedure TTestLogger.Error(const data: string);
begin
end;
function TTestLogger.GetVerbosity: TVerbosity;
begin
result := TVerbosity.Normal; //just to shut the compiler up.
end;
procedure TTestLogger.Information(const data: string; const important : boolean);
begin
end;
procedure TTestLogger.NewLine;
begin
///
end;
procedure TTestLogger.SetVerbosity(const value: TVerbosity);
begin
end;
procedure TTestLogger.Success(const data: string; const important: boolean);
begin
end;
procedure TTestLogger.Verbose(const data: string; const important : boolean);
begin
end;
procedure TTestLogger.Warning(const data: string; const important : boolean);
begin
end;
end.
|
{
publish with BSD Licence.
Copyright (c) Terry Lao
}
unit doCPLC;
{$MODE Delphi}
interface
uses iLBC_define,C2Delphi_header;
{----------------------------------------------------------------*
* Compute cross correlation and pitch gain for pitch prediction
* of last subframe at given lag.
*---------------------------------------------------------------}
procedure compCorr(
cc:pareal; { (o) cross correlation coefficient }
gc:pareal; { (o) gain }
pm:pareal;
buffer:PAreal; { (i) signal buffer }
lag:integer; { (i) pitch lag }
bLen:integer; { (i) length of buffer }
sRange:integer { (i) correlation search length }
);
procedure doThePLC(
PLCresidual:pareal; { (o) concealed residual }
PLClpc:pareal; { (o) concealed LP parameters }
PLI:integer; { (i) packet loss indicator
0 - no PL, 1 = PL }
decresidual:pareal; { (i) decoded residual }
lpc:pareal; { (i) decoded LPC (only used for no PL) }
inlag:integer; { (i) pitch lag }
iLBCdec_inst: piLBC_Dec_Inst_t
{ (i/o) decoder instance }
);
implementation
procedure compCorr(
cc:pareal; { (o) cross correlation coefficient }
gc:pareal; { (o) gain }
pm:pareal;
buffer:PAreal; { (i) signal buffer }
lag:integer; { (i) pitch lag }
bLen:integer; { (i) length of buffer }
sRange:integer { (i) correlation search length }
);
var
i:integer;
ftmp1, ftmp2, ftmp3:real;
begin
{ Guard against getting outside buffer }
if ((bLen-sRange-lag)<0) then
begin
sRange:=bLen-lag;
end;
ftmp1 := 0.0;
ftmp2 := 0.0;
ftmp3 := 0.0;
for i:=0 to sRange-1 do
begin
ftmp1 :=ftmp1+ buffer[bLen-sRange+i] * buffer[bLen-sRange+i-lag];
ftmp2 :=ftmp2+ buffer[bLen-sRange+i-lag] * buffer[bLen-sRange+i-lag];
ftmp3 :=ftmp3+ buffer[bLen-sRange+i] * buffer[bLen-sRange+i];
end;
if (ftmp2 > 0.0) then
begin
cc[0] := ftmp1*ftmp1/ftmp2;
gc[0] := abs(ftmp1/ftmp2);
pm[0] :=abs(ftmp1)/(sqrt(ftmp2)*sqrt(ftmp3));
end
else
begin
cc[0] := 0.0;
gc[0] := 0.0;
pm[0] := 0.0;
end;
end;
{----------------------------------------------------------------*
* Packet loss concealment routine. Conceals a residual signal
* and LP parameters. If no packet loss, update state.
*---------------------------------------------------------------}
procedure doThePLC(
PLCresidual:pareal; { (o) concealed residual }
PLClpc:pareal; { (o) concealed LP parameters }
PLI:integer; { (i) packet loss indicator
0 - no PL, 1 = PL }
decresidual:pareal; { (i) decoded residual }
lpc:pareal; { (i) decoded LPC (only used for no PL) }
inlag:integer; { (i) pitch lag }
iLBCdec_inst: piLBC_Dec_Inst_t
{ (i/o) decoder instance }
);
var
lag, randlag:integer;
gain, maxcc:real;
use_gain:real;
gain_comp, maxcc_comp, per, max_per:real;
i, pick, use_lag:integer;
ftmp, pitchfact, energy:real;
randvec:array [0..BLOCKL_MAX-1] of real;
begin
lag:=20;
{ Packet Loss }
if (PLI = 1) then
begin
iLBCdec_inst^.consPLICount := iLBCdec_inst^.consPLICount+1;
{ if previous frame not lost,
determine pitch pred. gain }
if (iLBCdec_inst^.prevPLI <> 1) then
begin
{ Search around the previous lag to find the
best pitch period }
lag:=inlag-3;
compCorr(@maxcc, @gain, @max_per,@iLBCdec_inst^.prevResidual,lag, iLBCdec_inst^.blockl, 60);
for i:=inlag-2 to inlag+3 do
begin
compCorr(@maxcc_comp, @gain_comp, @per,@iLBCdec_inst^.prevResidual,i, iLBCdec_inst^.blockl, 60);
if (maxcc_comp>maxcc) then
begin
maxcc:=maxcc_comp;
gain:=gain_comp;
lag:=i;
max_per:=per;
end;
end;
end
{ previous frame lost, use recorded lag and periodicity }
else
begin
lag:=iLBCdec_inst^.prevLag;
max_per:=iLBCdec_inst^.per;
end;
{ downscaling }
use_gain:=1.0;
if (iLBCdec_inst^.consPLICount*iLBCdec_inst^.blockl>320) then
use_gain:=0.9
else
if (iLBCdec_inst^.consPLICount*iLBCdec_inst^.blockl>2*320) then
use_gain:=0.7
else
if (iLBCdec_inst^.consPLICount*iLBCdec_inst^.blockl>3*320) then
use_gain:=0.5
else
if (iLBCdec_inst^.consPLICount*iLBCdec_inst^.blockl>4*320) then
use_gain:=0.0;
{ mix noise and pitch repeatition }
ftmp:=sqrt(max_per);
if (ftmp> 0.7) then
pitchfact:=1.0
else
if (ftmp>0.4) then
pitchfact:=(ftmp-0.4)/(0.7-0.4)
else
pitchfact:=0.0;
{ avoid repetition of same pitch cycle }
use_lag:=lag;
if (lag<80) then
begin
use_lag:=2*lag;
end;
{ compute concealed residual }
energy := 0.0;
for i:=0 to iLBCdec_inst^.blockl-1 do
begin
{ noise component }
iLBCdec_inst^.seed:=(iLBCdec_inst^.seed*69069+1) and ($80000000-1);
randlag := 50 + (iLBCdec_inst^.seed) mod 70;
pick := i - randlag;
if (pick < 0) then
begin
randvec[i] := iLBCdec_inst^.prevResidual[iLBCdec_inst^.blockl+pick];
end
else
begin
randvec[i] := randvec[pick];
end;
{ pitch repeatition component }
pick := i - use_lag;
if (pick < 0) then
begin
PLCresidual[i] :=iLBCdec_inst^.prevResidual[iLBCdec_inst^.blockl+pick];
end
else
begin
PLCresidual[i] := PLCresidual[pick];
end;
{ mix random and periodicity component }
if (i<80) then
PLCresidual[i] := use_gain*(pitchfact * PLCresidual[i] + (1.0 - pitchfact) * randvec[i])
else
if (i<160) then
PLCresidual[i] := 0.95*use_gain*(pitchfact *PLCresidual[i] +(1.0 - pitchfact) * randvec[i])
else
PLCresidual[i] := 0.9*use_gain*(pitchfact *PLCresidual[i] +(1.0 - pitchfact) * randvec[i]);
energy :=energy + PLCresidual[i] * PLCresidual[i];
end;
{ less than 30 dB, use only noise }
if (sqrt(energy/iLBCdec_inst^.blockl) < 30.0) then
begin
gain:=0.0;
for i:=0 to iLBCdec_inst^.blockl-1 do
begin
PLCresidual[i] := randvec[i];
end;
end;
{ use old LPC }
move(iLBCdec_inst^.prevLpc[0],PLClpc[0],(LPC_FILTERORDER+1)*sizeof(real));
end
{ no packet loss, copy input }
else
begin
move( decresidual[0],PLCresidual[0],iLBCdec_inst^.blockl*sizeof(real));
move( lpc[0],PLClpc[0], (LPC_FILTERORDER+1)*sizeof(real));
iLBCdec_inst^.consPLICount := 0;
end;
{ update state }
if (PLI=1) then
begin
iLBCdec_inst^.prevLag := lag;
iLBCdec_inst^.per := max_per;
end;
iLBCdec_inst^.prevPLI := PLI;
move ( PLClpc[0],iLBCdec_inst^.prevLpc[0], (LPC_FILTERORDER+1)*sizeof(real));
move ( PLCresidual[0],iLBCdec_inst^.prevResidual[0],iLBCdec_inst^.blockl*sizeof(real));
end;
end.
|
unit Tree;
interface
uses System.SysUtils, System.Variants, System.Classes, Wintypes;
type
pNode = ^TNode; //Указатель на TNode
TData = array [0..2,0..2] of integer;//тип поля игры
TField = array of TPoint;//тип массива свободных полей
//Класс Узла-----------------------------------------------------------------
TNode = class
private
// Поля
FData: TData; //Поле Данных
FParent:pNode; //Родитель
FVertKey:integer; //Ключ по вертикали
FHorzKey:integer; //Ключ по горизонтали
FKey:integer;
FCountChild:integer; //Кол-во потомков
FLinks:array of pNode; //Поле указателей на потомков на потомков
CoordinatesEmptyField:TField; //массив свободных полей
// Чтение-запись
function GetLinks(index:integer):pNode; // Чтение указателей на потомков
procedure SetLinks(index:integer;value:pNode); // Запись указателей потомков
function GetData :TData; //Чтение Состояния игры
procedure SetData (Data:TData);//Запись состояния игры
public
// Свойства
property Parent:pNode read FParent write FParent;
property Data :TData read GetData write SetData;
property Key:integer read FKey write FKey;
property CountChild:integer read FCountChild write FCountChild;
property Links[index:integer]:pNode read GetLinks write SetLinks;
property VertKey:integer read FVertKey write FVertKey;
property HorzKey:integer read FHorzKey write FHorzKey;
// Конструкторы
constructor Create();overload;// Пустой конструктор
constructor Create(Data:TData);overload;// Инициализатор данных
constructor Create(Data:TData;CountChild:integer);overload; //Инициализатор данных и потомков(ссылки пустые)
constructor Create(Data:TData;CountChild:integer; Parent:pNode);overload;//Инициализатор данных, родителя узла и потомков(ссылки пустые)
//--------------------------------------------------------------------------
end;
TTree = class
private
// Поля
FRoot:pNode;// Корень дерева
public
property Root:pNode read FRoot write FRoot;
// Конструктор
constructor Create();
// Деструктор
destructor Destroy;
//Инициализация дерева
procedure InitializationTree(Root: pNode; Data:TData; CountChild:integer; Parent:pNode);
//Поиск в пространстве состояний
function SearchState(Root:pNode; Data: TData):TData;
end;
function KeyWin(Data0:TData): Integer;
implementation
{ TNode }
// Реализация класса узла------------------------------------------------------
constructor TNode.Create;
var
I, j: Integer;
begin
for I := 0 to 2 do
for j := 0 to 2 do
FData[i,j]:=0 ;
FCountChild:=0;
FLinks:=nil;
FVertKey:=0;
FHorzKey:=0;
end;
constructor TNode.Create(Data: TData );
begin
FData:= Data;
FCountChild:=0;
FLinks:=nil;
FVertKey:=0;
FHorzKey:=0;
end;
constructor TNode.Create(Data:TData; CountChild: integer);
begin
FData:= Data;
FCountChild:=CountChild;
SetLength(FLinks, CountChild); // Выделение памяти под массив
FVertKey:=0;
FHorzKey:=0;
end;
constructor TNode.Create(Data: TData; CountChild: integer; Parent: pNode);
var
I: Integer;
j, l: Integer;
begin
FData:= Data;
FCountChild:=CountChild;
SetLength(FLinks, CountChild); // Выделение памяти под массив
FVertKey:=0;
FHorzKey:=0;
FParent:=Parent;
l:=0;
//Если есть родитель, то массиву свободных полей присваем массив родителя
if Parent<>nil then
begin
SetLength(CoordinatesEmptyField, length(FParent^.CoordinatesEmptyField));//выделение памяти
CoordinatesEmptyField:=FParent^.CoordinatesEmptyField;//присваиваем массив
end
else
//если нет, то присваем массиву все клетки(т.к. это корень всего дерева)
begin
SetLength(CoordinatesEmptyField, FCountChild); //выделение памяти
for I := 0 to 2 do
for j := 0 to 2 do
begin
if FData[i,j]=0 then
begin
CoordinatesEmptyField[l].X:=i;
CoordinatesEmptyField[l].Y:=j;
l:=l+1;
end;
end;
end;
end;
function TNode.GetData: TData;
begin
Getdata:= FData;
end;
function KeyWin(Data0:TData): Integer;
//------------------------------------------------------------------------------------------------------------------------------------------------------------
function VerticalTesting(data:TData):integer;
var i, value:integer;
begin
value:=3;
//Проверка по вертикали и присваивание соответствующей оценки
for I := 0 to 2 do
if ((Data[i,0]=2) and (Data[i,1]=2) and (Data[i,2]=0)) or ((Data[i,0]=0) and (Data[i,1]=2) and (Data[i,2]=2)) or ((Data[i,0]=2) and (Data[i,1]=2) and (Data[i,2]=2)) or((Data[i,0]=2) and (Data[i,1]=0) and (Data[i,2]=2)) then
begin
if value>1 then
value:=4;
if (Data[i,0]=2) and (Data[i,1]=2) and (Data[i,2]=2) then
value:=5;
end
else
if ((Data[i,0]=1) and (Data[i,1]=1) and (Data[i,2]=0)) or ((Data[i,0]=0) and (Data[i,1]=1) and (Data[i,2]=1)) or ((Data[i,0]=1) and (Data[i,1]=1) and (Data[i,2]=1)) or ((Data[i,0]=1) and (Data[i,1]=0) and (Data[i,2]=1))then
begin
if value<>5 then
value:=1;
if (Data[i,0]=1) and (Data[i,1]=1) and (Data[i,2]=1) then
value:=0;
end
else
if ((Data[i,0]=1) and (Data[i,1]=1) and (Data[i,2]=2)) or ((Data[i,0]=2) and (Data[i,1]=1) and (Data[i,2]=1)) or ((Data[i,0]=2) and (Data[i,1]=2) and (Data[i,2]=1)) or ((Data[i,0]=1) and (Data[i,1]=2) and (Data[i,2]=2)) then
begin
if value>1 then
value:=3;
end
else
if value>1 then
value:=2;
result:=value;
end;
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------
function HorizontalTesting(data:TData):integer;
var i, value:integer;
begin
value:=3;
//Проверка по горизонтали и присваивание соответствующей оценки
for I := 0 to 2 do
if ((Data[0, i]=2) and (Data[1,i]=2) and (Data[2,i]=0)) or ((Data[0, i]=0) and (Data[1,i]=2) and (Data[2,i]=2)) or ((Data[0,i]=2) and (Data[1,i]=2) and (Data[2,i]=2)) or ((Data[0, i]=2) and (Data[1, i]=0) and (Data[2, i]=2)) then
begin
if value>1 then
value:=4;
if (Data[0,i]=2) and (Data[1,i]=2) and (Data[2,i]=2) then
value:=5;
end
else
if ((Data[0, i]=1) and (Data[1, i]=1) and (Data[2, i]=0)) or ((Data[0, i]=0) and (Data[1, i]=1) and (Data[2, i]=1)) or ((Data[0, i]=1) and (Data[1, i]=1) and (Data[2, i]=1)) or ((Data[0, i]=1) and (Data[1, i]=0) and (Data[2, i]=1)) then
begin
if value<>5 then
value:=1;
if (Data[0, i]=1) and (Data[1, i]=1) and (Data[2, i]=1) then
value:=0;
end
else
if ((Data[0, i]=1) and (Data[1, i]=1) and (Data[2, i]=2)) or ((Data[0, i]=2) and (Data[1, i]=1) and (Data[2, i]=1)) or ((Data[0, i]=2) and (Data[1, i]=2) and (Data[2, i]=1)) or ((Data[0, i]=1) and (Data[1, i]=2) and (Data[2, i]=2)) then
begin
if value>1 then
value:=3;
end
else
if value>1 then
value:=2;
result:=value;
end;
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------
function DiagonalTesting_1(Data:TData):integer;
var value :integer;
begin
value:=3;
//Проверка по 1 диагонали и присваивание соответствующей оценки
if ((Data[0, 0]=2) and (Data[1,1]=2) and (Data[2,2]=0)) or ((Data[0, 0]=0) and (Data[1,1]=2) and (Data[2,2]=2)) or ((Data[0,0]=2) and (Data[1,1]=2) and (Data[2,2]=2)) or ((Data[0, 0]=2) and (Data[1, 1]=0) and (Data[2, 2]=2)) then
begin
if value>1 then
value:=4;
if (Data[0,0]=2) and (Data[1,1]=2) and (Data[2,2]=2) then
value:=5;
end
else
if ((Data[0, 0]=1) and (Data[1, 1]=1) and (Data[2, 2]=0)) or ((Data[0, 0]=0) and (Data[1, 1]=1) and (Data[2, 2]=1)) or ((Data[0, 0]=1) and (Data[1, 1]=1) and (Data[2, 2]=1)) or ((Data[0, 0]=1) and (Data[1, 1]=0) and (Data[2, 2]=1)) then
begin
if value<>5 then
value:=1;
if (Data[0, 0]=1) and (Data[1, 1]=1) and (Data[2, 2]=1) then
value:=0;
end
else
if ((Data[0, 0]=1) and (Data[1, 1]=1) and (Data[2, 2]=2)) or ((Data[0, 0]=2) and (Data[1, 1]=1) and (Data[2, 2]=1)) or ((Data[0, 0]=2) and (Data[1, 1]=2) and (Data[2, 2]=1)) or ((Data[0, 0]=1) and (Data[1, 1]=2) and (Data[2, 2]=2)) then
begin
if value>1 then
value:=3;
end
else
if value>1 then
value:=2;
result:=value;
end;
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------------------------------
function DiagonalTesting_2(Data:TData):integer;
var value :integer;
begin
value:=3;
//Проверка по 2 диагонали и присваивание соответствующей оценки
if ((Data[2, 0]=2) and (Data[1,1]=2) and (Data[0,2]=0)) or ((Data[2, 0]=0) and (Data[1,1]=2) and (Data[0,2]=2)) or ((Data[2,0]=2) and (Data[1,1]=2) and (Data[0,2]=2))or ((Data[2, 0]=2) and (Data[1, 1]=0) and (Data[0, 2]=2)) then
begin
if value>1 then
value:=4;
if (Data[2,0]=2) and (Data[1,1]=2) and (Data[0,2]=2) then
value:=5;
end
else
if ((Data[2, 0]=1) and (Data[1, 1]=1) and (Data[0, 2]=0)) or ((Data[2, 0]=0) and (Data[1, 1]=1) and (Data[0, 2]=1)) or ((Data[2, 0]=1) and (Data[1, 1]=1) and (Data[0, 2]=1)) or ((Data[2, 0]=1) and (Data[1, 1]=0) and (Data[0, 2]=1)) then
begin
if value<>5 then
value:=1;
if (Data[2, 0]=1) and (Data[1, 1]=1) and (Data[0, 2]=1) then
value:=0;
end
else
if ((Data[2, 0]=1) and (Data[1, 1]=1) and (Data[0, 2]=2)) or ((Data[2, 0]=2) and (Data[1, 1]=1) and (Data[0, 2]=1)) or ((Data[2, 0]=2) and (Data[1, 1]=2) and (Data[0, 2]=1)) or ((Data[2, 0]=1) and (Data[1, 1]=2) and (Data[0, 2]=2)) then
begin
if value>1 then
value:=3;
end
else
if value>1 then
value:=2;
result:=value;
end;
//------------------------------------------------------------------------------------------------------------------------------------------------------------
var
UpToDown, LeftToRight, diagonal1,diagonal2 :integer;
begin
UpToDown:=VerticalTesting(Data0);
LeftToRight:=HorizontalTesting(Data0);
diagonal1:=DiagonalTesting_1(Data0);
diagonal2:=DiagonalTesting_2(Data0);
//Сравниваем значения по вертикали горизонтали и диагоналям и выбираем большее
if (UpToDown>=LeftToRight) and (((UpToDown>=diagonal1) and (diagonal1>=diagonal2)) or ((UpToDown>=diagonal2) and (diagonal1<=diagonal2))) then
result:=UpToDown else
if (UpToDown<=LeftToRight) and (((LeftToRight>=diagonal1) and (diagonal1>=diagonal2)) or ((UpToDown>=diagonal2) and (diagonal1<=diagonal2)))then
result:=LeftToRight else
if (diagonal1>=diagonal2) and (((diagonal1>=uptodown) and (uptodown>=lefttoright)) or ((diagonal1>=lefttoright) and (uptodown<=lefttoright))) then
result:=diagonal1 else
if (diagonal1<=diagonal2) and (((diagonal2>=uptodown) and (uptodown>=lefttoright)) or ((diagonal2>=lefttoright) and (uptodown<=lefttoright))) then
result:=diagonal2;
if (UpToDown=0) or (LeftToRight=0) or (diagonal1=0) or (diagonal2=0) then
result:=0;
if (UpToDown=1) or (LeftToRight=1) or (diagonal1=1) or (diagonal2=1) then
result:=1;
if (UpToDown=5) or (LeftToright=5) or (diagonal1=5) or (diagonal2=5) then
result:=5;
end;
function TNode.GetLinks(index: integer): pNode;
begin
result:=FLinks[index];
end;
procedure TNode.SetData(Data:TData);
begin
FData:=Data;
end;
procedure TNode.SetLinks(index: integer; value: pNode);
begin
FLinks[index]:=value;
end;
//------------------------------------------------------------------------------
{ TTree }
// Реализация класса дерева----------------------------------------------------
constructor TTree.Create;
begin
FRoot:=nil;
new(FRoot);
end;
destructor TTree.destroy;
begin
FRoot:=nil;
dispose(FRoot);
end;
procedure TTree.InitializationTree(Root: pNode; Data:TData; CountChild: integer; Parent:pNode);
//----------------------------Генрация поля-------------------------------------
function Generation(Node:pNode; cross,toe:integer):TData;
var value, j:integer;
begin
value:=0;
randomize;
value:=random(length(Node^.CoordinatesEmptyField));
Result:=Node^.Data;
//Выбор хода и присваивание случайному полю (из массива свободных клеток) 1 или 2
if length(Node^.CoordinatesEmptyField)<>0 then
begin
if (cross>toe) then
Result[Node^.Parent^.CoordinatesEmptyField[value].X,Node^.Parent^.CoordinatesEmptyField[value].Y]:=2
else
Result[Node^.Parent^.CoordinatesEmptyField[value].X,Node^.Parent^.CoordinatesEmptyField[value].Y]:=1;
//Сдвиг элементов влево, которые находятся правее от присвоенного
for j := value to high(Node^.Parent^.CoordinatesEmptyField) do
if j<>high(Node^.Parent^.CoordinatesEmptyField) then
begin
//Сдвиг координат у узла
Node^.CoordinatesEmptyField[j].X:=Node^.CoordinatesEmptyField[j+1].X;
Node^.CoordinatesEmptyField[j].Y:=Node^.CoordinatesEmptyField[j+1].Y;
//Сдвиг координат у родителя узла
Node^.Parent^.CoordinatesEmptyField[j].X:=Node^.Parent^.CoordinatesEmptyField[j+1].X;
Node^.Parent^.CoordinatesEmptyField[j].Y:=Node^.Parent^.CoordinatesEmptyField[j+1].Y;
end;
//Удаление крайнего элемента
setlength(Node^.CoordinatesEmptyField, length(Node^.CoordinatesEmptyField)-1);
setlength(Node^.Parent^.CoordinatesEmptyField, length(Node^.Parent^.CoordinatesEmptyField)-1);
end;
end;
//-----------------------------------------------------------------------------
var
I, k: Integer;
cross,toe:byte;
begin
cross:=0;
toe:=0;
// Создаем корень------------------------
Root^:=Tnode.Create(Data,CountChild, Parent);
if Root^.Parent<>nil then
begin
//Считаем кол-во крестиков и ноликов
for i := 0 to 2 do
for k := 0 to 2 do
begin
if Root^.Parent^.Data[i,k]=1 then
cross:=cross+1 else
if Root^.Parent^.Data[i,k]=2 then
toe:=toe+1;
end;
//Генерируем поле для этого узла
Root^.Data:=Generation(Root, cross, toe);
end;
Root^.Key:=KeyWin(Root^.Data);
//Создание потомков
if (Root^.CountChild>0) and (Root^.key<>5) then
begin
for I := 0 to Root^.CountChild-1 do
if Root^.Links[i]=nil then
begin
Root^.Links[i]:=new(pNode);
InitializationTree( Root^.Links[i], Root^.Data, Root^.CountChild-1, Root);
end;
end;
end;
function TTree.SearchState(Root:pNode; Data: TData):TData;
var
I: Integer;
value:TData;
max:integer;
begin
max:=0;
//Выбор наибольшей оценки и состояния
for I := 0 to Root^.CountChild-1 do
if max<Root^.Links[i]^.Key then
begin
max:=Root^.Links[i]^.Key;
value:=Root^.Links[i]^.Data;
end;
//Если состояние игры проигрышное, то ищем состояние ничьей
if Root^.Key=1 then
begin
for I := 0 to Root^.CountChild-1 do
if (Root^.Links[i]^.Key=2) then
value:=Root^.Links[i]^.Data;
end;
result:=value;
end;
//------------------------------------------------------------------------------
end.
|
namespace GlHelper;
{$IF TOFFEE}
interface
uses
rtl,
Foundation,
CoreGraphics,
RemObjects.Elements.RTL,
OpenGL;
type GlImage = public class
private
fImg : glImageData;
fValid : Boolean;
method LoadCoreImage(const fullname : String) : Boolean;
public
constructor (const aPath : String);
property Valid : Boolean read fValid;
property Data : glImageData read fImg;
end;
implementation
constructor GlImage(const aPath: String);
begin
inherited ();
fValid := LoadCoreImage(Asset.getFullname( aPath));
end;
method GlImage.LoadCoreImage(const fullname: String): Boolean;
begin
result := false;
if fullname.FileExists then
begin
//var isPng := RemObjects.Elements.RTL.String(
var isPng := fullname.&PathExtension.ToUpperInvariant.contains('PNG');
//var mainBundle :CFBundleRef := CFBundleGetMainBundle();
//var FileURLRef : CFURLRef := CFBundleCopyResourceURL(mainBundle, CFStringRef('coral'), CFStringRef('png'), NULL);
//var dataProvider := CGDataProviderCreateWithURL(FileURLRef);
var dataProvider := CGDataProviderCreateWithFilename(NSString(fullname).cStringUsingEncoding(NSStringEncoding.NSUTF8StringEncoding));
if dataProvider <> nil then
begin
// We do have a valid Provider
// now try to read the Image
var image : CGImageRef;
if isPng then
image := CGImageCreateWithPNGDataProvider(
dataProvider,
nil,
false,
CGColorRenderingIntent.kCGRenderingIntentDefault
)
else
image := CGImageCreateWithJPEGDataProvider(
dataProvider,
nil,
false,
CGColorRenderingIntent.kCGRenderingIntentDefault
);
if image <> nil then
begin
result := true;
//var imageDataProvider := CGImageGetDataProvider(image);
var CGData := CGDataProviderCopyData(CGImageGetDataProvider(image));
fImg.imgData := CFDataGetBytePtr(CGData); // not premultiplied RGBA8 data
fImg.width := CGImageGetWidth(image);
fImg.Height := CGImageGetHeight(image);
fImg.Components := CGImageGetBitsPerPixel(image) div 8;
CGImageRelease(image);
end;
CGDataProviderRelease(dataProvider);
end;
end
else exit false;
end;
{$ENDIF} // TOFFFE
end. |
unit base_driver;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
LowxRTTI, lowX, StdCtrls,typinfo;
{
Thank you Mason Louie for you (very nice) example. The problem (commented line below) is now resolved.
This test case also demonstrates tcomponent > XML and back, pay attention to Font.Style .. before it would bomb
if the Style=[] (empty set).. now it is ok.
Also tagnames automatically build themselves if you do not specify them.
}
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
protected
_out: TLowXQuickRTTI;
end;
type
TCat = class(TPersistent)
public
procedure foo(); virtual; abstract;
private
_name: String;
_size: Integer;
published
property name: String read _name write _name;
property size: Integer read _size write _size;
end;
type
TLion = class(TCat)
public
procedure foo(); virtual;
private
_courage: Integer;
published
property courage: Integer read _courage write _courage;
end;
type
TLionard = class(TLion)
private
_temper: Integer;
_pal: TCat;
published
property temper: Integer read _temper write _temper;
property pal: TCat read _pal write _pal;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button2Click(Sender: TObject);
var
roar: TLion;
begin
{ this example doesn't work, ie won't display the object contents }
{ yeah there are better ways, but this is a quickie and it isolates the problem better }
_out := TLowXQuickRTTI.Create;
roar := TLion.Create;
{ parent class properties }
roar.name := 'Leon';
roar.size := 30;
{ native class property }
roar.courage := 100;
_out.RTTIObject := roar;
_out.TagName := 'Lion_Test';
{ RTTIObject is set by now }
Memo1.lines.text := _out.XML;
_out.free;
roar.free;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
meow: TCat;
begin
{ this example should work, ie display the object contents }
{ yeah there are better ways, but this is a quickie and it isolates the problem better }
_out := TLowXQuickRTTI.Create;
meow := TCat.Create;
meow.name := 'Morris';
meow.size := 5;
_out.RTTIObject := meow;
_out.TagName := 'Cat_Test';
{ RTTIObject is set by now }
Memo1.lines.text := _out.XML;
_out.free;
meow.free;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
roar: TLionard;
begin
{ this example doesn't work, ie won't display the object contents }
{ yeah there are better ways, but this is a quickie and it isolates the problem better }
_out := TLowXQuickRTTI.Create;
roar := TLionard.Create;
{ parent class properties }
roar.name := 'Leonard';
roar.size := 40;
roar.courage := 200;
{ native class property }
roar.temper := 30;
{ this will of course stick in a tag structure in the XML for the new object }
roar.pal := TLion.Create;
roar.pal.name := 'Scaredy';
roar.pal.size := 3;
{!!!!!!!!!!!!!!!!!!}
{UNCOMMENT THIS LINE To VIEW BEHAVIOR WHEN A PROPERTY IS NIL}
// roar.pal.free; roar.pal := nil;
_out.RTTIObject := roar;
_out.TagName := 'Lionard_Test';
{ RTTIObject is set by now }
Memo1.lines.text := _out.XML;
_out.free;
roar.free;
end;
{ TLion }
procedure TLion.foo;
begin
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
_out := TLowXQuickRTTI.Create;
_out.findtypes:=[tkInteger, tkChar, tkEnumeration, tkFloat,
tkString, tkSet, tkClass, tkWChar, tkLString, tkWString,
tkVariant, tkArray, tkRecord,tkInt64, tkDynArray];
_out.rttiobject:=button4 ;
Memo1.lines.text := _out.XML;
_out.free;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
_out := TLowXQuickRTTI.Create;
_out.findtypes:=[tkInteger, tkChar, tkEnumeration, tkFloat,
tkString, tkSet, tkClass, tkWChar, tkLString, tkWString,
tkVariant, tkArray, tkRecord,tkInt64, tkDynArray];
_out.rttiobject:=button4 ;
_out.XML:= Memo1.lines.text;
_out.free;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, uPSComponent, Forms, Controls, Graphics, Dialogs,
StdCtrls, process, unix, LCLIntf, ValEdit, ExtCtrls, ActnList, Buttons,
Ctypes;
type
{ TForm1 }
TForm1 = class(TForm)
ButtonLaunchTerminal: TButton;
ButtonSetKeyboard: TBitBtn;
ButtonSwapCtrlCapslock: TButton;
buttonQuit: TButton;
buttonLaunch: TButton;
buttonInvertColors: TButton;
buttonAbout: TButton;
ComboBox1: TComboBox;
Memo1: TMemo;
TrayIcon1: TTrayIcon;
procedure ButtonLaunchTerminalClick(Sender: TObject);
procedure ButtonSetKeyboardClick(Sender: TObject);
procedure buttonAboutClick(Sender: TObject);
procedure buttonInvertColorsClick(Sender: TObject);
procedure buttonLaunchClick(Sender: TObject);
procedure buttonQuitClick(Sender: TObject);
procedure ButtonSwapCtrlCapslockClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormCreate(Sender: TObject);
procedure TrayIcon1Click(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
// C-Function: char* getcwd(char *buf, size_t size);
// Requires: Uses Ctypes
function getcwd(buf: CTypes.pcchar; size: CTypes.csize_t): CTypes.pcchar; cdecl; external;
// C-Function: pid_t fork(void);
// Fork system-call (Fork current process)
function fork(): CTypes.cint32 ; cdecl; external;
// C-function: pid_t setsid(void);
function setsid(): CTypes.cuint32; cdecl; external;
// mode_t umask(mode_t mask);
function umask(mask: CTypes.cuint32): CTypes.cuint32; cdecl; external;
// C-Function: int execvp(const char *file, char *const argv[]);
// function execvp(prog: CTypes.pcchar; args: array of CTypes.pcchar): CTypes.cuint32 ; cdecl; external;
function execvp(prog: AnsiString; args: ppchar): CTypes.cuint32 ; cdecl; external;
function CurrentDirectory(): string;
begin
Result := SysUtils.StrPas(PAnsiChar(getcwd(nil, 0)))
end;
//=========== Functions =======================//
// Launch a subprocess
function LaunchAppFork(commandLine: String): Integer;
var
PP : PPChar;
pid : Integer;
begin
pid := fork();
if(pid = 0) then
begin
setsid();
umask(0);
//--- Executed in Forked Process (Child process)
GetMem (PP,1*SizeOf(Pchar));
PP[0] := nil;
// PP[0] := '/etc/fstab';
//PP[1] := nil;
Result := execvp(commandLine, PP);
end
end;
function LaunchApplication(commandLine: String): Integer;
var
Proc: TProcess;
begin
Proc := TProcess.Create(nil);
Proc.CommandLine := commandLine;
Proc.Execute;
Result := 0; // Dummy return value
end;
//=========== Form Handles ===================//
// Code executed during application initialization
procedure TForm1.FormCreate(Sender: TObject);
begin
TrayIcon1.Visible := True;
TrayIcon1.Hint := 'Hide';
Memo1.Text := CurrentDirectory();
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: boolean);
begin
// Minimize form instead of closing it when the user click at the (x)
// button
CanClose := False;
Hide;
end;
//============= Controls Handles =================//
procedure TForm1.buttonInvertColorsClick(Sender: TObject);
begin
// Note: Requires the application xcalib installed
LaunchApplication('xcalib -i -a');
end;
procedure TForm1.buttonLaunchClick(Sender: TObject);
begin
LaunchAppFork(ComboBox1.Text);
end;
// Exit Application
procedure TForm1.buttonQuitClick(Sender: TObject);
begin
// Exit application
Application.Terminate;
end;
procedure TForm1.ButtonSwapCtrlCapslockClick(Sender: TObject);
begin
LaunchApplication('setxkbmap -option "ctrl:swapcaps');
end;
// Open project's github repository in WebBrowser
procedure TForm1.buttonAboutClick(Sender: TObject);
begin
// Requires: uses LCLIntf;
OpenUrl('https://github.com/caiorss/lazarus-linux-panel');
end;
procedure TForm1.ButtonSetKeyboardClick(Sender: TObject);
begin
LaunchApplication('setxkbmap -model abnt2 -layout br -variant abnt2')
end;
procedure TForm1.ButtonLaunchTerminalClick(Sender: TObject);
begin
LaunchAppFork('terminator');
end;
procedure TForm1.TrayIcon1Click(Sender: TObject);
begin
if Form1.WindowState = TWindowState.wsNormal then
begin
Form1.Hide;
Form1.WindowState := TWindowState.wsMinimized
end
else
begin
Form1.Show;
Form1.WindowState := TWindowState.wsNormal;
end;
end;
end.
|
unit JclInstall;
interface
{$I jcl.inc}
uses
Windows, SysUtils, Classes, ComCtrls, JediInstallIntf;
type
TJclInstall = class (TInterfacedObject, IJediInstall)
private
FJclPath: string;
FJclSourcePath: string;
FClxDialogFileName: string;
FVclDialogFileName: string;
FVclDialogSendFileName: string;
FClxDialogIconFileName: string;
FVclDialogIconFileName: string;
FVclDialogSendIconFileName: string;
FJclChmHelpFileName: string;
FJclHlpHelpFileName: string;
FJclReadmeFileName: string;
FTool: IJediInstallTool;
public
function InitInformation(const ApplicationFileName: string): Boolean;
function Install: Boolean;
function PopulateTreeView(Nodes: TTreeNodes; VersionNumber: Integer; Page: TTabSheet): Boolean;
function SelectedNodeCollapsing(Node: TTreeNode): Boolean;
procedure SelectedNodeChanged(Node: TTreeNode);
procedure SetTool(const Value: IJediInstallTool);
property Tool: IJediInstallTool read FTool;
end;
function CreateJediInstall: IJediInstall;
implementation
uses
JclBase, JclFileUtils, JclStrings, DelphiInstall;
const
DialogsPath = 'examples\debugextension\dialog\';
ClxDialogFileName = 'ClxExceptDlg.pas';
VclDialogFileName = 'ExceptDlg.pas';
VclDlgSndFileName = 'ExceptDlgMail.pas';
ClxDialogName = 'CLX Exception Dialog';
VclDialogName = 'Exception Dialog';
VclDialogNameSend = 'Exception Dialog with Send';
DialogDescription = 'JCL Application exception dialog';
DialogAuthor = 'Project JEDI';
DialogPage = 'Dialogs';
JclChmHelpFile = 'Help\JCLHelp.chm';
JclHlpHelpFile = 'Help\JCLHelp.hlp';
JclHelpTitle = 'JCL 1.20 Help';
JclHelpIndexName = 'Jedi Code Library Reference';
HHFileName = 'HH.EXE';
JclRuntimeDpk = 'packages\DJCL%d0.dpk';
JclIdeDebugDpk = 'examples\debugextension\JclDebugIde%d0.dpk';
JclIdeAnalyzerDpk = 'examples\projectanalyzer\ProjectAnalyzer%d0.dpk';
JclIdeFavoriteDpk = 'examples\idefavopendialogs\IdeOpenDlgFavorite%d0.dpk';
JclIdeThrNamesDpk = 'examples\debugextension\threadnames\ThreadNameExpert%d0.dpk';
// Feature IDs
FID_JCL = $02000000;
FID_JCL_Env = FID_JCL + $00010000;
FID_JCL_EnvLibPath = FID_JCL + $00010100;
FID_JCL_Help = FID_JCL + $00020000;
FID_JCL_HelpHlp = FID_JCL + $00020100;
FID_JCL_HelpChm = FID_JCL + $00020200;
FID_JCL_Experts = FID_JCL + $00030000;
FID_JCL_ExpertDebug = FID_JCL + $00030100;
FID_JCL_ExpertAnalyzer = FID_JCL + $00030200;
FID_JCL_ExpertFavorite = FID_JCL + $00030300;
FID_JCL_ExpertsThrNames = FID_JCL + $00030400;
FID_JCL_ExcDialog = FID_JCL + $00040000;
FID_JCL_ExcDialogVCL = FID_JCL + $00040100;
FID_JCL_ExcDialogVCLSnd = FID_JCL + $00040200;
FID_JCL_ExcDialogCLX = FID_JCL + $00040300;
// Products
RsJCL = 'JEDI Code Library';
// Common features
RsEnvironment = 'Environment';
RsEnvLibPath = 'Include source code location to IDE Library Path';
RsHelpFiles = 'Help files';
RsIdeExperts = 'IDE experts';
RsIdeHelpHlp = 'Add help file to Delphi IDE help system';
RsIdeHelpChm = 'Add HTML help to the Tools menu';
// Product specific features
RsJCLExceptDlg = 'Sample Exception Dialogs in the Object Reporitory';
RsJCLDialogVCL = 'VCL Exception Dialog';
RsJCLDialogVCLSnd = 'VCL Exception Dialog with Send button';
RsJCLDialogCLX = 'CLX Exception Dialog';
RsJCLIdeDebug = 'Debug Extension';
RsJCLIdeAnalyzer = 'Project Analyzer';
RsJCLIdeFavorite = 'Favorite combobox in Open/Save dialogs';
RsJCLIdeThrNames = 'Displaying thread names in Thread Status window';
resourcestring
RsSourceLibHint = 'Adds "%s" to the Library Path';
RsStatusMessage = 'Installing %s ...';
RsInstallFailed = 'Installation of %s failed';
function CreateJediInstall: IJediInstall;
begin
Result := TJclInstall.Create as IJediInstall;
end;
{ TJclInstall }
function TJclInstall.InitInformation(const ApplicationFileName: string): Boolean;
var
ReadmeText: string;
begin
FJclPath := PathAddSeparator(PathCanonicalize(PathExtractFileDirFixed(ApplicationFileName) + '..'));
FJclSourcePath := FJclPath + 'Source';
FClxDialogFileName := AnsiUpperCase(FJclPath + DialogsPath + ClxDialogFileName);
FVclDialogFileName := AnsiUpperCase(FJclPath + DialogsPath + VclDialogFileName);
FVclDialogSendFileName := AnsiUpperCase(FJclPath + DialogsPath + VclDlgSndFileName);
FClxDialogIconFileName := ChangeFileExt(FClxDialogFileName, '.ICO');
FVclDialogIconFileName := ChangeFileExt(FVclDialogFileName, '.ICO');
FVclDialogSendIconFileName := ChangeFileExt(FVclDialogSendFileName, '.ICO');
FJclChmHelpFileName := FJclPath + JclChmHelpFile;
FJclHlpHelpFileName := FJclPath + JclHlpHelpFile;
if not FileExists(FJclChmHelpFileName) then
FJclChmHelpFileName := '';
if not FileExists(FJclHlpHelpFileName) then
FJclHlpHelpFileName := '';
// Reset ReadOnly flag for dialog forms
FileSetAttr(FClxDialogFileName, faArchive);
FileSetAttr(ChangeFileExt(FClxDialogFileName, '.xfm'), faArchive);
FileSetAttr(FVclDialogFileName, faArchive);
FileSetAttr(ChangeFileExt(FVclDialogFileName, '.dfm'), faArchive);
FileSetAttr(FVclDialogSendFileName, faArchive);
FileSetAttr(ChangeFileExt(FVclDialogSendFileName, '.dfm'), faArchive);
Result := (FileExists(FClxDialogFileName) and FileExists(FVclDialogFileName) and
FileExists(FClxDialogIconFileName) and FileExists(FVclDialogIconFileName));
FJclReadmeFileName := PathAddSeparator(FJclPath) + 'Readme.txt';
if FileExists(FJclReadmeFileName) then
begin
ReadmeText := FileToString(FJclReadmeFileName);
Tool.UpdateInfo(4, ReadmeText);
Tool.UpdateInfo(5, ReadmeText);
Tool.UpdateInfo(6, ReadmeText);
Tool.UpdateInfo(7, ReadmeText);
end;
end;
function TJclInstall.Install: Boolean;
var
Installation: TJclDelphiInstallation;
procedure AddHelpToDelphiHelp;
begin
Installation.OpenHelp.AddHelpFile(FJclHlpHelpFileName, JclHelpIndexName);
end;
procedure AddHelpToIdeTools;
var
ToolsIndex: Integer;
begin
if Installation.IdeTools.IndexOfTitle(JclHelpTitle) = -1 then
begin
ToolsIndex := Installation.IdeTools.Count;
Installation.IdeTools.Count := ToolsIndex + 1;
Installation.IdeTools.Title[ToolsIndex] := JclHelpTitle;
Installation.IdeTools.Path[ToolsIndex] := HHFileName;
Installation.IdeTools.Parameters[ToolsIndex] := StrDoubleQuote(FJclChmHelpFileName);
Installation.IdeTools.WorkingDir[ToolsIndex] := FJclPath;
end;
end;
function InstallPackage(const Name: string): Boolean;
var
PackageFileName: string;
begin
PackageFileName := FJclPath + Format(Name, [Installation.VersionNumber]);
Tool.UpdateStatus(Format(RsStatusMessage, [ExtractFileName(PackageFileName)]));
Result := Installation.Compiler.InstallPackage(PackageFileName, Tool.BPLPath(Installation.VersionNumber),
Tool.DCPPath(Installation.VersionNumber));
Tool.UpdateStatus('');
if not Result then
Tool.MessageBox(Format(RsInstallFailed, [PackageFileName]), MB_OK or MB_ICONERROR);
end;
procedure CleanupRepository;
begin
if Tool.FeatureChecked(FID_JCL, Installation.VersionNumber) then
begin
Installation.Repository.RemoveObjects(DialogsPath, VclDialogFileName, DelphiRepositoryFormTemplate);
Installation.Repository.RemoveObjects(DialogsPath, ClxDialogFileName, DelphiRepositoryFormTemplate);
Installation.Repository.RemoveObjects(DialogsPath, VclDlgSndFileName, DelphiRepositoryFormTemplate);
end;
end;
procedure D4Install;
begin
Tool.UpdateStatus(Format(RsStatusMessage, [Installation.Name]));
CleanupRepository;
if Tool.FeatureChecked(FID_JCL_EnvLibPath, Installation.VersionNumber) then
Installation.AddToLibrarySearchPath(FJclSourcePath);
if Tool.FeatureChecked(FID_JCL_HelpHlp, Installation.VersionNumber) then
AddHelpToDelphiHelp;
if Tool.FeatureChecked(FID_JCL_HelpChm, Installation.VersionNumber) then
AddHelpToIdeTools;
if Tool.FeatureChecked(FID_JCL_ExcDialogVCL, Installation.VersionNumber) then
Installation.Repository.AddObject(FVclDialogFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), VclDialogName, FVclDialogIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerDfm);
if Tool.FeatureChecked(FID_JCL_ExcDialogVCLSnd, Installation.VersionNumber) then
Installation.Repository.AddObject(FVclDialogSendFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), VclDialogNameSend, FVclDialogSendIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerDfm, FVclDialogFileName);
if Tool.FeatureChecked(FID_JCL_Experts, Installation.VersionNumber) then
InstallPackage(JclRuntimeDpk);
if Tool.FeatureChecked(FID_JCL_ExpertDebug, Installation.VersionNumber) then
InstallPackage(JclIdeDebugDpk);
if Tool.FeatureChecked(FID_JCL_ExpertAnalyzer, Installation.VersionNumber) then
InstallPackage(JclIdeAnalyzerDpk);
if Tool.FeatureChecked(FID_JCL_ExpertFavorite, Installation.VersionNumber) then
InstallPackage(JclIdeFavoriteDpk);
if Tool.FeatureChecked(FID_JCL_ExpertsThrNames, Installation.VersionNumber) then
InstallPackage(JclIdeThrNamesDpk);
end;
procedure D5Install;
begin
Tool.UpdateStatus(Format(RsStatusMessage, [Installation.Name]));
CleanupRepository;
if Tool.FeatureChecked(FID_JCL_EnvLibPath, Installation.VersionNumber) then
Installation.AddToLibrarySearchPath(FJclSourcePath);
if Tool.FeatureChecked(FID_JCL_HelpHlp, Installation.VersionNumber) then
AddHelpToDelphiHelp;
if Tool.FeatureChecked(FID_JCL_HelpChm, Installation.VersionNumber) then
AddHelpToIdeTools;
if Tool.FeatureChecked(FID_JCL_ExcDialogVCL, Installation.VersionNumber) then
Installation.Repository.AddObject(FVclDialogFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), VclDialogName, FVclDialogIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerDfm);
if Tool.FeatureChecked(FID_JCL_ExcDialogVCLSnd, Installation.VersionNumber) then
Installation.Repository.AddObject(FVclDialogSendFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), VclDialogNameSend, FVclDialogSendIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerDfm, FVclDialogFileName);
if Tool.FeatureChecked(FID_JCL_Experts, Installation.VersionNumber) then
InstallPackage(JclRuntimeDpk);
if Tool.FeatureChecked(FID_JCL_ExpertDebug, Installation.VersionNumber) then
InstallPackage(JclIdeDebugDpk);
if Tool.FeatureChecked(FID_JCL_ExpertAnalyzer, Installation.VersionNumber) then
InstallPackage(JclIdeAnalyzerDpk);
if Tool.FeatureChecked(FID_JCL_ExpertFavorite, Installation.VersionNumber) then
InstallPackage(JclIdeFavoriteDpk);
if Tool.FeatureChecked(FID_JCL_ExpertsThrNames, Installation.VersionNumber) then
InstallPackage(JclIdeThrNamesDpk);
end;
procedure D6Install;
begin
Tool.UpdateStatus(Format(RsStatusMessage, [Installation.Name]));
CleanupRepository;
if Tool.FeatureChecked(FID_JCL_EnvLibPath, Installation.VersionNumber) then
Installation.AddToLibrarySearchPath(FJclSourcePath);
if Tool.FeatureChecked(FID_JCL_HelpHlp, Installation.VersionNumber) then
AddHelpToDelphiHelp;
if Tool.FeatureChecked(FID_JCL_HelpChm, Installation.VersionNumber) then
AddHelpToIdeTools;
if Tool.FeatureChecked(FID_JCL_ExcDialogVCL, Installation.VersionNumber) then
Installation.Repository.AddObject(FVclDialogFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), VclDialogName, FVclDialogIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerDfm);
if Tool.FeatureChecked(FID_JCL_ExcDialogVCLSnd, Installation.VersionNumber) then
Installation.Repository.AddObject(FVclDialogSendFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), VclDialogNameSend, FVclDialogSendIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerDfm, FVclDialogFileName);
if Tool.FeatureChecked(FID_JCL_ExcDialogCLX, Installation.VersionNumber) then
Installation.Repository.AddObject(FClxDialogFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), ClxDialogName, FClxDialogIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerXfm);
if Tool.FeatureChecked(FID_JCL_Experts, Installation.VersionNumber) then
InstallPackage(JclRuntimeDpk);
if Tool.FeatureChecked(FID_JCL_ExpertDebug, Installation.VersionNumber) then
InstallPackage(JclIdeDebugDpk);
if Tool.FeatureChecked(FID_JCL_ExpertAnalyzer, Installation.VersionNumber) then
InstallPackage(JclIdeAnalyzerDpk);
if Tool.FeatureChecked(FID_JCL_ExpertFavorite, Installation.VersionNumber) then
InstallPackage(JclIdeFavoriteDpk);
if Tool.FeatureChecked(FID_JCL_ExpertsThrNames, Installation.VersionNumber) then
InstallPackage(JclIdeThrNamesDpk);
end;
procedure D7Install;
begin
Tool.UpdateStatus(Format(RsStatusMessage, [Installation.Name]));
CleanupRepository;
if Tool.FeatureChecked(FID_JCL_EnvLibPath, Installation.VersionNumber) then
Installation.AddToLibrarySearchPath(FJclSourcePath);
if Tool.FeatureChecked(FID_JCL_HelpHlp, Installation.VersionNumber) then
AddHelpToDelphiHelp;
if Tool.FeatureChecked(FID_JCL_HelpChm, Installation.VersionNumber) then
AddHelpToIdeTools;
if Tool.FeatureChecked(FID_JCL_ExcDialogVCL, Installation.VersionNumber) then
Installation.Repository.AddObject(FVclDialogFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), VclDialogName, FVclDialogIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerDfm);
if Tool.FeatureChecked(FID_JCL_ExcDialogVCLSnd, Installation.VersionNumber) then
Installation.Repository.AddObject(FVclDialogSendFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), VclDialogNameSend, FVclDialogSendIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerDfm, FVclDialogFileName);
if Tool.FeatureChecked(FID_JCL_ExcDialogCLX, Installation.VersionNumber) then
Installation.Repository.AddObject(FClxDialogFileName, DelphiRepositoryFormTemplate,
Installation.Repository.FindPage(DialogPage, 1), ClxDialogName, FClxDialogIconFileName,
DialogDescription, DialogAuthor, DelphiRepositoryDesignerXfm);
if Tool.FeatureChecked(FID_JCL_Experts, Installation.VersionNumber) then
InstallPackage(JclRuntimeDpk);
if Tool.FeatureChecked(FID_JCL_ExpertDebug, Installation.VersionNumber) then
InstallPackage(JclIdeDebugDpk);
if Tool.FeatureChecked(FID_JCL_ExpertAnalyzer, Installation.VersionNumber) then
InstallPackage(JclIdeAnalyzerDpk);
if Tool.FeatureChecked(FID_JCL_ExpertFavorite, Installation.VersionNumber) then
InstallPackage(JclIdeFavoriteDpk);
end;
begin
Result := True;
try
Installation := Tool.DelphiInstallations.InstallationFromVersion[4];
if Assigned(Installation) and Installation.Valid then
D4Install;
Installation := Tool.DelphiInstallations.InstallationFromVersion[5];
if Assigned(Installation) and Installation.Valid then
D5Install;
Installation := Tool.DelphiInstallations.InstallationFromVersion[6];
if Assigned(Installation) and Installation.Valid then
D6Install;
Installation := Tool.DelphiInstallations.InstallationFromVersion[7];
if Assigned(Installation) and Installation.Valid then
D7Install;
finally
Tool.UpdateStatus('');
end;
end;
function TJclInstall.PopulateTreeView(Nodes: TTreeNodes; VersionNumber: Integer; Page: TTabSheet): Boolean;
var
InstallationNode, ProductNode, TempNode: TTreeNode;
Installation: TJclDelphiInstallation;
function AddNode(Parent: TTreeNode; const Caption: string; FeatureID: Cardinal): TTreeNode;
begin
FeatureID := FeatureID or FID_Checked;
Result := Nodes.AddChildObject(Parent, Caption, Pointer(FeatureID));
Result.ImageIndex := IcoChecked;
Result.SelectedIndex := IcoChecked;
end;
begin
Installation := Tool.DelphiInstallations.InstallationFromVersion[VersionNumber];
Result := Assigned(Installation) and Installation.Valid;
Nodes.BeginUpdate;
try
if Result then
begin
InstallationNode := AddNode(nil, Installation.Name, 0);
InstallationNode.StateIndex := 0;
// JCL
ProductNode := AddNode(InstallationNode, RsJCL, FID_JCL);
TempNode := AddNode(ProductNode, RsEnvironment, FID_JCL_Env);
AddNode(TempNode, RsEnvLibPath, FID_JCL_EnvLibPath);
if (FJclHlpHelpFileName <> '') or (FJclChmHelpFileName <> '') then
begin
TempNode := AddNode(ProductNode, RsHelpFiles, FID_JCL_Help);
if FJclHlpHelpFileName <> '' then
AddNode(TempNode, RsIdeHelpHlp, FID_JCL_HelpHlp);
if FJclChmHelpFileName <> '' then
AddNode(TempNode, RsIdeHelpChm, FID_JCL_HelpChm);
end;
TempNode := AddNode(ProductNode, RsJCLExceptDlg, FID_JCL_ExcDialog);
AddNode(TempNode, RsJCLDialogVCL, FID_JCL_ExcDialogVCL);
AddNode(TempNode, RsJCLDialogVCLSnd, FID_JCL_ExcDialogVCLSnd);
if (Installation.VersionNumber >= 6) and (Installation.Edition <> deSTD) then
AddNode(TempNode, RsJCLDialogCLX, FID_JCL_ExcDialogCLX);
TempNode := AddNode(ProductNode, RsIdeExperts, FID_JCL_Experts);
AddNode(TempNode, RsJCLIdeDebug, FID_JCL_ExpertDebug);
AddNode(TempNode, RsJCLIdeAnalyzer, FID_JCL_ExpertAnalyzer);
AddNode(TempNode, RsJCLIdeFavorite, FID_JCL_ExpertFavorite);
if Installation.VersionNumber <= 6 then
AddNode(TempNode, RsJCLIdeThrNames, FID_JCL_ExpertsThrNames);
InstallationNode.Expand(True);
end;
finally
Nodes.EndUpdate;
end;
end;
procedure TJclInstall.SelectedNodeChanged(Node: TTreeNode);
begin
end;
function TJclInstall.SelectedNodeCollapsing(Node: TTreeNode): Boolean;
begin
Result := False;
end;
procedure TJclInstall.SetTool(const Value: IJediInstallTool);
begin
FTool := Value;
end;
end.
|
unit FormReplaceColour;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Voxel_Engine, BasicDataTypes, palette, voxel,
mouse, VoxelUndoEngine;
Type
TReplaceColourData = record
Col1 : byte;
Col2 : byte;
end;
type
TFrmReplaceColour = class(TForm)
Bevel3: TBevel;
PanelTitle: TPanel;
Image1: TImage;
Label5: TLabel;
Label6: TLabel;
Bevel4: TBevel;
Panel4: TPanel;
BtOK: TButton;
BtCancel: TButton;
Panel5: TPanel;
Label1: TLabel;
Label2: TLabel;
LabelReplace: TLabel;
LabelWith: TLabel;
PanelReplace: TPanel;
PanelWith: TPanel;
ListBox1: TListBox;
BtAdd: TButton;
BtEdit: TButton;
BtDelete: TButton;
Bevel1: TBevel;
cnvPalette: TPaintBox;
pnlPalette: TPanel;
lblActiveColour: TLabel;
pnlActiveColour: TPanel;
procedure FormDestroy(Sender: TObject);
procedure cnvPalettePaint(Sender: TObject);
procedure PanelReplaceClick(Sender: TObject);
procedure PanelWithClick(Sender: TObject);
procedure cnvPaletteMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure BtAddClick(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
procedure BtEditClick(Sender: TObject);
procedure BtDeleteClick(Sender: TObject);
procedure cnvPaletteMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BtOKClick(Sender: TObject);
procedure BtCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ReplaceColourData,TempColourData : array of TReplaceColourData;
Data_no : integer;
Replace : integer;
ReplaceW : integer;
end;
implementation
uses FormMain, GlobalVars, BasicVXLSETypes;
{$R *.dfm}
procedure TFrmReplaceColour.cnvPalettePaint(Sender: TObject);
begin
PaintPalette(cnvPalette, false);
end;
procedure TFrmReplaceColour.PanelReplaceClick(Sender: TObject);
begin
PanelReplace.BevelOuter := bvRaised;
PanelWith.BevelOuter := bvLowered;
end;
procedure TFrmReplaceColour.PanelWithClick(Sender: TObject);
begin
PanelWith.BevelOuter := bvRaised;
PanelReplace.BevelOuter := bvLowered;
end;
procedure TFrmReplaceColour.cnvPaletteMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
colwidth, rowheight: Real;
i, j, idx: Integer;
begin
If not isEditable then exit;
colwidth := cnvPalette.Width / 8;
rowheight := cnvPalette.Height / 32;
i := Trunc(X / colwidth);
j := Trunc(Y / rowheight);
idx := (i * 32) + j;
if SpectrumMode = ModeColours then
begin
if PanelReplace.BevelOuter = bvRaised then
begin
Replace := idx;
PanelReplace.Color := FrmMain.Document.Palette^[idx];
LabelReplace.Caption := inttostr(idx);
PanelWith.BevelOuter := bvRaised;
PanelReplace.BevelOuter := bvLowered;
end
else
begin
ReplaceW := idx;
PanelWith.Color := FrmMain.Document.Palette^[idx];
LabelWith.Caption := inttostr(idx);
PanelReplace.BevelOuter := bvRaised;
PanelWith.BevelOuter := bvLowered;
end;
end
else if not (idx > ActiveNormalsCount-1) then
if PanelReplace.BevelOuter = bvRaised then
begin
Replace := idx;
PanelReplace.Color := GetVXLPaletteColor(idx);
LabelReplace.Caption := inttostr(idx);
PanelWith.BevelOuter := bvRaised;
PanelReplace.BevelOuter := bvLowered;
end
else
begin
ReplaceW := idx;
PanelWith.Color := GetVXLPaletteColor(idx);
LabelWith.Caption := inttostr(idx);
PanelReplace.BevelOuter := bvRaised;
PanelWith.BevelOuter := bvLowered;
end;
end;
procedure TFrmReplaceColour.FormCreate(Sender: TObject);
begin
cnvPalette.Cursor := MouseBrush;
PanelTitle.DoubleBuffered := true;
Replace := -1;
ReplaceW := -1;
end;
procedure TFrmReplaceColour.BtAddClick(Sender: TObject);
var
x : integer;
B : Boolean;
begin
if (Replace = -1) or (ReplaceW = -1) then
begin
Messagebox(0,'Please Select 2 Colours','Colour Error',0);
exit;
end;
B := false;
if Replace = ReplaceW then exit; // U can't replace a colour with its self... pointless
if Data_no > 0 then
for x := 0 to Data_no-1 do
if b = false then
if ReplaceColourData[x].Col1 = Replace then
B := true;
if B = true then exit; // Stops pointless additions
inc(Data_no);
SetLength(ReplaceColourData,Data_no);
ReplaceColourData[Data_no-1].Col1 := Replace;
ReplaceColourData[Data_no-1].Col2 := ReplaceW;
ListBox1.Items.Add(Inttostr(Replace) + ' -> ' + Inttostr(ReplaceW));
end;
procedure TFrmReplaceColour.ListBox1Click(Sender: TObject);
begin
if Data_no > 0 then
begin
Replace := ReplaceColourData[ListBox1.ItemIndex].Col1;
ReplaceW := ReplaceColourData[ListBox1.ItemIndex].Col2;
PanelReplace.Color := GetVXLPaletteColor(Replace);
PanelWith.Color := GetVXLPaletteColor(ReplaceW);
LabelReplace.Caption := inttostr(Replace);
LabelWith.Caption := inttostr(ReplaceW);
end;
end;
procedure TFrmReplaceColour.BtEditClick(Sender: TObject);
begin
if Data_no > 0 then
begin
ReplaceColourData[ListBox1.ItemIndex].Col1 := Replace;
ReplaceColourData[ListBox1.ItemIndex].Col2 := ReplaceW;
ListBox1.Items.Strings[ListBox1.ItemIndex] := Inttostr(Replace) + ' -> ' + Inttostr(ReplaceW);
end;
end;
procedure TFrmReplaceColour.BtDeleteClick(Sender: TObject);
var
x,c,ItemIndex : integer;
begin
if data_no < 1 then exit;
// Get victim
ItemIndex := ListBox1.ItemIndex;
// Copy replace data to tempcolour data.
Setlength(TempColourData,data_no);
for x := Low(TempColourData) to High(TempColourData) do
begin
TempColourData[x].Col1 := ReplaceColourData[x].Col1;
TempColourData[x].Col2 := ReplaceColourData[x].Col2;
end;
// Reduce Temp colour data.
Dec(data_no);
Setlength(ReplaceColourData,data_no);
// Clear list.
ListBox1.Items.Clear;
// If empty, leaves.
if data_no < 1 then
begin
Setlength(TempColourData,0);
exit;
end;
// else, rebuid the list.
C := 0;
X := 0;
Repeat
if x <> ItemIndex then
begin
ReplaceColourData[c].Col1 := TempColourData[x].Col1;
ReplaceColourData[c].Col2 := TempColourData[x].Col2;
ListBox1.Items.Add(Inttostr(TempColourData[x].Col1) + ' -> ' + Inttostr(TempColourData[x].Col2));
inc(c);
end;
inc(x);
until c = data_no;
// and wipe tem colour data.
Setlength(TempColourData,0);
end;
procedure TFrmReplaceColour.cnvPaletteMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
colwidth, rowheight: Real;
i, j, idx: Integer;
begin
If not isEditable then exit;
colwidth := cnvPalette.Width / 8;
rowheight := cnvPalette.Height / 32;
i := Trunc(X / colwidth);
j := Trunc(Y / rowheight);
idx := (i * 32) + j;
if (SpectrumMode = ModeNormals) and (idx > ActiveNormalsCount-1) then exit;
lblActiveColour.Caption := inttostr(idx);
pnlActiveColour.Color := GetVXLPaletteColor(idx);
end;
procedure TFrmReplaceColour.FormClose(Sender: TObject;
var
Action: TCloseAction);
begin
data_no := 0;
Setlength(ReplaceColourData,0);
end;
procedure TFrmReplaceColour.BtOKClick(Sender: TObject);
var
ColourArray : array [0..255] of Byte;
x,y,z : integer;
v : TVoxelUnPacked;
begin
if data_no < 1 then Close; // nothing to do, so close.
BtOK.Enabled := false;
CreateVXLRestorePoint(FrmMain.Document.ActiveSection^,Undo); // Save Undo
For x := 0 to 255 do
ColourArray[x] := x;
For x := 0 to data_no-1 do
ColourArray[ReplaceColourData[x].Col1] := ReplaceColourData[x].Col2;
For x := 0 to FrmMain.Document.ActiveSection^.Tailer.XSize -1 do
For y := 0 to FrmMain.Document.ActiveSection^.Tailer.YSize -1 do
For z := 0 to FrmMain.Document.ActiveSection^.Tailer.ZSize -1 do
begin
FrmMain.Document.ActiveSection^.GetVoxel(x,y,z,v);
if SpectrumMode = ModeColours then
V.Colour := ColourArray[V.Colour]
else
V.Normal := ColourArray[V.Normal];
FrmMain.Document.ActiveSection^.SetVoxel(x,y,z,v);
end;
FrmMain.RefreshAll;
FrmMain.UpdateUndo_RedoState;
FrmMain.SetVoxelChanged(true);
Close;
end;
procedure TFrmReplaceColour.BtCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFrmReplaceColour.FormDestroy(Sender: TObject);
begin
SetLength(ReplaceColourData,0);
SetLength(TempColourData,0);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSLPostBlurShader <p>
A shader that blurs the entire scene.<p>
<b>History : </b><font size=-1><ul>
<li>22/04/10 - Yar - Fixes after GLState revision
< Added VectorTypes to uses
<li>16/04/07 - DaStr - Shader made ATI compatible
<li>05/04/07 - DaStr - Initial version (contributed to GLScene)
Previous version history:
v1.0 04 November '2006 Creation (based on RenderMonkey demo)
v1.1 04 March '2007 IGLPostShader support added
v1.2 30 March '2007 TGLCustomGLSLPostBlurShaderSceneObject removed
Shader now supports GL_TEXTURE_RECTANGLE_ARB
}
unit GLSLPostBlurShader;
interface
{$I GLScene.inc}
uses
// VCL
Classes,
// GLScene
GLTexture, GLScene, GLVectorGeometry, GLContext,
GLSLShader, GLCustomShader, GLRenderContextInfo, GLTextureFormat;
type
TGLCustomGLSLPostBlurShader = class(TGLCustomGLSLShader, IGLPostShader)
private
FThreshold: Single;
// Implementing IGLPostShader.
procedure DoUseTempTexture(const TempTexture: TGLTextureHandle;
TextureTarget: TGLTextureTarget);
function GetTextureTarget: TGLTextureTarget;
function StoreThreshold: Boolean;
protected
procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override;
function DoUnApply(var rci: TRenderContextInfo): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
property Threshold: Single read FThreshold write FThreshold stored StoreThreshold;
end;
TGLSLPostBlurShader = class(TGLCustomGLSLPostBlurShader)
published
property Threshold;
end;
implementation
uses
GLVectorTypes;
{ TGLCustomGLSLPostBlurShader }
constructor TGLCustomGLSLPostBlurShader.Create(
AOwner: TComponent);
begin
inherited;
with VertexProgram.Code do
begin
Add('varying vec2 vTexCoord; ');
Add(' ');
Add('void main(void) ');
Add('{ ');
Add(' ');
Add(' // Clean up inaccuracies ');
Add(' vec2 Position; ');
Add(' Position.xy = sign(gl_Vertex.xy); ');
Add(' ');
Add(' gl_Position = vec4(Position.xy, 0.0, 1.0); ');
Add(' vTexCoord = Position.xy *.5 + .5; ');
Add(' ');
Add('} ');
end;
with FragmentProgram.Code do
begin
Add('uniform float threshold; ');
Add('uniform vec2 ScreenExtents; ');
Add('uniform sampler2DRect Image; ');
Add(' ');
Add('varying vec2 vTexCoord; ');
Add(' ');
Add('void main() ');
Add('{ ');
Add(' ');
Add(' vec2 samples[8]; ');
Add(' vec2 vTexCoordScr = vTexCoord * ScreenExtents; ');
Add(' ');
Add(' samples[0] = vTexCoordScr + vec2(-1.0, -1.0); ');
Add(' samples[1] = vTexCoordScr + vec2( 0.0, -1.0); ');
Add(' samples[2] = vTexCoordScr + vec2( 1.0, -1.0); ');
Add(' samples[3] = vTexCoordScr + vec2(-1.0, 0.0); ');
Add(' samples[4] = vTexCoordScr + vec2( 1.0, 0.0); ');
Add(' samples[5] = vTexCoordScr + vec2(-1.0, 1.0); ');
Add(' samples[6] = vTexCoordScr + vec2( 0.0, 1.0); ');
Add(' samples[7] = vTexCoordScr + vec2( 1.0, 1.0); ');
Add(' ');
Add(' vec4 sample = texture2DRect(Image, vTexCoordScr); ');
Add(' ');
Add(' // Neighborhood average ');
Add(' vec4 avg = sample; ');
Add(' for (int i = 0; i < 8; i++) ');
Add(' { ');
Add(' avg += texture2DRect(Image, samples[i]); ');
Add(' } ');
Add(' ');
Add(' ');
Add(' avg /= 9.0; ');
Add(' ');
Add(' // If the difference between the average and the sample is ');
Add(' // large, we''ll assume it''s noise. ');
Add(' vec4 diff = abs(sample - avg); ');
Add(' float sel = float(dot(diff, vec4(0.25)) > threshold); ');
Add(' ');
Add(' gl_FragColor = mix(sample, avg, sel); ');
Add('} ');
end;
FThreshold := 0.1;
end;
procedure TGLCustomGLSLPostBlurShader.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
begin
GetGLSLProg.UseProgramObject;
GetGLSLProg.Uniform1f['threshold'] := FThreshold;
GetGLSLProg.Uniform2f['ScreenExtents'] := Vector2fMake(rci.viewPortSize.cx, rci.viewPortSize.cy);
end;
function TGLCustomGLSLPostBlurShader.DoUnApply(
var rci: TRenderContextInfo): Boolean;
begin
rci.GLStates.ActiveTexture := 0;
GetGLSLProg.EndUseProgramObject;
Result := False;
end;
procedure TGLCustomGLSLPostBlurShader.DoUseTempTexture(
const TempTexture: TGLTextureHandle; TextureTarget: TGLTextureTarget);
begin
Param['Image'].AsCustomTexture[2, TextureTarget] := TempTexture.Handle;
end;
function TGLCustomGLSLPostBlurShader.GetTextureTarget: TGLTextureTarget;
begin
Result := ttTextureRect;
end;
function TGLCustomGLSLPostBlurShader.StoreThreshold: Boolean;
begin
Result := Abs(FThreshold - 0.1) > 0.00001;
end;
end.
|
unit uMultiCore;
interface
uses Windows,Classes;
const _MultiCoreRotateCycle=16;
// function type
type
TMultiCoreThreadFunc = procedure(ptr:Pointer);
TMultiCoreThreadEvent = procedure(ptr:pointer) of object;
type
// TemaphoreClass
TMultiCoreSemaphore=class
protected
//FSema : THANDLE;
FCS : TRTLCriticalSection;
public
constructor Create(name:String='');
destructor Destroy; override;
procedure Lock(t:DWORD=$FFFFFF);
procedure UnLock;
end;
// MultiCore Thread Class
TMultiCoreThreadData=packed record
CoreNo : Integer;
FuncPtr : TMultiCoreThreadFunc;
EventPtr : TMultiCoreThreadEvent;
UserPtr : Pointer;
end;
TMultiCoreThread=class(TThread)
protected
FThreadCount,FThreadIndex : Integer;
// task array
FTasks : array of TMultiCoreThreadData;
FTaskCount,FEntryCount: Integer;
FSem : TMultiCoreSemaphore; // sync between mainthread and subthread
FWaitSem : TMultiCoreSemaphore; // wait(satndby) semaphore
FStart : Boolean; // task start flag. polling.
FFinished : boolean; // task finished flag. polling.
FWeight : integer; // task virtual weight.
procedure TaskArrayResize(need:integer);
procedure TaskExcute;
procedure Execute; override;
public
constructor Create(aThreadIndex,aThreadCount:integer);
destructor Destroy; override;
procedure Clear;
procedure TaskStart;
procedure TaskSync(sleeptime:integer=0);
procedure TaskAdd(func:TMultiCoreThreadFunc; ptr:Pointer); overload;
procedure TaskAdd(event:TMultiCoreThreadEvent; ptr:Pointer); overload;
property Weight:integer read FWeight write FWeight;
end;
// Manager Class
TMultiCoreThreadManager=class
protected
// thread
FThreadCount : Integer;
FThread : array of TMultiCoreThread;
FCoreLock : Boolean;
FSingleCoreProcess : Boolean;
FRotateCycle : Integer;
FTaskRotate : Boolean;
procedure CreateThread(n:Integer);
procedure FreeThread;
function GetLightWeightCore(FuncWeight:integer):integer;
public
constructor Create(ThreadCount:Integer=1; CoreLock:Boolean=TRUE);
destructor Destroy; override;
procedure Clear;
procedure Start(SingleCoreProcess:Boolean=FALSE);
procedure Sync(sleeptime:Integer=0);
procedure Add(func:TMultiCoreThreadFunc; ptr:Pointer; FuncWeight:Integer=1; ThreadIndex:Integer=-1); overload;
procedure Add(event:TMultiCoreThreadEvent; ptr:Pointer; FuncWeight:Integer=1; ThreadIndex:Integer=-1); overload;
property Count:Integer read FThreadCount;
property TaskRotate:Boolean read FTaskRotate write FTaskRotate; // rotation use core index.
end;
//get core count function
function _MultiCoreGetCoreCount:Integer;
//initialize
procedure _MultiCoreInitialize(ThreadCount:Integer=2; CoreLock:Boolean=true); // corelock=false : normal thread mode.
//finalize
procedure _MultiCoreFinalize;
var
_MultiCoreManager:TMultiCoreThreadManager = nil;
_MultiCore_IdealProcessorMargin:Integer = 1; // ThreadCount >= CPU.CoreCount-Margin ... thread force lock each core.
_MultiCore_SpinOutCount:integer = 500; // CriticalSection SpinOutTime.
implementation
procedure _MultiCoreInitialize(ThreadCount:Integer; CoreLock:Boolean);
var
cores : integer;
begin
cores := _MultiCoreGetCoreCount;
if ThreadCount > cores then ThreadCount := cores;
_MultiCoreManager := TMultiCoreThreadManager.Create(ThreadCount,CoreLock);
end;
procedure _MultiCoreFinalize;
begin
_MultiCoreManager.Free;
_MultiCoreManager := nil;
end;
function _MultiCoreGetCoreCount:Integer;
function inCoreCount(const r:SYSTEM_INFO):Integer;
var
n,a,i : Integer;
nn : Integer;
begin
nn := 0;
n := r.dwNumberOfProcessors;
a := 1;
for i:=0 to n-1 do
begin
if (r.dwActiveProcessorMask and a) <> 0 then inc(nn);
a := a shl 1;
end;
RESULT := nn;
end;
var
r : SYSTEM_INFO;
v : OSVERSIONINFO;
nn : Integer;
begin
RESULT := 1;
//OS Check
v.dwOSVersionInfoSize := sizeof(OSVERSIONINFO);
GetVersionEx(v);
if not(v.dwMajorVersion >= 5)then exit; //Windows98系はダメ
GetSystemInfo(r);
nn := inCoreCount(r); //nn := r.dwNumberOfProcessors; //論理コア
if nn < 1 then nn := 1;
if nn > 256 then nn := 256;
RESULT := nn;
end;
{ TMultiCoreThread }
procedure TMultiCoreThread.TaskAdd(func: TMultiCoreThreadFunc; ptr: Pointer);
begin
TaskArrayResize(FEntryCount+1);
FTasks[FEntryCount].FuncPtr := func;
FTasks[FEntryCount].EventPtr := nil;
FTasks[FEntryCount].UserPtr := ptr;
inc(FEntryCount);
end;
constructor TMultiCoreThread.Create(aThreadIndex,aThreadCount:integer);
begin
FThreadIndex := aThreadIndex; // ThreadNo
FThreadCount := aThreadCount; // AllThreadCount
FTaskCount := 64; // start cache size
SetLength(FTasks,FTaskCount);
FSem := TMultiCoreSemaphore.Create('');
FWaitSem := TMultiCoreSemaphore.Create('');
FWaitSem.Lock;
FStart := false;
FFinished := false;
FEntryCount := 0;
inherited Create(true); //create suspend true
end;
procedure TMultiCoreThread.TaskAdd(event: TMultiCoreThreadEvent; ptr: Pointer);
begin
TaskArrayResize(FEntryCount+1);
FTasks[FEntryCount].FuncPtr := nil;
FTasks[FEntryCount].EventPtr := event;
FTasks[FEntryCount].UserPtr := ptr;
inc(FEntryCount);
end;
procedure TMultiCoreThread.TaskArrayResize(need:integer);
var
newlen : integer;
begin
newlen := FTaskCount;
while (need >= newlen) do
newlen := newlen * 2;
if FTaskCount <> newlen then
begin
FTaskCount := newlen;
SetLength(FTasks,newlen);
end;
end;
procedure TMultiCoreThread.TaskExcute;
var
i,n : Integer;
begin
n := FEntryCount;
for i:=0 to n-1 do
begin
// function
if (Assigned(FTasks[i].FuncPtr))then
begin
try
FTasks[i].FuncPtr(FTasks[i].UserPtr);
except
break;
end;
end;
// event (class method)
if (Assigned(FTasks[i].EventPtr))then
begin
try
FTasks[i].EventPtr(FTasks[i].UserPtr);
except
break;
end;
end;
end;
end;
destructor TMultiCoreThread.Destroy;
begin
FSem.Lock;
FEntryCount := 0;
FStart := true; //start flag
FFinished := false;
Terminate; //set terminate
FSem.UnLock;
if Suspended then Start;
TaskStart;
Sleep(1);
WaitFor; //wait for escape execute function
FSem.Free;
FWaitSem.Free;
inherited;
end;
procedure TMultiCoreThread.Execute;
var
b : boolean;
begin
// thread : Execute
try
while not Terminated do
begin
// wait start flag. always loop.
while true do
begin
FWaitSem.Lock; // wait. start-sysnc間のみunlockされる。処理がないときはここで停止。
FWaitSem.UnLock;
FSem.Lock; // safety flag. FWaitSemだけでは終了時にLockが間に合わず数回通過するのでここで状態を監視する。
b := FStart;
FSem.UnLock;
if b then break; // if enable startflag , break wait loop.
sleep(0);
end;
// task execute
TaskExcute;
// task finished
FSem.Lock; // sync() との同期用
FStart := false;
FFinished := true;
Clear;
FSem.UnLock;
end;
except
{ error }
FStart := false;
FFinished := true;
Clear;
end;
end;
procedure TMultiCoreThread.Clear;
begin
FEntryCount := 0;
FWeight := 0;
end;
procedure TMultiCoreThread.TaskStart;
begin
// MainThread:set start flag.
// SubThread : break waitloop & task execute.
// set start flag
FSem.Lock;
FStart := true;
FFinished := false;
FSem.UnLock;
// subthread run
if Suspended then Start;
FWaitSem.UnLock; // thread wait unlock
end;
procedure TMultiCoreThread.TaskSync(sleeptime:integer);
var
b : boolean;
begin
// MainThread : waitfor FFinished = true.
// SubThread : task executing...
while true do
begin
FSem.Lock; //sync execute()
b := FFinished;
FSem.UnLock;
if b then
begin
FSem.Lock;
FStart := false;
FFinished := false;
FSem.UnLock;
break;
end;
sleep(sleeptime);
end;
FWaitSem.Lock; // thread wait lock. wait.
end;
{ TMultiCoreSemaphore }
constructor TMultiCoreSemaphore.Create(name: String);
begin
//InitializeCriticalSection(&FCS);
InitializeCriticalSectionAndSpinCount(&FCS,_MultiCore_SpinOutCount);
end;
destructor TMultiCoreSemaphore.Destroy;
begin
DeleteCriticalSection(&FCS);
inherited;
end;
procedure TMultiCoreSemaphore.Lock(t:DWORD);
begin
EnterCriticalSection(&FCS);
end;
procedure TMultiCoreSemaphore.UnLock;
begin
LeaveCriticalSection(&FCS);
end;
{ TMultiCoreThreadManager }
procedure TMultiCoreThreadManager.Add(func: TMultiCoreThreadFunc; ptr: Pointer; FuncWeight,ThreadIndex:Integer);
var
n : Integer;
begin
if ThreadIndex < 0 then
begin
//select min weight thread.
n := GetLightWeightCore(FuncWeight);
end
else
begin
n := ThreadIndex;
if not(n < FThreadCount) then n := FThreadCount-1;
end;
//add
FThread[n].TaskAdd(func,ptr);
//weight
FThread[n].Weight := FThread[n].FWeight + FuncWeight;
end;
procedure TMultiCoreThreadManager.CreateThread(n: Integer);
const inMaxProcesserMask:integer = 31;
function inRotation(n:integer):integer;
begin
result := (n + 1) and inMaxProcesserMask;
end;
function inBit(no:integer):cardinal;
begin
result := 1 shl (no and 31);
end;
procedure inCoreLock;
var
no : integer;
i : Integer;
r : SYSTEM_INFO;
v : OSVERSIONINFO;
b : Boolean;
begin
// OS version check
v.dwOSVersionInfoSize := sizeof(OSVERSIONINFO);
GetVersionEx(v);
if not(v.dwMajorVersion >= 5)then exit; // need windows2000 upper.
// use SetThreadAffinityMask() flag.
//スレッド数がプロセッサ数と同じ場合は、AffinityMaskを使用する
GetSystemInfo(r);
b := TRUE;
if FThreadCount <= r.dwNumberOfProcessors-_MultiCore_IdealProcessorMargin then b := FALSE;
no := (r.dwNumberOfProcessors div 2) and 0; // rotation start index
for i:=0 to FThreadCount-1 do
begin
while (r.dwActiveProcessorMask and inBit(no) = 0) do
no := inRotation(no);
if (b)then
SetThreadAffinityMask(FThread[i].Handle,inBit(no)) // set bit mask. use core lock.
else
SetThreadIdealProcessor(FThread[i].Handle,no); // set no. auto idel core select.
no := inRotation(no);
end;
end;
var
i : Integer;
begin
FreeThread;
FThreadCount := n;
SetLength(FThread,FThreadCount);
for i:=0 to FThreadCount-1 do
FThread[i] := TMultiCoreThread.Create(i,FThreadCount);
if (FCoreLock)then inCoreLock;
end;
procedure TMultiCoreThreadManager.Add(event: TMultiCoreThreadEvent; ptr: Pointer; FuncWeight, ThreadIndex: Integer);
var
n : Integer;
begin
if ThreadIndex < 0 then
begin
//select min weight thread.
n := GetLightWeightCore(FuncWeight);
end
else
begin
n := ThreadIndex;
if not(n < FThreadCount) then n := FThreadCount-1;
end;
//add
FThread[n].TaskAdd(event,ptr);
//weight
FThread[n].Weight := FThread[n].FWeight + FuncWeight;
end;
constructor TMultiCoreThreadManager.Create(ThreadCount:Integer; CoreLock:Boolean);
begin
if ThreadCount < 1 then ThreadCount := 1;
FCoreLock := CoreLock;
FTaskRotate := true;
CreateThread(ThreadCount);
Clear;
// create thread & standby
Start;
Sync;
end;
destructor TMultiCoreThreadManager.Destroy;
begin
FreeThread;
inherited;
end;
procedure TMultiCoreThreadManager.FreeThread;
var
th : TMultiCoreThread;
begin
for th in FThread do
th.Free;
FThreadCount := 0;
end;
function TMultiCoreThreadManager.GetLightWeightCore(FuncWeight: integer): integer;
var
w : integer;
i : integer;
rot,idx : integer;
begin
// rotation usecore index
rot := FRotateCycle div _MultiCoreRotateCycle;
rot := rot mod FThreadCount;
if not(FTaskRotate) then rot := 0;
w := $FFFFFF;
result := 0;
for i:=0 to FThreadCount-1 do
begin
// index rotation
idx := rot + i;
if idx >= FThreadCount then idx := idx - FThreadCount;
// select min weight
if FThread[idx].Weight < w then
begin
result := idx;
w := FThread[idx].Weight;
end;
end;
end;
procedure TMultiCoreThreadManager.Clear;
var
th : TMultiCoreThread;
begin
for th in FThread do
th.Clear;
end;
procedure TMultiCoreThreadManager.Start(SingleCoreProcess:Boolean);
var
th : TMultiCoreThread;
begin
FSingleCoreProcess := SingleCoreProcess; // single process flag
// rotation usecore index
FRotateCycle := (FRotateCycle + 1) and $ffffff;
if FSingleCoreProcess then
begin
// Single(MainThread)
for th in FThread do
th.TaskExcute;
end
else
begin
// Multicore(SubThreads)
for th in FThread do
th.TaskStart;
Sleep(0);
end;
end;
procedure TMultiCoreThreadManager.Sync(sleeptime:Integer);
var
th : TMultiCoreThread;
begin
if (FSingleCoreProcess)then
begin
// SingleCore
// none
end
else
begin
// MultiCore
// wait thread task finished
for th in FThread do
th.TaskSync(sleeptime);
end;
Clear;
end;
end.
|
unit fTINLoader;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.OpenGL,
System.SysUtils,
System.Variants,
System.Classes,
System.Math,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Imaging.Jpeg,
GLScene,
GLMesh,
GLCadencer,
GLTexture,
GLWin32Viewer,
GLObjects,
GLVectorGeometry,
GLVectorFileObjects,
GLPersistentClasses,
GLVectorLists,
GLKeyboard,
GLRenderContextInfo,
GLContext,
GLState,
GLColor,
GLMaterial,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses;
type
TMainForm = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
World: TGLDummyCube;
DGLContourLines: TGLDirectOpenGL;
DummyTerrain: TGLDummyCube;
MapImage: TImage;
procedure FormCreate(Sender: TObject);
procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure DGLContourLinesRender(var rci: TGLRenderContextInfo);
procedure LoadVerticesFromFile(filename: String);
procedure AddTriangle(const p1, p2, p3: TAffineVector;
const color: TColorVector);
function WordPosition(const N: Integer; const S: string;
const WordDelims: TSysCharSet): Integer;
{ This function lifted straight out of RXlib }
function ExtractWord(N: Integer; const S: string;
const WordDelims: TSysCharSet): string;
procedure BuildTerrainMesh(MeshFileName: String; MapFileName: String);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
public
mx, my, NumVertexY, NumGroup: Integer;
Xmin, Xmax, Ymin, Ymax, Zmin, Zmax: Single;
ID: String;
nVertice: Integer;
ptVertex: array of array [0 .. 2] of Single; // Contour Data Array
ptDT: array of array [0 .. 2] of Single; // Delaunay Triangulated Data Array
Group: array [0 .. 10000] of Integer; // Contour Line Group
TerrainMesh: TGLMesh;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
procedure TMainForm.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx := X;
my := Y;
end;
// Mouse move event handler
procedure TMainForm.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if ssLeft in Shift then
begin
GLCamera1.MoveAroundTarget(my - Y, mx - X);
mx := X;
my := Y;
end;
end;
function TMainForm.WordPosition(const N: Integer; const S: string;
const WordDelims: TSysCharSet): Integer;
var
Count, I: Integer;
begin
Count := 0;
I := 1;
Result := 0;
while (I <= Length(S)) and (Count <> N) do
begin
while (I <= Length(S)) and (S[I] in WordDelims) do
Inc(I);
if I <= Length(S) then
Inc(Count);
if Count <> N then
while (I <= Length(S)) and not(S[I] in WordDelims) do
Inc(I)
else
Result := I;
end;
end;
function TMainForm.ExtractWord(N: Integer; const S: string;
const WordDelims: TSysCharSet): string;
var
I: Integer;
Len: Integer;
begin
Len := 0;
I := WordPosition(N, S, WordDelims);
if I <> 0 then
while (I <= Length(S)) and not(S[I] in WordDelims) do
begin
Inc(Len);
SetLength(Result, Len);
Result[Len] := S[I];
Inc(I);
end;
SetLength(Result, Len);
end;
procedure TMainForm.LoadVerticesFromFile(filename: String);
var
f: TStringList;
linestring, strX, strY, strZ: String;
row, N, nGroup, nVerticePerGroup: Integer;
// Read 1 line from file
function ReadLine: String;
begin
Result := f[N];
Inc(N);
end;
begin
f := TStringList.create;
f.LoadFromFile(filename);
row := 0;
nVertice := 0;
nGroup := 0;
nVerticePerGroup := 0;
SetLength(ptVertex, f.Count * 3); // Dynamic alloc.
try
// Get header information
linestring := ReadLine();
Xmin := StrToFloat(ExtractWord(1, linestring, ['~']));
Xmax := StrToFloat(ExtractWord(2, linestring, ['~']));
linestring := ReadLine();
Ymin := StrToFloat(ExtractWord(1, linestring, ['~']));
Ymax := StrToFloat(ExtractWord(2, linestring, ['~']));
linestring := ReadLine();
Zmin := StrToFloat(ExtractWord(1, linestring, ['~']));
Zmax := StrToFloat(ExtractWord(2, linestring, ['~']));
// Parse ID and vertice coord data
while (row < f.Count - 3) do
begin
linestring := ReadLine();
if (copy(linestring, 1, 2) <> 'ID') then
begin
strX := ExtractWord(1, linestring, [',']);
strY := ExtractWord(2, linestring, [',']);
strZ := ExtractWord(3, linestring, [',']);
if (strX <> '') and (strY <> '') and (strZ <> '') then
begin
ptVertex[nVertice][0] := StrToFloat(strX);
ptVertex[nVertice][1] := StrToFloat(strY);
ptVertex[nVertice][2] := StrToFloat(strZ);
end;
Inc(nVertice);
Inc(nVerticePerGroup);
end
else
begin
ID := ExtractWord(2, linestring, [':']);
if (row <> 0) then
begin
Group[nGroup] := nVerticePerGroup;
Inc(nGroup);
nVerticePerGroup := 0;
end;
end;
Inc(row);
end;
NumVertexY := nVertice;
NumGroup := nGroup;
finally
f.free;
end;
end;
procedure TMainForm.AddTriangle(const p1, p2, p3: TAffineVector;
const color: TColorVector);
begin
with TerrainMesh.Vertices do
begin
AddVertex(p1, NullVector, color);
AddVertex(p2, NullVector, color);
AddVertex(p3, NullVector, color);
end;
end;
procedure TMainForm.BuildTerrainMesh(MeshFileName: String; MapFileName: String);
var
av1, av2, av3: TAffineVector;
I, nRemainder: Integer;
Devider: Integer;
XSize, YSize: Single;
CurrentDir: TFileName;
begin
NumGroup := 0;
NumVertexY := 0;
CurrentDir := GetCurrentDir();
LoadVerticesFromFile(Format('%s\%s', [CurrentDir, MeshFileName]));
TerrainMesh := TGLMesh(World.AddNewChild(TGLMesh));
MapImage.Visible := FALSE;
with TerrainMesh do
begin
Material.PolygonMode := pmFill; // pmLines;
Material.FaceCulling := fcNoCull;
Material.Texture.MappingMode := tmmObjectLinear; // tmmEyeLinear, tmmUser - no texture
Material.Texture.Image.LoadFromFile(CurrentDir + '\' + MapFileName);
Material.Texture.Disabled := False;
Mode := mmTriangles;
Vertices.Clear;
nRemainder := NumVertexY mod 3;
XSize := (Xmax - Xmin) / 2;
YSize := (Ymax - Ymin) / 2;
Devider := 500;
/// ///////////////////////////////////////////////////////////////
// make terrain mesh object
/// ///////////////////////////////////////////////////////////////
for I := 0 to Round(nVertice / 3) - 1 do
begin
av1 := AffineVectorMake((ptVertex[I * 3, 0] - Xmin - XSize) / Devider,
(ptVertex[I * 3, 1] - Ymin - YSize) / Devider,
(ptVertex[I * 3, 2] - Zmin) / Devider);
av2 := AffineVectorMake((ptVertex[I * 3 + 1, 0] - Xmin - XSize) / Devider,
(ptVertex[I * 3 + 1, 1] - Ymin - YSize) / Devider,
(ptVertex[I * 3 + 1, 2] - Zmin) / Devider);
av3 := AffineVectorMake((ptVertex[I * 3 + 2, 0] - Xmin - XSize) / Devider,
(ptVertex[I * 3 + 2, 1] - Ymin - YSize) / Devider,
(ptVertex[I * 3 + 2, 2] - Zmin) / Devider);
AddTriangle(av1, av2, av3, clrAqua);
Vertices.VertexTexCoord[I * 3] := texpointmake(av1.X / (Xmax - Xmin),
av1.Y / (Ymax - Ymin));
Vertices.VertexTexCoord[I * 3 + 1] := texpointmake(av2.X / (Xmax - Xmin),
av2.Y / (Ymax - Ymin));
Vertices.VertexTexCoord[I * 3 + 2] := texpointmake(av3.X / (Xmax - Xmin),
av3.Y / (Ymax - Ymin));
end;
if (nRemainder <> 0) then
begin
// Caption := 'Error';
end;
CalcNormals(fwCounterClockWise);
/// Overlay MapFileName
StructureChanged;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
BuildTerrainMesh('Terrain_1.tri', 'Map_1.jpg');
end;
procedure TMainForm.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
GLCamera1.AdjustDistanceToTarget(Power(1.1, WheelDelta / 120));
end;
procedure TMainForm.DGLContourLinesRender(var rci: TGLRenderContextInfo);
var
I, nGroup: Integer;
XSize, YSize: Single;
Devider: Integer;
begin
XSize := (Xmax - Xmin) / 2;
YSize := (Ymax - Ymin) / 2;
Devider := 10000;
glPushMatrix();
for nGroup := 0 to NumGroup do
begin
glBegin(GL_LINE_STRIP);
for I := 0 to (Group[nGroup]) - 1 do
begin
glVertex3f((ptVertex[I * 3, 0] - Xmin - XSize) / Devider,
(ptVertex[I * 3, 1] - Ymin - YSize) / Devider,
(ptVertex[I * 3, 2] - Zmin) / Devider);
end;
glEnd();
end;
glPopMatrix();
end;
procedure TMainForm.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
begin
if (IsKeyDown(VK_HOME)) then
begin
DummyTerrain.Translate(0, -1, 0);
World.Translate(0, -1, 0);
end;
if (IsKeyDown(VK_END)) then
begin
DummyTerrain.Translate(0, 1, 0);
World.Translate(0, 1, 0);
end;
if (IsKeyDown(VK_DELETE)) then
begin
DummyTerrain.Translate(1, 0, 0);
World.Translate(1, 0, 0);
end;
if (IsKeyDown(VK_NEXT)) then
begin
DummyTerrain.Translate(-1, 0, 0);
World.Translate(-1, 0, 0);
end;
if (IsKeyDown(VK_ADD)) then
begin
World.Scale.X := World.Scale.X * 1.1;
World.Scale.Y := World.Scale.Y * 1.1;
World.Scale.Z := World.Scale.Z * 1.1;
DummyTerrain.Scale.X := DummyTerrain.Scale.X * 1.1;
DummyTerrain.Scale.Y := DummyTerrain.Scale.Y * 1.1;
DummyTerrain.Scale.Z := DummyTerrain.Scale.Z * 1.1;
end;
if (IsKeyDown(VK_SUBTRACT)) then
begin
World.Scale.X := World.Scale.X / 1.1;
World.Scale.Y := World.Scale.Y / 1.1;
World.Scale.Z := World.Scale.Z / 1.1;
DummyTerrain.Scale.X := DummyTerrain.Scale.X / 1.1;
DummyTerrain.Scale.Y := DummyTerrain.Scale.Y / 1.1;
DummyTerrain.Scale.Z := DummyTerrain.Scale.Z / 1.1;
end;
if (IsKeyDown(VK_F1)) then
begin
DummyTerrain.RotateAbsolute(0, 0, 1);
World.RotateAbsolute(0, 0, 1);
end;
if (IsKeyDown(VK_F2)) then
begin
DummyTerrain.RotateAbsolute(0, 0, -1);
World.RotateAbsolute(0, 0, -1);
end;
if (IsKeyDown(VK_F3)) then
begin
DummyTerrain.RotateAbsolute(0, 1, 0);
World.RotateAbsolute(0, 1, 0);
end;
if (IsKeyDown(VK_F4)) then
begin
DummyTerrain.RotateAbsolute(0, -1, 0);
World.RotateAbsolute(0, -1, 0);
end;
if (IsKeyDown(VK_F5)) then
begin
DummyTerrain.RotateAbsolute(1, 0, 0);
World.RotateAbsolute(1, 0, 0);
end;
if (IsKeyDown(VK_F6)) then
begin
DummyTerrain.RotateAbsolute(-1, 0, 0);
World.RotateAbsolute(-1, 0, 0);
end;
end;
end.
|
unit ModflowTDisWriterUnit;
interface
uses SysUtils, CustomModflowWriterUnit, PhastModelUnit;
type
TTemporalDiscretizationWriter = class(TCustomModflowWriter)
private
procedure WriteDataSet0;
procedure WriteOptions;
procedure WriteDimensions;
procedure WriteStressPeriods;
public
class function Extension: string; override; // abstract;
procedure WriteFile(const AFileName: string);
end;
implementation
uses
frmProgressUnit, GoPhastTypes, ModflowTimeUnit;
resourcestring
StrWritingTemporalDis = 'Writing Temporal Discretization (TDIS) Package in' +
'put.';
{ TTemporalDiscretizationWriter }
class function TTemporalDiscretizationWriter.Extension: string;
begin
Result := '.tdis';
end;
procedure TTemporalDiscretizationWriter.WriteDataSet0;
begin
WriteString(File_Comment('TDIS'));
NewLine;
end;
procedure TTemporalDiscretizationWriter.WriteDimensions;
var
NPER: integer;
begin
NPER := Model.ModflowFullStressPeriods.Count;
WriteString('BEGIN DIMENSIONS');
NewLine;
WriteString(' NPER');
WriteInteger(NPER);
NewLine;
WriteString('END DIMENSIONS');
NewLine;
NewLine;
end;
procedure TTemporalDiscretizationWriter.WriteFile(const AFileName: string);
var
FTYPE: string;
NameOfFile: string;
begin
if Model.ModelSelection <> msModflow2015 then
begin
Exit;
end;
FTYPE := 'TDIS';
if Model.PackageGeneratedExternally(FTYPE) then
begin
Exit;
end;
NameOfFile := FileName(AFileName);
Model.SimNameWriter.TDisFileName := NameOfFile;
// WriteToNameFile(FTYPE, -1, NameOfFile, foInput);
OpenFile(NameOfFile);
try
frmProgressMM.AddMessage(StrWritingTemporalDis);
frmProgressMM.AddMessage(StrWritingDataSet0);
WriteDataSet0;
WriteOptions;
WriteDimensions;
WriteStressPeriods;
finally
CloseFile;
end;
end;
procedure TTemporalDiscretizationWriter.WriteOptions;
var
TimeUnit: Integer;
begin
TimeUnit := Model.ModflowOptions.TimeUnit;
WriteBeginOptions;
WriteString(' TIME_UNITS ');
case TimeUnit of
0: WriteString('unknown');
1: WriteString('seconds');
2: WriteString('minutes');
3: WriteString('hours');
4: WriteString('days');
5: WriteString('years');
end;
NewLine;
WriteEndOptions;
end;
procedure TTemporalDiscretizationWriter.WriteStressPeriods;
var
StressPeriods: TModflowStressPeriods;
StressPeriodIndex: Integer;
AStressPeriod: TModflowStressPeriod;
begin
StressPeriods := Model.ModflowFullStressPeriods;
WriteString('BEGIN STRESS_PERIODS');
NewLine;
for StressPeriodIndex := 0 to StressPeriods.Count - 1 do
begin
AStressPeriod := StressPeriods[StressPeriodIndex];
WriteString(' ');
WriteFloat(AStressPeriod.PeriodLength);
WriteInteger(AStressPeriod.NumberOfSteps);
WriteFloat(AStressPeriod.TimeStepMultiplier);
WriteString(' # perlen nstp tsmult, Stress period ');
WriteInteger(StressPeriodIndex+1);
NewLine;
end;
WriteString('END STRESS_PERIODS');
NewLine;
end;
end.
|
unit OrcamentoFornecedores.Model;
interface
uses OrcamentoFornecedores.Model.Interf,
ormbr.container.objectset.interfaces, ormbr.Factory.interfaces,
TESTORCAMENTOFORNECEDORES.Entidade.Model;
type
TOrcamentoFornecedoresModel = class(TInterfacedObject, IOrcamentoFornecedoresModel)
private
FConexao: IDBConnection;
FEntidade: TTESTORCAMENTOFORNECEDORES;
FDao: IContainerObjectSet<TTESTORCAMENTOFORNECEDORES>;
public
constructor Create;
destructor Destroy; override;
class function New: IOrcamentoFornecedoresModel;
function Entidade(AValue: TTESTORCAMENTOFORNECEDORES)
: IOrcamentoFornecedoresModel; overload;
function Entidade: TTESTORCAMENTOFORNECEDORES; overload;
function DAO: IContainerObjectSet<TTESTORCAMENTOFORNECEDORES>;
end;
implementation
{ TOrcamentoFornecedoresModel }
uses FacadeController, ormbr.container.objectset;
constructor TOrcamentoFornecedoresModel.Create;
begin
FConexao := TFacadeController.New.ConexaoController.conexaoAtual;
FDao := TContainerObjectSet<TTESTORCAMENTOFORNECEDORES>.Create(FConexao, 1);
end;
function TOrcamentoFornecedoresModel.DAO: IContainerObjectSet<TTESTORCAMENTOFORNECEDORES>;
begin
Result := FDao;
end;
destructor TOrcamentoFornecedoresModel.Destroy;
begin
inherited;
end;
function TOrcamentoFornecedoresModel.Entidade(AValue: TTESTORCAMENTOFORNECEDORES)
: IOrcamentoFornecedoresModel;
begin
Result := Self;
FEntidade := AValue;
end;
function TOrcamentoFornecedoresModel.Entidade: TTESTORCAMENTOFORNECEDORES;
begin
Result := FEntidade;
end;
class function TOrcamentoFornecedoresModel.New: IOrcamentoFornecedoresModel;
begin
Result := Self.Create;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: USpaceEntities
Author: J.Delauney
Purpose: Custom "Space" GLObject for better integrating with GLScene
- Multiple planets, Moons,... with their individual properties
- One Space object per orbit, unlimited orbit per Planet & for Sun
History: "Main Idea From Blaise Bernier"
-----------------------------------------------------------------------------}
unit USpaceEntities;
interface
uses
Classes,
GLObjects;
Type
TSystemData = record
NbPlanet : byte;
NbMoon : Byte;
// NbAsteroid : Byte;
// NbComete : Byte;
end;
TSunData = record
SunName : Array[0..9] of Char; // Also Equal to material
distance : single;
diametre : single;
AngleAxis : Single;
Mass : single;
DocIndex : Byte;
end;
TOrbitData =record
Period : Single;
Velocity : single;
Eccentricity : single;
AxisAngle : Single;
end;
TPlanetData = record
PlanetName : Array[0..15] of Char;
distance : single;
diametre : single;
Mass : single;
RotationPeriod : single;
AngleEquatorOrbit : single;
nbmoon : Byte;
AtmosphericConstituents : Array[0..19] of Char;
DocIndex : Byte;
end;
TMoonData = record
MoonName : Array[0..9] of Char;
distance : single;
diametre : single;
RotationPeriod : single;
AngleEquatorOrbit : Single;
Mass : single;
DocIndex : Byte;
end;
TGLSun=Class(TGLSphere)
Private
FExtraData : TSunData;
public
property ExtraData : TSunData read FExtraData write FExtraData;
end;
TGLOrbit=Class(TGLLines)
Private
FExtraData : TOrbitData;
public
property ExtraData : TOrbitData read FExtraData write FExtraData;
end;
TGLPlanet=Class(TGLSphere)
Private
FExtraData : TPlanetData;
public
property ExtraData : TPlanetData read FExtraData write FExtraData;
end;
// TGLPlanetRing=Class(TGLDisc)
// Private
// FExtraData : TRingData;
// public
// property ExtraData : TRingData read FExtraData write FExtraData;
// end;
TGLMoon=Class(TGLSphere)
Private
FExtraData : TMoonData;
public
property ExtraData : TMoonData read FExtraData write FExtraData;
end;
//
// TGLAsteroid=Class(TGLFreeForm)
// Private
// FExtraData : TAsteroidData;
// public
// Procedure BuildAsteroid;
// property ExtraData : TAsteroidData read FExtraData write FExtraData;
// end;
//
// TGLSpaceShip=Class(TGLFreeForm)
// Private
// FExtraData : TSpaceShipData;
// public
// property ExtraData : TAsteroidData read FExtraData write FExtraData;
// end;
//
// TGLSatelit=Class(TGLFreeForm)
// Private
// FExtraData : TSatelitData;
// public
// property ExtraData : TSatelitData read FExtraData write FExtraData;
// end;
implementation
uses
SysUtils;
{-----------------------------------------------------------------------------
Procedure : All Comment Below it's for creating Asteroids
it provided From : Alexandre Hirzel ?
Date : 17/juil./2003
Arguments : None
Result : None
Description :
-----------------------------------------------------------------------------}
//RandSeed:=Seed;
// MasterAsteroidF:=TFreeForm(dumMasters.AddNewChild(TFreeForm));
// Temp:=TGLMeshObject.CreateOwned(MasterAsteroidF.MeshObjects);
// BuildPotatoid(Temp,0.5,0,2);
//procedure Normalize(var v:array of single);
//var
// d :double;
//begin
// d:=sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
// v[0]:=v[0]/d; v[1]:=v[1]/d; v[2]:=v[2]/d;
//end;
//
//procedure NormCrossProd(const v1,v2:array of single;
// var Result:array of single);
//var
// i, j :GLint;
// length :single;
//begin
// Result[0]:= v1[1]*v2[2] - v1[2]*v2[1];
// Result[1]:= v1[2]*v2[0] - v1[0]*v2[2];
// Result[2]:= v1[0]*v2[1] - v1[1]*v2[0];
// Normalize(Result);
//end;
//
//procedure CartToPol(v:array of single;var Theta,Phi:single);
//var
// CosPhi :single;
//begin
// Normalize(v);
// Phi:=ArcSin(v[1]);
// if Abs(v[1])<1 then begin
// CosPhi:=sqrt(1-sqr(v[1]));
// Theta:=ArcCos(v[0]/CosPhi);
// if v[2]<0 then Theta:=-Theta;
// end
// else Theta:=0;
//end;
//
//procedure SpheroidAddTriangle(var Mesh:tMeshObject; const v1,v2,v3:array of single);
//var
// j :integer;
// d1,d2,norm :array [0..2] of single;
// Theta,Phi :array [0..2] of single;
//begin
// for j:=0 to 2 do begin
// d1[j]:=v1[j] - v2[j];
// d2[j]:=v2[j] - v3[j];
// end;//for j
// NormCrossProd(d1,d2,norm);
//
// CartToPol(v1,Theta[0],Phi[0]);
// CartToPol(v2,Theta[1],Phi[1]);
// CartToPol(v3,Theta[2],Phi[2]);
// if (abs(sign(Theta[0])+sign(Theta[1])+sign(Theta[2]))<3)and
// (Abs(Theta[0]*Theta[1]*Theta[2])>8) then begin
// if Theta[0]<0 then Theta[0]:=Theta[0]+2*pi;
// if Theta[1]<0 then Theta[1]:=Theta[1]+2*pi;
// if Theta[2]<0 then Theta[2]:=Theta[2]+2*pi;
// end;//if
//
// Mesh.Vertices.add (v1[0],v1[1],v1[2]);
//// Mesh.Normals.add ((v1[0]+norm[0])/2,(v1[1]+norm[1])/2,(v1[2]+norm[2])/2);
// Mesh.Normals.Add(norm[0],norm[1],norm[2]);
// Mesh.TexCoords.Add(Theta[0]/pi/2+0.5,Phi[0]/pi+0.5);
//
// Mesh.Vertices.add (v2[0],v2[1],v2[2]);
//// Mesh.Normals.add ((v2[0]+norm[0])/2,(v2[1]+norm[1])/2,(v2[2]+norm[2])/2);
// Mesh.Normals.Add(norm[0],norm[1],norm[2]);
// Mesh.TexCoords.Add(Theta[1]/pi/2+0.5,Phi[1]/pi+0.5);
//
// Mesh.Vertices.add (v3[0],v3[1],v3[2]);
//// Mesh.Normals.add ((v3[0]+norm[0])/2,(v3[1]+norm[1])/2,(v3[2]+norm[2])/2);
// Mesh.Normals.Add(norm[0],norm[1],norm[2]);
// Mesh.TexCoords.Add(Theta[2]/pi/2+0.5,Phi[2]/pi+0.5);
//end;
//
//procedure BuildSphere(var Mesh:tMeshObject; const Depth:integer=0);
//{Polyhedron and Subdivide algorithms from OpenGL Red Book}
//
// procedure Subdivide(const v1,v2,v3:array of single;const Depth:integer);
// var
// v12,v23,v31 :array[0..2] of single;
// i :integer;
// begin
// if Depth=0 then SpheroidAddTriangle(Mesh, v1,v2,v3)
// else begin
// for i:=0 to 2 do begin
// v12[i]:= v1[i]+v2[i];
// v23[i]:= v2[i]+v3[i];
// v31[i]:= v3[i]+v1[i];
// end;//for
// normalize(v12);
// normalize(v23);
// normalize(v31);
// Subdivide(v1,v12,v31,Depth-1);
// Subdivide(v2,v23,v12,Depth-1);
// Subdivide(v3,v31,v23,Depth-1);
// Subdivide(v12,v23,v31,Depth-1);
// end;//else
// end;
//
//const
// X=0.525731112119133606; // Chosen for a radius-1 icosahedron
// Z=0.850650808352039932; //
// vdata:array[0..11,0..2] of single = ( // 12 vertices
// (-X, 0.0, Z), (X, 0.0, Z), (-X, 0.0,-Z), (X, 0.0, -Z),
// (0.0, Z, X), (0.0, Z, -X), (0.0, -Z, X), (0.0, -Z, -X),
// (Z, X, 0.0), (-Z, X, 0.0), (Z, -X, 0.0), (-Z, -X, 0.0) );
//
// tindices:array[0..19,0..2]of glInt = ( // 20 faces
// (0,4,1), (0,9,4), (9,5,4), (4,5,8), (4,8,1),
// (8,10,1), (8,3,10), (5,3,8), (5,2,3), (2,7,3),
// (7,10,3), (7,6,10), (7,11,6), (11,0,6),(0,1,6),
// (6,1,10), (9,0,11), (9,11,2), (9,2,5), (7,2,11) );
//var
// i :integer;
//begin
// for i:=0 to 19 do begin
// Subdivide(vdata[tindices[i,0],0],
// vdata[tindices[i,1],0],
// vdata[tindices[i,2],0],
// Depth);
// end;//for
//end;
//function BuildPotatoid(var Mesh:tMeshObject; const Deviance:single=0.2;
// const Depth:integer=1; ActualDepth:integer=-1):boolean;
//{Fractal process to build a random potatoid. Depth correspond to the depth
// of the recursive process. Use ActualDepth to generate a same potatoid at
// various level of details}
//const
// Reduction=2;
//type
// pEdge=^tEdge;
// tEdge=record
// c1,c2 :pEdge;
// r :single;
// end;//record
//var
// i,j :integer;
// vdata2 :array[0..11,0..2] of single;
// rr :single;
// Edges :array[0..11,0..11] of pEdge;
// i0,i1,i2 :integer;
// DeltaDepth :integer;
//
// procedure SubdividePotatoid(const v1,v2,v3:array of single;
// Edges:array of pEdge;
// const Deviance:single; const Depth:integer);
// var
// v12,v23,v31 :array[0..2] of single;
// i :integer;
// inEdges :array[0..2] of pEdge;
// begin
// if Depth=DeltaDepth then SpheroidAddTriangle(Mesh,v1,v2,v3);
// if Depth>-DeltaDepth then begin
// for i:=0 to 2 do begin
// v12[i]:=(v1[i]+v2[i])/2;
// v23[i]:=(v2[i]+v3[i])/2;
// v31[i]:=(v3[i]+v1[i])/2;
// end;//for
// for i:=0 to 2 do begin
// v12[i]:=v12[i]*Edges[0]^.r; // Apply the deviance
// v31[i]:=v31[i]*Edges[1]^.r;
// v23[i]:=v23[i]*Edges[2]^.r;
// if Edges[i]^.c1=nil then begin
// New(Edges[i]^.c1);
// Edges[i]^.c1^.r:=exp((random*2-1)*(Deviance/Reduction)); // New division of the Edges
// Edges[i]^.c1^.c1:=nil;
// Edges[i]^.c1^.c2:=nil;
// New(Edges[i]^.c2);
// Edges[i]^.c2^.r:=Edges[i]^.c1^.r; // New division of the Edges
// Edges[i]^.c2^.c1:=nil;
// Edges[i]^.c2^.c2:=nil;
// end;//i
// New(inEdges[i]);
// inEdges[i]^.r:=exp((random*2-1)*(Deviance/Reduction));
// inEdges[i]^.c1:=nil;
// inEdges[i]^.c2:=nil;
// end;//for
//
// SubdividePotatoid(v1,v12,v31,
// [Edges[0]^.c1,Edges[1]^.c1,inEdges[0]],
// Deviance/Reduction,Depth-1);
// SubdividePotatoid(v2,v23,v12,
// [Edges[2]^.c1,Edges[0]^.c2,inEdges[1]],
// Deviance/Reduction,Depth-1);
// SubdividePotatoid(v3,v31,v23,
// [Edges[1]^.c2,Edges[2]^.c2,inEdges[2]],
// Deviance/Reduction,Depth-1);
// SubdividePotatoid(v12,v23,v31,
// [inEdges[1],inEdges[0],inEdges[2]],
// Deviance/Reduction,Depth-1);
// Dispose(inEdges[0]);
// Dispose(inEdges[1]);
// Dispose(inEdges[2]);
// end;//else
// end;
//
// procedure DisposeEdge(Edge:pEdge);
// begin
// if Edge^.c1<>nil then DisposeEdge(Edge^.c1);
// if Edge^.c2<>nil then DisposeEdge(Edge^.c2);
// Dispose(Edge);
// end;
//
//const
// X=0.525731112119133606; // Chosen for a radius-1 icosahedron
// Z=0.850650808352039932; //
// vdata:array[0..11,0..2] of single = ( // 12 vertices
// (-X, 0.0, Z), (X, 0.0, Z), (-X, 0.0,-Z), (X, 0.0, -Z),
// (0.0, Z, X), (0.0, Z, -X), (0.0, -Z, X), (0.0, -Z, -X),
// (Z, X, 0.0), (-Z, X, 0.0), (Z, -X, 0.0), (-Z, -X, 0.0) );
// tindices:array[0..19,0..2]of glInt = ( // 20 faces
// (0,4,1), (0,9,4), (9,5,4), (4,5,8), (4,8,1),
// (8,10,1), (8,3,10), (5,3,8), (5,2,3), (2,7,3),
// (7,10,3), (7,6,10), (7,11,6), (11,0,6),(0,1,6),
// (6,1,10), (9,0,11), (9,11,2), (9,2,5), (7,2,11) );
//begin
// Result:=False;
// if ActualDepth<Depth then ActualDepth:=Depth;
// DeltaDepth:=ActualDepth-Depth;
// Mesh.Mode:=momTriangles;
// Mesh.Vertices.Clear;
// Mesh.Normals.Clear;
// Mesh.TexCoords.Clear;
// for i:=0 to 11 do begin // randomize vertices
// rr:=exp((random*2-1)*(Deviance));
// for j:=0 to 2 do vdata2[i,j]:=vdata[i,j]*rr;
// end;//for i
// try
// for i:=1 to 11 do begin // randomize Edges
// for j:=0 to i-1 do begin
// New(Edges[i,j]);
// Edges[i,j]^.r:=exp((random*2-1)*(Deviance/Reduction));
// Edges[j,i]:=Edges[i,j];
// Edges[i,j]^.c1:=nil; Edges[i,j]^.c2:=nil;
// end;//for
// end;//for i
//
// for i:=0 to 19 do begin // Draw triangles
// i0:=tindices[i,0];
// i1:=tindices[i,1];
// i2:=tindices[i,2];
// SubdividePotatoid(Slice(vdata2[i0],3),
// Slice(vdata2[i1],3),
// Slice(vdata2[i2],3),
// [Edges[i0,i1],
// Edges[i0,i2],
// Edges[i1,i2] ],
// Deviance/Reduction, ActualDepth);
// end;//for
// finally
// for i:=1 to 11 do begin // Dispose of pointers
// for j:=0 to i-1 do begin
// DisposeEdge(Edges[i,j]);
// end;//for
// end;//for i
// end;//finally
// Result:=True;
//end;
end.
|
unit GuidHelper;
interface
// Gets a new GUID string
function NewGuid : String;
implementation
uses Classes, SysUtils;
function NewGuid : String;
var
guid: TGUID;
begin
CreateGUID(guid);
Result := GUIDToString(guid);
end;
end.
|
//
// Robert Rossmair, 2002-09-22
//
unit StretchGraphicDemoMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, Menus, ExtCtrls, ExtDlgs, JPEG,
JclGraphics;
type
TStretchDemoForm = class(TForm)
OpenDialog: TOpenPictureDialog;
PageControl: TPageControl;
OriginalPage: TTabSheet;
StretchedPage: TTabSheet;
StretchedImage: TImage;
MainMenu: TMainMenu;
Fil1: TMenuItem;
Open1: TMenuItem;
N1: TMenuItem;
ExitItem: TMenuItem;
Filter1: TMenuItem;
Box1: TMenuItem;
riangle1: TMenuItem;
Hermite1: TMenuItem;
Bell1: TMenuItem;
Spline1: TMenuItem;
Lanczos31: TMenuItem;
Mitchell1: TMenuItem;
Options1: TMenuItem;
PreserveAspectRatio1: TMenuItem;
PrevItem: TMenuItem;
NextItem: TMenuItem;
FilesPage: TTabSheet;
FileListBox: TListBox;
ScrollBox: TScrollBox;
OriginalImage: TImage;
procedure OpenFile(Sender: TObject);
procedure SelectFilter(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure PreserveAspectRatio1Click(Sender: TObject);
procedure ExitApp(Sender: TObject);
procedure PrevFile(Sender: TObject);
procedure NextFile(Sender: TObject);
procedure FileListBoxClick(Sender: TObject);
procedure LoadSelected;
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FDir: string;
FResamplingFilter: TResamplingFilter;
FPreserveAspectRatio: Boolean;
procedure DoStretch;
procedure LoadFile(const FileName: string);
procedure UpdateCaption;
procedure UpdateFileList(const FileName: string);
procedure UpdateNavButtons;
end;
var
StretchDemoForm: TStretchDemoForm;
implementation
{$R *.dfm}
uses JclFileUtils;
var
FileMask: string;
function IsGraphicFile(const Attr: Integer; const FileInfo: TSearchRec): Boolean;
var
Ext: string;
begin
Ext := AnsiLowerCase(ExtractFileExt(FileInfo.Name));
Result := (Pos(Ext, FileMask) > 0);
end;
procedure TStretchDemoForm.FormCreate(Sender: TObject);
begin
FileMask := Format('%s;%s', [GraphicFileMask(TJPEGImage), GraphicFileMask(TBitmap)]);
FResamplingFilter := rfSpline;
FPreserveAspectRatio := True;
UpdateNavButtons;
UpdateCaption;
end;
procedure TStretchDemoForm.UpdateFileList(const FileName: string);
var
Dir, D: string;
begin
D := ExtractFileDir(FileName);
{$IFDEF COMPILER6_UP}
Dir := IncludeTrailingPathDelimiter(D);
{$ELSE}
Dir := IncludeTrailingBackslash(D);
{$ENDIF}
if Dir <> FDir then
begin
FDir := Dir;
FilesPage.Caption := Format('Files in %s', [D]);
FileListBox.Items.Clear;
AdvBuildFileList(Dir + '*.*', faAnyFile, FileListBox.Items, amCustom, [], '', IsGraphicFile);
with FileListBox do
ItemIndex := Items.IndexOf(ExtractFileName(OpenDialog.FileName))
end;
end;
procedure TStretchDemoForm.LoadFile(const FileName: string);
begin
OriginalImage.Picture.LoadFromFile(FileName);
UpdateFileList(FileName);
UpdateNavButtons;
DoStretch;
end;
procedure TStretchDemoForm.OpenFile(Sender: TObject);
begin
if OpenDialog.Execute then
LoadFile(OpenDialog.FileName);
end;
procedure TStretchDemoForm.SelectFilter(Sender: TObject);
begin
with Sender as TMenuItem do
begin
Checked := True;
FResamplingFilter := TResamplingFilter(Tag);
DoStretch;
end;
end;
procedure TStretchDemoForm.DoStretch;
var
W, H: Integer;
begin
if OriginalImage.Picture.Graphic = nil then
Exit;
W := StretchedPage.Width;
H := StretchedPage.Height;
if FPreserveAspectRatio then
with OriginalImage.Picture.Graphic do
begin
if W * Height > H * Width then
W := H * Width div Height
else
H := W * Height div Width;
end;
StretchedImage.SetBounds(0, 0, W, H);
JclGraphics.Stretch(W, H, FResamplingFilter, 0, OriginalImage.Picture.Graphic,
StretchedImage.Picture.Bitmap);
PageControl.ActivePage := StretchedPage;
end;
procedure TStretchDemoForm.FormResize(Sender: TObject);
begin
DoStretch;
UpdateCaption;
end;
procedure TStretchDemoForm.PreserveAspectRatio1Click(Sender: TObject);
begin
with Sender as TMenuItem do
begin
Checked := not Checked;
FPreserveAspectRatio := Checked;
DoStretch;
end;
end;
procedure TStretchDemoForm.UpdateCaption;
begin
Caption := Format('JclGraphics.Stretch To %d x %d', [StretchedPage.Width, StretchedPage.Height]);
end;
procedure TStretchDemoForm.ExitApp(Sender: TObject);
begin
Close;
end;
procedure TStretchDemoForm.LoadSelected;
begin
with FileListBox do
if ItemIndex <> -1 then
LoadFile(FDir + Items[ItemIndex]);
end;
procedure TStretchDemoForm.PrevFile(Sender: TObject);
begin
with FileListBox do
ItemIndex := ItemIndex - 1;
LoadSelected;
end;
procedure TStretchDemoForm.NextFile(Sender: TObject);
begin
with FileListBox do
ItemIndex := ItemIndex + 1;
LoadSelected;
end;
procedure TStretchDemoForm.UpdateNavButtons;
begin
PrevItem.Enabled := FileListBox.ItemIndex > 0;
NextItem.Enabled := FileListBox.ItemIndex < FileListBox.Items.Count - 1;
end;
procedure TStretchDemoForm.FileListBoxClick(Sender: TObject);
begin
LoadSelected;
end;
procedure TStretchDemoForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_LEFT:
begin
PrevFile(Self);
Key := 0;
end;
VK_RIGHT:
begin
NextFile(Self);
Key := 0;
end;
end;
end;
end.
|
unit Dmitry.PathProviders;
interface
uses
Generics.Collections,
System.Classes,
System.SyncObjs,
System.SysUtils,
Winapi.Windows,
Winapi.CommCtrl,
Vcl.Graphics,
Vcl.ImgList,
Dmitry.Memory;
const
PATH_FEATURE_PROPERTIES = 'properties';
PATH_FEATURE_CHILD_LIST = 'child_list';
PATH_FEATURE_DELETE = 'delete';
PATH_FEATURE_RENAME = 'rename';
const
PATH_LOAD_NORMAL = 0;
PATH_LOAD_NO_IMAGE = 1;
PATH_LOAD_DIRECTORIES_ONLY = 2;
PATH_LOAD_NO_HIDDEN = 4;
PATH_LOAD_FOR_IMAGE_LIST = 8;
PATH_LOAD_FAST = 16;
PATH_LOAD_ONLY_FILE_SYSTEM = 32;
PATH_LOAD_CHECK_CHILDREN = 64;
type
TPathItem = class;
TPathImage = class(TObject)
private
FHIcon: HIcon;
FIcon: TIcon;
FBitmap: TBitmap;
procedure Init;
function GetGraphic: TGraphic;
public
constructor Create(Icon: TIcon); overload;
constructor Create(Icon: HIcon); overload;
constructor Create(Bitmap: TBitmap); overload;
destructor Destroy; override;
procedure DetachImage;
procedure Clear;
function Copy: TPathImage;
procedure Assign(Source: TPathImage; DetachSource: Boolean = False);
procedure AddToImageList(ImageList: TCustomImageList);
property HIcon: HIcon read FHIcon;
property Icon: TIcon read FIcon;
property Bitmap: TBitmap read FBitmap;
property Graphic: TGraphic read GetGraphic;
end;
TPathItemCollection = class(TList<TPathItem>)
private
FTag: NativeInt;
public
procedure FreeItems;
property Tag: NativeInt read FTag write FTag;
end;
TLoadListCallBack = procedure(Sender: TObject; Item: TPathItem; CurrentItems: TPathItemCollection; var Break: Boolean) of object;
TLoadListCallBackRef = reference to procedure(Sender: TObject; Item: TPathItem; CurrentItems: TPathItemCollection; var Break: Boolean);
TPathFeatureOptions = class(TObject)
private
FTag: Integer;
public
property Tag: Integer read FTag write FTag;
end;
TPathFeatureEditOptions = class(TPathFeatureOptions)
private
FNewName: string;
public
constructor Create(ANewName: string);
property NewName: string read FNewName write FNewName;
end;
TPathFeatureDeleteOptions = class(TPathFeatureOptions)
private
FSilent: Boolean;
public
constructor Create(ASilent: Boolean);
property Silent: Boolean read FSilent write FSilent;
end;
TPathProvider = class(TObject)
private
FExtProviders: TList<TPathProvider>;
procedure FillChildsCallBack(Sender: TObject; Item: TPathItem; CurrentItems: TPathItemCollection; var Break: Boolean);
//helper for Reference callback
procedure InternalCallBack(Sender: TObject; Item: TPathItem; CurrentItems: TPathItemCollection; var Break: Boolean);
protected
function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; virtual;
public
constructor Create;
destructor Destroy; override;
function ExtractPreview(Item: TPathItem; MaxWidth, MaxHeight: Integer; var Bitmap: TBitmap; var Data: TObject): Boolean; virtual;
function Supports(Path: string): Boolean; overload; virtual;
function Supports(PathItem: TPathItem): Boolean; overload; virtual;
function SupportsFeature(Feature: string): Boolean; virtual;
function ExecuteFeature(Sender: TObject; Items: TPathItemCollection; Feature: string; Options: TPathFeatureOptions): Boolean; overload; virtual;
function FillChilds(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer): Boolean;
function FillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; overload;
function FillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBackRef): Boolean; overload;
procedure RegisterExtension(ExtProvider: TPathProvider; InsertAsFirst: Boolean = False);
function CreateFromPath(Path: string): TPathItem; virtual;
end;
TPathProviderClass = class of TPathProvider;
TPathItem = class(TObject)
private
procedure SetImage(const Value: TPathImage);
protected
FPath: string;
FParent: TPathItem;
FImage: TPathImage;
FDisplayName: string;
FOptions: Integer;
FImageSize: Integer;
FTag: Integer;
FCanHaveChildren: Boolean;
function GetPath: string; virtual;
function GetDisplayName: string; virtual;
procedure SetDisplayName(const Value: string); virtual;
function GetPathImage: TPathImage; virtual;
function InternalGetParent: TPathItem; virtual;
function GetParent: TPathItem; virtual;
function GetProvider: TPathProvider; virtual;
function InternalCreateNewInstance: TPathItem; virtual;
function GetIsInternalIcon: Boolean; virtual;
function GetIsDirectory: Boolean; virtual;
function GetFileSize: Int64; virtual;
procedure UpdateText;
procedure UpdateImage(ImageSize: Integer);
public
constructor Create; virtual;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); virtual;
destructor Destroy; override;
function Copy: TPathItem; virtual;
procedure Assign(Item: TPathItem); virtual;
procedure DetachImage;
procedure UpdatePath(Path: string);
function LoadImage: Boolean; overload;
function LoadImage(AOptions, AImageSize: Integer): Boolean; overload; virtual;
function EqualsTo(Item: TPathItem): Boolean;
function ExtractImage: TPathImage;
property Provider: TPathProvider read GetProvider;
property Path: string read GetPath;
property DisplayName: string read GetDisplayName write SetDisplayName;
property Image: TPathImage read GetPathImage write SetImage;
property Parent: TPathItem read GetParent;
property IsInternalIcon: Boolean read GetIsInternalIcon;
property Options: Integer read FOptions;
property ImageSize: Integer read FImageSize;
property IsDirectory: Boolean read GetIsDirectory;
property FileSize: Int64 read GetFileSize;
property CanHaveChildren: Boolean read FCanHaveChildren;
property Tag: Integer read FTag write FTag;
end;
TPathItemClass = class of TPathItem;
TPathProviderManager = class(TObject)
private
FSync: TCriticalSection;
FProviders: TList<TPathProvider>;
function GetCount: Integer;
function GetPathProvider(PathItem: TPathItem): TPathProvider;
function GetProviderByIndex(Index: Integer): TPathProvider;
public
constructor Create;
destructor Destroy; override;
procedure RegisterProvider(Provider: TPathProvider);
procedure RegisterSubProvider(ProviderClass, ProviderSubClass: TPathProviderClass;
InsertAsFirst: Boolean = False);
function CreatePathItem(Path: string): TPathItem;
function Supports(Path: string): Boolean;
function Find(ProviderClass: TPathProviderClass): TPathProvider;
property Count: Integer read GetCount;
property Providers[Index: Integer]: TPathProvider read GetProviderByIndex;
function ExecuteFeature(Sender: TObject; Path, Feature: string): Boolean;
end;
TPathItemTextCallBack = procedure(Item: TPathItem);
TPathItemImageCallBack = procedure(Item: TPathItem; ImageSize: Integer);
function PathProviderManager: TPathProviderManager;
var
PathProvider_UpdateText: TPathItemTextCallBack = nil;
PathProvider_UpdateImage: TPathItemImageCallBack = nil;
implementation
var
FPathProviderManager: TPathProviderManager = nil;
function PathProviderManager: TPathProviderManager;
begin
if FPathProviderManager = nil then
FPathProviderManager := TPathProviderManager.Create;
Result := FPathProviderManager;
end;
{ TPathProviderManager }
constructor TPathProviderManager.Create;
begin
FSync := TCriticalSection.Create;
FProviders := TList<TPathProvider>.Create;
end;
function TPathProviderManager.CreatePathItem(Path: string): TPathItem;
var
I: Integer;
begin
Result := nil;
FSync.Enter;
try
for I := 0 to FProviders.Count - 1 do
if FProviders[I].Supports(Path) then
begin
Result := FProviders[I].CreateFromPath(Path);
Exit;
end;
finally
FSync.Leave;
end;
end;
function TPathProviderManager.Supports(Path: string): Boolean;
var
I: Integer;
begin
Result := False;
FSync.Enter;
try
for I := 0 to FProviders.Count - 1 do
if FProviders[I].Supports(Path) then
begin
Result := True;
Exit;
end;
finally
FSync.Leave;
end;
end;
destructor TPathProviderManager.Destroy;
begin
F(FSync);
FreeList(FProviders);
inherited;
end;
function TPathProviderManager.ExecuteFeature(Sender: TObject; Path,
Feature: string): Boolean;
var
PL: TPathItemCollection;
P: TPathItem;
begin
Result := False;
P := CreatePathItem(Path);
try
if P <> nil then
begin
if P.Provider.SupportsFeature(Feature) then
begin
PL := TPathItemCollection.Create;
try
PL.Add(P);
Result := P.Provider.ExecuteFeature(Sender, PL, Feature, nil);
finally
F(PL);
end;
end;
end;
finally
F(P);
end;
end;
function TPathProviderManager.Find(
ProviderClass: TPathProviderClass): TPathProvider;
var
I: Integer;
begin
Result := nil;
FSync.Enter;
try
for I := 0 to FProviders.COunt - 1 do
if FProviders[I] is ProviderClass then
begin
Result := FProviders[I];
Exit;
end;
finally
FSync.Leave;
end;
end;
function TPathProviderManager.GetCount: Integer;
begin
FSync.Enter;
try
Result := FProviders.Count;
finally
FSync.Leave;
end;
end;
function TPathProviderManager.GetPathProvider(
PathItem: TPathItem): TPathProvider;
var
I: Integer;
begin
Result := nil;
FSync.Enter;
try
for I := 0 to FProviders.COunt - 1 do
if FProviders[I].Supports(PathItem) then
begin
Result := FProviders[I];
Exit;
end;
finally
FSync.Leave;
end;
end;
function TPathProviderManager.GetProviderByIndex(Index: Integer): TPathProvider;
begin
FSync.Enter;
try
Result := FProviders[Index];
finally
FSync.Leave;
end;
end;
procedure TPathProviderManager.RegisterProvider(Provider: TPathProvider);
begin
FSync.Enter;
try
FProviders.Add(Provider);
finally
FSync.Leave;
end;
end;
procedure TPathProviderManager.RegisterSubProvider(ProviderClass,
ProviderSubClass: TPathProviderClass; InsertAsFirst: Boolean = False);
var
I, J: Integer;
begin
for I := 0 to Count - 1 do
if TPathProvider(FProviders[I]) is ProviderClass then
begin
for J := 0 to FProviders.Count - 1 do
if FProviders[J] is ProviderSubClass then
FProviders[I].RegisterExtension(TPathProvider(FProviders[J]), InsertAsFirst);
Break;
end;
end;
{ TPathItem }
procedure TPathItem.Assign(Item: TPathItem);
begin
F(FImage);
F(FParent);
FCanHaveChildren := Item.FCanHaveChildren;
FPath := Item.Path;
FDisplayName := Item.DisplayName;
F(FImage);
if Item.FImage <> nil then
FImage := Item.FImage.Copy;
end;
function TPathItem.Copy: TPathItem;
begin
Result := InternalCreateNewInstance;
Result.Assign(Self);
end;
constructor TPathItem.Create;
begin
FImage := nil;
FParent := nil;
FTag := 0;
end;
constructor TPathItem.CreateFromPath(APath: string; Options, ImageSize: Integer);
begin
FCanHaveChildren := True;
FPath := APath;
FImage := nil;
FParent := nil;
FDisplayName := APath;
FOptions := Options;
FImageSize := ImageSize;
end;
destructor TPathItem.Destroy;
begin
F(FImage);
F(FParent);
inherited;
end;
procedure TPathItem.DetachImage;
begin
FImage := nil;
end;
function TPathItem.EqualsTo(Item: TPathItem): Boolean;
begin
if Item = nil then
Exit(False);
Result := Item.Path = Path;
end;
function TPathItem.ExtractImage: TPathImage;
begin
Result := FImage;
FImage := nil;
end;
function TPathItem.GetDisplayName: string;
begin
Result := FDisplayName;
end;
function TPathItem.GetFileSize: Int64;
begin
Result := 0;
end;
function TPathItem.GetIsDirectory: Boolean;
begin
Result := False;
end;
function TPathItem.GetIsInternalIcon: Boolean;
begin
Result := False;
end;
function TPathItem.GetParent: TPathItem;
begin
if FParent = nil then
FParent := InternalGetParent;
Result := FParent;
end;
function TPathItem.GetPath: string;
begin
Result := FPath;
end;
function TPathItem.GetPathImage: TPathImage;
begin
if FImage = nil then
LoadImage;
Result := FImage;
end;
function TPathItem.GetProvider: TPathProvider;
begin
Result := PathProviderManager.GetPathProvider(Self);
end;
function TPathItem.InternalCreateNewInstance: TPathItem;
begin
Result := TPathItem.Create;
end;
function TPathItem.InternalGetParent: TPathItem;
begin
Result := nil;
end;
function TPathItem.LoadImage: Boolean;
begin
Result := LoadImage(Options, ImageSize);
end;
function TPathItem.LoadImage(AOptions, AImageSize: Integer): Boolean;
begin
Result := False;
end;
procedure TPathItem.SetDisplayName(const Value: string);
begin
FDisplayName := Value;
end;
procedure TPathItem.SetImage(const Value: TPathImage);
begin
F(FImage);
FImage := Value;
end;
procedure TPathItem.UpdateImage(ImageSize: Integer);
begin
if Assigned(PathProvider_UpdateImage) then
PathProvider_UpdateImage(Self, ImageSize);
end;
procedure TPathItem.UpdatePath(Path: string);
begin
FPath := Path;
end;
procedure TPathItem.UpdateText;
begin
if Assigned(PathProvider_UpdateText) then
PathProvider_UpdateText(Self);
end;
{ TPathItemCollection }
procedure TPathItemCollection.FreeItems;
var
Item: TPathItem;
begin
for Item in Self do
Item.Free;
Clear;
end;
{ TPathProvider }
function TPathProvider.ExecuteFeature(Sender: TObject; Items: TPathItemCollection;
Feature: string; Options: TPathFeatureOptions): Boolean;
begin
if not SupportsFeature(Feature) then
raise Exception.Create('Not supported!');
Result := False;
end;
constructor TPathProvider.Create;
begin
FExtProviders := TList<TPathProvider>.Create;
end;
function TPathProvider.CreateFromPath(Path: string): TPathItem;
begin
Result := nil;
end;
destructor TPathProvider.Destroy;
begin
F(FExtProviders);
inherited;
end;
function TPathProvider.ExtractPreview(Item: TPathItem; MaxWidth,
MaxHeight: Integer; var Bitmap: TBitmap; var Data: TObject): Boolean;
begin
Result := False;
end;
function TPathProvider.FillChildList(Sender: TObject; Item: TPathItem;
List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean;
var
I: Integer;
begin
Result := InternalFillChildList(Sender, Item, List, Options, ImageSize, PacketSize, CallBack);
for I := 0 to FExtProviders.Count - 1 do
Result := Result and FExtProviders[I].InternalFillChildList(Sender, Item, List, Options, ImageSize, PacketSize, CallBack);
end;
function TPathProvider.FillChildList(Sender: TObject; Item: TPathItem;
List: TPathItemCollection; Options, ImageSize, PacketSize: Integer;
CallBack: TLoadListCallBackRef): Boolean;
begin
if not Assigned(CallBack) then
begin
Result := FillChildList(Sender, Item, List, Options, ImageSize, PacketSize, TLoadListCallBack(nil));
Exit;
end;
List.Tag := Integer(@CallBack);
Result := FillChildList(Sender, Item, List, Options, ImageSize, PacketSize, InternalCallBack);
end;
function TPathProvider.FillChilds(Sender: TObject; Item: TPathItem;
List: TPathItemCollection; Options, ImageSize: Integer): Boolean;
begin
Result := InternalFillChildList(Sender, Item, List, Options, ImageSize, MaxInt, FillChildsCallBack);
end;
procedure TPathProvider.FillChildsCallBack(Sender: TObject; Item: TPathItem;
CurrentItems: TPathItemCollection; var Break: Boolean);
begin
Break := False;
end;
procedure TPathProvider.InternalCallBack(Sender: TObject; Item: TPathItem;
CurrentItems: TPathItemCollection; var Break: Boolean);
var
FCallBackRef: TLoadListCallBackRef;
begin
FCallBackRef := TLoadListCallBackRef(Pointer(CurrentItems.Tag)^);
FCallBackRef(Sender, Item, CurrentItems, Break);
end;
function TPathProvider.InternalFillChildList(Sender: TObject; Item: TPathItem;
List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean;
begin
Result := False;
end;
procedure TPathProvider.RegisterExtension(ExtProvider: TPathProvider; InsertAsFirst: Boolean = False);
begin
if InsertAsFirst then
FExtProviders.Insert(0, ExtProvider)
else
FExtProviders.Add(ExtProvider);
end;
function TPathProvider.Supports(Path: string): Boolean;
begin
Result := False;
end;
function TPathProvider.Supports(PathItem: TPathItem): Boolean;
begin
Result := False;
end;
function TPathProvider.SupportsFeature(Feature: string): Boolean;
begin
Result := False;
end;
{ TPathImage }
constructor TPathImage.Create(Icon: TIcon);
begin
Init;
FIcon := Icon;
end;
constructor TPathImage.Create(Icon: HIcon);
begin
Init;
FHIcon := Icon;
end;
procedure TPathImage.AddToImageList(ImageList: TCustomImageList);
begin
if FHIcon <> 0 then
ImageList_ReplaceIcon(ImageList.Handle, -1, FHIcon)
else if FIcon <> nil then
ImageList_ReplaceIcon(ImageList.Handle, -1, FIcon.Handle)
else if FBitmap <> nil then
ImageList.Add(FBitmap, nil);
end;
procedure TPathImage.Assign(Source: TPathImage; DetachSource: Boolean = False);
begin
Clear;
if DetachSource then
begin
FHIcon := Source.HIcon;
FIcon := Source.FIcon;
FBitmap := Source.FBitmap;
Source.DetachImage;
end else
begin
if Source.HIcon <> 0 then
FHIcon := CopyIcon(Source.HIcon);
if Source.Icon <> nil then
begin
FIcon := TIcon.Create;
FIcon.Assign(Source.Icon);
end;
if Source.Bitmap <> nil then
begin
FBitmap := TBitmap.Create;
FBitmap.Assign(Source.Bitmap);
end;
end;
end;
procedure TPathImage.Clear;
begin
F(FIcon);
F(FBitmap);
if FHIcon <> 0 then
DestroyIcon(FHIcon);
FHIcon := 0;
end;
function TPathImage.Copy: TPathImage;
var
Ico: TIcon;
Bit: TBitmap;
begin
if FHIcon <> 0 then
Result := TPathImage.Create(CopyIcon(HIcon))
else if FIcon <> nil then
begin
Ico := TIcon.Create;
try
Ico.Handle := CopyIcon(FIcon.Handle);
Result := TPathImage.Create(Ico);
Ico := nil;
finally
F(Ico);
end;
end else
begin
Bit := TBitmap.Create;
try
Bit.Assign(FBitmap);
Result := TPathImage.Create(Bit);
Bit := nil;
finally
F(Bit);
end;
end;
end;
constructor TPathImage.Create(Bitmap: TBitmap);
begin
Init;
FBitmap := Bitmap;
end;
destructor TPathImage.Destroy;
begin
Clear;
end;
procedure TPathImage.DetachImage;
begin
Init;
end;
function TPathImage.GetGraphic: TGraphic;
begin
Result := nil;
if FBitmap <> nil then
Result := FBitmap
else if FIcon <> nil then
Result := FIcon
else if FHIcon <> 0 then
begin
FIcon := TIcon.Create;
FIcon.Handle := CopyIcon(FHIcon);
Result := FIcon;
end;
end;
procedure TPathImage.Init;
begin
FHIcon := 0;
FIcon := nil;
FBitmap := nil;
end;
{ TPathFeatureEditOptions }
constructor TPathFeatureEditOptions.Create(ANewName: string);
begin
FNewName := ANewName;
end;
{ TPathFeatureDeleteOptions }
constructor TPathFeatureDeleteOptions.Create(ASilent: Boolean);
begin
FSilent := ASilent;
end;
initialization
finalization
F(FPathProviderManager);
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;
{$MODE Delphi}
interface
uses
Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller,
VO, PessoaVO, ZDataSet;
type
TPessoaController = class(TController)
private
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaLista(pFiltro: String): TListaPessoaVO;
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;
end;
implementation
uses T2TiORM,
PessoaFisicaVO, PessoaJuridicaVO, PessoaContatoVO, PessoaEnderecoVO,
PessoaTelefoneVO, PessoaAlteracaoVO;
var
ObjetoLocal: TPessoaVO;
class function TPessoaController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TPessoaVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TPessoaController.ConsultaLista(pFiltro: String): TListaPessoaVO;
begin
try
ObjetoLocal := TPessoaVO.Create;
Result := TListaPessoaVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class function TPessoaController.ConsultaObjeto(pFiltro: String): TPessoaVO;
begin
try
Result := TPessoaVO.Create;
Result := TPessoaVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
finally
end;
end;
class procedure TPessoaController.Insere(pObjeto: TPessoaVO);
var
UltimoID: Integer;
Contato: TPessoaContatoVO;
Endereco: TPessoaEnderecoVO;
Telefone: 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;
{kalel
// 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
PessoaAlteracao: TPessoaAlteracaoVO;
PessoaOld: TPessoaVO;
TipoPessoa: String;
begin
try
PessoaOld := ConsultaObjeto('ID='+ IntToStr(pObjeto.Id));
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;
{kalel
// 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);
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);
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);
finally
FreeAndNil(ObjetoLocal)
end;
end;
initialization
Classes.RegisterClass(TPessoaController);
finalization
Classes.UnRegisterClass(TPessoaController);
end.
|
unit AStarFrm;
{ [1] AStar Cube..Data Display Demo Directions
[2] Demo #1 Smiley
[3] PATHFINDING DEMO #2 - Smiley & Chaser
[4] PATHFINDING DEMO #3 - Smiley & Chaser (4-way)
[5] ;PATHFINDING DEMO #4a - Collision Avoidance (loop-based)
[6] ;PATHFINDING DEMO #4b - Collision Avoidance (time-based)
[7] ;PATHFINDING DEMO #5 - Group Movement }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics,
Printers, Menus, ImgList,
Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, System.ImageList;
type
TAStarForm = class(TForm)
Panel1: TPanel;
StatusBar1: TStatusBar;
MainMenu1: TMainMenu;
File1: TMenuItem;
RunMenu: TMenuItem;
Help1: TMenuItem;
Contents1: TMenuItem;
OnHelp1: TMenuItem;
Main1: TMenuItem;
About1: TMenuItem;
Open1: TMenuItem;
Save1: TMenuItem;
SaveAs1: TMenuItem;
N1: TMenuItem;
Print1: TMenuItem;
N2: TMenuItem;
Exit1: TMenuItem;
Run1: TMenuItem;
Walk1: TMenuItem;
Crawl1: TMenuItem;
Pause1: TMenuItem;
New1: TMenuItem;
View1: TMenuItem;
ProjectOptions1: TMenuItem;
Terrain3D1: TMenuItem;
PrinterSetupDialog1: TPrinterSetupDialog;
OpenDialog: TOpenDialog;
SaveDialog1: TSaveDialog;
SetupPrinter1: TMenuItem;
SearchMenu: TMenuItem;
Dijkstra1: TMenuItem;
ProjectMenu: TMenuItem;
AStarDataDisplayMenu: TMenuItem;
ComegetsomeMenu: TMenuItem;
GoGowishuponAStarMenu: TMenuItem;
KingAstaroftheMistyValleyMenu: TMenuItem;
KingAstarDynamicChaseMenu: TMenuItem;
CollisionAvoidancetimebased1: TMenuItem;
GroupMovement1: TMenuItem;
ScrollBox1: TScrollBox;
AStarImage: TImage;
N3: TMenuItem;
SizeMenu: TMenuItem;
Size256: TMenuItem;
Size512: TMenuItem;
Size650x500: TMenuItem;
Size800x600: TMenuItem;
Timer1: TTimer;
Size1024x1024: TMenuItem;
N4: TMenuItem;
Tools1: TMenuItem;
GridLines1: TMenuItem;
PathDisplay1: TMenuItem;
Size1280x1280: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
Size640x640: TMenuItem;
PrintDialog1: TPrintDialog;
Memo1: TMemo;
MemoActive: TMenuItem;
ImageList1: TImageList;
ImageList0: TImageList;
Size2560x2560: TMenuItem;
BFS1: TMenuItem;
Label1: TLabel;
Unit1Status: TLabel;
Unit2Status: TLabel;
Unit3Status: TLabel;
Unit4Status: TLabel;
Unit5Status: TLabel;
EnemyUnitStatus: TLabel;
Unit1Time: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
N7: TMenuItem;
TileSizeMenu: TMenuItem;
TileSize50x50: TMenuItem;
TileSize10x10: TMenuItem;
TileSize32x32: TMenuItem;
TileSize1x1: TMenuItem;
ProgressBar1: TProgressBar;
Diagonal1: TMenuItem;
Manhattan1: TMenuItem;
GR32Viewer1: TMenuItem;
Trot1: TMenuItem;
Jog1: TMenuItem;
Gallop1: TMenuItem;
Glide1: TMenuItem;
Trundle1: TMenuItem;
Toddle1: TMenuItem;
TieBreakersMenu: TMenuItem;
TBNone1: TMenuItem;
TBStraight1: TMenuItem;
TBClose1: TMenuItem;
TBFar1: TMenuItem;
SplashScreen1: TMenuItem;
AutoloadObstacleFile1: TMenuItem;
N9: TMenuItem;
ClearObstacles1: TMenuItem;
SetRandomObstacles1: TMenuItem;
Euclidean1: TMenuItem;
N10: TMenuItem;
TileSize16x16: TMenuItem;
TileSize8x8: TMenuItem;
Size2048x2048: TMenuItem;
Size4096x4096: TMenuItem;
TileSize2x2: TMenuItem;
TileSize4x4: TMenuItem;
N11: TMenuItem;
SaveUnitLocationsauf1: TMenuItem;
ProjectLandscaper1: TMenuItem;
N12: TMenuItem;
ProjectMapPainter1: TMenuItem;
UseOriginal1: TMenuItem;
N8: TMenuItem;
ProgramOptions1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure DisplayPOFSettings;
procedure ShowHint(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure AutoloadObstacleFile1Click(Sender: TObject);
procedure ClearObstacles1Click(Sender: TObject);
procedure SetRandomObstacles1Click(Sender: TObject);
procedure SaveUnitLocationsauf1Click(Sender: TObject);
procedure ProjectLandscaper1Click(Sender: TObject);
procedure ProjectMapPainter1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure Contents1Click(Sender: TObject);
procedure OnHelp1Click(Sender: TObject);
procedure Main1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure GridLines1Click(Sender: TObject);
procedure PathDisplay1Click(Sender: TObject);
procedure MemoActiveClick(Sender: TObject);
procedure New1Click(Sender: TObject);
procedure Open1Click(Sender: TObject);
procedure LoadObstacleData(fileName: String);
procedure Save1Click(Sender: TObject);
procedure SaveAs1Click(Sender: TObject);
procedure SetupPrinter1Click(Sender: TObject);
procedure Print1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure TileSizeMenuClick(Sender: TObject);
procedure TieBreakersMenuClick(Sender: TObject);
procedure SplashScreen1Click(Sender: TObject);
procedure GR32Viewer1Click(Sender: TObject);
procedure ProjectOptions1Click(Sender: TObject);
procedure Terrain3D1Click(Sender: TObject);
procedure SizeMenuClick(Sender: TObject);
procedure ResizeImage; // (Width,Height:Integer)
procedure LoadUnitData;
procedure RedrawData;
procedure ProjectMenuClick(Sender: TObject);
procedure RunMenuClick(Sender: TObject);
procedure SearchMenuClick(Sender: TObject);
procedure AStarImageMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure AStarImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Timer1Timer(Sender: TObject);
procedure DoSingleStepDrawing(Step: Integer);
procedure RunAStarProject;
procedure PaintAStarPath(ID: Integer);
procedure UseOriginal1Click(Sender: TObject);
procedure ProgramOptions1Click(Sender: TObject);
private
{ Private declarations }
public
UseOriginal: Boolean;
FPSCount: Integer;
AStarObstacleFileName: String;
end;
var
AStarForm: TAStarForm;
//==================================================================
implementation
//==================================================================
uses
AStarGlobals,
AStarCode,
AStarCodeH,
AStarAboutFrm, // About
AProjectOptionsFrm, // Options
fLandscape, // Terrain Creation
AProjectMapMakerFrm, // Terrain painter
AGr32ViewerFrm, // Gr32 Viewer: Bitmap sprites
ATerrainFrm, // 3D GLScene Viewer
GLVectorGeometry, // math atan2
GLCrossPlatform, // PrecisionTimer
JPeg, // Load textures
GLKeyboard, AProgramOptionsFrm; // User Interface
{$R *.DFM}
procedure TAStarForm.FormCreate(Sender: TObject);
var
dc: HDC;
temp: Integer;
begin
if FileExists(ExtractFilePath(ParamStr(0)) + 'AStar.pof') then
begin
DoLoader;
end
else
begin
ResetDefaults;
end;
dc := GetDc(0);
if not(GetDeviceCaps(dc, BITSPIXEL) = 32) then
begin
ShowMessage('32 bit Color Required' + #13#10 +
'Application Termination Suggested' + #13#10 + 'No idea what happens next'
+ #13#10 + 'All bets are off, AI is Offline');
end; // DisplaySplashScreen;
temp := ReleaseDc(0, dc); { Give back the screen dc }
if temp <> 1 then
Application.Terminate; // something REALLY failed
// Set Variables Not set by POF
EditModeActive := True;
LostinaLoop := False;
AstarUnitsRunning := False;
UseOriginal := False;
AStarObstacleFileName := '';
ProjectFilename := '';
// ProjectDirectory
ActiveEnemyNumber := 0;
gScreenCaptureNumber := 0;
FPSCount := 0;
left := AStarFormX;
top := AStarFormY;
// Makes Viewer: W650 x H500
Width := 767;
Height := 569;
SplashScreen1.Checked := SplashScreenDisplayed;
AutoloadObstacleFile1.Checked := AutoloadObstacleFile;
case SearchMode of
0:
begin
Dijkstra1.Checked := True;
End;
1:
begin
Diagonal1.Checked := True;
End;
2:
begin
Manhattan1.Checked := True;
End;
3:
begin
BFS1.Checked := True;
End;
4:
begin
Euclidean1.Checked := True;
End;
End; // case
case TieBreakerMode of
0:
begin
TBNone1.Checked := True;
End;
1:
begin
TBStraight1.Checked := True;
End;
2:
begin
TBClose1.Checked := True;
End;
3:
begin
TBFar1.Checked := True;
End;
End; // case
case TileSizeMode of
0:
begin
TileSize50x50.Checked := True;
tileSize := 50;
End;
1:
begin
TileSize32x32.Checked := True;
tileSize := 32;
End;
2:
begin
TileSize16x16.Checked := True;
tileSize := 16;
End;
3:
begin
TileSize10x10.Checked := True;
tileSize := 10;
End;
4:
begin
TileSize8x8.Checked := True;
tileSize := 8;
End;
5:
begin
TileSize4x4.Checked := True;
tileSize := 4;
End;
6:
begin
TileSize2x2.Checked := True;
tileSize := 2;
End;
7:
begin
TileSize1x1.Checked := True;
tileSize := 1;
End;
end;
case ImageSizeMode of
0:
begin
Size650x500.Checked := True;
ImageWidth := 650;
ImageHeight := 500;
End;
1:
begin
Size800x600.Checked := True;
ImageWidth := 800;
ImageHeight := 600;
End;
2:
begin
Size640x640.Checked := True;
ImageWidth := 640;
ImageHeight := 640;
End;
3:
begin
Size1280x1280.Checked := True;
ImageWidth := 1280;
ImageHeight := 1280;
End;
4:
begin
Size2560x2560.Checked := True;
ImageWidth := 2560;
ImageHeight := 2560;
End;
5:
begin
Size256.Checked := True;
ImageWidth := 256;
ImageHeight := 256;
End;
6:
begin
Size512.Checked := True;
ImageWidth := 512;
ImageHeight := 512;
End;
7:
begin
Size1024x1024.Checked := True;
ImageWidth := 1024;
ImageHeight := 1024;
End;
8:
begin
Size2048x2048.Checked := True;
ImageWidth := 2048;
ImageHeight := 1024;
End;
9:
begin
Size4096x4096.Checked := True;
ImageWidth := 4096;
ImageHeight := 1024;
End;
End; // case
case AstarMode of
1: AStarDataDisplayMenu.Click;
2: ComegetsomeMenu.Click;
3: GoGowishuponAStarMenu.Click;
4: KingAstarDynamicChaseMenu.Click;
5: KingAstaroftheMistyValleyMenu.Click;
6: CollisionAvoidancetimebased1.Click;
7: GroupMovement1.Click;
End; // case
// InitializePathfinder;
// Set any Changes..Defaults from POF
DisplayPOFSettings;
end;
procedure TAStarForm.FormActivate(Sender: TObject);
begin
DisplayPOFSettings;
end;
procedure TAStarForm.DisplayPOFSettings;
Begin
GridLines1.Checked := GridLinesDisplayed;
PathDisplay1.Checked := PathDisplayed;
End;
procedure TAStarForm.ShowHint(Sender: TObject);
begin
StatusBar1.Panels[5].Text := Application.Hint;
end;
procedure TAStarForm.FormShow(Sender: TObject);
begin
Application.OnHint := AStarForm.ShowHint;
// StatusBar1.Panels[5].Text := Application.Hint;
// Tip: To further customize the hint window,
// create a custom descendant of THintWindow
// and assign it to the global HintWindowClass variable.
end;
{ //ScreenCapture by pressing print screen or F12. Successive screen
//captures during the same program run will be saved separately.
Function ScreenCapture()
If KeyHit(88) Or KeyHit(183)
SaveBuffer(BackBuffer(),"screenshot"+gScreenCaptureNumber+".bmp")
gScreenCaptureNumber = gScreenCaptureNumber+1 ;global enables multiple captures
EndIf
End Function }
procedure TAStarForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// Cancel AStar pathfinding loop
if ssCtrl in Shift then
begin
If (Key = VK_F2) then
LostinaLoop := False;
If (Key = VK_F9) then
AstarUnitsRunning := (not AstarUnitsRunning);
// If KeyHit(88) Or KeyHit(183)
If (Key = VK_F12) then
AStarImage.picture.savetofile(ProjectDirectory + AStarObstacleFileName +
'screenshot' + inttostr(gScreenCaptureNumber) + '.bmp');
gScreenCaptureNumber := gScreenCaptureNumber + 1;
// global enables multiple captures
End;
if (Key = VK_ESCAPE) then
Close
else // if Key = #27 then Close;
if (Key = VK_RETURN) then
begin
// Enter key Toggles smileyActivated
// If smileyActivated then CreateMapImage() else EditMap();
EditModeActive := (not EditModeActive);
If EditModeActive then
StatusBar1.Panels[0].Text := 'Edit Mode'
else
StatusBar1.Panels[0].Text := 'Path Mode';
If AstarMode = 7 then
begin { This should be in Mouse Event
gGameStarted = False
For unit.unit = Each unit
unit\pathStatus = notstarted
//gDrawMore is toggled by Menu DrawPaths
;Toggle drawing more (Path Line) by pressing space bar
If KeyHit(57) Then gDrawMore = 1-gDrawMore
}
end;
end
else if ssCtrl in Shift then
begin
If ActiveEnemyNumber > 0 then
begin
if (Key = $31) then
ActiveEnemyNumber := 1
else if (Key = $32) then
ActiveEnemyNumber := 2
else if (Key = $33) then
ActiveEnemyNumber := 3
else if (Key = $34) then
ActiveEnemyNumber := 4
else if (Key = $35) then
ActiveEnemyNumber := 5;
if (Key = $36) then
begin
ActiveEnemyNumber := 6; // 6;//?
StatusBar1.Panels[2].Text := 'Enemy Unit ';
// +'Unit # '+Inttostr(ActiveUnitNumber);
end
else
StatusBar1.Panels[2].Text := 'Enemy # ' + inttostr(ActiveEnemyNumber);
end;
end
else
begin
// 5 Units possible + 1 Enemy
if (Key = $31) then
ActiveUnitNumber := 1
else if (Key = $32) then
ActiveUnitNumber := 2
else if (Key = $33) then
ActiveUnitNumber := 3
else if (Key = $34) then
ActiveUnitNumber := 4
else if (Key = $35) then
ActiveUnitNumber := 5;
If ActiveUnitNumber > NumberofUnits then
ActiveUnitNumber := NumberofUnits;
StatusBar1.Panels[2].Text := 'Unit # ' + inttostr(ActiveUnitNumber);
if (Key = $39) then
DoSingleStepDrawing(9); // key 9 Start SingleStep Drawing
if (Key = $30) then
DoSingleStepDrawing(0); // key 0 Finish Drawing
end;
end;
procedure TAStarForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
AStarFormX := AStarForm.left;
AStarFormY := AStarForm.top;
// showmessage('what');
DoSaver;
Application.ProcessMessages;
end;
procedure TAStarForm.FormDestroy(Sender: TObject);
begin
SetLength(MAGColorValueArray, 0);
EndPathfinder;
end;
procedure TAStarForm.Contents1Click(Sender: TObject);
begin
// Application.HelpFile := 'MYHELP.HLP';
// Application.HelpCommand(HELP_FINDER, 0);
Application.HelpCommand(HELP_CONTENTS, 0);
end;
procedure TAStarForm.OnHelp1Click(Sender: TObject);
begin
Application.HelpCommand(HELP_HELPONHELP, 0);
end;
procedure TAStarForm.Main1Click(Sender: TObject);
// Application.HelpContext(234);
var
PathS: string;
begin
PathS := ExtractFilePath(ParamStr(0));
if FileExists(PathS + 'astar1.html') then
ExecuteFile('astar1.html', '', PathS, SW_SHOW)
end;
procedure TAStarForm.About1Click(Sender: TObject);
begin
// AStarAboutForm.Show;
AStarAboutForm := TAStarAboutForm.Create(Application);
AStarAboutForm.ShowModal;
AStarAboutForm.Free;
end;
procedure TAStarForm.New1Click(Sender: TObject);
var
X, Y: Integer;
begin
// Reset whatever
EditModeActive := True;
AStarObstacleFileName := '';
ProjectFilename := '';
// initialize the map to completely walkable
for X := 0 to mapWidth do
for Y := 0 to mapHeight do
walkability[X][Y] := walkable;
// Repaint the Image
ResizeImage;
end;
procedure TAStarForm.Open1Click(Sender: TObject);
begin
// astar|*.dat|jpeg|*.jpg|bitmap|*.bmp|png|*.png ;*.dat
OpenDialog.Filter := 'astar Obstacle files|*.aof'; //
OpenDialog.InitialDir := ProjectDirectory;
// Clear or set anything previous
OpenDialog.fileName := ''; // '*.aof'; //'tile10x80x60.aof';
if OpenDialog.Execute then
Begin
// ProjectDirectory:=ExtractFilePath(OpenDialog.FileName);
Application.ProcessMessages;
{ if uppercase(extractfileext(OpenDialog.filename))='.APF' then
LoadProjectData(OpenDialog.FileName) else }
if uppercase(extractfileext(OpenDialog.fileName)) = '.AOF' then
LoadObstacleData(OpenDialog.fileName);
End;
end;
procedure TAStarForm.LoadObstacleData(fileName: String);
var
// F: TextFile; S: string;
F: File of Integer; // byte;
z, // :byte;
intilesize, inmapwidth, inmapHeight, X, Y: Integer;
Begin
Application.ProcessMessages;
AStarObstacleFileName := extractfilename(fileName);
AStarForm.Caption := 'AStar: ' + AStarObstacleFileName;
AssignFile(F, fileName);
Reset(F);
Read(F, intilesize);
Read(F, inmapwidth);
Read(F, inmapHeight);
If intilesize <= tileSize then
begin
for X := 0 to inmapwidth - 1 do
for Y := 0 to inmapHeight - 1 do
begin
Read(F, z);
walkability[X][Y] := z;
// Read(F, walkability [x][y]);
if (walkability[X][Y] > 1) then
walkability[X][Y] := 0;
end;
end
else
ShowMessage('in tilesize: ' + inttostr(intilesize) + ' is larger than ' +
inttostr(intilesize));
CloseFile(F);
RedrawData;
// Called when Moused... Things Might change... island
// If ProcessNoGoIslands then IdentifyIslands;
End;
procedure TAStarForm.Save1Click(Sender: TObject);
var
F: File of Integer;
X, Y, z: Integer;
begin
If AStarObstacleFileName = '' then
SaveAs1Click(Sender)
else
begin
Application.ProcessMessages;
AssignFile(F, ProjectDirectory + AStarObstacleFileName);
Rewrite(F);
write(F, tileSize);
write(F, mapWidth);
write(F, mapHeight);
for X := 0 to mapWidth - 1 do
for Y := 0 to mapHeight - 1 do
begin // walkable is 0
if (walkability[X][Y] <> 1) then
walkability[X][Y] := 0;
z := walkability[X][Y];
write(F, z);
end;
CloseFile(F);
end;
end;
procedure TAStarForm.SaveAs1Click(Sender: TObject);
begin
// astar|*.dat|jpeg|*.jpg|bitmap|*.bmp|png|*.png
SaveDialog1.Filter := 'astar.aof or bitmap.bmp|*.aof|bitmap|*.bmp';
SaveDialog1.InitialDir := ProjectDirectory;
SaveDialog1.fileName := AStarObstacleFileName;
if SaveDialog1.Execute then
Begin
if uppercase(extractfileext(SaveDialog1.fileName)) = '.AOF' then
begin
// ProjectDirectory:=ExtractFilePath(savedialog1.FileName);
AStarObstacleFileName := extractfilename(SaveDialog1.fileName);
Save1Click(Sender);
end
else if uppercase(extractfileext(SaveDialog1.fileName)) = '.BMP' then
begin
AStarImage.picture.savetofile(SaveDialog1.fileName);
end;
end;
end;
procedure TAStarForm.ProgramOptions1Click(Sender: TObject);
begin
AProgramOptionsForm.Show;
{ AProgramOptionsForm := TAProgramOptionsForm.Create(Application);
AProgramOptionsForm.ShowModal;
AProgramOptionsForm.Free;
DisplayPOFSettings; }
end;
procedure TAStarForm.SetupPrinter1Click(Sender: TObject);
begin
PrinterSetupDialog1.Execute;
end;
procedure TAStarForm.Print1Click(Sender: TObject);
// var p:TPoint;
begin
If PrintDialog1.Execute then
with Printer do
begin
// p:=getscale(pagewidth-1,pageheight-1);
BeginDoc;
// printer.canvas.stretchDraw(rect(1,1,p.x-2,p.y-2),AStarImage.picture.bitmap);
Canvas.Draw((PageWidth - AStarImage.picture.bitmap.Width) div 2,
(PageHeight - AStarImage.picture.bitmap.Height) div 2,
AStarImage.picture.bitmap);
EndDoc;
end;
end;
procedure TAStarForm.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TAStarForm.ProjectOptions1Click(Sender: TObject);
begin
AProjectOptionsForm.ShowModal; // Options
{ AProjectOptionsForm := TAProjectOptionsForm.Create(Application);
AProjectOptionsForm.ShowModal;
AProjectOptionsForm.Free;
DisplayPOFSettings; }
end;
procedure TAStarForm.ProjectLandscaper1Click(Sender: TObject);
begin
// frmLandscape.show;
frmLandscape := TfrmLandscape.Create(Application);
frmLandscape.ShowModal;
frmLandscape.Free;
end;
procedure TAStarForm.ProjectMapPainter1Click(Sender: TObject);
begin
AProjectMapMakerForm := TAProjectMapMakerForm.Create(Application);
AProjectMapMakerForm.ShowModal;
AProjectMapMakerForm.Free;
end;
procedure TAStarForm.GR32Viewer1Click(Sender: TObject);
begin
OpenDialog.Filter := 'astar projects|*.apf';
OpenDialog.InitialDir := ProjectDirectory;
OpenDialog.fileName := '*.apf';
if OpenDialog.Execute then
begin
Application.ProcessMessages;
if uppercase(extractfileext(OpenDialog.fileName)) = '.APF' then
begin // All inside as No Test mode...
ProjectFilename := OpenDialog.fileName;
AGr32ViewerForm := TAGr32ViewerForm.Create(Application);
AGr32ViewerForm.ShowModal;
AGr32ViewerForm.Free;
ProjectFilename := '';
end;
end;
end;
procedure TAStarForm.Terrain3D1Click(Sender: TObject);
begin
ProjectFilename := ''; // to enable Testing
OpenDialog.Filter := 'astar projects|*.apf';
OpenDialog.InitialDir := ProjectDirectory;
OpenDialog.fileName := '*.apf';
if OpenDialog.Execute then
begin
Application.ProcessMessages;
if uppercase(extractfileext(OpenDialog.fileName)) = '.APF' then
begin
ProjectFilename := OpenDialog.fileName;
end;
end;
// ATerrainForm 3D Viewer
ATerrainForm := TATerrainForm.Create(Application);
ATerrainForm.ShowModal;
ATerrainForm.Free;
ProjectFilename := '';
end;
procedure TAStarForm.ClearObstacles1Click(Sender: TObject);
var
X, Y: Integer;
begin
for X := 0 to mapWidth - 1 do
for Y := 0 to mapHeight - 1 do
walkability[X][Y] := 0;
RedrawData;
end;
procedure TAStarForm.SetRandomObstacles1Click(Sender: TObject);
var
X, Y, z: Integer;
begin
for X := 0 to mapWidth - 1 do
for Y := 0 to mapHeight - 1 do
begin //
z := Random(100);
if (walkability[X][Y] <> 1) then
If z > 92 then
walkability[X][Y] := 1; // obstacle created
end;
RedrawData;
end;
procedure TAStarForm.SaveUnitLocationsauf1Click(Sender: TObject);
begin
If NumberofUnits >= 5 then
Begin
// Load the file, then Change the Unit Locations.
OpenDialog.Filter := 'astar Units|*.auf';
OpenDialog.InitialDir := ProjectDirectory;
OpenDialog.fileName := '*.auf';
if OpenDialog.Execute then
begin
Application.ProcessMessages;
// FileAufEdit.Text:= OpenDialog.FileName;
LoadUnitsFile(OpenDialog.fileName);
end;
// startXLocArray,startYLocArray, //Set seeker location
// UnitRecordArray[1].startXLoc
// targetXLocArray,targetYLocArray,//Set initial target location.
// UnitRecordArray[1].targetX
// speedArray : Array [1..5]of Integer;
// UnitRecordArray[1].speed
// AProjectOptionsForm.SaveaufBtn.Click
End
else
ShowMessage('Select a Project having All 5 units Active');
end;
procedure TAStarForm.GridLines1Click(Sender: TObject);
begin
GridLines1.Checked := (not GridLines1.Checked);
GridLinesDisplayed := GridLines1.Checked;
end;
procedure TAStarForm.PathDisplay1Click(Sender: TObject);
begin
PathDisplay1.Checked := (not PathDisplay1.Checked);
PathDisplayed := PathDisplay1.Checked;
end;
procedure TAStarForm.SplashScreen1Click(Sender: TObject);
begin
SplashScreen1.Checked := (not SplashScreen1.Checked);
SplashScreenDisplayed := SplashScreen1.Checked;
end;
procedure TAStarForm.AutoloadObstacleFile1Click(Sender: TObject);
begin
AutoloadObstacleFile1.Checked := (not AutoloadObstacleFile1.Checked);
AutoloadObstacleFile := AutoloadObstacleFile1.Checked;
end;
procedure TAStarForm.MemoActiveClick(Sender: TObject);
begin
MemoActive.Checked := (not MemoActive.Checked);
Memo1.Enabled := MemoActive.Checked;
end;
//-----------------------------------------------------------------------
procedure TAStarForm.RunMenuClick(Sender: TObject);
begin
case TComponent(Sender).Tag of
// Key P Pause
// Number of Pixels along Path to move
// maybe Run is 1 ..Amount of Time * ? Application.ProcessMessages
1:
begin
Run1.Checked := True;
speedArray[ActiveUnitNumber] := 9;
End;
2:
begin
Gallop1.Checked := True;
speedArray[ActiveUnitNumber] := 8;
End;
3:
begin
Jog1.Checked := True;
speedArray[ActiveUnitNumber] := 7;
End;
4:
begin
Trot1.Checked := True;
speedArray[ActiveUnitNumber] := 6;
End;
5:
begin
Walk1.Checked := True;
speedArray[ActiveUnitNumber] := 5;
End;
6:
begin
Trundle1.Checked := True;
speedArray[ActiveUnitNumber] := 4;
End;
7:
begin
Glide1.Checked := True;
speedArray[ActiveUnitNumber] := 3;
End;
8:
begin
Toddle1.Checked := True;
speedArray[ActiveUnitNumber] := 2;
End;
9:
begin
Crawl1.Checked := True;
speedArray[ActiveUnitNumber] := 1;
End;
10:
begin
Pause1.Checked := True;
speedArray[ActiveUnitNumber] := 0;
End;
End; // case
end;
procedure TAStarForm.SearchMenuClick(Sender: TObject);
begin
SearchMode := TComponent(Sender).Tag;
case TComponent(Sender).Tag of
0:
begin
Dijkstra1.Checked := True;
End;
1:
begin
Diagonal1.Checked := True;
End;
2:
begin
Manhattan1.Checked := True;
End;
3:
begin
BFS1.Checked := True;
End;
4:
begin
Euclidean1.Checked := True;
End;
End; // case
end;
//-----------------------------------------------------------------------
procedure TAStarForm.UseOriginal1Click(Sender: TObject);
begin
UseOriginal1.Checked := (not UseOriginal1.Checked);
UseOriginal := UseOriginal1.Checked;
end;
procedure TAStarForm.TieBreakersMenuClick(Sender: TObject);
begin
TieBreakerMode := TComponent(Sender).Tag;
case TComponent(Sender).Tag of
0:
begin
TBNone1.Checked := True;
End;
1:
begin
TBStraight1.Checked := True;
End;
2:
begin
TBClose1.Checked := True;
End;
3:
begin
TBFar1.Checked := True;
End;
End; // case
end;
//-----------------------------------------------------------------------
procedure TAStarForm.ProjectMenuClick(Sender: TObject);
begin
EditModeActive := True;
StatusBar1.Panels[0].Text := 'Edit Mode';
// Application.ProcessMessages;
// ResizeImage;
// tileSize:=10;
case TComponent(Sender).Tag of
1:
begin
AStarDataDisplayMenu.Checked := True;
TileSizeMode := 0;
NumberofUnits := 1;
End;
2:
begin
ComegetsomeMenu.Checked := True;
NumberofUnits := 1;
TileSizeMode := 3;
End;
3:
begin
GoGowishuponAStarMenu.Checked := True;
NumberofUnits := 5;
TileSizeMode := 3;
End;
4:
begin
KingAstarDynamicChaseMenu.Checked := True;
NumberofUnits := 3;
TileSizeMode := 3;
End;
5:
begin
KingAstaroftheMistyValleyMenu.Checked := True;
NumberofUnits := 4;
TileSizeMode := 3;
End;
6:
begin
CollisionAvoidancetimebased1.Checked := True;
NumberofUnits := 5;
TileSizeMode := 3;
End;
7:
begin
GroupMovement1.Checked := True;
NumberofUnits := 5;
/// /6; 5or6
TileSizeMode := 3;
End; // Enemy is 6
End; // case
AstarMode := TComponent(Sender).Tag;
case TileSizeMode of
0:
begin
TileSize50x50.Checked := True;
tileSize := 50;
End;
1:
begin
TileSize32x32.Checked := True;
tileSize := 32;
End;
2:
begin
TileSize16x16.Checked := True;
tileSize := 16;
End;
3:
begin
TileSize10x10.Checked := True;
tileSize := 10;
End;
4:
begin
TileSize8x8.Checked := True;
tileSize := 8;
End;
5:
begin
TileSize4x4.Checked := True;
tileSize := 4;
End;
6:
begin
TileSize2x2.Checked := True;
tileSize := 2;
End;
7:
begin
TileSize1x1.Checked := True;
tileSize := 1;
End;
end;
ResizeImage;
end;
//-----------------------------------------------------------------------
procedure TAStarForm.SizeMenuClick(Sender: TObject);
begin
EditModeActive := True;
StatusBar1.Panels[0].Text := 'Edit Mode';
case TComponent(Sender).Tag of
0:
begin
Size650x500.Checked := True;
ImageWidth := 650;
ImageHeight := 500;
End;
1:
begin
Size800x600.Checked := True;
ImageWidth := 800;
ImageHeight := 600;
End;
2:
begin
Size640x640.Checked := True;
ImageWidth := 640;
ImageHeight := 640;
End;
3:
begin
Size1280x1280.Checked := True;
ImageWidth := 1280;
ImageHeight := 1280;
End;
4:
begin
Size2560x2560.Checked := True;
ImageWidth := 2560;
ImageHeight := 2560;
End;
5:
begin
Size256.Checked := True;
ImageWidth := 256;
ImageHeight := 256;
End;
6:
begin
Size512.Checked := True;
ImageWidth := 512;
ImageHeight := 512;
End;
7:
begin
Size1024x1024.Checked := True;
ImageWidth := 1024;
ImageHeight := 1024;
End;
8:
begin
Size2048x2048.Checked := True;
ImageWidth := 2048;
ImageHeight := 1024;
End;
9:
begin
Size4096x4096.Checked := True;
ImageWidth := 4096;
ImageHeight := 1024;
End;
End; // case
ImageSizeMode := TComponent(Sender).Tag;
ResizeImage;
end;
//-----------------------------------------------------------------------
procedure TAStarForm.TileSizeMenuClick(Sender: TObject);
begin
// TileSize50x50 TileSize25x25 TileSize10x10
case TComponent(Sender).Tag of
0:
begin
TileSize50x50.Checked := True;
tileSize := 50;
End;
1:
begin
TileSize32x32.Checked := True;
tileSize := 32;
End;
2:
begin
TileSize16x16.Checked := True;
tileSize := 16;
End;
3:
begin
TileSize10x10.Checked := True;
tileSize := 10;
End;
4:
begin
TileSize8x8.Checked := True;
tileSize := 8;
End;
5:
begin
TileSize4x4.Checked := True;
tileSize := 4;
End;
6:
begin
TileSize2x2.Checked := True;
tileSize := 2;
End;
7:
begin
TileSize1x1.Checked := True;
tileSize := 1;
End;
end;
TileSizeMode := TComponent(Sender).Tag;
ResizeImage;
end;
// This is a Cluster of things
// RedrawData is similar but does NOT ..
// EXPECT a set of things IAW AstarMode
// InitializePathfinder
// load the Map data LoadObstacleData
// Reset Unit data LoadUnitData
procedure TAStarForm.ResizeImage;
var
BitMap1: TBitMap;
X, Y: Integer;
Begin // ResizeImage(256,256);
AStarImage.Width := ImageWidth;
AStarImage.Height := ImageHeight;
BitMap1 := TBitMap.Create;
try
BitMap1.Width := ImageWidth;
BitMap1.Height := ImageHeight;
BitMap1.Canvas.Brush.Color := BackGroundColor; //
BitMap1.Canvas.Brush.Style := bsSolid;
BitMap1.Canvas.FillRect(Rect(0, 0, ImageWidth, ImageHeight));
AStarImage.picture.bitmap.Assign(BitMap1);
finally
BitMap1.Free;
end;
mapWidth := ImageWidth div tileSize;
mapHeight := ImageHeight div tileSize;
// EndPathfinder;
InitializePathfinder;
// Clear the map
For X := 0 to mapWidth - 1 do
For Y := 0 to mapHeight - 1 do
walkability[X][Y] := walkable;
// mapWidth = 16, mapHeight = 12, tileSize = 50, numberPeople = 1;
// 80 60 10
If AutoloadObstacleFile then
Case AstarMode of // tile50x13x10.aof //tile10x65x50.aof
1:
If FileExists(ProjectDirectory + 'tile50x13x10.aof') then
LoadObstacleData(ProjectDirectory + 'tile50x13x10.aof');
else
If FileExists(ProjectDirectory + 'tile10x65x50.aof') then
LoadObstacleData(ProjectDirectory + 'tile10x65x50.aof');
end;
// Draw Grid
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor; //
AStarImage.picture.bitmap.Canvas.Brush.Style := bsSolid;
If GridLinesDisplayed then
AStarImage.picture.bitmap.Canvas.Pen.Color := GridColor
else
AStarImage.picture.bitmap.Canvas.Pen.Color := BackGroundColor; //
{ CreateMapImage }
For X := 0 to mapWidth - 1 do
For Y := 0 to mapHeight - 1 do
begin
if (walkability[X][Y] = unwalkable) then
AStarImage.picture.bitmap.Canvas.Brush.Color := ObstacleColor
else
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor; //
AStarImage.picture.bitmap.Canvas.Rectangle
(Rect(X * tileSize, Y * tileSize, X * tileSize + tileSize,
Y * tileSize + tileSize));
end;
LoadUnitData;
For X := 1 to NumberofUnits do
Begin // Circles in Squares
walkability[startXLocArray[X] div tileSize][startYLocArray[X] div tileSize]
:= walkable;
walkability[targetXLocArray[X] div tileSize]
[targetXLocArray[X] div tileSize] := walkable;
// So the Units can have Base and Target the same Color
// and the Demo still has the Classic colors
If AstarMode = 1 then
AStarImage.picture.bitmap.Canvas.Brush.Color := clGreen
else
AStarImage.picture.bitmap.Canvas.Brush.Color := BaseStartColorArray[X];
// Base is Square..Make ? smaller than Block Ellipse
AStarImage.picture.bitmap.Canvas.Rectangle
(Rect(startXLocArray[X] * tileSize, startYLocArray[X] * tileSize,
startXLocArray[X] * tileSize + tileSize, startYLocArray[X] * tileSize +
tileSize));
If AstarMode = 1 then
AStarImage.picture.bitmap.Canvas.Brush.Color := clRed
else
AStarImage.picture.bitmap.Canvas.Brush.Color := TargetGoalColorArray[X];
AStarImage.picture.bitmap.Canvas.Ellipse(Rect(targetXLocArray[X] * tileSize,
targetYLocArray[X] * tileSize, (targetXLocArray[X] * tileSize) + tileSize,
(targetYLocArray[X] * tileSize) + tileSize));
End;
If ActiveEnemyNumber > 0 then
begin
walkability[EnemystartXLoc div tileSize][EnemystartYLoc div tileSize]
:= walkable;
// ActiveEnemyPosition Need Random Generator ?
AStarImage.picture.bitmap.Canvas.Brush.Color := EnemyUnitBaseColor;
// Base is Square..Make ? smaller than Block
AStarImage.picture.bitmap.Canvas.Rectangle(Rect(EnemystartXLoc * tileSize,
EnemystartYLoc * tileSize, EnemystartXLoc * tileSize + tileSize,
EnemystartYLoc * tileSize + tileSize));
AStarImage.picture.bitmap.Canvas.Brush.Color := EnemyUnitGoalTargetColor;
AStarImage.picture.bitmap.Canvas.Ellipse(Rect(EnemytargetXLoc * tileSize,
EnemytargetYLoc * tileSize, EnemytargetXLoc * tileSize + tileSize,
EnemytargetYLoc * tileSize + tileSize));
For X := 1 to 5 do
Begin // Circles in Squares
walkability[EnemyBaseXLocArray[X] div tileSize]
[EnemyBaseYLocArray[X] div tileSize] := walkable;
AStarImage.picture.bitmap.Canvas.Brush.Color := EnemyPositionsColor;
// Base is Square..Make ? smaller than Block
AStarImage.picture.bitmap.Canvas.Rectangle
(Rect(EnemyBaseXLocArray[X] * tileSize, EnemyBaseYLocArray[X] *
tileSize, EnemyBaseXLocArray[X] * tileSize + tileSize,
EnemyBaseYLocArray[X] * tileSize + tileSize));
end;
end;
// to set the image canvas font.. Must do every time cause it forgets.
AStarImage.picture.bitmap.Canvas.Font.Assign(AStarForm.Font);
StatusBar1.Panels[5].Text := 'Size X: ' + inttostr(ImageWidth) + ' Y: ' +
inttostr(ImageHeight) + ' Tilesize: ' + inttostr(tileSize);
End;
//-----------------------------------------------------------------------
procedure TAStarForm.RedrawData;
var
X, Y: Integer;
Begin
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor; //
AStarImage.picture.bitmap.Canvas.Brush.Style := bsSolid;
AStarImage.picture.bitmap.Canvas.FillRect(Rect(0, 0, ImageWidth,
ImageHeight));
// Draw Grid
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor; //
AStarImage.picture.bitmap.Canvas.Brush.Style := bsSolid;
If GridLinesDisplayed then
AStarImage.picture.bitmap.Canvas.Pen.Color := GridColor
else
AStarImage.picture.bitmap.Canvas.Pen.Color := BackGroundColor; //
{ CreateMapImage }
For X := 0 to mapWidth - 1 do
For Y := 0 to mapHeight - 1 do
begin
if (walkability[X][Y] = unwalkable) then
AStarImage.picture.bitmap.Canvas.Brush.Color := ObstacleColor
else
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor; //
AStarImage.picture.bitmap.Canvas.Rectangle
(Rect(X * tileSize, Y * tileSize, X * tileSize + tileSize,
Y * tileSize + tileSize));
end;
For X := 1 to NumberofUnits do
Begin // Circles in Squares
walkability[startXLocArray[X] div tileSize][startYLocArray[X] div tileSize]
:= walkable;
walkability[targetXLocArray[X] div tileSize]
[targetXLocArray[X] div tileSize] := walkable;
If AstarMode = 1 then
AStarImage.picture.bitmap.Canvas.Brush.Color := clGreen
else
AStarImage.picture.bitmap.Canvas.Brush.Color := BaseStartColorArray[X];
// Base is Square..Make ? smaller than Block
AStarImage.picture.bitmap.Canvas.Rectangle
(Rect(startXLocArray[X] * tileSize, startYLocArray[X] * tileSize,
startXLocArray[X] * tileSize + tileSize, startYLocArray[X] * tileSize +
tileSize));
If AstarMode = 1 then
AStarImage.picture.bitmap.Canvas.Brush.Color := clRed
else
AStarImage.picture.bitmap.Canvas.Brush.Color := TargetGoalColorArray[X];
AStarImage.picture.bitmap.Canvas.Ellipse(Rect(targetXLocArray[X] * tileSize,
targetYLocArray[X] * tileSize, (targetXLocArray[X] * tileSize) + tileSize,
(targetYLocArray[X] * tileSize) + tileSize));
End;
If ActiveEnemyNumber > 0 then
begin
walkability[EnemystartXLoc div tileSize][EnemystartYLoc div tileSize]
:= walkable;
// ActiveEnemyPosition Need Random Generator
AStarImage.picture.bitmap.Canvas.Brush.Color := EnemyUnitBaseColor;
// Base is Square..Make ? smaller than Block
AStarImage.picture.bitmap.Canvas.Rectangle(Rect(EnemystartXLoc * tileSize,
EnemystartYLoc * tileSize, EnemystartXLoc * tileSize + tileSize,
EnemystartYLoc * tileSize + tileSize));
AStarImage.picture.bitmap.Canvas.Brush.Color := EnemyUnitGoalTargetColor;
AStarImage.picture.bitmap.Canvas.Ellipse(Rect(EnemytargetXLoc * tileSize,
EnemytargetYLoc * tileSize, EnemytargetXLoc * tileSize + tileSize,
EnemytargetYLoc * tileSize + tileSize));
For X := 1 to 5 do
Begin // Circles in Squares
walkability[EnemyBaseXLocArray[X] div tileSize]
[EnemyBaseYLocArray[X] div tileSize] := walkable;
AStarImage.picture.bitmap.Canvas.Brush.Color := EnemyPositionsColor;
// Base is Square..Make ? smaller than Block
AStarImage.picture.bitmap.Canvas.Rectangle
(Rect(EnemyBaseXLocArray[X] * tileSize, EnemyBaseYLocArray[X] *
tileSize, EnemyBaseXLocArray[X] * tileSize + tileSize,
EnemyBaseYLocArray[X] * tileSize + tileSize));
end;
end;
End;
// -----------------------------------------------------------------------------
// Name: LoadUnitData
// Desc: Initialize unit-related data
// -----------------------------------------------------------------------------
procedure TAStarForm.LoadUnitData;
Begin
ActiveEnemyNumber := 0;
Case AstarMode of
1: // CubeDataDisplay1
Begin
NumberofUnits := 1;
ActiveUnitNumber := 1;
startXLocArray[ActiveUnitNumber] := // 3;
Trunc(((3) / 800) * ImageWidth);
startYLocArray[ActiveUnitNumber] := // 6;
Trunc(((5) / 600) * ImageHeight);
// *50 120x240 2x5
targetXLocArray[ActiveUnitNumber] := // 12;
Trunc(((11) / 800) * ImageWidth);
targetYLocArray[ActiveUnitNumber] := // 6;
Trunc(((5) / 600) * ImageHeight);
speedArray[ActiveUnitNumber] := 9;
End;
2: // Smiley1
Begin // 800x600 ImageWidth,ImageHeight
NumberofUnits := 1;
ActiveUnitNumber := 1;
startXLocArray[1] := Round((125 / 800) * ImageWidth / tileSize);
startYLocArray[1] := Round((225 / 600) * ImageHeight / tileSize);
// initial smiley location
targetXLocArray[1] := Round((725 / 800) * ImageWidth / tileSize);
targetYLocArray[1] := Round((525 / 600) * ImageHeight / tileSize);
// initial smiley location
speedArray[1] := 9; // smiley speed
End;
3: // Star
Begin
NumberofUnits := 5;
ActiveUnitNumber := 1;
startXLocArray[1] := { 46; } Round((462 / 650) * ImageWidth / tileSize);
startYLocArray[1] := { 20; } Round((202 / 500) * ImageHeight /
tileSize); // initial smiley location
targetXLocArray[1] := { 19; } Round((192 / 650) * ImageWidth /
tileSize);
targetYLocArray[1] := { 20;// } Round((202 / 500) * ImageHeight /
tileSize); // initial smiley location
startXLocArray[2] := { 19; } Round((192 / 650) * ImageWidth / tileSize);
startYLocArray[2] := { 20; } Round((202 / 500) * ImageHeight /
tileSize); // initial chaser location
targetXLocArray[2] := { 44; } Round((444 / 650) * ImageWidth /
tileSize);
targetYLocArray[2] := { 34; } Round((345 / 500) * ImageHeight /
tileSize); // initial smiley location
startXLocArray[3] := { 44; } Round((444 / 650) * ImageWidth / tileSize);
startYLocArray[3] := { 34; } Round((345 / 500) * ImageHeight /
tileSize); // initial chaser location
targetXLocArray[3] := { 33; } Round((333 / 650) * ImageWidth /
tileSize);
targetYLocArray[3] := { 13; } Round((132 / 500) * ImageHeight /
tileSize); // initial smiley location
startXLocArray[4] := { 33; } Round((333 / 650) * ImageWidth / tileSize);
startYLocArray[4] := { 13; } Round((132 / 500) * ImageHeight /
tileSize); // initial chaser location
targetXLocArray[4] := { 23; } Round((230 / 650) * ImageWidth /
tileSize);
targetYLocArray[4] := { 34;// } Round((340 / 500) * ImageHeight /
tileSize); // initial smiley location
startXLocArray[5] := { 23;// } Round((230 / 650) * ImageWidth /
tileSize);
startYLocArray[5] := { 34;// } Round((340 / 500) * ImageHeight /
tileSize); // initial chaser location
targetXLocArray[5] := { 46;// } Round((462 / 650) * ImageWidth /
tileSize);
targetYLocArray[5] := { 20;// } Round((202 / 500) * ImageHeight /
tileSize); // initial smiley location
speedArray[1] := 9; // smiley speed
speedArray[2] := 9; // chaser
speedArray[3] := 9; // chaser
speedArray[4] := 9; // chaser
speedArray[5] := 9; // chaser
End;
4: // King Astar : Dynamic Chase
Begin
NumberofUnits := 3;
ActiveUnitNumber := 1;
startXLocArray[1] := Round((112.5 / 800) * ImageWidth / tileSize);
startYLocArray[1] := Round((337.5 / 600) * ImageHeight / tileSize);
// initial smiley location
targetXLocArray[1] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[1] := Round((525 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[2] := Round((737.5 / 800) * ImageWidth / tileSize);
startYLocArray[2] := Round((337.5 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[2] := Round((125 / 800) * ImageWidth / tileSize);
targetYLocArray[2] := Round((325 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[3] := Round((437.5 / 800) * ImageWidth / tileSize);
startYLocArray[3] := Round((237.5 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[3] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[3] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
speedArray[1] := 5; // smiley speed
speedArray[2] := 4; // chaser
speedArray[3] := 3; // chaser
End;
5: // King Astar of the Misty Valley
Begin
NumberofUnits := 4;
ActiveUnitNumber := 1;
startXLocArray[1] := Round((125 / 800) * ImageWidth / tileSize);
startYLocArray[1] := Round((225 / 600) * ImageHeight / tileSize);
// initial smiley location
targetXLocArray[1] := Round((725 / 800) * ImageWidth / tileSize);
targetYLocArray[1] := Round((525 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[2] := Round((725 / 800) * ImageWidth / tileSize);
startYLocArray[2] := Round((325 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[2] := Round((125 / 800) * ImageWidth / tileSize);
targetYLocArray[2] := Round((325 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[3] := Round((365 / 800) * ImageWidth / tileSize);
startYLocArray[3] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[3] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[3] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[4] := Round((365 / 800) * ImageWidth / tileSize);
startYLocArray[4] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[4] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[4] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
speedArray[1] := 9; // smiley speed 9..0
speedArray[2] := 9; // chaser
speedArray[3] := 9; // chaser
speedArray[4] := 9; // chaser
End;
6: // CollisionAvoidancetimebased1
Begin
NumberofUnits := 5;
ActiveUnitNumber := 1;
startXLocArray[1] := Round((125 / 800) * ImageWidth / tileSize);
startYLocArray[1] := Round((225 / 600) * ImageHeight / tileSize);
// initial smiley location
targetXLocArray[1] := Round((725 / 800) * ImageWidth / tileSize);
targetYLocArray[1] := Round((525 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[2] := Round((725 / 800) * ImageWidth / tileSize);
startYLocArray[2] := Round((325 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[2] := Round((125 / 800) * ImageWidth / tileSize);
targetYLocArray[2] := Round((325 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[3] := Round((365 / 800) * ImageWidth / tileSize);
startYLocArray[3] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[3] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[3] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[4] := Round((365 / 800) * ImageWidth / tileSize);
startYLocArray[4] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[4] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[4] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[5] := Round((365 / 800) * ImageWidth / tileSize);
startYLocArray[5] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[5] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[5] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
speedArray[1] := 5; // smiley speed
speedArray[2] := 4; // chaser
speedArray[3] := 4; // chaser
speedArray[4] := 4; // chaser
speedArray[5] := 4; // chaser
End;
7: // Group Movement (w/Enemy)
Begin
NumberofUnits := 5;
ActiveUnitNumber := 1;
startXLocArray[1] := Round((125 / 800) * ImageWidth / tileSize);
startYLocArray[1] := Round((225 / 600) * ImageHeight / tileSize);
// initial smiley location
targetXLocArray[1] := Round((725 / 800) * ImageWidth / tileSize);
targetYLocArray[1] := Round((525 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[2] := Round((725 / 800) * ImageWidth / tileSize);
startYLocArray[2] := Round((325 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[2] := Round((125 / 800) * ImageWidth / tileSize);
targetYLocArray[2] := Round((325 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[3] := Round((365 / 800) * ImageWidth / tileSize);
startYLocArray[3] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[3] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[3] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[4] := Round((365 / 800) * ImageWidth / tileSize);
startYLocArray[4] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[4] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[4] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
startXLocArray[5] := Round((365 / 800) * ImageWidth / tileSize);
startYLocArray[5] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
targetXLocArray[5] := Round((775 / 800) * ImageWidth / tileSize);
targetYLocArray[5] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
speedArray[1] := 5; // smiley speed
speedArray[2] := 5; // chaser
speedArray[3] := 5; // chaser
speedArray[4] := 5; // chaser
speedArray[5] := 5; // chaser
// ALWAYS 5 blocks and 1 EnemyBase..Target
// Setting to > 1 makes for some action
ActiveEnemyNumber := 1;
EnemystartXLoc := Round((765 / 800) * ImageWidth / tileSize);
EnemystartYLoc := Round((123 / 600) * ImageWidth / tileSize);
EnemytargetXLoc := Round((123 / 800) * ImageWidth / tileSize);
EnemytargetYLoc := Round((456 / 600) * ImageWidth / tileSize);
EnemyBaseXLocArray[1] := Round((365 / 800) * ImageWidth / tileSize);
EnemyBaseYLocArray[1] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
EnemyBaseXLocArray[2] := Round((775 / 800) * ImageWidth / tileSize);
EnemyBaseYLocArray[2] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
EnemyBaseXLocArray[3] := Round((365 / 800) * ImageWidth / tileSize);
EnemyBaseYLocArray[3] := Round((145 / 600) * ImageHeight / tileSize);
// initial chaser location
EnemyBaseXLocArray[4] := Round((775 / 800) * ImageWidth / tileSize);
EnemyBaseYLocArray[4] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
EnemyBaseXLocArray[5] := Round((775 / 800) * ImageWidth / tileSize);
EnemyBaseYLocArray[5] := Round((425 / 600) * ImageHeight / tileSize);
// initial smiley location
End;
End;
End;
procedure TAStarForm.AStarImageMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
StatusBar1.Panels[3].Text := 'X: ' + inttostr(X) + ' Y: ' + inttostr(Y);
StatusBar1.Panels[4].Text := 'X: ' + inttostr((X div tileSize) + 1) + ' Y: ' +
inttostr((Y div tileSize) + 1);
end;
procedure TAStarForm.AStarImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
colCount, xx, yy, AStarx, AStary: Integer;
t: Int64;
colTotalTime, ts: Double; // Single;
// Past,Present: TDateTime;
// Hour, Min, Sec, MSec: Word;
begin
// All action starts at the Mouse Click
// Depends on the Current AstarMode Project demo type
// Turn ON the timer which Calls The AStar Runner
// this allows the mouse to be 'done' and still get something Activated
AStarx := X div tileSize;
AStary := Y div tileSize;
If EditModeActive then
begin
if ssLeft in Shift then { Base }
begin
if IsKeyDown('O') then // ObstacleColor
begin
walkability[AStarx][AStary] := 1 - walkability[AStarx][AStary];
if (walkability[AStarx][AStary] = unwalkable) then
AStarImage.picture.bitmap.Canvas.Brush.Color := ObstacleColor
else
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor; //
end
else
// ActiveEnemyPosition
if IsKeyDown('E') then // EnemyPositionsColor
begin
If ActiveEnemyNumber = 6 then
begin // EnemystartXLoc
EnemystartXLoc := AStarx;
EnemystartYLoc := AStary;
end
else
begin // 1..5
EnemyBaseXLocArray[ActiveEnemyNumber] := AStarx;
EnemyBaseYLocArray[ActiveEnemyNumber] := AStary;
walkability[AStarx][AStary] := 1 - walkability[AStarx][AStary];
if (walkability[AStarx][AStary] = unwalkable) then
AStarImage.picture.bitmap.Canvas.Brush.Color :=
EnemyPositionsColor
else
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor;
//
end;
end
else
begin
startXLocArray[ActiveUnitNumber] := AStarx;
startYLocArray[ActiveUnitNumber] := AStary;
AStarImage.picture.bitmap.Canvas.Brush.Color := BaseStartColorArray
[ActiveUnitNumber];
end;
end
else if ssRight in Shift then { Target }
begin
if IsKeyDown('E') then // EnemyPositionsColor
begin
If ActiveEnemyNumber = 6 then
begin // EnemystartXLoc
EnemytargetXLoc := AStarx;
EnemytargetYLoc := AStary;
end
end
else
begin
targetXLocArray[ActiveUnitNumber] := AStarx;
targetYLocArray[ActiveUnitNumber] := AStary;
AStarImage.picture.bitmap.Canvas.Brush.Color := TargetGoalColorArray
[ActiveUnitNumber];
end;
end;
// Fill with whatever color is Set
If GridLinesDisplayed then
AStarImage.picture.bitmap.Canvas.Pen.Color := GridColor
else
AStarImage.picture.bitmap.Canvas.Pen.Color := BackGroundColor; //
AStarImage.picture.bitmap.Canvas.Rectangle(Rect(AStarx * tileSize,
AStary * tileSize, AStarx * tileSize + tileSize,
AStary * tileSize + tileSize));
RedrawData;
end
else
begin // Pathfinding Mode
if ssLeft in Shift then { Base }
begin
if IsKeyDown('O') then // ObstacleColor
begin
walkability[AStarx][AStary] := 1 - walkability[AStarx][AStary];
if (walkability[AStarx][AStary] = unwalkable) then
AStarImage.picture.bitmap.Canvas.Brush.Color := ObstacleColor
else
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor; //
end
else
begin
startXLocArray[ActiveUnitNumber] := AStarx;
startYLocArray[ActiveUnitNumber] := AStary;
AStarImage.picture.bitmap.Canvas.Brush.Color := BaseStartColorArray
[ActiveUnitNumber];
end;
RedrawData;
end
else if ssRight in Shift then { Target }
begin
targetXLocArray[ActiveUnitNumber] := AStarx;
targetYLocArray[ActiveUnitNumber] := AStary;
AStarImage.picture.bitmap.Canvas.Brush.Color := TargetGoalColorArray
[ActiveUnitNumber];
end;
// either draws a box
If GridLinesDisplayed then
AStarImage.picture.bitmap.Canvas.Pen.Color := GridColor
else
AStarImage.picture.bitmap.Canvas.Pen.Color := BackGroundColor; //
AStarImage.picture.bitmap.Canvas.Rectangle(Rect(AStarx * tileSize,
AStary * tileSize, AStarx * tileSize + tileSize,
AStary * tileSize + tileSize));
RedrawData;
// Start A* pathfinding search if Right Click is hit
if ssRight in Shift then
begin
// Reset after finishing A* search if pressing mouse button or "1" or enter key
// Meanwhile pressing 9 or 0 keys will Single Step Draw the Path
if (pathStatus[ActiveUnitNumber] <> notfinished) then // if path is done
// if (MouseDown(1)==1 || MouseDown(2)==1 || KeyHit(49) || KeyHit(13)) then
begin
for xx := 0 to mapWidth - 1 do
for yy := 0 to mapHeight - 1 do
whichList[xx][yy] := 0;
for xx := 1 to 5 do
pathStatus[xx] := notfinished;
end;
if (pathStatus[ActiveUnitNumber] = notfinished) then
// if path not searched
Begin // ActiveUnitNumber pathfinderID
// so you know if it gets stuck
// If you see this ? something wrong?
StatusBar1.Panels[1].Text := 'Work';
If (UseOriginal and (SearchMode = 3) and (TieBreakerMode = 1)) then
StatusBar1.Panels[5].Text := 'AStar Normal'
else
StatusBar1.Panels[5].Text := 'AStar H: ' + inttostr(SearchMode) +
' : ' + inttostr(TieBreakerMode);
Application.ProcessMessages; // to show it
colTotalTime := 0;
Case AstarMode of
1 .. 2: // CubeDataDisplay1
Begin
colCount := 1; // NumberofUnits for when there are many units...
t := StartPrecisionTimer;
// Past:=Now;
If (UseOriginal and (SearchMode = 3) and (TieBreakerMode = 1))
then
pathStatus[ActiveUnitNumber] := FindPath(ActiveUnitNumber,
// startX*50,startY*50,targetX*50,targetY*50);
startXLocArray[ActiveUnitNumber] * tileSize,
startYLocArray[ActiveUnitNumber] * tileSize,
targetXLocArray[ActiveUnitNumber] * tileSize,
targetYLocArray[ActiveUnitNumber] * tileSize)
else
pathStatus[ActiveUnitNumber] := FindPathH(ActiveUnitNumber,
// startX*50,startY*50,targetX*50,targetY*50);
startXLocArray[ActiveUnitNumber] * tileSize,
startYLocArray[ActiveUnitNumber] * tileSize,
targetXLocArray[ActiveUnitNumber] * tileSize,
targetYLocArray[ActiveUnitNumber] * tileSize);
// Present:=Now;
// DecodeTime(Present-Past, Hour, Min, Sec, MSec);
colTotalTime := colTotalTime + StopPrecisionTimer(t);
// don't highlight the start square (aesthetics)
whichList // [startX][startY]
[startXLocArray[ActiveUnitNumber],
startYLocArray[ActiveUnitNumber]] := 0;
ts := colTotalTime * 1000 / colCount;
StatusBar1.Panels[1].Text := // IntToStr(MSec)+' ms';
Format('%.3f ms', [ts]);
end;
3 .. 6: // Smiley and Chasers
Begin // 5;
colCount := NumberofUnits; // for when there are many units...
t := StartPrecisionTimer;
// Past:=Now;
for xx := 1 to 5 do
begin
If (UseOriginal and (SearchMode = 3) and (TieBreakerMode = 1))
then
pathStatus[xx] := FindPath(xx,
// startX*50,startY*50,targetX*50,targetY*50);
startXLocArray[xx] * tileSize,
startYLocArray[xx] * tileSize, targetXLocArray[xx] *
tileSize, targetYLocArray[xx] * tileSize)
else
pathStatus[xx] := FindPathH(xx,
// startX*50,startY*50,targetX*50,targetY*50);
startXLocArray[xx] * tileSize,
startYLocArray[xx] * tileSize, targetXLocArray[xx] *
tileSize, targetYLocArray[xx] * tileSize);
end;
// Present:=Now;
// DecodeTime(Present-Past, Hour, Min, Sec, MSec);
colTotalTime := colTotalTime + StopPrecisionTimer(t);
ts := colTotalTime * 1000 / colCount;
StatusBar1.Panels[1].Text := // IntToStr(MSec)+' ms';
Format('%.3f / %d = %.3f ms',
[colTotalTime * 1000, colCount, ts]);
end;
End; // Case;
end;
// This will call the object movements
Timer1.Enabled := True;
end;
end;
end;
procedure TAStarForm.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := False;
RunAStarProject;
end;
// Called when a number 9 or 0 is presssed
procedure TAStarForm.DoSingleStepDrawing(Step: Integer);
Begin // DoSingleStepDrawing(0);
If (pathStatus[ActiveUnitNumber] = found) then
begin
If Step = 0 then
RunAStarProject
else // Do All the rest
If Step = 9 then // RunASingleStep; //1
begin
// Draw 1 Step.. MUST keep track of Current X and Y
// If the First time then Draw the Base stuff.
// procedure TAStarForm.PaintAStarPath(X,Y:Integer);
// procedure TAStarForm.PaintLinePath(X,Y:Integer);
end;
end;
End;
procedure TAStarForm.RunAStarProject;
var
// x,y, Z,ID,
i: Integer;
Procedure Runit(ID: Integer);
var
ii, xx: Integer;
Begin
If PathDisplayed then
AStarImage.picture.bitmap.Canvas.Pen.Color := TargetGoalColorArray[ID]
else
AStarImage.picture.bitmap.Canvas.Pen.Color := BackGroundColor;
// The Findpath calls ReadPath the does +1 so Have to reset back 1
// pathLocation[ID] := (pathLocation[ID] - 1);
For ii := 0 to pathLength[ID] - 1 do
begin
pathLocation[ID] := (pathLocation[ID] + 1);
xPath[ID] := ReadPathX(ID, pathLocation[ID]);
yPath[ID] := ReadPathY(ID, pathLocation[ID]);
AStarImage.picture.bitmap.Canvas.Brush.Color := TargetGoalColorArray[ID];
AStarImage.picture.bitmap.Canvas.Ellipse
(Rect(xPath[ID] + (2), yPath[ID] + (2), xPath[ID] + tileSize - (2),
yPath[ID] + tileSize - (2)));
// Move the Sprites IAW their Speed
// Call ____ times to allow time to SEE the Sprite move...
For xx := 0 to 1000000 * (10 - speedArray[ID]) do
Application.ProcessMessages;
// Paint over the Dot to 'erase'
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor;
AStarImage.picture.bitmap.Canvas.Ellipse
(Rect(xPath[ID] + (2), yPath[ID] + (2), xPath[ID] + tileSize - (2),
yPath[ID] + tileSize - (2)));
end;
// Change locations to have it go from present to next
If AstarMode = 2 then
begin
startXLocArray[1] := xPath[1] div tileSize;
startYLocArray[1] := yPath[1] div tileSize;
targetXLocArray[1] := xPath[1] div tileSize;
targetYLocArray[1] := yPath[1] div tileSize;
end;
// Repaint Last dot.. since it was 'erased'
AStarImage.picture.bitmap.Canvas.Brush.Color := TargetGoalColorArray[ID];
AStarImage.picture.bitmap.Canvas.Ellipse
(Rect(xPath[ID] + (2), yPath[ID] + (2), xPath[ID] + tileSize - (2),
yPath[ID] + tileSize - (2)));
End;
Procedure RunAll;
var
AllID, xx: Integer;
a1, a2, a3, a4, a5: Boolean;
Begin
a1 := True; // False True
a2 := True;
a3 := True;
a4 := True;
a5 := True;
// The Findpath calls ReadPath the does +1 so Have to reset back 1
For AllID := 1 to NumberofUnits Do
begin
// pathLocation[AllID] := (pathLocation[AllID] - 1);
Case AllID of
1:
a1 := False;
2:
a2 := False;
3:
a3 := False;
4:
a4 := False;
5:
a5 := False;
end;
end;
Repeat
Begin
For AllID := 1 to NumberofUnits Do
Begin
StatusBar1.Panels[5].Text := '';
If PathDisplayed then
AStarImage.picture.bitmap.Canvas.Pen.Color :=
TargetGoalColorArray[AllID]
else
AStarImage.picture.bitmap.Canvas.Pen.Color := BackGroundColor;
// If NONE set it back False..Then All done...
// For Ii:= 0 to pathLength[AllID]-1 do
If (xPath[AllID] div tileSize) <> (targetXLocArray[AllID]) then
begin
StatusBar1.Panels[5].Text := 'Processing: ' + inttostr(AllID);
pathLocation[AllID] := (pathLocation[AllID] + 1);
xPath[AllID] := ReadPathX(AllID, pathLocation[AllID]);
yPath[AllID] := ReadPathY(AllID, pathLocation[AllID]);
AStarImage.picture.bitmap.Canvas.Brush.Color :=
TargetGoalColorArray[AllID];
AStarImage.picture.bitmap.Canvas.Ellipse
(Rect(xPath[AllID] + (2), yPath[AllID] + (2),
xPath[AllID] + tileSize - (2), yPath[AllID] + tileSize - (2)));
// Move the Sprites IAW their Speed
// Call ____ times to allow time to SEE the Sprite move...
For xx := 0 to 1000000 * (10 - speedArray[AllID]) do
Application.ProcessMessages;
// Paint over the Dot to 'erase'
AStarImage.picture.bitmap.Canvas.Brush.Color := BackGroundColor;
AStarImage.picture.bitmap.Canvas.Ellipse
(Rect(xPath[AllID] + (2), yPath[AllID] + (2),
xPath[AllID] + tileSize - (2), yPath[AllID] + tileSize - (2)));
// Repaint Last dot.. since it was 'erased'
AStarImage.picture.bitmap.Canvas.Brush.Color :=
TargetGoalColorArray[AllID];
AStarImage.picture.bitmap.Canvas.Ellipse
(Rect(xPath[AllID] + (2), yPath[AllID] + (2),
xPath[AllID] + tileSize - (2), yPath[AllID] + tileSize - (2)));
end
else
begin
Case AllID of
1:
a1 := True;
2:
a2 := True;
3:
a3 := True;
4:
a4 := True;
5:
a5 := True;
end;
end;
End;
End;
Until ((a1 = True) and (a2 = True) and (a3 = True) and (a4 = True) and
(a5 = True));
StatusBar1.Panels[5].Text := 'All Paths Finished';
End;
begin
{ CubeDataDisplay1
GOGO
star
King valley
King chase
CollisionAvoidancetimebased1
GroupMovement1 }
{ If (path = found)then ReadPath(ActiveUnitNumber,
startXLocArray[ActiveUnitNumber],
startYLocArray[ActiveUnitNumber],1 );
}
Case AstarMode of
1: // CubeDataDisplay1
Begin
If (pathStatus[1] = found) then
begin
Memo1.Enabled := True;
Memo1.Lines.Clear;
Memo1.Lines.Add('(path = found)');
If pathLength[1] > 0 then // showmessage(
Memo1.Lines.Add('Location ' + inttostr(pathLocation[1]));
Memo1.Lines.Add('Length ' + inttostr(pathLength[1]));
// ID:=1;
Memo1.Lines.Add(inttostr(startXLocArray[1]) + ' start x..y ' +
inttostr(startYLocArray[1]));
// Memo1.Lines.Add('onClosedList: '+inttostr(onClosedList));
// The Findpath calls ReadPath the does +1 so Have to reset back 1
// pathLocation[1] := (pathLocation[1] - 1);
For i := 0 to pathLength[1] - 1 do
begin
pathLocation[1] := (pathLocation[1] + 1);
xPath[1] := ReadPathX(1, pathLocation[1]);
yPath[1] := ReadPathY(1, pathLocation[1]);
Memo1.Lines.Add(inttostr(xPath[1] div tileSize) + '..' +
inttostr(yPath[1] div tileSize));
// Add 1 to make the Path get Displayed different than Closedlist
whichList[xPath[1] div tileSize][yPath[1] div tileSize] :=
whichList[xPath[1] div tileSize][yPath[1] div tileSize] + 1;
end;
{ Z:= onClosedList-2;
For X:= 0 to mapWidth-1 do
For Y:= 0 to mapHeight-1 do
Memo1.Lines.Add(inttostr(whichList[x][y])+ '..-z '
+ inttostr((whichList[x][y])-Z) ); }
Memo1.Lines.Add(inttostr(targetXLocArray[1]) + '..' +
inttostr(targetYLocArray[1]));
Memo1.Lines.Add('eol');
// Draw the Path ,startXLocArray[ID],startYLocArray[ID]
PaintAStarPath(1);
end;
End;
2: // one after another
Begin
// ID:=1;
Runit(1);
End;
3: // Star
Begin
RunAll; // for I:= 1 to 5 do Runit(I);
End;
// Blitz code projects
4: // King chase [3]
Begin
FPSCount := 0;
// for I:= 1 to 3 do Runit(I);
// AstarUnitsRunning:=True;
// RunUnitLoop;// until ???? [Ctrl] F9 Toggles AstarUnitsRunning
End;
5: // King valley [4]
Begin
// AstarUnitsRunning:=True;
// RunUnitLoop;// until ???? [Ctrl] F9 Toggles AstarUnitsRunning
End;
6: // CollisionAvoidance [5]
Begin
//
End;
7: // GroupMovement1 [5+1=6]
Begin
//
// ;Draw unit claimed nodes
// DrawClaimedNodes(True);see shared functions.bb include file
End;
End;
end;
procedure TAStarForm.PaintAStarPath(ID: Integer);
var
dx1, dx2, dy1, dy2, cross, // Tiebreakers
XDistance, YDistance, HDistance, // Heuristic options
G, F, H, X, Y, z: Integer;
Procedure DrawImage(Image, X, Y: Integer);
begin
// Dta Display Demo IGNORES the Base .. Target Colors
Case Image of // 123: Draw a Color Rectangle
1:
begin
AStarImage.picture.bitmap.Canvas.Brush.Color := clGreen;
AStarImage.picture.bitmap.Canvas.FrameRect
(Rect(X, Y, X + tileSize, Y + tileSize));
end;
2:
begin
AStarImage.picture.bitmap.Canvas.Brush.Color := clBlue;
AStarImage.picture.bitmap.Canvas.FrameRect
(Rect(X, Y, X + tileSize, Y + tileSize));
end;
3:
begin // Paint the Base Red Dot;
AStarImage.picture.bitmap.Canvas.Brush.Color := clYellow;
AStarImage.picture.bitmap.Canvas.FrameRect
(Rect(X, Y, X + tileSize, Y + tileSize));
AStarImage.picture.bitmap.Canvas.Brush.Color := clRed;
AStarImage.picture.bitmap.Canvas.Ellipse
(Rect(X + (12), Y + (12), X + tileSize - (12),
Y + tileSize - (12)));
AStarImage.picture.bitmap.Canvas.Brush.Color := clYellow;
End;
end; // case
Case Image of
10 .. 17:
begin // Draw the ImageList image directional arrows
If AStarDataDisplayArrowsColor = 0 then
ImageList0.Draw(AStarImage.picture.bitmap.Canvas, X + (12),
Y + (12), Image - 10)
else
ImageList1.Draw(AStarImage.picture.bitmap.Canvas, X + (12),
Y + (12), Image - 10);
end;
end; // case
end; // DrawImage
Begin
// Cloned from RenderScreen
// onClosedList := onClosedList+2;
// onOpenList := onClosedList-1;
z := onClosedList - 2;
For X := 0 to mapWidth - 1 do
For Y := 0 to mapHeight - 1 do
Begin
// Draw cells on open list (green), closed list (blue) and
// part of the found path, if any (red dots).
if ((whichList[X][Y]) - z = 1) then
DrawImage(1 { greengrid } , X * 50, Y * 50)
else if ((whichList[X][Y]) - z = 2) then
DrawImage(2 { bluegrid } , X * 50, Y * 50)
else if ((whichList[X][Y]) - z = 3) then
DrawImage(3 { dottedPath } , X * 50, Y * 50);
// Draw arrows that point to each square's parent.
if (whichList[X][Y] - z = 1) or (whichList[X][Y] - z = 2) then
begin
If (parentX[X][Y] = X) and (parentY[X][Y] = Y - 1) then
DrawImage(10 { parentArrow[1] } , X * 50, Y * 50)
else if (parentX[X][Y] = X + 1) and (parentY[X][Y] = Y - 1) then
DrawImage(11 { parentArrow[2] } , X * 50, Y * 50)
else if (parentX[X][Y] = X + 1) and (parentY[X][Y] = Y) then
DrawImage(12 { parentArrow[3] } , X * 50, Y * 50)
else if (parentX[X][Y] = X + 1) and (parentY[X][Y] = Y + 1) then
DrawImage(13 { parentArrow[4] } , X * 50, Y * 50)
else if (parentX[X][Y] = X) and (parentY[X][Y] = Y + 1) then
DrawImage(14 { parentArrow[5] } , X * 50, Y * 50)
else if (parentX[X][Y] = X - 1) and (parentY[X][Y] = Y + 1) then
DrawImage(15 { parentArrow[6] } , X * 50, Y * 50)
else if (parentX[X][Y] = X - 1) and (parentY[X][Y] = Y) then
DrawImage(16 { parentArrow[7] } , X * 50, Y * 50)
else if (parentX[X][Y] = X - 1) and (parentY[X][Y] = Y - 1) then
DrawImage(17 { parentArrow[8] } , X * 50, Y * 50);
end;
// Print F, G and H costs in cells
if (whichList[X][Y] - z > 0) then
// if an open, closed, or path cell.
begin
G := Gcost[X][Y];
H := 0; // compiler shutup
// Heuristic Options
// H := 10*(abs(x - targetXLocArray[ID]) + abs(y - targetYLocArray[ID]));
Case SearchMode of
0:
H := 0; // Dijkstra
1: // Diagonal
Begin
XDistance := abs(X - targetXLocArray[ID]);
YDistance := abs(Y - targetYLocArray[ID]);
If XDistance > YDistance then
HDistance := ((14 * YDistance) + (10 * (XDistance - YDistance)))
else
HDistance :=
((14 * XDistance) + (10 * (YDistance - XDistance)));
H := HDistance;
End;
2: // Manhattan
H := 10 * (abs(X - targetXLocArray[ID]) +
abs(Y - targetYLocArray[ID]));
3: // BestFirst..Overestimated h
H := 10 * ((X - targetXLocArray[ID]) * (X - targetXLocArray[ID]) +
(Y - targetYLocArray[ID]) * (Y - targetYLocArray[ID]));
4: // Euclidian
H := Trunc
(10 * SQRT(((X - targetXLocArray[ID]) * (X - targetXLocArray[ID])
+ (Y - targetYLocArray[ID]) * (Y - targetYLocArray[ID]))));
End;
F := G + H; // compiler shutup
Case TieBreakerMode of
0:
F := G + H; // None
1:
begin // straight
dx1 := (X - targetXLocArray[ID]);
dx2 := (Y - targetYLocArray[ID]);
dy1 := (startXLocArray[ID] - targetXLocArray[ID]);
dy2 := (startYLocArray[ID] - targetYLocArray[ID]);
cross := abs((dx1 * dy2) - (dx2 * dy1));
// or Trunc ?
F := Round(G + H + (cross * 0.001));
end;
2:
F := Trunc(G + H - (0.1 * H)); // close
3:
F := Trunc(G + H + (0.1 * H)); // far
end;
// Print F in upper left corner of cell (F=G+H)
AStarImage.picture.bitmap.Canvas.textout(X * tileSize + 2,
Y * tileSize + 2, inttostr(F));
// Print G in bottom left corner of cell (G=distance from start)
AStarImage.picture.bitmap.Canvas.textout(X * tileSize + 2,
Y * tileSize + 36, inttostr(G));
// Print H in bottom right corner of cell (H=distance to target)
if (H < 100) then
AStarImage.picture.bitmap.Canvas.textout(X * tileSize + 37,
Y * tileSize + 36, inttostr(H))
else
AStarImage.picture.bitmap.Canvas.textout((X * tileSize) + 30,
Y * tileSize + 36, inttostr(H));
end; // 32
End;
End;
end.
|
unit DotEnv;
interface
uses System.SysUtils, System.Types, System.UITypes, System.Classes,
System.RegularExpressions, System.RegularExpressionsCore;
type
TDotEnv = class
private
public
dotEnvFile: TStringList;
class var Instance : TDotEnv;
class function getInstace: TDotEnv; static;
function loadDotEnvFile(fileName: string = 'env'): TDotEnv;
class function Get(key: string): string; static;
end;
implementation
class function TDotEnv.getInstace: TDotEnv;
begin
if Instance = nil then
Instance := TDotEnv.Create();
result := Instance;
end;
function TDotEnv.loadDotEnvFile(fileName: string ): TDotEnv;
begin
self.dotEnvFile := TStringList.Create;
self.dotEnvFile.LoadFromFile(GetCurrentDir + '/.'+ fileName);
result := self;
end;
class function TDotEnv.Get(key: string): string;
begin
const regex = TRegEx.Match(TDotEnv.getInstace().dotEnvFile.Text, key+'=.+').Value;
const value = TRegEx.Split(regex, '=')[1];
if value <> '' then
result := value
else
result := '';
end;
end.
|
unit fmPassword;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Oracle, Buttons;
type
TfmPass = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
edOld: TEdit;
edNew: TEdit;
Label2: TLabel;
edCheck: TEdit;
Label3: TLabel;
bbOk: TBitBtn;
BitBtn1: TBitBtn;
spSpremeniGeslo: TOracleQuery;
procedure bbOkClick(Sender: TObject);
procedure PreveriGesla;
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmPass: TfmPass;
implementation
uses dmOra, ResStrings;
{$R *.dfm}
procedure TfmPass.PreveriGesla;
begin
if (edOld.Text <> dmOracle.oraSession.LogonPassword) then begin
edOld.SetFocus;
raise Exception.Create(C_EXCEPT_MSG_OLD_PASSWORD_WRONG);
end;
if (edOld.text = edNew.Text) then begin
edNew.SetFocus;
raise Exception.Create (C_EXCEPT_MSG_NEW_PASSWORD_SAME);
end;
if (edNew.Text <> edCheck.Text) then begin
edNew.SetFocus;
raise Exception.Create (C_EXCEPT_MSG_NEW_PASSWORD_DONT_MATCH);
end;
end;
procedure TfmPass.bbOkClick(Sender: TObject);
var Amsg: string;
begin
PreveriGesla;
with spSpremeniGeslo do begin
SetVariable('P_USER', dmOracle.oraSession.LogonUsername);
SetVariable('P_PASSWORD', edNew.Text);
try
Execute;
MessageDlg (C_FMPASS_GESLO_SPREMENJENO_OK, mtInformation, [mbOk], 0);
fmPass.ModalResult := mrOk;
except
on E:EOracleError do begin
aMsg := C_FMPASS_GESLO_SPREMENJENO_ERR + ' Opis:' + E.Message;
MessageDlg (aMsg, mtError, [mbOk], 0);
end;
end;
end;
end;
end.
|
unit TestURateioController;
{
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, URateioVO, UCondominioVo, UCondominioController, DBClient, DBXJSON,
UItensRateioController, URateioController, DBXCommon, UITENSrateioVO,
Generics.Collections, Classes, UController, DB, SysUtils, ConexaoBD, SQLExpr;
type
// Test methods for class TRateioController
TestTRateioController = class(TTestCase)
strict private
FRateioController: TRateioController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
procedure TestConsultarPorIdNaoEncontrado;
end;
implementation
procedure TestTRateioController.SetUp;
begin
FRateioController := TRateioController.Create;
end;
procedure TestTRateioController.TearDown;
begin
FRateioController.Free;
FRateioController := nil;
end;
procedure TestTRateioController.TestConsultarPorId;
var
ReturnValue: TRateioVO;
begin
ReturnValue := FRateioController.ConsultarPorId(11);
if(returnvalue <> nil) then
check(true,'Rateio pesquisada com sucesso!')
else
check(False,'Rateio nao encontrada!');
end;
procedure TestTRateioController.TestConsultarPorIdNaoEncontrado;
var
ReturnValue: TRateioVO;
begin
ReturnValue := FRateioController.ConsultarPorId(69);
if(returnvalue <> nil) then
check(False,'Rateio pesquisada com sucesso!')
else
check(True,'Rateio nao encontrado!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTRateioController.Suite);
end.
|
unit ThCssStyle;
interface
uses
Classes, Messages, SysUtils, Types, Graphics,
ThMessages, ThStyleList, ThPicture;
type
TThCssBase = class(TPersistent)
private
FOnChanged: TNotifyEvent;
protected
procedure Changed; virtual;
public
//:$ OnChanged event is fired when a style property is changed.
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
end;
//
TThCssFontWeight = ( fwDefault, fwNormal, fwBold );
TThCssFontSizeRelEnum = ( fsDefault, fs_1_XxSmall, fs_2_XSmall, fs_3_Small,
fs_4_Medium, fs_5_Large, fs_6_XLarge, fs_7_XxLarge );
TThCssFontSizeRel = string;
TThCssFontDecoration = ( fdDefault, fdInherit, fdNone, fdUnderline,
fdOverline, fdLineThrough, fdBlink );
TThCssFontStyle = ( fstDefault, fstInherit, fstNormal, fstItalic,
fstOblique );
//
//:$ Describes CSS font properties.
TThCssFont = class(TThCssBase)
private
FFontSizeRel: TThCssFontSizeRel;
FFontFamily: TFontName;
FFontWeight: TThCssFontWeight;
FFontSizePx: Integer;
FFontSizePt: Integer;
FFontColor: TColor;
FFontDecoration: TThCssFontDecoration;
FFontStyle: TThCssFontStyle;
FDefaultFontPx: Integer;
FDefaultFontFamily: string;
protected
procedure SetDefaultFontFamily(const Value: string);
procedure SetDefaultFontPx(const Value: Integer);
procedure SetFontColor(const Value: TColor);
procedure SetFontFamily(const Value: TFontName);
procedure SetRelFontSize(const Value: TThCssFontSizeRel);
procedure SetFontWeight(const Value: TThCssFontWeight);
procedure SetFontSizePx(const Value: Integer);
procedure SetFontSizePt(const Value: Integer);
procedure SetFontDecoration(const Value: TThCssFontDecoration);
procedure SetFontStyle(const Value: TThCssFontStyle);
protected
function GetRelFontSize: Integer;
function GetSizeValue: string;
public
//:$ Copy all properties from another style instance.
procedure Assign(Source: TPersistent); override;
constructor Create;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: TThStyleList);
//:$ Converts a TThCssFont to a TFont.
procedure ToFont(inFont: TFont);
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inFont: TThCssFont);
public
property DefaultFontFamily: string read FDefaultFontFamily write SetDefaultFontFamily;
property DefaultFontPx: Integer read FDefaultFontPx write SetDefaultFontPx;
//:$ Font size, in points. Not published to encourage use of 'pixel'
//:: size instead. Pixel sizes translate better in browsers.
property FontSizePt: Integer read FFontSizePt write SetFontSizePt
default 0;
published
//:$ Font color.
property FontColor: TColor read FFontColor write SetFontColor
default clNone;
//:$ Font decoration.
property FontDecoration: TThCssFontDecoration read FFontDecoration
write SetFontDecoration default fdDefault;
//:$ Font family (face).
property FontFamily: TFontName read FFontFamily write SetFontFamily;
//:$ Font size, in pixels.
property FontSizePx: Integer read FFontSizePx write SetFontSizePx
default 0;
//:$ Relative font size.
property FontSizeRel: TThCssFontSizeRel read FFontSizeRel
write SetRelFontSize;
//:$ Font style.
property FontStyle: TThCssFontStyle read FFontStyle write SetFontStyle
default fstDefault;
//:$ Font weight.
property FontWeight: TThCssFontWeight read FFontWeight
write SetFontWeight default fwDefault;
end;
//
//:$ Describes CSS background properties.
//:: Usually available as a member of a TThCssStyle.
TThCssBackground = class(TThCssBase)
private
//FOwner: TComponent;
FPicture: TThPicture;
protected
procedure SetPicture(const Value: TThPicture);
protected
procedure PictureChange(inSender: TObject);
public
constructor Create(AOwner: TComponent);
destructor Destroy; override;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ Copy all properties from another style instance.
procedure Assign(Source: TPersistent); override;
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inBackground: TThCssBackground);
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: TThStyleList);
published
//$ Optional picture to be used as background.
//:: Background pictures are tiled to fill the style object.
property Picture: TThPicture read FPicture write SetPicture;
end;
//
TThCssBorderProp = ( bpWidth, bpStyle, bpColor);
TThCssBorderStyle = ( bsDefault, bsInherit, bsNone, bsHidden, bsDotted,
bsDashed, bsSolidBorder, bsGroove, bsRidge, bsInset, bsOutset, bsDouble );
TThCssBorderSide = ( bsAll, bsLeft, bsTop, bsRight, bsBottom );
//
//:$ Describes a CSS border.
//:: Usually available as a member of a TThCssBorders object.
TThCssBorder = class(TThCssBase)
private
FBorderColor: TColor;
FBorderPrefix: string;
FBorderSide: TThCssBorderSide;
FBorderStyle: TThCssBorderStyle;
FBorderWidth: string;
FDefaultBorderPixels: Integer;
FOwnerStyle: TThCssBase;
protected
procedure SetBorderColor(const Value: TColor);
procedure SetBorderStyle(const Value: TThCssBorderStyle);
procedure SetBorderWidth(const Value: string);
public
constructor Create(inOwner: TThCssBase; inSide: TThCssBorderSide);
procedure Changed; override;
function BorderVisible: Boolean; virtual;
function GetBorderPixels: Integer; overload;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: TThStyleList);
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inBorder: TThCssBorder);
procedure Assign(Source: TPersistent); override;
public
property BorderSide: TThCssBorderSide read FBorderSide write FBorderSide;
property DefaultBorderPixels: Integer read FDefaultBorderPixels
write FDefaultBorderPixels;
published
property BorderWidth: string read FBorderWidth write SetBorderWidth;
property BorderColor: TColor read FBorderColor write SetBorderColor
default clDefault;
property BorderStyle: TThCssBorderStyle read FBorderStyle
write SetBorderStyle default bsDefault;
end;
//
//:$ Describes CSS border properties.
//:: Aggregates TThCssBorder objects. Usually available as a member of a
//:: TThCssStyle.
TThCssBorderDetail = class(TThCssBase)
private
FBorderLeft: TThCssBorder;
FBorderTop: TThCssBorder;
FBorderRight: TThCssBorder;
FBorderBottom: TThCssBorder;
protected
procedure SetBorderBottom(const Value: TThCssBorder);
procedure SetBorderLeft(const Value: TThCssBorder);
procedure SetBorderRight(const Value: TThCssBorder);
procedure SetBorderTop(const Value: TThCssBorder);
procedure SetDefaultBorderPixels(inPixels: Integer);
public
constructor Create(inOwnerStyle: TThCssBase);
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
function BorderVisible: Boolean;
function GetBorder(inSide: TThCssBorderSide): TThCssBorder;
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inDetail: TThCssBorderDetail);
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: TThStyleList);
public
property DefaultBorderPixels: Integer write SetDefaultBorderPixels;
published
property BorderLeft: TThCssBorder read FBorderLeft write SetBorderLeft;
property BorderRight: TThCssBorder read FBorderRight
write SetBorderRight;
property BorderTop: TThCssBorder read FBorderTop write SetBorderTop;
property BorderBottom: TThCssBorder read FBorderBottom
write SetBorderBottom;
end;
//
//:$ Describes CSS border properties.
//:: Aggregates TThCssBorder objects. Usually available as a member of a
//:: TThCssStyle.
TThCssBorders = class(TThCssBorder)
private
FEdges: TThCssBorderDetail;
protected
procedure SetEdges(const Value: TThCssBorderDetail);
procedure SetDefaultBorderPixels(inPixels: Integer);
public
constructor Create;
destructor Destroy; override;
//procedure Changed; override;
function BorderVisible: Boolean; override;
function GetBorderColor(inSide: TThCssBorderSide): TColor;
function GetBorderStyle(inSide: TThCssBorderSide): TThCssBorderStyle;
function GetBorderPixels(inSide: TThCssBorderSide): Integer; overload;
procedure Assign(Source: TPersistent); override;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: TThStyleList);
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inBox: TThCssBorders);
public
property DefaultBorderPixels: Integer write SetDefaultBorderPixels;
published
property Edges: TThCssBorderDetail read FEdges
write SetEdges;
end;
//
TThCssPadDetail = class(TThCssBase)
private
FOwnerStyle: TThCssBase;
FPadLeft: Integer;
FPadBottom: Integer;
FPadTop: Integer;
FPadRight: Integer;
protected
procedure SetPadding(const Value: Integer);
procedure SetPadBottom(const Value: Integer);
procedure SetPadLeft(const Value: Integer);
procedure SetPadRight(const Value: Integer);
procedure SetPadTop(const Value: Integer);
public
constructor Create(inOwnerStyle: TThCssBase);
procedure Changed; override;
//:$ Determine if any padding has been set.
//:: Returns true if any of the padding properties are non-zero.
function HasPadding: Boolean;
//:$ Return the total width of padding.
//:: Returns PadLeft + PadRight.
function PadWidth: Integer;
//:$ Return the total height of padding.
//:: Returns PadTop + PadBottom.
function PadHeight: Integer;
//:$ Copy all properties from another style instance.
procedure Assign(Source: TPersistent); override;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: TThStyleList);
//:$ Add attribute values to an HTML node.
//:: Adds the attribute values for the style class to the list of
//:: style attributes maintained by the node.
//procedure Stylize(inNode: TThHtmlNode);
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inPad: TThCssPadDetail);
public
property Padding: Integer write SetPadding;
published
property PadLeft: Integer read FPadLeft write SetPadLeft default 0;
property PadRight: Integer read FPadRight write SetPadRight default 0;
property PadTop: Integer read FPadTop write SetPadTop default 0;
property PadBottom: Integer read FPadBottom write SetPadBottom default 0;
end;
//
//:$ Describes CSS padding properties.
//:: Usually available as a member of a TThCssStyle.
TThCssPadding = class(TThCssBase)
private
FPadding: Integer;
FPaddingDetails: TThCssPadDetail;
protected
procedure SetPadding(const Value: Integer);
procedure SetPaddingDetails(const Value: TThCssPadDetail);
public
constructor Create;
destructor Destroy; override;
//:$ Copy all properties from another style instance.
procedure Assign(Source: TPersistent); override;
procedure Changed; override;
//:$ Determine if any padding has been set.
//:: Returns true if any of the padding properties are non-zero.
function HasPadding: Boolean;
//:$ Assign properties from an ancestor style.
//:: Assigns properties from the input style into properties in this style
//:: that are set to their defaults. Properties in the current style that
//:: have been customized are not overriden.
procedure Inherit(inPad: TThCssPadding);
//:$ Returns formatted style attribute.
//:: InlineAttribute returns a style attribute formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: TThStyleList);
function PadBottom: Integer;
//:$ Return the total height of padding.
//:: Returns PadTop + PadBottom.
function PadHeight: Integer;
function PadLeft: Integer;
function PadRight: Integer;
function PadTop: Integer;
//:$ Return the total width of padding.
//:: Returns PadLeft + PadRight.
function PadWidth: Integer;
published
property Padding: Integer read FPadding write SetPadding default 0;
property PaddingDetails: TThCssPadDetail read FPaddingDetails
write SetPaddingDetails;
end;
//
//:$ TThCssStyle combines various style objects. Commonly used as
//:$ a property in objects needing style information.
TThCssStyle = class(TThCssBase)
private
FBackground: TThCssBackground;
FBorders: TThCssBorders;
FColor: TColor;
FCursor: string;
FExtraStyles: string;
FFont: TThCssFont;
FName: string;
//FOverflow: TThCssOverflow;
FOwner: TComponent;
FPadding: TThCssPadding;
FParentColor: Boolean;
FParentFont: Boolean;
protected
procedure SetBackground(const Value: TThCssBackground);
procedure SetBorders(const Value: TThCssBorders);
procedure SetColor(const Value: TColor);
procedure SetCursor(const Value: string);
procedure SetExtraStyles(const Value: string);
procedure SetFont(const Value: TThCssFont);
procedure SetName(const Value: string);
procedure SetPadding(const Value: TThCssPadding);
//procedure SetOverflow(const Value: TThCssOverflow);
procedure SetParentColor(const Value: Boolean);
procedure SetParentFont(const Value: Boolean);
protected
procedure InternalChanged(inSender: TObject); virtual;
public
constructor Create(AOwner: TComponent); virtual;
destructor Destroy; override;
function InlineColorAttribute: string;
function StyleAttribute: string;
//:$ Returns formatted style attributes.
//:: InlineAttribute returns style attributes formatted
//:: to be included in a style sheet or inline style declaration.
//:: Returned string is a series of attribute:value pairs separated by
//:: semicolons.
//:: e.g. <attr>:<value>; <attr>:<value>;
function InlineAttribute: string;
//:$ <br>Copy style attributes to a list.
//:: <br>Adds the attribute values for the style to a list of style
//:: attributes.
procedure ListStyles(inStyles: TThStyleList);
procedure Assign(Source: TPersistent); override;
procedure AssignFromParent(inParent: TThCssStyle);
procedure Inherit(inStyle: TThCssStyle);
procedure ToFont(inFont: TFont);
function GetBoxLeft: Integer;
function GetBoxTop: Integer;
function GetBoxRight: Integer;
function GetBoxBottom: Integer;
// procedure ExpandRect(var ioRect: TRect);
procedure UnpadRect(var ioRect: TRect);
function GetBoxHeightMargin: Integer;
function GetBoxWidthMargin: Integer;
procedure AdjustClientRect(var ioRect: TRect);
function AdjustHeight(inHeight: Integer): Integer;
function AdjustWidth(inWidth: Integer): Integer;
function Owner: TComponent;
public
property Name: string read FName write SetName;
property ParentFont: Boolean read FParentFont write SetParentFont;
property ParentColor: Boolean read FParentColor write SetParentColor;
published
property Background: TThCssBackground read FBackground write SetBackground;
property Border: TThCssBorders read FBorders write SetBorders;
property Color: TColor read FColor write SetColor default clNone;
property Cursor: string read FCursor write SetCursor;
property ExtraStyles: string read FExtraStyles write SetExtraStyles;
property Font: TThCssFont read FFont write SetFont;
//property Overflow: TThCssOverflow read FOverflow write SetOverflow;
property Padding: TThCssPadding read FPadding write SetPadding;
end;
function ThVisibleColor(inColor: TColor): Boolean;
function ThColorToHtml(const Color: TColor): string;
function ThInlineStylesToAttribute(const inStyles: string): string;
procedure ThCat(var ioDst: string; const inAdd: string);
const
ssPx = 'px';
ssPerc = '%';
ss100Percent = '100%';
//
ssHeight = 'height';
ssWidth = 'width';
ssLeft = 'left';
ssTop = 'top';
ssRight = 'right';
ssBottom = 'bottom';
ssCenter = 'center';
ssMarginLeft = 'margin-left';
ssMarginRight = 'margin-right';
ssPosition = 'position';
ssTextAlign = 'text-align';
ssColor = 'color';
ssBackgroundColor = 'background-color';
ssBackgroundImage = 'background-image';
ssBorderStyle = 'border-style';
ssBorderWidth = 'border-width';
ssBorderColor = 'border-color';
ssFont = 'font';
ssFontFamily = 'font-family';
ssFontSize = 'font-size';
ssFontWeight = 'font-weight';
ssFontStyle = 'font-style';
ssTextDecoration = 'text-decoration';
ssPadding = 'padding';
ssPaddingLeft = 'padding-left';
ssPaddingRight = 'padding-right';
ssPaddingTop = 'padding-top';
ssPaddingBottom = 'padding-bottom';
ssOverflow = 'overflow';
ssOverflowX = 'overflow-x';
ssOverflowY = 'overflow-y';
ssCursor = 'cursor';
//
ssStyle = 'style';
ssBorderPrefix = 'border';
ssBorderLeftPrefix = 'border-left';
ssBorderTopPrefix = 'border-top';
ssBorderRightPrefix = 'border-right';
ssBorderBottomPrefix = 'border-bottom';
//
ssBorderPrefixi: array[TThCssBorderSide] of string = ( ssBorderPrefix,
ssBorderLeftPrefix, ssBorderTopPrefix, ssBorderRightPrefix,
ssBorderBottomPrefix );
//
ssBorderStyles: array[TThCssBorderStyle] of string = ( '', 'inherit',
'none', 'hidden', 'dotted', 'dashed', 'solid', 'groove', 'ridge', 'inset',
'outset', 'double' );
//
//ssPositions: array[TThCssPosition] of string = ( 'absolute', 'relative' );
//
ssFontWeights: array[TThCssFontWeight] of string = ( '', 'normal',
'bold' );
ssRelFontSizes: array[TThCssFontSizeRelEnum] of string = ( '', 'xx-small',
'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large' );
cTFontSizes: array[TThCssFontSizeRelEnum] of Integer =
( 12, 7, 8, 12, 14, 18, 24, 36 );
ssTextDecorations: array[TThCssFontDecoration] of string = ( '', 'inherit',
'none', 'underline', 'overline', 'line-through', 'blink' );
ssFontStyles: array[TThCssFontStyle] of string = ( '', 'inherit', 'normal',
'italic', 'oblique' );
//
// ssOverflowStyles: array[TThCssOverflowStyle] of string = ( '', 'inherit',
// 'visible', 'hidden', 'scroll', 'auto' );
//
ssNumCursors = 19;
ssCursors: array[0..18] of string = ( '', 'inherit', 'default', 'auto',
'n-resize', 'ne-resize', 'e-resize', 'se-resize', 's-resize', 'sw-resize',
'w-resize', 'nw-resize', 'crosshair', 'pointer', 'move', 'text', 'wait',
'help', 'hand' );
const
ThDefaultFontFamily: string = 'Times New Roman';
ThDefaultFontPx: Integer = 16;
var
NilStyle: TThCssStyle;
implementation
function ThInlineStylesToAttribute(const inStyles: string): string;
begin
if inStyles = '' then
Result := ''
else
Result := ' style="' + inStyles + '"';
end;
function ThStringIsDigits(const inString: string): Boolean;
var
i: Integer;
begin
Result := false;
for i := 1 to Length(inString) do
if (inString[i] < '0') or (inString[i] > '9') then
exit;
Result := inString <> '';
end;
function ThVisibleColor(inColor: TColor): Boolean;
begin
Result := (inColor <> clNone) and (inColor <> clDefault);
end;
function ThColorToHtml(const Color: TColor): string;
var
c: TColor;
begin
c := ColorToRGB(Color);
{$ifndef __ThVcl__}
{
if Integer(Color) < 0 then
Result := '#' +
IntToHex(Byte(c shr 16), 2) +
IntToHex(Byte(c shr 8), 2) +
IntToHex(Byte(c), 2)
else
}
{$endif}
Result := '#' +
IntToHex(Byte(c), 2) +
IntToHex(Byte(c shr 8), 2) +
IntToHex(Byte(c shr 16), 2);
end;
function ThStyleProp(const inProp, inValue: string): string; overload;
begin
if inValue = '' then
Result := ''
else
Result := inProp + ':' + inValue + ';';
end;
function ThStyleProp(const inProp: string;
inColor: TColor): string; overload;
begin
if ThVisibleColor(inColor) then
Result := inProp + ':' + ThColorToHtml(inColor) + ';';
end;
function ThPercValue(inPerc: Integer): string;
begin
Result := IntToStr(inPerc) + ssPerc;
end;
function ThPxValue(inPx: Integer): string;
begin
Result := IntToStr(inPx) + ssPx;
end;
procedure ThCat(var ioDst: string; const inAdd: string);
begin
if (inAdd <> '') then
if (ioDst = '') then
ioDst := inAdd
else
ioDst := ioDst + ' ' + inAdd;
end;
{ TThCssBase }
procedure TThCssBase.Changed;
begin
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
{ TThCssFont }
constructor TThCssFont.Create;
begin
FontColor := clNone;
DefaultFontFamily := ThDefaultFontFamily;
DefaultFontPx := ThDefaultFontPx;
end;
procedure TThCssFont.SetFontFamily(const Value: TFontName);
begin
if FFontFamily <> Value then
begin
FFontFamily := Value;
Changed;
end;
end;
procedure TThCssFont.SetRelFontSize(const Value: TThCssFontSizeRel);
begin
if FFontSizeRel <> Value then
begin
FFontSizeRel := Value;
Changed;
end;
end;
procedure TThCssFont.SetFontWeight(const Value: TThCssFontWeight);
begin
if FFontWeight <> Value then
begin
FFontWeight := Value;
Changed;
end;
end;
procedure TThCssFont.SetFontSizePx(const Value: Integer);
begin
if FFontSizePx <> Value then
begin
FFontSizePx := Value;
Changed;
end;
end;
procedure TThCssFont.SetFontSizePt(const Value: Integer);
begin
if FFontSizePt <> Value then
begin
FFontSizePt := Value;
Changed;
end;
end;
procedure TThCssFont.SetFontColor(const Value: TColor);
begin
if FFontColor <> Value then
begin
FFontColor := Value;
Changed;
end;
end;
procedure TThCssFont.SetFontDecoration(
const Value: TThCssFontDecoration);
begin
FFontDecoration := Value;
Changed;
end;
procedure TThCssFont.SetFontStyle(const Value: TThCssFontStyle);
begin
FFontStyle := Value;
Changed;
end;
function TThCssFont.GetSizeValue: string;
begin
if (FontSizeRel <> '') then
Result := FontSizeRel
else if (FontSizePt <> 0) then
Result := Format('%dpt', [ FontSizePt ])
else if (FontSizePx <> 0) then
Result := ThPxValue(FontSizePx)
else
Result := '';
end;
{
procedure TThCssFont.Stylize(inNode: TThHtmlNode);
var
fs, s: string;
begin
fs := GetSizeValue;
if (FontFamily <> '') and (fs <> '') then
begin
s := ssFontStyles[FontStyle];
ThCat(s, ssFontWeights[FontWeight]);
ThCat(s, fs);
ThCat(s, FontFamily);
inNode.AddStyle(ssFont, s);
end
else begin
inNode.AddStyle(ssFontFamily, FontFamily);
inNode.AddStyle(ssFontSize, fs);
inNode.AddStyle(ssFontWeight, ssFontWeights[FontWeight]);
inNode.AddStyle(ssFontStyle, ssFontStyles[FontStyle]);
end;
inNode.AddStyle(ssColor, FontColor);
inNode.AddStyle(ssTextDecoration, ssTextDecorations[FontDecoration]);
end;
}
function TThCssFont.InlineAttribute: string;
var
fs: string;
begin
fs := GetSizeValue;
if (FontFamily <> '') and (fs <> '') then
begin
Result := ssFontStyles[FontStyle];
ThCat(Result, ssFontWeights[FontWeight]);
ThCat(Result, fs);
ThCat(Result, FontFamily);
Result := ThStyleProp(ssFont, Result);
end
else begin
Result := ThStyleProp(ssFontFamily, FontFamily);
ThCat(Result, ThStyleProp(ssFontSize, fs));
ThCat(Result, ThStyleProp(ssFontWeight, ssFontWeights[FontWeight]));
ThCat(Result, ThStyleProp(ssFontStyle, ssFontStyles[FontStyle]));
end;
ThCat(Result, ThStyleProp(ssColor, FontColor));
ThCat(Result, ThStyleProp(ssTextDecoration,
ssTextDecorations[FontDecoration]));
end;
procedure TThCssFont.ListStyles(inStyles: TThStyleList);
var
fs, s: string;
begin
fs := GetSizeValue;
if (FontFamily <> '') and (fs <> '') then
begin
s := ssFontStyles[FontStyle];
ThCat(s, ssFontWeights[FontWeight]);
ThCat(s, fs);
ThCat(s, FontFamily);
inStyles.Add(ssFont, s);
end
else begin
inStyles.Add(ssFontFamily, FontFamily);
inStyles.Add(ssFontSize, fs);
inStyles.Add(ssFontWeight, ssFontWeights[FontWeight]);
inStyles.Add(ssFontStyle, ssFontStyles[FontStyle]);
end;
inStyles.AddColor(ssColor, FontColor);
inStyles.Add(ssTextDecoration, ssTextDecorations[FontDecoration]);
end;
function TThCssFont.GetRelFontSize: Integer;
var
i: TThCssFontSizeRelEnum;
begin
Result := cTFontSizes[fsDefault];
for i := Low(TThCssFontSizeRelEnum) to High(TThCssFontSizeRelEnum) do
if (ssRelFontSizes[i] = FontSizeRel) then
begin
Result := cTFontSizes[i];
break;
end;
end;
procedure TThCssFont.ToFont(inFont: TFont);
var
s: TFontStyles;
begin
with inFont do
begin
if FontFamily <> '' then
Name := FontFamily
else
Name := DefaultFontFamily;
s := [];
if FontWeight = fwBold then
s := s + [ fsBold ];
if FontDecoration = fdUnderline then
s := s + [ fsUnderline ];
if FontDecoration = fdLineThrough then
s := s + [ fsStrikeOut ];
if (FontStyle = fstItalic) or (FontStyle = fstOblique) then
s := s + [ fsItalic ];
Style := s;
if FontSizeRel <> '' then
Size := GetRelFontSize
else if (FontSizePt <> 0) then
Height := -FontSizePt * 4 div 3
else if (FontSizePx <> 0) then
Height := -FontSizePx
else
Height := -DefaultFontPx;
if ThVisibleColor(FontColor) then
Color := FontColor
else
Color := clBlack;
end;
end;
procedure TThCssFont.Inherit(inFont: TThCssFont);
begin
if inFont = nil then
exit;
if (FFontFamily = '') then
FFontFamily := inFont.FFontFamily;
if (FontWeight = fwDefault) then
FFontWeight := inFont.FFontWeight;
//if (FFontColor = clDefault) then
if not ThVisibleColor(FFontColor) then
FFontColor := inFont.FFontColor;
if (FFontDecoration = fdDefault) then
FFontDecoration := inFont.FFontDecoration;
if (FFontStyle = fstDefault) then
FFontStyle := inFont.FFontStyle;
if (FFontSizePx = 0) then
begin
FFontSizePx := inFont.FFontSizePx;
if (FFontSizePt = 0) then
begin
FFontSizePt := inFont.FFontSizePt;
if (FFontSizeRel = '') then
FFontSizeRel := inFont.FFontSizeRel;
end;
end;
end;
procedure TThCssFont.Assign(Source: TPersistent);
begin
if not (Source is TThCssFont) then
inherited
else with TThCssFont(Source) do
begin
Self.FFontSizeRel := FFontSizeRel;
Self.FFontFamily := FFontFamily;
Self.FFontWeight := FFontWeight;
Self.FFontSizePx := FFontSizePx;
Self.FFontSizePt := FFontSizePt;
Self.FFontColor := FFontColor;
Self.FFontDecoration := FFontDecoration;
Self.FFontStyle := FFontStyle;
end;
end;
procedure TThCssFont.SetDefaultFontFamily(const Value: string);
begin
FDefaultFontFamily := Value;
end;
procedure TThCssFont.SetDefaultFontPx(const Value: Integer);
begin
FDefaultFontPx := Value;
end;
{ TThCssBackground }
constructor TThCssBackground.Create(AOwner: TComponent);
begin
inherited Create;
FPicture := TThPicture.Create(AOwner);
FPicture.OnChange := PictureChange;
end;
destructor TThCssBackground.Destroy;
begin
FPicture.Free;
inherited;
end;
procedure TThCssBackground.Assign(Source: TPersistent);
begin
if not (Source is TThCssBackground) then
inherited
else with TThCssBackground(Source) do
Self.Picture := Picture;
end;
procedure TThCssBackground.Inherit(inBackground: TThCssBackground);
begin
if not Picture.HasGraphic then
Picture := inBackground.Picture;
end;
function TThCssBackground.InlineAttribute: string;
begin
if Picture.PictureUrl <> '' then
Result := ThStyleProp(ssBackgroundImage, 'url(' + Picture.PictureUrl + ')')
else
Result := '';
end;
procedure TThCssBackground.ListStyles(inStyles: TThStyleList);
begin
if Picture.PictureUrl <> '' then
inStyles.Add(ssBackgroundImage, 'url(' + Picture.PictureUrl + ')');
end;
procedure TThCssBackground.PictureChange(inSender: TObject);
begin
Changed;
end;
procedure TThCssBackground.SetPicture(const Value: TThPicture);
begin
Picture.Assign(Value);
end;
{ TThCssBorder }
constructor TThCssBorder.Create(inOwner: TThCssBase;
inSide: TThCssBorderSide);
begin
FOwnerStyle := inOwner;
BorderSide := inSide;
FBorderPrefix := ssBorderPrefixi[inSide];
FBorderColor := clDefault;
end;
procedure TThCssBorder.Changed;
begin
inherited;
if FOwnerStyle <> nil then
FOwnerStyle.Changed;
end;
function TThCssBorder.BorderVisible: Boolean;
begin
case BorderStyle of
bsDefault: Result := DefaultBorderPixels <> 0;
bsNone, bsHidden: Result := false;
else Result := true;
end;
inherited;
end;
function TThCssBorder.GetBorderPixels: Integer;
const
cThickBorder = 6;
cMediumBorder = 4;
cThinBorder = 2;
cDefaultBorder = cMediumBorder;
begin
Result := 0;
if BorderVisible then
begin
if BorderStyle = bsDefault then
Result := DefaultBorderPixels
else if BorderWidth = '' then
Result := cDefaultBorder
else if BorderWidth = 'thin' then
Result := cThinBorder
else if BorderWidth = 'medium' then
Result := cMediumBorder
else if BorderWidth = 'thick' then
Result := cThickBorder
else
Result := StrToIntDef(BorderWidth, cDefaultBorder);
end;
end;
procedure TThCssBorder.SetBorderColor(const Value: TColor);
begin
FBorderColor := Value;
Changed;
end;
procedure TThCssBorder.SetBorderStyle(const Value: TThCssBorderStyle);
begin
FBorderStyle := Value;
Changed;
end;
procedure TThCssBorder.SetBorderWidth(const Value: string);
begin
FBorderWidth := Value;
Changed;
end;
function TThCssBorder.InlineAttribute: string;
var
bws: string;
begin
Result := '';
if ThStringIsDigits(BorderWidth) then
bws := BorderWidth + 'px'
else
bws := BorderWidth;
if BorderStyle <> bsDefault then
if (ssBorderStyles[BorderStyle] <> '') and (BorderWidth <> '') and
ThVisibleColor(BorderColor) then
begin
Result := ThStyleProp(FBorderPrefix,
bws + ' ' + ssBorderStyles[BorderStyle] + ' '
+ ThColorToHtml(BorderColor));
end else begin
ThCat(Result,
ThStyleProp(FBorderPrefix + '-' + ssStyle,
ssBorderStyles[BorderStyle]));
if bws <> '' then
ThCat(Result,
ThStyleProp(FBorderPrefix + '-' + ssWidth, bws));
ThCat(Result,
ThStyleProp(FBorderPrefix + '-' + ssColor, BorderColor));
end;
end;
procedure TThCssBorder.ListStyles(inStyles: TThStyleList);
var
bws: string;
begin
if ThStringIsDigits(BorderWidth) then
bws := BorderWidth + 'px'
else
bws := BorderWidth;
if BorderStyle <> bsDefault then
if (ssBorderStyles[BorderStyle] <> '') and (BorderWidth <> '') and
ThVisibleColor(BorderColor) then
begin
inStyles.Add(FBorderPrefix,
bws + ' ' + ssBorderStyles[BorderStyle] + ' '
+ ThColorToHtml(BorderColor));
end
else begin
inStyles.Add(FBorderPrefix + '-' + ssStyle, ssBorderStyles[BorderStyle]);
inStyles.Add(FBorderPrefix + '-' + ssWidth, bws);
inStyles.AddColor(FBorderPrefix + '-' + ssColor, BorderColor);
end;
end;
procedure TThCssBorder.Assign(Source: TPersistent);
begin
if not (Source is TThCssBorder) then
inherited
else with TThCssBorder(Source) do
begin
Self.FBorderWidth := FBorderWidth;
Self.FBorderStyle := FBorderStyle;
Self.FBorderColor := FBorderColor;
end;
end;
procedure TThCssBorder.Inherit(inBorder: TThCssBorder);
begin
if inBorder.FBorderWidth <> '' then
FBorderWidth := inBorder.FBorderWidth;
if inBorder.FBorderStyle <> bsDefault then
FBorderStyle := inBorder.FBorderStyle;
if ThVisibleColor(inBorder.FBorderColor) then
FBorderColor := inBorder.FBorderColor;
end;
{ TThCssBorderDetail }
constructor TThCssBorderDetail.Create(inOwnerStyle: TThCssBase);
begin
inherited Create;
FBorderLeft := TThCssBorder.Create(inOwnerStyle, bsLeft);
FBorderTop := TThCssBorder.Create(inOwnerStyle, bsTop);
FBorderRight := TThCssBorder.Create(inOwnerStyle, bsRight);
FBorderBottom := TThCssBorder.Create(inOwnerStyle, bsBottom);
end;
destructor TThCssBorderDetail.Destroy;
begin
FBorderLeft.Free;
FBorderTop.Free;
FBorderRight.Free;
FBorderBottom.Free;
inherited;
end;
function TThCssBorderDetail.BorderVisible: Boolean;
begin
Result := BorderLeft.BorderVisible or
BorderTop.BorderVisible or
BorderRight.BorderVisible or
BorderBottom.BorderVisible;
end;
procedure TThCssBorderDetail.Assign(Source: TPersistent);
begin
if not (Source is TThCssBorderDetail) then
inherited
else with TThCssBorderDetail(Source) do
begin
Self.FBorderLeft.Assign(FBorderLeft);
Self.FBorderTop.Assign(FBorderTop);
Self.FBorderRight.Assign(FBorderRight);
Self.FBorderBottom.Assign(FBorderBottom);
end;
end;
procedure TThCssBorderDetail.Inherit(inDetail: TThCssBorderDetail);
begin
FBorderLeft.Inherit(inDetail.FBorderLeft);
FBorderTop.Inherit(inDetail.FBorderTop);
FBorderRight.Inherit(inDetail.FBorderRight);
FBorderBottom.Inherit(inDetail.FBorderBottom);
end;
function TThCssBorderDetail.InlineAttribute: string;
begin
Result := BorderLeft.InlineAttribute
+ BorderTop.InlineAttribute
+ BorderRight.InlineAttribute
+ BorderBottom.InlineAttribute;
end;
procedure TThCssBorderDetail.ListStyles(inStyles: TThStyleList);
begin
BorderLeft.ListStyles(inStyles);
BorderTop.ListStyles(inStyles);
BorderRight.ListStyles(inStyles);
BorderBottom.ListStyles(inStyles);
end;
function TThCssBorderDetail.GetBorder(inSide: TThCssBorderSide): TThCssBorder;
begin
case inSide of
bsLeft: Result := BorderLeft;
bsTop: Result := BorderTop;
bsRight: Result := BorderRight;
bsBottom: Result := BorderBottom;
else Result := BorderLeft;
end;
end;
procedure TThCssBorderDetail.SetBorderBottom(const Value: TThCssBorder);
begin
FBorderBottom.Assign(Value);
end;
procedure TThCssBorderDetail.SetBorderLeft(const Value: TThCssBorder);
begin
FBorderLeft.Assign(Value);
end;
procedure TThCssBorderDetail.SetBorderRight(const Value: TThCssBorder);
begin
FBorderRight.Assign(Value);
end;
procedure TThCssBorderDetail.SetBorderTop(const Value: TThCssBorder);
begin
FBorderTop.Assign(Value);
end;
procedure TThCssBorderDetail.SetDefaultBorderPixels(inPixels: Integer);
begin
BorderLeft.DefaultBorderPixels := inPixels;
BorderTop.DefaultBorderPixels := inPixels;
BorderRight.DefaultBorderPixels := inPixels;
BorderBottom.DefaultBorderPixels := inPixels;
end;
{ TThCssBorders }
constructor TThCssBorders.Create;
begin
inherited Create(nil, bsAll);
FEdges := TThCssBorderDetail.Create(Self);
Changed;
end;
destructor TThCssBorders.Destroy;
begin
FEdges.Free;
inherited;
end;
procedure TThCssBorders.Assign(Source: TPersistent);
begin
inherited;
if (Source is TThCssBorders) then
with TThCssBorders(Source) do
Self.Edges.Assign(Edges);
end;
procedure TThCssBorders.Inherit(inBox: TThCssBorders);
begin
inherited Inherit(inBox);
Edges.Inherit(inBox.Edges);
end;
function TThCssBorders.InlineAttribute: string;
begin
if BorderStyle <> bsDefault then
Result := inherited InlineAttribute
else
Result := Edges.InlineAttribute;
end;
procedure TThCssBorders.ListStyles(inStyles: TThStyleList);
begin
if BorderStyle <> bsDefault then
inherited ListStyles(inStyles)
else
Edges.ListStyles(inStyles);
end;
function TThCssBorders.GetBorderColor(inSide: TThCssBorderSide): TColor;
begin
if BorderStyle <> bsDefault then
Result := BorderColor
else
Result := Edges.GetBorder(inSide).BorderColor;
end;
function TThCssBorders.GetBorderStyle(
inSide: TThCssBorderSide): TThCssBorderStyle;
begin
if BorderStyle <> bsDefault then
Result := BorderStyle
else
Result := Edges.GetBorder(inSide).BorderStyle;
end;
function TThCssBorders.GetBorderPixels(inSide: TThCssBorderSide): Integer;
begin
if BorderStyle <> bsDefault then
Result := GetBorderPixels
else
Result := Edges.GetBorder(inSide).GetBorderPixels;
end;
function TThCssBorders.BorderVisible: Boolean;
begin
Result := inherited BorderVisible or Edges.BorderVisible;
end;
procedure TThCssBorders.SetDefaultBorderPixels(inPixels: Integer);
begin
FDefaultBorderPixels := inPixels;
Edges.DefaultBorderPixels := inPixels;
end;
procedure TThCssBorders.SetEdges(const Value: TThCssBorderDetail);
begin
FEdges.Assign(Value);
end;
{ TThCssPadDetail }
constructor TThCssPadDetail.Create(inOwnerStyle: TThCssBase);
begin
FOwnerStyle := inOwnerStyle;
end;
procedure TThCssPadDetail.Changed;
begin
inherited;
if FOwnerStyle <> nil then
FOwnerStyle.Changed;
end;
function TThCssPadDetail.HasPadding: Boolean;
begin
Result := (PadLeft <> 0) or (PadRight <> 0) or (PadTop <> 0)
or (PadBottom <> 0);
end;
procedure TThCssPadDetail.Assign(Source: TPersistent);
begin
if not (Source is TThCssPadDetail) then
inherited
else with TThCssPadDetail(Source) do
begin
Self.FPadLeft := FPadLeft;
Self.FPadTop := FPadTop;
Self.FPadRight := FPadRight;
Self.FPadBottom := FPadBottom;
end;
end;
procedure TThCssPadDetail.Inherit(inPad: TThCssPadDetail);
begin
if (inPad.FPadLeft <> 0) then
FPadLeft := inPad.FPadLeft;
if (inPad.FPadTop <> 0) then
FPadTop := inPad.FPadTop;
if (inPad.FPadRight <> 0) then
FPadRight := inPad.FPadRight;
if (inPad.FPadBottom <> 0) then
FPadBottom := inPad.FPadBottom;
end;
function TThCssPadDetail.InlineAttribute: string;
begin
Result := '';
if (PadLeft <> 0) then
ThCat(Result, ThStyleProp(ssPaddingLeft, ThPxValue(PadLeft)));
if (PadTop <> 0) then
ThCat(Result, ThStyleProp(ssPaddingTop, ThPxValue(PadTop)));
if (PadRight <> 0) then
ThCat(Result, ThStyleProp(ssPaddingRight, ThPxValue(PadRight)));
if (PadBottom <> 0) then
ThCat(Result, ThStyleProp(ssPaddingBottom, ThPxValue(PadBottom)));
end;
procedure TThCssPadDetail.ListStyles(inStyles: TThStyleList);
begin
with inStyles do
begin
AddIfNotZero(ssPaddingLeft, PadLeft, ssPx);
AddIfNotZero(ssPaddingTop, PadTop, ssPx);
AddIfNotZero(ssPaddingRight, PadRight, ssPx);
AddIfNotZero(ssPaddingBottom, PadBottom, ssPx);
end;
end;
function TThCssPadDetail.PadHeight: Integer;
begin
Result := PadTop + PadBottom;
end;
function TThCssPadDetail.PadWidth: Integer;
begin
Result := PadLeft + PadRight;
end;
procedure TThCssPadDetail.SetPadBottom(const Value: Integer);
begin
FPadBottom := Value;
Changed;
end;
procedure TThCssPadDetail.SetPadLeft(const Value: Integer);
begin
FPadLeft := Value;
Changed;
end;
procedure TThCssPadDetail.SetPadRight(const Value: Integer);
begin
FPadRight := Value;
Changed;
end;
procedure TThCssPadDetail.SetPadTop(const Value: Integer);
begin
FPadTop := Value;
Changed;
end;
procedure TThCssPadDetail.SetPadding(const Value: Integer);
begin
FPadLeft := Value;
FPadRight := Value;
FPadTop := Value;
FPadBottom := Value;
Changed;
end;
{ TThCssPadding }
constructor TThCssPadding.Create;
begin
inherited;
FPaddingDetails := TThCssPadDetail.Create(Self);
end;
destructor TThCssPadding.Destroy;
begin
FPaddingDetails.Free;
inherited;
end;
procedure TThCssPadding.Changed;
begin
if PaddingDetails.HasPadding then
FPadding := 0;
inherited;
end;
function TThCssPadding.HasPadding: Boolean;
begin
Result := (Padding <> 0) or PaddingDetails.HasPadding;
end;
function TThCssPadding.PadHeight: Integer;
begin
if Padding <> 0 then
Result := Padding + Padding
else
Result := PaddingDetails.PadHeight;
end;
function TThCssPadding.PadWidth: Integer;
begin
if Padding <> 0 then
Result := Padding + Padding
else
Result := PaddingDetails.PadWidth;
end;
function TThCssPadding.PadLeft: Integer;
begin
if Padding <> 0 then
Result := Padding
else
Result := PaddingDetails.PadLeft;
end;
function TThCssPadding.PadTop: Integer;
begin
if Padding <> 0 then
Result := Padding
else
Result := PaddingDetails.PadTop;
end;
function TThCssPadding.PadRight: Integer;
begin
if Padding <> 0 then
Result := Padding
else
Result := PaddingDetails.PadRight;
end;
function TThCssPadding.PadBottom: Integer;
begin
if Padding <> 0 then
Result := Padding
else
Result := PaddingDetails.PadBottom;
end;
procedure TThCssPadding.Assign(Source: TPersistent);
begin
if not (Source is TThCssPadding) then
inherited
else with TThCssPadding(Source) do
begin
Self.Padding := Padding;
Self.PaddingDetails.Assign(PaddingDetails);
end;
end;
procedure TThCssPadding.Inherit(inPad: TThCssPadding);
begin
if (inPad.Padding <> 0) then
Padding := inPad.Padding;
PaddingDetails.Inherit(inPad.PaddingDetails);
end;
function TThCssPadding.InlineAttribute: string;
begin
if (Padding <> 0) then
Result := ThStyleProp(ssPadding, ThPxValue(Padding))
else
Result := PaddingDetails.InlineAttribute;
end;
procedure TThCssPadding.ListStyles(inStyles: TThStyleList);
begin
if (Padding <> 0) then
inStyles.Add(ssPadding, Padding, 'px')
else
PaddingDetails.ListStyles(inStyles);
end;
procedure TThCssPadding.SetPadding(const Value: Integer);
begin
FPadding := Value;
Changed;
end;
procedure TThCssPadding.SetPaddingDetails(const Value: TThCssPadDetail);
begin
FPaddingDetails.Assign(Value);
end;
{ TThCssStyle }
constructor TThCssStyle.Create(AOwner: TComponent);
begin
inherited Create;
FOwner := AOwner;
FBackground := TThCssBackground.Create(AOwner);
FBackground.OnChanged := InternalChanged;
FFont := TThCssFont.Create;
FFont.OnChanged := InternalChanged;
FBorders := TThCssBorders.Create;
FBorders.OnChanged := InternalChanged;
FPadding := TThCssPadding.Create;
FPadding.OnChanged := InternalChanged;
// FOverflow := TThCssOverflow.Create;
// FOverflow.OnChanged := InternalChanged;
FColor := clNone;
end;
destructor TThCssStyle.Destroy;
begin
// FOverflow.Free;
FPadding.Free;
FBorders.Free;
FFont.Free;
FBackground.Free;
inherited;
end;
function TThCssStyle.Owner: TComponent;
begin
Result := FOwner;
end;
procedure TThCssStyle.InternalChanged(inSender: TObject);
begin
Changed;
end;
function TThCssStyle.StyleAttribute: string;
begin
Result := InlineAttribute;
if Result <> '' then
Result := ' style="' + Result + '"';
end;
function TThCssStyle.InlineColorAttribute: string;
begin
Result := ThStyleProp(ssBackgroundColor, Color);
end;
function TThCssStyle.InlineAttribute: string;
begin
Result := '';
ThCat(Result, FFont.InlineAttribute);
ThCat(Result, InlineColorAttribute);
ThCat(Result, FBackground.InlineAttribute);
ThCat(Result, FBorders.InlineAttribute);
ThCat(Result, FPadding.InlineAttribute);
//ThCat(Result, FOverflow.InlineAttribute);
ThCat(Result, ExtraStyles);
end;
procedure TThCssStyle.ListStyles(inStyles: TThStyleList);
begin
FFont.ListStyles(inStyles);
inStyles.AddColor(ssBackgroundColor, Color);
FBackground.ListStyles(inStyles);
FBorders.ListStyles(inStyles);
FPadding.ListStyles(inStyles);
inStyles.Add(ssCursor, Cursor);
inStyles.ExtraStyles := inStyles.ExtraStyles + ExtraStyles;
end;
procedure TThCssStyle.ToFont(inFont: TFont);
begin
Font.ToFont(inFont);
end;
procedure TThCssStyle.AssignFromParent(inParent: TThCssStyle);
begin
if FParentFont then
FFont.Assign(inParent.FFont);
if FParentColor then
FColor := inParent.FColor;
end;
procedure TThCssStyle.Assign(Source: TPersistent);
begin
if Source <> nil then
if not (Source is TThCssStyle) then
inherited
else with TThCssStyle(Source) do
begin
Self.FBackground.Assign(FBackground);
Self.FBorders.Assign(FBorders);
Self.FFont.Assign(FFont);
//Self.FOverflow.Assign(FOverflow);
Self.FPadding.Assign(FPadding);
Self.FColor := FColor;
Self.FCursor := FCursor;
Self.ExtraStyles := ExtraStyles;
end;
end;
procedure TThCssStyle.Inherit(inStyle: TThCssStyle);
begin
if (inStyle <> nil) then
begin
FBackground.Inherit(inStyle.FBackground);
FBorders.Inherit(inStyle.FBorders);
FFont.Inherit(inStyle.FFont);
//FOverflow.Inherit(inStyle.FOverflow);
FPadding.Inherit(inStyle.FPadding);
if not ThVisibleColor(FColor) then
FColor := inStyle.FColor;
if (inStyle.FCursor <> '') then
FCursor := inStyle.FCursor;
//ExtraStyles := ThConcatWithDelim(ExtraStyles, inStyle.ExtraStyles, ';');
end;
end;
procedure TThCssStyle.SetBorders(const Value: TThCssBorders);
begin
FBorders.Assign(Value);
Changed;
end;
procedure TThCssStyle.SetBackground(const Value: TThCssBackground);
begin
FBackground.Assign(Value);
Changed;
end;
procedure TThCssStyle.SetFont(const Value: TThCssFont);
begin
FFont.Assign(Value);
Changed;
end;
//procedure TThCssStyle.SetOverflow(const Value: TThCssOverflow);
//begin
// FOverflow.Assign(Value);
// Changed;
//end;
procedure TThCssStyle.SetPadding(const Value: TThCssPadding);
begin
FPadding.Assign(Value);
Changed;
end;
procedure TThCssStyle.SetName(const Value: string);
begin
FName := Value;
end;
procedure TThCssStyle.SetColor(const Value: TColor);
begin
FColor := Value;
if (FOwner = nil) or not (csLoading in FOwner.ComponentState) then
begin
FParentColor := false;
Changed;
end;
end;
procedure TThCssStyle.SetExtraStyles(const Value: string);
begin
FExtraStyles := Value;
end;
procedure TThCssStyle.SetCursor(const Value: string);
begin
FCursor := Value;
Changed;
end;
procedure TThCssStyle.SetParentColor(const Value: Boolean);
begin
FParentColor := Value;
Changed;
end;
procedure TThCssStyle.SetParentFont(const Value: Boolean);
begin
FParentFont := Value;
Changed;
//Font.ParentFont := FParentFont;
end;
function TThCssStyle.GetBoxBottom: Integer;
begin
Result := Border.GetBorderPixels(bsBottom) + Padding.PadBottom;
end;
function TThCssStyle.GetBoxLeft: Integer;
begin
Result := Border.GetBorderPixels(bsLeft) + Padding.PadLeft;
end;
function TThCssStyle.GetBoxRight: Integer;
begin
Result := Border.GetBorderPixels(bsRight) + Padding.PadRight;
end;
function TThCssStyle.GetBoxTop: Integer;
begin
Result := Border.GetBorderPixels(bsTop) + Padding.PadTop;
end;
procedure TThCssStyle.UnpadRect(var ioRect: TRect);
begin
with ioRect do
begin
Left := Left + Padding.PadLeft;
Right := Right - Padding.PadRight;
Top := Top + Padding.PadTop;
Bottom := Bottom - Padding.PadBottom;
end;
end;
{
procedure TThCssStyle.ExpandRect(var ioRect: TRect);
begin
with ioRect do
begin
Left := Left - GetBoxLeft;
Right := Right + GetBoxRight;
Top := Top - GetBoxTop;
Bottom := Bottom + GetBoxBottom;
end;
end;
}
procedure TThCssStyle.AdjustClientRect(var ioRect: TRect);
begin
with ioRect do
begin
Inc(Left, GetBoxLeft);
Inc(Top, GetBoxTop);
Dec(Right, GetBoxRight);
Dec(Bottom, GetBoxBottom);
// Left := Left + GetBoxLeft;
// Right := Right - GetBoxRight;
// Top := Top + GetBoxTop;
// Bottom := Bottom - GetBoxBottom;
end;
end;
function TThCssStyle.GetBoxWidthMargin: Integer;
begin
Result := GetBoxLeft + GetBoxRight;
end;
function TThCssStyle.GetBoxHeightMargin: Integer;
begin
Result := GetBoxTop + GetBoxBottom;
end;
function TThCssStyle.AdjustWidth(inWidth: Integer): Integer;
begin
Result := inWidth - GetBoxWidthMargin;
end;
function TThCssStyle.AdjustHeight(inHeight: Integer): Integer;
begin
Result := inHeight - GetBoxHeightMargin;
end;
initialization
NilStyle := TThCssStyle.Create(nil);
finalization
NilStyle.Free;
end.
|
unit LightSourceUnit;
// ========================================================================
// MesoCam: Light Source control module
// (c) J.Dempster, Strathclyde Institute for Pharmacy & Biomedical Sciences
// ========================================================================
interface
uses
System.SysUtils, System.Classes, LabIOUnit ;
const
MaxLightSources = 8 ;
type
TLightSource = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Active : Array [0..MaxLightSources-1] of Boolean ;
Intensity : Array[0..MaxLightSources-1] of Double ;
ControlLines : Array[0..MaxLightSources-1] of Integer ;
Names : Array[0..MaxLightSources-1] of string ;
MinLevel : Array[0..MaxLightSources-1] of Double ;
MaxLevel : Array[0..MaxLightSources-1] of Double ;
List : Array[0..MaxLightSources-1] of Integer ;
NumList : Integer ;
ListIndex : Integer ;
procedure GetTypes( List : TStrings ) ;
procedure GetControlLineNames( List : TStrings ) ;
procedure Update ;
end;
var
LightSource : TLightSource ;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TLightSource.GetTypes( List : TStrings ) ;
// -----------------------------------
// Get list of supported light sources
// -----------------------------------
begin
List.Clear ;
List.Add('None') ;
List.Add('LED') ;
end;
procedure TLightSource.DataModuleCreate(Sender: TObject);
var
I: Integer;
// --------------------------------
// Initialise light source settings
// --------------------------------
begin
for I := 0 to High(Names) do begin
Names[i] := format('LS%d',[i]) ;
ControlLines[i] := LineDisabled ;
MinLevel[i] := 0.0 ;
MaxLevel[i] := 5.0 ;
end;
end;
Procedure TLightSource.GetControlLineNames( List : TStrings ) ;
// -----------------------------------
// Get list of available control ports
// -----------------------------------
var
i : Integer ;
iDev: Integer;
s : string ;
begin
List.Clear ;
List.AddObject('None',TObject(LineDisabled)) ;
for i := 0 to LabIO.NumResources-1 do
begin
if (LabIO.Resource[i].ResourceType = DACOut) then
begin
// Analog outputs
s := format('Dev%d: AO.%d',
[LabIO.Resource[i].Device,
LabIO.Resource[i].StartChannel]) ;
List.AddObject(s,TObject(i))
end
else if (LabIO.Resource[i].ResourceType = DIGOut) then
begin
// Digital outputs
s := format('Dev%d: PO.%d',
[LabIO.Resource[i].Device,
LabIO.Resource[i].StartChannel]) ;
List.AddObject(s,TObject(i))
end ;
end;
end;
procedure TLightSource.Update ;
// ---------------------------------
// Update light source control lines
// ---------------------------------
var
V : Single ;
i,Dev,Chan : Integer ;
ResourceType : TResourceType ;
begin
for i := 0 to High(ControlLines) do if ControlLines[i] < LineDisabled then
begin
Dev := LabIO.Resource[ControlLines[i]].Device ;
Chan := LabIO.Resource[ControlLines[i]].StartChannel ;
ResourceType := LabIO.Resource[ControlLines[i]].ResourceType ;
if ResourceType = DACOut then
begin
// Analogue outputs
if Active[i] then V := (MaxLevel[i] - MinLevel[i])*(Intensity[i]/100.0) + MinLevel[i]
else V := MinLevel[i] ;
LabIO.DACOutState[Dev][Chan] := V ;
LabIO.WriteDAC(Dev,V,Chan);
end
else if ResourceType = DIGOut then
begin
// Digital outputs
if Active[i] then LabIO.SetBit(LabIO.DigOutState[Dev],Chan,0)
else LabIO.SetBit(LabIO.DigOutState[Dev],Chan,1) ;
end;
end;
// Update digital outputs
for Dev := 1 to LabIO.NumDevices do LabIO.WriteToDigitalOutPutPort( Dev, LabIO.DigOutState[Dev] ) ;
end;
end.
|
unit UII2XOptions;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
UIOptionsBase,
StdCtrls,
Buttons,
ComCtrls,
ExtCtrls,
OmniXML,
ActnList,
ImgList,
Typinfo,
uStrUtil,
Grids,
uI2XOptions,
uI2XDLL,
uHashTable,
uI2XPluginManager,
uI2XOCR
;
type
TI2XOptionsEnum = (
iAPPLICATION = 0,
iPLUGINS,
iPLUGINSOCR,
iPLUGINSIMG,
iTWAIN
);
TI2XOptionsUI = class(TOptionsBaseUI)
pnlApplication: TPanel;
pnlPlugins: TPanel;
chkGridSnap: TCheckBox;
txtGridSize: TEdit;
UpDownGridSize: TUpDown;
lblGridSize: TLabel;
grdPlugins: TStringGrid;
pnlTWAIN: TPanel;
lblDeviceList: TLabel;
lstTWAINDevices: TListBox;
lblRootPath: TLabel;
btnJobRootPathSelect: TSpeedButton;
txtJobRootPath: TEdit;
procedure FormCreate(Sender: TObject); override;
procedure txtGridSizeChange(Sender: TObject);
procedure FormDestroy(Sender: TObject); override;
procedure chkGridSnapClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure TreeNodeCheckBoxClickHandler( Node :TTreeNode; isChecked : boolean );
procedure lstTWAINDevicesClick(Sender: TObject);
procedure btnJobRootPathSelectClick(Sender: TObject);
private
FI2XOptions : TI2XOptions;
oStrUtil : CStrUtil;
FUIEVents : boolean;
FShowOCRPlugins : boolean;
FShowImagePlugins : boolean;
procedure FillOptionsList();
procedure OptionGroupSelected( const SelectedGroup : string ); override;
procedure ShowApplicationPanel();
procedure ShowPluginsPanel( const OCRPlugins : boolean = true; const ImagePlugins : boolean = true);
procedure ShowTWAINPanel();
procedure HidePanels();
function getI2XOptions: TI2XOptions;
procedure setI2XOptions(const Value: TI2XOptions);
procedure SetPluginGridSize( const OCRPlugins : boolean; const ImagePlugins : boolean );
procedure TestUpdated(Sender: TObject);
public
property I2XOptions : TI2XOptions read getI2XOptions write setI2XOptions;
function LoadOptionsAndDisplay( Options : TOptionsController ) : boolean; override;
procedure SetCurrentPanel(const PanelDisplay: TI2XOptionsEnum);
end;
var
frmI2XOptions: TI2XOptionsUI;
implementation
uses uImage2XML;
{$R *.dfm}
{ TI2XOptionsUI }
procedure TI2XOptionsUI.btnJobRootPathSelectClick(Sender: TObject);
var
sFolder : string;
begin
inherited;
if FFileDir.BrowseForFolder( self.txtJobRootPath.Text, sFolder ) then
txtJobRootPath.Text := sFolder;
end;
procedure TI2XOptionsUI.chkGridSnapClick(Sender: TObject);
begin
if ( self.FUIEVents ) then begin
FI2XOptions.EnableGridSnap := chkGridSnap.Checked;
end;
end;
procedure TI2XOptionsUI.FillOptionsList;
begin
end;
procedure TI2XOptionsUI.FormCreate(Sender: TObject);
Begin
FI2XOptions := Options;
self.FOptionsController := FI2XOptions;
oStrUtil := CStrUtil.Create;
HidePanels;
FUIEVents := true;
inherited FormCreate( Sender, FOptionsController );
ShowApplicationPanel();
self.OnTreeNodeCheckBoxClickEvent := TreeNodeCheckBoxClickHandler;
End;
procedure TI2XOptionsUI.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil( oStrUtil );
end;
procedure TI2XOptionsUI.FormResize(Sender: TObject);
begin
inherited;
if ( self.FShowOCRPlugins or self.FShowImagePlugins ) then begin
self.SetPluginGridSize( self.FShowOCRPlugins, self.FShowImagePlugins );
end;
end;
function TI2XOptionsUI.getI2XOptions: TI2XOptions;
begin
Result := TI2XOptions( self.FOptionsController );
end;
procedure TI2XOptionsUI.HidePanels;
begin
self.pnlApplication.Visible := false;
self.pnlPlugins.Visible := false;
self.pnlTWAIN.Visible := false;
FShowOCRPlugins := false;
FShowImagePlugins := false;
end;
function TI2XOptionsUI.LoadOptionsAndDisplay(
Options: TOptionsController): boolean;
begin
self.FUIEVents := false;
inherited LoadOptionsAndDisplay( Options );
self.FUIEVents := true;
end;
procedure TI2XOptionsUI.lstTWAINDevicesClick(Sender: TObject);
begin
inherited;
I2XOptions.TWAINDeviceDefault :=
lstTWAINDevices.Items[ lstTWAINDevices.ItemIndex ];
end;
procedure TI2XOptionsUI.SetCurrentPanel(const PanelDisplay : TI2XOptionsEnum );
Begin
case PanelDisplay of
iAPPLICATION:
begin
ShowApplicationPanel();
end;
iPLUGINS :
begin
ShowPluginsPanel();
end;
iPLUGINSOCR :
begin
ShowPluginsPanel(true, false);
end;
iPLUGINSIMG :
begin
ShowPluginsPanel(false, true);
end;
iTWAIN :
begin
self.ShowTWAINPanel();
end;
end;
End;
procedure TI2XOptionsUI.OptionGroupSelected(const SelectedGroup: string);
Begin
inherited OptionGroupSelected( SelectedGroup );
SetCurrentPanel( TI2XOptionsEnum(GetEnumValue(TypeInfo(TI2XOptionsEnum),'i' + UpperCase(SelectedGroup))) );
End;
procedure TI2XOptionsUI.setI2XOptions(const Value: TI2XOptions);
Begin
self.FOptionsController := Value;
End;
procedure TI2XOptionsUI.ShowApplicationPanel;
begin
HidePanels;
with self.pnlApplication do begin
self.FUIEVents := false;
Visible := true;
self.txtGridSize.Text := IntToStr( FI2XOptions.GridSize );
chkGridSnap.Checked := I2XOptions.EnableGridSnap;
self.txtJobRootPath.Text := I2XOptions.JobRootPath;
self.FUIEVents := true;
Align := alClient;
end;
end;
procedure TI2XOptionsUI.ShowPluginsPanel( const OCRPlugins : boolean; const ImagePlugins : boolean );
var
bShowPluginType : boolean;
i, iRow, iCol, nWidth : integer;
oimg : TDLLImageProc;
oOcr : TDLLOCREngine;
arrKeyList : TKeyList;
ht : THashTable;
begin
HidePanels;
bShowPluginType := (OCRPlugins and ImagePlugins);
with self.pnlPlugins do begin
self.FUIEVents := false;
Visible := true;
self.grdPlugins.RowCount := 1;
iRow := 0;
iCol := 0;
FShowOCRPlugins := OCRPlugins;
FShowImagePlugins := ImagePlugins;
if ( (PluginManager.ImageDLLCount + PluginManager.OCREngineDLLCount) > 1) then begin
SetPluginGridSize( OCRPlugins, ImagePlugins );
if ( ImagePlugins ) then begin
for i := 0 to PluginManager.ImageDLLCount - 1 do begin
iCol := 0;
oimg := PluginManager.ImageDLL[i];
Inc( iRow );
self.grdPlugins.RowCount := iRow + 1;
if ( iRow = 1 ) then
self.grdPlugins.FixedRows := 1;
if ( bShowPluginType ) then begin
self.grdPlugins.Cells[iCol, iRow] := 'IMAGE';
Inc(iCol);
end;
self.grdPlugins.Cells[iCol, iRow] := oimg.ShortName;
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := oimg.Description;
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := oimg.Version;
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := oimg.DLLName;
Inc(iCol);
end;
end;
if ( OCRPlugins ) then begin
for i := 0 to PluginManager.OCREngineDLLCount - 1 do begin
iCol := 0;
oOcr := PluginManager.OCREngineDLL[i];
Inc( iRow );
self.grdPlugins.RowCount := iRow + 1;
if ( iRow = 1 ) then
self.grdPlugins.FixedRows := 1;
if ( bShowPluginType ) then begin
self.grdPlugins.Cells[iCol, iRow] := 'OCR';
Inc(iCol);
end;
self.grdPlugins.Cells[iCol, iRow] := oOcr.ShortName;
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := oOcr.Description;
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := oOcr.Version;
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := oOcr.DLLName;
Inc(iCol);
end;
end;
end;
self.FUIEVents := true;
Align := alClient;
end;
end;
procedure TI2XOptionsUI.ShowTWAINPanel;
var
i : integer;
begin
HidePanels;
with self.pnlTWAIN do begin
self.FUIEVents := false;
Visible := true;
self.lstTWAINDevices.Items.Clear;
self.lstTWAINDevices.Items.AddStrings( FI2XOptions.TWAINDevices );
for i := 0 to lstTWAINDevices.Count - 1 do begin
if ( lstTWAINDevices.Items[i] = FI2XOptions.TWAINDeviceDefault )then begin
lstTWAINDevices.ItemIndex := i;
end;
end;
self.FUIEVents := true;
Align := alClient;
end;
end;
procedure TI2XOptionsUI.TreeNodeCheckBoxClickHandler(Node: TTreeNode;
isChecked: boolean);
var
test : TDLLOCRTest;
dwpersist : TDWPersist;
begin
if ( Node.data <> nil ) then begin
dwpersist := TDWPersist(Node.data);
dwpersist.Enabled := isChecked;
//dbg( 'classname=' + dwpersist.ClassName );
//test := TDLLOCRTest(dwpersist);
//test := TDLLOCRTest(Node.data);
//test.Enabled := isChecked;
FI2XOptions.IsDirty := true;
FI2XOptions.OnChange( self );
end;
end;
procedure TI2XOptionsUI.SetPluginGridSize( const OCRPlugins : boolean; const ImagePlugins : boolean );
var
i, iRow, iCol, nWidth : integer;
bShowPluginType : boolean;
Begin
bShowPluginType := (OCRPlugins and ImagePlugins);
nWidth := pnlRight.Width - 12;
iRow := 0;
iCol := 0;
if ( bShowPluginType ) then begin
self.grdPlugins.ColCount := 5;
self.grdPlugins.Cells[iCol, iRow] := 'Plugin Type';
self.grdPlugins.ColWidths[iCol] := Round(nWidth * 0.05);
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := 'Short Name';
self.grdPlugins.ColWidths[iCol] := Round(nWidth * 0.05);
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := 'Description';
self.grdPlugins.ColWidths[iCol] := Round(nWidth * 0.35);
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := 'Version';
self.grdPlugins.ColWidths[iCol] := Round(nWidth * 0.10);
Inc(iCol);
self.grdPlugins.Cells[iCol, iRow] := 'File Name';
self.grdPlugins.ColWidths[iCol] := Round(nWidth * 0.45);
Inc(iCol);
end else begin
self.grdPlugins.ColCount := 4;
self.grdPlugins.ColWidths[0] := Round(nWidth * 0.10);
self.grdPlugins.ColWidths[1] := Round(nWidth * 0.30);
self.grdPlugins.ColWidths[2] := Round(nWidth * 0.20);
self.grdPlugins.ColWidths[3] := Round(nWidth * 0.40);
self.grdPlugins.Cells[0, iRow] := 'Short Name';
self.grdPlugins.Cells[1, iRow] := 'Description';
self.grdPlugins.Cells[2, iRow] := 'Version';
self.grdPlugins.Cells[3, iRow] := 'File Name';
end;
End;
procedure TI2XOptionsUI.txtGridSizeChange(Sender: TObject);
var
GridSize : Integer;
doChange : boolean;
Begin
if ( FUIEVents ) then begin
doChange := false;
GridSize := -1;
if ( oStrUtil.IsNumeric( txtGridSize.Text )) then begin
I2XOptions.GridSize := StrToInt( txtGridSize.Text );
doChange := (( I2XOptions.GridSize >= 1 ) and ( I2XOptions.GridSize <= 50 ));
end;
if ( doChange ) then begin
//reg.RegSet( REG_KEY, 'grid_size', txtGridSize.Text, HKEY_CURRENT_USER );
I2XOptions.GridSize := StrToInt( txtGridSize.Text );
end else begin
//txtGridSize.Text := reg.RegGet( REG_KEY, 'grid_size', '5', HKEY_CURRENT_USER );
end;
end;
End;
procedure TI2XOptionsUI.TestUpdated(Sender: TObject);
var
GridSize : Integer;
doChange : boolean;
Begin
if ( FUIEVents ) then begin
doChange := false;
GridSize := -1;
if ( oStrUtil.IsNumeric( txtGridSize.Text )) then begin
I2XOptions.GridSize := StrToInt( txtGridSize.Text );
doChange := (( I2XOptions.GridSize >= 1 ) and ( I2XOptions.GridSize <= 50 ));
end;
if ( doChange ) then begin
//reg.RegSet( REG_KEY, 'grid_size', txtGridSize.Text, HKEY_CURRENT_USER );
I2XOptions.GridSize := StrToInt( txtGridSize.Text );
end else begin
//txtGridSize.Text := reg.RegGet( REG_KEY, 'grid_size', '5', HKEY_CURRENT_USER );
end;
end;
End;
END.
|
unit Main_Window;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Menus, ExtCtrls,
StdCtrls, ComCtrls, ActnList, Buttons;
type
{ TMainWindow }
TMainWindow = class(TForm)
actionTerminalSettings: TAction;
actionHardwareInfo: TAction;
actionAbout: TAction;
actionRun: TAction;
actionSlowRun: TAction;
actionSingleStep: TAction;
actionReset: TAction;
actionStop: TAction;
actionHddDrive: TAction;
actionFloppyDrive: TAction;
actionMemorySettings: TAction;
actionCpuIoRegister: TAction;
actionCpuCoreRegister: TAction;
actionMemoryEditor: TAction;
actionClose: TAction;
actionLoadFileToRam: TAction;
actionlistMainWindow: TActionList;
comboboxRun: TComboBox;
comboboxSlowRun: TComboBox;
imagelistMainWindow: TImageList;
menuCpuCoreRegister: TMenuItem;
menuCpuIoRegister: TMenuItem;
menuFloppyImages: TMenuItem;
menuHddImage: TMenuItem;
menuHardwareInfo: TMenuItem;
menuCopyCpmFiles: TMenuItem;
menuCreateCpmDiscImages: TMenuItem;
panelMiscellaneous: TPanel;
panelSlowRun: TPanel;
panelRun: TPanel;
panelCpuControl: TPanel;
panelSystemData: TPanel;
panelCpuDataView: TPanel;
panelHdd: TPanel;
panelFdd0: TPanel;
panelFdd1: TPanel;
menuTerminalSettings: TMenuItem;
menuTools: TMenuItem;
menuReset: TMenuItem;
menuRun: TMenuItem;
menuSlowRun: TMenuItem;
menuSingleStep: TMenuItem;
N1: TMenuItem;
menuStop: TMenuItem;
menuMemorySettings: TMenuItem;
menuSystem: TMenuItem;
menuControl: TMenuItem;
menuMemoryEditor: TMenuItem;
menuView: TMenuItem;
menuMainWindow: TMainMenu;
menuFile: TMenuItem;
menuLoadFileToRam: TMenuItem;
menuSeparator1: TMenuItem;
menuClose: TMenuItem;
menuHelp: TMenuItem;
menuAbout: TMenuItem;
FileOpenDialog: TOpenDialog;
cpuRun: TTimer;
panelSystemTerminal: TPanel;
statusbarMainWindow: TPanel;
panelButtons: TPanel;
buttonCpuCoreRegister: TSpeedButton;
buttonCpuIoRegister: TSpeedButton;
buttonFloppyImages: TSpeedButton;
buttonHddImage: TSpeedButton;
buttonMemoryEditor: TSpeedButton;
buttonMemorySettings: TSpeedButton;
buttonReset: TSpeedButton;
buttonRun: TSpeedButton;
buttonSingleStep: TSpeedButton;
buttonSlowRun: TSpeedButton;
buttonStop: TSpeedButton;
buttonTerminal: TSpeedButton;
procedure actionAboutExecute(Sender: TObject);
procedure actionCloseExecute(Sender: TObject);
procedure actionCpuCoreRegisterExecute(Sender: TObject);
procedure actionCpuIoRegisterExecute(Sender: TObject);
procedure actionFloppyDriveExecute(Sender: TObject);
procedure actionHardwareInfoExecute(Sender: TObject);
procedure actionHddDriveExecute(Sender: TObject);
procedure actionLoadFileToRamExecute(Sender: TObject);
procedure actionMemoryEditorExecute(Sender: TObject);
procedure actionMemorySettingsExecute(Sender: TObject);
procedure actionResetExecute(Sender: TObject);
procedure actionRunExecute(Sender: TObject);
procedure actionSingleStepExecute(Sender: TObject);
procedure actionSlowRunExecute(Sender: TObject);
procedure actionStopExecute(Sender: TObject);
procedure actionTerminalSettingsExecute(Sender: TObject);
procedure comboboxRunChange(Sender: TObject);
procedure comboboxSlowRunChange(Sender: TObject);
procedure cpuRunTimer(Sender: TObject);
procedure cpuSlowRunTimer(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure panelFdd0Paint(Sender: TObject);
procedure panelFdd1Paint(Sender: TObject);
procedure panelHddPaint(Sender: TObject);
private
bootRomEnabled: boolean;
runSpeedValue: integer;
slowRunSpeedValue: integer;
{$ifndef Windows}
isKeyAltGr: boolean;
{$endif}
public
end;
var
MainWindow: TMainWindow;
implementation
{$R *.lfm}
uses UscaleDPI, System_Settings, Cpu_Register, Cpu_Io_Register, Memory_Editor, Memory_Settings,
System_Memory, System_InOut, Z180_CPU, System_Terminal, System_Fdc, Fdd_Settings, Terminal_Settings,
About_Window, System_Hdc, Hdd_Settings, Hardware_Info, System_Rtc, System_Prt, Types;
{ TformMainWindow }
const
{$ifndef Windows}
RUNSPEED_4MHZ = 2500;
RUNSPEED_8MHZ = 4500;
RUNSPEED_12MHZ = 6500;
RUNSPEED_16MHZ = 8500;
{$else}
RUNSPEED_4MHZ = 6875;
RUNSPEED_8MHZ = 12375;
RUNSPEED_12MHZ = 17875;
RUNSPEED_16MHZ = 23375;
{$endif}
SLOWSPEED_1OPS = 1000;
SLOWSPEED_2OPS = 500;
SLOWSPEED_5OPS = 200;
SLOWSPEED_10OPS = 100;
// --------------------------------------------------------------------------------
procedure TMainWindow.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
if (cpuRun.Enabled = True) then begin
cpuRun.Enabled := False;
cpuRun.OnTimer := nil;
end;
FreeAndNil(CpuRegister);
FreeAndNil(MemoryEditor);
FreeAndNil(CpuIoRegister);
FreeAndNil(HardwareInfo);
FreeAndNil(Z180Cpu);
FreeAndNil(SystemInOut);
FreeAndNil(SystemFdc);
FreeAndNil(SystemHdc);
FreeAndNil(SystemRtc);
FreeAndNil(SystemPrt);
FreeAndNil(SystemMemory);
FreeAndNil(SystemTerminal);
SystemSettings.saveFormState(TForm(self));
CloseAction := caFree;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
{$ifndef Windows}
var
termShift: TShiftState;
{$endif}
begin
{$ifndef Windows}
if ((Key = 235) and (Shift = [SSALT])) then begin
isKeyAltGr := True;
end;
if (isKeyAltGr) then begin
termShift := [ssAlt..ssCtrl];
end
else begin
termShift := Shift;
end;
SystemTerminal.getKeyBoardInput(Key, termShift);
{$else}
SystemTerminal.getKeyBoardInput(Key, Shift);
{$endif}
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
begin
{$ifndef Windows}
if ((Key = 235) and (Shift = [])) then begin
isKeyAltGr := False;
end;
{$endif}
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.FormShow(Sender: TObject);
begin
SystemSettings.restoreFormState(TForm(self));
ScaleDPI(self, 96);
SystemMemory := TSystemMemory.Create;
bootRomEnabled := SystemMemory.isRomFileValid;
SystemFdc := TSystemFdc.Create(panelFdd0, panelFdd1);
SystemHdc := TSystemHdc.Create(panelHdd);
SystemTerminal := TSystemTerminal.Create(panelSystemTerminal, False);
SystemRtc := TSystemRtc.Create;
SystemPrt := TSystemPrt.Create;
SystemInOut := TSystemInOut.Create;
Z180Cpu := TZ180Cpu.Create;
panelButtons.Constraints.MaxHeight := ((statusbarMainWindow.Height div 4) * 6);
panelButtons.Constraints.MinHeight := panelButtons.Constraints.MaxHeight;
{$ifdef Windows}
comboboxRun.BorderSpacing.Top := 3;
comboboxSlowRun.BorderSpacing.Top := 3;
{$endif}
comboboxRun.ItemIndex := SystemSettings.ReadInteger('Emulation', 'RunSpeed', 0);
comboboxRunChange(nil);
comboboxSlowRun.ItemIndex := SystemSettings.ReadInteger('Emulation', 'SlowRunSpeed', 2);
comboboxSlowRunChange(nil);
actionResetExecute(nil);
self.Activate;
panelSystemTerminal.SetFocus;
{$ifndef Windows}
isKeyAltGr := False;
{$endif}
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.panelFdd0Paint(Sender: TObject);
begin
if (panelFdd0.Enabled) then begin
imagelistMainWindow.Draw(panelFdd0.Canvas, 0, 1, 20);
end
else begin
imagelistMainWindow.Draw(panelFdd0.Canvas, 0, 1, 22);
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.panelFdd1Paint(Sender: TObject);
begin
if (panelFdd1.Enabled) then begin
imagelistMainWindow.Draw(panelFdd1.Canvas, 0, 1, 21);
end
else begin
imagelistMainWindow.Draw(panelFdd1.Canvas, 0, 1, 23);
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.panelHddPaint(Sender: TObject);
begin
if (panelHdd.Enabled) then begin
imagelistMainWindow.Draw(panelHdd.Canvas, 0, 1, 5);
end
else begin
imagelistMainWindow.Draw(panelHdd.Canvas, 0, 1, 24);
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.cpuRunTimer(Sender: TObject);
begin
Z180Cpu.exec(runSpeedValue);
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.cpuSlowRunTimer(Sender: TObject);
begin
Z180Cpu.exec(1);
if Assigned(MemoryEditor) then begin
MemoryEditor.showMemoryData;
end;
if Assigned(CpuRegister) then begin
CpuRegister.showRegisterData;
end;
if Assigned(CpuIoRegister) then begin
CpuIoRegister.showRegisterData;
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.FormActivate(Sender: TObject);
var
size: TSize;
begin
size := SystemTerminal.getDisplaySize;
Constraints.MinWidth := size.Width;
Constraints.MinHeight := size.Height + panelButtons.Height + statusbarMainWindow.Height + (Height - ClientHeight);
Constraints.MaxWidth := Constraints.MinWidth;
Constraints.MaxHeight := Constraints.MinHeight;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionLoadFileToRamExecute(Sender: TObject);
begin
FileOpenDialog.Title := 'Lade Binär-Datei ins RAM';
FileOpenDialog.Filter := 'Binär Dateien (*.bin)|*.bin;*.BIN|Alle Dateien (*.*)|*.*|';
FileOpenDialog.InitialDir := GetUserDir;
if (FileOpenDialog.Execute) then begin
SystemMemory.LoadRamFile(FileOpenDialog.FileName);
bootRomEnabled := False;
if Assigned(MemoryEditor) then begin
MemoryEditor.showMemoryData;
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionMemoryEditorExecute(Sender: TObject);
begin
if not Assigned(MemoryEditor) then begin
Application.CreateForm(TMemoryEditor, MemoryEditor);
end;
if ((MemoryEditor.IsVisible) and (MemoryEditor.WindowState <> wsMinimized)) then begin
MemoryEditor.Close;
end
else begin
MemoryEditor.Show;
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionMemorySettingsExecute(Sender: TObject);
var
dialog: TMemorySettings;
begin
Application.CreateForm(TMemorySettings, dialog);
dialog.ShowModal;
bootRomEnabled := SystemMemory.isRomFileValid;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionResetExecute(Sender: TObject);
begin
Z180Cpu.reset;
SystemTerminal.terminalReset;
SystemMemory.EnableBootRom(bootRomEnabled);
SystemHdc.doReset;
if (not cpuRun.Enabled) then begin
actionHddDrive.Enabled := True;
end;
if Assigned(MemoryEditor) then begin
MemoryEditor.showMemoryData;
end;
if Assigned(CpuRegister) then begin
CpuRegister.showRegisterData;
end;
if Assigned(CpuIoRegister) then begin
CpuIoRegister.showRegisterData;
end;
actionMemorySettings.Enabled := True;
actionFloppyDrive.Enabled := True;
actionLoadFileToRam.Enabled := True;
comboboxRun.Enabled := True;
comboboxSlowRun.Enabled := True;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionRunExecute(Sender: TObject);
begin
if (cpuRun.Enabled = True) then begin
cpuRun.Enabled := False;
cpuRun.OnTimer := nil;
end;
cpuRun.OnTimer := @cpuRunTimer;
cpuRun.Interval := 2;
cpuRun.Enabled := True;
actionMemorySettings.Enabled := False;
actionHddDrive.Enabled := False;
actionLoadFileToRam.Enabled := False;
comboboxRun.Enabled := True;
comboboxSlowRun.Enabled := False;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionSingleStepExecute(Sender: TObject);
begin
if (cpuRun.Enabled = True) then begin
cpuRun.Enabled := False;
cpuRun.OnTimer := nil;
end;
Z180Cpu.exec(1);
if Assigned(MemoryEditor) then begin
MemoryEditor.showMemoryData;
end;
if Assigned(CpuRegister) then begin
CpuRegister.showRegisterData;
end;
if Assigned(CpuIoRegister) then begin
CpuIoRegister.showRegisterData;
end;
actionMemorySettings.Enabled := True;
actionHddDrive.Enabled := True;
actionLoadFileToRam.Enabled := True;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionSlowRunExecute(Sender: TObject);
begin
if (cpuRun.Enabled = True) then begin
cpuRun.Enabled := False;
cpuRun.OnTimer := nil;
end;
cpuRun.OnTimer := @cpuSlowRunTimer;
cpuRun.Interval := slowRunSpeedValue;
cpuRun.Enabled := True;
actionMemorySettings.Enabled := False;
actionHddDrive.Enabled := False;
actionLoadFileToRam.Enabled := False;
comboboxRun.Enabled := False;
comboboxSlowRun.Enabled := True;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionStopExecute(Sender: TObject);
begin
if (cpuRun.Enabled = True) then begin
cpuRun.Enabled := False;
cpuRun.OnTimer := nil;
end;
if Assigned(MemoryEditor) then begin
MemoryEditor.showMemoryData;
end;
if Assigned(CpuRegister) then begin
CpuRegister.showRegisterData;
end;
if Assigned(CpuIoRegister) then begin
CpuIoRegister.showRegisterData;
end;
Z180Cpu.clrSlpHalt;
actionMemorySettings.Enabled := True;
actionFloppyDrive.Enabled := True;
actionLoadFileToRam.Enabled := True;
comboboxRun.Enabled := True;
comboboxSlowRun.Enabled := True;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionTerminalSettingsExecute(Sender: TObject);
var
dialog: TTerminalSettings;
begin
Application.CreateForm(TTerminalSettings, dialog);
dialog.ShowModal;
self.Activate;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.comboboxRunChange(Sender: TObject);
begin
case (comboboxRun.ItemIndex) of
0: runSpeedValue := RUNSPEED_4MHZ;
1: runSpeedValue := RUNSPEED_8MHZ;
2: runSpeedValue := RUNSPEED_12MHZ;
3: runSpeedValue := RUNSPEED_16MHZ;
else runSpeedValue := RUNSPEED_4MHZ;
end;
SystemSettings.WriteInteger('Emulation', 'RunSpeed', comboboxRun.ItemIndex);
panelSystemTerminal.SetFocus;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.comboboxSlowRunChange(Sender: TObject);
begin
case (comboboxSlowRun.ItemIndex) of
0: slowRunSpeedValue := SLOWSPEED_1OPS;
1: slowRunSpeedValue := SLOWSPEED_2OPS;
2: slowRunSpeedValue := SLOWSPEED_5OPS;
3: slowRunSpeedValue := SLOWSPEED_10OPS;
else slowRunSpeedValue := SLOWSPEED_5OPS;
end;
SystemSettings.WriteInteger('Emulation', 'SlowRunSpeed', comboboxSlowRun.ItemIndex);
cpuRun.Interval := slowRunSpeedValue;
panelSystemTerminal.SetFocus;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionCloseExecute(Sender: TObject);
begin
Close;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionAboutExecute(Sender: TObject);
var
dialog: TAboutWindow;
begin
Application.CreateForm(TAboutWindow, dialog);
dialog.ShowModal;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionCpuCoreRegisterExecute(Sender: TObject);
begin
if not Assigned(CpuRegister) then begin
Application.CreateForm(TCpuRegister, CpuRegister);
end;
if ((CpuRegister.IsVisible) and (CpuRegister.WindowState <> wsMinimized)) then begin
CpuRegister.Close;
end
else begin
CpuRegister.Show;
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionCpuIoRegisterExecute(Sender: TObject);
begin
if not Assigned(CpuIoRegister) then begin
Application.CreateForm(TCpuIoRegister, CpuIoRegister);
end;
if ((CpuIoRegister.IsVisible) and (CpuIoRegister.WindowState <> wsMinimized)) then begin
CpuIoRegister.Close;
end
else begin
CpuIoRegister.Show;
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionFloppyDriveExecute(Sender: TObject);
var
dialog: TFddSettings;
begin
Application.CreateForm(TFddSettings, dialog);
dialog.ShowModal;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionHardwareInfoExecute(Sender: TObject);
begin
if not Assigned(HardwareInfo) then begin
Application.CreateForm(THardwareInfo, HardwareInfo);
end;
if ((HardwareInfo.IsVisible) and (HardwareInfo.WindowState <> wsMinimized)) then begin
HardwareInfo.Close;
end
else begin
HardwareInfo.Show;
end;
end;
// --------------------------------------------------------------------------------
procedure TMainWindow.actionHddDriveExecute(Sender: TObject);
var
dialog: THddSettings;
begin
Application.CreateForm(THddSettings, dialog);
dialog.ShowModal;
end;
// --------------------------------------------------------------------------------
end.
|
unit Filters;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, VirtualShellUtilities,
VirtualWideStrings, Forms;
const
ProfileData = 'Profile.dat';
STR_WARNING = WideString('Warning');
STR_CONFIRM = WideString('Confirmation');
STR_BLANKPROFILENAME = WideString('A blank name for a Profile is not allowed');
STR_PROFILENAME1 = WideString('The Profile "');
STR_PROFILENAME2 = WideString('" is already used. Overwrite the current Profile?');
STR_PROFILENOTFOUND = WideString('" can not be found');
STR_PROFILESAVESUCCESS = WideString('The Profile was successfully saved');
STR_PROFILEDELETEQUERY1 = WideString('Are you sure you want to delete the Profile: ');
STR_PROFILEDELETEQUERY2 = WideString('?');
type
TFilter = class(TPersistent)
private
FEnabled: Boolean;
public
function Allowed(NS: TNamespace): Boolean;
function ApplyFilter(NS: TNamespace): Boolean; virtual; abstract;
procedure SaveToStream(S: TStream); virtual;
procedure LoadFromStream(S: TStream); virtual;
property Enabled: Boolean read FEnabled write FEnabled;
end;
TFilterArray = array of TFilter;
TNameFilter = class(TFilter)
private
FExtEnabled: Boolean;
FMatchEnabled: Boolean;
FMatch: WideString;
FExtension: WideString;
FExtList: TWideStringList;
procedure SetExtension(const Value: WideString);
protected
property ExtList: TWideStringList read FExtList write FExtList;
public
constructor Create;
destructor Destroy; override;
function ApplyFilter(NS: TNamespace): Boolean; override;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
property ExtEnabled: Boolean read FExtEnabled write FExtEnabled;
property MatchEnabled: Boolean read FMatchEnabled write FMatchEnabled;
property Extension: WideString read FExtension write SetExtension;
property Match: WideString read FMatch write FMatch;
end;
TTimeFilter = class(TFilter)
private
FBeforeTime: TFileTime;
FAfterTime: TFileTime;
FBeforeTimeEnabled: Boolean;
FAfterTimeEnabled: Boolean;
public
constructor Create;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
procedure Assign(Source: TPersistent); override;
property AfterTime: TFileTime read FAfterTime write FAfterTime;
property AfterTimeEnabled: Boolean read FAfterTimeEnabled write FAfterTimeEnabled;
property BeforeTime: TFileTime read FBeforeTime write FBeforeTime;
property BeforeTimeEnabled: Boolean read FBeforeTimeEnabled write FBeforeTimeEnabled;
end;
TCreationTimeFilter = class(TTimeFilter)
public
function ApplyFilter(NS: TNamespace): Boolean; override;
end;
TAccessTimeFilter = class(TTimeFilter)
public
function ApplyFilter(NS: TNamespace): Boolean; override;
end;
TModifyTimeFilter = class(TTimeFilter)
public
function ApplyFilter(NS: TNamespace): Boolean; override;
end;
TTimeFilters = class(TFilter)
private
FCreateFilter: TCreationTimeFilter;
FAccessFilter: TAccessTimeFilter;
FModifyFilter: TModifyTimeFilter;
FLockEnabled: Boolean;
procedure SetLockEnabled(const Value: Boolean);
public
constructor Create;
destructor Destroy; override;
function ApplyFilter(NS: TNamespace): Boolean; override;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
property AccessFilter: TAccessTimeFilter read FAccessFilter write FAccessFilter;
property CreateFilter: TCreationTimeFilter read FCreateFilter write FCreateFilter;
property LockEnabled: Boolean read FLockEnabled write SetLockEnabled;
property ModifyFilter: TModifyTimeFilter read FModifyFilter write FModifyFilter;
end;
TAttribFilter = class(TFilter)
private
FArchiveEnabled: Boolean;
FReadOnlyEnabled: Boolean;
FHiddenEnabled: Boolean;
FSystemEnabled: Boolean;
public
function ApplyFilter(NS: TNamespace): Boolean; override;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
property ArchiveEnabled: Boolean read FArchiveEnabled write FArchiveEnabled;
property ReadOnlyEnabled: Boolean read FReadOnlyEnabled write FReadOnlyEnabled;
property SystemEnabled: Boolean read FSystemEnabled write FSystemEnabled;
property HiddenEnabled: Boolean read FHiddenEnabled write FHiddenEnabled;
end;
TTypeFilter = class(TFilter)
private
FMatchEnabled: Boolean;
FFolderEnabled: Boolean;
FFileEnabled: Boolean;
FMatch: WideString;
public
function ApplyFilter(NS: TNamespace): Boolean; override;
procedure SaveToStream(S: TStream); override;
procedure LoadFromStream(S: TStream); override;
property FolderEnabled: Boolean read FFolderEnabled write FFolderEnabled;
property FileEnabled: Boolean read FFileEnabled write FFileEnabled;
property MatchEnabled: Boolean read FMatchEnabled write FMatchEnabled;
property Match: WideString read FMatch write FMatch;
end;
PProfileRec = ^TProfileRec;
TProfileRec = packed record
Name: WideString;
Data: TMemoryStream;
end;
TAddProfileResult = (
aprNew,
aprOverwrite,
aprError
);
TProfile = class(TPersistent)
private
FProfileList: TList;
FNameList: TStringList;
function GetNameList: TStringList;
protected
procedure ClearProfileList;
function DuplicateProfile(Name: WideString; var Index: Integer): Boolean;
property ProfileList: TList read FProfileList write FProfileList;
public
constructor Create;
destructor Destroy; override;
function AddProfile(Name: WideString; FilterList: TFilterArray): TAddProfileResult;
procedure DeletePofile(Name: WideString);
function FindProfile(Name: WideString): Integer;
procedure LoadProfile(Name: WideString; FilterList: TFilterArray);
procedure SaveToStream(S: TStream);
procedure LoadFromStream(S: TStream);
procedure SaveToFile(FileName: WideString);
procedure LoadFromFile(FileName: WideString);
property NameList: TStringList read GetNameList write FNameList;
end;
function DateTimeToFileTime(DateTime: TDateTime): TFileTime;
function FileTimeToDateTime(FileTime: TFileTime): TDateTime;
function ValidFileTime(DateTime: TFileTime): Boolean;
implementation
function DateTimeToFileTime(DateTime: TDateTime): TFileTime;
var
SysTime: TSystemTime;
begin
DateTimeToSystemTime(DateTime, SysTime);
SystemTimeToFileTime(SysTime, Result);
end;
function FileTimeToDateTime(FileTime: TFileTime): TDateTime;
var
SysTime: TSystemTime;
begin
FileTimeToSystemTime(FileTime, SysTime);
Result := SystemTimeToDateTime(SysTime);
end;
function ValidFileTime(DateTime: TFileTime): Boolean;
begin
Result := (DateTime.dwLowDateTime <> 0) and (DateTime.dwHighDateTime <> 0)
end;
{ TNameFilter }
function TNameFilter.ApplyFilter(NS: TNamespace): Boolean;
var
i: Integer;
Allow: Boolean;
begin
Allow := True;
if Enabled then
begin
if ExtEnabled then
begin
i := 0;
Allow := False;
while not Allow and (i < ExtList.Count) do
begin
Allow := StrCompW(PWideChar(ExtList[i]), PWideChar(ExtractFileExtW(NS.NameForParsingInFolder))) = 0;
Inc(i)
end
end;
// Now check for the string matching, note if first compare excluded it then
// don't waste our time.
if MatchEnabled and Allow then
Allow := Assigned(StrPosW(PWideChar(NS.NameForParsingInFolder), PWideChar(Match)));
end;
Result := Allow;
end;
constructor TNameFilter.Create;
begin
ExtList := TWideStringList.Create;
end;
destructor TNameFilter.Destroy;
begin
ExtList.Free;
inherited;
end;
procedure TNameFilter.LoadFromStream(S: TStream);
begin
inherited;
S.Read(FExtEnabled, SizeOf(FExtEnabled));
S.Read(FMatchEnabled, SizeOf(FMatchEnabled));
LoadWideString(S, FExtension);
LoadWideString(S, FMatch);
end;
procedure TNameFilter.SaveToStream(S: TStream);
begin
inherited;
S.Write(FExtEnabled, SizeOf(FExtEnabled));
S.Write(FMatchEnabled, SizeOf(FMatchEnabled));
SaveWideString(S, FExtension);
SaveWideString(S, FMatch);
end;
procedure TNameFilter.SetExtension(const Value: WideString);
var
Head, Tail: PWideChar;
Temp: WideString;
begin
if StrCompW(PWideChar(Value), PWideChar(FExtension)) <> 0 then
begin
ExtList.Clear;
FExtension := Value;
Temp := Value;
Head := PWideChar(Temp);
while Assigned(Head) do
begin
Tail := StrScanW(Head, WideChar('|'));
if Assigned(Tail) then
Tail^ := WideNull;
ExtList.Add(ExtractFileExtW(Head));
Head := Tail;
if Assigned(Head) then
Inc(Head);
end
end
end;
{ TTimeFilters }
function TTimeFilters.ApplyFilter(NS: TNamespace): Boolean;
var
Allow: Boolean;
begin
Allow := True;
if Enabled then
begin
Allow := CreateFilter.ApplyFilter(NS);
if Allow then
Allow := AccessFilter.ApplyFilter(NS);
if Allow then
Allow := ModifyFilter.ApplyFilter(NS);
end;
Result := Allow
end;
constructor TTimeFilters.Create;
begin
CreateFilter := TCreationTimeFilter.Create;
AccessFilter := TAccessTimeFilter.Create;
ModifyFilter := TModifyTimeFilter.Create;
end;
destructor TTimeFilters.Destroy;
begin
CreateFilter.Free;
AccessFilter.Free;
ModifyFilter.Free;
inherited;
end;
procedure TTimeFilters.LoadFromStream(S: TStream);
begin
inherited;
AccessFilter.LoadFromStream(S);
CreateFilter.LoadFromStream(S);
ModifyFilter.LoadFromStream(S);
S.Read(FLockEnabled, SizeOf(FLockEnabled))
end;
procedure TTimeFilters.SaveToStream(S: TStream);
begin
inherited;
AccessFilter.SaveToStream(S);
CreateFilter.SaveToStream(S);
ModifyFilter.SaveToStream(S);
S.Write(FLockEnabled, SizeOf(FLockEnabled))
end;
procedure TTimeFilters.SetLockEnabled(const Value: Boolean);
begin
FLockEnabled := Value;
end;
{ TFilter }
function TFilter.Allowed(NS: TNamespace): Boolean;
begin
Result := True;
end;
procedure TFilter.LoadFromStream(S: TStream);
begin
S.Read(FEnabled, SizeOf(FEnabled))
end;
procedure TFilter.SaveToStream(S: TStream);
begin
S.Write(FEnabled, SizeOf(FEnabled))
end;
{ TTimeFilter }
procedure TTimeFilter.Assign(Source: TPersistent);
var
F: TTimeFilter;
begin
if Source is TTimeFilter then
begin
F := TTimeFilter(Source);
AfterTime := F.AfterTime;
AfterTimeEnabled := F.AfterTimeEnabled;
BeforeTime := F.BeforeTime;
BeforeTimeEnabled := F.BeforeTimeEnabled;
Enabled := F.Enabled
end;
end;
constructor TTimeFilter.Create;
begin
FBeforeTime := DateTimeToFileTime(Date);
FAfterTime := DateTimeToFileTime(Date);
end;
procedure TTimeFilter.LoadFromStream(S: TStream);
begin
inherited;
S.Read(FBeforeTime, SizeOf(FBeforeTime));
S.Read(FAfterTime, SizeOf(FAfterTime));
S.Read(FBeforeTimeEnabled, SizeOf(FBeforeTimeEnabled));
S.Read(FAfterTimeEnabled, SizeOf(FAfterTimeEnabled));
end;
procedure TTimeFilter.SaveToStream(S: TStream);
begin
inherited;
S.Write(FBeforeTime, SizeOf(FBeforeTime));
S.Write(FAfterTime, SizeOf(FAfterTime));
S.Write(FBeforeTimeEnabled, SizeOf(FBeforeTimeEnabled));
S.Write(FAfterTimeEnabled, SizeOf(FAfterTimeEnabled));
end;
{ TAttribFilter }
function TAttribFilter.ApplyFilter(NS: TNamespace): Boolean;
begin
if Enabled then
begin
Result := (ArchiveEnabled and NS.Archive) or
(ReadOnlyEnabled and NS.ReadOnlyFile) or
(HiddenEnabled and NS.Hidden) or
(SystemEnabled and NS.SystemFile)
end else
Result := True
end;
procedure TAttribFilter.LoadFromStream(S: TStream);
begin
inherited;
S.Read(FArchiveEnabled, SizeOf(FArchiveEnabled));
S.Read(FReadOnlyEnabled, SizeOf(FReadOnlyEnabled));
S.Read(FHiddenEnabled, SizeOf(FHiddenEnabled));
S.Read(FSystemEnabled, SizeOf(FSystemEnabled));
end;
procedure TAttribFilter.SaveToStream(S: TStream);
begin
inherited;
S.Write(FArchiveEnabled, SizeOf(FArchiveEnabled));
S.Write(FReadOnlyEnabled, SizeOf(FReadOnlyEnabled));
S.Write(FHiddenEnabled, SizeOf(FHiddenEnabled));
S.Write(FSystemEnabled, SizeOf(FSystemEnabled));
end;
{ TTypeFilter }
function TTypeFilter.ApplyFilter(NS: TNamespace): Boolean;
var
Allow: Boolean;
begin
Allow := True;
if Enabled then
begin
Allow := (FolderEnabled and NS.Folder) or
(FileEnabled and not NS.Folder);
if Allow and MatchEnabled then
Allow := Assigned(StrPosW(PWideChar(NS.FileType), PWideChar(Match)))
end;
Result := Allow
end;
procedure TTypeFilter.LoadFromStream(S: TStream);
begin
inherited;
S.Read(FMatchEnabled, SizeOf(FMatchEnabled));
S.Read(FFolderEnabled, SizeOf(FFolderEnabled));
S.Read(FFileEnabled, SizeOf(FFileEnabled));
LoadWideString(S, FMatch);
end;
procedure TTypeFilter.SaveToStream(S: TStream);
begin
inherited;
S.Write(FMatchEnabled, SizeOf(FMatchEnabled));
S.Write(FFolderEnabled, SizeOf(FFolderEnabled));
S.Write(FFileEnabled, SizeOf(FFileEnabled));
SaveWideString(S, FMatch);
end;
{ TProfile }
function TProfile.AddProfile(Name: WideString; FilterList: TFilterArray): TAddProfileResult;
var
Profile: PProfileRec;
i, DupIndex: Integer;
begin
Result := aprError;
if Name <> '' then
begin
if not DuplicateProfile(Name, DupIndex) then
begin
New(Profile);
Profile.Name := Name;
Profile.Data := TMemoryStream.Create;
for i := 0 to Length(FilterList) - 1 do
FilterList[i].SaveToStream(Profile.Data);
ProfileList.Add(Profile);
Result := aprNew
end else
begin
// This is suppose to be available in Win9x too
if MessageBoxW(Application.Handle, PWideChar(STR_PROFILENAME1 + Name + STR_PROFILENAME2),
STR_WARNING, MB_YESNO or MB_ICONHAND) = IDYES then
begin
Profile := ProfileList[DupIndex];
Profile.Data.Seek(0, soFromBeginning);
for i := 0 to Length(FilterList) - 1 do
FilterList[i].SaveToStream(Profile.Data);
Result := aprOverwrite
end;
end;
end else
// This is suppose to be available in Win9x too
if MessageBoxW(Application.Handle, PWideChar(STR_BLANKPROFILENAME),
STR_WARNING, MB_OK or MB_ICONWARNING) = IDYES then
end;
procedure TProfile.ClearProfileList;
var
i: Integer;
begin
for i := 0 to ProfileList.Count - 1 do
begin
PProfileRec(ProfileList[i]).Data.Free;
Dispose(PProfileRec(ProfileList[i]))
end;
end;
constructor TProfile.Create;
begin
ProfileList := TList.Create;
NameList := TStringList.Create
end;
procedure TProfile.DeletePofile(Name: WideString);
var
i: Integer;
Profile: PProfileRec;
begin
i := FindProfile(Name);
if i > -1 then
begin
Profile := PProfileRec(ProfileList[i]);
ProfileList.Delete(i);
Profile.Data.Free;
Dispose(Profile)
end;
end;
destructor TProfile.Destroy;
begin
ClearProfileList;
ProfileList.Free;
NameList.Free;
inherited;
end;
function TProfile.DuplicateProfile(Name: WideString; var Index: Integer): Boolean;
begin
Index := FindProfile(Name);
Result := Index > -1
end;
function TProfile.FindProfile(Name: WideString): Integer;
var
i: Integer;
begin
Result := -1;
i := 0;
while (Result = -1) and (i < ProfileList.Count) do
begin
if StrICompW(PWideChar(PProfileRec(ProfileList[i]).Name), PWideChar(Name)) = 0 then
Result := i;
Inc(i)
end
end;
function TProfile.GetNameList: TStringList;
var
i: Integer;
begin
FNameList.Clear;
for i := 0 to ProfileList.Count - 1 do
FNameList.Add( PProfileRec(ProfileList[i]).Name);
Result := FNameList;
end;
procedure TProfile.LoadFromFile(FileName: WideString);
var
S: TWideFileStream;
begin
S := TWideFileStream.Create(FileName, fmOpenRead or fmShareExclusive);
try
LoadFromStream(S)
finally
S.Free
end
end;
procedure TProfile.LoadFromStream(S: TStream);
var
i: Integer;
Profile: PProfileRec;
Count: Integer;
begin
ClearProfileList;
S.Read(Count, SizeOf(Count));
for i := 0 to Count - 1 do
begin
New(Profile);
LoadWideString(S, Profile.Name);
Profile.Data := TMemoryStream.Create;
// Memory Stream thinks the whole stream is his!!!! Do it by hand
S.Read(Count, SizeOf(Count));
Profile.Data.Size := Count;
S.Read(Profile.Data.Memory^, Count);
ProfileList.Add(Profile)
end
end;
procedure TProfile.LoadProfile(Name: WideString; FilterList: TFilterArray);
var
i: Integer;
Profile: PProfileRec;
begin
i := FindProfile(Name);
if i > -1 then
begin
Profile := ProfileList[i];
Profile.Data.Position := 0;
for i := 0 to Length(FilterList) - 1 do
FilterList[i].LoadFromStream(Profile.Data);
end else
MessageBoxW(Application.Handle, PWideChar(STR_PROFILENAME1 + Name + STR_PROFILENOTFOUND),
STR_WARNING, MB_YESNOCANCEL or MB_ICONWARNING)
end;
procedure TProfile.SaveToFile(FileName: WideString);
var
S: TWideFileStream;
begin
S := TWideFileStream.Create(FileName, fmCreate or fmShareExclusive);
try
SaveToStream(S)
finally
S.Free
end
end;
procedure TProfile.SaveToStream(S: TStream);
var
i: Integer;
Profile: PProfileRec;
Count: Integer;
begin
Count := ProfileList.Count;
S.Write(Count, SizeOf(Count));
for i := 0 to Count - 1 do
begin
Profile := PProfileRec(ProfileList[i]);
SaveWideString(S, Profile.Name);
// Memory Stream thinks the whole stream is his!!!! Do it by hand
Count := Profile.Data.Size;
S.Write(Count, SizeOf(Count));
S.Write(Profile.Data.Memory^, Count);
end
end;
{ TCreationTimeFilter }
function TCreationTimeFilter.ApplyFilter(NS: TNamespace): Boolean;
var
Allow: Boolean;
begin
Allow := True;
if AfterTimeEnabled then
begin
if ValidFileTime(NS.CreationTimeRaw) and ValidFileTime(AfterTime) then
Allow := CompareFileTime(NS.CreationTimeRaw, AfterTime) >= 0 ;
end;
// Don't waste time if the previous and disallowed the item
if BeforeTimeEnabled and Allow then
if ValidFileTime(NS.CreationTimeRaw) and ValidFileTime(BeforeTime) then
Allow := CompareFileTime(NS.CreationTimeRaw, BeforeTime) <= 0;
Result := Allow;
end;
{ TAccessTimeFilter }
function TAccessTimeFilter.ApplyFilter(NS: TNamespace): Boolean;
var
Allow: Boolean;
begin
Allow := True;
if AfterTimeEnabled then
begin
if ValidFileTime(NS.LastAccessTimeRaw) and ValidFileTime(AfterTime) then
Allow := CompareFileTime(NS.LastAccessTimeRaw, AfterTime) >= 0 ;
end;
// Don't waste time if the previous and disallowed the item
if BeforeTimeEnabled and Allow then
if ValidFileTime(NS.LastAccessTimeRaw) and ValidFileTime(BeforeTime) then
Allow := CompareFileTime(NS.LastAccessTimeRaw, BeforeTime) <= 0;
Result := Allow;
end;
{ TModifyTimeFilter }
function TModifyTimeFilter.ApplyFilter(NS: TNamespace): Boolean;
var
Allow: Boolean;
begin
Allow := True;
if AfterTimeEnabled then
begin
if ValidFileTime(NS.LastWriteTimeRaw) and ValidFileTime(AfterTime) then
Allow := CompareFileTime(NS.LastWriteTimeRaw, AfterTime) >= 0 ;
end;
// Don't waste time if the previous and disallowed the item
if BeforeTimeEnabled and Allow then
if ValidFileTime(NS.LastWriteTimeRaw) and ValidFileTime(BeforeTime) then
Allow := CompareFileTime(NS.LastWriteTimeRaw, BeforeTime) <= 0;
Result := Allow;
end;
end.
|
Unit Splines;
{
This program has been designed and is CopyLefted by:
* Han de Bruijn; Systems for Research "A little bit of Physics would be (===)
* and Education (DTO/SOO), Mekelweg 6 NO Idleness in Mathematics"(HdB) @-O^O-@
* 2628 CD Delft, The Netherlands http://huizen.dto.tudelft.nl/deBruijn #/_\#
* E-mail: Han.deBruijn@DTO.TUDelft.NL Tel: +31 15 27 82751. Fax: 81722 ###
All I ask is to be credited when it is appropriate.
}
interface
Uses Controls, Graphics, Extctrls;
procedure Test;
procedure Definitie(Scherm : TImage);
function BuigLijn(X,Y : integer ; start : boolean) : double;
implementation
type
vektor = record
x : double;
y : double;
end;
const
Grens = 7;
var
{ Initial
position,
velocity,
acceleration: }
s,v,a : vektor;
{ Control points of spline: }
z,C : array[0..2] of vektor;
{ Recursion depth: }
Diepst : integer;
{ Upper / Lower bounds for Length: }
boven,onder : array[0..Grens] of double;
{ Computer Graphics: }
grafisch : boolean;
Beeld : TImage;
{ Increments: }
t : integer;
procedure Omzet;
{
Translate Geometry into Analysis
}
begin
s.x := (z[0].x + 2*z[1].x + z[2].x)/4;
s.y := (z[0].y + 2*z[1].y + z[2].y)/4;
v.x := z[2].x - z[0].x;
v.y := z[2].y - z[0].y;
a.x := 2*(z[0].x - 2*z[1].x + z[2].x);
a.y := 2*(z[0].y - 2*z[1].y + z[2].y);
end;
function L(t : double) : double;
{
Exact Length of a Conic Spline
------------------------------
(see accompanying TeX document)
}
var
La,D,w,r,I : double;
begin
La := sqr(a.x) + sqr(a.y);
L := sqrt(sqr(v.x) + sqr(v.y)) * t;
if La = 0 then Exit;
D := v.x*a.y - v.y*a.x;
I := a.x*v.x + a.y*v.y;
L := sqrt(La) * (sqr(t)/2 + I*t/La);
if D = 0 then Exit;
w := (La*t + I)/D;
La := La*sqrt(La);
r := sqrt(1+sqr(w));
L := sqr(D)/La * (w*r + ln(w+r)) / 2;
end;
procedure NeemWat;
{
Some points
}
var
k : integer;
begin
for k := 0 to 2 do
begin
z[k].x := Random;
z[k].y := Random;
end;
end;
procedure Schrijf(p : array of vektor);
{
Writeup
}
var
k : integer;
begin
if Length(p) <> 3 then Exit;
for k := 0 to 2 do
Writeln(' (',p[k].x:8:5,',',p[k].y:8:5,')');
Writeln;
end;
procedure Voorbeeld(keer : integer);
{
Example
}
var
k : integer;
begin
for k := 1 to keer do
begin
NeemWat;
Omzet;
Writeln(L(1/2)-L(-1/2));
end;
Schrijf(z);
end;
function H(p,q : vektor) : double;
{
Distance between two points
}
begin
H := sqrt(sqr(p.x-q.x) + sqr(p.y-q.y));
end;
procedure Halveer(p : array of vektor ; diep : integer);
{
Recursive procedure for defining a spline
}
var
q : array[0..2] of vektor;
x,y : integer;
begin
{ Erroneous input: }
if Length(p) <> 3 then Exit;
{ End of recursion: }
if diep > Diepst then Exit;
if not grafisch then
begin
Write(diep,' ');
{ Upper and Lower bounds on Length: }
boven[diep] := boven[diep] + H(p[0],p[1]) + H(p[1],p[2]);
onder[diep] := onder[diep] + H(p[0],p[2]);
end;
if diep = Diepst then
if grafisch then
begin
x := Round(p[2].x);
y := Round(p[2].y);
Beeld.Canvas.LineTo(x,y);
end;
{ Left half of spline: }
q[0] := p[0];
q[1].x := (p[0].x + p[1].x)/2;
q[1].y := (p[0].y + p[1].y)/2;
q[2].x := (p[0].x + 2*p[1].x + p[2].x)/4;
q[2].y := (p[0].y + 2*p[1].y + p[2].y)/4;
{ Recursion: }
Halveer(q,diep+1);
{ Right half of spline: }
q[0] := q[2];
q[1].x := (p[2].x + p[1].x)/2;
q[1].y := (p[2].y + p[1].y)/2;
q[2] := p[2];
{ Recursion: }
Halveer(q,diep+1);
{ Pieces will come out
in the right order ! }
end;
procedure Recursief(plotten : boolean);
{
Test on Recursion
}
var
k : integer;
berekend : double;
begin
for k := 0 to Grens do
begin
onder[k] := 0;
boven[k] := 0;
end;
Diepst := Grens;
Halveer(z,0);
Writeln;
{ Exact Length in between
Upper and Lower bounds: }
berekend := L(1/2)-L(-1/2);
for k := 0 to Grens do
Writeln(k,' : ',onder[k],' < ',berekend,' < ',boven[k]);
end;
procedure Test;
begin
Voorbeeld(3);
Recursief(false);
end;
procedure Definitie;
{
Image Definition
}
begin
Beeld := Scherm;
grafisch := true;
end;
function log2(n : integer) : integer;
{
Logarithm base 2
---------------- }
var
k, L : byte;
begin
log2 := 0;
if n <= 0 then Exit;
for k := 1 to 32 do
begin
n := n div 2 ; L := k;
if n = 0 then Break ;
end;
log2 := L;
end;
function BuigLijn;
{
Draw the Conic Splines
----------------------
Determine total Length
}
var
m,n : integer;
hoog,laag : double;
px,py : integer;
function half(a,b : vektor) : vektor;
begin
half.x := (a.x + b.x)/2;
half.y := (a.y + b.y)/2;
end;
begin
BuigLijn := 0;
if start then t := 0;
m := (t mod 3);
{ Store three
successive points: }
C[m].x := X;
C[m].y := Y;
t := t + 1;
if t < 3 then Exit;
{ Spline Control Points: }
m := ((t-3) mod 3);
n := ((t-2) mod 3);
z[0] := half(C[m],C[n]);
z[1] := C[n];
m := ((t-1) mod 3);
z[2] := half(C[n],C[m]);
{ Bound on number of points needed: }
hoog := H(z[0],z[1]) + H(z[1],z[2]);
laag := H(z[0],z[2]);
Diepst := log2(Round((hoog+laag)/2));
{ Writeln('Depth = ',Diepst); }
px := Round(z[0].x);
py := Round(z[0].y);
Beeld.Canvas.MoveTo(px,py);
Beeld.Canvas.Pen.Color := clRed;
{ Recursion: }
Halveer(z,0);
Beeld.Canvas.MoveTo(X,Y);
Beeld.Canvas.Pen.Color := clSilver;
{ Length calculation: }
Omzet;
BuigLijn := abs(L(1/2)-L(-1/2));
end;
end.
|
unit API_Parse;
interface
type
TParseTools = class
class function ParseByRegEx(aPage:string; aRegEx:string): TArray<string>;
class function ParseStrByRegEx(aPage:string; aRegEx:string): string;
class function Explode(aIncome: string; aDelimiter: string): TArray<string>;
class function GetNormalizeString(aLine: string): string;
end;
implementation
uses
System.SysUtils
,RegularExpressions;
class function TParseTools.GetNormalizeString(aLine: string): string;
begin
while Pos(#$D, aLine)>0 do
aLine:=StringReplace(aLine, #$D, ' ', [rfReplaceAll, rfIgnoreCase]);
while Pos(#$A, aLine)>0 do
aLine:=StringReplace(aLine, #$A, ' ', [rfReplaceAll, rfIgnoreCase]);
while Pos(' ', aLine)>0 do
aLine:=StringReplace(aLine, ' ', ' ', [rfReplaceAll, rfIgnoreCase]);
Result:=Trim(aLine);
end;
class function TParseTools.ParseByRegEx(aPage:string; aRegEx:string): TArray<string>;
var
m: TMatch;
begin
m := TRegEx.Match(aPage, aRegEx);
while m.Success do
begin
Result := Result + [m.value];
m := m.NextMatch;
end;
end;
class function TParseTools.ParseStrByRegEx(aPage:string; aRegEx:string): string;
var
m: TArray<string>;
begin
Result:='';
m:=ParseByRegEx(aPage, aRegEx);
if Length(m)>0 then Result:=m[0];
end;
class function TParseTools.Explode(aIncome: string; aDelimiter: string): TArray<string>;
var
i: integer;
tx: string;
begin
tx:='';
for i := 1 to Length(aIncome) do
begin
if (aIncome[i]<>aDelimiter) then tx:=tx+aIncome[i];
if (aIncome[i]=aDelimiter) or (i=Length(aIncome)) then
begin
SetLength(Result, Length(Result)+1);
Result[Length(Result)-1]:=Trim(tx);
tx:='';
end;
end;
end;
end.
|
{
Laz-Model
Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde
Portions (C) 2016 Peter Dyson. Initial Lazarus port
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.
}
unit uConfig;
{$mode objfpc}{$H+}
interface
uses
SysUtils, IniFiles,
LResources;
type
//Save changed diagram layout setting
TDiSaveSetting = (dsAlways,dsAsk,dsNever);
{ TConfig }
TConfig = class
private
FIni: TMemIniFile;
FDiSave : TDiSaveSetting;
FDiShowAssoc: boolean;
FDiVisibilityFilter: integer;
FEditorCommandLine: String;
FDocGenImages: boolean;
FDocsFromFPDoc: boolean;
FProjectName: string;
FDocsDir: string;
public
constructor Create;
destructor Destroy; override;
function GetResource(AName: String; AType: String): String;
public
IsLimitedColors : boolean;
IsTerminating : boolean;
property EditorCommandLine: String read FEditorCommandLine write FEditorCommandLine;
procedure WriteStr(const Key : string; const Value : string);
function ReadStr(const Key : string; const Default : string) : string;
procedure WriteInt(const Key : string; const Value : Integer);
function ReadInt(const Key : string; const Default : Integer) : Integer;
procedure WriteBool(const Key : string; const Value : Boolean);
function ReadBool(const Key : string; const Default : Boolean) : Boolean;
procedure StoreSettings;
published
property DiSave : TDiSaveSetting read FDiSave write FDiSave;
property DiShowAssoc : boolean read FDiShowAssoc write FDiShowAssoc;
property DiVisibilityFilter : integer read FDiVisibilityFilter write FDiVisibilityFilter;
property ProjectName: string read FProjectName write FProjectName;
property DocGenImages: boolean read FDocGenImages write FDocGenImages default True;
property DocsDir: string read FDocsDir write FDocsDir;
property DocsFromFPDoc: boolean read FDocsFromFPDoc write FDocsFromFPDoc default True;
end;
var
Config: TConfig;
implementation
const
cSettings = 'Settings';
constructor TConfig.Create;
var
FDir: String;
begin
IsLimitedColors := False;
FDir := GetUserDir + '.essmodel';
if not DirectoryExists(FDir) then
begin
ForceDirectories(FDir);
FileSetAttr(FDir, faHidden);
end;
FIni := TMemIniFile.Create(FDir + DirectorySeparator + 'config.ini');
FDiShowAssoc := ReadInt('DiShowAssoc',0)<>0;
FDiVisibilityFilter := ReadInt('DiVisibilityFilter',0);
FEditorCommandLine := ReadStr('EditorCommandLine','');
// TODO PROJECT SETTINGS
FProjectName := 'Laz-Model';
FDocsDir := 'FPDoc';
end;
destructor TConfig.Destroy;
begin
FIni.UpdateFile;
FIni.Free;
inherited Destroy;
end;
function TConfig.GetResource(AName: String; AType: String): String;
var
FRes: TLazarusResourceStream;
begin
FRes := TLazarusResourceStream.Create(AName, PChar(AType));
try
Result := FRes.Res.Value;
finally
FRes.Free;
end;
end;
function TConfig.ReadInt(const Key: string;
const Default: integer): integer;
begin
Result := FIni.ReadInteger(cSettings, Key, Default);
end;
procedure TConfig.WriteBool(const Key: string; const Value: Boolean);
begin
FIni.WriteBool(cSettings, Key, Value);
end;
function TConfig.ReadBool(const Key: string; const Default: Boolean): Boolean;
begin
Result := FIni.ReadBool(cSettings, Key, Default);
end;
function TConfig.ReadStr(const Key: string; const Default: string): string;
begin
Result := FIni.ReadString(cSettings, Key, Default);
end;
procedure TConfig.WriteInt(const Key: string; const Value: Integer);
begin
FIni.WriteInteger(cSettings, Key, Value);
end;
procedure TConfig.WriteStr(const Key: string; const Value: string);
begin
FIni.WriteString(cSettings, Key, Value)
end;
procedure TConfig.StoreSettings;
begin
WriteInt('DiSave',Integer(FDiSave));
WriteBool('DiShowAssoc',FDiShowAssoc);
WriteInt('DiVisibilityFilter',FDiVisibilityFilter);
WriteStr('EditorCommandLine',FEditorCommandLine);
end;
initialization
Config := TConfig.Create;
finalization
Config.Free;
end.
|
(*
Category: SWAG Title: STRING HANDLING ROUTINES
Original name: 0005.PAS
Description: PERM-STR.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:58
*)
{
Here it is. note that this permutes a set of Characters. if you want to
do something different, you will have to modify the code, but that should
be easy.
}
Type
tThingRec = Record
ch : Char;
occ : Boolean;
end;
Var
Thing : Array[1..255] of tThingRec;
EntryString : String;
Procedure Permute(num : Byte);
{ N.B. Procedure _must_ be called With num = 1;
it then calls itself recursively,
incrementing num }
Var
i : Byte;
begin
if num > length(EntryString) then
begin
num := 1;
For i := 1 to length(EntryString) do
Write(Thing[i].Ch); { You'll want to direct }
Writeln; { output somewhere else }
end
else
begin
For i := 1 to length(EntryString) do
begin
if (not Thing[i].Occ) then
begin
Thing[i].Occ := True;
Thing[i].Ch := EntryString[num];
Permute(succ(num));
Thing[i].Occ := False;
end;
end;
end;
end;
begin
FillChar(Thing,sizeof(Thing),0);
Write('Enter String of Characters to Permute: ');
Readln(EntryString);
Permute(1);
Writeln;
Writeln('Done');
end.
|
(*
Category: SWAG Title: TEXT FILE MANAGEMENT ROUTINES
Original name: 0059.PAS
Description: Expanding Tabs
Author: MICHAEL TEATOR
Date: 05-27-95 10:37
*)
program ExpandTabs;
{
Public domain by Michael Teator
February 1995
}
const
Space: byte = 32;
type
TextFile = file of byte;
var
OutputFile, InputFile: TextFile;
OutputName, InputName: string;
t, Pos, TabSpace, ch: byte;
begin
writeln ('Tab Expander 1.0 Public Domain by Michael Teator');
writeln;
write ('Input File: ');
readln (InputName);
write ('Output File: ');
readln (OutputName);
if InputName = OutputName then begin
writeln ('Output file cannot be the same as the input file.');
halt (1)
end;
write ('Spaces between tabs: ');
readln (TabSpace);
if TabSpace < 1 then TabSpace := 1;
assign (InputFile, InputName);
assign (OutputFile, OutputName);
reset (InputFile);
rewrite (OutputFile);
Pos := 0;
while not eof(InputFile) do begin
read (InputFile, ch);
case ch of
9: for t := 1 to (TabSpace - (Pos mod TabSpace)) do begin
write (OutputFile, Space);
inc (Pos)
end;
13, 10: begin
Pos := 0;
write (OutputFile, ch)
end;
else begin
write (OutputFile, ch);
inc (Pos)
end;
end; { case }
end; { while }
close (InputFile);
close (OutputFile);
writeln ('Done.')
end.
|
unit Car;
{$mode delphi}
interface
uses
SysUtils, Graphics, Classes, LCLIntf,
Entity, StopLine, TrafficSignal, Rotator;
type
TCarEntity = class(TEntity)
protected
Rotated, AtStopLine, Hurry: Boolean;
Signal: TSignalEntity;
public
Color: TColor;
procedure Paint; override;
procedure Touch(e: TEntity); override;
function Think: Boolean; override;
end;
implementation
procedure TCarEntity.Paint;
begin
Randomize;
with self.PaintBox.Canvas do
begin
Pen.Style := psSolid;
{ draw tires }
Pen.Color := clBlack;
Pen.Width := Round(self.Width * Width / 5);
self.DrawLine(-1.0, -0.7, -1.0, -0.5);
self.DrawLine(1.0, -0.7, 1.0, -0.5);
self.DrawLine(-1.0, 0.5, -1.0, 0.7);
self.DrawLine(1.0, 0.5, 1.0, 0.7);
{ draw headlights }
Pen.Color := clYellow;
self.DrawLine(-0.8, -1.05, -0.6, -1.05);
self.DrawLine(0.6, -1.05, 0.8, -1.05);
{ draw body }
Pen.Width := 1;
Pen.Color := clBlack;
Brush.Color := self.Color;
self.DrawRectangle(-1.0, -1.0, 1.0, 1.0);
{ draw bonnet }
self.DrawLine(-1.0, -1.0, -0.8, -0.7);
self.DrawLine(1.0, -1.0, 0.8, -0.7);
{ draw trunk }
self.DrawLine(-0.8, 0.7, -1.0, 1.0);
self.DrawLine(0.8, 0.7, 1.0, 1.0);
{ draw roof }
self.DrawLine(-0.8, -0.3, -0.8, 0.3);
self.DrawLine(0.8, -0.3, 0.8, 0.3);
{ draw windshield }
Brush.Color := clBlue;
self.DrawRectangle(-0.8, -0.7, 0.8, -0.3);
{ draw back window }
self.DrawRectangle(-0.8, 0.3, 0.8, 0.7);
end;
end;
function TCarEntity.Think;
var
i: Integer;
c: TCarEntity;
X, Y, Distance: Real;
begin
self.Speed := self.MaxSpeed;
for i := 0 to self.EntList.Count - 1 do
begin
if not (self.EntList.Items[i] is TCarEntity) then
continue;
c := self.EntList.Items[i] as TCarEntity;
X := self.X; Y := self.Y;
case self.Orientation of
up:
begin
Y := self.TopLeft.Y - 0.07;
Distance := self.TopLeft.Y - c.BottomRight.Y;
end;
down:
begin
Y := self.BottomRight.Y + 0.07;
Distance := c.TopLeft.Y - self.BottomRight.Y;
end;
left:
begin
X := self.TopLeft.X - 0.07;
Distance := self.TopLeft.X - c.BottomRight.X;
end;
right:
begin
X := self.BottomRight.X + 0.07;
Distance := c.TopLeft.X - self.BottomRight.X;
end;
end;
if (X > c.TopLeft.X) and (X < c.BottomRight.X)
and (Y > c.TopLeft.Y) and (Y < c.BottomRight.Y) then
begin
if (distance > 0.06) then
self.Speed := c.Speed
else
self.Speed := 0;
end;
end;
if self.AtStopLine then
begin
if not self.Hurry then
begin
if self.Signal.Sequence = Stop then
self.Speed := 0
else
self.Hurry := true;
end;
self.AtStopLine := false;
end
else
self.Hurry := false;
Result := true;
end;
procedure TCarEntity.Touch;
begin
if (not self.Rotated) and (e is TRotateEntity) then
begin
self.Rotated := true;
self.Orientation := e.Orientation;
end;
if (not self.AtStopLine) and (e is TStopLineEntity) then
begin
self.AtStopLine := true;
self.Signal := (e as TStopLineEntity).Signal as TSignalEntity;
end;
end;
end.
|
unit Ellipsoid_Integration;
//
// PHOLIAGE Model, (c) Roelof Oomen, 2006-2007
//
// Model integration methods
//
interface
uses
Model_Absorption, GaussInt;
type
TEllipse = class(TGaussIntA)
private
r : Double; // Radius of circle transformation at Z
Z : Double; // Z-Coordinate in sphere transformation
public
Env : TEnvironment;
function fuGI(const xGI:Double): GIResult; override;
constructor Create;
destructor Destroy; override;
end;
TRing = class(TGaussIntA)
public
Ellipse : TEllipse;
constructor Create;
destructor Destroy; override;
function fuGI(const xGI:Double): GIResult; override;
end;
TEllipsoid = class(TGaussIntA)
private
procedure SetgpPsi(val : Integer);
function GetgpPsi : Integer;
procedure SetgpR(val : Integer);
function GetgpR : Integer;
procedure SetgpZ(val : Integer);
function GetgpZ : Integer;
public
Ring : TRing;
Name : String; // Plant's identifier
constructor Create;
destructor Destroy; override;
function fuGI(const xGI:Double): GIResult; override;
function Calculate: GIResult;
// Number of gaussian integration points for each integral
property gpZ : Integer read GetgpZ write SetgpZ;
property gpPsi : Integer read GetgpPsi write SetgpPsi;
property gpR : Integer read GetgpR write SetgpR;
end;
TPlot = class
// Identification
Name : String;
Location : String;
// Array of plant calculation classes
Plants : Array of TEllipsoid;
// Heights of Plants, used to calculate correct vegetation heights
// relative to ellipsoid center
Heights : Array of Double;
// Results of light absorption calculations
AbsResults : GIResult;
// Results of photosynthesis calculations
PhotResults : GIResult;
// Frees Plant, Heights and AbsResults arrays
procedure Clear;
// Call to make sure Plant array objects are freed
destructor Destroy; override;
end;
implementation
uses
SysUtils, Vector, Paths;
function TEllipse.fuGI(const xGI:Double): GIResult;
var
p : TVectorC;
begin
// As We integrate over a unit sphere, instead of the original ellipsoidal
// crown, we have to translate parameter p to a point p in the crown.
// We have to transform the cylindrical coordinates (r, psi, Z)
// (with xGI as psi), used for integrating, to Cartesian coordinates to be
// able to translate over three orthonormal ellipsoid axes.
p.x:=(r*cos(xGI))*Env.Crown.a;
p.y:=(r*sin(xGI))*Env.Crown.b;
p.z:=Z*Env.Crown.c;
SetLength(Result, 2);
result[0]:=Env.Absorption.I( p );
result[1]:=Env.Assimilation.P_tot( p );
end;
constructor TEllipse.Create;
begin
inherited Create;
if not assigned(Env) then
Env:=TEnvironment.Create;
// Initialise for testing purposes, when TEllipse is used stand-alone
r:=1;
Z:=0;
x_min:=0;
x_max:=2*pi;
end;
destructor TEllipse.Destroy;
begin
FreeAndNil(Env);
inherited Destroy;
end;
function TRing.fuGI(const xGI:Double): GIResult;
var
I: Integer;
begin
Ellipse.r:=xGI;
result:=Ellipse.integrate;// Default: (0,2*pi)
for I := 0 to High(result) do
result[I]:=Ellipse.r*result[I];
end;
constructor TRing.Create;
begin
inherited Create;
Ellipse:=TEllipse.Create;
end;
destructor TRing.Destroy;
begin
FreeAndNil(Ellipse);
inherited Destroy;
end;
function TEllipsoid.fuGI(const xGI:Double): GIResult;
begin
Ring.Ellipse.Z:=xGI;
result:=Ring.integrate(0,sqrt(1-sqr(Ring.Ellipse.Z)));
end;
function TEllipsoid.Calculate: GIResult;
var
I: Integer;
GIR : GIResult;
p : TVectorC;
begin
// Initialise light at the top of the ellipsoid, used for the nitrogen distr
p.x:=0;
p.y:=0;
p.z:=Ring.Ellipse.Env.Crown.c;
// Divide light by a_L as we want the incident and not the absorbed light
Ring.Ellipse.Env.Photosynthesis.I_top:=Ring.Ellipse.Env.Absorption.I( p )/Ring.Ellipse.Env.Crown.F.a_L;
// Actual calculation
GIR:=integrate; // Default: (-1,1)
SetLength(result, Length(GIR));
// Translate to ellipsoid
for I := 0 to High(GIR) do
result[I]:=Ring.Ellipse.Env.crown.a*Ring.Ellipse.Env.crown.b*Ring.Ellipse.Env.crown.c*GIR[I];
end;
constructor TEllipsoid.Create;
begin
inherited Create;
Ring:=TRing.Create;
x_min:=-1;
x_max:=1;
end;
destructor TEllipsoid.Destroy;
begin
FreeAndNil(Ring);
inherited Destroy;
end;
function TEllipsoid.GetgpZ: Integer;
begin
result:=GP;
end;
procedure TEllipsoid.SetgpZ(val : Integer);
begin
GP:=val;
end;
function TEllipsoid.GetgpPsi: Integer;
begin
result:=Ring.Ellipse.GP;
end;
procedure TEllipsoid.SetgpPsi(val : Integer);
begin
Ring.Ellipse.GP:=val;
end;
function TEllipsoid.GetgpR: Integer;
begin
result:=Ring.GP;
end;
procedure TEllipsoid.SetgpR(val : Integer);
begin
Ring.GP:=val;
end;
{ TPlot }
procedure TPlot.Clear;
var
I : Integer;
begin
// Clean up
for I := 0 to High(Plants) do
FreeAndNil(Plants[I]);
SetLength(Plants, 0);
SetLength(Heights,0);
SetLength(AbsResults,0);
SetLength(PhotResults,0);
end;
destructor TPlot.Destroy;
begin
Clear;
inherited;
end;
end.
|
unit uGameScreen.Credits;
interface
uses
Windows,
GLScene, GLObjects, GLWin32Viewer, GLHUDObjects, GLMaterial, GLTexture,
GLKeyboard, GLFilePNG, GLState,
uGameScreen,
dfKeyboardExt;
const
C_SCREEN_NAME = 'Credits';
C_CREDITS_TEXTUREPATH = 'data\menu\';
C_CREDITS_IMAGESCALE = 1/1;
C_BACK_SCALE_X = 1.0;
C_BACK_SCALE_Y = 1.0;
C_BACK_STRAFE_X = 0;
C_BACK_STRAFE_Y = 0;
C_BACK_ALPHA = 0.5;
C_CREDITS_ORIGIN_STRAFE_X = 150;
C_CREDITS_ORIGIN_STRAFE_Y = -50;
C_PROGRAMMING_STRAFE_X = 0;
C_PROGRAMMING_STRAFE_Y = 0;
C_ART_STRAFE_X = 0;
C_ART_STRAFE_Y = 150;
C_GLSCENERU_STRAFE_X = 0;
C_GLSCENERU_STRAFE_Y = 250;
C_CREDITS_FADEIN_TIME = 1.5;
C_CREDITS_FADEOUT_TIME = 0.8;
type
TdfCredits = class (TdfGameScreen)
private
FRoot: TGLDummyCube;
FViewerW, FViewerH: Integer;
FBackground: TGLHUDSprite;
FProgramming, FArtModels, FForGLSceneRu: TGLHUDSprite;
FMainMenu: TdfGameScreen;
Ft: Double;
procedure AddCreditsMaterial(var aObject: TGLHUDSprite; const aTextureName: String);
procedure AddBackgroundMaterial(var aBack: TGLHUDSprite);
procedure FadeInComplete();
procedure FadeOutComplete();
protected
procedure FadeIn(deltaTime: Double); override;
procedure FadeOut(deltaTime: Double); override;
procedure SetStatus(const aStatus: TdfGameSceneStatus); override;
public
constructor Create(); override;
destructor Destroy; override;
procedure Load(); override;
procedure Unload(); override;
procedure Update(deltaTime: Double; X, Y: Integer); override;
procedure SetGameScreens(aMainMenu: TdfGameScreen);
end;
implementation
uses
uGLSceneObjects;
{ TdfCredits }
procedure TdfCredits.AddBackgroundMaterial(var aBack: TGLHUDSprite);
begin
with aBack.Material do
begin
Texture.Enabled := False;
Texture.TextureMode := tmModulate;
BlendingMode := bmTransparency;
MaterialOptions := [moIgnoreFog, moNoLighting];
FrontProperties.Diffuse.SetColor(0,0,0, C_BACK_ALPHA);
end;
end;
procedure TdfCredits.AddCreditsMaterial(var aObject: TGLHUDSprite;
const aTextureName: String);
begin
with aObject.Material do
begin
Texture.Image.LoadFromFile(C_CREDITS_TEXTUREPATH + aTextureName);
Texture.Enabled := True;
Texture.TextureMode := tmModulate;
BlendingMode := bmTransparency;
MaterialOptions := [moIgnoreFog, moNoLighting];
FrontProperties.Diffuse.SetColor(1,1,1);
BlendingParams.BlendFuncSFactor := bfOne;
BlendingParams.BlendFuncDFactor := bfOne;
end;
aObject.Width := aObject.Material.Texture.Image.Width * C_CREDITS_IMAGESCALE;
aObject.Height := aObject.Material.Texture.Image.Height * C_CREDITS_IMAGESCALE;
end;
constructor TdfCredits.Create();
begin
inherited;
FName := C_SCREEN_NAME;
FRoot := TGLDummyCube.CreateAsChild(dfGLSceneObjects.Scene.Objects);
FRoot.Visible := False;
FViewerW := dfGLSceneObjects.Viewer.Width;
FViewerH := dfGLSceneObjects.Viewer.Height;
FBackground := TGLHUDSprite.CreateAsChild(FRoot);
AddBackgroundMaterial(FBackground);
with FBackground do
begin
Position.SetPoint(FViewerW / 2 + C_BACK_STRAFE_X, FViewerH / 2 + C_BACK_STRAFE_Y, -0.9);
Width := FViewerW * C_BACK_SCALE_X;
Height := FViewerH * C_BACK_SCALE_Y;
end;
FProgramming := TGLHUDSprite.CreateAsChild(FRoot);
AddCreditsMaterial(FProgramming, 'credit_program.png');
FProgramming.Position.SetPoint(FViewerW / 2 + C_CREDITS_ORIGIN_STRAFE_X + C_PROGRAMMING_STRAFE_X,
FViewerH / 2 + C_CREDITS_ORIGIN_STRAFE_Y + C_PROGRAMMING_STRAFE_Y, -0.5);
FArtModels := TGLHUDSprite.CreateAsChild(FRoot);
AddCreditsMaterial(FArtModels, 'credit_artmodel.png');
FArtModels.Position.SetPoint(FViewerW / 2 + C_CREDITS_ORIGIN_STRAFE_X + C_ART_STRAFE_X,
FViewerH / 2 + C_CREDITS_ORIGIN_STRAFE_Y + C_ART_STRAFE_Y, -0.5);
FForGLSceneRu := TGLHUDSprite.CreateAsChild(FRoot);
AddCreditsMaterial(FForGLSceneRu, 'credit_glsceneru.png');
FForGLSceneRu.Position.SetPoint(FViewerW / 2 + C_CREDITS_ORIGIN_STRAFE_X + C_GLSCENERU_STRAFE_X,
FViewerH / 2 + C_CREDITS_ORIGIN_STRAFE_Y + C_GLSCENERU_STRAFE_Y, -0.5);
// FBackground.MoveFirst;
end;
destructor TdfCredits.Destroy;
begin
FRoot.Free;
inherited;
end;
procedure TdfCredits.FadeIn(deltaTime: Double);
begin
Ft := Ft + deltaTime;
FBackground.Material.FrontProperties.Diffuse.Alpha := (Ft / C_CREDITS_FADEIN_TIME) * C_BACK_ALPHA ;
FProgramming.Material.FrontProperties.Diffuse.Alpha := Ft / C_CREDITS_FADEIN_TIME;
FArtModels.Material.FrontProperties.Diffuse.Alpha := Ft / C_CREDITS_FADEIN_TIME;
FForGLSceneRu.Material.FrontProperties.Diffuse.Alpha := Ft / C_CREDITS_FADEIN_TIME;
if FT >= C_CREDITS_FADEIN_TIME then
inherited;
end;
procedure TdfCredits.FadeInComplete;
begin
FBackground.Material.FrontProperties.Diffuse.Alpha := C_BACK_ALPHA;
FProgramming.Material.FrontProperties.Diffuse.Alpha := 1.0;
FArtModels.Material.FrontProperties.Diffuse.Alpha := 1.0;
FForGLSceneRu.Material.FrontProperties.Diffuse.Alpha := 1.0;
end;
procedure TdfCredits.FadeOut(deltaTime: Double);
begin
Ft := Ft + deltaTime;
FBackground.Material.FrontProperties.Diffuse.Alpha := C_BACK_ALPHA - (Ft / C_CREDITS_FADEOUT_TIME) * C_BACK_ALPHA ;
FProgramming.Material.FrontProperties.Diffuse.Alpha := 1 - Ft / C_CREDITS_FADEOUT_TIME;
FArtModels.Material.FrontProperties.Diffuse.Alpha := 1 - Ft / C_CREDITS_FADEOUT_TIME;
FForGLSceneRu.Material.FrontProperties.Diffuse.Alpha := 1 - Ft / C_CREDITS_FADEOUT_TIME;
if FT >= C_CREDITS_FADEOUT_TIME then
inherited;
end;
procedure TdfCredits.FadeOutComplete;
begin
FBackground.Material.FrontProperties.Diffuse.Alpha := 0;
FProgramming.Material.FrontProperties.Diffuse.Alpha := 0;
FArtModels.Material.FrontProperties.Diffuse.Alpha := 0;
FForGLSceneRu.Material.FrontProperties.Diffuse.Alpha := 0;
FRoot.Visible := False;
FStatus := gssNone;
end;
procedure TdfCredits.Load;
begin
inherited;
if FLoaded then
Exit;
//*
FLoaded := True;
end;
procedure TdfCredits.SetGameScreens(aMainMenu: TdfGameScreen);
begin
FMainMenu := aMainMenu;
end;
procedure TdfCredits.SetStatus(const aStatus: TdfGameSceneStatus);
begin
inherited;
case aStatus of
gssNone : Exit;
gssReady : Exit;
gssFadeIn :
begin
FRoot.Visible := True;
Ft := 0;
end;
gssFadeInComplete : FadeInComplete();
gssFadeOut : Ft := 0;
gssFadeOutComplete: FadeOutComplete();
end;
end;
procedure TdfCredits.Unload;
begin
inherited;
if not FLoaded then
Exit;
//*
FLoaded := False;
end;
procedure TdfCredits.Update(deltaTime: Double; X, Y: Integer);
begin
inherited;
case FStatus of
gssNone: Exit;
gssReady:
begin
//Надо что-то придумать с VK_LBUTTON. Нужен перехват именно кликов
//UPD: сделано
if IsMouseClicked(VK_LBUTTON) then
if Assigned(FMainMenu) then
OnNotify(FMainMenu, naSwitchTo);
end;
gssFadeIn: FadeIn(deltaTime);
gssFadeInComplete: Exit;
gssFadeOut: FadeOut(deltaTime);
gssFadeOutComplete: Exit;
gssPaused: Exit;
end;
end;
end.
|
unit uFrmExportItems;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ADODB,
ComCtrls;
type
TFrmExportItems = class(TForm)
pnlBottom: TPanel;
btnOk: TcxButton;
btnCancel: TcxButton;
grdItems: TcxGrid;
grdItemsDB: TcxGridDBTableView;
grdItemsLevel: TcxGridLevel;
quItems: TADODataSet;
dsItems: TDataSource;
lbPath: TLabel;
quItemsModelo: TStringField;
quItemsDescricao: TStringField;
quItemsUnidade: TStringField;
quItemsCodTrib: TStringField;
quItemsSellingPrice: TBCDField;
quItemsIDModel: TIntegerField;
grdItemsDBModelo: TcxGridDBColumn;
grdItemsDBDescricao: TcxGridDBColumn;
grdItemsDBUnidade: TcxGridDBColumn;
grdItemsDBCodTrib: TcxGridDBColumn;
grdItemsDBSellingPrice: TcxGridDBColumn;
PB: TProgressBar;
procedure btnCancelClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FTextFile: TextFile;
FFileName : String;
procedure ExportarArquivo;
procedure CriarItems;
procedure OpenItems;
procedure CloseItems;
public
procedure Start;
end;
implementation
uses uFrmMain, uStringFunctions;
{$R *.dfm}
{ TFrmExportItems }
procedure TFrmExportItems.Start;
begin
ShowModal;
end;
procedure TFrmExportItems.btnCancelClick(Sender: TObject);
begin
Close;
CloseItems;
end;
procedure TFrmExportItems.btnOkClick(Sender: TObject);
begin
try
ExportarArquivo;
MessageDlg('Arquivo exportado com sucesso!', mtInformation, [mbOK], 0);
except
MessageDlg('Erro ao exportar arquivo.', mtError, [mbOK], 0);
end;
end;
procedure TFrmExportItems.FormShow(Sender: TObject);
var
sFilePath: String;
begin
sFilePath := FrmMain.GetAppProperty('Default', 'FilePath');
if sFilePath = '' then
begin
MessageDlg('O caminho para o arquivo não foi configurado!', mtInformation, [mbOK], 0);
Close;
end;
FFileName := ExtractFileDir(sFilePath) + '\PRODUTO.GSS';
lbPath.Caption := 'Criar arquivo em: ' + FFileName;
try
Cursor := crHourGlass;
OpenItems;
finally
Cursor := crDefault;
end;
end;
procedure TFrmExportItems.ExportarArquivo;
begin
try
AssignFile(FTextFile, FFileName);
Rewrite(FTextFile);
CriarItems;
finally
CloseFile(FTextFile);
end;
end;
procedure TFrmExportItems.CloseItems;
begin
with quItems do
if Active then
Close;
end;
procedure TFrmExportItems.OpenItems;
begin
with quItems do
if not Active then
Open;
end;
procedure TFrmExportItems.CriarItems;
var
sLinha : String;
begin
try
PB.Visible := True;
with quItems do
begin
DisableControls;
PB.Max := RecordCount;
PB.Position := 1;
First;
while not Eof do
begin
if FieldByName('CodTrib').AsString <> '' then
begin
sLinha := AE(FieldByName('Modelo').AsString, 20);
sLinha := sLinha + AE(FieldByName('Modelo').AsString, 16);
sLinha := sLinha + AE(FieldByName('Descricao').AsString, 40);
sLinha := sLinha + AE(FieldByName('Descricao').AsString, 39);
sLinha := sLinha + '00000001'; //Seção
sLinha := sLinha + AE(FieldByName('CodTrib').AsString, 3); //COD TRIB;
sLinha := sLinha + Replace(Replace(FormatFloat('000000000000.00', FieldByName('SellingPrice').AsFloat), ',', ''), '.', '');
sLinha := sLinha + FieldByName('Unidade').AsString;
Writeln(FTextFile, sLinha);
end;
Next;
PB.StepIt;
end;
EnableControls;
First;
end;
finally
PB.Visible := False;
end;
end;
end.
|
unit eRecord;
interface
uses
API_ORM,
eCommon;
type
TRecord = class(TEntity)
private
FKey: string;
FOwnerGroupID: Integer;
FValue: string;
public
class function GetStructure: TSructure; override;
published
property Key: string read FKey write FKey;
property OwnerGroupID: Integer read FOwnerGroupID write FOwnerGroupID;
property Value: string read FValue write FValue;
end;
TRecordList = TEntityAbstractList<TRecord>;
implementation
uses
eGroup;
class function TRecord.GetStructure: TSructure;
begin
Result.TableName := 'CORE_RECORDS';
AddForeignKey(Result.ForeignKeyArr, 'OWNER_GROUP_ID', TGroup, 'ID');
end;
end.
|
unit HilfsFunktionen;
interface
uses
SysUtils;
function Zufallszahl(minimum, maximum: integer): integer;
function ZufallsBoolean(Wahrscheinlichkeit: integer): boolean; overload;
function ZufallsBoolean(Wahrscheinlichkeit: integer; Basis: integer): boolean; overload;
type
TKassenStatus = (ksWareScannen, ksWareScannenFertig, ksKassieren, ksKassierenFertig,
ksNaechsterKunde, ksNaechsterKundeFertig, ksBereitZumSchliessen, ksGeschlossen);
TKundenStatus = (ksArtikelEinpacken, ksZurKasseGehen, ksBereitZumZahlen, ksInWarteschlange,
ksZahlen, ksZahlenFertig);
TKundenVerwalterStatus = (kvNormal, kvFlashMob);
TWarteschlangenVolumen = record
ArtikelVolumen: double;
SchlangenNummer: integer;
SchlangeOffen: boolean;
end;
TKassenParameter = record
AnzahlKassen: integer;
maxScanGeschwindigkeit: integer;
end;
TSortimentParameter = record
Pfad: string;
Trennzeichen: string;
end;
TKleingeldParameter = record
AlterKleingeldquote: integer;
KleingeldZahlerAlt: integer;
KleingeldZahlerRest: integer;
end;
TKundenParameter = record
MinAlter: integer;
MaxAlter: integer;
MinBargeld: integer;
MaxBargeld: integer;
Kundenfrequenz: integer;
Kundenkapazitaet: integer;
FlashmobQuote: integer;
end;
TAuswertungsParameter = record
KassierteKunden: integer;
WartezeitDurchschnitt : integer;
WartezeitMaximum : integer;
WartezeitMinimun : integer;
WarenkorbDurchschnitt : double;
FlashmobAnzahl : integer;
RechnungsBetragDurchschnitt : double;
RechnungsBetragMaximum : double;
Laufzeit: integer;
end;
implementation
function Zufallszahl(minimum, maximum: integer): integer;
begin
Result := Random(maximum - minimum) + minimum;
end;
function ZufallsBoolean(Wahrscheinlichkeit: integer): boolean;
begin
Result := Random(100) < Wahrscheinlichkeit;
end;
function ZufallsBoolean(Wahrscheinlichkeit: integer; Basis: integer): boolean;
begin
Result := Random(Basis) < Wahrscheinlichkeit;
end;
end.
|
unit uRBApp;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, forms, controls,
rtti_serializer_uXmlStore, rtti_serializer_uFactory, rtti_broker_iBroker,
rtti_idebinder_iBindings, rtti_idebinder_uDesigner, iStart,
rtti_broker_uPersistClassRegister;
type
{ TRBApp }
TRBApp = class(TInterfacedObject, IApp, IAppContext_kvyhozeni)
private
fSerialFactory: IRBFactory;
fConfig, fData: IRBStore;
fDesigner: IRBDesigner;
fMainF: TForm;
fStorageFile: string;
fControlClasses: IRBPersistClassRegister;
protected
// IMainContext
function GetConfig: IRBStore;
function GetData: IRBStore;
function GetClassFactory: IRBFactory;
function GetDataQuery: IRBDataQuery;
function GetDesigner: IRBDesigner;
function GetBinderContext: IRBBinderContext;
function GetControlClasses: IRBPersistClassRegister;
function PrepareHomeDir(const AHomeSubdir: string): string;
function ConfigFile: string;
function ConifgFileName: string; virtual;
function DefaultDataFile: string;
public
procedure OpenConfig;
function OpenData: IRBStore; virtual;
procedure RegisterDataClasses(const AClasses: array of TClass);
procedure RegisterControlClasses(const ACtlClasses: array of TControlClass);
procedure Run(const AFormClass: TFormClass);
property ClassFactory: IRBFactory read GetClassFactory;
property Config: IRBStore read GetConfig;
property DataQuery: IRBDataQuery read GetDataQuery;
property Designer: IRBDesigner read GetDesigner;
property ControlClasses: IRBPersistClassRegister read GetControlClasses;
property BinderContext: IRBBinderContext read GetBinderContext;
end;
implementation
{ TRBApp }
function TRBApp.GetConfig: IRBStore;
begin
if fConfig = nil then
raise Exception.Create('Config store not available');
Result := fConfig;
end;
function TRBApp.GetData: IRBStore;
begin
if fData = nil then
fData := OpenData;
if fData = nil then
raise Exception.Create('Data store not available');
Result := fData;
end;
function TRBApp.GetClassFactory: IRBFactory;
begin
if fSerialFactory = nil then
fSerialFactory := TSerialFactory.Create;
Result := fSerialFactory;
end;
function TRBApp.GetDataQuery: IRBDataQuery;
begin
Result := Config as IRBDataQuery;
end;
function TRBApp.GetDesigner: IRBDesigner;
begin
if fDesigner = nil then begin
fDesigner := TRBDesigner.Create;
end;
Result := fDesigner;
end;
function TRBApp.GetBinderContext: IRBBinderContext;
begin
//Result := Self;
end;
function TRBApp.GetControlClasses: IRBPersistClassRegister;
begin
if fControlClasses = nil then
fControlClasses := TRBPersistClassRegister.Create;
Result := fControlClasses;
end;
function TRBApp.PrepareHomeDir(const AHomeSubdir: string): string;
begin
{$IFDEF UNIX}
Result := GetEnvironmentVariable('HOME') + PathDelim + AHomeSubdir + PathDelim;
{$ENDIF UNIX}
{$IFDEF WINDOWS}
Result := GetEnvironmentVariable('APPDATA') + PathDelim + AHomeSubdir + PathDelim;
{$ENDIF WINDOWS}
if not DirectoryExists(Result) then
begin
if not ForceDirectories(Result) then
raise Exception.Create('Cannot create directory ' + Result);
end;
end;
function TRBApp.ConfigFile: string;
begin
Result := PrepareHomeDir('.' + ExtractFileName(ParamStr(0))) + ConifgFileName;
end;
function TRBApp.ConifgFileName: string;
begin
Result := 'config.xml';
end;
function TRBApp.DefaultDataFile: string;
begin
Result := PrepareHomeDir('.' + ExtractFileName(ParamStr(0))) + 'data.xml';
end;
procedure TRBApp.OpenConfig;
begin
if fConfig <> nil then
fConfig.Flush;
fConfig := TXmlStore.Create(ClassFactory, ConfigFile);
end;
function TRBApp.OpenData: IRBStore;
begin
Result := TXmlStore.Create(ClassFactory, DefaultDataFile);
end;
procedure TRBApp.RegisterDataClasses(const AClasses: array of TClass);
var
m: TClass;
begin
for m in AClasses do
ClassFactory.RegisterClass(m);
end;
procedure TRBApp.RegisterControlClasses(
const ACtlClasses: array of TControlClass);
var
m: TControlClass;
begin
for m in ACtlClasses do
ControlClasses.Add(m);
end;
procedure TRBApp.Run(const AFormClass: TFormClass);
begin
OpenConfig;
RequireDerivedFormResource := True;
Application.Initialize;
Application.CreateForm(AFormClass, fMainF);
Designer.Bind(fMainF, Config, ClassFactory, DataQuery, ControlClasses);
//if Supports(fMainF, IStartContextConnectable) then
// (fMainF as IStartContextConnectable).Connect(self);
//Application.ShowMainForm := False;
Application.Run;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.