text stringlengths 14 6.51M |
|---|
unit ClsMaps;
interface
uses
Contnrs, Windows, Classes, StrUtils, IniFiles,
UnitConsts;
type
TNPCID = (
ShuiCheng_Forge, ShuiCheng_Med, ShuiCheng_Jewelry, ShuiCheng_Pet, // 水
ShuCheng_Forge, ShuCheng_Med, ShuCheng_Jewelry, // 树
ShanCheng_Forge, ShanCheng_Med, ShanCheng_Jewelry, // 山
ShaCheng_Forge, ShaCheng_Med, ShaCheng_Jewelry, // 沙
XueCheng_Med, // 雪
HaiCheng_Med // 海
); // NPC 编号:铁匠、药店、珠宝店、宠物店
// 步骤信息
TStepInfo = Class
Action: Integer;
X: String;
Y: String;
Z: String;
SubStepIndex: integer;
CalledNPCID: TNPCID;
public
constructor Create(tmpAct: Integer = ActUnknown; tmpX: String = '';
tmpY: String = ''; tmpZ: String = '');
class procedure ExtractStepInfo(SrcStr: string; var Action: integer;
var X: string; var Y: string);
end;
{ // 步骤列表
TStepList = Class(TObjectList)
private
function GetItem(Index: Integer): TStepInfo;
procedure SetItem(Index: Integer; const Value: TStepInfo);
public
property Items[Index: Integer]: TStepInfo read GetItem write SetItem; default;
end; }
// 药店信息
TStoreInfo = Class
ID : DWORD; // 药店地图编号
Name : WideString; // 药店名称
EnteredX : integer; // 刚刚进去后时的地图坐标
EnteredY : integer;
DoctorPosX : Integer; // 大夫坐标
DoctorPosY : Integer;
NursePosX : Integer; // 护士坐标
NursePosY : Integer;
MedList : TStringList; // 药品列表
public
constructor Create;
destructor Destroy; override;
end;
// 药店列表
TStoreList = Class(TObjectList)
private
function GetItem(Index: Integer): TStoreInfo;
procedure SetItem(Index: Integer; const Value: TStoreInfo);
public
property Items[Index: Integer]: TStoreInfo read GetItem write SetItem; default;
end;
// 地图切换点信息
TTransportInfo = Class(TObjectList)
ID: Integer;
StepIndex: integer;
// IsDoingTrans: Boolean;
OldNPCDialog: WideString;
private
function GetItem(Index: Integer): TStepInfo;
procedure SetItem(Index: Integer; const Value: TStepInfo);
public
property Items[Index: Integer]: TStepInfo read GetItem write SetItem; default;
end;
// 地图切换点列表
TTransportList = Class(TObjectList)
private
function GetItem(Index: Integer): TTransportInfo;
procedure SetItem(Index: Integer; const Value: TTransportInfo);
public
function ItemOfTransportID(const TransportID: Integer): TTransportInfo;
property Items[Index: Integer]: TTransportInfo read GetItem write SetItem; default;
end;
// 地区信息
TZoneInfo = Class
ID : Integer; // 地区编号
Name : WideString; // 地区名称
MapList : TList; // 地图列表
public
constructor Create;
destructor Destroy; override;
end;
// 地区列表
TZoneList = Class(TObjectList)
private
function GetItem(Index: Integer): TZoneInfo;
procedure SetItem(Index: Integer; const Value: TZoneInfo);
public
property Items[Index: Integer]: TZoneInfo read GetItem write SetItem; default;
function ItemOfZoneID(const ZoneID: Integer): TZoneInfo;
end;
TNodeList = Class;
TMapInfo = Class
ID: DWORD; // 在游戏里面的地图编号
PosInMapList: integer; // 在MapList中的序号
NumberOfMapINI: integer; // 在Map.ini里面的[map序号]
Zone: Integer; // 地区编号
Name: WideString; // 地图名称
NodeNum: integer; // 节点数
NodeList: TNodeList; // 节点列表
public
constructor Create;
destructor Destroy; override;
end;
// 地图列表
TMapList = Class(TObjectList)
private
FIniFileName: WideString;
FStoreList: TStoreList;
FTransportList: TTransportList;
FZoneList: TZoneList;
function ExtractStoreInfo(iniFile: TIniFile; SourceStr: string): TStoreInfo;
protected
function GetItem(Index: Integer): TMapInfo;
procedure SetItem(Index: Integer; Value: TMapInfo);
public
constructor Create;
destructor Destroy; override;
procedure LoadMapList;
procedure LoadStoreList;
procedure LoadZoneList;
procedure LoadTransportList;
procedure ReadOneMap(PosInMapList: Integer);
property IniFileName: WideString read FIniFileName write FIniFileName;
function ItemOfMapID(const MapID: LongWord): TMapInfo;
property Items[Index: Integer]: TMapInfo read GetItem write SetItem; default;
property StoreList: TStoreList read FStoreList;
property TransportList: TTransportList read FTransportList;
property ZoneList: TZoneList read FZoneList;
end;
// 节点信息
TNodeInfo = Class
MyMap: TMapInfo;
InHL_X: Integer;
InHL_Y: Integer;
OutMapID: DWORD;
private
function GetCommaText: WideString;
procedure SetCommaText(const Value: WideString);
public
constructor Create;
destructor Destroy; override;
property CommaText: WideString read GetCommaText Write SetCommaText;
end;
// 节点列表
TNodeList = Class(TObjectList)
private
function GetItem(Index: Integer): TNodeInfo;
procedure SetItem(Index: Integer; const Value: TNodeInfo);
public
property Items[Index: Integer]: TNodeInfo read GetItem write SetItem; default;
end;
var
GameMaps: TMapList;
implementation
uses
SysUtils;
//==============================================================================
{ TMapInfo }
// 地图信息
constructor TMapInfo.Create;
begin
self.NodeList := TNodeList.Create;
end;
destructor TMapInfo.Destroy;
begin
self.NodeList.Free;
inherited;
end;
//==============================================================================
{ TMapList }
// 地图列表
constructor TMapList.Create;
// 构造地图列表
begin
inherited;
FStoreList := TStoreList.Create;
FZoneList := TZoneList.Create;
FTransportList := TTransportList.Create;
IniFileName := IDS_InfoFilesPath + IDS_DefaultMapFileName; // 设置默认地图文件
end;
destructor TMapList.Destroy;
// 销毁地图列表
begin
FStoreList.Free;
FZoneList.Free;
FTransportList.Free;
inherited;
end;
function TMapList.ExtractStoreInfo(iniFile: TIniFile; SourceStr: string): TStoreInfo;
// 返回药店信息
var
i, iMedNum, tmpPos, iID, X, Y: integer;
sName: WideString;
tmpStringList: TStringList;
begin
Result := nil; // 初始化对象
tmpPos := Pos(',', SourceStr);
if tmpPos = 0 then Exit;
iID := StrToIntDef(copy(SourceStr, 1, tmppos - 1), -1);
SourceStr := Copy(SourceStr, tmpPos + 1, length(SourceStr) - tmpPos);
tmpPos := Pos(',', SourceStr);
if tmpPos = 0 then Exit;
X := StrToIntDef(copy(SourceStr, 1, tmpPos - 1), -1);
SourceStr := Copy(SourceStr, tmpPos + 1, length(SourceStr) - tmpPos);
tmpPos := Pos(',', SourceStr);
if tmpPos = 0 then Exit;
Y := StrToIntDef(copy(SourceStr, 1, tmppos - 1), -1);
sName := Copy(SourceStr, tmpPos + 1, length(SourceStr) - tmpPos);
Result := TStoreInfo.Create; // 创建对象
tmpStringList := TStringList.Create;
try
iniFile.ReadSectionValues('Store' + IntToStr(iID), tmpStringList);
With Result do begin
ID := iID;
DoctorPosX := X;
DoctorPosY := Y;
Name := sName;
EnteredX := StrToIntDef(tmpStringList.Values['EnteredX'], -1);
EnteredY := StrToIntDef(tmpStringList.Values['EnteredY'], -1);
NursePosX := StrToIntDef(tmpStringList.Values['NursePosX'], -1);
NursePosY := StrToIntDef(tmpStringList.Values['NursePosY'], -1);
iMedNum := StrToIntDef(tmpStringList.Values['Num'], -1);
if iMedNum <= 0 then Exit;
for i := 0 to iMedNum -1 do
Result.MedList.Add(tmpStringList.Values[format('Med%d', [i])]);
end;
finally
tmpStringList.Free;
end;
end;
function TMapList.GetItem(Index: Integer): TMapInfo;
begin
Result := TMapInfo(inherited Items[Index]);
end;
function TMapList.ItemOfMapID(const MapID: LongWord): TMapInfo;
// 获取指定标识的地图信息
var
i: integer;
TmpMap: TMapInfo;
begin
Result := nil;
for i := 0 to Self.Count - 1 do
begin
TmpMap := Self.Items[i];
if TmpMap.ID = 0 then Self.ReadOneMap(i);
if TmpMap.ID = MapID then
begin
Result := TmpMap;
Break;
end;
end;
end;
procedure TMapList.LoadMapList;
// 装载地图列表
var
MapIni: TIniFile;
i, MapNum, iZone: Integer;
tmpMap: TMapInfo;
tmpZone: TZoneInfo;
begin
MapIni := TIniFile.Create(self.FIniFileName);
with MapIni do
try
MapNum := ReadInteger('Main', 'MapNum', 0);
if MapNum = 0 then
Exit;
for i := 0 to MapNum - 1 do
begin
iZone := ReadInteger(format('Map%d', [i]), 'Zone', -1);
if iZone = -1 then Continue; // 没有map[i]
tmpMap := TMapInfo.Create;
tmpMap.ID := 0;
tmpMap.PosInMapList := self.Count; // 在MapList中的序号
tmpMap.NumberOfMapINI := i; // 在Map.ini里面的[map序号]
tmpMap.Zone := iZone; // 地区编号
tmpZone := FZoneList.ItemOfZoneID(iZone);
tmpZone.MapList.Add(tmpMap);
self.Add(tmpMap);
// =========================================
// self.ReadOneMap(tmpMap.PosInMapList); // 装载地图信息
// =========================================
end;
finally
Free;
end;
end;
procedure TMapList.LoadStoreList;
// 装载药店列表
var
i, StoreNum: integer;
tmpStr: WideString;
tmpStringList: TStringList;
tmpStoreInfo: TStoreInfo;
tmpIniFile: TIniFile;
begin
FStoreList.Clear;
tmpIniFile := TIniFile.Create(IDS_InfoFilesPath + IDS_StoreFilename); // 打开药店文件
with tmpIniFile do
try
tmpStringList := TStringList.Create;
try
ReadSectionValues('Store', tmpStringList);
StoreNum := StrToIntDef(tmpStringList.Values['Num'], 0); // 获得药店数目
if StoreNum = 0 then // 药店数为0,退出
Exit;
for i := 0 to StoreNum - 1 do
begin
tmpStr := tmpStringList.Values[format('Store%d', [i])];
tmpStoreInfo := ExtractStoreInfo(tmpIniFile, tmpStr); // 返回药店信息
FStoreList.Add(tmpStoreInfo);
end;
finally
tmpStringList.Free; // 销毁字串列表
end;
finally
Free; // 销毁 INI 对象
end;
end;
procedure TMapList.LoadTransportList;
var
i, j, StepNum: integer;
MapIni: TINIFile;
tmpTransportInfo: TTransportInfo;
tmpStep: TStepInfo;
tmpStr: String;
tmpStringList: TStringList;
begin
MapIni := TIniFile.Create(self.FIniFileName);
try
tmpStringList := TStringList.Create;
try
i := 0;
repeat
i := i + 1;
MapIni.ReadSectionValues(Format('Transport%d', [i]), tmpStringList);
StepNum := StrToIntDef(tmpStringList.Values['StepNum'], 0);
if StepNum < 1 then Break;
tmpTransportInfo := TTransportInfo.Create;
tmpTransportInfo.ID := i;
for j := 0 to StepNum - 1 do
begin
tmpStep := TStepInfo.Create;
tmpStr := tmpStringList.Values[format('Step%d', [j])];
TStepInfo.ExtractStepInfo(tmpStr, tmpStep.Action, tmpStep.X, tmpStep.Y);
tmpTransportInfo.Add(tmpStep);
end;
TransportList.Add(tmpTransportInfo);
until False;
finally
tmpStringList.Free;
end;
finally
MapIni.Free;
end;
end;
procedure TMapList.LoadZoneList;
// 装载地区列表
var
MapIni: TIniFile;
i, ZoneNum: integer;
tmpZone: TZoneInfo;
tmpStringList: TStringList;
begin
FZoneList.Clear;
MapIni := TIniFile.Create(self.FIniFileName);
try
ZoneNum := MapIni.ReadInteger('Zone', 'Num', 0);
if ZoneNum = 0 then
Exit;
tmpStringList := TStringList.Create;
try
tmpStringList.Clear;
MapIni.ReadSectionValues('Zone', tmpStringList);
for i := 0 to ZoneNum - 1 do
begin
tmpZone := TZoneInfo.Create;
tmpZone.Name := tmpStringList.Values[format('Zone%d', [i])];
tmpZone.ID := i;
FZoneList.Add(tmpZone);
end;
finally
tmpStringList.Clear;
tmpStringList.Free;
end;
finally
MapIni.Free;
end;
end;
procedure TMapList.ReadOneMap(PosInMapList: Integer);
// 读入一个地图信息
var
MapIni: TIniFile;
tmpMap: TMapInfo;
i: integer;
tmpNode: TNodeInfo;
tmpStr: WideString;
tmpStringList: TStringList;
begin
tmpMap := Self.Items[PosInMapList];
MapIni := TIniFile.Create(self.FIniFileName);
with MapIni do
try
tmpStringList := TStringList.Create;
try
ReadSectionValues(Format('Map%d', [tmpMap.NumberOfMapINI]), tmpStringList);
tmpMap.Name := tmpStringList.Values['Name'];
tmpMap.ID := StrToIntDef(tmpStringList.Values['ID'], 0);
tmpMap.NodeNum := StrToIntDef(tmpStringList.Values['NodeNum'], 0);
if tmpMap.NodeNum = 0 then Exit; // 节点数为0
for i := 0 to tmpMap.NodeNum - 1 do
begin
tmpStr := tmpStringList.Values[Format('Node%d', [i])];
if tmpStr = '' then Break;
tmpNode := TNodeInfo.Create;
tmpNode.MyMap := tmpMap;
tmpNode.CommaText := tmpStr;
tmpMap.NodeList.Add(tmpNode);
end;
tmpMap.NodeNum := tmpMap.NodeList.Count;
finally
tmpStringList.Clear;
tmpStringList.Free;
end;
finally
Free;
end;
end;
procedure TMapList.SetItem(Index: Integer; Value: TMapInfo);
begin
inherited Items[Index] := Value;
end;
//==============================================================================
{ TNodeInfo }
// 节点信息
constructor TNodeInfo.Create;
begin
end;
destructor TNodeInfo.Destroy;
begin
inherited;
end;
function TNodeInfo.GetCommaText: WideString;
begin
Result := Format('%d, %d, %d', [InHL_X, InHL_Y, OutMapID]);
end;
procedure TNodeInfo.SetCommaText(const Value: WideString);
var
tmpStringList: TStringList;
begin
tmpStringList := TStringList.Create;
try
tmpStringList.CommaText := Value;
if tmpStringList.Count <> 3 then Exit;
Self.InHL_X := StrToIntDef(tmpStringList[0], 0);
Self.InHL_Y := StrToIntDef(tmpStringList[1], 0);
Self.OutMapID := StrToIntDef(tmpStringList[2], 0);
finally
tmpStringList.Free;
end;
end;
//==============================================================================
{ TNodeList }
// 节点列表
function TNodeList.GetItem(Index: Integer): TNodeInfo;
begin
Result := TNodeInfo(inherited Items[Index]);
end;
procedure TNodeList.SetItem(Index: Integer; const Value: TNodeInfo);
begin
inherited Items[Index] := Value;
end;
//==============================================================================
{ TStepInfo }
// 步骤信息
constructor TStepInfo.Create(tmpAct: Integer; tmpX, tmpY, tmpZ: String);
begin
Inherited Create;
Action := tmpAct;
X := tmpX;
Y := tmpY;
Z := tmpZ;
SubStepIndex := 0;
end;
class procedure TStepInfo.ExtractStepInfo(SrcStr: string;
var Action: Integer; var X, Y: string);
var
tmpPos: Integer;
begin
X:='';
Y:='';
tmpPos := Pos(',', SrcStr);
if tmpPos =0 then Exit;
Action := StrToIntDef(copy(SrcStr, 1, tmpPos - 1), -1);
SrcStr := Copy(SrcStr, tmpPos + 1, length(SrcStr) - tmpPos);
tmpPos := Pos(',', SrcStr);
if tmpPos = 0 then Exit;
X := copy(SrcStr, 1, tmpPos - 1);
Y := copy(SrcStr, tmpPos + 1, length(srcstr) - tmpPos);
end;
//==============================================================================
{ TStoreInfo }
// 药店信息
constructor TStoreInfo.Create;
begin
MedList := TStringList.Create;
end;
destructor TStoreInfo.Destroy;
begin
self.MedList.Free;
inherited;
end;
//==============================================================================
{ TStoreList }
// 药店列表
function TStoreList.GetItem(Index: Integer): TStoreInfo;
begin
Result := TStoreInfo(inherited Items[Index]);
end;
procedure TStoreList.SetItem(Index: Integer; const Value: TStoreInfo);
begin
inherited Items[Index] := Value;
end;
//==============================================================================
{ TTransportInfo }
// 地图切换点信息
function TTransportInfo.GetItem(Index: Integer): TStepInfo;
begin
Result := TStepInfo(inherited Items[Index]);
end;
procedure TTransportInfo.SetItem(Index: Integer; const Value: TStepInfo);
begin
inherited Items[Index] := Value;
end;
//==============================================================================
{ TTransportList }
// 地图切换点列表
function TTransportList.GetItem(Index: Integer): TTransportInfo;
begin
Result := TTransportInfo(inherited Items[Index]);
end;
function TTransportList.ItemOfTransportID(
const TransportID: Integer): TTransportInfo;
// 返回指定标识的传送点信息
var
i: Integer;
tmpTrans: TTransportInfo;
begin
Result := nil;
for i := 0 to self.Count - 1 do
begin
tmpTrans := self.Items[i];
if tmpTrans.ID = TransportID then
begin
Result := tmpTrans;
Exit;
end;
end;
end;
procedure TTransportList.SetItem(Index: Integer;
const Value: TTransportInfo);
begin
inherited Items[Index] := Value;
end;
//==============================================================================
{ TZoneInfo }
// 区域信息
constructor TZoneInfo.Create;
begin
MapList := TList.Create;
end;
destructor TZoneInfo.Destroy;
begin
self.MapList.Free;
inherited;
end;
//==============================================================================
{ TZoneList }
// 区域列表
function TZoneList.GetItem(Index: Integer): TZoneInfo;
begin
Result := TZoneInfo(inherited Items[Index]);
end;
function TZoneList.ItemOfZoneID(const ZoneID: Integer): TZoneInfo;
var
i: Integer;
begin
for i := 0 to Self.Count - 1 do
begin
Result := Self.Items[i];
if Result.ID = ZoneID then
Exit;
end;
Result := nil;
end;
procedure TZoneList.SetItem(Index: Integer; const Value: TZoneInfo);
begin
inherited Items[Index] := Value;
end;
initialization
GameMaps := TMapList.Create;
GameMaps.LoadStoreList;
GameMaps.LoadZoneList;
GameMaps.loadMapList;
GameMaps.LoadTransportList;
finalization
GameMaps.Free;
end.
|
{ I.TEXTUL PROBLEMEI.
Fie un graf G=(X,U) oarecare.Sa se determine un arbore de pondere minima
ce trece printr-o muchie u data, folosind algoritmul lui Kruskal nr. 4.
II.SPECIFICATIA.
DATE n -nr de varfuri ale grafului;
m -nr muchiilor grafului
a,b -doua siruri de m componentece codifica reprezentarea
grafului prin lista arcelor;
v -sir de m componente ce contine valorile arcelor;
REZULTATE T -data de tip multime ce contine arcele
arborelui de pondere minima;
III.ALGORITM.
Algoritmui Kruskal4 Este;
( determina un arbore de pondere minima al grafului G=(X,U),
unde X={1,..,n),U=[1..m] muchiile sunt numerotate )
T:=[1..m];
pentru k:=1,m executa
T:=T-[k];
daca conex(X,T)=0 atunci
fie w=U-T+[k] unicul cociclu al acestui graf naconex
fie vv î U-T+[k] de valoare minima
T:=T+[vv];
sfdaca
sfpentru
SfKruskal
functia conex(X,T) este:
pentru k:=1,n executa
(1)modifica (X,T) a.i. k sa fie primul varf
(2)aplica un algoritm Moore-Dijkstra pt calcularea valorilor
minime ale drumurilor de la vf 1 la toate celelalte vf din T;
se determina astfel sirul lambda
(3)pentru i:=1,m executa
daca lambda[i]=infinit
atunci conex:=0 (graful nu e conex pt ca nu exista drum de la
1 la i )
STOP;
sfdaca
sfpentru
sfpentru
IV.TEXTUL SURSA
}
program arbore_pondere_minima;
uses crt;
const w=10; {nr de varfuri}
ww=20; {nr de muchii}
type sir=array[1..ww] of integer;
var n,m,o:integer;
a,b,v:sir;
procedure citire(var n,m:integer;var a,b,v:sir);
var k:integer;
begin
clrscr;
write('Dati nr de varfuri n=');readln(n);
writeln('Introduceti muchiile grafului impreuna cu valorile lor (0=STOP)');
repeat begin
m:=k;
write('muchia :');read(k);
if(k<>0) then begin
write('extremitate initiala :');read(a[k]);
write('extremitate finala :');read(b[k]);
write('valoarea muchiei ',k,' :');read(v[k]);
end;
end;
until k=0;
end;
procedure md(n,m:integer;a,b,v:sir;var l:sir);
var k,i,j,min:integer;
s:set of 2..ww;
begin
l[1]:=0;for i:=2 to n do l[i]:=MaxInt;
s:=[2..n];
for i:=1 to m do begin
if a[i]=1 then l[b[i]]:=v[i];
if b[i]=1 then l[a[i]]:=v[i];
end;
k:=0;
repeat
min:=MaxInt;
for i:=1 to n do
if i in s then
if l[i]<min then begin
min:=l[i];
j:=i;
end;
s:=s-[j];
k:=k+1;
for i:=1 to m do begin
if a[i]=j then
if l[j]+v[i]<l[b[i]] then begin
l[b[i]]:=l[j]+v[i];
s:=s+[b[i]];
end;
if b[i]=j then
if l[j]+v[i]<l[a[i]] then begin
l[a[i]]:=l[j]+v[i];
s:=s+[a[i]];
end;
end;
until (s=[]) or (k>m);
end;
function conex(n,m:integer;a,b,v:sir):integer;
{returneaza 1 daca e conex si 0 in caz contrar}
var i,j,k,t:integer;
a1,b1,l:sir;
procedure sch(m:integer;i:integer;var a1,b1:sir);
var j,k:integer;
begin
if i=1 then
for j:=1 to m do begin a1[j]:=a[j];b1[j]:=b[j];end
else
for j:=1 to m do begin a1[j]:=a[j];b1[j]:=b[j];end;
for j:=1 to m do begin
if a[j]=1 then a1[j]:=i;
if b[j]=1 then b1[j]:=i;
if a[j]=i then a1[j]:=1;
if b[j]=i then b1[j]:=1;
end;
end;
begin
j:=1;
k:=1;
while (j<=m)and(k=1) do begin
sch(m,j,a1,b1);
md(n,m,a1,b1,v,l);
for t:=1 to n do
if l[t]=MaxInt then k:=0;
j:=j+1;
end;
conex:=k;
end;
procedure Kruskal(n,m:integer;a,b,v:sir);
var i,j,k,min,con:integer;
aa,bb,vv:sir;
U,T,U_T,cociclu:set of 1..ww;
begin
U:=[1..m];
T:=[1..m];
for i:=1 to m do begin aa[i]:=a[i];bb[i]:=b[i];end;
for k:=1 to m do begin
aa[k]:=0;bb[k]:=0;T:=T-[k];
con:=conex(n,m,aa,bb,v);
if con=0 then begin
min:=m+1;
v[min]:=MaxInt;
for j:=1 to m do
if j in U-T+[k] then
if v[j]<v[min] then min:=j;
T:=T+[min];
for j:=1 to m do
if(j=min)and (aa[j]=0)and(bb[j]=0) then begin
aa[j]:=a[j];
bb[j]:=b[j];
end;
end;
end;
writeln('Arborele de pondere minima este cel ce contine muchiile:');
for i:=1 to m do
if i in T then write(' ',i)
else write(' ');
end;
begin
citire(n,m,a,b,v);
Kruskal(n,m,a,b,v);
repeat until keypressed;
end. |
//BuyPrice = Exclude, SellPrice = Include PPN
unit uModQuotation;
interface
uses
uModApp, uModSuplier, uModBarang, uModSatuan, System.Generics.Collections;
type
TModQuotationDetail = class;
TModQuotation = class(TModApp)
private
FTransDate: TDatetime;
FEffectiveDate: TDatetime;
FEndDate: TDatetime;
FIsMailer: Integer;
FIsProcessed: Integer;
FRefNo: string;
FRemark: String;
FDetails: TObjectList<TModQuotationDetail>;
FSupplierMerchanGroup: TModSuplierMerchanGroup;
FMerchandise: TModMerchandise;
function GetDetails: TObjectList<TModQuotationDetail>;
public
class function GetTableName: String; override;
property Details: TObjectList<TModQuotationDetail> read GetDetails write
FDetails;
published
property TransDate: TDatetime read FTransDate write FTransDate;
property EffectiveDate: TDatetime read FEffectiveDate write FEffectiveDate;
property EndDate: TDatetime read FEndDate write FEndDate;
property IsMailer: Integer read FIsMailer write FIsMailer;
property IsProcessed: Integer read FIsProcessed write FIsProcessed;
[AttributeOfCode]
property RefNo: string read FRefNo write FRefNo;
property Remark: String read FRemark write FRemark;
[AttributeOfForeign('SUPLIER_MERCHAN_GRUP_ID')]
property SupplierMerchanGroup: TModSuplierMerchanGroup read
FSupplierMerchanGroup write FSupplierMerchanGroup;
[AttributeOfForeign('MERCHANDISE_ID')]
property Merchandise: TModMerchandise read FMerchandise write FMerchandise;
end;
TModQuotationDetail = class(TModApp)
private
FBUYDISC1: Double;
FBarang: TModBarang;
FBarangSupplier: TModBarangSupplier;
FBUYPRICE_INC_PPN: Double;
FSELLDISCPERCENT: Double;
FMargin: Double;
FSELLPRICE: Double;
FQuotation: TModQuotation;
FBUYDISC2: Double;
FBUYDISC3: Double;
FBUYPRICE: Double;
FBUYPRICE_INC_DISC: Double;
FIsUpdateSellPrice: Integer;
FSatuan: TModSatuan;
FSELLDISCRP: Double;
FKonversi: Double;
FPPN: Double;
FIsBKP: Integer;
FIsSellingPrice: Integer;
FTipeHarga: TModTipeHarga;
public
destructor Destroy; override;
class function GetTableName: String; override;
procedure SetBarangHargaJual(aBarangHrgJual: TModBarangHargaJual);
procedure SetBarangSupplier(aBarangSupp: TModBarangSupplier);
published
[AttributeOfHeader]
property Quotation: TModQuotation read FQuotation write FQuotation;
property BUYDISC1: Double read FBUYDISC1 write FBUYDISC1;
property Barang: TModBarang read FBarang write FBarang;
property BarangSupplier: TModBarangSupplier read FBarangSupplier write
FBarangSupplier;
property BUYPRICE_INC_PPN: Double read FBUYPRICE_INC_PPN write
FBUYPRICE_INC_PPN;
property SELLDISCPERCENT: Double read FSELLDISCPERCENT write FSELLDISCPERCENT;
property Margin: Double read FMargin write FMargin;
property SELLPRICE: Double read FSELLPRICE write FSELLPRICE;
property BUYDISC2: Double read FBUYDISC2 write FBUYDISC2;
property BUYDISC3: Double read FBUYDISC3 write FBUYDISC3;
property BUYPRICE: Double read FBUYPRICE write FBUYPRICE;
property BUYPRICE_INC_DISC: Double read FBUYPRICE_INC_DISC write
FBUYPRICE_INC_DISC;
property IsUpdateSellPrice: Integer read FIsUpdateSellPrice write
FIsUpdateSellPrice;
[AttributeOfForeign('SATUAN_ID')]
property Satuan: TModSatuan read FSatuan write FSatuan;
property SELLDISCRP: Double read FSELLDISCRP write FSELLDISCRP;
property Konversi: Double read FKonversi write FKonversi;
property PPN: Double read FPPN write FPPN;
property IsBKP: Integer read FIsBKP write FIsBKP;
property IsSellingPrice: Integer read FIsSellingPrice write FIsSellingPrice;
property TipeHarga: TModTipeHarga read FTipeHarga write FTipeHarga;
end;
implementation
function TModQuotation.GetDetails: TObjectList<TModQuotationDetail>;
begin
if not assigned(FDetails) then
FDetails := Tobjectlist<TModQuotationDetail>.create;
Result := FDetails;
end;
class function TModQuotation.GetTableName: String;
begin
Result := 'Quotation';
end;
destructor TModQuotationDetail.Destroy;
begin
inherited;
end;
class function TModQuotationDetail.GetTableName: String;
begin
Result := 'Quotation_Detail';
end;
procedure TModQuotationDetail.SetBarangSupplier(aBarangSupp:
TModBarangSupplier);
begin
aBarangSupp.BRGSUP_IS_PRIMARY := 1;
aBarangSupp.BRGSUP_IS_ACTIVE := 1;
aBarangSupp.BRGSUP_BUY_PRICE := Self.BUYPRICE;
aBarangSupp.BRGSUP_DISC1 := Self.BUYDISC1;
aBarangSupp.BRGSUP_DISC2 := Self.BUYDISC2;
aBarangSupp.BRGSUP_DISC3 := Self.BUYDISC3;
end;
procedure TModQuotationDetail.SetBarangHargaJual(aBarangHrgJual:
TModBarangHargaJual);
begin
aBarangHrgJual.Barang := TModBarang.CreateID(Self.Barang.ID);
aBarangHrgJual.BHJ_PURCHASE_PRICE := Self.BUYPRICE_INC_DISC;
aBarangHrgJual.BHJ_PPN := Self.PPN;
aBarangHrgJual.BHJ_SELL_PRICE := Self.SELLPRICE;
aBarangHrgJual.BHJ_DISC_PERSEN := Self.SELLDISCPERCENT;
aBarangHrgJual.BHJ_DISC_NOMINAL := Self.SELLDISCRP;
aBarangHrgJual.BHJ_MARK_UP := Self.Margin;
aBarangHrgJual.BHJ_CONV_VALUE := Self.Konversi;
aBarangHrgJual.BHJ_SELL_PRICE_DISC := aBarangHrgJual.BHJ_SELL_PRICE - aBarangHrgJual.BHJ_DISC_NOMINAL;
aBarangHrgJual.TipeHarga := TModTipeHarga.CreateID(Self.TipeHarga.ID);
aBarangHrgJual.Satuan := TModSatuan.CreateID(Self.Satuan.ID);
if Self.IsBKP = 1 then
aBarangHrgJual.BHJ_PPN := Self.PPN
else
aBarangHrgJual.BHJ_PPN := 0;
end;
initialization
//if error "can not instantiate type of uModel.xxxx" occured, register here
TModQuotation.RegisterRTTI;
TModQuotationDetail.RegisterRTTI;
end.
|
unit Work.ImportBooks;
interface
uses
System.JSON,
Plus.TWork,
ExtGUI.ListBox.Books;
type
TImportBooksWork = class (TWork)
private
FBooksConfig: TBooksListBoxConfigurator;
procedure DoImportBooks;
procedure AddNewBookToDataModuleFromWeb(jsBooks: TJSONArray);
procedure SetBooksConfig(const Value: TBooksListBoxConfigurator);
public
procedure Execute; override;
property BooksConfig: TBooksListBoxConfigurator read FBooksConfig write SetBooksConfig;
end;
implementation
{ TImportBooksWork }
uses
ClientAPI.Books,
Consts.Application,
Model.Book,
Data.Main;
procedure TImportBooksWork.AddNewBookToDataModuleFromWeb
(jsBooks: TJSONArray);
var
jsBook: TJSONObject;
b: TBook;
b2: TBook;
i: Integer;
begin
for i := 0 to jsBooks.Count - 1 do
begin
jsBook := jsBooks.Items[i] as TJSONObject;
b := TBook.Create();
// TODO: DodaŠ try-finnaly oraz zwalanie b.Free;
// czyli b przekazywane do InsertNewBook musi byŠ sklonowane
b.LoadFromJSON (jsBook);
b.Validate;
b2 := FBooksConfig.GetBookList(blkAll).FindByISBN(b.isbn);
if not Assigned(b2) then
begin
FBooksConfig.InsertNewBook(b);
// ----------------------------------------------------------------
// Append report into the database:
// Fields: ISBN, Title, Authors, Status, ReleseDate, Pages, Price,
// Currency, Imported, Description
DataModMain.dsBooks.InsertRecord([b.isbn, b.title, b.author, b.status,
b.releseDate, b.pages, b.price, b.currency, b.imported, b.description]);
end
else
b.Free;
end;
end;
procedure TImportBooksWork.DoImportBooks;
var
jsBooks: TJSONArray;
begin
jsBooks := ImportBooksFromWebService(Client_API_Token);
try
AddNewBookToDataModuleFromWeb(jsBooks);
finally
jsBooks.Free;
end;
end;
procedure TImportBooksWork.Execute;
begin
inherited;
DoImportBooks
end;
procedure TImportBooksWork.SetBooksConfig(
const Value: TBooksListBoxConfigurator);
begin
FBooksConfig := Value;
end;
end.
|
unit BaseTovarOperRef;
interface
uses uCommonForm,
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Base, StdCtrls, ToolEdit, Mask, Menus, Db, DBTables, Grids, DBGridEh,
Buttons, ExtCtrls, RXCtrls, MemDS, DBAccess, Ora, ActnList, uOilQuery,
uOilStoredProc, Variants, GridsEh, DBGridEhGrouping;
type
TBaseTovarOperRefForm = class(TBaseForm)
deBeginDate: TDateEdit;
Label1: TLabel;
deEndDate: TDateEdit;
Label7: TLabel;
qChecker: TOilQuery;
N2: TMenuItem;
eFrom: TEdit;
lblFrom: TLabel;
eTo: TEdit;
lblTo: TLabel;
lblProduct: TLabel;
eProduct: TEdit;
dsDetailTank: TOraDataSource;
qDetailTank: TOilQuery;
grDetailTank: TDBGridEh;
pDetailTank: TPanel;
sbBackToMonth: TSpeedButton;
sbFirstD2: TSpeedButton;
lDetailTank: TLabel;
pGridRow: TPanel;
pGridRowDoc: TPanel;
grDetailAuto: TDBGridEh;
procedure bbSearchClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure sbTotalClick(Sender: TObject);
procedure qFilterRecord(DataSet: TDataSet; var Accept: Boolean);
procedure eProductChange(Sender: TObject);
procedure DBGrid1CellClick(Column: TColumnEh);
procedure DBGrid1CheckRowHaveDetailPanel(Sender: TCustomDBGridEh;
var RowHaveDetailPanel: Boolean);
procedure DBGrid1RowDetailPanelShow(Sender: TCustomDBGridEh;
var CanShow: Boolean);
procedure DBGrid1RowDetailPanelHide(Sender: TCustomDBGridEh;
var CanHide: Boolean);
procedure DBGrid1DblClick(Sender: TObject);
procedure sbBackToMonthClick(Sender: TObject);
private
FOnGoToMonth: TNotifyEvent;
FTankFarmName: string;
protected
public
property OnGoToMonth: TNotifyEvent read FOnGoToMonth write FOnGoToMonth;
property TankFarmName: string read FTankFarmName write FTankFarmName;
end;
var
BaseMeteringRefForm: TBaseTovarOperRefForm;
implementation
uses ExFunc, UDbFunc;
{$R *.DFM}
procedure TBaseTovarOperRefForm.bbSearchClick(Sender: TObject);
begin
inherited;
q.Close;
q.ParamByName('BeginDate').asDate := deBeginDate.Date;
q.ParamByName('EndDate').asDate := deEndDate.Date;
q.RestoreSQL;
_OpenQuery(q);
end;
procedure TBaseTovarOperRefForm.FormShow(Sender: TObject);
begin
inherited;
bbSearch.Click;
// cbShowDetail.Checked := True;
// cbShowDetailClick(cbShowDetail);
end;
procedure TBaseTovarOperRefForm.FormCreate(Sender: TObject);
begin
inherited;
SetCurrentMonth(deBeginDate, deEndDate);
end;
procedure TBaseTovarOperRefForm.sbTotalClick(Sender: TObject);
begin
if sbTotal.Down then
dbGrid1.FooterRowCount := 1
else
dbGrid1.FooterRowCount := 0;
DBGridDetail.FooterRowCount := dbGrid1.FooterRowCount;
end;
procedure TBaseTovarOperRefForm.qFilterRecord(DataSet: TDataSet; var Accept: Boolean);
begin
inherited;
Accept := True;
if eProduct.Text <> '' then
Accept := Accept and (pos(AnsiUpperCase(eProduct.Text), AnsiUpperCase(DataSet.FieldBYName('PRODUCT_NAME').AsString)) > 0);
if eFrom.Text <> '' then
Accept := Accept and (pos(AnsiUpperCase(eFrom.Text), AnsiUpperCase(DataSet.FieldBYName('TANK_FROM').AsString)) > 0);
if eTo.Text <> '' then
Accept := Accept and (pos(AnsiUpperCase(eTo.Text), AnsiUpperCase(DataSet.FieldBYName('TANK_TO').AsString)) > 0);
end;
procedure TBaseTovarOperRefForm.eProductChange(Sender: TObject);
begin
inherited;
q.Filtered := False;
q.Filtered := True;
end;
procedure TBaseTovarOperRefForm.DBGrid1CellClick(Column: TColumnEh);
begin
inherited;
if (q.ParamByName('BeginDate').AsDate <> deBeginDate.Date) or(q.ParamByName('EndDate').AsDate <> deEndDate.Date) then
bbSearch.Click;
end;
procedure TBaseTovarOperRefForm.DBGrid1CheckRowHaveDetailPanel(
Sender: TCustomDBGridEh; var RowHaveDetailPanel: Boolean);
begin
inherited;
RowHaveDetailPanel := q.FieldByName('is_have_det').AsInteger = 1;
end;
procedure TBaseTovarOperRefForm.DBGrid1RowDetailPanelShow(
Sender: TCustomDBGridEh; var CanShow: Boolean);
begin
inherited;
if not (q.FieldByName('tank_from').AsString = 'жд приход') then
begin
if not qDetail.Active then
_OpenQueryPar(qDetail,
['BeginDate', q.ParamByName('BeginDate').AsDateTime,
'EndDate', q.ParamByName('EndDate').AsDateTime])
else
// Уже открывается, ждем пока откроется
while qDetail.Active and not qDetail.Fetched do
Sleep(100);
qDetail.Filter :=
' DATE_RASH = ' + QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn:ss', q.FieldByName('TR_DATE').AsDateTime)) +
' and RRA_NUM = ' + q.FieldByName('TANK_FROM').AsString;
qDetail.Filtered := True;
CanShow := (qDetail.RecordCount > 0);
grDetailAuto.Visible:=True;
grDetailTank.Visible:=False;
grDetailAuto.Align:=alClient;
lDetailTank.Caption :=
'Расходы '+FTankFarmName+': Месяц: '+ q.FieldByName('MONYEAR').AsString +' \ Нефтепродукт: '+ q.FieldByName('PRODUCT_NAME').AsString;
// Поместить грид детализацию расходы в панель pGridRow и развернуть
pDetailTank.Parent := pGridRow;
grDetailAuto.Parent := pGridRow;
pBase.Align := alTop;
pGridRow.Align := alClient;
pGridRow.Visible := true;
pBase.Visible := not pGridRow.Visible;
end
else
begin
qDetailTank.Close;
qDetailTank.ParamByName('trans_id').AsInteger := q.FieldByName('transfer_id').AsInteger;
qDetailTank.Open;
CanShow := (qDetailTank.RecordCount > 0);
grDetailAuto.Visible:=False;
grDetailTank.Visible:=True;
grDetailTank.Align:=alClient;
lDetailTank.Caption :=
'Приходы '+FTankFarmName+': Месяц: '+ q.FieldByName('MONYEAR').AsString +' \ Нефтепродукт: '+ q.FieldByName('PRODUCT_NAME').AsString;
// Поместить грид детализацию жд приходы в панель pGridRow и развернуть
pDetailTank.Parent := pGridRow;
grDetailTank.Parent := pGridRow;
pBase.Align := alTop;
pGridRow.Align := alClient;
pGridRow.Visible := true;
pBase.Visible := not pGridRow.Visible;
end;
end;
procedure TBaseTovarOperRefForm.DBGrid1RowDetailPanelHide(
Sender: TCustomDBGridEh; var CanHide: Boolean);
begin
inherited;
qDetail.Close;
qDetailTank.Close;
pDetailTank.Parent := DBGrid1.RowDetailPanelControl;
grDetailTank.Parent := DBGrid1.RowDetailPanelControl;
grDetailAuto.Parent := DBGrid1.RowDetailPanelControl;
pGridRow.Align := alTop;
pBase.Align := alClient;
pGridRow.Visible := false;
pBase.Visible := not pGridRow.Visible;
DBGrid1.RowDetailPanel.Active := true;
end;
procedure TBaseTovarOperRefForm.DBGrid1DblClick(Sender: TObject);
begin
inherited;
if q.FieldByName('is_have_det').AsInteger = 1 then
DBGrid1.RowDetailPanel.Visible := not DBGrid1.RowDetailPanel.Visible;
end;
procedure TBaseTovarOperRefForm.sbBackToMonthClick(Sender: TObject);
begin
inherited;
if Assigned(FOnGoToMonth) then
FOnGoToMonth(Self)
else
begin
DBGrid1.RowDetailPanel.Visible := False;
end;
end;
initialization
RegisterClass(TBaseTovarOperRefForm);
end.
|
unit UDLines;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32;
type
TCrpeLinesDlg = class(TForm)
lblNumber: TLabel;
lbNumbers: TListBox;
lblCount: TLabel;
editCount: TEdit;
cbExtend: TCheckBox;
cbSuppress: TCheckBox;
{Size and Position}
gbSizeAndPosition: TGroupBox;
pnlSize: TPanel;
lblTop: TLabel;
lblLeft: TLabel;
lblBottom: TLabel;
lblRight: TLabel;
editTop: TEdit;
editLeft: TEdit;
editBottom: TEdit;
editRight: TEdit;
rgUnits: TRadioGroup;
lblSectionStart: TLabel;
cbSectionStart: TComboBox;
lblSectionEnd: TLabel;
cbSectionEnd: TComboBox;
{Buttons}
btnOk: TButton;
btnClear: TButton;
ColorDialog1: TColorDialog;
pnlLines: TPanel;
lblLineStyle: TLabel;
lblWidth: TLabel;
lblColor: TLabel;
cbLineStyle: TComboBox;
editWidth: TEdit;
cbColor: TColorBox;
procedure btnClearClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure UpdateLines;
procedure FormCreate(Sender: TObject);
procedure editSizeEnter(Sender: TObject);
procedure editSizeExit(Sender: TObject);
procedure lbNumbersClick(Sender: TObject);
procedure cbColorChange(Sender: TObject);
procedure cbLineStyleChange(Sender: TObject);
procedure editWidthEnter(Sender: TObject);
procedure editWidthExit(Sender: TObject);
procedure cbExtendClick(Sender: TObject);
procedure cbSuppressClick(Sender: TObject);
procedure cbSectionStartChange(Sender: TObject);
procedure cbSectionEndChange(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure rgUnitsClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
LineIndex : smallint;
PrevSize : string;
CustomColor : TColor;
end;
var
CrpeLinesDlg: TCrpeLinesDlg;
bLines : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UCrpeClasses;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.FormCreate(Sender: TObject);
begin
bLines := True;
LoadFormPos(Self);
LineIndex := -1;
btnOk.Tag := 1;
CustomColor := clBlack;
{LineStyle}
cbLineStyle.Clear;
with cbLineStyle.Items do
begin
Add('lsNone');
Add('lsSingle');
Add('lsDouble');
Add('lsDash');
Add('lsDot');
end;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.FormShow(Sender: TObject);
begin
UpdateLines;
end;
{------------------------------------------------------------------------------}
{ UpdateLines }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.UpdateLines;
var
OnOff : boolean;
i : integer;
begin
LineIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Cr.Lines.Count > 0);
{Get Lines Index}
if OnOff then
begin
if Cr.Lines.ItemIndex > -1 then
LineIndex := Cr.Lines.ItemIndex
else
LineIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
{Fill Section ComboBox}
cbSectionStart.Clear;
cbSectionStart.Items.AddStrings(Cr.SectionFormat.Names);
cbSectionEnd.Clear;
cbSectionEnd.Items.AddStrings(Cr.SectionFormat.Names);
{Fill Numbers ListBox}
for i := 0 to Cr.Lines.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Cr.Lines.Count);
lbNumbers.ItemIndex := LineIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TColorBox then
TColorBox(Components[i]).Enabled := OnOff;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.lbNumbersClick(Sender: TObject);
begin
LineIndex := lbNumbers.ItemIndex;
cbLineStyle.ItemIndex := Ord(Cr.Lines[LineIndex].LineStyle);
editWidth.Text := IntToStr(Cr.Lines.Item.Width);
cbColor.Selected := Cr.Lines.Item.Color;
{Format Options}
cbExtend.Checked := Cr.Lines.Item.Extend;
cbSuppress.Checked := Cr.Lines.Item.Suppress;
{Size and Position}
cbSectionStart.ItemIndex := Cr.SectionFormat.IndexOf(Cr.Lines.Item.SectionStart);
cbSectionEnd.ItemIndex := Cr.SectionFormat.IndexOf(Cr.Lines.Item.SectionEnd);
rgUnitsClick(Self);
end;
{------------------------------------------------------------------------------}
{ cbLineStyleChange }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.cbLineStyleChange(Sender: TObject);
begin
Cr.Lines.Item.LineStyle := TCrLineStyle(cbLineStyle.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ editWidthEnter }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.editWidthEnter(Sender: TObject);
begin
PrevSize := editWidth.Text;
end;
{------------------------------------------------------------------------------}
{ editWidthExit }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.editWidthExit(Sender: TObject);
begin
if not IsNumeric(editWidth.Text) then
editWidth.Text := PrevSize
else
Cr.Lines.Item.Width := StrToInt(editWidth.Text);
end;
{------------------------------------------------------------------------------}
{ cbColorChange }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.cbColorChange(Sender: TObject);
begin
Cr.Lines.Item.Color := cbColor.Selected;
end;
{------------------------------------------------------------------------------}
{ editSizeEnter }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.editSizeEnter(Sender: TObject);
begin
if Sender is TEdit then
PrevSize := TEdit(Sender).Text;
end;
{------------------------------------------------------------------------------}
{ editSizeExit }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.editSizeExit(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
if not IsFloating(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.Lines.Item.Top := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editBottom' then
Cr.Lines.Item.Bottom := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.Lines.Item.Left := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editRight' then
Cr.Lines.Item.Right := InchesStrToTwips(TEdit(Sender).Text);
UpdateLines; {this will truncate any decimals beyond 3 places}
end;
end
else {twips}
begin
if not IsNumeric(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.Lines.Item.Top := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editBottom' then
Cr.Lines.Item.Bottom := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.Lines.Item.Left := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editRight' then
Cr.Lines.Item.Right := StrToInt(TEdit(Sender).Text);
end;
end;
end;
{------------------------------------------------------------------------------}
{ rgUnitsClick }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.rgUnitsClick(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
editTop.Text := TwipsToInchesStr(Cr.Lines.Item.Top);
editBottom.Text := TwipsToInchesStr(Cr.Lines.Item.Bottom);
editLeft.Text := TwipsToInchesStr(Cr.Lines.Item.Left);
editRight.Text := TwipsToInchesStr(Cr.Lines.Item.Right);
end
else {twips}
begin
editTop.Text := IntToStr(Cr.Lines.Item.Top);
editBottom.Text := IntToStr(Cr.Lines.Item.Bottom);
editLeft.Text := IntToStr(Cr.Lines.Item.Left);
editRight.Text := IntToStr(Cr.Lines.Item.Right);
end;
end;
{------------------------------------------------------------------------------}
{ cbExtendClick }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.cbExtendClick(Sender: TObject);
begin
Cr.Lines.Item.Extend := cbExtend.Checked;
end;
{------------------------------------------------------------------------------}
{ cbSuppressClick }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.cbSuppressClick(Sender: TObject);
begin
Cr.Lines.Item.Suppress := cbSuppress.Checked;
end;
{------------------------------------------------------------------------------}
{ cbSectionStartChange }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.cbSectionStartChange(Sender: TObject);
begin
Cr.Lines.Item.SectionStart := cbSectionStart.Items[cbSectionStart.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ cbSectionEndChange }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.cbSectionEndChange(Sender: TObject);
begin
Cr.Lines.Item.SectionEnd := cbSectionEnd.Items[cbSectionEnd.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.btnClearClick(Sender: TObject);
begin
Cr.Lines.Clear;
UpdateLines;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.btnOkClick(Sender: TObject);
begin
rgUnits.ItemIndex := 1; {change to twips to avoid the UpdateLines call}
if (not IsStrEmpty(Cr.ReportName)) and (LineIndex > -1) then
begin
editSizeExit(editTop);
editSizeExit(editBottom);
editSizeExit(editLeft);
editSizeExit(editRight);
end;
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeLinesDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bLines := False;
Release;
end;
end.
|
unit uBase1024;
{
Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
}
interface
uses
System.SysUtils, uBase;
function Encode(data: TBytes): String;
function Decode(data: String): TBytes;
Const
DefaultAlphabet: Array [0 .. 1023] of string = ('0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'ª', 'µ', 'º', 'À',
'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï',
'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'Þ', 'ß',
'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î',
'ï', 'ð', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'þ',
'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č',
'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ',
'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī',
'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'ĸ', 'Ĺ', 'ĺ',
'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn',
'Ŋ', 'ŋ', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř',
'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ',
'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ',
'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƀ', 'Ɓ', 'Ƃ', 'ƃ', 'Ƅ', 'ƅ',
'Ɔ', 'Ƈ', 'ƈ', 'Ɖ', 'Ɗ', 'Ƌ', 'ƌ', 'ƍ', 'Ǝ', 'Ə', 'Ɛ', 'Ƒ', 'ƒ', 'Ɠ', 'Ɣ',
'ƕ', 'Ɩ', 'Ɨ', 'Ƙ', 'ƙ', 'ƚ', 'ƛ', 'Ɯ', 'Ɲ', 'ƞ', 'Ɵ', 'Ơ', 'ơ', 'Ƣ', 'ƣ',
'Ƥ', 'ƥ', 'Ʀ', 'Ƨ', 'ƨ', 'Ʃ', 'ƪ', 'ƫ', 'Ƭ', 'ƭ', 'Ʈ', 'Ư', 'ư', 'Ʊ', 'Ʋ',
'Ƴ', 'ƴ', 'Ƶ', 'ƶ', 'Ʒ', 'Ƹ', 'ƹ', 'ƺ', 'ƻ', 'Ƽ', 'ƽ', 'ƾ', 'ƿ', 'ǀ', 'ǁ',
'ǂ', 'ǃ', 'DŽ', 'Dž', 'dž', 'LJ', 'Lj', 'lj', 'NJ', 'Nj', 'nj', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ',
'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'ǝ', 'Ǟ', 'ǟ',
'Ǡ', 'ǡ', 'Ǣ', 'ǣ', 'Ǥ', 'ǥ', 'Ǧ', 'ǧ', 'Ǩ', 'ǩ', 'Ǫ', 'ǫ', 'Ǭ', 'ǭ', 'Ǯ',
'ǯ', 'ǰ', 'DZ', 'Dz', 'dz', 'Ǵ', 'ǵ', 'Ƕ', 'Ƿ', 'Ǹ', 'ǹ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ',
'Ǿ', 'ǿ', 'Ȁ', 'ȁ', 'Ȃ', 'ȃ', 'Ȅ', 'ȅ', 'Ȇ', 'ȇ', 'Ȉ', 'ȉ', 'Ȋ', 'ȋ', 'Ȍ',
'ȍ', 'Ȏ', 'ȏ', 'Ȑ', 'ȑ', 'Ȓ', 'ȓ', 'Ȕ', 'ȕ', 'Ȗ', 'ȗ', 'Ș', 'ș', 'Ț', 'ț',
'Ȝ', 'ȝ', 'Ȟ', 'ȟ', 'Ƞ', 'ȡ', 'Ȣ', 'ȣ', 'Ȥ', 'ȥ', 'Ȧ', 'ȧ', 'Ȩ', 'ȩ', 'Ȫ',
'ȫ', 'Ȭ', 'ȭ', 'Ȯ', 'ȯ', 'Ȱ', 'ȱ', 'Ȳ', 'ȳ', 'ȴ', 'ȵ', 'ȶ', 'ȸ', 'ȹ', 'Ⱥ',
'Ȼ', 'ȼ', 'Ƚ', 'Ⱦ', 'ȿ', 'ɀ', 'Ɂ', 'ɂ', 'Ƀ', 'Ʉ', 'Ʌ', 'Ɇ', 'ɇ', 'Ɉ', 'ɉ',
'Ɋ', 'ɋ', 'Ɍ', 'ɍ', 'Ɏ', 'ɏ', 'ɐ', 'ɑ', 'ɒ', 'ɓ', 'ɔ', 'ɕ', 'ɖ', 'ɗ', 'ɘ',
'ə', 'ɚ', 'ɛ', 'ɜ', 'ɝ', 'ɞ', 'ɟ', 'ɠ', 'ɡ', 'ɢ', 'ɣ', 'ɤ', 'ɥ', 'ɦ', 'ɧ',
'ɨ', 'ɩ', 'ɪ', 'ɫ', 'ɬ', 'ɭ', 'ɮ', 'ɯ', 'ɰ', 'ɱ', 'ɲ', 'ɳ', 'ɴ', 'ɵ', 'ɶ',
'ɷ', 'ɸ', 'ɹ', 'ɺ', 'ɻ', 'ɼ', 'ɽ', 'ɾ', 'ɿ', 'ʀ', 'ʁ', 'ʂ', 'ʃ', 'ʄ', 'ʅ',
'ʆ', 'ʇ', 'ʈ', 'ʉ', 'ʊ', 'ʋ', 'ʌ', 'ʍ', 'ʎ', 'ʏ', 'ʐ', 'ʑ', 'ʒ', 'ʓ', 'ʔ',
'ʕ', 'ʖ', 'ʗ', 'ʘ', 'ʙ', 'ʚ', 'ʛ', 'ʜ', 'ʝ', 'ʞ', 'ʟ', 'ʠ', 'ʡ', 'ʢ', 'ʣ',
'ʤ', 'ʥ', 'ʦ', 'ʧ', 'ʨ', 'ʩ', 'ʪ', 'ʫ', 'ʬ', 'ʭ', 'ʮ', 'ʯ', 'ʰ', 'ʱ', 'ʲ',
'ʳ', 'ʴ', 'ʵ', 'ʶ', 'ʷ', 'ʸ', 'ʹ', 'ʺ', 'ʻ', 'ʼ', 'ʽ', 'ʾ', 'ʿ', 'ˀ', 'ˁ',
'ˆ', 'ˇ', 'ˈ', 'ˉ', 'ˊ', 'ˋ', 'ˌ', 'ˍ', 'ˎ', 'ˏ', 'ː', 'ˑ', 'ˠ', 'ˡ', 'ˢ',
'ˣ', 'ˤ', 'ˬ', 'ˮ', 'ʹ', 'ͺ', 'ͻ', 'ͼ', 'ͽ', 'Ά', 'Έ', 'Ή', 'Ί', 'Ό', 'Ύ',
'Ώ', 'ΐ', 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν',
'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω', 'Ϊ', 'Ϋ', 'ά', 'έ',
'ή', 'ί', 'ΰ', 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ',
'ν', 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω', 'ϊ', 'ϋ',
'ό', 'ύ', 'ώ', 'ϐ', 'ϑ', 'ϒ', 'ϓ', 'ϔ', 'ϕ', 'ϖ', 'ϗ', 'Ϙ', 'ϙ', 'Ϛ', 'ϛ',
'Ϝ', 'ϝ', 'Ϟ', 'ϟ', 'Ϡ', 'ϡ', 'Ϣ', 'ϣ', 'Ϥ', 'ϥ', 'Ϧ', 'ϧ', 'Ϩ', 'ϩ', 'Ϫ',
'ϫ', 'Ϭ', 'ϭ', 'Ϯ', 'ϯ', 'ϰ', 'ϱ', 'ϲ', 'ϳ', 'ϴ', 'ϵ', 'Ϸ', 'ϸ', 'Ϲ', 'Ϻ',
'ϻ', 'ϼ', 'Ͻ', 'Ͼ', 'Ͽ', 'Ѐ', 'Ё', 'Ђ', 'Ѓ', 'Є', 'Ѕ', 'І', 'Ї', 'Ј', 'Љ',
'Њ', 'Ћ', 'Ќ', 'Ѝ', 'Ў', 'Џ', 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ж', 'З', 'И',
'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч',
'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ж',
'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х',
'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я', 'ѐ', 'ё', 'ђ', 'ѓ', 'є',
'ѕ', 'і', 'ї', 'ј', 'љ', 'њ', 'ћ', 'ќ', 'ѝ', 'ў', 'џ', 'Ѡ', 'ѡ', 'Ѣ', 'ѣ',
'Ѥ', 'ѥ', 'Ѧ', 'ѧ', 'Ѩ', 'ѩ', 'Ѫ', 'ѫ', 'Ѭ', 'ѭ', 'Ѯ', 'ѯ', 'Ѱ', 'ѱ', 'Ѳ',
'ѳ', 'Ѵ', 'ѵ', 'Ѷ', 'ѷ', 'Ѹ', 'ѹ', 'Ѻ', 'ѻ', 'Ѽ', 'ѽ', 'Ѿ', 'ѿ', 'Ҁ', 'ҁ',
'Ҋ', 'ҋ', 'Ҍ', 'ҍ', 'Ҏ', 'ҏ', 'Ґ', 'ґ', 'Ғ', 'ғ', 'Ҕ', 'ҕ', 'Җ', 'җ', 'Ҙ',
'ҙ', 'Қ', 'қ', 'Ҝ', 'ҝ', 'Ҟ', 'ҟ', 'Ҡ', 'ҡ', 'Ң', 'ң', 'Ҥ', 'ҥ', 'Ҧ', 'ҧ',
'Ҩ', 'ҩ', 'Ҫ', 'ҫ', 'Ҭ', 'ҭ', 'Ү', 'ү', 'Ұ', 'ұ', 'Ҳ', 'ҳ', 'Ҵ', 'ҵ', 'Ҷ',
'ҷ', 'Ҹ', 'ҹ', 'Һ', 'һ', 'Ҽ', 'ҽ', 'Ҿ', 'ҿ', 'Ӏ', 'Ӂ', 'ӂ', 'Ӄ', 'ӄ', 'Ӆ',
'ӆ', 'Ӈ', 'ӈ', 'Ӊ', 'ӊ', 'Ӌ', 'ӌ', 'Ӎ', 'ӎ', 'ӏ', 'Ӑ', 'ӑ', 'Ӓ', 'ӓ', 'Ӕ',
'ӕ', 'Ӗ', 'ӗ', 'Ә', 'ә', 'Ӛ', 'ӛ', 'Ӝ', 'ӝ', 'Ӟ', 'ӟ', 'Ӡ', 'ӡ', 'Ӣ', 'ӣ',
'Ӥ', 'ӥ', 'Ӧ', 'ӧ', 'Ө', 'ө', 'Ӫ', 'ӫ', 'Ӭ', 'ӭ', 'Ӯ', 'ӯ', 'Ӱ', 'ӱ', 'Ӳ',
'ӳ', 'Ӵ', 'ӵ', 'Ӷ', 'ӷ', 'Ӹ', 'ӹ', 'Ӻ', 'ӻ', 'Ӽ', 'ӽ', 'Ӿ', 'ӿ', 'Ԁ', 'ԁ',
'Ԃ', 'ԃ', 'Ԅ', 'ԅ', 'Ԇ', 'ԇ', 'Ԉ', 'ԉ', 'Ԋ', 'ԋ', 'Ԍ', 'ԍ', 'Ԏ', 'ԏ', 'Ԑ',
'ԑ', 'Ԓ', 'ԓ', 'Ԛ', 'ԛ', 'Ԝ', 'ԝ', 'Ա', 'Բ', 'Գ', 'Դ', 'Ե', 'Զ', 'Է', 'Ը',
'Թ', 'Ժ', 'Ի', 'Լ', 'Խ', 'Ծ', 'Կ', 'Հ', 'Ձ', 'Ղ', 'Ճ', 'Մ', 'Յ', 'Ն', 'Շ',
'Ո', 'Չ', 'Պ', 'Ջ', 'Ռ', 'Ս', 'Վ', 'Տ', 'Ր', 'Ց', 'Ւ', 'Փ', 'Ք');
DefaultSpecial = '=';
implementation
function Encode(data: TBytes): String;
var
dataLength, i, x1, x2, x3, x4, x5, length5, tempInt: Integer;
tempResult: TStringBuilder;
begin
if ((data = nil) or (Length(data) = 0)) then
begin
Exit('');
end;
dataLength := Length(data);
tempResult := TStringBuilder.Create;
tempResult.Clear;
try
length5 := (dataLength div 5) * 5;
i := 0;
while i < length5 do
begin
x1 := data[i];
x2 := data[i + 1];
x3 := data[i + 2];
x4 := data[i + 3];
x5 := data[i + 4];
tempResult.Append(DefaultAlphabet[x1 or ((x2 and $03) shl 8)]);
tempResult.Append(DefaultAlphabet[(x2 shr 2) or ((x3 and $0F) shl 6)]);
tempResult.Append(DefaultAlphabet[(x3 shr 4) or ((x4 and $3F) shl 4)]);
tempResult.Append(DefaultAlphabet[(x4 shr 6) or (x5 shl 2)]);
inc(i, 5);
end;
tempInt := dataLength - length5;
Case tempInt of
1:
begin
x1 := data[i];
tempResult.Append(DefaultAlphabet[x1]);
tempResult.Append(DefaultSpecial, 4);
end;
2:
begin
x1 := data[i];
x2 := data[i + 1];
tempResult.Append(DefaultAlphabet[x1 or ((x2 and $03) shl 8)]);
tempResult.Append(DefaultAlphabet[x2 shr 2]);
tempResult.Append(DefaultSpecial, 3);
end;
3:
begin
x1 := data[i];
x2 := data[i + 1];
x3 := data[i + 2];
tempResult.Append(DefaultAlphabet[x1 or ((x2 and $03) shl 8)]);
tempResult.Append(DefaultAlphabet[(x2 shr 2) or
((x3 and $0F) shl 6)]);
tempResult.Append(DefaultAlphabet[x3 shr 4]);
tempResult.Append(DefaultSpecial, 2);
end;
4:
begin
x1 := data[i];
x2 := data[i + 1];
x3 := data[i + 2];
x4 := data[i + 3];
tempResult.Append(DefaultAlphabet[x1 or ((x2 and $03) shl 8)]);
tempResult.Append(DefaultAlphabet[(x2 shr 2) or
((x3 and $0F) shl 6)]);
tempResult.Append(DefaultAlphabet[(x3 shr 4) or
((x4 and $3F) shl 4)]);
tempResult.Append(DefaultAlphabet[x4 shr 6]);
tempResult.Append(DefaultSpecial);
end;
end;
result := tempResult.ToString;
finally
tempResult.Free;
end;
end;
function Decode(data: String): TBytes;
var
lastSpecialInd, tailLength, i, srcInd, x1, x2, x3, x4, length5: Integer;
begin
if isNullOrEmpty(data) then
begin
SetLength(result, 1);
result := Nil;
Exit;
end;
lastSpecialInd := Length(data);
while (data[lastSpecialInd] = DefaultSpecial) do
begin
dec(lastSpecialInd);
end;
tailLength := Length(data) - lastSpecialInd;
SetLength(result, Length(data) div 4 * 5 - tailLength);
i := 0;
srcInd := 0;
length5 := (Length(data) div 4 - 1) * 5;
Base(Length(DefaultAlphabet), DefaultAlphabet, DefaultSpecial);
while i < length5 do
begin
inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x3 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x4 := InvAlphabet[Ord(data[srcInd])];
result[i] := Byte(x1);
result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2));
result[i + 2] := Byte((x2 shr 6) and $0F or (x3 shl 4));
result[i + 3] := Byte((x3 shr 4) and $3F or (x4 shl 6));
result[i + 4] := Byte(x4 shr 2);
inc(i, 5);
end;
if (tailLength = 0) then
begin
inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x3 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x4 := InvAlphabet[Ord(data[srcInd])];
result[i] := Byte(x1);
result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2));
result[i + 2] := Byte((x2 shr 6) and $0F or (x3 shl 4));
result[i + 3] := Byte((x3 shr 4) and $3F or (x4 shl 6));
result[i + 4] := Byte(x4 shr 2);
end;
Case (tailLength) of
4:
begin
inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
result[i] := Byte(x1);
end;
3:
begin
inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
result[i] := Byte(x1);
result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2));
end;
2:
begin
inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x3 := InvAlphabet[Ord(data[srcInd])];
result[i] := Byte(x1);
result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2));
result[i + 2] := Byte((x2 shr 6) and $0F or (x3 shl 4));
end;
1:
begin
inc(srcInd);
x1 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x2 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x3 := InvAlphabet[Ord(data[srcInd])];
inc(srcInd);
x4 := InvAlphabet[Ord(data[srcInd])];
result[i] := Byte(x1);
result[i + 1] := Byte((x1 shr 8) and $03 or (x2 shl 2));
result[i + 2] := Byte((x2 shr 6) and $0F or (x3 shl 4));
result[i + 3] := Byte((x3 shr 4) and $3F or (x4 shl 6));
end;
end;
result := result;
end;
end.
|
{******************************************************************************}
{ }
{ Icon Fonts ImageList: An extended ImageList for Delphi }
{ to simplify use of Icons (resize, colors and more...) }
{ }
{ Copyright (c) 2019 (Ethea S.r.l.) }
{ Contributors: }
{ Carlo Barazzetta }
{ Nicola Tambascia }
{ }
{ https://github.com/EtheaDev/IconFontsImageList }
{ }
{******************************************************************************}
{ }
{ 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 IconFontsImageList;
interface
{$INCLUDE IconFontsImageList.inc}
uses
Classes
, ImgList
, Windows
, Graphics
, Forms
, Messaging;
type
TIconFontsImageList = class;
TIconFontItem = class(TCollectionItem)
private
FFontName: TFontName;
FCharacter: Char;
FFontColor: TColor;
FMaskColor: TColor;
FIconName: string;
procedure SetFontColor(const AValue: TColor);
procedure SetFontName(const AValue: TFontName);
procedure SetMaskColor(const AValue: TColor);
procedure SetIconName(const AValue: string);
procedure SetCharacter(const AValue: char);
procedure SetFontIconHex(const AValue: string);
procedure SetFontIconDec(const AValue: Integer);
function GetFontIconDec: Integer;
function GetFontIconHex: string;
procedure Changed;
function GetCharacter: char;
procedure UpdateIconAttributes(const AFontColor, AMaskColor: TColor;
const AFontName: string = ''; const AReplace: Boolean = True);
function GetIconFontsImageList: TIconFontsImageList;
function StoreFontColor: Boolean;
function StoreMaskColor: Boolean;
function StoreFontName: Boolean;
public
function GetDisplayName: string; override;
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property IconFontsImageList: TIconFontsImageList read GetIconFontsImageList;
property FontIconDec: Integer read GetFontIconDec write SetFontIconDec stored false;
property FontIconHex: string read GetFontIconHex write SetFontIconHex stored false;
property FontName: TFontName read FFontName write SetFontName stored StoreFontName;
property FontColor: TColor read FFontColor write SetFontColor stored StoreFontColor;
property MaskColor: TColor read FMaskColor write SetMaskColor stored StoreMaskColor;
property IconName: string read FIconName write SetIconName;
property Character: char read GetCharacter write SetCharacter default #0;
end;
{TIconFontItems}
TIconFontItems = class(TOwnedCollection)
private
function GetItem(AIndex: Integer): TIconFontItem;
procedure SetItem(AIndex: Integer; const Value: TIconFontItem);
procedure UpdateImage(const AIndex: Integer);
function GetIconFontsImageList: TIconFontsImageList;
protected
procedure Notify(Item: TCollectionItem; Action: TCollectionNotification); override;
public
function Add: TIconFontItem;
procedure Assign(Source: TPersistent); override;
function Insert(AIndex: Integer): TIconFontItem;
FUNCTION GetIconByName(const AIconName: string): TIconFontItem;
property IconFontsImageList: TIconFontsImageList read GetIconFontsImageList;
property Items[Index: Integer]: TIconFontItem read GetItem write SetItem; default;
end;
{TIconFontsImageList}
TIconFontsImageList = class(TCustomImageList)
private
FStopDrawing: Integer;
FIconFontItems: TIconFontItems;
FFontName: TFontName;
FMaskColor: TColor;
FFontColor: TColor;
{$IFDEF HiDPISupport}
FScaled: Boolean;
FDPIChangedMessageID: Integer;
{$ENDIF}
{$IFDEF NeedStoreBitmapProperty}
FStoreBitmap: Boolean;
{$ENDIF}
procedure SetIconSize(const ASize: Integer);
procedure SetIconFontItems(const AValue: TIconFontItems);
procedure UpdateImage(const AIndex: Integer);
procedure ClearImages;
procedure DrawFontIcon(const AIndex: Integer; const ABitmap: TBitmap;
const AAdd: Boolean);
procedure SetFontColor(const AValue: TColor);
procedure SetFontName(const AValue: TFontName);
procedure SetMaskColor(const AValue: TColor);
procedure StopDrawing(const AStop: Boolean);
function GetSize: Integer;
procedure SetSize(const AValue: Integer);
function GetHeight: Integer;
function GetWidth: Integer;
procedure SetHeight(const AValue: Integer);
procedure SetWidth(const AValue: Integer);
{$IFDEF HiDPISupport}
procedure DPIChangedMessageHandler(const Sender: TObject; const Msg: Messaging.TMessage);
{$ENDIF}
protected
{$IFDEF NeedStoreBitmapProperty}
procedure DefineProperties(Filer: TFiler); override;
procedure ReadData(Stream: TStream); override;
procedure WriteData(Stream: TStream); override;
{$ENDIF}
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Delete(const AIndex: Integer);
procedure Replace(const AIndex: Integer; const AChar: Char;
const AFontName: TFontName = ''; const AFontColor: TColor = clNone;
AMaskColor: TColor = clNone);
procedure AddIcon(const AChar: Char; const AFontName: TFontName = '';
const AFontColor: TColor = clNone; const AMaskColor: TColor = clNone); virtual;
//Multiple icons methods
function AddIcons(const AFrom, ATo: Char; const AFontName: TFontName = '';
const AFontColor: TColor = clNone; AMaskColor: TColor = clNone): Integer; virtual;
procedure UpdateIconsAttributes(const AFontColor, AMaskColor: TColor;
const AFontName: string = ''; const AReplace: Boolean = True); virtual;
procedure ClearIcons; virtual;
procedure RedrawImages; virtual;
property Width: Integer read GetWidth write SetWidth;
property Height: Integer read GetHeight write SetHeight;
published
//Publishing properties of Custom Class
property OnChange;
//New properties
property IconFontItems: TIconFontItems read FIconFontItems write SetIconFontItems;
property FontName: TFontName read FFontName write SetFontName;
property FontColor: TColor read FFontColor write SetFontColor default clNone;
property MaskColor: TColor read FMaskColor write SetMaskColor default clNone;
property Size: Integer read GetSize write SetSize default 16;
{$IFDEF NeedStoreBitmapProperty}
property StoreBitmap: Boolean read FStoreBitmap write FStoreBitmap default False;
{$ELSE}
property StoreBitmap default False;
{$ENDIF}
/// <summary>
/// Enable and disable scaling with form
/// </summary>
{$IFDEF HiDPISupport}
property Scaled: Boolean read FScaled write FScaled default True;
{$ENDIF}
end;
implementation
uses
SysUtils
, StrUtils;
{ TIconFontItem }
procedure TIconFontItem.Assign(Source: TPersistent);
begin
if Source is TIconFontItem then
begin
FFontName := TIconFontItem(Source).FFontName;
FCharacter := TIconFontItem(Source).FCharacter;
FFontColor := TIconFontItem(Source).FFontColor;
FMaskColor := TIconFontItem(Source).FMaskColor;
FIconName := TIconFontItem(Source).FIconName;
end
else
inherited Assign(Source);
end;
constructor TIconFontItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FCharacter := Chr(0);
FFontColor := clNone;
FMaskColor := clNone;
end;
destructor TIconFontItem.Destroy;
begin
inherited Destroy;
end;
function TIconFontItem.StoreFontColor: Boolean;
begin
Result := Assigned(IconFontsImageList) and
(FFontColor <> IconFontsImageList.FFontColor) and
(FFontColor <> clNone);
end;
function TIconFontItem.StoreFontName: Boolean;
begin
Result := Assigned(IconFontsImageList) and
(FFontName <> IconFontsImageList.FFontName) and
(FFontName <> '');
end;
function TIconFontItem.StoreMaskColor: Boolean;
begin
Result := Assigned(IconFontsImageList) and
(FMaskColor <> IconFontsImageList.FMaskColor) and
(FMaskColor <> clNone);
end;
function TIconFontItem.GetCharacter: char;
begin
Result := FCharacter;
end;
function TIconFontItem.GetDisplayName: string;
begin
Result := Format('%s - Hex: %s%s',
[FFontName, FontIconHex, ifthen(FIconName<>'', ' - ('+FIconName+')', '')]);
end;
function TIconFontItem.GetFontIconDec: Integer;
begin
Result := ord(FCharacter);
end;
function TIconFontItem.GetFontIconHex: string;
begin
Result := IntToHex(Ord(FCharacter), 4);
end;
function TIconFontItem.GetIconFontsImageList: TIconFontsImageList;
begin
if Assigned(Collection) then
Result := TIconFontItems(Collection).IconFontsImageList
else
Result := nil;
end;
procedure TIconFontItem.SetCharacter(const AValue: char);
begin
if AValue <> FCharacter then
begin
FCharacter := AValue;
Changed;
end;
end;
procedure TIconFontItem.SetFontColor(const AValue: TColor);
begin
if AValue <> FFontColor then
begin
FFontColor := AValue;
Changed;
end;
end;
procedure TIconFontItem.SetFontIconDec(const AValue: Integer);
begin
Character := Chr(AValue);
end;
procedure TIconFontItem.SetFontIconHex(const AValue: string);
begin
if (Length(AValue) = 4) or (Length(AValue)=0) then
Character := Chr(StrToInt('$' + AValue));
end;
procedure TIconFontItem.SetFontName(const AValue: TFontName);
begin
if AValue <> FFontName then
begin
FFontName := AValue;
if IconFontsImageList.FontName = '' then
IconFontsImageList.FontName := FFontName;
Changed;
end;
end;
procedure TIconFontItem.SetIconName(const AValue: string);
begin
FIconName := AValue;
end;
procedure TIconFontItem.SetMaskColor(const AValue: TColor);
begin
if AValue <> FMaskColor then
begin
FMaskColor := AValue;
Changed;
end;
end;
procedure TIconFontItem.UpdateIconAttributes(const AFontColor, AMaskColor: TColor;
const AFontName: string = ''; const AReplace: Boolean = True);
begin
if (FFontColor <> AFontColor) or (FMaskColor <> AMaskColor) then
begin
if AReplace then
begin
FFontColor := AFontColor;
FMaskColor := AMaskColor;
if AFontName <> '' then
FFontName := AFontName;
end;
Changed;
end;
end;
procedure TIconFontItem.Changed;
begin
if Assigned(Collection) then
TIconFontItems(Collection).UpdateImage(Index);
end;
{ TIconFontsImageList }
procedure TIconFontsImageList.ClearIcons;
begin
StopDrawing(True);
try
FIconFontItems.Clear;
Clear;
finally
StopDrawing(False);
end;
end;
procedure TIconFontsImageList.ClearImages;
begin
StopDrawing(True);
try
while Count > 0 do
inherited Delete(0);
finally
StopDrawing(False);
end;
end;
constructor TIconFontsImageList.Create(AOwner: TComponent);
begin
inherited;
FStopDrawing := 0;
FFontColor := clNone;
FMaskColor := clNone;
FIconFontItems := TIconFontItems.Create(Self, TIconFontItem);
StoreBitmap := False;
{$IFDEF HiDPISupport}
FScaled := True;
FDPIChangedMessageID := TMessageManager.DefaultManager.SubscribeToMessage(TChangeScaleMessage, DPIChangedMessageHandler);
{$ENDIF}
end;
procedure TIconFontsImageList.Delete(const AIndex: Integer);
begin
//Don't call inherited method of ImageList, to avoid errors
if Assigned(IconFontItems) then
IconFontItems.Delete(AIndex);
end;
destructor TIconFontsImageList.Destroy;
begin
{$IFDEF HiDPISupport}
TMessageManager.DefaultManager.Unsubscribe(TChangeScaleMessage, FDPIChangedMessageID);
{$ENDIF}
FreeAndNil(FIconFontItems);
inherited;
end;
{$IFDEF HiDPISupport}
procedure TIconFontsImageList.DPIChangedMessageHandler(const Sender: TObject;
const Msg: Messaging.TMessage);
var
W: Integer;
//H: Integer;
begin
if FScaled and (TChangeScaleMessage(Msg).Sender = Owner) then
begin
W := MulDiv(Width, TChangeScaleMessage(Msg).M, TChangeScaleMessage(Msg).D);
//H := MulDiv(Height, TChangeScaleMessage(Msg).M, TChangeScaleMessage(Msg).D);
FScaling := True;
try
SetSize(W);
finally
FScaling := False;
end;
end;
end;
{$ENDIF}
procedure TIconFontsImageList.SetFontColor(const AValue: TColor);
begin
if FFontColor <> AValue then
begin
FFontColor := AValue;
UpdateIconsAttributes(FFontColor, FMaskColor, FFontName, False);
end;
end;
procedure TIconFontsImageList.SetFontName(const AValue: TFontName);
begin
if FFontName <> AValue then
begin
FFontName := AValue;
UpdateIconsAttributes(FFontColor, FMaskColor, FFontName, False);
end;
end;
procedure TIconFontsImageList.SetHeight(const AValue: Integer);
begin
SetIconSize(AValue);
end;
procedure TIconFontsImageList.SetIconFontItems(const AValue: TIconFontItems);
begin
FIconFontItems := AValue;
end;
procedure TIconFontsImageList.SetIconSize(const ASize: Integer);
begin
if Width <> ASize then
inherited Width := ASize;
if Height <> ASize then
inherited Height := ASize;
end;
procedure TIconFontsImageList.SetMaskColor(const AValue: TColor);
begin
if FMaskColor <> AValue then
begin
FMaskColor := AValue;
UpdateIconsAttributes(FFontColor, FMaskColor, FFontName, False);
end;
end;
procedure TIconFontsImageList.SetSize(const AValue: Integer);
begin
if (AValue <> Height) or (AValue <> Width) then
begin
StopDrawing(True);
try
SetIconSize(AValue);
finally
StopDrawing(False);
end;
ClearImages;
RedrawImages;
end;
end;
procedure TIconFontsImageList.SetWidth(const AValue: Integer);
begin
SetIconSize(AValue);
end;
procedure TIconFontsImageList.StopDrawing(const AStop: Boolean);
begin
if AStop then
Inc(FStopDrawing)
else
Dec(FStopDrawing);
end;
procedure TIconFontsImageList.AddIcon(const AChar: Char;
const AFontName: TFontName = ''; const AFontColor: TColor = clNone;
const AMaskColor: TColor = clNone);
var
LIconFontItem: TIconFontItem;
begin
LIconFontItem := FIconFontItems.Add;
LIconFontItem.FCharacter := AChar;
if AFontName <> '' then
LIconFontItem.FFontName := AFontName;
if AFontColor <> clNone then
LIconFontItem.FFontColor := AFontColor;
if AMaskColor <> clNone then
LIconFontItem.FMaskColor := AMaskColor;
end;
function TIconFontsImageList.AddIcons(const AFrom, ATo: Char;
const AFontName: TFontName = '';
const AFontColor: TColor = clNone; AMaskColor: TColor = clNone): Integer;
var
LChar: Char;
begin
StopDrawing(True);
try
Result := 0;
for LChar := AFrom to ATo do
begin
AddIcon(LChar, AFontName, AFontColor, AMaskColor);
Inc(Result);
end;
finally
StopDrawing(False);
end;
ClearImages;
RedrawImages;
end;
procedure TIconFontsImageList.Assign(Source: TPersistent);
begin
if Source is TIconFontsImageList then
begin
FFontName := TIconFontsImageList(Source).FontName;
FFontColor := TIconFontsImageList(Source).FontColor;
FMaskColor := TIconFontsImageList(Source).FMaskColor;
StoreBitmap := TIconFontsImageList(Source).StoreBitmap;
Height := TIconFontsImageList(Source).Height;
FIconFontItems.Assign(TIconFontsImageList(Source).FIconFontItems);
end
else
inherited;
end;
procedure TIconFontsImageList.DrawFontIcon(const AIndex: Integer;
const ABitmap: TBitmap; const AAdd: Boolean);
var
LIconFontItem: TIconFontItem;
CharWidth: Integer;
CharHeight: Integer;
LCharacter: Char;
LFontName: string;
LMaskColor, LFontColor: TColor;
begin
if FStopDrawing > 0 then
Exit;
if Assigned(ABitmap) then
begin
LIconFontItem := IconFontItems.GetItem(AIndex);
//Default values from ImageList if not supplied from Item
if LIconFontItem.FMaskColor <> clNone then
LMaskColor := LIconFontItem.FMaskColor
else
LMaskColor := FMaskColor;
if LIconFontItem.FFontColor <> clNone then
LFontColor := LIconFontItem.FFontColor
else
LFontColor := FFontColor;
if LIconFontItem.FFontName <> '' then
LFontName := LIconFontItem.FFontName
else
LFontName := FFontName;
LCharacter := LIconFontItem.Character;
ABitmap.Width := Width;
ABitmap.Height := Height;
with ABitmap.Canvas do
begin
Font.Name := LFontName;
Font.Height := Height;
Font.Color := LFontColor;
Brush.Color := LMaskColor;
FillRect(Rect(0, 0, Width, Height));
CharWidth := TextWidth(LCharacter);
CharHeight := TextHeight(LCharacter);
TextOut((Width - CharWidth) div 2, (Height - CharHeight) div 2, LCharacter);
end;
if AAdd then
AddMasked(ABitmap, LMaskColor)
else
ReplaceMasked(AIndex, ABitmap, LMaskColor);
end;
end;
function TIconFontsImageList.GetHeight: Integer;
begin
Result := inherited Height;
end;
function TIconFontsImageList.GetSize: Integer;
begin
Result := inherited Width;
end;
function TIconFontsImageList.GetWidth: Integer;
begin
Result := inherited Width;
end;
procedure TIconFontsImageList.Loaded;
begin
inherited;
if not StoreBitmap then
RedrawImages;
end;
procedure TIconFontsImageList.UpdateIconsAttributes(const AFontColor,
AMaskColor: TColor; const AFontName: string = '';
const AReplace: Boolean = True);
var
I: Integer;
LIconFontItem: TIconFontItem;
begin
if (AFontColor <> clNone) and (AMaskColor <> clNone) then
begin
FFontColor := AFontColor;
FMaskColor := AMaskColor;
for I := 0 to IconFontItems.Count -1 do
begin
LIconFontItem := IconFontItems.Items[I];
LIconFontItem.UpdateIconAttributes(FFontColor, FMaskColor, AFontName, AReplace);
end;
end;
end;
procedure TIconFontsImageList.UpdateImage(const AIndex: Integer);
var
LBitmap: TBitmap;
begin
if (Height = 0) or (Width = 0) then
Exit;
LBitmap := TBitmap.Create;
try
DrawFontIcon(AIndex, LBitmap, Count <= AIndex);
Self.Change;
finally
LBitmap.Free;
end;
end;
procedure TIconFontsImageList.RedrawImages;
var
I: Integer;
LBitmap: TBitmap;
begin
if not Assigned(FIconFontItems) or
(csLoading in ComponentState) or
(csDestroying in ComponentState) then
Exit;
inherited Clear;
LBitmap := TBitmap.Create;
try
for I := 0 to FIconFontItems.Count -1 do
DrawFontIcon(I, LBitmap, True);
Self.Change;
finally
LBitmap.Free;
end;
end;
procedure TIconFontsImageList.Replace(const AIndex: Integer; const AChar: Char;
const AFontName: TFontName; const AFontColor: TColor; AMaskColor: TColor);
var
LIconFontItem: TIconFontItem;
begin
LIconFontItem := IconFontItems.GetItem(AIndex);
if Assigned(LIconFontItem) then
begin
LIconFontItem.Character := AChar;
LIconFontItem.UpdateIconAttributes(AFontColor, AMaskColor,
AFontName, True);
end;
end;
{$IFDEF NeedStoreBitmapProperty}
procedure TIconFontsImageList.ReadData(Stream: TStream);
begin
if FStoreBitmap then
inherited;
end;
procedure TIconFontsImageList.WriteData(Stream: TStream);
begin
if FStoreBitmap then
inherited;
end;
procedure TIconFontsImageList.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
end;
{$ENDIF}
{ TIconFontItems }
function TIconFontItems.Add: TIconFontItem;
begin
Result := TIconFontItem(inherited Add);
end;
procedure TIconFontItems.Assign(Source: TPersistent);
begin
if (Source is TIconFontItems) and (IconFontsImageList <> nil) then
begin
IconFontsImageList.StopDrawing(True);
try
inherited;
finally
IconFontsImageList.StopDrawing(False);
end;
IconFontsImageList.RedrawImages;
end
else
inherited;
end;
function TIconFontItems.GetIconByName(const AIconName: string): TIconFontItem;
var
I: Integer;
LIconFontItem: TIconFontItem;
begin
Result := nil;
for I := 0 to Count -1 do
begin
LIconFontItem := Items[I];
if SameText(LIconFontItem.IconName, AIconName) then
begin
Result := LIconFontItem;
Break;
end;
end;
end;
function TIconFontItems.GetIconFontsImageList: TIconFontsImageList;
begin
if Owner <> nil then
Result := TIconFontsImageList(Owner)
else
Result := nil;
end;
function TIconFontItems.GetItem(AIndex: Integer): TIconFontItem;
begin
Result := TIconFontItem(inherited GetItem(AIndex));
end;
function TIconFontItems.Insert(AIndex: Integer): TIconFontItem;
begin
Result := TIconFontItem(inherited Insert(AIndex));
IconFontsImageList.RedrawImages;
end;
procedure TIconFontItems.Notify(Item: TCollectionItem;
Action: TCollectionNotification);
begin
inherited;
if (Owner <> nil) and (IconFontsImageList.FStopDrawing = 0) and
(Action in [cnExtracting, cnDeleting]) then
TIconFontsImageList(Owner).RedrawImages;
end;
procedure TIconFontItems.SetItem(AIndex: Integer;
const Value: TIconFontItem);
begin
inherited SetItem(AIndex, Value);
end;
procedure TIconFontItems.UpdateImage(const AIndex: Integer);
begin
if Owner <> nil then
TIconFontsImageList(Owner).UpdateImage(AIndex);
end;
end.
|
unit Pedidos;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, ComCtrls, DB, SqlExpr, DBClient,
StrUtils, Math, Controle, Clientes, PedidosProdutos;
type
TPedidos = class
private
iNumeroPedido: integer;
dtDtEmissao: TDate;
iCliente: integer;
sNomeCliente: string;
nVlrTotal: double;
iOldNumeroPedido: integer;
dtOldDtEmissao: TDate;
iOldCliente: integer;
nOldVlrTotal: double;
oClientes: TClientes;
oPedidosProdutos: TPedidosProdutos;
function getNomeCliente: string;
procedure LimparPropriedades;
procedure PreencherPropriedades;
procedure PreencherOldValue;
protected
oControle: TControle;
procedure OnAfterInsert(DataSet: TDataSet);
procedure OnAfterEdit(DataSet: TDataSet);
procedure OnAfterOpen(DataSet: TDataSet);
procedure InserirPedido(pResetarCDS: Boolean = True);
procedure AlterarPedido(pResetarCDS: Boolean = True);
procedure setNumeroPedido(pNumeroPedido: Integer);
function getNumeroPedido: Integer;
function getCdsPedidos: TClientDataSet;
function getNewPK: Integer;
property OldNumeroPedido: integer read iOldNumeroPedido;
property OldDtEmissao: TDate read dtOldDtEmissao;
property OldCliente: integer read iOldCliente;
property OldVlrTotal: double read nOldVlrTotal;
public
constructor Create(pConexaoControle: TControle);
destructor Destroy; override;
function PesquisarPedido(pNumeroPedido: Integer; pCarregarCDS: Boolean = False): Boolean;
function ObrigarSalvarPedido: Boolean;
procedure AtualziarCDSResult;
procedure GravarPedido(pResetarCDS: Boolean = True);
procedure GravarItemPedido(pResetarCDS: Boolean = True);
procedure ExcluirPedido(pNumeroPedido: Integer);
//property NumeroPedido: integer read iNumeroPedido write iNumeroPedido;
property NumeroPedido: integer read getNumeroPedido write setNumeroPedido;
property DtEmissao: TDate read dtDtEmissao write dtDtEmissao;
property Cliente: integer read iCliente write iCliente;
property NomeCliente: string read getNomeCliente;
property VlrTotal: double read nVlrTotal write nVlrTotal;
property CdsPedidos: TClientDataSet read getCdsPedidos;
property ItensProduto: TPedidosProdutos read oPedidosProdutos;
end;
implementation
{ TPedidos }
function TPedidos.ObrigarSalvarPedido: Boolean;
begin
Result := Self.OldVlrTotal <> Self.VlrTotal;
end;
procedure TPedidos.OnAfterEdit(DataSet: TDataSet);
begin
oPedidosProdutos.Carregar_PedidoProdutos(DataSet.FieldByName('NUMEROPEDIDO').AsInteger);
DataSet.FieldByName('VLR_TOTAL').AsCurrency := oPedidosProdutos.CalcularTotal_PedidoProdutos;
Self.PreencherPropriedades;
Self.PreencherOldValue;
end;
procedure TPedidos.OnAfterInsert(DataSet: TDataSet);
begin
Self.LimparPropriedades;
Self.PreencherPropriedades;
DataSet.FieldByName('NUMEROPEDIDO').AsInteger := getNewPK;
DataSet.FieldByName('DT_EMISSAO').AsDateTime := Date;
DataSet.FieldByName('VLR_TOTAL').AsCurrency := 0;
oControle.SqlQuery.Close;
oPedidosProdutos.Carregar_PedidoProdutos(DataSet.FieldByName('NUMEROPEDIDO').AsInteger);
end;
procedure TPedidos.OnAfterOpen(DataSet: TDataSet);
begin
TCurrencyField(DataSet.FindField('VLR_TOTAL')).DisplayFormat := '#,###,###,##0.00';
TDateField(DataSet.FindField('DT_EMISSAO')).EditMask := '99/99/9999;1;_';
end;
function TPedidos.PesquisarPedido(pNumeroPedido: Integer; pCarregarCDS: Boolean): Boolean;
begin
if (pNumeroPedido > 0) then
begin
if not pCarregarCDS then
begin
if ((not oControle.SqlQuery.Active) or
((oControle.SqlQuery.Active) and (not SameValue(oControle.SqlQuery.FieldByName('NUMEROPEDIDO').AsInteger, pNumeroPedido)))) then
begin
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('SELECT ');
oControle.SqlQuery.SQL.Add(' PEDIDOS.NUMEROPEDIDO, ');
oControle.SqlQuery.SQL.Add(' PEDIDOS.DT_EMISSAO, ');
oControle.SqlQuery.SQL.Add(' PEDIDOS.CLIENTE, ');
oControle.SqlQuery.SQL.Add(' CLIENTES.NOME, ');
oControle.SqlQuery.SQL.Add(' PEDIDOS.VLR_TOTAL ');
oControle.SqlQuery.SQL.Add('FROM ');
oControle.SqlQuery.SQL.Add(' PEDIDOS ');
oControle.SqlQuery.SQL.Add(' INNER JOIN CLIENTES ON ');
oControle.SqlQuery.SQL.Add(' CLIENTES.CODIGO = PEDIDOS.CLIENTE ');
oControle.SqlQuery.SQL.Add('WHERE ');
oControle.SqlQuery.SQL.Add(' PEDIDOS.NUMEROPEDIDO = :pNumeroPedido ');
oControle.SqlQuery.Params.Clear;
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pNumeroPedido', ptInput);
oControle.SqlQuery.Params.ParamByName('pNumeroPedido').AsInteger := pNumeroPedido;
try
oControle.SqlQuery.Open;
if oControle.SqlQuery.IsEmpty then
begin
LimparPropriedades;
Result := False;
end else
begin
Self.NumeroPedido := oControle.SqlQuery.FieldByName('NUMEROPEDIDO').AsInteger;
Self.DtEmissao := oControle.SqlQuery.FieldByName('DT_EMISSAO').AsDateTime;
Self.Cliente := oControle.SqlQuery.FieldByName('CLIENTE').AsInteger;
sNomeCliente := oControle.SqlQuery.FieldByName('NOME').AsString;
Self.VlrTotal := oControle.SqlQuery.FieldByName('VLR_TOTAL').AsCurrency;
Result := True;
end;
except
Result := False;
end;
end;
end else
begin
oControle.CdsResult.Active := False;
oControle.CdsResult.Params.ParamByName('pNumeroPedido').AsInteger := pNumeroPedido;
oControle.CdsResult.Active := True;
if (not oControle.CdsResult.IsEmpty) then
begin
oPedidosProdutos.Carregar_PedidoProdutos(pNumeroPedido);
oControle.CdsResult.Edit;
Result := True;
end else
Result := False;
end;
end else
Result := False;
end;
procedure TPedidos.PreencherOldValue;
begin
iOldNumeroPedido := oControle.CdsResult.FieldByName('NUMEROPEDIDO').AsInteger;
dtOldDtEmissao := oControle.CdsResult.FieldByName('DT_EMISSAO').AsDateTime;
iOldCliente := oControle.CdsResult.FieldByName('CLIENTE').AsInteger;
nOldVlrTotal := oControle.CdsResult.FieldByName('VLR_TOTAL').AsCurrency;
end;
procedure TPedidos.PreencherPropriedades;
begin
iNumeroPedido := oControle.CdsResult.FieldByName('NUMEROPEDIDO').AsInteger;
dtDtEmissao := oControle.CdsResult.FieldByName('DT_EMISSAO').AsDateTime;
iCliente := oControle.CdsResult.FieldByName('CLIENTE').AsInteger;
nVlrTotal := oControle.CdsResult.FieldByName('VLR_TOTAL').AsCurrency;
if oPedidosProdutos.CdsListaPedidosProdutos.State in [dsInsert, dsEdit] then
nVlrTotal := nVlrTotal + oPedidosProdutos.CalcularTotal_PedidoProdutos;
end;
procedure TPedidos.setNumeroPedido(pNumeroPedido: Integer);
begin
iNumeroPedido := pNumeroPedido;
oPedidosProdutos.NumeroPedido := pNumeroPedido;
end;
procedure TPedidos.AlterarPedido(pResetarCDS: Boolean = True);
var
bTemAlteracao: Boolean;
begin
bTemAlteracao := (not SameValue(Self.DtEmissao, Self.OldDtEmissao)) or
(not SameValue(Self.Cliente, Self.OldCliente)) or
(not SameValue(Self.VlrTotal, Self.OldVlrTotal));
if bTemAlteracao then
begin
PreencherPropriedades;
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('UPDATE ');
oControle.SqlQuery.SQL.Add(' PEDIDOS ');
oControle.SqlQuery.SQL.Add('SET ');
if not SameValue(Self.DtEmissao, Self.OldDtEmissao) then
oControle.SqlQuery.SQL.Add(' DT_EMISSAO = CAST('+QuotedStr(FormatDateTime('DD.MM.YYYY', Self.DtEmissao))+' AS DATE), ');
if not SameValue(Self.Cliente, Self.OldCliente) then
oControle.SqlQuery.SQL.Add(' CLIENTE = :pCliente, ');
if not SameValue(Self.VlrTotal, Self.OldVlrTotal) then
oControle.SqlQuery.SQL.Add(' VLR_TOTAL = :pVlrTotal, ');
oControle.SqlQuery.SQL.Text := Copy(oControle.SqlQuery.SQL.Text, 0, Length(Trim(oControle.SqlQuery.SQL.Text)) - 1) + ' '; // remove o últmo ", ".
oControle.SqlQuery.SQL.Add('WHERE ');
oControle.SqlQuery.SQL.Add(' NUMEROPEDIDO = :pNumeroPedido ');
oControle.SqlQuery.Params.Clear;
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pNumeroPedido', ptInput);
if not SameValue(Self.Cliente, Self.OldCliente) then
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pCliente', ptInput);
if not SameValue(Self.VlrTotal, Self.OldVlrTotal) then
oControle.SqlQuery.Params.CreateParam(ftFloat, 'pVlrTotal', ptInput);
oControle.SqlQuery.Params.ParamByName('pNumeroPedido').AsInteger := Self.NumeroPedido;
if not SameValue(Self.Cliente, Self.OldCliente) then
oControle.SqlQuery.Params.ParamByName('pCliente').AsInteger := Self.Cliente;
if not SameValue(Self.VlrTotal, Self.OldVlrTotal) then
oControle.SqlQuery.Params.ParamByName('pVlrTotal').AsCurrency := Self.VlrTotal;
try
oControle.SqlQuery.ExecSQL;
if pResetarCDS then
begin
Application.MessageBox(PWideChar('Pedido alterado com sucesso.'), 'Informação', MB_ICONINFORMATION + MB_OK);
LimparPropriedades;
oControle.CdsResult.Cancel;
oControle.CdsResult.Insert;
end;
except
on e: Exception do
begin
Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao alterar o pedido.'+#13+#10+' "'+e.Message+'".'), 'Erro na alteração', MB_ICONERROR + MB_OK);
end;
end;
end else
begin
LimparPropriedades;
oControle.CdsResult.Cancel;
if pResetarCDS then
oControle.CdsResult.Insert
else
begin
oControle.CdsResult.Refresh;
if oControle.CdsResult.Locate('NUMEROPEDIDO', Self.NumeroPedido, [loPartialKey, loCaseInsensitive]) then
begin
oControle.CdsResult.Edit;
Self.PreencherPropriedades;
Self.PreencherOldValue;
end;
end;
end;
end;
procedure TPedidos.AtualziarCDSResult;
begin
try
oControle.CdsResult.DisableControls;
oControle.CdsResult.Cancel;
oControle.CdsResult.Close;
oControle.CdsResult.Params.ParamByName('pNumeroPedido').AsInteger := Self.NumeroPedido;
oControle.CdsResult.Open;
oControle.CdsResult.Locate('NUMEROPEDIDO', Self.NumeroPedido, [loPartialKey, loCaseInsensitive]);
oControle.CdsResult.Edit;
finally
oControle.CdsResult.EnableControls;
end;
end;
constructor TPedidos.Create(pConexaoControle: TControle);
begin
if not Assigned(oControle) then
oControle := pConexaoControle;
if not Assigned(oClientes) then
oClientes := TClientes.Create(pConexaoControle);
{$REGION 'Configuração do CDS Pedidos'}
oControle.CdsResult.AfterInsert := Self.OnAfterInsert;
oControle.CdsResult.AfterEdit := Self.OnAfterEdit;
oControle.CdsResult.AfterOpen := Self.OnAfterOpen;
oControle.CdsResult.Close;
oControle.CdsResult.CommandText := 'SELECT '+
' PEDIDOS.NUMEROPEDIDO, '+
' PEDIDOS.DT_EMISSAO, '+
' PEDIDOS.CLIENTE, '+
' CLIENTES.NOME, '+
' PEDIDOS.VLR_TOTAL '+
'FROM '+
' PEDIDOS '+
' INNER JOIN CLIENTES ON '+
' CLIENTES.CODIGO = PEDIDOS.CLIENTE '+
'WHERE '+
' PEDIDOS.NUMEROPEDIDO = :pNumeroPedido ';
oControle.CdsResult.Params.Clear;
oControle.CdsResult.Params.CreateParam(ftInteger, 'pNumeroPedido', ptInput);
{$ENDREGION}
if not Assigned(oPedidosProdutos) then
oPedidosProdutos := TPedidosProdutos.Create(pConexaoControle);
end;
destructor TPedidos.Destroy;
begin
if Assigned(oClientes) then
FreeAndNil(oClientes);
inherited;
end;
procedure TPedidos.ExcluirPedido(pNumeroPedido: Integer);
begin
if PesquisarPedido(pNumeroPedido) then
begin
try
oControle.StartTransaction;
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('DELETE FROM PEDIDOSPRODUTOS WHERE NUMEROPEDIDO = :pNumeroPedido');
oControle.SqlQuery.Params.Clear;
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pNumeroPedido', ptInput);
oControle.SqlQuery.Params.ParamByName('pNumeroPedido').AsInteger := pNumeroPedido;
try
oControle.SqlQuery.ExecSQL;
except
on e: Exception do
begin
if oControle.InTransaction then
oControle.RollbackTransaction;
Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao excluir o pedido de número "'+IntToStr(pNumeroPedido)+'". Por favor, verifique o erro à seguir:'+#13+#10+'Erro: "'+e.Message+'".'), 'Erro', MB_ICONERROR + MB_OK);
end;
end;
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('DELETE FROM PEDIDOS WHERE NUMEROPEDIDO = :pNumeroPedido');
oControle.SqlQuery.Params.Clear;
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pNumeroPedido', ptInput);
oControle.SqlQuery.Params.ParamByName('pNumeroPedido').AsInteger := pNumeroPedido;
try
oControle.SqlQuery.ExecSQL;
Application.MessageBox(PWideChar('O pedido de número "'+IntToStr(pNumeroPedido)+'" foi excluído com sucesso.'), 'Informação', MB_ICONINFORMATION + MB_OK);
except
on e: Exception do
begin
if oControle.InTransaction then
oControle.RollbackTransaction;
Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao excluir o pedido de número "'+IntToStr(pNumeroPedido)+'". Por favor, verifique o erro à seguir:'+#13+#10+'Erro: "'+e.Message+'".'), 'Erro', MB_ICONERROR + MB_OK);
end;
end;
finally
if oControle.InTransaction then
oControle.CommitTransaction;
if (oControle.CdsResult.State in [dsInsert, dsEdit]) then
oControle.CdsResult.Cancel;
if (oControle.CdsResult.Active) and (not (oControle.CdsResult.State in [dsInsert, dsEdit])) then
oControle.CdsResult.Insert;
end;
end else
Application.MessageBox(PWideChar('Não foi possível excluir o pedido de número "'+IntToStr(pNumeroPedido)+'", pois o pedido não existe.'), 'Atenção', MB_ICONWARNING + MB_OK);
end;
function TPedidos.getCdsPedidos: TClientDataSet;
begin
Result := oControle.CdsResult;
end;
function TPedidos.getNewPK: Integer;
begin
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('SELECT COALESCE(MAX(NUMEROPEDIDO),0) + 1 NEWPK FROM PEDIDOS');
try
oControle.SqlQuery.Open;
Result := oControle.SqlQuery.FieldByName('NEWPK').AsInteger;
except
on e: Exception do
begin
Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao buscar o novo número do pedido.'+#13+#10+'Erro: "'+e.Message+'".'), 'Erro', MB_ICONERROR + MB_OK);
Result := 0;
end;
end;
end;
function TPedidos.getNomeCliente: string;
begin
if oClientes.PesquisarCliente(Self.Cliente) then
begin
sNomeCliente := oClientes.nome;
end else
sNomeCliente := '';
Result := sNomeCliente;
end;
function TPedidos.getNumeroPedido: Integer;
begin
Result := iNumeroPedido;
end;
procedure TPedidos.GravarItemPedido(pResetarCDS: Boolean = True);
begin
if (Self.CdsPedidos.State in [dsInsert]) then
Self.GravarPedido(pResetarCDS);
if (oPedidosProdutos.CdsListaPedidosProdutos.State in [dsInsert, dsEdit]) then
if oPedidosProdutos.SalvarItem_PedidoProdutos then
begin
Self.VlrTotal := oPedidosProdutos.CalcularTotal_PedidoProdutos;
oControle.CdsResult.FieldByName('VLR_TOTAL').AsCurrency := Self.VlrTotal;
Self.AlterarPedido(pResetarCDS);
Self.AtualziarCDSResult;
end;
end;
procedure TPedidos.GravarPedido(pResetarCDS: Boolean = True);
begin
if oControle.CdsResult.State in [dsInsert] then
InserirPedido(pResetarCDS)
else if oControle.CdsResult.State in [dsEdit] then
AlterarPedido(pResetarCDS);
end;
procedure TPedidos.InserirPedido(pResetarCDS: Boolean = True);
var
iNewPK: integer;
iNumPedido: integer;
begin
PreencherPropriedades;
iNewPK := getNewPK;
if Self.NumeroPedido < iNewPK then
begin
Application.MessageBox(PWideChar('O número do pedido será atualizado para: "'+IntToStr(iNewPK)+'".'), 'Informação', MB_ICONINFORMATION + MB_OK);
Self.NumeroPedido := iNewPK;
if oControle.CdsResult.State in [dsInsert] then
oControle.CdsResult.FieldByName('NUMEROPEDIDO').AsInteger := iNewPK;
end;
oControle.SqlQuery.Close;
oControle.SqlQuery.SQL.Clear;
oControle.SqlQuery.SQL.Add('INSERT INTO PEDIDOS ');
oControle.SqlQuery.SQL.Add(' (NUMEROPEDIDO ');
oControle.SqlQuery.SQL.Add(' ,DT_EMISSAO ');
oControle.SqlQuery.SQL.Add(' ,CLIENTE ');
oControle.SqlQuery.SQL.Add(' ,VLR_TOTAL) ');
oControle.SqlQuery.SQL.Add('VALUES ');
oControle.SqlQuery.SQL.Add(' (:pNumeroPedido ');
oControle.SqlQuery.SQL.Add(' ,:pDtEmissao ');
oControle.SqlQuery.SQL.Add(' ,:pCliente ');
oControle.SqlQuery.SQL.Add(' ,:pVlrTotal) ');
oControle.SqlQuery.Params.Clear;
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pNumeroPedido', ptInput);
oControle.SqlQuery.Params.CreateParam(ftDate, 'pDtEmissao', ptInput);
oControle.SqlQuery.Params.CreateParam(ftInteger, 'pCliente', ptInput);
oControle.SqlQuery.Params.CreateParam(ftFloat, 'pVlrTotal', ptInput);
oControle.SqlQuery.Params.ParamByName('pNumeroPedido').AsInteger := Self.NumeroPedido;
oControle.SqlQuery.Params.ParamByName('pDtEmissao').AsDate := Self.DtEmissao;
oControle.SqlQuery.Params.ParamByName('pCliente').AsInteger := Self.Cliente;
oControle.SqlQuery.Params.ParamByName('pVlrTotal').AsCurrency := Self.VlrTotal;
try
oControle.SqlQuery.ExecSQL;
if pResetarCDS then
begin
Application.MessageBox(PWideChar('Pedido cadastrador com sucesso.'), 'Informação', MB_ICONINFORMATION + MB_OK);
LimparPropriedades;
oControle.CdsResult.Cancel;
oControle.CdsResult.Insert;
end;
except
on e: Exception do
begin
Application.MessageBox(PWideChar('Ocorreu o seguinte erro ao inserir um novo pedido.'+#13+#10+' "'+e.Message+'".'), 'Erro de inclusão', MB_ICONERROR + MB_OK);
end;
end;
end;
procedure TPedidos.LimparPropriedades;
begin
iNumeroPedido := 0;
dtDtEmissao := 0;
iCliente := 0;
sNomeCliente := '';
nVlrTotal := 0;
iOldNumeroPedido := 0;
dtOldDtEmissao := 0;
iOldCliente := 0;
nOldVlrTotal := 0;
end;
end.
|
unit sysmenu;
interface
uses Winapi.Windows, Winapi.Messages, Classes, Graphics, Vcl.Controls, Vcl.ImgList, Vcl.Menus;
type
THelperBitmap = class Helper for TBitmap
public
procedure LoadIconFromResource(Instance: THandle; ResName: string);
function MaskedColor: TColor;
end;
THelperImageList = class Helper for TImageList
public
function LoadFromResource(Instance: THandle; ResName: string): integer;
end;
TSystemMenu = class(TPopupMenu)
private
FSysHandle: HMENU;
procedure AttachItem(Item: TMenuItem);
procedure SetMenuImage(Item: TMenuItem); overload;
procedure SetMenuImage(HMENU: HMENU; idMenu: Cardinal; hBitmap: hBitmap); overload;
public
function Add(Caption: string; ImageIndex: integer; OnEvent: TNotifyEvent): TMenuItem;
procedure Attach(hSysMenu: HMENU);
function OnCommand(var Msg: TWMSysCommand): boolean;
end;
implementation
// THelperBitmap
function THelperBitmap.MaskedColor: TColor;
begin
Result := Canvas.Pixels[0, 0];
end;
procedure THelperBitmap.LoadIconFromResource(Instance: THandle; ResName: string);
var
buff: TBitmap;
buffrect: TRect;
begin
buff := TBitmap.Create;
try
buff.LoadFromResourceName(Instance, ResName);
buffrect := buff.Canvas.ClipRect;
if buffrect.Height > buffrect.Width then
buffrect.Height := buffrect.Width
else
buffrect.Width := buffrect.Height;
Canvas.Brush.Color := buff.MaskedColor;
Canvas.FillRect(Canvas.ClipRect);
Canvas.CopyRect(Canvas.ClipRect, buff.Canvas, buffrect);
finally
buff.Free;
end;
end;
// THelperImageList
function THelperImageList.LoadFromResource(Instance: THandle; ResName: string): integer;
var
icon: TBitmap;
begin
icon := TBitmap.Create;
try
icon.SetSize(Width, Height);
icon.LoadIconFromResource(Instance, ResName);
Result := AddMasked(icon, icon.MaskedColor);
finally
icon.Free;
end;
end;
// TSystemMenu
function TSystemMenu.Add(Caption: string; ImageIndex: integer; OnEvent: TNotifyEvent): TMenuItem;
begin
Result := TMenuItem.Create(Self);
Result.ImageIndex := ImageIndex;
Result.Caption := Caption;
Result.OnClick := OnEvent;
InsertComponent(Result);
Items.Add(Result);
end;
procedure TSystemMenu.Attach(hSysMenu: HMENU);
var
Index: integer;
Item: TMenuItem;
begin
FSysHandle := hSysMenu;
AttachItem(nil);
for Index := 0 to Items.Count - 1 do
begin
Item := Items[Index];
if Item.Tag = 0 then
Item.Tag := Index + 1;
AttachItem(Item);
end;
end;
procedure TSystemMenu.SetMenuImage(Item: TMenuItem);
begin
if not Assigned(Images) then
Exit;
Item.Bitmap.PixelFormat := pf24bit;
Item.Bitmap.SetSize(Images.Width, Images.Height);
Item.Bitmap.Canvas.Brush.Color := clMenu;
Item.Bitmap.Canvas.FillRect(Item.Bitmap.Canvas.ClipRect);
Images.Draw(Item.Bitmap.Canvas, 0, 0, Item.ImageIndex, Vcl.ImgList.dsTransparent, Vcl.ImgList.itImage, true);
end;
procedure TSystemMenu.SetMenuImage(HMENU: HMENU; idMenu: Cardinal; hBitmap: hBitmap);
var
mInfo: MENUITEMINFO;
begin
mInfo.cbSize := sizeof(MENUITEMINFO);
mInfo.fMask := MIIM_BITMAP;
mInfo.hbmpItem := hBitmap;
SetMenuItemInfo(HMENU, idMenu, false, &mInfo);
end;
procedure TSystemMenu.AttachItem(Item: TMenuItem);
var
j: integer;
begin
if (FSysHandle = 0) then
Exit;
if not Assigned(Item) then
begin
Winapi.Windows.AppendMenu(FSysHandle, MF_SEPARATOR, 0, '');
end else if Item.Enabled then
if Item.IsLine then
begin
Winapi.Windows.AppendMenu(FSysHandle, MF_SEPARATOR, 0, '');
end
else begin
if Item.Count = 0 then
begin
Winapi.Windows.AppendMenu(FSysHandle, MF_STRING, WM_USER + Item.Tag, PWideChar(Item.Caption));
if Assigned(Images) and (Item.ImageIndex >= 0) then
begin
SetMenuImage(Item);
SetMenuImage(FSysHandle, WM_USER + Item.Tag, Item.Bitmap.Handle);
end;
end
else begin
Winapi.Windows.AppendMenu(FSysHandle, MF_SEPARATOR, 0, '');
for j := 0 to Item.Count - 1 do
AttachItem(Item[j]);
end;
end;
end;
function TSystemMenu.OnCommand(var Msg: TWMSysCommand): boolean;
var
N, j: integer;
obj: TComponent;
begin
Result := false;
N := Msg.CmdType - WM_USER;
for j := 0 to ComponentCount - 1 do
begin
obj := Components[j];
if obj is TMenuItem then
if TMenuItem(obj).Tag = N then
begin
if Assigned(TMenuItem(obj)) then
begin
TMenuItem(obj).OnClick(Self);
end;
Result := true;
Exit;
end;
end;
end;
end.
|
{******************************************************************************}
{ }
{ Delphi SwagDoc Library }
{ Copyright (c) 2018 Marcelo Jaloto }
{ https://github.com/marcelojaloto/SwagDoc }
{ }
{******************************************************************************}
{ }
{ 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 Swag.Common.Types;
interface
uses
System.Generics.Collections;
type
TSwagStatusCode = string;
TSwagMimeType = string;
TSwagJsonExampleDescription = string;
TSwagSecuritySchemaName = string;
TSwagSecurityDefinitionType = (ssdNotDefined, ssdBasic, ssdApiKey, ssdOAuth2);
TSwagSecurityDefinitionsType = set of TSwagSecurityDefinitionType;
TSwagSecurityScopesSchemaName = string;
TSwagSecurityScopesSchemaDescription = string;
TSwagSecurityScopes = TDictionary<TSwagSecurityScopesSchemaName, TSwagSecurityScopesSchemaDescription>;
TSwagTransferProtocolScheme = (tpsNotDefined, tpsHttp, tpsHttps, tpsWs, tpsWss);
TSwagTransferProtocolSchemes = set of TSwagTransferProtocolScheme;
TSwagRequestParameterInLocation = (rpiNotDefined, rpiQuery, rpiHeader, rpiPath, rpiFormData, rpiBody);
TSwagPathTypeOperation = (ohvNotDefined, ohvGet, ohvPost, ohvPut, ohvDelete, ohvOptions, ohvHead, ohvPatch);
implementation
end.
|
unit eaterUtils;
interface
procedure OutLn(const x:string);
procedure ErrLn(const x:string);
procedure Out0(const x:string);
procedure SaveUTF16(const fn:string;const Data:WideString);
function StartsWith(const Value,Prefix:string):boolean;
function StartsWithX(const Value,Prefix:string;var Suffix:string):boolean;
function HTMLStartsWithImg(const Value:string):boolean;
function ConvDate1(const x:string):TDateTime;
function ConvDate2(const x:string):TDateTime;
function UtcNow:TDateTime;
function HTMLEncode(const x:string):string;
function HTMLEncodeQ(const x:string):string;
function URLEncode(const x:string):AnsiString;
function StripWhiteSpace(const x:WideString):WideString;
function IsSomethingEmpty(const x:WideString):boolean;
function StripHTML(const x:WideString;MaxLength:integer):WideString;
function HTMLDecode(const w:WideString):WideString;
function IsProbablyHTML(const x:WideString):boolean;
function VarArrFirst(const v:Variant):Variant;
function VarArrLast(const v:Variant):Variant;
implementation
uses Windows, SysUtils, Variants, Classes;
procedure OutLn(const x:string);
begin
WriteLn(FormatDateTime('hh:nn:ss.zzz ',Now)+x);
end;
procedure ErrLn(const x:string);
begin
WriteLn(ErrOutput,FormatDateTime('hh:nn:ss.zzz ',Now)+x);
end;
procedure Out0(const x:string);
begin
Write(FormatDateTime('hh:nn:ss.zzz ',Now)+x);
end;
procedure SaveUTF16(const fn:string;const Data:WideString);
var
rf:TFileStream;
i:word;
begin
rf:=TFileStream.Create(fn,fmCreate);
try
i:=$FEFF;
rf.Write(i,2);
rf.Write(Data[1],Length(Data)*2);
finally
rf.Free;
end;
end;
function StartsWith(const Value,Prefix:string):boolean; inline;
begin
Result:=Copy(Value,1,Length(Prefix))=Prefix;
end;
function StartsWithX(const Value,Prefix:string;var Suffix:string):boolean;
begin
if Copy(Value,1,Length(Prefix))=Prefix then
begin
Suffix:=Copy(Value,Length(Prefix)+1,Length(Value)-Length(Prefix));
Result:=true;
end
else
Result:=false;
end;
function HTMLStartsWithImg(const Value:string):boolean;
var
i,j,l:integer;
ok:boolean;
s:string;
begin
i:=1;
l:=Length(Value);
Result:=false;//default
ok:=true;//
while ok do
begin
//ignore white space
while (i<=l) and (Value[i]<=' ') do inc(i);
//next element
if (i<=l) and (Value[i]='<') then
begin
inc(i);
j:=i;
while (j<=l) and (Value[j]>' ') and (Value[j]<>'>') and (Value[j]<>'/') do inc(j);
s:=LowerCase(Copy(Value,i,j-i));
//skippable?
if (s='a') or (s='div') or (s='p') or (s='center') then
//continue loop
else
//image?
if (s='img') or (s='figure') or (s='picture') then
begin
Result:=true;
ok:=false;//end loop
end;
if ok then
begin
i:=j;
while (i<=l) and (Value[i]<>'>') do inc(i);
inc(i);
end;
end
else
ok:=false;//end loop
end;
end;
function ConvDate1(const x:string):TDateTime;
var
dy,dm,dd,th,tm,ts,tz,b,b0:word;
i,l,b1:integer;
procedure nx(var xx:word;yy:integer);
var
ii:integer;
begin
xx:=0;
for ii:=0 to yy-1 do
if (i<=l) and (AnsiChar(x[i]) in ['0'..'9']) then
begin
xx:=xx*10+(byte(x[i]) and $F);
inc(i);
end;
end;
begin
i:=1;
l:=Length(x);
while (i<=l) and (x[i]<=' ') do inc(i);
nx(dy,4); inc(i);//':'
nx(dm,2); inc(i);//':'
nx(dd,2); inc(i);//'T'
nx(th,2); inc(i);//':'
nx(tm,2); inc(i);//':'
nx(ts,2);
if (i<=l) and (x[i]='.') then
begin
inc(i);
nx(tz,3);
//ignore superflous digits
while (i<=l) and (AnsiChar(x[i]) in ['0'..'9']) do inc(i);
end
else
tz:=0;
b:=0;//default
b1:=0;//default
if i<=l then
case x[i] of
'+':
begin
b1:=-1; inc(i);
nx(b,2); inc(i);//':'
nx(b0,2); b:=b*100+b0;
end;
'-':
begin
b1:=+1; inc(i);
nx(b,2); inc(i);//':'
nx(b0,2); b:=b*100+b0;
end;
'Z':begin b1:=0; b:=0000; end;
'A'..'M':begin b1:=-1; b:=(byte(x[1])-64)*100; end;
'N'..'Y':begin b1:=+1; b:=(byte(x[1])-77)*100; end;
end;
Result:=
EncodeDate(dy,dm,dd)+
EncodeTime(th,tm,ts,tz)+
b1*((b div 100)/24.0+(b mod 100)/1440.0);
end;
const
TimeZoneCodeCount=191;
TimeZoneCode:array[0..TimeZoneCodeCount-1] of string=(
'ACDT+1030' ,
'ACST+0930',
'ACT-0500',
//'ACT+0800'//ASEAN Common
'ACWST+0845',
'ADT-0300',
'AEDT+1100',
'AEST+1000',
'AFT+0430',
'AKDT-0800',
'AKST-0900',
'AMST-0300',
'AMT+0400',
'ART-0300',
'AST+0300',
'AST-0400',
'AWST+0800',
'AZOST+0000',
'AZOT-0100',
'AZT+0400',
'BDT+0800',
'BIOT+0600',
'BIT-1200',
'BOT-0400',
'BRST-0200',
'BRT-0300',
'BST+0600',
'BST+1100',
'BTT+0600',
'CAT+0200',
'CCT+0630',
'CDT-0500',
'CDT-0400',
'CEST+0200',
'CET+0100',
'CHADT+1345',
'CHAST+1245',
'CHOT+0800',
'CHOST+0900',
'CHST+1000',
'CHUT+1000',
'CIST-0800',
'CIT+0800',
'CKT-1000',
'CLST-0300',
'CLT-0400',
'COST-0400',
'COT-0500',
'CST-0600',
'CST+0800',
'CST-0500',
'CT+0800',
'CVT-0100',
'CWST+0845',
'CXT+0700',
'DAVT+0700',
'DDUT+1000',
'DFT+0100',
'EASST-0500',
'EAST-0600',
'EAT+0300',
'ECT-0400',
'ECT-0500',
'EDT-0400',
'EEST+0300',
'EET+0200',
'EGST+0000',
'EGT-0100',
'EIT+0900',
'EST-0500',
'FET+0300',
'FJT+1200',
'FKST-0300',
'FKT-0400',
'FNT-0200',
'GALT-0600',
'GAMT-0900',
'GET+0400',
'GFT-0300',
'GILT+1200',
'GIT-0900',
'GMT+0000',
'GST-0200',
'GST+0400',
'GYT-0400',
'HDT-0900',
'HAEC+0200',
'HST-1000',
'HKT+0800',
'HMT+0500',
'HOVST+0800',
'HOVT+0700',
'ICT+0700',
'IDLW-1200',
'IDT+0300',
'IOT+0300',
'IRDT+0430',
'IRKT+0800',
'IRST+0330',
'IST+0530',//Indian Standard Time
//'IST+0100',//Irish Standard Time
//'IST+0200',//Israel Standard Time
'JST+0900',
'KALT+0200',
'KGT+0600',
'KOST+1100',
'KRAT+0700',
'KST+0900',
'LHST+1030',//Lord Howe Standard Time
//'LHST+1100',//Lord Howe Summer Time
'LINT+1400',
'MAGT+1200',
'MART-0930',
'MAWT+0500',
'MDT-0600',
'MET+0100',
'MEST+0200',
'MHT+1200',
'MIST+1100',
'MIT-0930',
'MMT+0630',
'MSK+0300',
//'MST+0800',//Malaysia Standard Time
'MST-0700',//Mountain Standard Time (North America)
'MUT+0400',
'MVT+0500',
'MYT+0800',
'NCT+1100',
'NDT-0230',
'NFT+1100',
'NPT+0545',
'NST-0330',
'NT-0330',
'NUT-1100',
'NZDT+1300',
'NZST+1200',
'OMST+0600',
'ORAT+0500',
'PDT-0700',
'PET-0500',
'PETT+1200',
'PGT+1000',
'PHOT+1300',
'PHT+0800',
'PKT+0500',
'PMDT-0200',
'PMST-0300',
'PONT+1100',
'PST-0800',//Pacific Standard Time (North America)
//'PST+0800',//Phillipine Standard Time
'PYST-0300',
'PYT-0400',
'RET+0400',
'ROTT-0300',
'SAKT+1100',
'SAMT+0400',
'SAST+0200',
'SBT+1100',
'SCT+0400',
'SDT-1000',
'SGT+0800',
'SLST+0530',
'SRET+1100',
'SRT-0300',
'SST-1100',
'SST+0800',
'SYOT+0300',
'TAHT-1000',
'THA+0700',
'TFT+0500',
'TJT+0500',
'TKT+1300',
'TLT+0900',
'TMT+0500',
'TRT+0300',
'TOT+1300',
'TVT+1200',
'ULAST+0900',
'ULAT+0800',
'UTC+0000',
'UYST-0200',
'UYT-0300',
'UZT+0500',
'VET-0400',
'VLAT+1000',
'VOLT+0400',
'VOST+0600',
'VUT+1100',
'WAKT+1200',
'WAST+0200',
'WAT+0100',
'WEST+0100',
'WET+0000',
'WIT+0700',
'WST+0800',
'YAKT+0900',
'YEKT+0500');
function ConvDate2(const x:string):TDateTime;
var
dy,dm,dd,th,tm,ts,tz,b:word;
dda:boolean;
i,j,k,l,b1:integer;
st:TSystemTime;
procedure nx(var xx:word;yy:integer);
var
ii:integer;
begin
xx:=0;
for ii:=0 to yy-1 do
if (i<=l) and (AnsiChar(x[i]) in ['0'..'9']) then
begin
xx:=xx*10+(byte(x[i]) and $F);
inc(i);
end;
end;
begin
i:=1;
l:=Length(x);
while (i<=l) and (x[i]<=' ') do inc(i);
//check number of digits
j:=i;
if (i<=l) and (AnsiChar(x[i]) in ['0'..'9']) then
while (j<=l) and (AnsiChar(x[j]) in ['0'..'9']) do inc(j);
if j-i=4 then //assume "yyyy-mm-dd hh:nn:ss
Result:=ConvDate1(x)
else
begin
//day of week 'Mon,','Tue,'...
while (i<=l) and not(AnsiChar(x[i]) in [',',' ']) do inc(i);
while (i<=l) and not(AnsiChar(x[i]) in ['0'..'9','A'..'Z']) do inc(i);
dda:=(i<=l) and (AnsiChar(x[i]) in ['0'..'9']);
if dda then
begin
//day of month
nx(dd,2);
inc(i);//' '
end;
//month
dm:=0;//default
if i+3<l then
case x[i] of
'J':
case x[i+1] of
'a':dm:=1;//Jan
'u':
case x[i+2] of
'n':dm:=6;//Jun
'l':dm:=7;//Jul
end;
end;
'F':dm:=2;//Feb
'M':
case x[i+2] of
'r':dm:=3;//Mar
'y':dm:=5;//May
end;
'A':
case x[i+1] of
'p':dm:=4;//Apr
'u':dm:=8;//Aug
end;
'S':dm:=9;//Sep
'O':dm:=10;//Oct
'N':dm:=11;//Nov
'D':dm:=12;//Dec
end;
if dda then
inc(i,4)
else
begin
while (i<=l) and not(x[i]=' ') do inc(i);
inc(i);//' '
nx(dd,2);
inc(i);//',';
inc(i);//' ';
end;
nx(dy,4); inc(i);//' '
if dy<100 then
begin
//guess century
GetSystemTime(st);
j:=st.wYear div 100;
if ((st.wYear mod 100)>70) and (dy<30) then dec(j);//?
dy:=dy+j*100;
end;
if not dda then inc(i);//','
nx(th,2); inc(i);//':'
nx(tm,2); inc(i);//':'
if dda then
begin
nx(ts,2); inc(i);//' '
end
else
begin
ts:=0;
//AM/PM
if (i<l) and (x[i]='P') and (x[i+1]='M') then
begin
if th<>12 then th:=th+12;
inc(i,3);
end
else
if (i<l) and (x[i]='A') and (x[i+1]='M') then
inc(i,3);
end;
tz:=0;
//timezone
b:=0;//default
b1:=0;//default
if i+2<=l then
case x[i] of
'+':
begin
b1:=-1;
inc(i);
nx(b,4);
end;
'-':
begin
b1:=+1;
inc(i);
nx(b,4);
end;
'A'..'Z':
begin
j:=0;
while j<>TimeZoneCodeCount do
begin
k:=0;
while (byte(TimeZoneCode[j][1+k])>64) and
(x[i+k]=TimeZoneCode[j][1+k]) do inc(k);
if byte(TimeZoneCode[j][1+k])<64 then
begin
if TimeZoneCode[j][1+k]='-' then b1:=+1 else b1:=-1;
b:=StrToInt(Copy(TimeZoneCode[j],2+k,4));
j:=TimeZoneCodeCount;
end
else
inc(j);
end;
end;
end;
Result:=
EncodeDate(dy,dm,dd)+
EncodeTime(th,tm,ts,tz)+
b1*((b div 100)/24.0+(b mod 100)/1440.0);
end;
end;
function UtcNow:TDateTime;
var
st:TSystemTime;
begin
GetSystemTime(st);
Result:=
EncodeDate(st.wYear,st.wMonth,st.wDay)+
EncodeTime(st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);
end;
function HTMLEncode(const x:string):string;
begin
//TODO: redo smarter than sequential StringReplace
Result:=
StringReplace(
StringReplace(
StringReplace(
x
,'&','&',[rfReplaceAll])
,'<','<',[rfReplaceAll])
,'>','>',[rfReplaceAll])
;
end;
function HTMLEncodeQ(const x:string):string;
begin
Result:=
StringReplace(
StringReplace(
StringReplace(
StringReplace(
x
,'&','&',[rfReplaceAll])
,'<','<',[rfReplaceAll])
,'>','>',[rfReplaceAll])
,'"','"',[rfReplaceAll])
;
end;
function URLEncode(const x:string):AnsiString;
const
Hex:array[0..15] of AnsiChar='0123456789abcdef';
var
s,t:AnsiString;
p,q,l:integer;
begin
s:=UTF8Encode(x);
q:=1;
l:=Length(s)+$80;
SetLength(t,l);
for p:=1 to Length(s) do
begin
if q+4>l then
begin
inc(l,$80);
SetLength(t,l);
end;
case s[p] of
#0..#31,'"','#','$','%','&','''','+','/',
'<','>','?','@','[','\',']','^','`','{','|','}',
#$80..#$FF:
begin
t[q]:='%';
t[q+1]:=Hex[byte(s[p]) shr 4];
t[q+2]:=Hex[byte(s[p]) and $F];
inc(q,2);
end;
' ':
t[q]:='+';
else
t[q]:=s[p];
end;
inc(q);
end;
SetLength(t,q-1);
Result:=t;
end;
function StripWhiteSpace(const x:WideString):WideString;
var
i,j,k,l:integer;
w:word;
const
WhiteSpaceCodesCount=30;
WhiteSpaceCodes:array[0..WhiteSpaceCodesCount-1] of word=//WideChar=
($0009,$000A,$000B,$000C,$000D,$0020,$0085,$00A0,
$1680,$180E,$2000,$2001,$2002,$2003,$2004,$2005,
$2006,$2007,$2008,$2009,$200A,$200B,$200C,$200D,
$2028,$2029,$202F,$205F,$2060,$3000);
begin
l:=Length(x);
i:=1;
j:=1;
SetLength(Result,l);
while i<=l do
begin
w:=word(x[i]);
k:=0;
while (k<WhiteSpaceCodesCount) and (w<>WhiteSpaceCodes[k]) do inc(k);
if k=WhiteSpaceCodesCount then
begin
Result[j]:=x[i];
inc(j);
end;
inc(i);
end;
SetLength(Result,j-1);
end;
function IsSomethingEmpty(const x:WideString):boolean;
var
xx:WideString;
begin
if Length(x)>60 then Result:=false else
begin
xx:=StripWhiteSpace(x);
Result:=(xx='')
or (xx='<div></div>');
end;
end;
function StripHTML(const x:WideString;MaxLength:integer):WideString;
var
i,r:integer;
b:boolean;
begin
Result:=#$2039+x+'.....';
i:=1;
r:=1;
b:=false;
while (i<=length(x)) and (r<MaxLength) do
begin
if x[i]='<' then
begin
inc(i);
while (i<=Length(x)) and (x[i]<>'>') do inc(i);
end
else
if x[i]<=' ' then
b:=r>1
else
begin
if b then
begin
inc(r);
Result[r]:=' ';
b:=false;
end;
inc(r);
Result[r]:=x[i];
end;
inc(i);
end;
if (i<Length(x)) then
begin
while (r<>0) and (Result[r]<>' ') do dec(r);
Result[r]:='.';
inc(r);
Result[r]:='.';
inc(r);
Result[r]:='.';
end;
inc(r);
Result[r]:=#$203A;
SetLength(Result,r);
end;
function HTMLDecode(const w:WideString):WideString;
var
i,j,l:integer;
c:word;
begin
//just for wp/v2 feedname for now
//TODO: full HTMLDecode
Result:=w;
l:=Length(w);
i:=1;
j:=0;
while (i<=l) do
begin
if (i<l) and (w[i]='&') and (w[i+1]='#') then
begin
inc(i,2);
c:=0;
if w[i]='x' then
begin
inc(i);
while (i<=l) and (w[i]<>';') do
begin
if (word(w[i]) and $FFF0)=$0030 then //if w[i] in ['0'..'9'] then
c:=(c shl 4) or (word(w[i]) or $F)
else
c:=(c shl 4) or (9+word(w[i]) or 7);
end;
end
else
while (i<=l) and (w[i]<>';') do
begin
c:=c*10+(word(w[i]) and $F);
inc(i);
end;
inc(j);
Result[j]:=WideChar(c);
end
else
begin
inc(j);
Result[j]:=w[i];
end;
inc(i);
end;
SetLength(Result,j);
end;
function IsProbablyHTML(const x:WideString):boolean;
var
i:integer;
begin
i:=1;
while (i<=Length(x)) and (x[i]<=' ') do inc(i); //skip whitespace
Result:=(i<=Length(x)) and (x[i]='<');
end;
function VarArrFirst(const v:Variant):Variant;
begin
if VarIsArray(v) then
Result:=v[VarArrayLowBound(v,1)]
else
Result:=Null;
end;
function VarArrLast(const v:Variant):Variant;
begin
if VarIsArray(v) and (VarArrayHighBound(v,1)>=VarArrayLowBound(v,1)) then
Result:=v[VarArrayHighBound(v,1)]
else
Result:=Null;
end;
end.
|
unit uDrawClass;
interface
uses
Vcl.Graphics, System.Classes;
type
tEntType = (etLine, etRectangle, etCircle);
TDrawClass = class(TObject)
private
FList : TList;
public
constructor Create;
destructor Destroy; override;
procedure Add(AEntType:tEntType);
procedure Draw;
end;
implementation
{ TDrawClass }
procedure TDrawClass.Add(AEntType: tEntType);
var
ent : TEntity;
begin
case AEntType of
etLine : ent := TLine.Create();
etRectangle : TRectangle.Create();
etCircle : TCircle.Create();
end;
FList.Add(ent)
end;
constructor TDrawClass.Create;
begin
FList := TList.Create;
end;
destructor TDrawClass.Destroy;
begin
FList.Free;
inherited;
end;
end.
|
unit DirectoryEnum;
interface
uses UniStrUtils;
{Enumerates files in a directory and possibly subdirectories,
and adds them to the list.}
procedure EnumFiles_in(dir, mask: string; subdirs: boolean; var files: TStringArray);
procedure EnumAddFiles(fname: string; subdirs: boolean; var files: TStringArray);
function EnumFiles(fname: string; subdirs: boolean): TStringArray;
procedure AddFile(var files: TStringArray; fname: string); inline;
implementation
uses SysUtils;
procedure AddFile(var files: TStringArray; fname: string); inline;
begin
SetLength(files, Length(files)+1);
files[Length(files)-1] := fname;
end;
{Enumerates files in a directory and possibly subdirectories,
and adds them to the list.}
procedure EnumFiles_in(dir, mask: string; subdirs: boolean; var files: TStringArray);
var SearchRec: TSearchRec;
res: integer;
begin
//First we look through files
res := FindFirst(dir + '\' + mask, faAnyFile and not faDirectory, SearchRec);
while (res = 0) do begin
AddFile(files, dir + '\' + SearchRec.Name);
res := FindNext(SearchRec);
end;
SysUtils.FindClose(SearchRec);
//If no subdir scan is planned, then it's over.
if not subdirs then exit;
//Else we go through subdirectories
res := FindFirst(dir + '\' + '*.*', faAnyFile, SearchRec);
while (res = 0) do begin
//Ignore . and ..
if (SearchRec.Name='.')
or (SearchRec.Name='..') then begin
end else
//Default - directory
if ((SearchRec.Attr and faDirectory) = faDirectory) then
EnumFiles_in(dir + '\' + SearchRec.Name, mask, subdirs, files);
res := FindNext(SearchRec);
end;
SysUtils.FindClose(SearchRec);
end;
procedure EnumAddFiles(fname: string; subdirs: boolean; var files: TStringArray);
var dir: string;
mask: string;
begin
//Single file => no scan
if FileExists(fname) then begin
AddFile(files, fname);
exit;
end;
if DirectoryExists(fname) then begin
dir := fname;
mask := '*.*';
end else begin
dir := ExtractFilePath(fname);
mask := ExtractFileName(fname);
if mask='' then
mask := '*.*';
end;
EnumFiles_in(dir, mask, subdirs, files);
end;
function EnumFiles(fname: string; subdirs: boolean): TStringArray;
begin
SetLength(Result, 0);
EnumAddFiles(fname, subdirs, Result);
end;
end. |
unit ACMOut;
{Version modifiée pour quelques essais}
{-----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: ACMOut.pas, released August 28, 2000.
The Initial Developer of the Original Code is Peter Morris (pete@stuckindoors.com),
Portions created by Peter Morris are Copyright (C) 2000 Peter Morris.
All Rights Reserved.
Purpose of file:
Allows you to open an audio-output stream, in almost any format
Contributor(s):
None as yet
Last Modified: September 14, 2000
Current Version: 1.00
You may retrieve the latest version of this file at http://www.stuckindoors.com/dib
Known Issues:
TrueSpeech doesn't work for some reason.
-----------------------------------------------------------------------------}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
MMSystem;
type
EACMOut = class(Exception);
TBufferPlayedEvent = procedure(Sender : TObject; Header : PWaveHDR) of object;
TACMOut = class(TComponent)
private
{ Private declarations }
FActive : Boolean;
FNumBuffersLeft : Byte;
FBackBufferList : TList;
FNumBuffers : Byte;
FBufferList : TList;
FFormat : TWaveFormatEx;
FOnBufferPlayed : TBufferPlayedEvent;
FWaveOutHandle : HWaveOut;
FWindowHandle : HWnd;
function GetBufferCount: Integer;
protected
{ Protected declarations }
function NewHeader : PWaveHDR;
procedure DisposeHeader(Header : PWaveHDR);
procedure DoWaveDone(Header : PWaveHdr);
procedure WndProc(var Message : TMessage);
public
{ Public declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Close;
procedure Open(aFormat : TWaveFormatEx);
procedure Play(var Buffer; Size : Integer);
procedure RaiseException(const aMessage : String; Result : Integer);
property Active : Boolean
read FActive;
property BufferCount : Integer
read GetBufferCount;
property Format : TWaveFormatEx
read FFormat;
property WindowHandle : HWnd
read FWindowHandle;
published
{ Published declarations }
property NumBuffers : Byte
read FNumBuffers
write FNumBuffers;
property OnBufferPlayed : TBufferPlayedEvent
read FOnBufferPlayed
write FOnBufferPlayed;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Sound', [TACMOut]);
end;
{ TACMOut }
procedure TACMOut.Close;
var
X : Integer;
begin
if not Active then exit;
FActive := False;
WaveOutReset(FWaveOutHandle);
WaveOutClose(FWaveOutHandle);
FBackBufferList.Clear;
FWaveOutHandle := 0;
For X:=FBufferList.Count-1 downto 0 do DisposeHeader(PWaveHDR(FBufferList[X]));
end;
constructor TACMOut.Create(AOwner: TComponent);
begin
inherited;
FBufferList := TList.Create;
FBackBufferList := TList.Create;
FActive := False;
FWindowHandle := AllocateHWND(WndProc);
FWaveOutHandle := 0;
FNumBuffers := 4;
end;
destructor TACMOut.Destroy;
begin
if Active then Close;
FBufferList.Free;
DeAllocateHWND(FWindowHandle);
FBackBufferList.Free;
inherited;
end;
procedure TACMOut.DisposeHeader(Header: PWaveHDR);
var
X : Integer;
begin
X := FBufferList.IndexOf(Header);
if X < 0 then exit;
Freemem(header.lpData);
Freemem(header);
FBufferList.Delete(X);
end;
procedure TACMOut.DoWaveDone(Header : PWaveHdr);
var
Res : Integer;
begin
if not Active then exit;
if Assigned(FOnBufferPlayed) then FOnBufferPlayed(Self, Header);
Res := WaveOutUnPrepareHeader(FWaveOutHandle, Header, SizeOf(TWaveHDR));
if Res <> 0 then RaiseException('WaveOut-UnprepareHeader',Res);
DisposeHeader(Header);
end;
function TACMOut.GetBufferCount: Integer;
begin
Result := FBufferList.Count;
end;
function TACMOut.NewHeader: PWaveHDR;
begin
GetMem(Result, SizeOf(TWaveHDR));
FBufferList.Add(Result);
end;
procedure TACMOut.Open(aFormat: TWaveFormatEx);
var
Res : Integer;
Device : Integer;
Params : Integer;
begin
if Active then exit;
FWaveOutHandle := 0;
FNumBuffersLeft := FNumBuffers;
FFormat := aFormat;
if FFormat.wFormatTag = 1 then begin
Params := CALLBACK_WINDOW;
Device := -1;
end else begin
Params := CALLBACK_WINDOW or WAVE_MAPPED;
Device := 0;
end;
Res := WaveOutOpen(@FWaveOutHandle,Device,@FFormat,FWindowHandle,0, params);
if Res <> 0 then RaiseException('WaveOutOpen',Res);
FActive := True;
end;
procedure TACMOut.Play(var Buffer; Size: Integer);
var
TempHeader : PWaveHdr;
Data : Pointer;
Res : Integer;
X : Integer;
procedure PlayHeader(Header : PWaveHDR);
begin
Res := WaveOutPrepareHeader(FWaveOutHandle,Header,SizeOf(TWaveHDR));
if Res <> 0 then RaiseException('WaveOut-PrepareHeader',Res);
Res := WaveOutWrite(FWaveOutHandle, Header, SizeOf(TWaveHDR));
if Res <> 0 then RaiseException('WaveOut-Write',Res);
end;
begin
if Size = 0 then exit;
if not active then exit;
TempHeader := NewHeader;
GetMem(Data, Size);
Move(Buffer,Data^,Size);
with TempHeader^ do begin
lpData := Data;
dwBufferLength := Size;
dwBytesRecorded :=0; //Was " := Size;" but not needed, and crashes some PC's
dwUser := 0;
dwFlags := 0;
dwLoops := 1;
end;
if FNumBuffersLeft > 0 then begin
FBackBufferList.Add(TempHeader);
Dec(FNumBuffersLeft);
end else begin
for X:=0 to FBackBufferList.Count-1 do
PlayHeader(PWaveHDR(FBackBufferList[X]));
FBackBufferList.Clear;
PlayHeader(TempHeader);
end;
end;
procedure TACMOut.RaiseException(const aMessage: String; Result: Integer);
begin
end;
procedure TACMOut.WndProc(var Message: TMessage);
begin
case Message.Msg of
MM_WOM_DONE : DoWaveDone(PWaveHDR(Message.LParam));
end;
end;
end.
|
unit memoIHM;
Interface
uses memoJeu, memoTypes, crt, sysutils;
procedure difficulte(var taille : Integer);
procedure jeu(taille : Integer; var nbCoups : Integer);
procedure afficherGrille(taille : Integer; g : Grille);
procedure tour(taille : Integer; g : Grille; var x1, y1, x2, y2 : Integer);
procedure saisieCase(taille :Integer; var x, y : Integer);
procedure retournerCase(x, y : Integer; g : Grille);
procedure afficherScore(score : Integer);
Implementation
procedure difficulte(var taille : Integer);
var c : Char;
begin
writeln('Quelle difficulte voulez-vous? (f)acile ou (d)ifficile?');
repeat
readln(c);
case c of
'f' : taille := 4;
'd' : taille := 6;
else writeln('Difficulte non valide!')
end;
until (c = 'f') or (c = 'd');
ClrScr;
end;
////////////////////////////////////////////////////
procedure jeu(taille : Integer; var nbCoups : Integer);
var x, y, x1, y1, x2, y2, nbRetourne : Integer;
g : Grille;
begin
nbCoups := 0;
initGrille(taille, g);
GotoXY(1,12);
{for y := 1 to taille do
begin
for x := 1 to taille do
write(g[x][y].lettre);
writeln;
end;}
GotoXY(1, taille + 3);
write('X = ');
GotoXY(1, taille + 4);
write('Y = ');
GotoXY(1, taille + 6);
write(nbCoups);
repeat
nbRetourne := 0;
afficherGrille(taille,g);
tour(taille, g, x1, y1, x2, y2);
modifGrille(x1, y1, x2, y2, g);
for y := 1 to taille do
for x := 1 to taille do
if g[x][y].retourne then
nbRetourne := nbRetourne + 1;
nbCoups := nbCoups + 1;
GotoXY(1, taille + 6);
write(nbCoups);
until nbRetourne = taille*taille;
end;
procedure afficherGrille(taille : Integer; g : Grille);
var x, y : Integer;
begin
GotoXY(1,1);
for y := 1 to taille do
begin
for x := 1 to taille do
if g[x][y].retourne = True then
write(g[x][y].lettre + ' ')
else write('# ');
writeln;
end;
{GotoXY(1,20);
for y := 1 to taille do
begin
for x := 1 to taille do
write(g[x][y].retourne);
writeln;
end;}
end;
procedure tour(taille : Integer; g : Grille; var x1, y1, x2, y2 : Integer);
begin
saisieCase(taille, x1, y1);
retournerCase(x1, y1, g);
saisieCase(taille, x2, y2);
retournerCase(x2, y2, g);
sleep(1000);
end;
procedure saisieCase(taille : Integer; var x, y : Integer);
begin
repeat
GotoXY(5, taille + 3);
readln(x);
until (x > 0) and (x <= taille);
repeat
GotoXY(5, taille + 4);
readln(y);
until (y > 0) and (y <= taille);
end;
procedure retournerCase(x, y : Integer; g : Grille);
begin
GotoXY(2*x-1,y);
write(g[x][y].lettre);
end;
////////////////////////////////////////////////////
procedure afficherScore(score : Integer);
begin
ClrScr;
writeln('Score realise : ', score);
end;
END.
|
unit IlwisMap;
interface
uses sysutils, classes, ClueTypes;
const
bUNDEF : byte = 0;
iUNDEF : integer = -MaxInt;
type
TIlwisMap<T> = class
_name : string;
_georef : string;
_domain : string;
_rows : integer;
_cols : integer;
_buffer : TMatrix<T>;
private
data : TFileStream;
writer : TBinaryWriter;
procedure storeElem(value : T); overload;
procedure storeElem(value : byte); overload;
procedure storeElem(value : integer); overload;
public
constructor Create;
function map : TMatrix<T>;
function pixel(row: integer; col : integer) : T;
function line(row : integer) : TVector<T>;
procedure setMap(values : TMatrix<T>);
procedure store;
procedure storeMetadata;
function getNodata(v : T): T; overload;
function getNodata(v : byte): byte; overload;
function getNodata(v : integer): integer; overload;
property filename : string read _name write _name;
property rows : integer read _rows write _rows;
property cols : integer read _cols write _cols;
property georef : string read _georef write _georef;
property domain : string read _domain write _domain;
// property nodata : T read getNodata;
end;
TIlwisByteMap = TIlwisMap<byte>;
implementation
uses
typinfo, inifiles;
{ TIlwisByteMap }
constructor TIlwisMap<T>.Create;
begin
_buffer := nil;
end;
function TIlwisMap<T>.map: TMatrix<T>;
begin
if _buffer = nil then
; // do some loading ?
map := _buffer;
end;
function TIlwisMap<T>.pixel(row: integer; col : integer) : T;
begin
pixel := _buffer[row][col];
end;
function TIlwisMap<T>.getNodata(V : T): T;
//var
// info : PTypeInfo;
begin
// info := System.TypeInfo(T);
// case info^.Kind of
// tkChar : getNodata := bUNDEF;
// tkInteger : getNodata := iUNDEF;
// end;
end;
function TIlwisMap<T>.getNodata(V : byte): byte;
begin
getNodata := bUNDEF;
end;
function TIlwisMap<T>.getNodata(v : integer): integer;
begin
getNodata := iUNDEF;
end;
function TIlwisMap<T>.line(row: integer): TVector<T>;
begin
line := _buffer[row];
end;
procedure TIlwisMap<T>.setMap(values: TMatrix<T>);
begin
_buffer := values;
end;
procedure TIlwisMap<T>.store;
var
datafile : string;
row, col : integer;
begin
datafile := ChangeFileExt(_name, '.mp#');
data := TBufferedFileStream.Create(datafile, fmOpenWrite or fmCreate);
writer := TBinaryWriter.Create(data);
try
for row := 0 to _rows - 1 do
for col := 0 to _cols - 1 do
storeElem(_buffer[row][col]);
writer.Close;
finally
writer.Free;
data.Free;
end;
storeMetadata;
end;
procedure TIlwisMap<T>.storeElem(value: T);
begin
// empty on purpose
end;
procedure TIlwisMap<T>.storeElem(value: byte);
begin
writer.write(value);
end;
procedure TIlwisMap<T>.storeElem(value: integer);
begin
writer.Write(value);
end;
procedure TIlwisMap<T>.storeMetadata;
var
mprfile : TIniFile;
mprname : string;
datafile : string;
grfname : string;
domname : string;
info : PTypeInfo;
typeName : string;
begin
mprname := ChangeFileExt(_name, '.mpr');
datafile := ChangeFileExt(_name, '.mp#');
grfname := ChangeFileExt(_georef, '.grf');
domname := ChangeFileExt(_domain, '.dom');
mprfile := TIniFile.Create(mprname);
mprfile.WriteString('BaseMap', 'Domain', ExtractFileName(domname));
mprfile.WriteString('BaseMap', 'Type', 'Map');
mprfile.WriteString('Ilwis', 'Type', 'BaseMap');
mprfile.WriteString('Map', 'Type', 'MapStore');
mprfile.WriteString('Map', 'GeoRef', ExtractFileName(grfName));
mprfile.WriteString('Map', 'Size', format('%-4d %-4d', [rows, cols]));
info := System.TypeInfo(T);
typeName := string(info^.Name);
if typeName = 'Integer' then
typeName := 'Int';
mprfile.WriteString('MapStore', 'Type', typeName);
mprfile.WriteString('MapStore', 'Structure', 'Line');
mprfile.WriteString('MapStore', 'Data', ExtractFileName(datafile));
mprfile.Free;
end;
end.
|
unit FuncionarioAssalariadoComComissaoModel;
interface
uses
InterfaceFuncionarioModel;
type
TFuncionarioAssalariadoComComissaoModel = class(TInterfacedObject, IFuncionarioModel)
private
FNome: String;
FSalarioBase: Double;
FAliquotaComissao: Double;
function GetAliquotaComissao: Double; stdcall;
function GetNome: string; stdcall;
function GetSalarioBase: Double; stdcall;
public
function CalcularSalario(const pFaturamentoMes: Double): Double; stdcall;
constructor Create(const pNome: String; const pSalarioBase: Double; const pAliquotaComissao: Double);
end;
implementation
{ TFuncionarioAssalariadoComComissaoModel }
function TFuncionarioAssalariadoComComissaoModel.CalcularSalario(
const pFaturamentoMes: Double): Double;
begin
Result := Self.FSalarioBase + ((pFaturamentoMes * Self.FAliquotaComissao) / 100);
end;
constructor TFuncionarioAssalariadoComComissaoModel.Create(const pNome: String; const pSalarioBase,
pAliquotaComissao: Double);
begin
inherited Create();
Self.FNome := pNome;
Self.FSalarioBase := pSalarioBase;
Self.FAliquotaComissao := pAliquotaComissao;
end;
function TFuncionarioAssalariadoComComissaoModel.GetAliquotaComissao: Double;
begin
Result := Self.FAliquotaComissao;
end;
function TFuncionarioAssalariadoComComissaoModel.GetNome: string;
begin
Result := Self.FNome;
end;
function TFuncionarioAssalariadoComComissaoModel.GetSalarioBase: Double;
begin
Result := Self.FSalarioBase;
end;
end.
|
unit LanguageUnit;
interface
uses
LanguageStringMapUnit;
type
{ TLanguage }
TLanguage = class
protected
FStorage: TStringMap;
function GetItem(const aKey: string): string; inline;
function GetItemExists(const aKey: string): Boolean; inline;
public
property Storage: TStringMap read FStorage;
property Items[const aKey: string]: string read GetItem; default;
property ItemExists[const aKey: string]: Boolean read GetItemExists;
constructor Create(const aStorage: TStringMap);
function ToDebugText: string;
destructor Destroy; override;
end;
implementation
{ TLanguage }
function TLanguage.GetItem(const aKey: string): string;
begin
if
Storage.contains(aKey)
then
result := Storage[aKey]
else
result := '';
end;
function TLanguage.GetItemExists(const aKey: string): Boolean;
begin
result := Storage.contains(aKey);
end;
constructor TLanguage.Create(const aStorage: TStringMap);
begin
inherited Create;
FStorage := aStorage;
end;
function TLanguage.ToDebugText: string;
var
i: TStringMap.TIterator;
begin
i := Storage.Iterator;
if
i <> nil
then
begin
result := '';
repeat
result += '"' + i.Key + '": "' + i.Value + '"' + LineEnding;
until not i.Next;
i.Free;
end
else
result := 'no items' + LineEnding;
end;
destructor TLanguage.Destroy;
begin
Storage.Free;
inherited Destroy;
end;
end.
|
{
FCGIApp unit implements, in my opinion, the best behavior for Web applications: statefull, multi-threaded, blocking and non-multiplexed connection.
This is a native and full Object Pascal implementation that doesn't depend on DLLs or external libraries.
This unit is based on <extlink http://www.fastcgi.com/devkit/doc/fcgi-spec.html>FastCGI specs</extlink>, read it for more details.
The initial state in a <link TFCGIApplication, FastCGI application> is a listening socket, through which it accepts connections from a Web server.
After a FastCGI application <link TFCGIApplication.DoRun, accepts a connection on its listening socket>,
a <link TFCGIThread> is <link TFCGIThread.Create, created> that executes the FCGI protocol to <link TFCGIThread.ReadRequestHeader, receive> and <link TFCGIThread.SendResponse, send> data.
As the actual Web paradigm is based on non-related requests, FCGIApp uses a Cookie to relate requests of a same browser session.
This cookie is a <link TFCGIThread.SetCurrentFCGIThread, GUID that is associated> to actual <link TFCGIThread, Thread> address.
In this way a statefull and multi-thread behavior is provided.
-Limitations and architectural decisions:-
1. Multiplexing is not supported. Multiplexing don't works with Apache anyway. Indeed Apache don't supports Filter role.
2. Only Sockets is supported, because is more flexible providing the ability to run applications remotely, named pipes is not.
So IIS is not natively supported, use <link CGIGateway.dpr> instead.
3. Only Responder role is implemented.
4. Event-driven paradigm is not supported, instead FCGIApp uses extensively multi-thread approach.
Author: Wanderlan Santos dos Anjos (wanderlan.anjos@gmail.com)
Date: apr-2008
License: BSD<extlink http://www.opensource.org/licenses/bsd-license.php>BSD</extlink>
}
unit FCGIApp;
interface
uses
{$IFNDEF MSWINDOWS}cthreads,{$ENDIF}
BlockSocket, SysUtils, SyncObjs, Classes, ExtPascalClasses, ExtPascalUtils;
type
TFCGISession = class(TCustomWebSession)
protected
function CanCallAfterHandleRequest : Boolean; override;
function CanHandleUrlPath : Boolean; override;
procedure DoLogout; override;
procedure DoSetCookie(const Name, ValueRaw : string); override;
class function GetCurrentWebSession : TCustomWebSession; override;
function GetDocumentRoot : string; override;
function GetRequestHeader(const Name : string) : string; override;
function GetRequestBody: string; override;
function GetWebServer : string; override;
procedure SendResponse(const Msg : AnsiString); override;
function UploadBlockType(const Buffer : AnsiString; var MarkPos : Integer) : TUploadBlockType; override;
function UploadNeedUnknownBlock : Boolean; override;
public
constructor Create(AOwner: TObject); override;
end;
TWebSession = class(TFCGISession);
TFCGIThreadData = record
Session: TFCGISession;
end;
{
Statefull and multi-thread behavior for FastCGI applications. This class has a garbage collector that frees idle threads.
The initial state in a FastCGI application is a listening socket, through which it accepts connections from a Web server.
After a FastCGI application <link TFCGIApplication.DoRun, accepts a connection on its listening socket>,
a <link TFCGIThread> is <link TFCGIThread.Create, created> that executes the FCGI protocol to <link TFCGIThread.ReadRequestHeader, receive> and <link TFCGIThread.SendResponse, send> data.
}
TFCGIApplication = class(TCustomWebApplication)
private
FExeName : string;
FThreads: TStringList;
FThreadsCount : integer;
// Configurable options
MaxIdleTime : TDateTime;
WebServers : TStringList;
procedure GarbageThreads;
protected
function GetTerminated: Boolean; override;
public
GarbageNow : boolean; // Set to true to trigger the garbage colletor
Shutdown : boolean; // Set to true to shutdown the application after the last thread to end, default is false
AccessThreads: TCriticalSection;
property ExeName : string read FExeName;
procedure DoRun; override;
function CanConnect(Address : string) : boolean;
function GetThread(I : integer) : TThread;
function GetThreadData(const I: Integer): TFCGIThreadData;
function ThreadsCount : integer;
function ReachedMaxConns : boolean;
procedure OnPortInUseError; virtual;
constructor Create(const AOwner: TComponent;
pTitle : string; ASessionClass : TCustomWebSessionClass; pPort : word = 2014; pMaxIdleMinutes : word = 30;
pShutdownAfterLastThreadDown : boolean = false; pMaxConns : integer = 1000); reintroduce;
destructor Destroy; override;
procedure TerminateAllThreads;
end;
var
Application : TFCGIApplication = nil; // FastCGI application object
threadvar
_CurrentWebSession: TFCGISession; // current FastCGI session object
function CreateWebApplication(const ATitle : string; ASessionClass : TCustomWebSessionClass; APort : Word = 2014;
AMaxIdleMinutes : Word = 30; AShutdownAfterLastThreadDown : Boolean = False;
AMaxConns : Integer = 1000) : TFCGIApplication;
implementation
uses
StrUtils, Math;
function CreateWebApplication(const ATitle : string; ASessionClass : TCustomWebSessionClass; APort : Word = 2014;
AMaxIdleMinutes : Word = 30; AShutdownAfterLastThreadDown : Boolean = False;
AMaxConns : Integer = 1000) : TFCGIApplication; begin
Result := TFCGIApplication.Create(nil, ATitle, ASessionClass, APort, AMaxIdleMinutes, AShutdownAfterLastThreadDown, AMaxConns);
end;
type
// FastCGI record types, i.e. the general function that the record performs
TRecType = (rtBeginRequest = 1, rtAbortRequest, rtEndRequest, rtParams, rtStdIn, rtStdOut, rtStdErr, rtData, rtGetValues, rtGetValuesResult, rtUnknown);
// FastCGI roles, only Responder role is supported in this FCGIApp version
TRole = (rResponder = 1, rAuthorizer, rFilter);
// FastCGI level status code
TProtocolStatus = (psRequestComplete, psCantMPXConn, psOverloaded, psUnknownRole, psBusy);
// HTTP request methods
TRequestMethod = (rmGet, rmPost, rmHead, rmPut, rmDelete);
{
Each browser session generates a TFCGIThread. On first request it is <link TFCGIThread.Create, created> and a Cookie is associated with it.
On subsequent requests this <link TFCGIThread.SetCurrentFCGIThread, Cookie is read to recover the original thread address>.
Each request <link TFCGIThread.Execute, is interpreted as a FastCGI record and executed according> to its <link TRecType, record type>.
}
TFCGIThread = class(TThread)
private
FRequestID : word; // FastCGI request ID for this thread
FRole : TRole; // FastCGI Thread role
FRequestMethod : TRequestMethod; // Current HTTP request method
FSocket : TBlockSocket; // Current socket for current FastCGI request
FGarbage,
FKeepConn : boolean; // Not used
FRequest: RawByteString;
FRequestHeader : TStringList;
FSession : TFCGISession;
FLastAccess : TDateTime;
function CompleteRequestHeaderInfo(Buffer : AnsiString; I : integer) : boolean;
procedure CopyContextFrom(const AThread: TFCGIThread);
protected
procedure AddParam(var S : string; Param : array of string);
procedure ReadRequestHeader(var RequestHeader : TStringList; Stream : AnsiString; ParseCookies : Boolean = False);
procedure ReadBeginRequest(var FCGIHeader; Content : AnsiString);
procedure GetValues(Content : AnsiString);
function HandleRequest(pRequest : AnsiString) : AnsiString;
function SetCurrentFCGIThread : boolean;
public
BrowserCache : boolean; // If false generates 'cache-control:no-cache' and 'pragma:no-cache' in HTTP header, default is false
AccessThread : TCriticalSection;
property Role : TRole read FRole; // FastCGI role for the current request
property Request: RawByteString read FRequest; // Request body string
property LastAccess : TDateTime read FLastAccess; // Last TDateTime access of this thread
property RequestMethod : TRequestMethod read FRequestMethod; // HTTP request method for the current request
constructor Create(NewSocket : integer); reintroduce; virtual;
destructor Destroy; override;
procedure SendResponse(S : AnsiString; pRecType : TRecType = rtStdOut);
procedure Execute; override;
procedure SendEndRequest(Status : TProtocolStatus = psRequestComplete);
procedure SetResponseHeader(Header : string);
end;
threadvar
_CurrentFCGIThread : TFCGIThread; // Current FastCGI thread address assigned by <link TFCGIThread.SetCurrentFCGIThread, SetCurrentFCGIThread> method
type
// FastCGI header
TFCGIHeader = packed record
Version : byte; // FastCGI protocol version, ever constant 1
RecType : TRecType; // FastCGI record type
ID, // Is zero if management request else is data request. Used also to determine if the session is being multiplexed
Len : word; // FastCGI record length
PadLen : byte; // Pad length to complete the alignment boundery that is 8 bytes on FastCGI protocol
Filler : byte; // Pad field
end;
// <link TRecType, Begin request> record
TBeginRequest = packed record
Header : TFCGIHeader; // FastCGI header
Filler : byte; // Pad field
Role : TRole; // FastCGI role
KeepConn : boolean; // Keep connection
Filler2 : array[1..5] of byte; // Pad field
end;
{
Converts a Request string into a FastCGI Header
@param Buffer Input buffer to convert
@param FCGIHeader FastCGI header converted from Buffer
@see MoveFromFCGIHeader
}
procedure MoveToFCGIHeader(var Buffer : AnsiChar; var FCGIHeader : TFCGIHeader);
begin
move(Buffer, FCGIHeader, sizeof(TFCGIHeader));
{$IFNDEF FPC_BIG_ENDIAN}
FCGIHeader.ID := swap(FCGIHeader.ID);
FCGIHeader.Len := swap(FCGIHeader.Len);
{$ENDIF}
end;
{
Converts a Request string into a FastCGI Header
@param Buffer Input buffer to convert
@param FCGIHeader FastCGI header converted from Buffer
@see MoveToFCGIHeader
}
procedure MoveFromFCGIHeader(FCGIHeader : TFCGIHeader; var Buffer : AnsiChar);
begin
{$IFNDEF FPC_BIG_ENDIAN}
FCGIHeader.ID := swap(FCGIHeader.ID);
FCGIHeader.Len := swap(FCGIHeader.Len);
{$ENDIF}
move(FCGIHeader, Buffer, sizeof(TFCGIHeader));
end;
{
Creates a TFCGIThread to handle a new request to be read from the NewSocket parameter
@param NewSocket Socket to read a new request
}
constructor TFCGIThread.Create(NewSocket : integer);
begin
if Application.FThreadsCount < 0 then Application.FThreadsCount := 0;
inc(Application.FThreadsCount);
FSocket := TBlockSocket.Create(NewSocket);
FRequestHeader := TStringList.Create;
FRequestHeader.StrictDelimiter := true;
FSession := TFCGISession(Application.SessionClass.Create(Self));
FSession.FApplication := Application;
FSession.ContentType := 'text/html';
AccessThread := TCriticalSection.Create;
inherited Create;
end;
// Destroys the TFCGIThread invoking the Thread Garbage Collector to free the associated objects
destructor TFCGIThread.Destroy;
begin
// Assign _CurrentWebSession to avoid AV destroying Ext Objects that uses _CurrentWebSession
_CurrentWebSession := FSession;
AccessThread.Free;
FSession.Free;
FRequestHeader.Free;
dec(Application.FThreadsCount);
{$IFDEF MSWINDOWS}inherited;{$ENDIF} // Collateral effect of Unix RTL FPC bug
end;
{
Appends or cleans HTTP response header. The HTTP response header is sent using <link TFCGIThread.SendResponse, SendResponse> method.
@param Header Use '' to clean response header else Header parameter is appended to response header
}
procedure TFCGIThread.SetResponseHeader(Header : string);
begin
FSession.FCustomResponseHeaders.Add(Header);
end;
{
Sends a FastCGI response record to the Web Server. Puts the HTTP header in front of response, generates the FastCGI header and sends using sockets.
@param S String to format using FastCGI protocol
@param pRecType FastCGI record type
@see MoveFromFCGIHeader
@see TBlockSocket.SendString
}
procedure TFCGIThread.SendResponse(S : AnsiString; pRecType : TRecType = rtStdOut);
const
MAX_BUFFER = 65536 - sizeof(TFCGIHeader);
var
FCGIHeader : TFCGIHeader;
Buffer : AnsiString;
I : integer;
begin
if pRecType = rtStdOut then begin
if FRequestMethod = rmHead then S := '';
FSession.CustomResponseHeaders['content-type'] := FSession.ContentType;
if not BrowserCache and not FSession.IsDownload then begin
FSession.CustomResponseHeaders['cache-control'] := 'no-cache';
FSession.CustomResponseHeaders['pragma'] := 'no-cache';
end;
S := AnsiString(FSession.FCustomResponseHeaders.Text) + ^M^J + S;
FSession.FCustomResponseHeaders.Clear;
FSession.ContentType := 'text/html';
end;
fillchar(FCGIHeader, sizeof(FCGIHeader), 0);
with FCGIHeader do begin
Version := 1;
ID := IfThen(pRecType in [rtGetValuesResult, rtUnknown], 0, FRequestID);
RecType := pRecType;
I := 1;
repeat
Len := IfThen((length(S)-I+1) <= MAX_BUFFER, length(S)-I+1, MAX_BUFFER);
PadLen := Len mod 8;
SetLength(Buffer, sizeof(TFCGIHeader) + Len + PadLen);
MoveFromFCGIHeader(FCGIHeader, Buffer[1]);
move(S[I], Buffer[sizeof(TFCGIHeader) + 1], Len);
inc(I, Len);
FSocket.SendString(Buffer);
until I > length(S);
end;
end;
{
Sends an end request record to the Web Server and ends this thread.
@param Status Status of request. Default is psRequestComplete
}
procedure TFCGIThread.SendEndRequest(Status : TProtocolStatus = psRequestComplete);
begin
if Status <> psRequestComplete then begin
case Status of
psCantMPXConn : FSession.Alert('Multiplexing is not allowed.');
psOverloaded : FSession.Alert('Maximum connection limit is ' + IntToStr(Application.MaxConns) + ' and was reached.');
psUnknownRole : FSession.Alert('Unknown FastCGI Role received.');
psBusy : ;//Alert('Session is busy, try later.');
end;
SendResponse(FSession.EncodeResponse);
end;
SendResponse(#0#0#0#0#0#0#0#0, rtEndRequest);
Terminate;
end;
{
Reads the begin request record from FastCGI request to the thread.
@param FCGIHeader FastCGI Header
@param Content Additional bytes from FastCGI request
}
procedure TFCGIThread.ReadBeginRequest(var FCGIHeader; Content : AnsiString);
var
BeginRequest : TBeginRequest;
begin
FLastAccess := Now;
BeginRequest.Header := TFCGIHeader(FCGIHeader);
move(Content[1], BeginRequest.Filler, sizeof(BeginRequest)-sizeof(TFCGIHeader));
if BeginRequest.Role in [rResponder..rFilter] then begin
FRequestID := BeginRequest.Header.ID;
FRole := BeginRequest.Role;
FKeepConn := BeginRequest.KeepConn; // can't close socket if true
end
else
SendEndRequest(psUnknownRole);
end;
{
Reads HTTP headers and cookies from FastCGI rtParams record type
@param RequestHeader List of HTTP headers to initialize
@param Stream rtParams record type body
@param Cookies List of HTTP cookies to initialize
}
procedure TFCGIThread.ReadRequestHeader(var RequestHeader : TStringList; Stream : AnsiString; ParseCookies : Boolean = False);
var
I, Pos : integer;
Len : array[0..1] of integer;
Param : array[0..1] of AnsiString;
begin
RequestHeader.Clear;
if ParseCookies then FSession.FCookies.Clear;
Pos := 1;
while Pos < length(Stream) do begin
for I := 0 to 1 do begin
Len[I] := byte(Stream[Pos]);
if Len[I] > 127 then begin
Len[I] := ((byte(Stream[Pos]) and $7F) shl 24) + (byte(Stream[Pos+1]) shl 16) + (byte(Stream[Pos+2]) shl 8) + byte(Stream[Pos+3]);
inc(Pos, 4);
end
else
inc(Pos);
SetLength(Param[I], Len[I]);
end;
if Len[0] > 0 then move(Stream[Pos], Param[0][1], Len[0]);
inc(Pos, Len[0]);
if Len[1] > 0 then move(Stream[Pos], Param[1][1], Len[1]);
inc(Pos, Len[1]);
if Param[0] = 'HTTP_COOKIE' then begin
if ParseCookies then FSession.FCookies.DelimitedText := URLDecode(string(Param[1]))
end
else
RequestHeader.Values[string(Param[0])] := string(Param[1]);
end;
end;
// Sets FLastAccess, FPathInfo, FRequestMethod and FQuery internal fields
function TFCGIThread.CompleteRequestHeaderInfo(Buffer : AnsiString; I : integer) : boolean;
var
ReqMet, CT : string;
begin
FLastAccess := Now;
with FSession do begin
FPathInfo := FRequestHeader.Values['PATH_INFO'];
if FPathInfo = '' then // Windows 2003 Server bug
FPathInfo := copy(FRequestHeader.Values['SCRIPT_NAME'], length(ScriptName) + 1, 100)
else
FPathInfo := copy(FPathInfo, 2, 100);
end;
ReqMet := FRequestHeader.Values['REQUEST_METHOD'];
case ReqMet[1] of
'G' : FRequestMethod := rmGet;
'P' :
if ReqMet = 'POST' then
FRequestMethod := rmPost
else
FRequestMethod := rmPut;
'H' : FRequestMethod := rmHead;
'D' : FRequestMethod := rmDelete;
end;
FSession.SetQueryText(FRequestHeader.Values['QUERY_STRING'], True, False);
FSession.IsUpload := false;
CT := FSession.RequestHeader['CONTENT_TYPE'];
if pos('multipart/form-data', CT) <> 0 then FSession.UploadPrepare(CT, Buffer, I);
Result := FSession.IsUpload
end;
{
Adds a pair Name/Value to a FastCGI rtGetValuesResult <link TRecType, record type>
@param S Body of rtGetValuesResult <link TRecType, record type>
@param Param Pair Name/Value
}
procedure TFCGIThread.AddParam(var S : string; Param : array of string);
var
I, J : integer;
Len : array[0..1] of integer;
Format : array[0..1] of integer;
begin
for I := 0 to 1 do begin
Len[I] := length(Param[I]);
if Len[I] <= 127 then
Format[I] := 1
else
Format[I] := 4;
end;
J := length(S);
SetLength(S, J + Len[0] + Format[0] + Len[1] + Format[1]);
inc(J);
for I := 0 to 1 do begin
if Format[I] = 1 then
S[J] := char(Len[I])
else begin
S[J] := char(((Len[I] shr 24) and $FF) + $80);
S[J+1] := char( (Len[I] shr 16) and $FF);
S[J+2] := char( (Len[I] shr 8) and $FF);
S[J+3] := char( Len[I] and $FF);
end;
inc(J, Format[I]);
end;
move(Param[0][1], S[J], Len[0]);
move(Param[1][1], S[J + Len[0]], Len[1]);
end;
{
Handles the FastCGI rtGetValues record type and sends a rtgetValuesResult record type
@param Body of rtGetValues record type
}
procedure TFCGIThread.GetValues(Content : AnsiString);
var
Values : TStringList;
GetValuesResult : string;
begin
if Content = '' then exit;
Values := TStringList.Create;
ReadRequestHeader(Values, Content);
GetValuesResult := '';
if Values.IndexOf('FCGI_MAX_CONNS') <> -1 then AddParam(GetValuesResult, ['FCGI_MAX_CONNS', IntToStr(Application.MaxConns)]);
if Values.IndexOf('FCGI_MAX_REQS') <> -1 then AddParam(GetValuesResult, ['FCGI_MAX_REQS', IntToStr(Application.MaxConns)]);
if Values.IndexOf('FCGI_MPXS_CONNS') <> -1 then AddParam(GetValuesResult, ['FCGI_MPXS_CONNS', '0']);
Values.Free;
SendResponse(AnsiString(GetValuesResult), rtGetValuesResult);
end;
{
Sets the context of current thread to the context of associated session using a cookie (<b>FCGIThread</b>).
When a browser session sends its first request this method associates the current browser session, this first thread, to a new cookie (<b>FCGIThread</b>),
whose value is a <extlink http://en.wikipedia.org/wiki/GUID>GUID</extlink>.
In subsequent requests this cookie is the key to find the browser session, i.e. the original <link TFCGIThread, Thread>.
In this way a statefull and multi-thread behavior is provided.
@return False if it fails to find the session associated with the cookie, for example if the session already expired.
}
function TFCGIThread.SetCurrentFCGIThread : boolean;
var
LPathInfo: string;
LPos: Integer;
LSessionId: string;
I : integer;
begin
Result := true;
Application.AccessThreads.Enter;
try
// Extract optional namespace from URL. URLs come in the forms:
// /$<namespace> (root, with namespace)
// /$<namespace>/<methodname>
// / (root, no namespace)
// <methodname>
LPathInfo := FRequestHeader.Values['PATH_INFO'];
if Pos('/$', LPathInfo) = 1 then
begin
Delete(LPathInfo, 1, 1); // remove first /.
LPos := Pos('/', LPathInfo);
if LPos > 0 then
FSession.NameSpace := Copy(LPathInfo, 1, LPos - 1)
else
FSession.NameSpace := LPathInfo;
end
else
FSession.NameSpace := '';
FSession.ScriptName := FRequestHeader.Values['SCRIPT_NAME'];
LSessionId := FSession.SessionCookie;
if LSessionId = '' then begin
// No session - make a new one and send the cookie to the client.
LSessionId := FSession.CreateNewSessionId;
FSession.SessionCookie := LSessionId;
FSession.SessionGUID := LSessionId;
I := -1;
end
else
I := Application.FThreads.IndexOf(LSessionId);
if I = -1 then begin
FSession.NewThread := true;
AccessThread.Enter;
if Application.ReachedMaxConns then begin
SendEndRequest(psOverloaded);
Result := false;
end
else begin
Application.FThreads.AddObject(LSessionId, Self);
FSession.AfterNewSession;
end;
end
else begin
_CurrentFCGIThread := TFCGIThread(Application.FThreads.Objects[I]);
_CurrentFCGIThread.AccessThread.Enter;
_CurrentWebSession := _CurrentFCGIThread.FSession;
_CurrentFCGIThread.CopyContextFrom(Self);
_CurrentFCGIThread.FSession.NewThread := false;
_CurrentFCGIThread.FSession.FCustomResponseHeaders.Clear;
_CurrentFCGIThread.FSession.ContentType := 'text/html';
FreeOnTerminate := True;
end;
finally
Application.AccessThreads.Leave;
end;
end;
procedure TFCGIThread.CopyContextFrom(const AThread: TFCGIThread);
begin
StrToTStrings(AThread.FRequestHeader.DelimitedText, FRequestHeader);
FSession.CopyContextFrom(AThread.FSession);
end;
{
The thread main loop.<p>
On receive a request, each request, on its execution cycle, does:
* <link MoveToFCGIHeader, Reads its FCGI header>
* Depending on <link TRecType, record type> does:
* <link TFCGIThread.ReadBeginRequest, Starts a request> or
* <link TFCGIThread.Logout, Aborts the request> or
* <link TFCGIThread.SendEndRequest, Ends the request> or
* <link TFCGIThread.ReadRequestHeader, Reads HTTP headers> or
* <link TFCGIThread.HandleRequest, Handles the request> with these internal steps:
* <link TFCGIThread.BeforeHandleRequest, BeforeHandleRequest>
* The <link TFCGIThread.HandleRequest, HandleRequest> own method
* <link TFCGIThread.AfterHandleRequest, AfterHandleRequest>
}
procedure TFCGIThread.Execute;
var
FCGIHeader : TFCGIHeader;
Buffer, Content : RawByteString;
I: Integer;
begin
_CurrentFCGIThread := Self;
_CurrentWebSession := FSession;
FRequest := '';
try
if Application.CanConnect(string(FSocket.GetHostAddress)) then
begin
repeat
if FSocket.WaitingData > 0 then begin
Buffer := FSocket.RecvPacket;
if FSocket.Error <> 0 then
Terminate
else begin
I := 1;
while I <= length(Buffer) do begin
MoveToFCGIHeader(Buffer[I], FCGIHeader);
if (FRequestID <> 0) and (FCGIHeader.ID <> 0) and (FCGIHeader.ID <> FRequestID) then
SendEndRequest(psCantMPXConn)
else begin
inc(I, sizeof(FCGIHeader));
Content := Copy(Buffer, I, FCGIHeader.Len);
case FCGIHeader.RecType of
rtBeginRequest : ReadBeginRequest(FCGIHeader, Content);
rtAbortRequest : FSession.Logout;
rtGetValues : GetValues(Content);
rtParams, rtStdIn, rtData :
if Content = '' then
begin
if FCGIHeader.RecType = rtParams then
begin
ReadRequestHeader(FRequestHeader, AnsiString(FRequest), True);
if SetCurrentFCGIThread then
begin
FSession.IsUpload := _CurrentFCGIThread.CompleteRequestHeaderInfo(Buffer, I);
FSession.MaxUploadSize := _CurrentFCGIThread.FSession.MaxUploadSize;
FSession.AcceptedWildCards := _CurrentFCGIThread.FSession.AcceptedWildCards;
if FSession.IsUpload then
begin
FSession.FFileUploaded := _CurrentFCGIThread.FSession.FFileUploaded;
FSession.FFileUploadedFullName := _CurrentFCGIThread.FSession.FFileUploadedFullName;
FSession.Response := _CurrentFCGIThread.FSession.Response;
FSession.UploadMark := _CurrentFCGIThread.FSession.UploadMark;
end;
end
else
Break;
end
else
begin
_CurrentFCGIThread.FSession.IsUpload := FSession.IsUpload;
_CurrentFCGIThread.FSession.Response := FSession.Response;
FSession.Response := string(_CurrentFCGIThread.HandleRequest(AnsiString(FRequest)));
FSession.FCustomResponseHeaders.Text := _CurrentFCGIThread.FSession.FCustomResponseHeaders.Text;
FSession.ContentType := _CurrentFCGIThread.FSession.ContentType;
FGarbage := _CurrentFCGIThread.FGarbage;
FSession.IsDownload := _CurrentFCGIThread.FSession.IsDownload;
if (FSession.Response <> '') or (RequestMethod in [rmGet, rmHead]) then
begin
if FSession.IsDownload then
SendResponse(AnsiString(FSession.Response))
else
SendResponse(FSession.EncodeResponse);
end;
SendEndRequest;
end;
FRequest := '';
end
else
if FSession.IsUpLoad then
FSession.UploadWriteFile(Content)
else
begin
FRequest := FRequest + Content;
end
else
SendResponse(AnsiChar(FCGIHeader.RecType), rtUnknown);
Buffer := '';
Sleep(200);
Break;
end;
end;
Inc(I, FCGIHeader.Len + FCGIHeader.PadLen);
end;
end;
end
else
Sleep(5);
until Terminated;
end
else
Terminate;
except
on E: Exception do
begin
Content := AnsiString(E.ClassName + ': ' + E.Message + ' at ' + IntToStr(Integer(ExceptAddr)));
SendResponse(Content);
SendResponse(Content, rtStdErr);
SendEndRequest;
end;
end;
_CurrentFCGIThread.AccessThread.Leave;
FSocket.Free;
if FGarbage then begin
_CurrentFCGIThread.FLastAccess := 0;
FLastAccess := 0;
Application.GarbageNow := true;
end;
{$IFNDEF MSWINDOWS}EndThread(0){$ENDIF} // Unix RTL FPC bug
end;
{
Calls the published method indicated by PathInfo. Before calls <link TFCGIThread.BeforeHandleRequest, BeforeHandleRequest> method and after calls <link TFCGIThread.AfterHandleRequest, AfterHandleRequest> method.
If PathInfo is null then <link TFCGIThread.Home, Home> method will be called.
The published method will use the Request as input and the Response as output.
<link TFCGIThread.OnError, OnError> method is called if an exception is raised in published method.
<link TFCGIThread.OnNotFoundError, OnNotFoundError> method is called if the published method is not declared in this thread.
@param pRequest Request body assigned to FRequest field or to <link TFCGIThread.Query, Query> array if FRequestMethod is <link TRequestMethod, rmPost>, it is the input to the published method
@return Response body to <link TFCGIThread.SendResponse, send>
}
function TFCGIThread.HandleRequest(pRequest : AnsiString) : AnsiString;
begin
if (FRequestMethod = rmPost) and (Pos(AnsiString('='), pRequest) <> 0) then
FSession.SetQueryText(string(pRequest), True, True);
FRequest := pRequest;
if not FSession.IsUpload then FSession.Response := '';
FSession.IsDownload := false;
FSession.HandleRequest(pRequest);
if FSession.IsDownload or (FSession.IsUpload and (FSession.Browser = brIE)) then
Result := AnsiString(FSession.Response)
else
Result := FSession.EncodeResponse;
end;
// Frees a TFCGIApplication
destructor TFCGIApplication.Destroy;
begin
FThreads.Free;
AccessThreads.Free;
WebServers.Free;
inherited;
end;
{
Creates a FastCGI application instance.
@param pTitle Application title used by <link TExtSession.AfterHandleRequest, AfterHandleRequest>
@param pFCGIThreadClass Thread class type to create when a new request arrives
@param pPort TCP/IP port used to comunicate with the Web Server, default is 2014
@param pMaxIdleMinutes Minutes of inactivity before the end of the thread, releasing it from memory, default is 30 minutes
@param pShutdownAfterLastThreadDown If true Shutdown the application after the last thread to end, default is false. Good for commercial CGI hosting.
@param pMaxConns Maximum accepted connections, default is 1000
}
constructor TFCGIApplication.Create(const AOwner: TComponent; pTitle : string;
ASessionClass: TCustomWebSessionClass; pPort : word = 2014;
pMaxIdleMinutes : word = 30; pShutdownAfterLastThreadDown : boolean = false;
pMaxConns : integer = 1000);
var
WServers : string;
begin
inherited Create(AOwner, pTitle, ASessionClass, pPort, pMaxIdleMinutes, pMaxConns);
Assert(Assigned(ASessionClass) and ASessionClass.InheritsFrom(TFCGISession));
FThreads := TStringList.Create;
AccessThreads := TCriticalSection.Create;
MaxIdleTime := EncodeTime(pMaxIdleMinutes div 60, pMaxIdleMinutes mod 60, 0, 0);
Shutdown := pShutdownAfterLastThreadDown;
WServers := GetEnvironmentVariable('FCGI_WEB_SERVER_ADDRS');
if WServers <> '' then begin
WebServers := TStringList.Create;
WebServers.DelimitedText := WServers;
end;
FExeName := ExtractFileName(ParamStr(0));
end;
{
Tests if Address parameter is an IP address in WebServers list
@param Address IP address to find
@return True if Address is in WebServers list
}
function TFCGIApplication.CanConnect(Address : string) : boolean;
begin
Result := (WebServers = nil) or (WebServers.IndexOf(Address) <> -1)
end;
{
Tests if MaxConns (max connections), default is 1000, was reached
@return True if was reached
}
function TFCGIApplication.ReachedMaxConns : boolean;
begin
Result := FThreads.Count >= MaxConns
end;
// Thread Garbage Collector. Frees all expired threads
procedure TFCGIApplication.GarbageThreads;
var
I : integer;
Thread : TFCGIThread;
begin
for I := FThreads.Count-1 downto 0 do begin
Thread := TFCGIThread(FThreads.Objects[I]);
if (Now - Thread.LastAccess) > MaxIdleTime then begin
AccessThreads.Enter;
try
Thread.Free;
FThreads.Delete(I);
finally
AccessThreads.Leave;
end;
end;
end;
end;
// Frees all threads regardless of expiration
procedure TFCGIApplication.TerminateAllThreads;
var
I: Integer;
Thread: TFCGIThread;
begin
AccessThreads.Enter;
try
for I := FThreads.Count - 1 downto 0 do begin
Thread := TFCGIThread(FThreads.Objects[I]);
Thread.Free;
FThreads.Delete(I);
end;
finally
AccessThreads.Leave;
end;
end;
function TFCGIApplication.GetTerminated : Boolean;
begin
Result := inherited GetTerminated or (Shutdown and (ThreadsCount = 0));
end;
{
Returns the Ith thread
@param I Index of the thread to return
}
function TFCGIApplication.GetThread(I : integer) : TThread;
begin
Result := TThread(FThreads.Objects[I])
end;
function TFCGIApplication.GetThreadData(const I: Integer): TFCGIThreadData;
var
LThread: TFCGIThread;
begin
LThread := TFCGIThread(FThreads.Objects[I]);
Result.Session := LThread.FSession;
end;
{
Handles "Port #### already in use" error. Occurs when the port is already in use for another service or application.
Can be overrided in descendent thread class. It shall be overrided if the application is a service.
@see Create
@see DoRun
}
procedure TFCGIApplication.OnPortInUseError;
begin
writeln('Port: ', Port, ' already in use.');
sleep(10000);
end;
{
The application main loop. Listens a socket port, through which it accepts connections from a Web server.
For each connection a <link TFCGIThread> is <link TFCGIThread.Create, created> that executes the FCGI protocol
to <link TFCGIThread.ReadRequestHeader, receive> and <link TFCGIThread.SendResponse, send> data.
@param OwnerThread Optional parameter to use with a service thread, see ExtPascalSamples.pas.
When this thread is terminated the application is terminated too.
}
procedure TFCGIApplication.DoRun;
var
NewSocket, I : integer;
begin
I := 0;
FThreadsCount := -1;
with TBlockSocket.Create do begin
try
Bind(Port, 1000);
if Error = 0 then
begin
repeat
NewSocket := Accept(250);
if NewSocket <> 0 then
TFCGIThread.Create(NewSocket);
if ((I mod 40) = 0) or GarbageNow then begin // A garbage for each 10 seconds
GarbageThreads;
GarbageNow := false;
I := 0;
end;
inc(I);
until Terminated;
TerminateAllThreads;
end
else
OnPortInUseError;
finally
Free;
end;
end;
end;
// Returns the number of active threads
function TFCGIApplication.ThreadsCount : integer;
begin
Result := FThreadsCount
end;
{ TFCGISession }
constructor TFCGISession.Create(AOwner: TObject);
begin
Assert(AOwner is TFCGIThread);
inherited Create(AOwner);
end;
function TFCGISession.CanCallAfterHandleRequest : Boolean;
begin
Result := True;
end;
function TFCGISession.CanHandleUrlPath : Boolean;
begin
Result := not IsUpload or (Pos('success:true', Response) <> 0);
end;
procedure TFCGISession.DoLogout;
begin
inherited;
TFCGIThread(Owner).FGarbage := True;
end;
procedure TFCGISession.DoSetCookie(const Name, ValueRaw : string);
begin
CustomResponseHeaders['Set-Cookie'] := Name + '=' + ValueRaw;
end;
class function TFCGISession.GetCurrentWebSession : TCustomWebSession;
begin
Result := _CurrentWebSession;
end;
function TFCGISession.GetDocumentRoot : string;
begin
Result := RequestHeader['DOCUMENT_ROOT'];
if (Result <> '') and CharInSet(Result[Length(Result)], ['/', '\']) then
Delete(Result, Length(Result), 1);
end;
function TFCGISession.GetRequestBody: string;
var
LContent: RawByteString;
I: Integer;
LBytes: TBytes;
begin
LContent := TFCGIThread(Owner).Request;
SetLength(LBytes, Length(LContent));
for I := 1 to Length(LContent) do
LBytes[I - 1] := Byte(LContent[I]);
Result := TEncoding.UTF8.GetString(LBytes);
end;
function TFCGISession.GetRequestHeader(const Name : string) : string;
begin
Result := TFCGIThread(Owner).FRequestHeader.Values[Name];
end;
function TFCGISession.GetWebServer : string;
begin
Result := RequestHeader['Server_Software'];
if Result = '' then Result := 'Embedded';
end;
procedure TFCGISession.SendResponse(const Msg : AnsiString);
begin
TFCGIThread(Owner).SendResponse(Msg);
end;
function TFCGISession.UploadBlockType(const Buffer : AnsiString; var MarkPos : Integer) : TUploadBlockType;
begin
MarkPos := Pos(UploadMark, Buffer);
case MarkPos of
0 : Result := ubtMiddle;
1 : Result := ubtBegin;
else
Result := ubtEnd;
end;
end;
function TFCGISession.UploadNeedUnknownBlock : Boolean;
begin
Result := True;
end;
initialization
finalization
if Application <> nil then Application.Free;
end.
|
unit Tests;
interface
uses
VRS,
Player,
Crypto,
Errors,
Situation;
procedure TestPlayer(isNeedCreate:boolean);
procedure TestVRS;
procedure TestSituation;
procedure TestCrypto;
implementation
procedure TestPlayer(isNeedCreate:boolean);
var
sUserBuf:string;
pPlayer:TPlayer;
begin
writeln('Testing player.pas module.');
if isNeedCreate then begin
writeln('Trying to create new player...');
writeln('Name - from keyboard');
writeln('Health - 100%');
writeln('Password - 12345');
writeln('ID - random');
writeln('Current situation - 0');
write('Enter player name: ');
readln(sUserBuf);
sUserBuf:=Trim(sUserBuf);
if sUserBuf = '' then begin
writeln('Invalid input. Test canceled.');
exit;
end;
pPlayer:=TPlayer.Create;
pPlayer.CreateNewPlayer(sUserBuf, True);
pPlayer.SetHealth(100);
pPlayer.SetPlayerPassword('12345');
pPlayer.SetSituation(0);
writeln('Trying to update the player file...');
if pPlayer.UpdatePlayerFile=0
then writeln('Success')
else writeln('Shit');
end else begin
writeln('Testing LoadFromFile method');
write('Enter name of existing player: ');
readln(sUserBuf);
pPlayer:=TPlayer.Create;
writeln('Exec result: ', pPlayer.LoadPlayerFromFile(sUserBuf+'.pl'));
writeln('Name: ', pPlayer.GetName);
writeln('Health: ', pPlayer.GetHealth);
writeln('Password: ', pPlayer.GetPlayerPassword);
writeln('ID: ', pPlayer.GetPlayerID);
writeln('Current situation: ', pPlayer.GetSituation);
writeln('Test done.');
end;
end;
procedure TestCrypto;
begin
end;
procedure TestSituation;
var
sSit:TSituation;
begin
writeln('Testing situation.pas module');
writeln('Creating TSituation instance...');
sSit:=TSituation.Create;
writeln('isFileOpened: ', sSit.GetFileOpened);
writeln('isFileAssigned: ', sSit.GetFileAssigned);
{writeln('Creating new file...');
writeln('Exec result: ', sSit.CreateFile('testOpen.sit', true));
writeln('isFileOpened: ', sSit.GetFileOpened);
writeln('isFileAssigned: ', sSit.GetFileAssigned);}
writeln('Opening existing file...');
writeln('Exec result: ', sSit.OpenFile('testOpen.sit'));
writeln('isFileOpened: ', sSit.GetFileOpened);
writeln('isFileAssigned: ', sSit.GetFileAssigned);
writeln('Adding new record...');
writeln('Text: First record. How r u going to deal with it?');
writeln('Exec result: ', sSit.AddSituation('First record. How r u going to deal with it?', '4235', True));
writeln('Situation ID: ', sSit.GetSitID);
writeln('Situation Text: ', sSit.GetSitText);
writeln('Situation VRSs: ', sSit.GetSitVRSs);
end;
procedure TestVRS;
var
VRS:TVRS;
begin
writeln('Testing VRS.pas module');
writeln('Creating TVRS instance...');
VRS:=TVRS.Create;
writeln('isFileOpened: ', VRS.GetFileOpened);
writeln('isFileAssigned:' , VRS.GetFileAssigned);
//Для начала нужно присвоить файл
writeln('AssignVRSFile: ', VRS.AssignVRSFile('VRSs.vrs'));
//Пересоздаем файл
writeln('CreateVRSFile: ', VRS.CreateVRSFile(true));
//Алгоритм записи
//Генерируем новую запись
writeln('GenNewVRS: ', VRS.GenNewVRS);
//Заполняем остальные поля
VRS.SetText('Huyhuyhuyhuy');
VRS.SetSitLink(5);
//Сохраняем
writeln('SaveCurVRS: ', VRS.SaveCurVRS);
//Еще одну
writeln('GenNewVRS: ', VRS.GenNewVRS);
VRS.SetText('sdgfsdfgserghsetbsertfhdrtfhdrthdrth');
VRS.SetSitLink(23);
writeln('SaveCurVRS: ', VRS.SaveCurVRS);
writeln('isFileOpened: ', VRS.GetFileOpened);
writeln('isFileAssigned:' , VRS.GetFileAssigned);
end;
end.
|
{: Sample showing use of TGLSprite for "caterpillar" effect.<p>
A bunch of TGLSprite is created in FormCreate, all copied from Sprite2 (used
as "template"), then we move and resize them as they orbit a pulsating "star".<br>
Textures are loaded from a "flare1.bmp" file that is expected to be in the
same directory as the compiled EXE.<p>
There is nothing really fancy in this code, but in the objects props :<ul>
<li>blending is set to bmAdditive (for the color saturation effect)
<li>DepthTest is disabled
<li>ball color is determined with the Emission color
</ul><br>
The number of sprites is low to avoid stalling a software renderer
(texture alpha-blending is a costly effect), if you're using a 3D hardware,
you'll get FPS in the hundredths and may want to make the sprite count higher.<p>
A material library component is used to store the material (and texture) for
all the sprites, if we don't use it, sprites will all maintain their own copy
of the texture, which would just be a waste of resources. With the library,
only one texture exists (well, two, the sun has its own).
}
unit Unit1;
interface
uses
Forms, GLScene, GLObjects, StdCtrls, GLTexture, Classes, Controls, ExtCtrls,
GLCadencer, GLLCLViewer, GLCrossPlatform, GLMaterial, GLProxyObjects,
GLCoordinates;
type
{ TForm1 }
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
DummyCube1: TGLDummyCube;
GLCamera1: TGLCamera;
Sprite1: TGLSprite;
Sprite2: TGLSprite;
GLMaterialLibrary1: TGLMaterialLibrary;
Timer1: TTimer;
GLCadencer1: TGLCadencer;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: double);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses SysUtils, GLVectorGeometry, FileUtil;
procedure TForm1.FormCreate(Sender: TObject);
var
picName: string;
i: integer;
spr: TGLSprite;
path: UTF8String;
p: integer;
begin
path := ExtractFilePath(ParamStrUTF8(0));
p := Pos('DemosLCL', path);
Delete(path, p + 5, Length(path));
path := IncludeTrailingPathDelimiter(path) + 'media';
SetCurrentDirUTF8(path);
// Load texture for sprite2, this is the hand-coded way using a PersistentImage
// Sprite1 uses a PicFileImage, and so the image is automagically loaded by
// GLScene when necessary (no code is required).
// (Had I used two PicFileImage, I would have avoided this code)
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('flare1.bmp');
Sprite1.Material.Texture.Assign(GLMaterialLibrary1.Materials[0].Material.Texture);
// New sprites are created by duplicating the template "sprite2"
for i := 1 to 9 do
begin
spr := TGLSprite(DummyCube1.AddNewChild(TGLSprite));
spr.Assign(sprite2);
end;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double);
var
i: integer;
a, aBase: double;
begin
// angular reference : 90° per second <=> 4 second per revolution
aBase := 90 * newTime;
// "pulse" the star
a := DegToRad(aBase);
Sprite1.SetSquareSize(4 + 0.2 * cos(3.5 * a));
// rotate the sprites around the yellow "star"
for i := 0 to DummyCube1.Count - 1 do
begin
a := DegToRad(aBase + i * 8);
with (DummyCube1.Children[i] as TGLSprite) do
begin
// rotation movement
Position.X := 4 * cos(a);
Position.Z := 4 * sin(a);
// ondulation
Position.Y := 2 * cos(2.1 * a);
// sprite size change
SetSquareSize(2 + cos(3 * a));
end;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
// update FPS count and reset counter
Caption := Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
// This lines take cares of auto-zooming.
// magic numbers explanation :
// 333 is a form width where things looks good when focal length is 50,
// ie. when form width is 333, uses 50 as focal length,
// when form is 666, uses 100, etc...
GLCamera1.FocalLength := Width * 50 / 333;
end;
end.
|
unit DrdDataSet;
{***********************************************************}
{ ...::: DRD SISTEMAS :::... }
{ www.drdsistemas.com.br }
{ Programador........: Eduardo Silva dos Santos. }
{ Tester.............: Uélita Giacomim da Silva. }
{ Função do Módulo...: Componente com Múltiplos SQL's }
{ Data de Criação....: 24/04/2002 -- 22:20 }
{ Observações........: }
{ }
{***********************************************************}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DB,
{MyDAC}
MyAccess, DBAccess;
type
TCallSQL = (csSelect, csInsert, csUpdate, csDelete,
csOther1, csOther2, csOther3, csOther4, csOther5,
csOther6,csOther7,csOther8,csOther9,csOther10,csOther11,
csOther12,csOther13,csOther14,csOther15);
type
TDRDQuery = class( TMyQuery ) //Muda a classe Ascendete caso necessário..
private
{ Private declarations }
FSQLSelect, FSQLInsert, FSQLUpdate, FSQLDelete,
FSQLOther1, FSQLOther2, FSQLOther3, FSQLOther4, FSQLOther5,
FSQLOther6,FSQLOther7,FSQLOther8,FSQLOther9 ,FSQLOther10,
FSQLOther11,FSQLOther12,FSQLOther13,FSQLOther14,FSQLOther15: TStrings;
procedure SetSelect(Value: TStrings);
procedure SetInsert(Value: TStrings);
procedure SetUpdate(Value: TStrings);
procedure SetDelete(Value: TStrings);
procedure SetOther1(Value: TStrings);
procedure SetOther2(Value: TStrings);
procedure SetOther3(Value: TStrings);
procedure SetOther4(Value: TStrings);
procedure SetOther5(Value: TStrings);
procedure SetOther6(Value: TStrings);
procedure SetOther7(Value: TStrings);
procedure SetOther8(Value: TStrings);
procedure SetOther9(Value: TStrings);
procedure SetOther10(Value: TStrings);
procedure SetOther11(Value: TStrings);
procedure SetOther12(Value: TStrings);
procedure SetOther13(Value: TStrings);
procedure SetOther14(Value: TStrings);
procedure SetOther15(Value: TStrings);
protected
{ Protected declarations }
property SQL;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CallSQL(Value: TCallSQL; lPrepare: Boolean = False);
published
{ Published declarations }
property SQL_Select: TStrings read FSQLSelect write SetSelect;
property SQL_Insert: TStrings read FSQLInsert write SetInsert;
property SQL_Update: TStrings read FSQLUpdate write SetUpdate;
property SQL_Delete: TStrings read FSQLDelete write SetDelete;
property SQL_Other1: TStrings read FSQLOther1 write SetOther1;
property SQL_Other2: TStrings read FSQLOther2 write SetOther2;
property SQL_Other3: TStrings read FSQLOther3 write SetOther3;
property SQL_Other4: TStrings read FSQLOther4 write SetOther4;
property SQL_Other5: TStrings read FSQLOther5 write SetOther5;
property SQL_Other6: TStrings read FSQLOther6 write SetOther6;
property SQL_Other7: TStrings read FSQLOther7 write SetOther7;
property SQL_Other8: TStrings read FSQLOther8 write SetOther8;
property SQL_Other9: TStrings read FSQLOther9 write SetOther9;
property SQL_Other10: TStrings read FSQLOther10 write SetOther10;
property SQL_Other11: TStrings read FSQLOther11 write SetOther11;
property SQL_Other12: TStrings read FSQLOther12 write SetOther12;
property SQL_Other13: TStrings read FSQLOther13 write SetOther13;
property SQL_Other14: TStrings read FSQLOther14 write SetOther14;
property SQL_Other15: TStrings read FSQLOther15 write SetOther15;
end;
procedure Register;
implementation
constructor TDRDQuery.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSQLSelect := TStringList.Create;
FSQLInsert := TStringList.Create;
FSQLUpdate := TStringList.Create;
FSQLDelete := TStringList.Create;
FSQLOther1 := TStringList.Create;
FSQLOther2 := TStringList.Create;
FSQLOther3 := TStringList.Create;
FSQLOther4 := TStringList.Create;
FSQLOther5 := TStringList.Create;
FSQLOther6 := TStringList.Create;
FSQLOther7 := TStringList.Create;
FSQLOther8 := TStringList.Create;
FSQLOther9 := TStringList.Create;
FSQLOther10 := TStringList.Create;
FSQLOther11 := TStringList.Create;
FSQLOther12 := TStringList.Create;
FSQLOther13 := TStringList.Create;
FSQLOther14 := TStringList.Create;
FSQLOther15 := TStringList.Create;
end;
procedure TDRDQuery.SetSelect(Value: TStrings);
begin
if SQL_Select.Text <> Value.Text then
begin
SQL_Select.BeginUpdate;
try
SQL_Select.Assign(Value);
finally
SQL_Select.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetInsert(Value: TStrings);
begin
if SQL_Insert.Text <> Value.Text then
begin
SQLInsert.BeginUpdate;
try
SQLInsert.Assign(Value);
finally
SQLInsert.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetUpdate(Value: TStrings);
begin
if SQL_Update.Text <> Value.Text then
begin
SQLUpdate.BeginUpdate;
try
SQLUpdate.Assign(Value);
finally
SQLUpdate.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetDelete(Value: TStrings);
begin
if SQL_Delete.Text <> Value.Text then
begin
SQLDelete.BeginUpdate;
try
SQLDelete.Assign(Value);
finally
SQLDelete.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther1(Value: TStrings);
begin
if SQL_Other1.Text <> Value.Text then begin
SQL_Other1.BeginUpdate;
try
SQL_Other1.Assign(Value);
finally
SQL_Other1.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther2(Value: TStrings);
begin
if SQL_Other2.Text <> Value.Text then
begin
SQL_Other2.BeginUpdate;
try
SQL_Other2.Assign(Value);
finally
SQL_Other2.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther3(Value: TStrings);
begin
if SQL_Other3.Text <> Value.Text then
begin
SQL_Other3.BeginUpdate;
try
SQL_Other3.Assign(Value);
finally
SQL_Other3.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther4(Value: TStrings);
begin
if SQL_Other4.Text <> Value.Text then
begin
SQL_Other4.BeginUpdate;
try
SQL_Other4.Assign(Value);
finally
SQL_Other4.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther5(Value: TStrings);
begin
if SQL_Other5.Text <> Value.Text then
begin
SQL_Other5.BeginUpdate;
try
SQL_Other5.Assign(Value);
finally
SQL_Other5.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther6(Value: TStrings);
begin
if SQL_Other6.Text <> Value.Text then
begin
SQL_Other6.BeginUpdate;
try
SQL_Other6.Assign(Value);
finally
SQL_Other6.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther7(Value: TStrings);
begin
if SQL_Other7.Text <> Value.Text then
begin
SQL_Other7.BeginUpdate;
try
SQL_Other7.Assign(Value);
finally
SQL_Other7.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther8(Value: TStrings);
begin
if SQL_Other8.Text <> Value.Text then
begin
SQL_Other8.BeginUpdate;
try
SQL_Other8.Assign(Value);
finally
SQL_Other8.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther9(Value: TStrings);
begin
if SQL_Other9.Text <> Value.Text then
begin
SQL_Other9.BeginUpdate;
try
SQL_Other9.Assign(Value);
finally
SQL_Other9.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther10(Value: TStrings);
begin
if SQL_Other10.Text <> Value.Text then
begin
SQL_Other10.BeginUpdate;
try
SQL_Other10.Assign(Value);
finally
SQL_Other10.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther11(Value: TStrings);
begin
if SQL_Other11.Text <> Value.Text then
begin
SQL_Other11.BeginUpdate;
try
SQL_Other11.Assign(Value);
finally
SQL_Other11.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther12(Value: TStrings);
begin
if SQL_Other12.Text <> Value.Text then
begin
SQL_Other12.BeginUpdate;
try
SQL_Other12.Assign(Value);
finally
SQL_Other12.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther13(Value: TStrings);
begin
if SQL_Other13.Text <> Value.Text then
begin
SQL_Other13.BeginUpdate;
try
SQL_Other13.Assign(Value);
finally
SQL_Other13.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther14(Value: TStrings);
begin
if SQL_Other14.Text <> Value.Text then
begin
SQL_Other14.BeginUpdate;
try
SQL_Other14.Assign(Value);
finally
SQL_Other14.EndUpdate;
end;
end;
end;
procedure TDRDQuery.SetOther15(Value: TStrings);
begin
if SQL_Other15.Text <> Value.Text then
begin
SQL_Other15.BeginUpdate;
try
SQL_Other15.Assign(Value);
finally
SQL_Other15.EndUpdate;
end;
end;
end;
procedure TDRDQuery.CallSQL(Value: TCallSQL; lPrepare: Boolean = False);
begin
Close;
SQL.Clear; // Seleciona o SQL a utilizar
case Value of
csSelect: SQL.AddStrings(FSQLSelect);
csInsert: SQL.AddStrings(FSQLInsert);
csUpdate: SQL.AddStrings(FSQLUpdate);
csDelete: SQL.AddStrings(FSQLDelete);
csOther1: SQL.AddStrings(FSQLOther1);
csOther2: SQL.AddStrings(FSQLOther2);
csOther3: SQL.AddStrings(FSQLOther3);
csOther4: SQL.AddStrings(FSQLOther4);
csOther5: SQL.AddStrings(FSQLOther5);
csOther6: SQL.AddStrings(FSQLOther6);
csOther7: SQL.AddStrings(FSQLOther7);
csOther8: SQL.AddStrings(FSQLOther8);
csOther9: SQL.AddStrings(FSQLOther9);
csOther10: SQL.AddStrings(FSQLOther10);
csOther11: SQL.AddStrings(FSQLOther11);
csOther12: SQL.AddStrings(FSQLOther12);
csOther13: SQL.AddStrings(FSQLOther13);
csOther14: SQL.AddStrings(FSQLOther14);
csOther15: SQL.AddStrings(FSQLOther15);
end;
// if lPrepare then
// Prepare; se colocar para preparar da problema pq os parametros ainda não foram passados.
end;
destructor TDRDQuery.Destroy;
begin
FreeAndNil( FSQLSelect );
FreeAndNil( FSQLInsert );
FreeAndNil( FSQLUpdate );
FreeAndNil( FSQLDelete );
FreeAndNil( FSQLOther1 );
FreeAndNil( FSQLOther2 );
FreeAndNil( FSQLOther3 );
FreeAndNil( FSQLOther4 );
FreeAndNil( FSQLOther5 );
FreeAndNil( FSQLOther6 );
FreeAndNil( FSQLOther7 );
FreeAndNil( FSQLOther8 );
FreeAndNil( FSQLOther9 );
FreeAndNil( FSQLOther10 );
FreeAndNil( FSQLOther11 );
FreeAndNil( FSQLOther12 );
FreeAndNil( FSQLOther13 );
FreeAndNil( FSQLOther14 );
FreeAndNil( FSQLOther15 );
inherited Destroy;
end;
procedure Register;
begin
RegisterComponents('ARTHUS', [TDRDQuery]);
end;
end.
|
program Unit1;
uses Crt, SysUtils;
{------------------------------------------------------------------------------}
Procedure Password;
const Quick = 400;
Slow = 1500;
var
key, guess : string;
begin
key := 'Winter is coming';
ClrScr; TextColor(White);
Window(20, 7, 60, 8); TextBackground(Red); ClrScr;
WriteLn(' Game of Thrones');
repeat
Window(20,8,60,12);
TextBackground(White);
TextColor(Black);
Clrscr;
Write('Password: ');
TextColor(blue);
ReadLn(guess);
Delay(Quick);
if guess <> key then
begin
TextColor(Red);
GotoXY(15,3);
WriteLn('Incorrect password!');
Delay(Slow);
end;
until key = guess;
end;
{------------------------------------------------------------------------------}
Procedure MainMenu(var x : char);
begin
Window(1,1,80,25);
TextBackground(Black);
ClrScr;
TextColor(White);
Repeat
Clrscr;
WriteLn('----------------');
WriteLn('Choose:');
WriteLn('----------------');
WriteLn('A) 1st practise;');
WriteLn('B) 2nd practise;');
WriteLn('C) 3rd practise;');
WriteLn('D) 4th practise;');
WriteLn('E) Shuffle it.');
WriteLn('----------------');
Write('Your choice: ');
ReadLn(x);
WriteLn('----------------');
x := UpCase(x);
until (x = 'A') or (x = 'B') or (x = 'C') or (x = 'D') or (x = 'E') or (x = 'F');
end;
{------------------------------------------------------------------------------}
Procedure SubMenuA(x : char; var y : string);
begin
ClrScr;
if x = 'A' then
begin
Repeat
Clrscr;
WriteLn('------------------------');
Writeln('Choose:');
WriteLn('------------------------');
Writeln('A1) English - Lithuanian');
Writeln('A2) Lithuanian - English');
WriteLn('------------------------');
Write('Your choice: ');
Readln(y);
WriteLn('------------------------');
y := UpperCase(y);
Until (y = 'A1') or (y = 'A2');
end;
end;
{------------------------------------------------------------------------------}
Procedure SubMenuB(x : char; var y : string);
begin
ClrScr;
if (x = 'B') then
begin
repeat
Clrscr;
WriteLn('------------------------');
Writeln('Choose:');
WriteLn('------------------------');
Writeln('B1) English - Lithuanian');
Writeln('B2) Lithuanian - English');
WriteLn('------------------------');
Write('Choice: ');
Readln(y);
WriteLn('------------------------');
y := UpperCase(y);
until (y = 'B1') or (y = 'B2');
end;
end;
{------------------------------------------------------------------------------}
Procedure SubMenuC(x : char; var y : string);
begin
ClrScr;
if (x = 'C') then
begin
Repeat
Clrscr;
WriteLn('------------------------');
Writeln('Choose:');
WriteLn('------------------------');
Writeln('C1) English - Lithuanian');
Writeln('C2) Lithuanian - English');
WriteLn('------------------------');
Write('Choise: ');
Readln(y);
WriteLn('------------------------');
y := UpperCase(y);
Until (y = 'C1') or (y = 'C2');
end;
end;
{------------------------------------------------------------------------------}
Procedure SubMenuD(x : char; var y : string);
begin
ClrScr;
if (x = 'D') then
begin
Repeat
Clrscr;
WriteLn('------------------------');
Writeln('Choose:');
WriteLn('------------------------');
Writeln('D1) English - Lithuanian');
Writeln('D2) Lithuanian - English');
WriteLn('------------------------');
Write('Choise: ');
Readln(y);
WriteLn('------------------------');
y := UpperCase(y);
Until (y = 'D1') or (y = 'D2');
end;
end;
{------------------------------------------------------------------------------}
Procedure SubMenuE(x : char; var y : string);
begin
ClrScr;
if (x = 'E') then
begin
Repeat
Clrscr;
WriteLn('------------------------');
Writeln('Choose:');
WriteLn('------------------------');
Writeln('E1) English - Lithuanian');
Writeln('E2) Lithuanian - English');
WriteLn('------------------------');
Write('Choise: ');
Readln(y);
WriteLn('------------------------');
y := UpperCase(y);
Until (y = 'E1') or (y = 'E2');
end;
end;
{------------------------------------------------------------------------------}
Procedure A1(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'A1') then
begin
ClrScr;
Write('hackles - ');
ReadLn(g);
i := i + 1;
if (g <> 'suns karciai') and (g <> 'arklio karciai') and (g <> 'karciai') and (g <> 'neislaikyti') and (g <> 'gaidzio kaklo plunksnos') and (g <> 'kaklo plunksnos') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (suns, arklio) karciai, (gaidzio) kaklo plunksnos');
TextColor(White);
end;
Write('slender - ');
ReadLn(g);
i := i + 1;
if (g <> 'lieknas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: lieknas');
TextColor(White);
end;
Write('mounted - ');
ReadLn(g);
i := i + 1;
if (g <> 'raitas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: raitas');
TextColor(White);
end;
Write('tower - ');
ReadLn(g);
i := i + 1;
if (g <> 'kysoti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: kysoti');
TextColor(White);
end;
Write('supple - ');
ReadLn(g);
i := i + 1;
if (g <> 'lankstus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: lankstus');
TextColor(White);
end;
Write('gleam - ');
ReadLn(g);
i := i + 1;
if (g <> 'spindeti') and (g <> 'sviesti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: spindeti, sviesti');
TextColor(White);
end;
Write('layer - ');
ReadLn(g);
i := i + 1;
if (g <> 'sluoksnis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sluoksnis');
TextColor(White);
end;
Write('vocation - ');
ReadLn(g);
i := i + 1;
if (g <> 'pasaukimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: pasaukimas');
TextColor(White);
end;
Write('insofar as - ');
ReadLn(g);
i := i + 1;
if (g <> 'tiek, kiek') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: tiek, kiek');
TextColor(White);
end;
Write('sable - ');
ReadLn(g);
i := i + 1;
if (g <> 'sabalo kailis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sabalo kailis');
TextColor(White);
end;
Write('reflect - ');
ReadLn(g);
i := i + 1;
if (g <> 'apmastyti') and (g <> 'mastyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (ap)mastyti');
TextColor(White);
end;
Write('adjust - ');
ReadLn(g);
i := i + 1;
if (g <> 'sureguliuoti') and (g <> 'prisitaikyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: prisitaikyti, sureguliuoti');
TextColor(White);
end;
Write('drape - ');
ReadLn(g);
i := i + 1;
if (g <> 'apmusalas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: apmusalas');
TextColor(White);
end;
Write('clad - ');
ReadLn(g);
i := i + 1;
if (g <> 'aprengtas') and (g <> 'apsirenges') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: aprengtas, apsirenges');
TextColor(White);
end;
Write('cocksure - ');
ReadLn(g);
i := i + 1;
if (g <> 'tikras') and (g <> 'isitikines') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: tikras, isitikines');
TextColor(White);
end;
Write('pace - ');
ReadLn(g);
i := i + 1;
if (g <> 'greitis') and (g <> 'tempas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: greitis, tempas');
TextColor(White);
end;
Write('deign - ');
ReadLn(g);
i := i + 1;
if (g <> 'teiktis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: teiktis');
TextColor(White);
end;
Write('sheath - ');
ReadLn(g);
i := i + 1;
if (g <> 'makstis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: makstis');
TextColor(White);
end;
Write('acquiescence - ');
ReadLn(g);
i := i + 1;
if (g <> 'sutikimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sutikimas');
TextColor(White);
end;
Write('grope - ');
ReadLn(g);
i := i + 1;
if (g <> 'ieskoti apgraibomis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: ieskoti apgraibomis');
TextColor(White);
end;
Write('parry - ');
ReadLn(g);
i := i + 1;
if (g <> 'apsigynimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: apsigynimas');
TextColor(White);
end;
Write('well - ');
ReadLn(g);
i := i + 1;
if (g <> 'plusti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: plusti');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure A2(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'A2') then
begin
ClrScr;
Write('(suns, arklio) karciai, (gaidzio) kaklo plunksnos - ');
ReadLn(g);
i := i + 1;
if (g <> 'hackles') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: hackles');
TextColor(White);
end;
Write('lieknas - ');
ReadLn(g);
i := i + 1;
if (g <> 'slender') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: slender');
TextColor(White);
end;
Write('raitas - ');
ReadLn(g);
i := i + 1;
if (g <> 'mounted') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: mounted');
TextColor(White);
end;
Write('kysoti - ');
ReadLn(g);
i := i + 1;
if (g <> 'tower') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: tower');
TextColor(White);
end;
Write('lankstus - ');
ReadLn(g);
i := i + 1;
if (g <> 'supple') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: supple');
TextColor(White);
end;
Write('spindeti, sviesti - ');
ReadLn(g);
i := i + 1;
if (g <> 'gleam') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gleam');
TextColor(White);
end;
Write('sluoksnis - ');
ReadLn(g);
i := i + 1;
if (g <> 'layer') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: layer');
TextColor(White);
end;
Write('pasaukimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'vocation') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: vocation');
TextColor(White);
end;
Write('tiek, kiek - ');
ReadLn(g);
i := i + 1;
if (g <> 'insofar as') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: insofar as');
TextColor(White);
end;
Write('sabalo kailis - ');
ReadLn(g);
i := i + 1;
if (g <> 'sable') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sable');
TextColor(White);
end;
Write('(ap)mastyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'reflect') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: reflect');
TextColor(White);
end;
Write('sureguliuoti, prisitaikyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'adjust') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: adjust');
TextColor(White);
end;
Write('apmusalas - ');
ReadLn(g);
i := i + 1;
if (g <> 'drape') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: drape');
TextColor(White);
end;
Write('aprengtas, apsirenges - ');
ReadLn(g);
i := i + 1;
if (g <> 'clad') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: clad');
TextColor(White);
end;
Write('tikras, isitikines - ');
ReadLn(g);
i := i + 1;
if (g <> 'cocksure') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: cocksure');
TextColor(White);
end;
Write('greitis, tempas - ');
ReadLn(g);
i := i + 1;
if (g <> 'pace') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: pace');
TextColor(White);
end;
Write('teiktis - ');
ReadLn(g);
i := i + 1;
if (g <> 'deign') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: deign');
TextColor(White);
end;
Write('makstis - ');
ReadLn(g);
i := i + 1;
if (g <> 'sheath') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sheath');
TextColor(White);
end;
Write('sutikimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'acquiescence') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: acquiescence');
TextColor(White);
end;
Write('ieskoti apgraibomis - ');
ReadLn(g);
i := i + 1;
if (g <> 'grope') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: grope');
TextColor(White);
end;
Write('apsigynimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'parry') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: parry');
TextColor(White);
end;
Write('plusti - ');
ReadLn(g);
i := i + 1;
if (g <> 'well') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: well');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure B1(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'B1') then
begin
ClrScr;
Write('crispness - ');
ReadLn(g);
i := i + 1;
if (g <> 'gaivumas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gaivumas');
TextColor(White);
end;
Write('hint - ');
ReadLn(g);
i := i + 1;
if (g <> 'uzsiminti') and (g <> 'padaryti uzuomina') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: uzsiminti, padaryti uzuomina');
TextColor(White);
end;
Write('forth - ');
ReadLn(g);
i := i + 1;
if (g <> 'pirmyn') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: pirmyn');
TextColor(White);
end;
Write('behead - ');
ReadLn(g);
i := i + 1;
if (g <> 'nukirsti galva') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nukirsti galva');
TextColor(White);
end;
Write('deem - ');
ReadLn(g);
i := i + 1;
if (g <> 'manyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: manyti');
TextColor(White);
end;
Write('hearth - ');
ReadLn(g);
i := i + 1;
if (g <> 'zidinys') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: zidinys');
TextColor(White);
end;
Write('ward - ');
ReadLn(g);
i := i + 1;
if (g <> 'ginklanesys') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: ginklanesys');
TextColor(White);
end;
Write('bastard - ');
ReadLn(g);
i := i + 1;
if (g <> 'nesantuokinis') and (g <> 'pavainikis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nesantuokinis, pavainikis');
TextColor(White);
end;
Write('bolt - ');
ReadLn(g);
i := i + 1;
if (g <> 'leisti begti') and (g <> 'mestis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: leisti begti, mestis');
TextColor(White);
end;
Write('stump - ');
ReadLn(g);
i := i + 1;
if (g <> 'kelmas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: kelmas');
TextColor(White);
end;
Write('forfeit - ');
ReadLn(g);
i := i + 1;
if (g <> 'prarastas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: prarastas');
TextColor(White);
end;
Write('bannerman - ');
ReadLn(g);
i := i + 1;
if (g <> 'veliavnesys') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: veliavnesys');
TextColor(White);
end;
Write('antler - ');
ReadLn(g);
i := i + 1;
if (g <> 'elnio ragai') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: elnio ragai');
TextColor(White);
end;
Write('dismay - ');
ReadLn(g);
i := i + 1;
if (g <> 'isgastis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: isgastis');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure B2(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'B2') then
begin
ClrScr;
Write('gaivumas - ');
ReadLn(g);
i := i + 1;
if (g <> 'crispness') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: crispness');
TextColor(White);
end;
Write('uzsiminti, padaryti uzuomina - ');
ReadLn(g);
i := i + 1;
if (g <> 'hint') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: hint');
TextColor(White);
end;
Write('pirmyn - ');
ReadLn(g);
i := i + 1;
if (g <> 'forth') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: forth');
TextColor(White);
end;
Write('nukirsti galva - ');
ReadLn(g);
i := i + 1;
if (g <> 'behead') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: behead');
TextColor(White);
end;
Write('manyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'deem') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: deem');
TextColor(White);
end;
Write('zidinys - ');
ReadLn(g);
i := i + 1;
if (g <> 'hearth') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: hearth');
TextColor(White);
end;
Write('ginklanesys - ');
ReadLn(g);
i := i + 1;
if (g <> 'ward') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: ward');
TextColor(White);
end;
Write('nesantuokinis, pavainikis - ');
ReadLn(g);
i := i + 1;
if (g <> 'bastard') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: bastard');
TextColor(White);
end;
Write('leistis begti, mestis - ');
ReadLn(g);
i := i + 1;
if (g <> 'bolt') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: bolt');
TextColor(White);
end;
Write('kelmas - ');
ReadLn(g);
i := i + 1;
if (g <> 'stump') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: stump');
TextColor(White);
end;
Write('prarastas - ');
ReadLn(g);
i := i + 1;
if (g <> 'forfeit') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: forfeit');
TextColor(White);
end;
Write('veliavnesys - ');
ReadLn(g);
i := i + 1;
if (g <> 'bannerman') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: bannerman');
TextColor(White);
end;
Write('elnio ragai - ');
ReadLn(g);
i := i + 1;
if (g <> 'antler') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: antler');
TextColor(White);
end;
Write('isgastis - ');
ReadLn(g);
i := i + 1;
if (g <> 'dismay') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: dismay');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure C1(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'C1') then
begin
ClrScr;
Write('moist - ');
ReadLn(g);
i := i + 1;
if (g <> 'dregnas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: dregnas');
TextColor(White);
end;
Write('decay - ');
ReadLn(g);
i := i + 1;
if (g <> 'gedimas') and (g <> 'puvimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gedimas, puvimas');
TextColor(White);
end;
Write('anoint - ');
ReadLn(g);
i := i + 1;
if (g <> 'patepti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: patepti');
TextColor(White);
end;
Write('bark - ');
ReadLn(g);
i := i + 1;
if (g <> 'zieve') and (g <> 'tosis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: zieve, tosis');
TextColor(White);
end;
Write('forge - ');
ReadLn(g);
i := i + 1;
if (g <> 'nukalti') and (g <> 'kalti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (nu)kalti');
TextColor(White);
end;
Write('rueful - ');
ReadLn(g);
i := i + 1;
if (g <> 'gailus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gailus');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure C2(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'C2') then
begin
ClrScr;
Write('dregnas - ');
ReadLn(g);
i := i + 1;
if (g <> 'moist') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: moist');
TextColor(White);
end;
Write('gedimas, puvimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'decay') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: decay');
TextColor(White);
end;
Write('patepti - ');
ReadLn(g);
i := i + 1;
if (g <> 'anoint') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: anoint');
TextColor(White);
end;
Write('zieve, tosis - ');
ReadLn(g);
i := i + 1;
if (g <> 'bark') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: bark');
TextColor(White);
end;
Write('(nu)kalti - ');
ReadLn(g);
i := i + 1;
if (g <> 'forge') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: forge');
TextColor(White);
end;
Write('gailus - ');
ReadLn(g);
i := i + 1;
if (g <> 'rueful') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: rueful');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure D1(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'D1') then
begin
ClrScr;
Write('hold up - ');
ReadLn(g);
i := i + 1;
if (g <> 'laikyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: laikyti');
TextColor(White);
end;
Write('gown - ');
ReadLn(g);
i := i + 1;
if (g <> 'vakarine suknia') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: vakarine suknia');
TextColor(White);
end;
Write('inspection - ');
ReadLn(g);
i := i + 1;
if (g <> 'apziurejimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: apziurejimas');
TextColor(White);
end;
Write('caress - ');
ReadLn(g);
i := i + 1;
if (g <> 'paglostyti') and (g <> 'glostyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (pa)glostyti');
TextColor(White);
end;
Write('smooth - ');
ReadLn(g);
i := i + 1;
if (g <> 'svelnus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: svelnus');
TextColor(White);
end;
Write('nigh - ');
ReadLn(g);
i := i + 1;
if (g <> 'arti') and (g <> 'netoli') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: arti, netoli');
TextColor(White);
end;
Write('pamper - ');
ReadLn(g);
i := i + 1;
if (g <> 'islepinti') and (g <> 'lepinti') and (g <> 'ispaikinti') and (g <> 'lepinti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (is)lepinti, (is)paikinti');
TextColor(White);
end;
Write('meekly - ');
ReadLn(g);
i := i + 1;
if (g <> 'romiai') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: romiai');
TextColor(White);
end;
Write('wistfully - ');
ReadLn(g);
i := i + 1;
if (g <> 'ilgesingai') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: ilgesingai');
TextColor(White);
end;
Write('estate - ');
ReadLn(g);
i := i + 1;
if (g <> 'zemes valda') and (g <> 'dvaras') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: zemes valda, dvaras');
TextColor(White);
end;
Write('scent - ');
ReadLn(g);
i := i + 1;
if (g <> 'iskvepinti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: iskvepinti');
TextColor(White);
end;
Write('fragrant - ');
ReadLn(g);
i := i + 1;
if (g <> 'aromatingas') and (g <> 'kvapnus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: aromatingas, kvapnus');
TextColor(White);
end;
Write('enrapture - ');
ReadLn(g);
i := i + 1;
if (g <> 'suzaveti') and (g <> 'zaveti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (su)zaveti');
TextColor(White);
end;
Write('trifling - ');
ReadLn(g);
i := i + 1;
if (g <> 'nereiksmingas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nereiksmingas');
TextColor(White);
end;
Write('affront - ');
ReadLn(g);
i := i + 1;
if (g <> 'izeidimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: izeidimas');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure D2(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'D2') then
begin
ClrScr;
Write('laikyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'hold up') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: hold up');
TextColor(White);
end;
Write('vakarine suknia - ');
ReadLn(g);
i := i + 1;
if (g <> 'gown') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gown');
TextColor(White);
end;
Write('apziurejimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'inspection') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: inspection');
TextColor(White);
end;
Write('(pa)glostyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'caress') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: caress');
TextColor(White);
end;
Write('svelnus - ');
ReadLn(g);
i := i + 1;
if (g <> 'smooth') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: smooth');
TextColor(White);
end;
Write('arti, netoli - ');
ReadLn(g);
i := i + 1;
if (g <> 'nigh') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nigh');
TextColor(White);
end;
Write('(is)lepinti, (is)paikinti - ');
ReadLn(g);
i := i + 1;
if (g <> 'pamper') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: pamper');
TextColor(White);
end;
Write('romiai - ');
ReadLn(g);
i := i + 1;
if (g <> 'meekly') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: meekly');
TextColor(White);
end;
Write('ilgesingai - ');
ReadLn(g);
i := i + 1;
if (g <> 'wistfully') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: wistfully');
TextColor(White);
end;
Write('zemes valda, dvaras - ');
ReadLn(g);
i := i + 1;
if (g <> 'estate') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: estate');
TextColor(White);
end;
Write('iskvepinti - ');
ReadLn(g);
i := i + 1;
if (g <> 'scent') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: scent');
TextColor(White);
end;
Write('aromatingas, kvapnus - ');
ReadLn(g);
i := i + 1;
if (g <> 'fragrant') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: fragrant');
TextColor(White);
end;
Write('(su)zaveti - ');
ReadLn(g);
i := i + 1;
if (g <> 'enrapture') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: enrapture');
TextColor(White);
end;
Write('nereiksmingas - ');
ReadLn(g);
i := i + 1;
if (g <> 'trifling') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: trifling');
TextColor(White);
end;
Write('izeidimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'affront') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: affront');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure E1(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'E1') then
begin
ClrScr;
Write('well - ');
ReadLn(g);
i := i + 1;
if (g <> 'plusti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: plusti');
TextColor(White);
end;
Write('dismay - ');
ReadLn(g);
i := i + 1;
if (g <> 'isgastis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: isgastis');
TextColor(White);
end;
Write('rueful - ');
ReadLn(g);
i := i + 1;
if (g <> 'gailus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gailus');
TextColor(White);
end;
Write('affront - ');
ReadLn(g);
i := i + 1;
if (g <> 'izeidimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: izeidimas');
TextColor(White);
end;
Write('grope - ');
ReadLn(g);
i := i + 1;
if (g <> 'ieskoti apgraibomis') and (g <> 'grabalioti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: grabalioti, ieskoti apgraibomis');
TextColor(White);
end;
Write('bannerman - ');
ReadLn(g);
i := i + 1;
if (g <> 'veliavnesys') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: veliavnesys');
TextColor(White);
end;
Write('bark - ');
ReadLn(g);
i := i + 1;
if (g <> 'zieve') and (g <> 'tosis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: zieve, tosis');
TextColor(White);
end;
Write('enrapture - ');
ReadLn(g);
i := i + 1;
if (g <> 'suzaveti') and (g <> 'zaveti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (su)zaveti');
TextColor(White);
end;
Write('sheath - ');
ReadLn(g);
i := i + 1;
if (g <> 'makstis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: makstis');
TextColor(White);
end;
Write('forfeit - ');
ReadLn(g);
i := i + 1;
if (g <> 'prarastas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: prarastas');
TextColor(White);
end;
Write('decay - ');
ReadLn(g);
i := i + 1;
if (g <> 'gedimas') and (g <> 'puvimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gedimas, puvimas');
TextColor(White);
end;
Write('scent - ');
ReadLn(g);
i := i + 1;
if (g <> 'iskvepinti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: iskvepinti');
TextColor(White);
end;
Write('pace - ');
ReadLn(g);
i := i + 1;
if (g <> 'greitis') and (g <> 'tempas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: greitis, tempas');
TextColor(White);
end;
Write('bolt - ');
ReadLn(g);
i := i + 1;
if (g <> 'leistis begti') and (g <> 'mestis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: leistis begti, mestis');
TextColor(White);
end;
Write('forge - ');
ReadLn(g);
i := i + 1;
if (g <> 'nukalti') and (g <> 'kalti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nukalti, kalti');
TextColor(White);
end;
Write('wistfully - ');
ReadLn(g);
i := i + 1;
if (g <> 'ilgesingai') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: ilgesingai');
TextColor(White);
end;
Write('clad - ');
ReadLn(g);
i := i + 1;
if (g <> 'aprengtas') and (g <> 'apsirenges') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: aprengtas, apsirenges');
TextColor(White);
end;
Write('ward - ');
ReadLn(g);
i := i + 1;
if (g <> 'ginklanesys') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: ginklanesys');
TextColor(White);
end;
Write('anoint - ');
ReadLn(g);
i := i + 1;
if (g <> 'patepti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: patepti');
TextColor(White);
end;
Write('pamper - ');
ReadLn(g);
i := i + 1;
if (g <> 'islepinti') and (g <> 'lepinti') and (g <> 'ispaikinti') and (g <> 'paikinti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (is)lepinti, (is)paikinti');
TextColor(White);
end;
Write('adjust - ');
ReadLn(g);
i := i + 1;
if (g <> 'sureguliuoti') and (g <> 'prisitaikyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sureguliuoti, prisitaikyti');
TextColor(White);
end;
Write('deem - ');
ReadLn(g);
i := i + 1;
if (g <> 'manyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: manyti');
TextColor(White);
end;
Write('moist - ');
ReadLn(g);
i := i + 1;
if (g <> 'dregnas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: dregnas');
TextColor(White);
end;
Write('forth - ');
ReadLn(g);
i := i + 1;
if (g <> 'pirmyn') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: pirmyn');
TextColor(White);
end;
Write('sable - ');
ReadLn(g);
i := i + 1;
if (g <> 'sabalo kailis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sabalo kailis');
TextColor(White);
end;
Write('smooth - ');
ReadLn(g);
i := i + 1;
if (g <> 'svelnus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: svelnus');
TextColor(White);
end;
Write('inspection - ');
ReadLn(g);
i := i + 1;
if (g <> 'apziurejimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: apziurejimas');
TextColor(White);
end;
Write('vocation - ');
ReadLn(g);
i := i + 1;
if (g <> 'pasaukimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: pasaukimas');
TextColor(White);
end;
Write('crispness - ');
ReadLn(g);
i := i + 1;
if (g <> 'gaivumas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gaivumas');
TextColor(White);
end;
Write('hold up - ');
ReadLn(g);
i := i + 1;
if (g <> 'laikyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: laikyti');
TextColor(White);
end;
Write('gleam - ');
ReadLn(g);
i := i + 1;
if (g <> 'spindeti') and (g <> 'sviesti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: spindeti, sviesti');
TextColor(White);
end;
Write('antler - ');
ReadLn(g);
i := i + 1;
if (g <> 'elnio ragai') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: elnio ragai');
TextColor(White);
end;
Write('trifling - ');
ReadLn(g);
i := i + 1;
if (g <> 'nereiksmingas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nereiksmingas');
TextColor(White);
end;
Write('tower - ');
ReadLn(g);
i := i + 1;
if (g <> 'kysoti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: kysoti');
TextColor(White);
end;
Write('fragrant - ');
ReadLn(g);
i := i + 1;
if (g <> 'aromatingas') and (g <> 'kvapnus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: kvapnus, aromatingas');
TextColor(White);
end;
Write('slender - ');
ReadLn(g);
i := i + 1;
if (g <> 'lieknas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: lieknas');
TextColor(White);
end;
Write('stump - ');
ReadLn(g);
i := i + 1;
if (g <> 'kelmas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: kelmas');
TextColor(White);
end;
Write('estate - ');
ReadLn(g);
i := i + 1;
if (g <> 'zemes valda') and (g <> 'dvaras') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: zemes valda, dvaras');
TextColor(White);
end;
Write('parry - ');
ReadLn(g);
i := i + 1;
if (g <> 'apsigynimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: apsigynimas');
TextColor(White);
end;
Write('bastard - ');
ReadLn(g);
i := i + 1;
if (g <> 'nesantuokinis') and (g <> 'pavainikis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nesantuokinis, pavainikis');
TextColor(White);
end;
Write('meekly - ');
ReadLn(g);
i := i + 1;
if (g <> 'romiai') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: romiai');
TextColor(White);
end;
Write('acquiescence - ');
ReadLn(g);
i := i + 1;
if (g <> 'sutikimas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sutikimas');
TextColor(White);
end;
Write('hearth - ');
ReadLn(g);
i := i + 1;
if (g <> 'zidinys') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: zidinys');
TextColor(White);
end;
Write('nigh - ');
ReadLn(g);
i := i + 1;
if (g <> 'arti') and (g <> 'netoli') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: arti, netoli');
TextColor(White);
end;
Write('deign - ');
ReadLn(g);
i := i + 1;
if (g <> 'teiktis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: teiktis');
TextColor(White);
end;
Write('behead - ');
ReadLn(g);
i := i + 1;
if (g <> 'nukirsti galva') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nukirsti galva');
TextColor(White);
end;
Write('caress - ');
ReadLn(g);
i := i + 1;
if (g <> 'paglostyti') and (g <> 'glostyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (pa)glostyti');
TextColor(White);
end;
Write('cocksure - ');
ReadLn(g);
i := i + 1;
if (g <> 'tikras') and (g <> 'isitikines') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: tikras, isitikines');
TextColor(White);
end;
Write('hint - ');
ReadLn(g);
i := i + 1;
if (g <> 'uzsiminti') and (g <> 'padaryti uzuomina') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: uzsiminti ,padaryti uzuomina');
TextColor(White);
end;
Write('gown - ');
ReadLn(g);
i := i + 1;
if (g <> 'vakarine suknia') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: vakarine suknia');
TextColor(White);
end;
Write('drape - ');
ReadLn(g);
i := i + 1;
if (g <> 'apmusalas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: apmusalas');
TextColor(White);
end;
Write('reflect - ');
ReadLn(g);
i := i + 1;
if (g <> 'apmastyti') and (g <> 'mastyti') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (ap)mastyti');
TextColor(White);
end;
Write('insofar as - ');
ReadLn(g);
i := i + 1;
if (g <> 'tiek, kiek') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: tiek, kiek');
TextColor(White);
end;
Write('layer - ');
ReadLn(g);
i := i + 1;
if (g <> 'sluoksnis') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sluoksnis');
TextColor(White);
end;
Write('supple - ');
ReadLn(g);
i := i + 1;
if (g <> 'lankstus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: lankstus');
TextColor(White);
end;
Write('mounted - ');
ReadLn(g);
i := i + 1;
if (g <> 'raitas') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: raitas');
TextColor(White);
end;
Write('hackles - ');
ReadLn(g);
i := i + 1;
if (g <> 'suns karciai') and (g <> 'karciai') and (g <> 'arklio karciai') and (g <> 'gaidzio kaklo plunksnos') and (g <> 'kaklo plunsknos') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: (suns, arklio) karciai, (gaidzio) kaklo plunksnos');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure E2(y : string);
var g : string; // spejimas
n, // klaidos
i, // zodziu skaicius
t : integer; // teisingi spejimai
vid : real; // vidurkis
begin
i := 0; t := 0; n := 0;
if (y = 'E2') then
begin
ClrScr;
Write('apsigynimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'parry') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: parry');
TextColor(White);
end;
Write('elnio ragai - ');
ReadLn(g);
i := i + 1;
if (g <> 'antler') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: antler');
TextColor(White);
end;
Write('(nu)kalti - ');
ReadLn(g);
i := i + 1;
if (g <> 'forge') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: forge');
TextColor(White);
end;
Write('nereiksmingas - ');
ReadLn(g);
i := i + 1;
if (g <> 'trifling') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: trifling');
TextColor(White);
end;
Write('sutikimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'acquiescence') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: acquiescence');
TextColor(White);
end;
Write('patepti - ');
ReadLn(g);
i := i + 1;
if (g <> 'anoint') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: anoint');
TextColor(White);
end;
Write('aromatingas, kvapnus - ');
ReadLn(g);
i := i + 1;
if (g <> 'fragrant') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: fragrant');
TextColor(White);
end;
Write('teiktis - ');
ReadLn(g);
i := i + 1;
if (g <> 'deign') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: deign');
TextColor(White);
end;
Write('kelmas - ');
ReadLn(g);
i := i + 1;
if (g <> 'stump') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: stump');
TextColor(White);
end;
Write('dregnas - ');
ReadLn(g);
i := i + 1;
if (g <> 'moist') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: moist');
TextColor(White);
end;
Write('zemes valda, dvaras - ');
ReadLn(g);
i := i + 1;
if (g <> 'estate') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: estate');
TextColor(White);
end;
Write('tikras, isitikines - ');
ReadLn(g);
i := i + 1;
if (g <> 'cocksure') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: cocksure');
TextColor(White);
end;
Write('nesantuokinis, pavainikis - ');
ReadLn(g);
i := i + 1;
if (g <> 'bastard') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: bastard');
TextColor(White);
end;
Write('rueful - ');
ReadLn(g);
i := i + 1;
if (g <> 'gailus') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gailus');
TextColor(White);
end;
Write('romiai - ');
ReadLn(g);
i := i + 1;
if (g <> 'meekly') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: meekly');
TextColor(White);
end;
Write('apmusalas - ');
ReadLn(g);
i := i + 1;
if (g <> 'drape') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: drape');
TextColor(White);
end;
Write('zidinys - ');
ReadLn(g);
i := i + 1;
if (g <> 'hearth') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: hearth');
TextColor(White);
end;
Write('zieve, tosis - ');
ReadLn(g);
i := i + 1;
if (g <> 'bark') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: bark');
TextColor(White);
end;
Write('arti, netoli - ');
ReadLn(g);
i := i + 1;
if (g <> 'nigh') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: nigh');
TextColor(White);
end;
Write('(ap)mastyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'reflect') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: reflect');
TextColor(White);
end;
Write('nukirsti galva - ');
ReadLn(g);
i := i + 1;
if (g <> 'behead') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: behead');
TextColor(White);
end;
Write('gedimas, puvimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'decay') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: decay');
TextColor(White);
end;
Write('(pa)glostyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'caress') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: caress');
TextColor(White);
end;
Write('tiek, kiek - ');
ReadLn(g);
i := i + 1;
if (g <> 'insofar as') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: insofar as');
TextColor(White);
end;
Write('uzsiminti, padaryti uzuomina - ');
ReadLn(g);
i := i + 1;
if (g <> 'hint') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: hint');
TextColor(White);
end;
Write('vakarine suknia - ');
ReadLn(g);
i := i + 1;
if (g <> 'gown') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gown');
TextColor(White);
end;
Write('sluoksnis - ');
ReadLn(g);
i := i + 1;
if (g <> 'layer') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: layer');
TextColor(White);
end;
Write('sluoksnis - ');
ReadLn(g);
i := i + 1;
if (g <> 'layer') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: layer');
TextColor(White);
end;
Write('isgastis - ');
ReadLn(g);
i := i + 1;
if (g <> 'dismay') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: dismay');
TextColor(White);
end;
Write('lankstus - ');
ReadLn(g);
i := i + 1;
if (g <> 'supple') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: supple');
TextColor(White);
end;
Write('veliavnesys - ');
ReadLn(g);
i := i + 1;
if (g <> 'bannerman') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: bannerman');
TextColor(White);
end;
Write('izeidimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'affront') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: affront');
TextColor(White);
end;
Write('raitas - ');
ReadLn(g);
i := i + 1;
if (g <> 'mounted') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: mounted');
TextColor(White);
end;
Write('prarastas - ');
ReadLn(g);
i := i + 1;
if (g <> 'forfeit') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: forfeit');
TextColor(White);
end;
Write('(su)zaveti - ');
ReadLn(g);
i := i + 1;
if (g <> 'enrapture') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: enrapture');
TextColor(White);
end;
Write('(suns, arklio) karciai, (gaidzio) kaklo plunksnos - ');
ReadLn(g);
i := i + 1;
if (g <> 'hackles') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: hackles');
TextColor(White);
end;
Write('leistis begti, mestis - ');
ReadLn(g);
i := i + 1;
if (g <> 'bolt') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: bolt');
TextColor(White);
end;
Write('iskvepinti - ');
ReadLn(g);
i := i + 1;
if (g <> 'scent') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: scent');
TextColor(White);
end;
Write('plusti - ');
ReadLn(g);
i := i + 1;
if (g <> 'well') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: well');
TextColor(White);
end;
Write('ginklanesys - ');
ReadLn(g);
i := i + 1;
if (g <> 'ward') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: ward');
TextColor(White);
end;
Write('ilgesingai - ');
ReadLn(g);
i := i + 1;
if (g <> 'wistfully') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: wistfully');
TextColor(White);
end;
Write('ieskoti apgraibomis, grabalioti - ');
ReadLn(g);
i := i + 1;
if (g <> 'grope') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: grope');
TextColor(White);
end;
Write('manyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'deem') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: deem');
TextColor(White);
end;
Write('(is)lepinti, (is)paikinti - ');
ReadLn(g);
i := i + 1;
if (g <> 'pamper') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: pamper');
TextColor(White);
end;
Write('makstis - ');
ReadLn(g);
i := i + 1;
if (g <> 'sheath') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sheath');
TextColor(White);
end;
Write('pirmyn - ');
ReadLn(g);
i := i + 1;
if (g <> 'forth') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: forth');
TextColor(White);
end;
Write('svelnus - ');
ReadLn(g);
i := i + 1;
if (g <> 'smooth') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: smooth');
TextColor(White);
end;
Write('greitis, tempas - ');
ReadLn(g);
i := i + 1;
if (g <> 'pace') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: pace');
TextColor(White);
end;
Write('gaivumas - ');
ReadLn(g);
i := i + 1;
if (g <> 'crispness') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: crispness');
TextColor(White);
end;
Write('apziurejimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'inspection') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: inspection');
TextColor(White);
end;
Write('aprengtas, apsirenges - ');
ReadLn(g);
i := i + 1;
if (g <> 'clad') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: clad');
TextColor(White);
end;
Write('laikyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'hold up') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: hold up');
TextColor(White);
end;
Write('sureguliuoti, prisitaikyti - ');
ReadLn(g);
i := i + 1;
if (g <> 'adjust') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: adjust');
TextColor(White);
end;
Write('sabalo kailis - ');
ReadLn(g);
i := i + 1;
if (g <> 'sable') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: sable');
TextColor(White);
end;
Write('pasaukimas - ');
ReadLn(g);
i := i + 1;
if (g <> 'vocation') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: vocation');
TextColor(White);
end;
Write('spindeti, sviesti - ');
ReadLn(g);
i := i + 1;
if (g <> 'gleam') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: gleam');
TextColor(White);
end;
Write('kysoti - ');
ReadLn(g);
i := i + 1;
if (g <> 'tower') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: tower');
TextColor(White);
end;
Write('lieknas - ');
ReadLn(g);
i := i + 1;
if (g <> 'slender') then
begin
n := n + 1;
TextColor(LightRed);
WriteLn('Wrong!');
TextColor(Green);
WriteLn('Right answer is: slender');
TextColor(White);
end;
ReadLn;
ClrScr;
t := i - n;
vid := (t * 10) / i;
Window(30, 7, 48, 18);
TextBackground(Red);
ClrScr;
TextColor(White);
GotoXY(1,2);
WriteLn(' -----------------');
GotoXY(2,3);
Writeln('Results:');
GotoXY(1,4);
WriteLn(' -----------------');
GotoXY(2,5);
Writeln(' Words: ',i);
GotoXY(2,6);
Writeln(' Right: ',t);
GotoXY(2,7);
Writeln(' Mistakes: ',n);
GotoXY(2,8);
Writeln(' Ratio: ',t,'/',i);
GotoXY(2,9);
Writeln(' Rate: ',vid:7:2);
GotoXY(2,10);
Writeln(' Mark: ',vid:7:0);
GotoXY(1,11);
WriteLn(' -----------------');
Readln;
end;
end;
{------------------------------------------------------------------------------}
Procedure ShutDown(var re : char);
Begin
Repeat
ClrScr;
Window(1,1,80,25);
TextBackground(Black);
ClrScr;
Window(20,7,57,12);
TextBackground(White);
ClrScr;
TextColor(Red);
GoToXY(5, 3);
Write('Do you want to restart? (Y/N): ');
TextColor(Blue);
Readln(re);
re := Upcase(re);
Until (re = 'Y') or (re = 'N');
end;
{----------------------------Pagrindine programa-------------------------------}
var
Choise1 : char; // naudojamas MainMenu
Choise2 : string; // naudojamas SubMenu
Restart : char; // Restart kintamasis
{$R *.res}
begin
TextBackground(Black);
Password;
Repeat
MainMenu(Choise1);
SubMenuA(Choise1, Choise2);
SubMenuB(Choise1, Choise2);
SubMenuC(Choise1, Choise2);
SubMenuD(Choise1, Choise2);
SubMenuE(Choise1, Choise2);
A1(Choise2);
A2(Choise2);
B1(Choise2);
B2(Choise2);
C1(Choise2);
C2(Choise2);
D1(Choise2);
D2(Choise2);
E1(Choise2);
E2(Choise2);
ShutDown(Restart);
Until (Restart = 'N');
end.
|
unit ZipInterfaceVCLZIP;
interface
uses Classes, SysUtils,
ZipInterface, VCLUnZip;
type TXLSReadZipVCLZIP = class(TXLSReadZip)
private
FZIP: TVCLUnZip;
public
constructor Create;
destructor Destroy; override;
procedure OpenZip(Zipfile: WideString); override;
procedure CloseZip; override;
function ReadFileToStream(Filename: WideString; Stream: TStream): boolean; override;
end;
implementation
{ TXLSReadZipVCLZIP }
procedure TXLSReadZipVCLZIP.CloseZip;
begin
FZIP.ClearZip;
end;
constructor TXLSReadZipVCLZIP.Create;
begin
FZIP := TVCLUnZip.Create(Nil);
end;
destructor TXLSReadZipVCLZIP.Destroy;
begin
FZIP.Free;
inherited;
end;
procedure TXLSReadZipVCLZIP.OpenZip(Zipfile: WideString);
begin
FZIP.ZipName := Zipfile;
end;
function TXLSReadZipVCLZIP.ReadFileToStream(Filename: WideString; Stream: TStream): boolean;
begin
Result := FZIP.UnZipToStream(Stream,Filename) = 1;
end;
end.
|
unit uNewUnit;
interface
uses
SysUtils, Classes, uCompany, UTSbaseClass, FireDAC.Comp.Client, udmMain;
type
TUnit = class(TSBaseClass)
private
FAppID: string;
FCompany: TCompany;
FCompanyID: string;
FDescription: string;
FID: string;
FKode: string;
FNama: string;
function FLoadFromDB( aSQL : String ): Boolean;
function GetCompany: TCompany;
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
procedure ClearProperties;
function CustomTableName: string;
function ExecuteCustomSQLTask: Boolean;
function ExecuteCustomSQLTaskPrior: Boolean;
function ExecuteGenerateSQL: Boolean;
function GenerateInterbaseMetaData: Tstrings;
function GetFieldNameFor_AppID: string; dynamic;
function GetFieldNameFor_Company: string; dynamic;
function GetFieldNameFor_Description: string; dynamic;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_Kode: string; dynamic;
function GetFieldNameFor_Nama: string; dynamic;
function GetGeneratorName: string;
function GetHeaderFlag: Integer;
function LoadByID(aID: string): Boolean;
function LoadByKode( aKode : string): Boolean;
procedure UpdateData(aAppID, aCompany_ID, aDescription, aID, aKode, aNama:
string);
property AppID: string read FAppID write FAppID;
property Company: TCompany read GetCompany write FCompany;
property Description: string read FDescription write FDescription;
property ID: string read FID write FID;
property Kode: string read FKode write FKode;
property Nama: string read FNama write FNama;
end;
implementation
uses DB;
{
************************************ TUnit *************************************
}
constructor TUnit.Create(aOwner : TComponent);
begin
inherited create(aOwner);
ClearProperties;
end;
destructor TUnit.Destroy;
begin
ClearProperties;
inherited Destroy;
end;
procedure TUnit.ClearProperties;
begin
AppID := '';
FCompanyID := '';
if FCompany <> nil then
FreeAndNil(FCompany);
Description := '';
ID := '';
Kode := '';
Nama := '';
end;
function TUnit.CustomTableName: string;
begin
result := 'AUT$UNIT';
end;
function TUnit.ExecuteCustomSQLTask: Boolean;
begin
result := True;
end;
function TUnit.ExecuteCustomSQLTaskPrior: Boolean;
begin
result := True;
end;
function TUnit.ExecuteGenerateSQL: Boolean;
var
S: string;
begin
result := False;
if State = csNone then
Begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
if not ExecuteCustomSQLTaskPrior then
begin
cRollbackTrans;
Exit;
end else begin
// If FID <= 0 then
If FID = '' then
begin
// FID := cGetNextID(GetFieldNameFor_AppID, CustomTableName);
FID := cGetNextIDGUIDToString;
S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_AppID + ', ' + GetFieldNameFor_Company + ', ' + GetFieldNameFor_Description + ', ' + GetFieldNameFor_ID + ', ' + GetFieldNameFor_Kode + ', ' + GetFieldNameFor_Nama + ') values ('
+ QuotedStr( FAppID) + ', '
+ IntToStr( Company.ID) + ', '
+ QuotedStr( FDescription) + ', '
+ QuotedStr( FID) + ', '
+ QuotedStr(FKode ) + ','
+ QuotedStr(FNama ) + ');'
end else
begin
S := 'Update ' + CustomTableName + ' set Stamp = Null '
+ ', ' + GetFieldNameFor_AppID + ' = ' + QuotedStr( FAppID)
+ ', ' + GetFieldNameFor_Company + ' = ' + IntToStr( Company.ID)
+ ', ' + GetFieldNameFor_Description + ' = ' + QuotedStr( FDescription)
+ ', ' + GetFieldNameFor_Kode + ' = ' + QuotedStr( FKode )
+ ', ' + GetFieldNameFor_Nama + ' = ' + QuotedStr( FNama )
+ ' Where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(FID) + ';';
end;
if not cExecSQL(S, dbtStore, False) then
begin
cRollbackTrans;
Exit;
end else
Result := ExecuteGenerateSQL;
end;
end;
function TUnit.FLoadFromDB( aSQL : String ): Boolean;
var
iQ: TFDQuery;
begin
result := false;
State := csNone;
ClearProperties;
iQ := cOpenQuery(aSQL);
try
with iQ do
Begin
if not EOF then
begin
FAppID := FieldByName(GetFieldNameFor_AppID).AsString;
FCompanyID := FieldByName(GetFieldNameFor_Company).AsString;
FDescription := FieldByName(GetFieldNameFor_Description).AsString;
FID := FieldByName(GetFieldNameFor_ID).AsString;
FKode := FieldByName(GetFieldNameFor_Kode).asString;
FNama := FieldByName(GetFieldNameFor_Nama).asString;
Self.State := csLoaded;
Result := True;
end;
End;
finally
FreeAndNil(iQ);
end;
end;
function TUnit.GenerateInterbaseMetaData: Tstrings;
begin
result := TstringList.create;
result.Append( '' );
result.Append( 'Create Table TUnit ( ' );
result.Append( 'TRMSBaseClass_ID Integer not null, ' );
result.Append( 'AppID Integer Not Null , ' );
result.Append( 'Company_ID Integer Not Null, ' );
result.Append( 'Description Integer Not Null , ' );
result.Append( 'ID Integer Not Null Unique, ' );
result.Append( 'Kode Varchar(30) Not Null Unique, ' );
result.Append( 'Nama Varchar(30) Not Null , ' );
result.Append( 'Stamp TimeStamp ' );
result.Append( ' ); ' );
end;
function TUnit.GetCompany: TCompany;
begin
if FCompany = nil then
begin
FCompany := TCompany.Create(Self);
FCompany.LoadByID(StrToInt(FCompanyID));
end;
Result := FCompany;
end;
function TUnit.GetFieldNameFor_AppID: string;
begin
// Result := 'UNT_APP_ID';// <<-- Rubah string ini untuk mapping
Result := 'AUT$APP_ID';
end;
function TUnit.GetFieldNameFor_Company: string;
begin
// Result := 'UNT_COMP_ID';// <<-- Rubah string ini untuk mapping
Result := 'COMPANY_ID';
end;
function TUnit.GetFieldNameFor_Description: string;
begin
Result := 'UNT_DESCRIPTION';// <<-- Rubah string ini untuk mapping
end;
function TUnit.GetFieldNameFor_ID: string;
begin
// Result := 'UNT_ID';// <<-- Rubah string ini untuk mapping
Result := 'AUT$UNIT_ID';
end;
function TUnit.GetFieldNameFor_Kode: string;
begin
Result := 'UNT_CODE';// <<-- Rubah string ini untuk mapping
end;
function TUnit.GetFieldNameFor_Nama: string;
begin
Result := 'UNT_NAME';// <<-- Rubah string ini untuk mapping
end;
function TUnit.GetGeneratorName: string;
begin
Result := 'gen_aut$unit_id';
end;
function TUnit.GetHeaderFlag: Integer;
begin
result := 504;
end;
function TUnit.LoadByID(aID: string): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(aID) );
end;
function TUnit.LoadByKode( aKode : string): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName + ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode));
end;
procedure TUnit.UpdateData(aAppID, aCompany_ID, aDescription, aID, aKode,
aNama: string);
begin
FAppID := aAppID;
FCompanyID := aCompany_ID;
FDescription := aDescription;
FID := aID;
FKode := trim(aKode);
FNama := trim(aNama);
State := csCreated;
end;
end.
|
unit RecordsEditorForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
FireDAC.Comp.Client, Vcl.DBGrids,
Data.DB, Bde.DBTables;
type
TSpecialEdit = class(TEdit)
public
FieldNumber: Integer;
end;
type
TFieldEditor = record
EditorEdit: TSpecialEdit;
EditorLabel: TLabel;
EditorComboBox: TComboBox;
end;
type
TEditorForm = class(TForm)
procedure FormShow(Sender: TObject);
private
FieldEditorsArray: array of TFieldEditor;
CommitButton: TBitBtn;
RollbackButton: TBitBtn;
public
RecordFields: array of String;
NativeValues: array of String;
MainTableIDs: array of Integer;
Kind: Boolean;
procedure CommitButtonClick(Sender: TObject);
function CheckExistense(Query: TFDQuery; DataSource: TDataSource): Boolean;
procedure ShowReferenceEditor(Sender: TObject);
function GetId(Tag: Integer; Index: Integer; Text: String): Integer;
end;
var
EditorForm: TEditorForm;
implementation
{$R *.dfm}
uses MetaData, ConnectionForm, SQLGenerator, ReferenceEditorForm;
function TEditorForm.CheckExistense(Query: TFDQuery;
DataSource: TDataSource): Boolean;
var
i: Integer;
SQLText: String;
begin
Result := true;
for i := 1 to High(TablesMetaData.Tables[Self.Tag].TableFields) do
if TablesMetaData.Tables[Self.Tag].TableFields[i].References <> Nil then
begin
begin
Query.SQL.Text := Query.SQL.Text + GetJoinWhere(Query.Params.Count,
Self.Tag, TablesMetaData.Tables[Self.Tag].TableFields[i]
.References.Table + '.' + TablesMetaData.Tables[Self.Tag].TableFields
[i].References.Name + ' = ', '');
Query.Params[Query.Params.Count - 1].Value := RecordFields[i - 1];
end;
Query.Active := true;
if DataSource.DataSet.FieldByName(TablesMetaData.Tables[Self.Tag]
.TableFields[i].References.Name).AsString = '' then
Result := false;
end
else
begin
Query.SQL.Text := GetSelectJoinWhere(0, Self.Tag,
TablesMetaData.Tables[Self.Tag].TableName + '.' + TablesMetaData.Tables
[Self.Tag].TableFields[i].FieldName + ' = ', '');
Query.Params[Query.Params.Count - 1].Value := RecordFields[i - 1];
Query.Active := true;
if DataSource.DataSet.FieldByName(TablesMetaData.Tables[Self.Tag]
.TableFields[i].FieldName).AsString = '' then
Result := false;
end;
end;
procedure TEditorForm.CommitButtonClick(Sender: TObject);
var
Query: TFDQuery;
DataSource: TDataSource;
i, j: Integer;
MaxID, ID: Integer;
DBGrid: TDBGrid;
Exists: Boolean;
begin
SetLength(RecordFields, 0);
Exists := true;
for i := 0 to High(Self.FieldEditorsArray) do
begin
SetLength(RecordFields, Length(RecordFields) + 1);
if FieldEditorsArray[i].EditorEdit.Text = '' then
RecordFields[High(RecordFields)] := FieldEditorsArray[i]
.EditorComboBox.Text
else
RecordFields[High(RecordFields)] := FieldEditorsArray[i].EditorEdit.Text;
end;
Query := TFDQuery.Create(Self);
Query.Connection := ConnectionFormWindow.MainConnection;
DataSource := TDataSource.Create(Self);
DataSource.DataSet := Query;
DBGrid := TDBGrid.Create(Self);
DBGrid.DataSource := DataSource;
Query.Active := false;
Query.SQL.Text := 'SELECT Max(ID) FROM ' + TablesMetaData.Tables
[(Sender as TBitBtn).Tag].TableName;
Query.Active := true;
MaxID := DBGrid.Fields[0].Value;
Query.Active := false;
Query.SQL.Text := SetGenerator(MaxID);
Query.ExecSQL;
Query.Active := false;
Query.SQL.Text := '';
Exists := CheckExistense(Query, DataSource);
{ if Exists then
ShowMessage('Данная запись уже существует')
else
case (Sender as TBitBtn).Kind of
bkOk:
begin
Query.SQL.Text := GetInsert(Tag, i, High(RecordFields));
Query.Params[0].Value := RecordFields[i - 1];
Query.ExecSQL;
end
else
begin
SetLength(MainTableIDs, Length(MainTableIDs) + 1);
MainTableIDs[High(MainTableIDs)] := DataSource.DataSet.FieldByName
('ID').AsInteger;
end;
end;
bkYes:
if not Exists then
begin
Query.Active := false;
Query.SQL.Text := GetInsert(Tag, i, High(RecordFields));
Query.Params[0].Value := RecordFields[i - 1];
Query.ExecSQL;
end;
end; }
// else
begin
Exists := CheckExistense(Query, DataSource);
// if not Exists then
case (Sender as TBitBtn).Kind of
bkOk:
begin
if not Exists then
begin
Query.Active := false;
Query.SQL.Text := GetInsert((Sender as TBitBtn).Tag, i,
High(RecordFields));
for j := 0 to Query.Params.Count - 1 do
if Length(MainTableIDs) = 0 then
Query.Params[j].Value := RecordFields[j]
else
Query.Params[j].Value := MainTableIDs[j];
if i = High(TablesMetaData.Tables[(Sender as TBitBtn).Tag]
.TableFields) then
Query.ExecSQL;
end
else
begin
ShowMessage('Такая запись уже существует!');
if Length(MainTableIDs) = 0 then
begin
SetLength(Self.MainTableIDs, Length(Self.MainTableIDs) + 1);
MainTableIDs[High(MainTableIDs)] := DataSource.DataSet.FieldByName
('ID').AsInteger;
end;
end;
end;
bkYes:
begin
if not Exists then
begin
Query.Active := false;
Query.SQL.Text := '';
for i := 1 to High(TablesMetaData.Tables[Self.Tag].TableFields) do
begin
if Length(MainTableIDs) = 0 then
Query.SQL.Text := GetSelectJoinWhere(Query.Params.Count, Self.Tag,
TablesMetaData.Tables[Self.Tag].TableName + '.' +
TablesMetaData.Tables[Self.Tag].TableFields[i].FieldName +
' = ', Query.SQL.Text)
else
Query.SQL.Text := GetSelectJoinWhere(Query.Params.Count, Self.Tag,
TablesMetaData.Tables[Self.Tag].TableFields[i].References.Table + '.' +
TablesMetaData.Tables[Self.Tag].TableFields[i].References.Name +
' = ', Query.SQL.Text);
Query.Params[Query.Params.Count - 1].Value := NativeValues[i - 1]
end;
Query.Active := true;
ID := DBGrid.Fields[0].Value;
Query.Active := false;
for j := 0 to High(TablesMetaData.Tables[Tag].TableFields) - 1 do
begin
Query.SQL.Text := GetUpdate((Sender as TBitBtn).Tag, j);
if Length(MainTableIDs) = 0 then
Query.Params[Query.Params.Count - 1].Value := RecordFields[j]
else
Query.Params[Query.Params.Count - 1].Value := MainTableIDs[j];
end;
Query.SQL.Text := Query.SQL.Text +
GetUpdate((Sender as TBitBtn).Tag, j);
Query.Params[Query.Params.Count - 1].Value := ID;
Query.ExecSQL;
end
else
ShowMessage('Такая запись уже существует!');
end;
end;
end;
{ if Length(MainTableIDs) <> 0 then
begin
Query.Active := false;
Query.SQL.Text := 'INSERT INTO ' + TablesMetaData.Tables[Self.Tag].TableName
+ '(' + TablesMetaData.Tables[Self.Tag].TableFields[0].FieldName;
for i := 1 to High(TablesMetaData.Tables[Self.Tag].TableFields) do
Query.SQL.Text := Query.SQL.Text + ', ' + TablesMetaData.Tables[Self.Tag]
.TableFields[i].FieldName;
Query.SQL.Text := Query.SQL.Text + ') VALUES ( GEN_ID(GenNewID, 1)';
for i := 0 to High(MainTableIDs) do
Query.SQL.Text := Query.SQL.Text + ', :' + IntToStr(i);
Query.SQL.Text := Query.SQL.Text + ');';
for i := 0 to Query.Params.Count - 1 do
Query.Params[i].Value := MainTableIDs[i];
Query.ExecSQL;
end; }
Self.Close;
end;
procedure TEditorForm.FormShow(Sender: TObject);
var
i, j, k: Integer;
CurTop: Integer;
ItemList: TStringList;
begin
CurTop := 0;
for i := 0 to High(TablesMetaData.Tables[(Sender as TForm).Tag]
.TableFields) - 1 do
begin
SetLength(FieldEditorsArray, Length(FieldEditorsArray) + 1);
FieldEditorsArray[High(FieldEditorsArray)].EditorLabel :=
TLabel.Create(Self);
with FieldEditorsArray[High(FieldEditorsArray)].EditorLabel do
begin
Parent := Self;
Top := CurTop + Height + 10;
Left := 10;
Anchors := [akTop, akLeft];
if TablesMetaData.Tables[(Sender as TForm).Tag].TableFields[i + 1]
.References = Nil then
Caption := TablesMetaData.Tables[(Sender as TForm).Tag].TableFields
[i + 1].FieldCaption
else
Caption := TablesMetaData.Tables[(Sender as TForm).Tag].TableFields
[i + 1].References.Caption;
end;
if TablesMetaData.Tables[(Sender as TForm).Tag].TableFields[1].References <> nil
then
begin
FieldEditorsArray[High(FieldEditorsArray)].EditorEdit :=
TSpecialEdit.Create(Self);
FieldEditorsArray[High(FieldEditorsArray)].EditorEdit.Tag :=
TablesMetaData.Tables[(Sender as TForm).Tag].TableFields[i + 1]
.References.TableTag;
with FieldEditorsArray[High(FieldEditorsArray)].EditorEdit do
begin
Parent := Self;
Top := FieldEditorsArray[High(FieldEditorsArray)].EditorLabel.Top;
Left := 120;
Width := Self.Width - Width - 30;
Anchors := [akTop, akLeft, akRight];
CurTop := Top;
FieldNumber := i;
if Length(NativeValues) <> 0 then
Text := NativeValues[i];
ReadOnly := true;
OnClick := ShowReferenceEditor;
end;
SetLength(Self.MainTableIDs, Length(Self.MainTableIDs) + 1);
MainTableIDs[i] := GetId(TablesMetaData.Tables[(Sender as TForm).Tag]
.TableFields[i + 1].References.TableTag, 1,
FieldEditorsArray[High(FieldEditorsArray)].EditorEdit.Text);
end
else
begin
FieldEditorsArray[High(FieldEditorsArray)].EditorComboBox :=
TComboBox.Create(Self);
with FieldEditorsArray[High(FieldEditorsArray)].EditorComboBox do
begin
Parent := Self;
Top := FieldEditorsArray[High(FieldEditorsArray)].EditorLabel.Top;
Left := 120;
Width := Self.Width - Width - 30;
Anchors := [akTop, akLeft, akRight];
CurTop := Top;
Tag := i;
Items.Add('');
ItemList := TablesMetaData.Tables[(Sender as TForm).Tag].GetDataList(1);
for j := 0 to ItemList.Count - 1 do
Items.Add(ItemList[j]);
if Length(NativeValues) <> 0 then
for k := 0 to Items.Count - 1 do
if Items[k] = NativeValues[i] then
ItemIndex := k;
end;
break;
end;
end;
RollbackButton := TBitBtn.Create(Self);
with RollbackButton do
begin
Parent := Self;
Left := 10;
Width := Round(Self.Width / 2) - 30;
Top := CurTop + 30;
Kind := bkCancel;
Caption := 'Отменить';
end;
CommitButton := TBitBtn.Create(Self);
with CommitButton do
begin
Parent := Self;
Width := RollbackButton.Width;
Left := RollbackButton.Left + RollbackButton.Width + 20;
Top := RollbackButton.Top;
if Self.Kind then
Kind := bkOk
else
Kind := bkYes;
Caption := 'Применить';
OnClick := CommitButtonClick;
Tag := Self.Tag;
end;
Self.Height := RollbackButton.Top + RollbackButton.Height * 3;
end;
function TEditorForm.GetId(Tag: Integer; Index: Integer; Text: String): Integer;
var
Query: TFDQuery;
DataSource: TDataSource;
Grid: TDBGrid;
begin
Query := TFDQuery.Create(Self);
Query.Connection := ConnectionFormWindow.MainConnection;
DataSource := TDataSource.Create(Self);
DataSource.DataSet := Query;
Grid := TDBGrid.Create(Self);
Grid.DataSource := DataSource;
Query.Active := false;
Query.SQL.Text := 'SELECT * FROM ' + TablesMetaData.Tables[Tag].TableName +
' WHERE ' + TablesMetaData.Tables[Tag].TableFields[Index].FieldName
+ ' = :0';
Query.Params[0].Value := Text;
Query.Active := true;
Result := Grid.Fields[0].AsInteger;
end;
procedure TEditorForm.ShowReferenceEditor(Sender: TObject);
var
Form: TEditorForm;
i, j: Integer;
Test: Integer;
TransQuery: TFDQuery;
TransSource: TDataSource;
begin
Form := TEditorForm.Create(Application);
Form.Tag := (Sender as TEdit).Tag;
Form.Kind := true;
SetLength(Form.NativeValues, Length(Form.NativeValues) + 1);
Form.NativeValues[High(Form.NativeValues)] := (Sender as TEdit).Text;
Form.ShowModal;
Self.MainTableIDs[(Sender as TSpecialEdit).FieldNumber] :=
Form.MainTableIDs[0];
(Sender as TEdit).Text := Form.FieldEditorsArray[0].EditorComboBox.Text;
end;
end.
|
unit HS4D.Credential;
interface
uses
HS4D.Interfaces;
type
THS4DCredential = class(TInterfacedObject, iHS4DCredential)
private
[weak]
FParent : iHS4D;
FBaseURL : string;
FEndPoint : string;
public
constructor Create(Parent : iHS4D);
destructor Destroy; override;
class function New(aParent : iHS4D) : iHS4DCredential;
function BaseURL(const aValue : string) : iHS4DCredential; overload;
function BaseURL : string; overload;
function &End : iHS4D;
end;
implementation
{ THS4DCredential }
function THS4DCredential.BaseURL(const aValue : string) : iHS4DCredential;
begin
Result:= Self;
FBaseURL:= aValue;
end;
function THS4DCredential.&End: iHS4D;
begin
Result:= FParent;
end;
function THS4DCredential.BaseURL: string;
begin
Result:= FBaseURL;
end;
constructor THS4DCredential.Create(Parent: iHS4D);
begin
FParent:= Parent;
end;
destructor THS4DCredential.Destroy;
begin
inherited;
end;
class function THS4DCredential.New(aParent: iHS4D): iHS4DCredential;
begin
result:= Self.Create(aParent);
end;
end.
|
unit Design;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
DesignController, DesignSurface;
type
TDesignForm = class(TForm)
DesignController: TDesignController;
procedure FormPaint(Sender: TObject);
private
{ Private declarations }
protected
procedure ReaderError(Reader: TReader; const Message: string;
var Handled: Boolean);
public
{ Public declarations }
function CreateSelectionList: TList;
procedure LoadFromFile(const inFilename: string);
procedure SaveToFile(const inFilename: string);
end;
var
DesignForm: TDesignForm;
implementation
uses
Utils;
{$R *.dfm}
procedure TDesignForm.FormPaint(Sender: TObject);
begin
PaintRules(Canvas, ClientRect);
end;
function TDesignForm.CreateSelectionList: TList;
var
i: Integer;
begin
Result := TList.Create;
for i := 0 to Pred(DesignController.Count) do
Result.Add(DesignController.Selection[i]);
end;
procedure TDesignForm.ReaderError(Reader: TReader; const Message: string;
var Handled: Boolean);
begin
Handled := true;
end;
procedure TDesignForm.LoadFromFile(const inFilename: string);
begin
DesignController.Free;
LoadComponentFromFile(Self, inFilename, ReaderError);
DesignController.Active := true;
end;
procedure TDesignForm.SaveToFile(const inFilename: string);
begin
SaveComponentToFile(Self, inFilename);
end;
end.
|
unit frmInnerRepairCheck;
{*|<PRE>*****************************************************************************
软件名称 FNM CLIENT MODEL
版权所有 (C) 2004-2005 ESQUEL GROUP GET/IT
单元名称 frmAnalysisQuality.pas
创建日期 2004-10-13 15:47:43
创建人员 lvzd
修改人员
修改日期
修改原因
对应用例
字段描述
相关数据库表
调用重要函数/SQL对象说明
功能描述 分析返工,C级,降等质量事故的工序.
******************************************************************************}
interface
uses
Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, DB,
DBClient, cxSplitter, StdCtrls, ComCtrls, Buttons, ExtCtrls, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, Grids,
DBGrids;
type
TInnerRepairCheckForm = class(TForm)
cds_FabricData: TClientDataSet;
ds_FabricData: TDataSource;
btn_Help: TSpeedButton;
btn_Query: TSpeedButton;
btn_Save: TSpeedButton;
btn_Exit: TSpeedButton;
txt_Only: TStaticText;
pnl_Only: TPanel;
dtp_OperateTime: TDateTimePicker;
Panel1: TPanel;
btn_Ignore: TSpeedButton;
edt_Remark: TEdit;
Label1: TLabel;
cxgrid_FabricData: TcxGrid;
cxgridtv_FabricData: TcxGridDBTableView;
cxGridl_FabricData: TcxGridLevel;
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure btn_QueryClick(Sender: TObject);
procedure btn_IgnoreClick(Sender: TObject);
procedure btn_ExitClick(Sender: TObject);
procedure btn_SaveClick(Sender: TObject);
procedure dtp_OperateTimeChange(Sender: TObject);
procedure cds_FabricDataAfterScroll(DataSet: TDataSet);
private
{ private declarations }
procedure GetInnerRepairData;
public
{ Public declarations }
end;
var
InnerRepairCheckForm: TInnerRepairCheckForm;
implementation
uses SysUtils, Variants, cxDropDownEdit, uDictionary, uFNMArtInfo, UAppOption,
ServerDllPub, uFNMResource, StrUtils, uLogin, UGridDecorator,
uShowMessage, frmInput;
{$R *.dfm}
procedure TInnerRepairCheckForm.FormDestroy(Sender: TObject);
begin
InnerRepairCheckForm:=nil;
end;
procedure TInnerRepairCheckForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TInnerRepairCheckForm.FormCreate(Sender: TObject);
begin
btn_Query.Glyph.LoadFromResourceName(HInstance, RES_QUERY);
btn_Help.Glyph.LoadFromResourceName(HInstance, RES_HELPABOUT);
btn_Save.Glyph.LoadFromResourceName(HInstance, RES_SAVE);
btn_Exit.Glyph.LoadFromResourceName(HInstance, RES_EXIT);
dtp_OperateTime.Date := Now-1;
btn_Save.Enabled:=False;
end;
procedure TInnerRepairCheckForm.btn_ExitClick(Sender: TObject);
begin
Close;
end;
procedure TInnerRepairCheckForm.GetInnerRepairData;
var
vData: OleVariant;
sErrorMsg: WideString;
begin
try
cds_FabricData.DisableControls;
FNMServerObj.GetInnerRepairInfo(Login.CurrentDepartment, DateToStr(dtp_OperateTime.Date), vData, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetAnalysisData, [sErrorMsg]);
cds_FabricData.Data:=vData;
cds_FabricData.FieldByName('Iden').Visible:=False;
cds_FabricData.FieldByName('Changed').Visible:=False;
GridDecorator.BindCxViewWithDataSource(cxgridtv_FabricData, ds_FabricData);
cds_FabricData.AfterScroll(cds_FabricData);
btn_Save.Enabled:=False;
finally
cds_FabricData.EnableControls;
end;
end;
procedure TInnerRepairCheckForm.btn_QueryClick(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
GetInnerRepairData;
Screen.Cursor := crDefault
end;
procedure TInnerRepairCheckForm.btn_IgnoreClick(Sender: TObject);
begin
if (not cds_FabricData.Active) or (cds_FabricData.IsEmpty) then Exit;
if MessageDlg('你确认要忽略或取消忽略选中的内回修记录吗?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then Exit;
with cds_FabricData do
begin
Edit;
FieldByName('Is_Ignore').AsBoolean:=not FieldByName('Is_Ignore').AsBoolean;
FieldByName('Ignore_Remark').AsString:=edt_Remark.Text;
FieldByName('Ignorer').AsString:=Login.LoginName;
FieldByName('Ignore_Time').AsDateTime:=Now;
FieldByName('Changed').AsBoolean:=True;
AfterScroll(cds_FabricData);
btn_Save.Enabled:=True;
end;
end;
procedure TInnerRepairCheckForm.btn_SaveClick(Sender: TObject);
var
i: Integer;
sErrorMsg: WideString;
begin
cds_FabricData.DisableControls;
try
cds_FabricData.First;
for i := 0 to cds_FabricData.RecordCount - 1 do
begin
if cds_FabricData.FieldByName('Changed').AsBoolean then
cds_FabricData.Next
else
cds_FabricData.Delete;
end;
finally
cds_FabricData.EnableControls;
end;
cds_FabricData.MergeChangeLog;
FNMServerObj.SaveIgnoredInnerRepairInfo(cds_FabricData.Data, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveAnalysisQualtityData, [sErrorMsg]);
cds_FabricData.EmptyDataSet;
btn_Save.Enabled:=False;
end;
procedure TInnerRepairCheckForm.dtp_OperateTimeChange(Sender: TObject);
begin
if cds_FabricData.Active then
cds_FabricData.EmptyDataSet;
end;
procedure TInnerRepairCheckForm.cds_FabricDataAfterScroll(
DataSet: TDataSet);
begin
btn_Ignore.Caption:=IfThen(DataSet.FieldByName('Is_Ignore').AsBoolean, '取消忽略(&U)', '忽略(&I)');
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://192.168.3.70:8080/fire/services/FireDwr?wsdl
// >Import : http://192.168.3.70:8080/fire/services/FireDwr?wsdl:0
// Encoding : UTF-8
// Version : 1.0
// (2011/7/6 17:45:16 - - $Rev: 10138 $)
// ************************************************************************ //
unit FireDwr;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
const
IS_NLBL = $0004;
IS_REF = $0080;
type
FireDwrPortType = interface(IInvokable)
['{2603990C-5694-AF6B-EB17-8E02F9A444F5}']
function addInfo(const in0: WideString; const in1: WideString): Boolean; stdcall;
end;
function GetFireDwrPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): FireDwrPortType;
implementation
uses SysUtils;
function GetFireDwrPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): FireDwrPortType;
const
defWSDL = 'http://192.168.3.70:8080/fire/services/FireDwr?wsdl';
defURL = 'http://192.168.3.70:8080/fire/services/FireDwr';
defSvc = 'FireDwr';
defPrt = 'FireDwrHttpPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as FireDwrPortType);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(FireDwrPortType), 'http://dwr.fireinfo.fire.sxsihe.com', 'UTF-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(FireDwrPortType), '');
InvRegistry.RegisterInvokeOptions(TypeInfo(FireDwrPortType), ioDocument);
InvRegistry.RegisterExternalParamName(TypeInfo(FireDwrPortType), 'addInfo', 'out_', 'out');
end. |
unit UnitAlwaysOnTop;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UnitMain, Menus, ComCtrls, StdCtrls, Buttons, sSkinProvider;
type
TFormAlwaysOnTop = class(TForm)
ListView1: TListView;
PopupMenu1: TPopupMenu;
Check1: TMenuItem;
UnCheck1: TMenuItem;
N1: TMenuItem;
Apply1: TMenuItem;
sSkinProvider1: TsSkinProvider;
SpeedButton1: TSpeedButton;
procedure PopupMenu1Popup(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Check1Click(Sender: TObject);
procedure UnCheck1Click(Sender: TObject);
procedure Apply1Click(Sender: TObject);
procedure ListView1DblClick(Sender: TObject);
procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn);
procedure ListView1KeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormAlwaysOnTop: TFormAlwaysOnTop;
implementation
{$R *.dfm}
procedure TFormAlwaysOnTop.Apply1Click(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure TFormAlwaysOnTop.Check1Click(Sender: TObject);
begin
if ListView1.Selected <> nil then
ListView1.Selected.Checked := True;
end;
procedure TFormAlwaysOnTop.FormCreate(Sender: TObject);
begin
FormMain.ImageListDiversos.GetBitmap(18, SpeedButton1.Glyph);
end;
procedure TFormAlwaysOnTop.FormShow(Sender: TObject);
var
i: integer;
Item: TListItem;
begin
ListView1.Items.Clear;
for i := 0 to Screen.FormCount - 1 do
begin
if Screen.Forms[i].Visible = False then Continue;
if Screen.Forms[i].Handle = Handle then Continue;
Item := ListView1.Items.Add;
Item.Caption := IntToStr(Screen.Forms[i].Handle);
Item.SubItems.Add(Screen.Forms[i].Caption);
if GetWindowLong(Screen.Forms[i].Handle, GWL_EXSTYLE) and WS_EX_TOPMOST <> 0 then Item.Checked := True else
Item.Checked := False;
end;
end;
var
LastSortedColumn: TListColumn;
Ascending: boolean;
function SortByColumn(Item1, Item2: TListItem; Data: integer): integer; stdcall;
var
n1, n2: int64;
s1, s2: string;
begin
if LastSortedColumn.Index = 0 then
begin
if LastSortedColumn.Index = 0 then
begin
n1 := StrToIntDef(Item1.caption, 0);
n2 := StrToIntDef(Item2.caption, 0);
end;
if (n1 = n2) then Result := 0 else if (n1 > n2) then Result := 1 else Result := -1;
end else
begin
Result := 0;
if Data = 0 then Result := AnsiCompareText(Item1.Caption, Item2.Caption)
else Result := AnsiCompareText(Item1.SubItems[Data - 1], Item2.SubItems[Data - 1]);
end;
if not Ascending then Result := -Result;
end;
procedure TFormAlwaysOnTop.ListView1ColumnClick(Sender: TObject;
Column: TListColumn);
var
i: integer;
begin
Ascending := not Ascending;
if Column <> LastSortedColumn then Ascending := not Ascending;
for i := 0 to Listview1.Columns.Count -1 do Listview1.Column[i].ImageIndex := -1;
LastSortedColumn := Column;
Listview1.CustomSort(@SortByColumn, LastSortedColumn.Index);
end;
procedure TFormAlwaysOnTop.ListView1DblClick(Sender: TObject);
begin
if ListView1.Selected = nil then Exit;
ListView1.Selected.Checked := not ListView1.Selected.Checked;
end;
procedure TFormAlwaysOnTop.ListView1KeyPress(Sender: TObject; var Key: Char);
begin
if key = #27 then Close;
end;
procedure TFormAlwaysOnTop.PopupMenu1Popup(Sender: TObject);
begin
if ListView1.Selected = nil then
begin
Check1.Enabled := False;
UnCheck1.Enabled := False;
end else
if ListView1.Selected.Checked then
begin
Check1.Enabled := False;
UnCheck1.Enabled := True;
end else
if ListView1.Selected.Checked = False then
begin
Check1.Enabled := True;
UnCheck1.Enabled := False;
end;
end;
procedure TFormAlwaysOnTop.SpeedButton1Click(Sender: TObject);
begin
Apply1.Click;
end;
procedure TFormAlwaysOnTop.UnCheck1Click(Sender: TObject);
begin
if ListView1.Selected <> nil then
ListView1.Selected.Checked := False;
end;
end.
|
// Wheberson Hudson Migueletti, em Brasília, 18 de abril de 1999.
// Tratamento de arquivos Windows Cabinet.
unit DelphiCabinet;
interface
uses Windows, Classes, SysUtils;
const
cCabSignature= $4643534D; // MSCF (Em ordem inversa)
cCabVersion = $0103;
type
{
CAB FILE LAYOUT (Sven B. Schreiber, sbs@orgon.com)
=================================================================
(1) CAB_HEADER structure
(2) Reserved area, if CAB_HEADER.flags & CAB_FLAG_RESERVE
(3) Previous cabinet name, if CAB_HEADER.flags & CAB_FLAG_HASPREV
(4) Previous disk name, if CAB_HEADER.flags & CAB_FLAG_HASPREV
(5) Next cabinet name, if CAB_HEADER.flags & CAB_FLAG_HASNEXT
(6) Next disk name, if CAB_HEADER.flags & CAB_FLAG_HASNEXT
(7) CAB_FOLDER structures (n = CAB_HEADER.cFolders)
(8) CAB_ENTRY structures / file names (n = CAB_HEADER.cFiles)
(9) File data (offset = CAB_FOLDER.coffCabStart)
}
TCabHeader= packed record
Sig : LongInt; // File signature 'MSCF'
cSumHeader : LongInt; // Header checksum (0 if not used)
cbCabinet : LongInt; // Cabinet file size
cSumFolders: LongInt; // Folders checksum (0 if not used)
cOffFiles : LongInt; // Offset of first CAB_ENTRY
cSumFiles : LongInt; // Files checksum (0 if not used)
Version : Word; // Cabinet version
cFolders : Word; // Number of folders
cFiles : Word; // Number of files
Flags : Word; // Cabinet flags
SetID : Word; // Cabinet set id
iCabinet : Word; // Zero-based cabinet number
end;
tCabFolder= packed record
cOffCabStart: LongInt; // Offset of folder data
cCFData : Word;
TypeCompress: Word; // Compression type
end;
tCabEntry= packed record
cbFile : LongInt; // Uncompressed file size
uOffFolderStart: LongInt; // File offset after decompression
iFolder : Word; // File control id
Date : Word; // File date stamp, as used by DOS
Time : Word; // File time stamp, as used by DOS
Attribs : Word; // File attributes
end;
pInfoCabinet= ^tInfoCabinet;
tInfoCabinet= record
Descompactado: LongInt;
Modificado : TDateTime;
end;
TCabinet= class
protected
Stream: TStream;
procedure Armazenar (Arquivo: String; Descompactado: LongInt; Data, Hora: Word);
public
Status: Boolean;
Lista : TStringList;
constructor Create;
destructor Destroy; override;
function ExtrairNomePath (const Completo: String; var Path: String): String;
function IsValid (const FileName: String): Boolean;
procedure LoadFromFile (const FileName: String);
end;
implementation
const
cSizeOfCabHeader= SizeOf (TCabHeader);
constructor TCabinet.Create;
begin
inherited Create;
Lista:= TStringList.Create;
end; // Create ()
destructor TCabinet.Destroy;
begin
Lista.Free;
inherited Destroy;
end; // Destroy ()
procedure TCabinet.Armazenar (Arquivo: String; Descompactado: LongInt; Data, Hora: Word);
var
Aux : LongInt;
Info : pInfoCabinet;
DataHora: TDateTime;
begin
try
LongRec (Aux).Hi:= Data;
LongRec (Aux).Lo:= Hora;
DataHora := FileDateToDateTime (Aux);
except
DataHora:= 0;
end;
New (Info);
Info^.Descompactado:= Descompactado;
Info^.Modificado := DataHora;
Lista.AddObject (Arquivo, TObject (Info));
end; // Armazenar ()
function TCabinet.ExtrairNomePath (const Completo: String; var Path: String): String;
var
K, P: Integer;
begin
P:= 0;
for K:= Length (Completo) downto 1 do
if (Completo[K] = '\') or (Completo[K] = '/') then begin
P:= K;
Break;
end;
Result:= Copy (Completo, P+1, Length (Completo)-P);
if P > 0 then
Path:= Copy (Completo, 1, P)
else
Path:= '';
end; // ExtrairNomePath ()
procedure TCabinet.LoadFromFile (const FileName: String);
var
Header: TCabHeader;
function CapturarHeader: Boolean;
begin
Stream.Read (Header, cSizeOfCabHeader);
Status:= (Header.Sig = cCabSignature) and (Header.Version = cCabVersion) and (Header.cOffFiles > cSizeOfCabHeader);
Result:= Status;
end; // CapturarHeader ()
procedure CapturarArquivos;
var
C : Char;
P : Word;
Arquivo: String;
Entry : tCabEntry;
begin
try
Stream.Position:= Header.cOffFiles;
for P:= 1 to Header.cFiles do begin
Stream.Read (Entry, SizeOf (tCabEntry));
Arquivo:= '';
repeat
Stream.Read (C, 1);
Arquivo:= Arquivo + C;
until C = #0;
Armazenar (Arquivo, Entry.cbFile, Entry.Date, Entry.Time);
end;
except
Status:= False;
end;
end; // CapturarArquivos ()
begin
try
Status:= False;
Stream:= TMemoryStream.Create;
TMemoryStream (Stream).LoadFromFile (FileName);
Lista.Clear;
if CapturarHeader then
CapturarArquivos;
finally
Stream.Free;
end;
end; // LoadFromFile ()
function TCabinet.IsValid (const FileName: String): Boolean;
var
Header: TCabHeader;
begin
Result:= False;
Status:= False;
if FileExists (Filename) then begin
try
Stream:= TFileStream.Create (FileName, fmOpenRead);
Result:= (Stream.Read (Header, cSizeOfCabHeader) = cSizeOfCabHeader) and (Header.Sig = cCabSignature) and (Header.Version = cCabVersion) and (Header.cOffFiles > cSizeOfCabHeader);
Status:= True;
finally
Stream.Free;
end;
end;
end; // IsValid ()
end.
|
unit frmRecipe;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, frmBase, StdCtrls, Buttons, ComCtrls, cxControls, cxContainer,
cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, ExtCtrls, cxSplitter, DB,
DBClient, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxDBData, cxGridLevel, cxClasses, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Menus,
Grids, ValEdit;
type
TRecipeForm = class(TBaseForm)
pgcRecipe: TPageControl;
ts_Only: TTabSheet;
cxbeGFKey: TcxButtonEdit;
cbbOnlineOperation: TComboBox;
GroupBox2: TGroupBox;
lstUncheck: TListBox;
tvOnline: TTreeView;
Label1: TLabel;
btnCheck: TSpeedButton;
btnSave: TSpeedButton;
btnClose: TSpeedButton;
btnDeletet: TSpeedButton;
btnRefresh: TSpeedButton;
cxspl_Only: TcxSplitter;
pnl_Only: TPanel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label12: TLabel;
cbbFloodPercent: TComboBox;
cbbFloodClass: TComboBox;
cbbMachineID: TComboBox;
cbbSampleType: TComboBox;
cbTrace: TCheckBox;
edtRecipeNO: TEdit;
edtOperationName: TEdit;
edtOperator: TEdit;
edtOperateTime: TEdit;
edtChecker: TEdit;
edtCheckTime: TEdit;
cdsCards: TClientDataSet;
Label13: TLabel;
edtCurVolume: TEdit;
Splitter1: TSplitter;
PopupMenu1: TPopupMenu;
NAddTry: TMenuItem;
NDiluteTry: TMenuItem;
grp1: TGroupBox;
lvIncludeCard: TListView;
chkAll: TCheckBox;
pnlClient: TPanel;
grp_Only: TGroupBox;
mmoRemark: TMemo;
GroupBox1: TGroupBox;
tvChemical: TTreeView;
btnAdd: TSpeedButton;
btnDel: TSpeedButton;
cxSplitter1: TcxSplitter;
vleChemicallist: TValueListEditor;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure btnCheckClick(Sender: TObject);
procedure btnDeletetClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure cxbeGFKeyPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cbbOnlineOperationKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure lstUncheckKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnAddClick(Sender: TObject);
procedure tvOnlineKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnDelClick(Sender: TObject);
procedure NAddTryClick(Sender: TObject);
procedure NDiluteTryClick(Sender: TObject);
procedure ChangeValues(Sender: TObject);
procedure cbTraceClick(Sender: TObject);
procedure chkAllClick(Sender: TObject);
procedure tvChemicalKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure pgcRecipeChange(Sender: TObject);
private
{ Private declarations }
Modify: Boolean;
procedure GenerateSubRecipe(aType: string);
procedure GetRecipeCardInfo;
procedure Refresh;
procedure FillCards(cdsCards: TClientDataSet);
procedure GetRecipeInfo(Recipe_NO: string);
function SaveRecipeInfo(Checker: string;IType: Integer): string;
function CheckChemmicalData(var AChemicalStr: string; var AUnitQtyStr: string): Boolean;
protected
procedure UpdateActions; override;
public
{ Public declarations }
end;
var
RecipeForm: TRecipeForm;
implementation
uses StrUtils, Math, ServerDllPub, uLogin, uFNMArtInfo, uGridDecorator,
UAppOption, uShowMessage, uCADInfo, UFNMResource, uDictionary, uGlobal,
frmSubRecipe;
{$R *.dfm}
function TRecipeForm.CheckChemmicalData(var AChemicalStr: string; var AUnitQtyStr: string): Boolean;
var i: Integer;
begin
if vleChemicallist.Strings.Text <> '' then
begin
for i := 1 to vleChemicallist.RowCount - 1 do
begin
AChemicalStr := AChemicalStr + IntTostr(Integer(vleChemicallist.Strings.Objects[i-1])) + '+';
AUnitQtyStr := AUnitQtyStr + vleChemicallist.Values[vleChemicallist.Keys[i]] + '+';
end;
end;
Result := (AChemicalStr<>'') and (AUnitQtyStr<>'');
end;
procedure TRecipeForm.GenerateSubRecipe(aType: string);
var
i:Integer;
Recipe_NO: string;
Node: TTreeNode;
sCondition,SubRecipeNO,sErrorMsg: widestring;
begin
if tvOnline.Selected = nil then Exit;
Recipe_NO := tvOnline.Selected.Text;
if tvOnline.Selected.HasChildren then
Node := tvOnline.Selected
else
Node := tvOnline.Selected.Parent;
if Recipe_NO <> edtRecipeNO.Text then GetRecipeInfo(Recipe_NO);
if vleChemicallist.Strings.Text = '' then Exit;
if not Assigned(SubRecipeForm) then
SubRecipeForm:= TSubRecipeForm.Create(Self);
with SubRecipeForm do
begin
sType := aType;
if aType = '冲稀' then
begin
Caption := '化料冲稀';
if vleChemicallist.Strings.Text <> '' then
for i := 1 to vleChemicallist.RowCount - 1 do
clbChemicalList.Items.AddObject(vleChemicallist.Keys[i] + ':'+StringOfChar(' ', 20 - Length(vleChemicallist.Keys[i]))+ vleChemicallist.Values[vleChemicallist.Keys[i]],vleChemicallist.Strings.Objects[i-1]);
gbDilute.BringToFront;
end else
begin
Caption := '化料加料';
if vleChemicallist.Strings.Text <> '' then
for i := 1 to vleChemicallist.RowCount - 1 do
SubChemicallist.Strings.AddObject(vleChemicallist.Keys[i] + ':'+StringOfChar(' ', 25 - Length(vleChemicallist.Keys[i]))+ vleChemicallist.Values[vleChemicallist.Keys[i]]+'='+vleChemicallist.Values[vleChemicallist.Keys[i]],vleChemicallist.Strings.Objects[i-1]);
gbAdd.BringToFront;
end;
if ShowModal = mrOK then
begin
if (ChemicalStr <>'') and (UnitQtyStr <>'') then
begin
sCondition := QuotedStr(aType)+','+QuotedStr(Recipe_NO)+','+
QuotedStr(ChemicalStr)+','+ QuotedStr(UnitQtyStr)+','+
QuotedStr(edtCurVolume.Text)+','+QuotedStr(Login.LoginID);
FNMServerObj.SaveDataBySQLEx('RCPCreateSubRecipeInfo',sCondition,SubRecipeNO,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveAssiPrescription, [sErrorMsg]);
ShowMsgDialog(@MSG_SaveRecipeSuccess, mtInformation);
tvOnline.Items.AddChild(Node,SubRecipeNO);
Node.Expand(True);
GetRecipeInfo(SubRecipeNO);
end;
end;
end;
end;
procedure TRecipeForm.FillCards(cdsCards: TClientDataSet);
begin
if not cdsCards.Active then Exit;
lvIncludeCard.Items.BeginUpdate;
lvIncludeCard.Items.Clear;
with cdsCards do
begin
DisableControls;
First;
while not Eof do
begin
with lvIncludeCard.Items.Add do
begin
Caption := Trim(FieldByName('FN_Card').AsString);
SubItems.Add(Trim(FieldByName('GF_NO').AsString));
SubItems.Add(Trim(FieldByName('Quantity').AsString));
Checked := True;
end;
Next;
end;
EnableControls;
end;
lvIncludeCard.Items.EndUpdate;
end;
function TRecipeForm.SaveRecipeInfo(Checker: string;iType: Integer): string;
var
ChemicalStr, UnitQtyStr, FNCardStr: string;
i: Integer;
sCondition,Recipe_NO,sErrorMsg: widestring;
begin
ChemicalStr := '';
UnitQtyStr := '';
if not CheckChemmicalData(ChemicalStr,UnitQtyStr) then Exit;
FNCardStr := '';
for i := 0 to lvIncludeCard.Items.Count - 1 do
if lvIncludeCard.Items[i].Checked then
FNCardStr := FNCardStr + lvIncludeCard.Items[i].Caption + ',';
if FNCardStr = '' then Exit;
sCondition := QuotedStr(edtRecipeNO.Text)+','+QuotedStr(edtOperationName.Hint)+','+
QuotedStr(LeftStr(cbbMachineID.Text,4))+',0,0'+','+QuotedStr(cbbFloodClass.Text)+','+
QuotedStr(cbbFloodPercent.Text)+','+QuotedStr(IntToStr(cbbSampleType.ItemIndex))+','+
QuotedStr(ifThen(cbTrace.Checked,'1','0'))+','+QuotedStr(mmoRemark.Text)+','+
QuotedStr(ChemicalStr)+','+ QuotedStr(UnitQtyStr)+','+QuotedStr(FNCardStr)+','+
QuotedStr(Login.CurrentDepartment)+','+QuotedStr(Login.LoginID)+','+
QuotedStr(Checker)+','+ IntToStr(iType);
FNMServerObj.SaveDataBySQLEx('RCPSaveRecipeInfo',sCondition,Recipe_NO,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveAssiPrescription, [sErrorMsg]);
ShowMsgDialog(@MSG_SaveRecipeSuccess, mtInformation);
result := Recipe_NO;
end;
procedure TRecipeForm.GetRecipeCardInfo;
var
vData: OleVariant;
sCondition,sErrorMsg: WideString;
begin
if Trim(cxbeGFKey.Text) = '' then exit;
sCondition := QuotedStr('') + ','+ QuotedStr(cxbeGFKey.Text) + ','+
QuotedStr('') + ','+ QuotedStr('') + ','+
QuotedStr('') + ','+ QuotedStr(Login.CurrentDepartment) + ',2';
FNMServerObj.GetQueryData(vData,'RCPGetRecipeCardInfo',sCondition,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetOnlineStdPrescripNO, [sErrorMsg]);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetOnLineOperationList, [(cxbeGFKey.Text), sErrorMsg]);
cdsCards.Data:=vData;
if cdsCards.IsEmpty then
raise Exception.CreateResFmt(@ERR_OnLineOperationList, [(cxbeGFKey.Text)]);
cxbeGFKey.Text:=cdsCards['GF_NO'];
cxbeGFKey.Tag:=cdsCards['GF_ID'];
FillItemsFromDataSet(cdsCards, 'Operation_Code', 'Operation_Name', '', '--', cbbOnLineOperation.Items);
end;
procedure TRecipeForm.GetRecipeInfo(Recipe_NO: string);
var
sCondition,sErrorMsg: WideString;
vData: OleVariant;
begin
sCondition := QuotedStr(Recipe_NO);
FNMServerObj.GetQueryData(vData,'RCPGetRecipeInfo',sCondition,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@GetAssiPrescriptionError, [sErrorMsg]);
TempClientDataSet.Data := vData[0];
with TempClientDataSet do
begin
FillMachineListByOperationCode(Login.CurrentDepartment,FieldByName('Operation_Code').AsString, cbbMachineID.Items);
TGlobal.SetComboBoxValue(cbbMachineID, Trim(FieldByName('Machine_ID').AsString));
TGlobal.SetComboBoxValue(cbbFloodClass, Trim(FieldByName('Flood_Class').AsString));
TGlobal.SetComboBoxValue(cbbFloodPercent, Trim(FieldByName('Flood_Percent').AsString));
TGlobal.SetComboBoxValue(cbbSampleType, Trim(FieldByName('Sample_Type').AsString));
edtRecipeNO.Text := FieldByName('Recipe_NO').AsString;
edtCurVolume.Text := FieldByName('Fact_Volume').AsString;
edtOperationName.Text :=FieldByName('Operation_CHN').AsString;
edtOperationName.Hint :=FieldByName('Operation_Code').AsString;
edtOperator.Text:=FieldByName('Operator').AsString;
edtOperateTime.Text:=FieldByName('Operate_Time').AsString;
edtChecker.Text:=FieldByName('Checker').AsString;
edtCheckTime.Text:=FieldByName('Check_Time').AsString;
mmoRemark.Text:=FieldByName('Remark').AsString;
end;
//填充具体化工料
TempClientDataSet.Data := vData[1];
FillItemsFromDataSet(TempClientDataSet, 'Chemical_Name', 'Unit_QTY', 'Chemical_ID', '=', vleChemicallist.Strings);
//填充卡号
TempClientDataSet.Data := vData[2];
FillCards(TempClientDataSet);
end;
procedure TRecipeForm.UpdateActions;
begin
btnAdd.Enabled := pgcRecipe.ActivePageIndex = 0;
btnDel.Enabled := pgcRecipe.ActivePageIndex = 0;
btnSave.Enabled := pgcRecipe.ActivePageIndex = 0;
btnCheck.Enabled := (pgcRecipe.ActivePageIndex = 0) AND (edtRecipeNO.Text<>'');
btnDeletet.Enabled := (pgcRecipe.ActivePageIndex = 0) AND (edtRecipeNO.Text<>'');
if pgcRecipe.ActivePageIndex = 0 then
vleChemicallist.Options:=vleChemicallist.Options + [goEditing]
else
vleChemicallist.Options:=vleChemicallist.Options - [goEditing];
lvIncludeCard.Enabled := pgcRecipe.ActivePageIndex = 0;
mmoRemark.ReadOnly := pgcRecipe.ActivePageIndex = 1;
end;
procedure TRecipeForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Action:=caFree;
end;
procedure TRecipeForm.FormCreate(Sender: TObject);
begin
inherited;
//加载图标
btnSave.Glyph.LoadFromResourceName(HInstance, RES_SAVE);
btnAdd.Glyph.LoadFromResourceName(HInstance, RES_DOWN);
btnDel.Glyph.LoadFromResourceName(HInstance, RES_DELETE);
btnClose.Glyph.LoadFromResourceName(HInstance, RES_EXIT);
btnRefresh.Glyph.LoadFromResourceName(HInstance, RES_REFRESH);
cxbeGFKey.Properties.Buttons.Items[0].Glyph.LoadFromResourceName(HInstance, RES_QUERYSMALL);
pgcRecipe.ActivePageIndex:=0;
tvChemical.OnDblClick:=TGlobal.DblClickATreeview;
tvOnline.OnDblClick:=TGlobal.DblClickATreeview;
cbbOnlineOperation.OnDblClick:=TGlobal.DblClickAWinControl;
lstUncheck.OnDblClick:=TGlobal.DblClickAWinControl;
cbbOnLineOperation.Align:=alClient;
pgcRecipe.ActivePageIndex := 0;
Modify := False;
end;
procedure TRecipeForm.FormDestroy(Sender: TObject);
begin
inherited;
RecipeForm:=nil;
end;
procedure TRecipeForm.FormActivate(Sender: TObject);
begin
inherited;
Application.ProcessMessages;
//填充可选化工料
FillTreeItemsFromDataSetByClassField(Dictionary.cds_ChemicalList, 'Chemical_Name', 'Chemical_Type', 'Chemical_ID', '', tvChemical.Items);
OnActivate:=nil;
end;
procedure TRecipeForm.btnRefreshClick(Sender: TObject);
begin
Refresh;
end;
procedure TRecipeForm.Refresh;
var
vData: OleVariant;
sCondition,sErrorMsg: WideString;
begin
if pgcRecipe.ActivePageIndex = 0 then
sCondition := QuotedStr(Login.CurrentDepartment)+',0'
else
sCondition := QuotedStr(Login.CurrentDepartment)+',4';
FNMServerObj.GetQueryData(vData, 'RCPGetRecipeTaskInfo', sCondition, sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_GetNoCheckRecipe, [sErrorMsg]);
TempClientDataSet.Data:=vData;
if TempClientDataSet.IsEmpty then
raise Exception.CreateRes(@EMP_NoCheckRecipe);
if pgcRecipe.ActivePageIndex = 0 then
FillItemsFromDataSet(TempClientDataSet, 'Recipe_NO', '', '', '', lstUncheck.Items, False, True, True)
else
begin
tvOnline.Items.Clear;
FillTreeItemsFromDataSetByClassField(TempClientDataSet, 'Recipe_NO', 'Recipe_Type', '', '', tvOnline.Items);
end;
end;
procedure TRecipeForm.btnCheckClick(Sender: TObject);
var
Recipe_NO: widestring;
begin
inherited;
if Modify then
Recipe_NO := SaveRecipeInfo(Login.LoginID,1) // check配方时更改了配方
else
Recipe_NO := SaveRecipeInfo(Login.LoginID,2);//直接check配方
if lstUncheck.Items.IndexOf(Recipe_NO) > 0 then
lstUncheck.Items.Delete(lstUncheck.Items.IndexOf(Recipe_NO));
ShowMsgDialog(@MSG_SaveCheckPrescriptionSuccess, mtInformation);
end;
procedure TRecipeForm.btnDeletetClick(Sender: TObject);
var
sCondition,sErrorMsg: WideString;
begin
if edtRecipeNO.Text = '' then Exit;
sCondition := QuotedStr(edtRecipeNO.Text)+ ','+ QuotedStr(Login.LoginName)+','+QuotedStr('1');
FNMServerObj.SaveDataBySQL('RCPDeleteRecipeInfo',sCondition,sErrorMsg);
if sErrorMsg <> '' then
raise ExceptionEx.CreateResFmt(@ERR_SaveDelRecipe, [sErrorMsg]);
ShowMsgDialog(@MSG_SaveDelRecipeSuccess, mtInformation);
end;
procedure TRecipeForm.btnSaveClick(Sender: TObject);
var
Recipe_NO: string;
begin
inherited;
Recipe_NO := SaveRecipeInfo('',0); //新建工艺
if pgcRecipe.ActivePageIndex = 0 then
begin
if lstUncheck.Items.IndexOf(Recipe_NO) = -1 then
lstUncheck.Items.Add(Recipe_NO);
end;
end;
procedure TRecipeForm.btnCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TRecipeForm.cxbeGFKeyPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
begin
inherited;
GetRecipeCardInfo;
end;
procedure TRecipeForm.cbbOnlineOperationKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
Operation_Code: string;
begin
inherited;
if Key = VK_RETURN then
begin
if cbbOnlineOperation.ItemIndex = -1 then exit;
Operation_Code := LeftStr(cbbOnlineOperation.Text, 3);
FillMachineListByOperationCode(Login.CurrentDepartment, Operation_Code, cbbMachineID.Items);
cdsCards.Filtered := False;
cdsCards.Filter := 'Operation_Code = ' + QuotedStr(Operation_Code);
cdsCards.Filtered := True;
FillCards(cdsCards);
end;
end;
procedure TRecipeForm.lstUncheckKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
begin
if lstUncheck.ItemIndex = -1 then Exit;
GetRecipeInfo(lstUncheck.Items[lstUncheck.ItemIndex]);
end;
end;
procedure TRecipeForm.btnAddClick(Sender: TObject);
var
Chemical_ID: Integer;
begin
inherited;
if (tvChemical.Selected = nil) or (tvChemical.Selected.Level = 0) then exit;
Chemical_ID:=Integer(tvChemical.Selected.Data);
if vleChemicallist.Strings.IndexOfObject(TObject(Chemical_ID)) = -1 then
if vleChemicallist.RowCount = 2 then
vleChemicallist.Strings.AddObject(tvChemical.Selected.Text + '=0.00', TObject(Chemical_ID))
else
vleChemicallist.Strings.InsertObject(vleChemicallist.Row, tvChemical.Selected.Text + '=0.00', TObject(Chemical_ID));
end;
procedure TRecipeForm.tvOnlineKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if Key = VK_RETURN then
begin
if tvOnline.Selected = nil then Exit;
GetRecipeInfo(tvOnline.Selected.Text);
end;
end;
procedure TRecipeForm.btnDelClick(Sender: TObject);
begin
inherited;
if vleChemicallist.Strings.Text <> '' then
vleChemicallist.DeleteRow(vleChemicallist.Row);
end;
procedure TRecipeForm.NAddTryClick(Sender: TObject);
begin
inherited;
GenerateSubRecipe('加料');
end;
procedure TRecipeForm.NDiluteTryClick(Sender: TObject);
begin
inherited;
GenerateSubRecipe('冲稀');
end;
procedure TRecipeForm.ChangeValues(Sender: TObject);
begin
Modify := True;
end;
procedure TRecipeForm.cbTraceClick(Sender: TObject);
begin
inherited;
Modify := True;
end;
procedure TRecipeForm.chkAllClick(Sender: TObject);
var
i: Integer;
begin
with lvIncludeCard.Items do
for i := 0 to Count - 1 do
Item[i].Checked := chkAll.Checked;;
end;
procedure TRecipeForm.tvChemicalKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_RETURN) and (pgcRecipe.ActivePageIndex = 0) then
btnAdd.Click;
end;
procedure TRecipeForm.pgcRecipeChange(Sender: TObject);
begin
inherited;
vleChemicallist.Strings.Clear;
lvIncludeCard.Clear;
mmoRemark.Lines.Clear;
if tvOnline.Items.Count = 0 then
Refresh;
end;
end.
|
unit SettingsUnit;
interface
uses
Vcl.Graphics, vcl.stdctrls;
type
settings = class
setting1: settings;
checkboxRed:TCheckbox;
checkboxYellow:TCheckbox;
checkboxBlue:TCheckbox;
labelColor:Tlabel;
labelSize:Tlabel;
public
procedure print(Form1: TForm1);
procedure clean(Form1: TForm1);
end;
implementation
{ settings }
procedure settings.clean(Form1: TForm1);
begin
end;
procedure settings.print(Form1: TForm1);
begin
checkboxRed:=checkboxRed.create(TForm1);
checkboxYellow:=checkboxYellow.create(TForm1);
checkboxBlue:=checkboxBlue.create(TForm1);
LabelColor:=labelColor.Create(TForm1);
LabelSize:=labelSize.Create(TForm1);
with labelColor do
begin
caption:='Выберите цвет фона:';
width:=50;
height:=20;
top:=20;
left:=30;
end;
with checkboxRed do
begin
caption:='Красный';
top:=45;
left:=30;
width:=50;
height:=20;
end;
with checkboxYellow do
begin
caption:='Желтый';
top:=65;
left:=30;
width:=50;
height:=20;
end;
with checkboxBlue do
begin
caption:='Синий';
top:=85;
left:=30;
width:=50;
height:=20;
end;
with labelSize do
begin
caption:='Введите размеры окна:';
width:=50;
height:=20;
top:=100;
left:=30;
end;
end;
end.
|
{*
FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn
Cryptograpical code from OpenSSL Project
*}
unit sshauth;
interface
uses Classes, sshutil;
type
TSSHAUTH = class
protected
Session: TObject;
public
user: string;
constructor Create(Owner: TObject); virtual;
function OnPacket(Packet: TObject): boolean; virtual; // faint
end;
TSSHPASSWDAUTH = class(TSSHAUTH)
protected
pass: string;
AuthTries: integer;
public
constructor Create(Owner: TObject); override;
function OnPacket(Packet: TObject): boolean; override; // still virtual
end;
TSSH1PASSWDAuthState = (BEFORE_AUTH, USER_SENT, PASS_SENT, AUTH_OK);
TSSH1PASSWDAUTH = class(TSSHPASSWDAUTH)
private
state: TSSH1PASSWDAuthState;
public
constructor Create(Owner: TObject); override;
function OnPacket(Packet: TObject): boolean; override;
end;
TSSH2PASSWDAuthState = (BEGIN_AUTH, AUTH_SRVREQ_SENT, AUTH_USERNAME_SENT,
AUTH_PASS_SENT, AUTH_COMPLETE, CONN_LOOP);
TSSH2PASSWDAUTH = class(TSSHPASSWDAUTH)
private
state: TSSH2PASSWDAuthState;
public
constructor Create(Owner: TObject); override;
function OnPacket(Packet: TObject): boolean; override;
end;
implementation
uses SSHSession, sshconst, sshchannel, sshwsock;
{ TSSHAUTH }
constructor TSSHAUTH.Create(Owner: TObject);
begin
Session := Owner;
end;
function TSSHAUTH.OnPacket(Packet: TObject): boolean;
begin
Result := False;
end;
{ TSSHPASSWDAUTH }
constructor TSSH2PASSWDAUTH.Create(Owner: TObject);
begin
inherited Create(Owner);
state := BEGIN_AUTH;
AuthTries := 1;
end;
constructor TSSHPASSWDAUTH.Create(Owner: TObject);
begin
inherited;
end;
function TSSH2PASSWDAUTH.OnPacket(Packet: TObject): boolean;
var
MyPacket: TSSH2PacketReceiver;
MySession: TSSH2Session;
s: string;
chn: TSSH2Channel;
i: integer;
Canceled: boolean;
begin
MyPacket := TSSH2PacketReceiver(Packet);
MySession := TSSH2Session(Session);
Result := False;
case state of
BEGIN_AUTH:
begin
MySession.OutPacket.StartPacket(SSH2_MSG_SERVICE_REQUEST);
MySession.OutPacket.AddString('ssh-userauth');
MySession.OutPacket.Write;
state := AUTH_SRVREQ_SENT;
Result := True;
end;
AUTH_SRVREQ_SENT:
begin
if MyPacket.PacketType <> SSH2_MSG_SERVICE_ACCEPT then
raise ESSHError.Create('Server rejected auth request');
Canceled := False;
if Assigned(MySession.OnUserPrompt) then
MySession.OnUserPrompt(MySession, user, Canceled);
if Canceled then
begin
MySession.Disconnect('user cancelled');
Result := True;
exit;
end;
MySession.OutPacket.StartPacket(SSH2_MSG_USERAUTH_REQUEST);
MySession.OutPacket.AddString(user);
MySession.OutPacket.AddString('ssh-connection');
MySession.OutPacket.AddString('none');
MySession.OutPacket.Write;
state := AUTH_USERNAME_SENT;
Result := True;
end;
AUTH_USERNAME_SENT:
begin
if MyPacket.PacketType = SSH2_MSG_USERAUTH_SUCCESS then
begin
state := AUTH_COMPLETE;
Result := True;
exit;
end;
if MyPacket.PacketType <> SSH2_MSG_USERAUTH_FAILURE then
raise ESSHError.Create('Faint');
MyPacket.GetString(s);
if Pos('password', s) = 0 then
raise ESSHError.Create('Server does not support password auth');
Canceled := False;
if Assigned(MySession.OnPassPrompt) then
MySession.OnPassPrompt(MySession, pass, Canceled);
if Canceled then
begin
MySession.Disconnect('user cancelled');
Result := True;
exit;
end;
MySession.OutPacket.StartPacket(SSH2_MSG_USERAUTH_REQUEST);
MySession.OutPacket.AddString(user);
MySession.OutPacket.AddString('ssh-connection');
MySession.OutPacket.AddString('password');
MySession.OutPacket.AddByte(0);
MySession.OutPacket.AddString(pass);
MySession.OutPacket.Write;
state := AUTH_PASS_SENT;
Result := True;
end;
AUTH_PASS_SENT:
begin
if MyPacket.PacketType = SSH2_MSG_USERAUTH_SUCCESS then
begin
state := AUTH_COMPLETE;
// open channels here
chn := TSSH2Channel.Create(MySession);
chn.LocalChannelID := 0;
chn.LocalWinSize := 16384;
chn.LocalMaxPkt := $4000;
MySession.AddChannel(chn);
MySession.MainChan := chn;
MySession.OutPacket.StartPacket(SSH2_MSG_CHANNEL_OPEN);
MySession.OutPacket.AddString('session');
MySession.OutPacket.AddInteger(0);
MySession.OutPacket.AddInteger(16384);
MySession.OutPacket.AddInteger($4000);
MySession.OutPacket.Write;
Result := True;
exit;
end;
if MyPacket.PacketType <> SSH2_MSG_USERAUTH_FAILURE then
raise ESSHError.Create('faint');
if AuthTries = 0 then raise ESSHError.Create('Too many tries');
Canceled := False;
if Assigned(MySession.OnPassPrompt) then
MySession.OnPassPrompt(MySession, pass, Canceled);
if Canceled then
begin
MySession.Disconnect('user cancelled');
Result := True;
exit;
end;
MySession.OutPacket.StartPacket(SSH2_MSG_USERAUTH_REQUEST);
MySession.OutPacket.AddString(user);
MySession.OutPacket.AddString('ssh-connection');
MySession.OutPacket.AddString('password');
MySession.OutPacket.AddByte(0);
MySession.OutPacket.AddString(pass);
MySession.OutPacket.Write;
Dec(AuthTries);
Result := True;
end;
AUTH_COMPLETE:
begin
if MyPacket.PacketType <> SSH2_MSG_CHANNEL_OPEN_CONFIRMATION then
raise ESSHError.Create('server refuses open channel');
MyPacket.GetInteger(i);
if i <> TSSH2channel(MySession.MainChan).LocalChannelID then
raise ESSHError.Create('server refuses open channel');
MyPacket.GetInteger(i);
TSSH2channel(MySession.MainChan).RemoteChannelID := i;
MyPacket.GetInteger(i);
TSSH2channel(MySession.MainChan).RemotewinSize := i;
MyPacket.GetInteger(i);
TSSH2channel(MySession.MainChan).RemoteMaxPkt := i;
// add the ondata handler
TSSH2channel(MySession.MainChan).OnDataAvalible :=
TSSHWSocket(MySession.Sock).AddData;
TSSH2channel(MySession.MainChan).OnExtDataAvalible :=
TSSHWSocket(MySession.Sock).AddData;
state := CONN_LOOP;
Result := False; // trigger upper level
end;
CONN_LOOP:
begin
// we handle SSH2_MSG_CHANNEL_WINDOW_ADJUST here
if MyPacket.PacketType = SSH2_MSG_CHANNEL_WINDOW_ADJUST then
begin
MyPacket.Getinteger(i);
chn := MySession.FindChannel(i);
if chn = nil then exit; // wrong channel , ignore
MyPacket.Getinteger(i);
Inc(chn.RemoteWinSize, i);
// If this channel has data pending, send it now
chn.Flush;
Result := True;
end;
end;
end;
end;
function TSSHPASSWDAUTH.OnPacket(Packet: TObject): boolean;
begin
// still pure virtual method
Result := False;
end;
{ TSSH1PASSWDAUTH }
constructor TSSH1PASSWDAUTH.Create(Owner: TObject);
begin
inherited;
AuthTries := 3;
state := BEFORE_AUTH;
end;
function TSSH1PASSWDAUTH.OnPacket(Packet: TObject): boolean;
var
MyPacket: TSSH1PacketReceiver;
MySession: TSSH1Session;
Canceled: boolean;
begin
MyPacket := TSSH1PacketReceiver(Packet);
MySession := TSSH1Session(Session);
Result := False;
case state of
BEFORE_AUTH:
begin
// send username
MySession.OutPacket.StartPacket(SSH1_CMSG_USER);
Canceled := False;
if Assigned(MySession.OnUserPrompt) then
MySession.OnUserPrompt(MySession, user, Canceled);
//MySession.OnUserPrompt(user,Canceled);
if Canceled then
begin
MySession.Disconnect('user cancel');
Result := True;
exit;
end;
MySession.OutPacket.AddString(user);
MySession.OutPacket.Write;
state := USER_SENT;
Result := True;
end;
USER_SENT:
begin
if MyPacket.PacketType = SSH1_SMSG_SUCCESS then
begin
state := AUTH_OK;
Result := False; // trigger connection protocol
exit;
end;
if MyPacket.PacketType <> SSH1_SMSG_FAILURE then
raise ESSHError.Create('strange response from server');
Canceled := False;
if Assigned(MySession.OnPassPrompt) then
MySession.OnPassPrompt(MySession, pass, Canceled);
//MySession.OnPassPrompt(Pass,Canceled);
if Canceled then
begin
MySession.Disconnect('user cancel');
Result := True;
exit;
end;
MySession.OutPacket.StartPacket(SSH1_CMSG_AUTH_PASSWORD);
Mysession.OutPacket.AddString(pass);
MySession.OutPacket.Write;
Result := True;
end;
AUTH_OK:
begin
Result := False;
end;
end;
end;
end.
|
unit FFPBox;
{=======================================================}
interface
{=======================================================}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls;
type
TFFPaintEvent = procedure (Sender: TObject; Canvas: TCanvas) of Object;
TFlickerFreePaintBox = class(TCustomControl)
private
{ Private declarations }
FOnFFPaint:TFFPaintEvent;
protected
{ Protected declarations }
procedure Paint; override;
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
property OnPaint:TFFPaintEvent read FOnFFPaint write FOnFFPaint;
property Align;
property Color;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
procedure Register;
{=======================================================}
implementation
{=======================================================}
constructor TFlickerFreePaintBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
TabStop := False;
end;
{-------------------------------------------------------}
procedure TFlickerFreePaintBox.Paint;
var bmp: TBitmap;
begin
if csDesigning in ComponentState then
with Canvas do
begin
Pen.Style := psDash;
Brush.Style := bsSolid;
Canvas.Brush.Color := Color;
Rectangle(0, 0, Width, Height);
exit;
end;
bmp := TBitmap.Create;
try
bmp.Canvas.Brush.Color := Color;
bmp.Width := Width;
bmp.Height := Height;
bmp.Canvas.Font := Font;
if Assigned(FOnFFPaint) then begin
FOnFFPaint(Self, bmp.Canvas);
Canvas.Draw(0,0, bmp);
end;
finally
bmp.Free;
end;
end;
{-------------------------------------------------------}
{------------------------¹Ø¼üÖ®´¦-----------------------}
procedure TFlickerFreePaintBox.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
Message.Result := 1;
end;
{=======================================================}
procedure Register;
begin
RegisterComponents('System', [TFlickerFreePaintBox]);
end;
end. |
unit ctm_loader;
{$mode objfpc}{$H+}
//CTM format loader
// Format specification : http://openctm.sourceforge.net/?page=about
// C source code (Marcus Geelnard) : http://openctm.sourceforge.net/?page=download
// JavaScript code (Juan Mellado) https://github.com/jcmellado/js-openctm
//
//ported Pascal by Chris Rorden and retain original license
// closely based on C source code, and retains same license
// Description: Implementation of the MG2 compression method.
//-----------------------------------------------------------------------------
// Copyright (c) 2009-2010 Marcus Geelnard
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
interface
uses
Classes, SysUtils, define_types, ULZMADecoder, dialogs;
function readCTM(const FileName: string; var Faces: TFaces; var Verts: TVertices; var vertexRGBA : TVertexRGBA): boolean;
implementation
const
kLZMApropBytes = 5; //LZMA specific props (five bytes, required by the LZMA decoder)
type
TMG2Header = packed record
magic : int32;
vtxPrec, nPrec, LBx, LBy, LBz, HBx, HBy, HBz: single;
divx, divy, divz: uint32;
end;
type
CTMfloat3 = array[0..2] of single;
CTMuint3 = array[0..2] of uint32;
procedure deByteInterleave(var F: TMemoryStream);
//see "1.3.2 Byte interleaving" of CTM specification
const
kElementSize = 4; //LZMA specific props (five bytes, required by the LZMA decoder)
var
iBytes, Bytes: array of byte;
n, i,j, k, nElem: integer;
begin
n := F.Size;
setlength(iBytes, n);
setlength(Bytes, n);
F.Position := 0;
F.Read(iBytes[0], n);
nElem := n div kElementSize;
k := 0;
for i := 0 to nElem do begin
for j := (kElementSize-1) downto 0 do begin
Bytes[k] := iBytes[(j * nElem)+ i];
k := k + 1;
end;
end;
F.Clear;
F.Position:= 0;
F.WriteBuffer(Bytes[0], n);
F.Position:= 0;
end;
function LZMAdecompress(var inStream, outStream: TMemoryStream; count: Int64): Int64;
var
decoder: TLZMADecoder;
propArray : array of byte;
begin
outStream.Clear;
result := 0;
setlength(propArray,kLZMApropBytes);
inStream.Read(propArray[0],kLZMApropBytes);
decoder := TLZMADecoder.Create;
if not decoder.SetDecoderProperties(propArray) then begin
showmessage('decode error');
exit;
end;
decoder.OnProgress:= nil;
if not decoder.Code(inStream, outStream, count) then exit;
//decoder.CleanupInstance;
decoder.free;
result := outStream.Size;
outStream.Position:= 0;
deByteInterleave(OutStream);
end;
procedure restoreIndices(var inStream : TMemoryStream; var faces: TFaces; triangleCount: int32);
// see "3.2.1 Indices" of CTM specification
// compressMG2.c
var
outSize, i, nTri, nTri2: integer;
ints: array of longint;
begin
outSize := triangleCount * sizeof(TPoint3i);
if (inStream.Size <> outSize) or (triangleCount < 1) then exit;
setLength(ints, triangleCount * 3);
inStream.Read(ints[0], outSize);
inStream.Clear;
setlength(faces, triangleCount);
nTri := triangleCount; //element interleaving stride for Y
nTri2 := nTri * 2; //element interleaving stride for Z
faces[0].X := ints[0];
faces[0].Y := faces[0].X + ints[nTri];
faces[0].Z := faces[0].X + ints[nTri2];
if nTri < 2 then exit;
for i := 1 to (nTri-1) do begin
faces[i].X := faces[i-1].X + ints[i];
if (faces[i].X = faces[i-1].X) then
faces[i].Y := faces[i-1].Y + ints[i+nTri]
else
faces[i].Y := faces[i].X + ints[i+nTri];
faces[i].Z := faces[i].X + ints[i+nTri2];
end;
end;
procedure gridIdxToPoint(mDivision: CTMuint3; mSize, mMin: CTMfloat3; aIdx: uint32; out aPoint: CTMfloat3);
var
zdiv, ydiv, i: uint32;
gridIdx: CTMuint3;
begin
zdiv := mDivision[0] * mDivision[1];
ydiv := mDivision[0];
gridIdx[2] := trunc(aIdx / zdiv);
aIdx := aIdx - (gridIdx[2] * zdiv);
gridIdx[1] := trunc(aIdx / ydiv);
aIdx := aIdx - (gridIdx[1] * ydiv);
gridIdx[0] := aIdx;
for i := 0 to 2 do
aPoint[i] := gridIdx[i] * mSize[i] + mMin[i];
end;
procedure restoreVertices(hdr: TMG2Header; var intVertices, gridIndices: TInts; var Verts: TVertices; mVertexCount: int32);
//3.3.3 Vertices for MG2 - see function ctmRestoreVertices of "compressMG2.c" Copyright (c) 2009-2010 Marcus Geelnard
var
i,j: integer;
gridOrigin, mMin, mMax, mSize: CTMfloat3;
mDivision: CTMuint3;
scale: single;
gridIdx, prevGridIndex: uint32;
deltaX, prevDeltaX: int32;
intVerticesA: TInts;
begin
if (mVertexCount < 3) or (length(gridIndices) <> mVertexCount) or (length(intVertices) <> (3 *mVertexCount)) then exit; //single triangle has 3 vertices
//remove element interleaving
intVerticesA := Copy(intVertices, Low(intVertices), Length(intVertices));
j := 0;
for i := 0 to (mVertexCount - 1) do begin
intVertices[j] := intVerticesA[i];
intVertices[j+1] := intVerticesA[i+mVertexCount];
intVertices[j+2] := intVerticesA[i+mVertexCount+mVertexCount];
j := j + 3;
end;
setlength(intVerticesA, 0);
//decode vertices
setlength(Verts,mVertexCount);
mMin[0] := hdr.LBx; mMin[1] := hdr.LBy; mMin[2] := hdr.LBz;
mMax[0] := hdr.HBx; mMax[1] := hdr.HBy; mMax[2] := hdr.HBz;
mDivision[0] := hdr.divX; mDivision[1] := hdr.divY; mDivision[2] := hdr.divZ;
for i := 0 to 2 do
mSize[i] := (mMax[i]- mMin[i]) / mDivision[i];
for i := 1 to (mVertexCount -1) do // Restore grid indices (deltas)
gridIndices[i] := gridIndices[i] + gridIndices[i-1]; //run length encoded, convert gi' -> gi, 3.3.4
scale := hdr.vtxPrec;
prevGridIndex := $7fffffff;
prevDeltaX := 0;
for i := 0 to (mVertexCount-1) do begin
// Get grid box origin
gridIdx := gridIndices[i];
//ctmGridIdxToPoint(aGrid, gridIdx, gridOrigin);
gridIdxToPoint(mDivision, mSize, mMin, gridIdx, gridOrigin);
// Restore original point
deltaX := intVertices[i * 3];
if (gridIdx = prevGridIndex) then
deltaX := deltaX + prevDeltaX;
Verts[i].X := scale * deltaX + gridOrigin[0];
Verts[i].Y := scale * intVertices[i * 3 + 1] + gridOrigin[1];
Verts[i].Z := scale * intVertices[i * 3 + 2] + gridOrigin[2];
prevGridIndex := gridIdx;
prevDeltaX := deltaX;
end;
end;
procedure RestoreAttribs(var inStream : TMemoryStream; var vertexRGBA: TVertexRGBA; vertexCount: int32; scale: single);
//decode MG2 ATTR, see 3.3.8 Attribute maps
var
i,j: integer;
aIntAttribs: TInts;
value,prev: int32;
b :byte;
begin
if vertexCount < 1 then exit;
setlength(aIntAttribs, vertexCount * 4);
inStream.Read(aIntAttribs[0], vertexCount * 4 * sizeof(single));
//adjust for Signed magnitude representation, see 1.3.3
for i := 0 to ((4*vertexCount)-1) do begin
if odd(aIntAttribs[i]) then
aIntAttribs[i] := -(1+(aIntAttribs[i]shr 1))
else
aIntAttribs[i] := aIntAttribs[i]shr 1;
end;
setlength(vertexRGBA, vertexCount);
for j := 0 to 3 do begin
prev := 0;
for i := 0 to (vertexCount-1) do begin
value := aIntAttribs[i+(J * vertexCount)] + prev;
b := round(255 * value * scale);
case j of
0: vertexRGBA[i].R := b;
1: vertexRGBA[i].G := b;
2: vertexRGBA[i].B := b;
3: vertexRGBA[i].A := b;
end;
prev := value;
end; //for i: each vertex
end; //for j: RGBA
end;
function readCTM(const FileName: string; var Faces: TFaces; var Verts: TVertices; var vertexRGBA : TVertexRGBA): boolean;
type
TCTMFileHeader = record
magic, fileFormat, compressionMethod,vertexCount,triangleCount,uvMapCount,attrMapCount, flags, commentBytes: int32;
end;
label
123, 666;
const
kFileMagic = 1297367887; //"OCTM" as 32-bit little-endian integer
kRAW = $00574152; //"RAW\0"
kMG1 = $0031474d; //"MG1\0"
kMG2 = $0032474d; //"MG2\0"
kMG2Magic = $4832474d; //"MG2H"
kVertMagic = $54524556; //"VERT"
kGidxMagic = $58444947; //"GIDX"
kIndxMagic = $58444e49; //"INDX"
kNormMagic = $4d524f4e; //"NORM"
kTexcMagic = $43584554; //"TEXC" UV texture map
kAttrMagic = $52545441; //"ATTR"
var
F: TMemoryStream;
Bytes : TBytes;
hdr: TCTMFileHeader;
hdrMG2 : TMG2Header;
id, sz, attr: int32;
outSize:int64;
outStream : TMemoryStream;
intVertices, gridIndices: TInts;
vertAttr: array of single;
i,j, mx: integer;
str: string;
sAttr: single;
begin
{$IFDEF ENDIAN_BIG} adjust code to bytewap values {$ENDIF}
result := false;
setlength(vertexRGBA,0);
if not FileExists(FileName) then exit;
//initialize values
outStream :=TMemoryStream.Create;
F := TMemoryStream.Create;
F.LoadFromFile(FileName);
//CTM Header
F.Read(hdr, sizeof(hdr));
if hdr.magic <> kFileMagic then goto 666; //signature does not match
if (hdr.compressionMethod <> kRAW) and (hdr.compressionMethod <> kMG1) and (hdr.compressionMethod <> kMG2) then goto 666; //signature does not match
if hdr.commentBytes > 0 then begin
setlength(Bytes, hdr.commentBytes);
F.Read(Bytes[0], hdr.commentBytes);
//comment:= TEncoding.ASCII.GetString(Bytes);
end;
//raw format
if (hdr.compressionMethod = kRAW) then begin
//read INDX
F.Read(id, sizeof(int32));
if (id <> kIndxMagic) then goto 666;
setlength(Faces, hdr.triangleCount);
F.Read(Faces[0], hdr.triangleCount * sizeof(TPoint3i) );
F.Read(id, sizeof(int32));
//read VERT
if (id <> kVertMagic) then goto 666;
setlength(Verts, hdr.vertexCount);
F.Read(Verts[0], hdr.vertexCount * 3 * sizeof(single));
if hdr.attrMapCount < 1 then goto 123; //all done - no vertex color map
attr := 0;
while (attr < hdr.attrMapCount) and (F.Position < (F.Size-12)) do begin
F.Read(id, sizeof(int32));
if id = kNormMagic then // 3.1.3 Normals
F.Seek(4*(1 + 3 * hdr.vertexCount), soFromCurrent); //skip this
if id = kTexcMagic then //3.1.4 UV maps
goto 123; //this file uses color texture, not vertex colors
if id = kAttrMagic then begin
F.Read(sz, sizeof(int32));
setlength(Bytes, sz);
F.Read(Bytes[0], sz);
//For all versions of Lazarus
SetString(str, PAnsiChar(@Bytes[0]), sz);
//For newer versions of Lazarus
// str := upcase(TEncoding.ASCII.GetString(Bytes));
setlength(vertAttr, hdr.vertexCount * 4);
F.Read(vertAttr[0], hdr.vertexCount * 4 * sizeof(single));
if (sz = 5) and (upcase(str) = 'COLOR') then begin
setlength(vertexRGBA, hdr.vertexCount);
for i := 0 to (hdr.vertexCount - 1) do begin
j := i * 4;
vertexRGBA[i].R := round(255 * vertAttr[j]);
vertexRGBA[i].G := round(255 * vertAttr[j+1]);
vertexRGBA[i].B := round(255 * vertAttr[j+2]);
vertexRGBA[i].A := round(255 * vertAttr[j+3]);
end;
goto 123; //all done: vertex color map loaded
end; //is COLOR
attr := attr + 1;
end; //is ATTR
end; //while not EOF
goto 123; //all done: no vertex color map found
end; //RAW
if (hdr.compressionMethod = kMG1) then begin
//read INDX
F.Read(id, sizeof(int32));
F.Read(sz, sizeof(int32));
if (id <> kIndxMagic) or (sz < 8) then goto 666;
outSize := hdr.triangleCount * sizeof(TPoint3i);
sz := LZMAdecompress(F,outStream,outSize);
if sz <> outSize then goto 666;
restoreIndices(outStream, Faces, hdr.triangleCount);
//read VERT
F.Read(id, sizeof(int32));
F.Read(sz, sizeof(int32));
if (id <> kVertMagic) or (sz < 8) then goto 666;
outSize := hdr.vertexCount * 3 * sizeof(single);
sz := LZMAdecompress(F,outStream,outSize);
if sz <> outSize then goto 666;
setlength(Verts, hdr.vertexCount);
outStream.Read(Verts[0], outSize);
end; //MG1
if (hdr.compressionMethod = kMG2) then begin
//read MG2H
F.Read(hdrMG2, sizeof(hdrMG2));
if (hdrMG2.magic <> kMG2Magic)then goto 666;
//read VERT
F.Read(id, sizeof(int32));
F.Read(sz, sizeof(int32));
if (id <> kVertMagic) or (sz < 8) then goto 666;
outSize := hdr.vertexCount * 3 * sizeof(int32);
outStream.Clear;
sz := LZMAdecompress(F,outStream,outSize);
if sz <> outSize then
showmessage(inttostr(sz)+'<>'+inttostr(outSize));
if sz <> outSize then goto 666;
setlength(intVertices, hdr.vertexCount * 3);
outStream.Read(intVertices[0], outSize);
//read GIDX
F.Read(id, sizeof(int32));
F.Read(sz, sizeof(int32));
if (id <> kGidxMagic) or (sz < 8) then goto 666;
outSize := hdr.vertexCount * sizeof(int32); //one element per vertex
sz := LZMAdecompress(F,outStream,outSize);
if sz <> outSize then goto 666;
setlength(gridIndices, hdr.vertexCount);
outStream.Read(gridIndices[0], outSize);
restoreVertices(hdrMG2, intVertices, gridIndices, Verts, hdr.vertexCount);
//read INDX
F.Read(id, sizeof(int32));
F.Read(sz, sizeof(int32));
if (id <> kIndxMagic) or (sz < 8) then goto 666;
outSize := hdr.triangleCount * sizeof(TPoint3i);
//showmessage(inttostr(F.Position)+' '+inttostr(outSize));
sz := LZMAdecompress(F,outStream,outSize);
if sz <> outSize then goto 666;
restoreIndices(outStream, Faces, hdr.triangleCount);
end; //MG2
//read color for MG1 and MG2
if hdr.attrMapCount < 1 then goto 123; //all done - no vertex color map
attr := 0;
while (attr < hdr.attrMapCount) and (F.Position < (F.Size-12)) do begin
F.Read(id, sizeof(int32));
F.Read(sz, sizeof(int32));
if id = kNormMagic then // 3.1.3 Normals
F.Seek(kLZMApropBytes + sz, soFromCurrent); //skip this, 5
if id = kTexcMagic then //3.1.4 UV maps
goto 123; //this file uses color texture, not vertex colors
if id = kAttrMagic then begin
setlength(Bytes, sz); //sz refers to size of string
F.Read(Bytes[0], sz);
//For all versions of Lazarus
SetString(str, PAnsiChar(@Bytes[0]), sz);
//For newer versions of Lazarus
// str := upcase(TEncoding.ASCII.GetString(Bytes));
if (hdr.compressionMethod = kMG2) then
F.Read(sAttr, sizeof(single)); //see 3.3.8 : Attribute value precision, s.
F.Read(sz, sizeof(int32)); //sz refers to packed bytes
outSize := hdr.vertexCount * 4 * sizeof(single);
outStream.Clear; outStream.position := 0;
sz := LZMAdecompress(F,outStream,outSize);
if (outSize = sz) and (length(str) = 5) and (upcase(str) = 'COLOR') then begin
if (hdr.compressionMethod = kMG2) then
RestoreAttribs(outStream, vertexRGBA, hdr.vertexCount, sAttr)
else begin
setlength(vertAttr, hdr.vertexCount * 4);
outStream.Read(vertAttr[0], outSize);
setlength(vertexRGBA, hdr.vertexCount);
for i := 0 to (hdr.vertexCount - 1) do begin //n.b. element interleaving
vertexRGBA[i].R := round(255 * vertAttr[i]);
vertexRGBA[i].G := round(255 * vertAttr[i+hdr.vertexCount]);
vertexRGBA[i].B := round(255 * vertAttr[i+(2*hdr.vertexCount)]);
vertexRGBA[i].A := round(255 * vertAttr[i+(3*hdr.vertexCount)]);
end; //for each vertex
end; //if MG2 else MG1
goto 123;
end; //attr = COLOR
attr := attr + 1;
end; //is ATTR
end; //not EOF
123:
result := true;
if length(vertexRGBA) > 0 then begin //if alpha not assigned, make vertex colors opaque
mx := 0;
for i := 0 to (length(vertexRGBA)-1) do
if vertexRGBA[i].A > mx then
mx := vertexRGBA[i].A;
if mx = 0 then
for i := 0 to (length(vertexRGBA)-1) do
vertexRGBA[i].A := 128;
end;
666:
outStream.Free;
F.Free;
if not result then begin
Showmessage('Unable to decode CTM file '+Filename);
setlength(Faces,0);
setlength(Verts,0);
end;
end; // readCTM()
end.
|
{
Copyright (c) 2016 by Albert Molina
Copyright (c) 2017 by BlaiseCoin developers
Distributed under the MIT software license, see the accompanying file LICENSE
or visit http://www.opensource.org/licenses/mit-license.php.
This unit is a part of BlaiseCoin, a P2P crypto-currency.
}
unit UNode;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{ UNode contains the basic structure to operate
- An app can only contains 1 node.
- A node contains:
- 1 Bank
- 1 NetServer (Accepting incoming connections)
- 1 Operations (Operations has actual BlockChain with Operations and SafeBankTransaction to operate with the Bank)
- 0..x NetClients
- 0..x Miners
}
interface
uses
Classes, UBlockChain, UNetProtocol, UAccounts, UCrypto, UThread, SyncObjs, ULog;
Type
{ TNode }
TNode = class(TComponent)
private
FNodeLog : TLog;
FLockNodeOperations : TPCCriticalSection;
FNotifyList : TList;
FBank : TPCBank;
FOperations : TPCOperationsComp;
FNetServer : TNetServer;
FBCBankNotify : TPCBankNotify;
FPeerCache : AnsiString;
FDisabledsNewBlocksCount : Integer;
procedure OnBankNewBlock(Sender : TObject);
procedure SetNodeLogFilename(const Value: AnsiString);
function GetNodeLogFilename: AnsiString;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
class function Node : TNode;
class procedure DecodeIpStringToNodeServerAddressArray(Const Ips : AnsiString; var NodeServerAddressArray : TNodeServerAddressArray);
class function EncodeNodeServerAddressArrayToIpString(Const NodeServerAddressArray : TNodeServerAddressArray) : AnsiString;
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
property Bank : TPCBank read FBank;
function NetServer : TNetServer;
procedure NotifyNetClientMessage(Sender : TNetConnection; Const TheMessage : AnsiString);
//
property Operations : TPCOperationsComp read FOperations;
//
function AddNewBlockChain(SenderConnection : TNetConnection; NewBlockOperations: TPCOperationsComp; var newBlockAccount: TBlockAccount; var errors: AnsiString): Boolean;
function AddOperations(SenderConnection : TNetConnection; Operations : TOperationsHashTree; OperationsResult : TOperationsResumeList; var errors: AnsiString): Integer;
function AddOperation(SenderConnection : TNetConnection; Operation : TPCOperation; var errors: AnsiString): Boolean;
function SendNodeMessage(Target : TNetConnection; TheMessage : AnsiString; var errors : AnsiString) : Boolean;
//
procedure NotifyBlocksChanged;
//
procedure GetStoredOperationsFromAccount(const OperationsResume: TOperationsResumeList; account_number: Cardinal; MaxDepth, MaxOperations : Integer);
function FindOperation(Const OperationComp : TPCOperationsComp; Const OperationHash : TRawBytes; var block : Cardinal; var operation_block_index : Integer) : Boolean;
//
procedure AutoDiscoverNodes(Const ips : AnsiString);
function IsBlockChainValid(var WhyNot : AnsiString) : Boolean;
function IsReady(var CurrentProcess : AnsiString) : Boolean;
property PeerCache : AnsiString read FPeerCache write FPeerCache;
procedure DisableNewBlocks;
procedure EnableNewBlocks;
property NodeLogFilename : AnsiString read GetNodeLogFilename write SetNodeLogFilename;
end;
TNodeNotifyEvents = class;
TThreadSafeNodeNotifyEvent = class(TPCThread)
FNodeNotifyEvents : TNodeNotifyEvents;
FNotifyBlocksChanged : Boolean;
FNotifyOperationsChanged : Boolean;
procedure SynchronizedProcess;
protected
procedure BCExecute; override;
constructor Create(ANodeNotifyEvents : TNodeNotifyEvents);
end;
TNodeMessageEvent = Procedure(NetConnection : TNetConnection; MessageData : TRawBytes) of object;
{ TNodeNotifyEvents is ThreadSafe and will only notify in the main thread }
TNodeNotifyEvents = class(TComponent)
private
FNode: TNode;
FPendingNotificationsList : TPCThreadList;
FThreadSafeNodeNotifyEvent : TThreadSafeNodeNotifyEvent;
FOnBlocksChanged: TNotifyEvent;
FOnOperationsChanged: TNotifyEvent;
FMessages : TStringList;
FOnNodeMessageEvent: TNodeMessageEvent;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetNode(const Value: TNode);
procedure NotifyBlocksChanged;
procedure NotifyOperationsChanged;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
property Node : TNode read FNode write SetNode;
property OnBlocksChanged : TNotifyEvent read FOnBlocksChanged write FOnBlocksChanged;
property OnOperationsChanged : TNotifyEvent read FOnOperationsChanged write FOnOperationsChanged;
property OnNodeMessageEvent : TNodeMessageEvent read FOnNodeMessageEvent write FOnNodeMessageEvent;
end;
TThreadNodeNotifyNewBlock = class(TPCThread)
FNetConnection : TNetConnection;
protected
procedure BCExecute; override;
constructor Create(NetConnection : TNetConnection);
end;
TThreadNodeNotifyOperations = class(TPCThread)
FNetConnection : TNetConnection;
FOperationsHashTree : TOperationsHashTree;
protected
procedure BCExecute; override;
constructor Create(NetConnection : TNetConnection; MakeACopyOfOperationsHashTree : TOperationsHashTree);
destructor Destroy; override;
end;
implementation
uses UOpTransaction, SysUtils, UConst, UTime;
var _Node : TNode;
{ TNode }
constructor TNode.Create(AOwner: TComponent);
begin
FNodeLog := TLog.Create(Self);
FNodeLog.ProcessGlobalLogs := false;
RegisterOperationsClass;
if Assigned(_Node) then
raise Exception.Create('Duplicate nodes protection');
TLog.NewLog(ltInfo, ClassName, 'TNode.Create');
inherited;
FDisabledsNewBlocksCount := 0;
FLockNodeOperations := TPCCriticalSection.Create('TNode_LockNodeOperations');
FBank := TPCBank.Create(Self);
FBCBankNotify := TPCBankNotify.Create(Self);
FBCBankNotify.Bank := FBank;
FBCBankNotify.OnNewBlock := OnBankNewBlock;
FNetServer := TNetServer.Create;
FOperations := TPCOperationsComp.Create(Self);
FOperations.bank := FBank;
FNotifyList := TList.Create;
if not Assigned(_Node) then
_Node := Self;
end;
destructor TNode.Destroy;
var step : String;
begin
TLog.NewLog(ltInfo, ClassName, 'TNode.Destroy START');
try
step := 'Deleting critical section';
FreeAndNil(FLockNodeOperations);
step := 'Desactivating server';
FNetServer.Active := false;
step := 'Destroying NetServer';
FreeAndNil(FNetServer);
step := 'Destroying NotifyList';
FreeAndNil(FNotifyList);
step := 'Destroying Operations';
FreeAndNil(FOperations);
step := 'Assigning NIL to node var';
if _Node = Self then
_Node := nil;
step := 'Destroying Bank';
FreeAndNil(FBCBankNotify);
FreeAndNil(FBank);
step := 'inherited';
FreeAndNil(FNodeLog);
inherited;
except
on E:Exception do
begin
TLog.NewLog(lterror, Classname, 'Error destroying Node step: ' + step + ' Errors (' + E.ClassName + '): ' +E.Message);
raise;
end;
end;
TLog.NewLog(ltInfo, ClassName, 'TNode.Destroy END');
end;
function TNode.AddNewBlockChain(SenderConnection: TNetConnection; NewBlockOperations: TPCOperationsComp;
var newBlockAccount: TBlockAccount; var errors: AnsiString): Boolean;
var
i, j : Integer;
nc : TNetConnection;
ms : TMemoryStream;
s : String;
errors2 : AnsiString;
OpBlock : TOperationBlock;
begin
Result := false;
if FDisabledsNewBlocksCount > 0 then
begin
TLog.NewLog(ltinfo, Classname, Format('Cannot Add new BlockChain due is adding disabled - Connection:%s NewBlock:%s', [
Inttohex(PtrInt(SenderConnection), 8), TPCOperationsComp.OperationBlockToText(NewBlockOperations.OperationBlock)]));
exit;
end;
if NewBlockOperations.OperationBlock.block <> Bank.BlocksCount then
exit;
OpBlock := NewBlockOperations.OperationBlock;
TLog.NewLog(ltdebug, Classname, Format('AddNewBlockChain Connection:%s NewBlock:%s', [
Inttohex(PtrInt(SenderConnection), 8), TPCOperationsComp.OperationBlockToText(OpBlock)]));
if not TPCThread.TryProtectEnterCriticalSection(Self, 2000, FLockNodeOperations) then
begin
if NewBlockOperations.OperationBlock.block <> Bank.BlocksCount then
exit;
s := 'Cannot AddNewBlockChain due blocking lock operations node';
TLog.NewLog(lterror, Classname, s);
if TThread.CurrentThread.ThreadID = MainThreadID then
raise Exception.Create(s)
else
exit;
end;
try
ms := TMemoryStream.Create;
try
FOperations.SaveBlockToStream(false, ms);
Result := Bank.AddNewBlockChainBlock(NewBlockOperations, newBlockAccount, errors);
if Result then
begin
if Assigned(SenderConnection) then
begin
FNodeLog.NotifyNewLog(ltupdate, SenderConnection.ClassName, Format(';%d;%s;%s', [OpBlock.block, SenderConnection.ClientRemoteAddr, OpBlock.block_payload]));
end else
begin
FNodeLog.NotifyNewLog(ltupdate, ClassName, Format(';%d;%s;%s', [OpBlock.block, 'NIL', OpBlock.block_payload]));
end;
end else
begin
if Assigned(SenderConnection) then
begin
FNodeLog.NotifyNewLog(lterror, SenderConnection.ClassName, Format(';%d;%s;%s;%s', [OpBlock.block, SenderConnection.ClientRemoteAddr, OpBlock.block_payload, errors]));
end else
begin
FNodeLog.NotifyNewLog(lterror, ClassName, Format(';%d;%s;%s;%s', [OpBlock.block, 'NIL', OpBlock.block_payload, errors]));
end;
end;
FOperations.Clear(true);
ms.Position := 0;
if not FOperations.LoadBlockFromStream(ms, errors2) then
begin
TLog.NewLog(lterror, Classname, 'Error recovering operations to sanitize: ' + errors2);
if Result then
errors := errors2
else
errors := errors +' - ' + errors2;
end;
finally
ms.Free;
end;
FOperations.SanitizeOperations;
finally
FLockNodeOperations.Release;
TLog.NewLog(ltdebug, Classname, Format('Finalizing AddNewBlockChain Connection:%s NewBlock:%s', [
Inttohex(PtrInt(SenderConnection), 8), TPCOperationsComp.OperationBlockToText(OpBlock) ]));
end;
if Result then begin
// Notify to clients
j := TNetData.NetData.ConnectionsCountAll;
for i := 0 to j-1 do
begin
if (TNetData.NetData.GetConnection(i, nc)) then
begin
if (nc <> SenderConnection) and nc.Connected then
TThreadNodeNotifyNewBlock.Create(nc);
end;
end;
// Notify it!
NotifyBlocksChanged;
end;
end;
function TNode.AddOperation(SenderConnection : TNetConnection; Operation: TPCOperation; var errors: AnsiString): Boolean;
var ops : TOperationsHashTree;
begin
ops := TOperationsHashTree.Create;
try
ops.AddOperationToHashTree(Operation);
Result := AddOperations(SenderConnection, ops, Nil, errors) = 1;
finally
ops.Free;
end;
end;
function TNode.AddOperations(SenderConnection : TNetConnection; Operations : TOperationsHashTree; OperationsResult : TOperationsResumeList; var errors: AnsiString): Integer;
Var
i, j : Integer;
valids_operations : TOperationsHashTree;
nc : TNetConnection;
e : AnsiString;
s : String;
OPR : TOperationResume;
ActOp : TPCOperation;
begin
Result := -1;
if Assigned(OperationsResult) then
OperationsResult.Clear;
if FDisabledsNewBlocksCount > 0 then
begin
errors := Format('Cannot Add Operations due is adding disabled - OpCount:%d', [Operations.OperationsCount]);
TLog.NewLog(ltinfo, Classname, errors);
exit;
end;
Result := 0;
errors := '';
valids_operations := TOperationsHashTree.Create;
try
TLog.NewLog(ltdebug, Classname, Format('AddOperations Connection:%s Operations:%d', [
Inttohex(PtrInt(SenderConnection), 8), Operations.OperationsCount]));
if not TPCThread.TryProtectEnterCriticalSection(Self, 4000, FLockNodeOperations) then
begin
s := 'Cannot AddOperations due blocking lock operations node';
TLog.NewLog(lterror, Classname, s);
if TThread.CurrentThread.ThreadID = MainThreadID then
raise Exception.Create(s)
else
exit;
end;
try
for j := 0 to Operations.OperationsCount-1 do
begin
ActOp := Operations.GetOperation(j);
if FOperations.OperationsHashTree.IndexOfOperation(ActOp) < 0 then
begin
if (FOperations.AddOperation(true, ActOp, e)) then
begin
inc(Result);
valids_operations.AddOperationToHashTree(ActOp);
TLog.NewLog(ltdebug, Classname, Format('AddOperation %d/%d: %s', [(j + 1), Operations.OperationsCount, ActOp.ToString]));
if Assigned(OperationsResult) then
begin
TPCOperation.OperationToOperationResume(0, ActOp, ActOp.SenderAccount, OPR);
OPR.NOpInsideBlock := FOperations.Count-1;
OPR.Balance := FOperations.SafeBoxTransaction.Account(ActOp.SenderAccount).balance;
OperationsResult.Add(OPR);
end;
end else
begin
if (errors <> '') then
errors := errors + ' ';
errors := errors + 'Op ' + IntToStr(j + 1) + '/' + IntToStr(Operations.OperationsCount) + ':' + e;
TLog.NewLog(ltdebug, Classname, Format('AddOperation invalid/duplicated %d/%d: %s - Error:%s',
[(j + 1), Operations.OperationsCount, ActOp.ToString, e]));
if Assigned(OperationsResult) then
begin
TPCOperation.OperationToOperationResume(0, ActOp, ActOp.SenderAccount, OPR);
OPR.valid := false;
OPR.NOpInsideBlock := -1;
OPR.OperationHash := '';
OPR.errors := e;
OperationsResult.Add(OPR);
end;
end;
end
else
begin
// XXXXX DEBUG ONLY
// TLog.NewLog(ltdebug, Classname, Format('AddOperation made before %d/%d: %s', [(j + 1), Operations.OperationsCount, ActOp.ToString]));
end;
end;
finally
FLockNodeOperations.Release;
if Result <> 0 then
begin
TLog.NewLog(ltdebug, Classname, Format('Finalizing AddOperations Connection:%s Operations:%d valids:%d', [
Inttohex(PtrInt(SenderConnection), 8), Operations.OperationsCount, Result ]));
end;
end;
if Result = 0 then
exit;
// Send to other nodes
j := TNetData.NetData.ConnectionsCountAll;
for i := 0 to j-1 do
begin
if TNetData.NetData.GetConnection(i, nc) then
begin
if (nc <> SenderConnection) and nc.Connected then
TThreadNodeNotifyOperations.Create(nc, valids_operations);
end;
end;
finally
valids_operations.Free;
end;
// Notify it!
for i := 0 to FNotifyList.Count-1 do
begin
TNodeNotifyEvents( FNotifyList[i] ).NotifyOperationsChanged;
end;
end;
procedure TNode.AutoDiscoverNodes(const ips: AnsiString);
var
i, j : Integer;
nsarr : TNodeServerAddressArray;
begin
DecodeIpStringToNodeServerAddressArray(ips + ';' + PeerCache, nsarr);
for i := low(nsarr) to high(nsarr) do
begin
TNetData.NetData.AddServer(nsarr[i]);
end;
j := (CT_MaxServersConnected - TNetData.NetData.ConnectionsCount(true));
if j <= 0 then
exit;
TNetData.NetData.DiscoverServers;
end;
class procedure TNode.DecodeIpStringToNodeServerAddressArray(
const Ips: AnsiString; var NodeServerAddressArray: TNodeServerAddressArray);
function GetIp(var ips_string : AnsiString; var nsa : TNodeServerAddress) : Boolean;
const CT_IP_CHARS = ['a'..'z', 'A'..'Z', '0'..'9', '.', '-', '_'];
var i : Integer;
port : AnsiString;
begin
nsa := CT_TNodeServerAddress_NUL;
Result := false;
if length(trim(ips_string)) = 0 then
begin
ips_string := '';
exit;
end;
i := 1;
while (i < length(ips_string)) and (not (ips_string[i] in CT_IP_CHARS)) do
inc(i);
if (i > 1) then
ips_string := copy(ips_string, i, length(ips_string));
//
i := 1;
while (i <= length(ips_string)) and (ips_string[i] in CT_IP_CHARS) do
inc(i);
nsa.ip := copy(ips_string, 1, i-1);
if (i <= length(ips_string)) and (ips_string[i] = ':') then
begin
inc(i);
port := '';
while (i <= length(ips_string)) and (ips_string[i] in ['0'..'9']) do
begin
port := port + ips_string[i];
inc(i);
end;
nsa.port := StrToIntDef(port, 0);
end;
ips_string := copy(ips_string, i + 1, length(ips_string));
if nsa.port = 0 then
nsa.port := CT_NetServer_Port;
Result := (trim(nsa.ip) <> '');
end;
var
ips_string : AnsiString;
nsa : TNodeServerAddress;
begin
SetLength(NodeServerAddressArray, 0);
ips_string := Ips;
repeat
if GetIp(ips_string, nsa) then
begin
SetLength(NodeServerAddressArray, length(NodeServerAddressArray) + 1);
NodeServerAddressArray[High(NodeServerAddressArray)] := nsa;
end;
until (ips_string = '');
end;
procedure TNode.DisableNewBlocks;
begin
inc(FDisabledsNewBlocksCount);
end;
procedure TNode.EnableNewBlocks;
begin
if FDisabledsNewBlocksCount = 0 then
raise Exception.Create('Dev error 20160924-1');
dec(FDisabledsNewBlocksCount);
end;
class function TNode.EncodeNodeServerAddressArrayToIpString(
const NodeServerAddressArray: TNodeServerAddressArray): AnsiString;
var i : Integer;
begin
Result := '';
for i := low(NodeServerAddressArray) to high(NodeServerAddressArray) do
begin
if (Result <> '') then Result := Result + ';';
Result := Result + NodeServerAddressArray[i].ip;
if NodeServerAddressArray[i].port > 0 then
begin
Result := Result + ':' + IntToStr(NodeServerAddressArray[i].port);
end;
end;
end;
function TNode.GetNodeLogFilename: AnsiString;
begin
Result := FNodeLog.FileName;
end;
function TNode.IsBlockChainValid(var WhyNot : AnsiString): Boolean;
var unixtimediff : Integer;
begin
Result :=false;
if (TNetData.NetData.NetStatistics.ActiveConnections <= 0) then
begin
WhyNot := 'No connection to check blockchain';
exit;
end;
if (Bank.LastOperationBlock.block <= 0) then
begin
WhyNot := 'No blockchain';
exit;
end;
unixtimediff := UnivDateTimeToUnix(DateTime2UnivDateTime(Now)) - Bank.LastOperationBlock.timestamp;
{
if (unixtimediff < -CT_MaxSecondsDifferenceOfNetworkNodes * 2) then
begin
WhyNot := 'Invalid Last Block Time';
exit;
end;
}
if unixtimediff > CT_NewLineSecondsAvg*10 then
begin
WhyNot := 'Last block has a long time ago... ' + inttostr(unixtimediff);
exit;
end;
Result := true;
end;
function TNode.IsReady(var CurrentProcess: AnsiString): Boolean;
begin
Result := false;
CurrentProcess := '';
if FBank.IsReady(CurrentProcess) then
begin
if FNetServer.Active then
begin
if TNetData.NetData.IsGettingNewBlockChainFromClient then
begin
CurrentProcess := 'Obtaining valid BlockChain - Found block ' + inttostr(TNetData.NetData.MaxRemoteOperationBlock.block);
end else
begin
if TNetData.NetData.MaxRemoteOperationBlock.block > FOperations.OperationBlock.block then
begin
CurrentProcess := 'Found block ' + inttostr(TNetData.NetData.MaxRemoteOperationBlock.block) + ' (Wait until downloaded)';
end else
begin
Result := true;
end;
end;
end else
begin
CurrentProcess := 'Server not active';
end;
end;
end;
function TNode.NetServer: TNetServer;
begin
Result := FNetServer;
end;
class function TNode.Node: TNode;
begin
if not assigned(_Node) then
_Node := TNode.Create(Nil);
Result := _Node;
end;
procedure TNode.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
end;
procedure TNode.NotifyBlocksChanged;
var i : Integer;
begin
for i := 0 to FNotifyList.Count-1 do
begin
TNodeNotifyEvents( FNotifyList[i] ).NotifyBlocksChanged;
end;
end;
procedure TNode.GetStoredOperationsFromAccount(const OperationsResume: TOperationsResumeList; account_number: Cardinal; MaxDepth, MaxOperations: Integer);
procedure DoGetFromBlock(block_number : Cardinal; last_balance : Int64; act_depth : Integer);
var
opc : TPCOperationsComp;
op : TPCOperation;
OPR : TOperationResume;
l : TList;
i : Integer;
next_block_number : Cardinal;
begin
if (act_depth <= 0) or ((block_number <= 0) and (block_number > 0)) then
exit;
opc := TPCOperationsComp.Create(Nil);
try
if not Bank.Storage.LoadBlockChainBlock(opc, block_number) then
begin
TLog.NewLog(lterror, ClassName, 'Error searching for block ' + inttostr(block_number));
exit;
end;
l := TList.Create;
try
next_block_number := 0;
opc.OperationsHashTree.GetOperationsAffectingAccount(account_number, l);
for i := l.Count - 1 downto 0 do
begin
op := opc.Operation[PtrInt(l.Items[i])];
if (i = 0) then
begin
if op.SenderAccount = account_number then
next_block_number := op.Previous_Sender_updated_block
else
next_block_number := op.Previous_Destination_updated_block;
end;
if TPCOperation.OperationToOperationResume(block_number, Op, account_number, OPR) then
begin
OPR.NOpInsideBlock := Op.tag; // Note: Used Op.tag to include operation index inside a list
OPR.time := opc.OperationBlock.timestamp;
OPR.Block := block_number;
OPR.Balance := last_balance;
last_balance := last_balance - ( OPR.Amount + OPR.Fee );
OperationsResume.Add(OPR);
end;
end;
// Is a new block operation?
if (TAccountComp.AccountBlock(account_number) = block_number) and ((account_number mod CT_AccountsPerBlock) = 0) then
begin
OPR := CT_TOperationResume_NUL;
OPR.valid := true;
OPR.Block := block_number;
OPR.time := opc.OperationBlock.timestamp;
OPR.AffectedAccount := account_number;
OPR.Amount := opc.OperationBlock.reward;
OPR.Fee := opc.OperationBlock.fee;
OPR.Balance := last_balance;
OPR.OperationTxt := 'Blockchain reward';
OperationsResume.Add(OPR);
end;
//
opc.Clear(true);
if (next_block_number >= 0) and (next_block_number < block_number) and (act_depth > 0)
and (next_block_number >= (account_number div CT_AccountsPerBlock))
and ((OperationsResume.Count < MaxOperations) or (MaxOperations <= 0))
then
DoGetFromBlock(next_block_number, last_balance, act_depth-1);
finally
l.Free;
end;
finally
opc.Free;
end;
end;
var acc : TAccount;
begin
if MaxDepth < 0 then
exit;
if account_number >= Bank.SafeBox.AccountsCount then
exit;
acc := Bank.SafeBox.Account(account_number);
if (acc.updated_block > 0) or (acc.account = 0) then
DoGetFromBlock(acc.updated_block, acc.balance, MaxDepth);
end;
function TNode.FindOperation(const OperationComp: TPCOperationsComp;
const OperationHash: TRawBytes; var block: Cardinal;
var operation_block_index: Integer): Boolean;
{ With a OperationHash, search it }
var
account, n_operation : Cardinal;
i : Integer;
op : TPCOperation;
initial_block, aux_block : Cardinal;
begin
Result := False;
// Decode OperationHash
if not TPCOperation.DecodeOperationHash(OperationHash, block, account, n_operation) then
exit;
initial_block := block;
//
if (account >= Bank.AccountsCount) then
exit; // Invalid account number
// if block = 0 then we must search in pending operations first
if (block = 0) then
begin
FOperations.Lock;
try
for i := 0 to FOperations.Count-1 do
begin
if (FOperations.Operation[i].SenderAccount = account) then
begin
if (TPCOperation.OperationHash(FOperations.Operation[i], 0) = OperationHash) then
begin
operation_block_index := i;
OperationComp.CopyFrom(FOperations);
Result := true;
exit;
end;
end;
end;
finally
FOperations.Unlock;
end;
// block = 0 and not found... start searching at block updated by account updated_block
block := Bank.SafeBox.Account(account).updated_block;
if Bank.SafeBox.Account(account).n_operation < n_operation then
exit; // n_operation is greater than found in safebox
end;
if (block = 0) or (block >= Bank.BlocksCount) then
exit;
// Search in previous blocks
while (not Result) and (block > 0) do
begin
aux_block := block;
if not Bank.LoadOperations(OperationComp, block) then
exit;
for i := OperationComp.Count-1 downto 0 do
begin
op := OperationComp.Operation[i];
if (op.SenderAccount = account) then
begin
if (op.N_Operation < n_operation) then
exit; // n_operation is greaten than found
if (op.N_Operation = n_operation) then
begin
// Possible candidate or dead
if TPCOperation.OperationHash(op, initial_block) = OperationHash then
begin
operation_block_index := i;
Result := true;
exit;
end
else
exit; // not found!
end;
if op.Previous_Sender_updated_block > block then
exit;
block := op.Previous_Sender_updated_block;
end;
end;
if (block >= aux_block) then
exit; // Error... not found a valid block positioning
if (initial_block <> 0) then
exit; // if not found in specified block, no valid hash
end;
end;
procedure TNode.NotifyNetClientMessage(Sender: TNetConnection; const TheMessage: AnsiString);
var
i : Integer;
begin
for i := 0 to FNotifyList.Count-1 do
begin
if Assigned( TNodeNotifyEvents( FNotifyList[i] ).OnNodeMessageEvent) then
begin
TNodeNotifyEvents( FNotifyList[i] ).FMessages.AddObject(TheMessage, Sender);
end;
end;
end;
procedure TNode.OnBankNewBlock(Sender: TObject);
begin
FOperations.SanitizeOperations;
end;
function TNode.SendNodeMessage(Target: TNetConnection; TheMessage: AnsiString; var errors: AnsiString): Boolean;
var
i, j : Integer;
nc : TNetConnection;
s : String;
begin
Result := false;
if not TPCThread.TryProtectEnterCriticalSection(Self, 4000, FLockNodeOperations) then
begin
s := 'Cannot Send node message due blocking lock operations node';
TLog.NewLog(lterror, Classname, s);
if TThread.CurrentThread.ThreadID = MainThreadID then
raise Exception.Create(s)
else
exit;
end;
try
errors := '';
if assigned(Target) then
begin
Target.Send_Message(TheMessage);
end else
begin
j := TNetData.NetData.ConnectionsCountAll;
for i := 0 to j-1 do
begin
if TNetData.NetData.GetConnection(i, nc) then
begin
if TNetData.NetData.ConnectionLock(Self, nc, 500) then
begin
try
nc.Send_Message(TheMessage);
finally
TNetData.NetData.ConnectionUnlock(nc)
end;
end;
end;
end;
end;
result := true;
finally
FLockNodeOperations.Release;
end;
end;
procedure TNode.SetNodeLogFilename(const Value: AnsiString);
begin
FNodeLog.FileName := Value;
end;
{ TNodeNotifyEvents }
constructor TNodeNotifyEvents.Create(AOwner: TComponent);
begin
inherited;
FOnOperationsChanged := nil;
FOnBlocksChanged := nil;
FOnNodeMessageEvent := nil;
FMessages := TStringList.Create;
FPendingNotificationsList := TPCThreadList.Create('TNodeNotifyEvents_PendingNotificationsList');
FThreadSafeNodeNotifyEvent := TThreadSafeNodeNotifyEvent.Create(Self);
FThreadSafeNodeNotifyEvent.FreeOnTerminate := true; // This is to prevent locking when freeing component
Node := _Node;
end;
destructor TNodeNotifyEvents.Destroy;
begin
if Assigned(FNode) then
FNode.FNotifyList.Remove(Self);
FThreadSafeNodeNotifyEvent.FNodeNotifyEvents := nil;
FThreadSafeNodeNotifyEvent.Terminate;
FreeAndNil(FPendingNotificationsList);
FreeAndNil(FMessages);
inherited;
end;
procedure TNodeNotifyEvents.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opremove) then
begin
if AComponent = FNode then
FNode := nil;
end;
end;
procedure TNodeNotifyEvents.NotifyBlocksChanged;
begin
if Assigned(FThreadSafeNodeNotifyEvent) then
FThreadSafeNodeNotifyEvent.FNotifyBlocksChanged := true;
end;
procedure TNodeNotifyEvents.NotifyOperationsChanged;
begin
if Assigned(FThreadSafeNodeNotifyEvent) then
FThreadSafeNodeNotifyEvent.FNotifyOperationsChanged := true;
end;
procedure TNodeNotifyEvents.SetNode(const Value: TNode);
begin
if FNode = Value then
exit;
if Assigned(FNode) then
begin
FNode.RemoveFreeNotification(Self);
FNode.FNotifyList.Add(Self);
end;
FNode := Value;
if Assigned(FNode) then
begin
FNode.FreeNotification(Self);
FNode.FNotifyList.Add(Self);
end;
end;
{ TThreadSafeNodeNotifyEvent }
procedure TThreadSafeNodeNotifyEvent.BCExecute;
begin
while (not Terminated) and (Assigned(FNodeNotifyEvents)) do
begin
if (FNotifyOperationsChanged) or (FNotifyBlocksChanged) or (FNodeNotifyEvents.FMessages.Count > 0) then
Synchronize(SynchronizedProcess);
Sleep(100);
end;
end;
constructor TThreadSafeNodeNotifyEvent.Create(ANodeNotifyEvents: TNodeNotifyEvents);
begin
FNodeNotifyEvents := ANodeNotifyEvents;
Inherited Create(false);
end;
procedure TThreadSafeNodeNotifyEvent.SynchronizedProcess;
var i : Integer;
begin
try
if (Terminated) or (not Assigned(FNodeNotifyEvents)) then
exit;
if FNotifyBlocksChanged then
begin
FNotifyBlocksChanged := false;
DebugStep := 'Notify OnBlocksChanged';
if Assigned(FNodeNotifyEvents) and (Assigned(FNodeNotifyEvents.FOnBlocksChanged)) then
FNodeNotifyEvents.FOnBlocksChanged(FNodeNotifyEvents);
end;
if FNotifyOperationsChanged then
begin
FNotifyOperationsChanged := false;
DebugStep := 'Notify OnOperationsChanged';
if Assigned(FNodeNotifyEvents) and (Assigned(FNodeNotifyEvents.FOnOperationsChanged)) then
FNodeNotifyEvents.FOnOperationsChanged(FNodeNotifyEvents);
end;
if FNodeNotifyEvents.FMessages.Count > 0 then
begin
DebugStep := 'Notify OnNodeMessageEvent';
if Assigned(FNodeNotifyEvents) and (Assigned(FNodeNotifyEvents.FOnNodeMessageEvent)) then
begin
for i := 0 to FNodeNotifyEvents.FMessages.Count - 1 do
begin
DebugStep := 'Notify OnNodeMessageEvent ' + inttostr(i + 1) + '/' + inttostr(FNodeNotifyEvents.FMessages.Count);
FNodeNotifyEvents.FOnNodeMessageEvent(TNetConnection(FNodeNotifyEvents.FMessages.Objects[i]), FNodeNotifyEvents.FMessages.Strings[i]);
end;
end;
FNodeNotifyEvents.FMessages.Clear;
end;
except
on E:Exception do
begin
TLog.NewLog(lterror, ClassName, 'Exception inside a Synchronized process: ' + E.ClassName + ':' + E.Message + ' Step:' + DebugStep);
end;
end;
end;
{ TThreadNodeNotifyNewBlock }
constructor TThreadNodeNotifyNewBlock.Create(NetConnection: TNetConnection);
begin
FNetConnection := NetConnection;
inherited Create(false);
FreeOnTerminate := true;
end;
procedure TThreadNodeNotifyNewBlock.BCExecute;
begin
if TNetData.NetData.ConnectionLock(Self, FNetConnection, 500) then
begin
try
if not FNetConnection.Connected then
exit;
TLog.NewLog(ltdebug, ClassName, 'Sending new block found to ' + FNetConnection.Client.ClientRemoteAddr);
FNetConnection.Send_NewBlockFound;
if TNode.Node.Operations.OperationsHashTree.OperationsCount > 0 then
begin
TLog.NewLog(ltdebug, ClassName, 'Sending ' + inttostr(TNode.Node.Operations.OperationsHashTree.OperationsCount) + ' sanitized operations to ' + FNetConnection.ClientRemoteAddr);
FNetConnection.Send_AddOperations(TNode.Node.Operations.OperationsHashTree);
end;
finally
TNetData.NetData.ConnectionUnlock(FNetConnection);
end;
end;
end;
{ TThreadNodeNotifyOperations }
constructor TThreadNodeNotifyOperations.Create(NetConnection: TNetConnection;
MakeACopyOfOperationsHashTree: TOperationsHashTree);
begin
FOperationsHashTree := TOperationsHashTree.Create;
FOperationsHashTree.CopyFromHashTree(MakeACopyOfOperationsHashTree);
FNetConnection := NetConnection;
Inherited Create(false);
FreeOnTerminate := true;
end;
destructor TThreadNodeNotifyOperations.Destroy;
begin
FreeAndNil(FOperationsHashTree);
inherited;
end;
procedure TThreadNodeNotifyOperations.BCExecute;
begin
if TNetData.NetData.ConnectionLock(Self, FNetConnection, 500) then
begin
try
if FOperationsHashTree.OperationsCount <= 0 then
exit;
if not FNetconnection.Connected then
exit;
TLog.NewLog(ltdebug, ClassName, 'Sending ' + inttostr(FOperationsHashTree.OperationsCount) + ' Operations to ' + FNetConnection.ClientRemoteAddr);
FNetConnection.Send_AddOperations(FOperationsHashTree);
finally
TNetData.NetData.ConnectionUnlock(FNetConnection);
end;
end;
end;
initialization
_Node := nil;
finalization
FreeAndNil(_Node);
end.
|
unit TestCalcUnit;
interface
uses
DUnitX.TestFramework, CalcUnit;
type
[TestFixture]
TestTCalc = class(TObject)
strict private
aTCalc: TCalc;
R: Real;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[TestCase('TesteSoma1','8,2,10')]
[TestCase('TesteSoma2','5,5,10')]
[TestCase('TesteSoma3','4,2,6')]
[TestCase('TesteSoma4','8000,2,8002')]
[TestCase('TesteSoma5','1,10000,10001')]
procedure TesteSoma(Value1, Value2, _Result: Real);
[TestCase('TesteSubtracao1','3,4,-1')]
[TestCase('TesteSubtracao2','5,4,1')]
[TestCase('TesteSubtracao3','100,90,10')]
[TestCase('TesteSubtracao4','100,80,20')]
procedure TesteSubtracao(Value1, Value2, _Result: Real);
[TestCase('TesteMultiplicacao1','3,4,12')]
[TestCase('TesteMultiplicacao2','5,4,20')]
[TestCase('TesteMultiplicacao3','100,90,9000')]
[TestCase('TesteMultiplicacao4','-1,8,-8')]
procedure TesteMultiplicacao(Value1, Value2, _Result: Real);
[TestCase('TesteDivisao1','3,0,0')]
[TestCase('TesteDivisao2','5,4,1.25')]
[TestCase('TesteDivisao3','100,90,1.11')]
[TestCase('TesteDivisao4','80,100,0.80')]
procedure TesteDivisao(Value1, Value2, _Result: Real);
end;
implementation
procedure TestTCalc.Setup;
begin
aTCalc := TCalc.Create;
end;
procedure TestTCalc.TearDown;
begin
aTCalc := nil;
end;
procedure TestTCalc.TesteSoma(Value1, Value2, _Result: Real);
begin
R := aTCalc.Adicao(Value1, Value2);
Assert.AreEqual(R, _Result);
end;
procedure TestTCalc.TesteSubtracao(Value1, Value2, _Result: Real);
begin
R := aTCalc.Subtracao(Value1, Value2);
Assert.AreEqual(R, _Result);
end;
procedure TestTCalc.TesteMultiplicacao(Value1, Value2, _Result: Real);
begin
R := aTCalc.Multiplicacao(Value1, Value2);
Assert.AreEqual(R, _Result);
end;
procedure TestTCalc.TesteDivisao(Value1, Value2, _Result: Real);
begin
R := aTCalc.Divisao(Value1, Value2);
Assert.AreEqual(R, _Result);
end;
initialization
TDUnitX.RegisterTestFixture(TestTCalc);
end.
|
unit Grijjy.OpenSSL;
{ OpenSSL handler for Grijjy connections }
{$I Grijjy.inc}
interface
uses
System.SysUtils,
Grijjy.OpenSSL.API,
Grijjy.MemoryPool;
const
DEFAULT_BLOCK_SIZE = 4096;
type
{ Callback events }
TgoOpenSSLNotify = procedure of object;
TgoOpenSSLData = procedure(const ABuffer: Pointer; const ASize: Integer) of object;
{ OpenSSL handler instance }
TgoOpenSSL = class(TObject)
protected
FOnConnected: TgoOpenSSLNotify;
FOnRead: TgoOpenSSLData;
FOnWrite: TgoOpenSSLData;
private
{ OpenSSL related objects }
FHandshaking: Boolean;
FSSLContext: PSSL_CTX;
FSSL: PSSL;
FBIORead: PBIO;
FBIOWrite: PBIO;
FSSLWriteBuffer: Pointer;
FSSLReadBuffer: Pointer;
{ Certificate and Private Key }
FCertificate: TBytes;
FPrivateKey: TBytes;
FPassword: UnicodeString;
public
constructor Create;
destructor Destroy; override;
public
{ Start SSL connect handshake }
function Connect(const AALPN: Boolean = False): Boolean;
{ Free SSL related objects }
procedure Release;
{ Do SSL read from socket }
procedure Read(const ABuffer: Pointer = nil; const ASize: Integer = 0);
{ Do SSL write to socket }
function Write(const ABuffer: Pointer; const ASize: Integer): Boolean;
{ Returns True if ALPN is negotiated }
function ALPN: Boolean;
public
{ Certificate in PEM format }
property Certificate: TBytes read FCertificate write FCertificate;
{ Private key in PEM format }
property PrivateKey: TBytes read FPrivateKey write FPrivateKey;
{ Password for private key }
property Password: UnicodeString read FPassword write FPassword;
public
{ Fired when the SSL connection is established }
property OnConnected: TgoOpenSSLNotify read FOnConnected write FOnConnected;
{ Fired when decrypted SSL data is ready to be read }
property OnRead: TgoOpenSSLData read FOnRead write FOnRead;
{ Fired when encrypted SSL data is ready to be sent }
property OnWrite: TgoOpenSSLData read FOnWrite write FOnWrite;
end;
implementation
var
_MemBufferPool: TgoMemoryPool;
{ TgoOpenSSL }
constructor TgoOpenSSL.Create;
begin
inherited Create;
FHandshaking := False;
FSSL := nil;
FSSLContext := nil;
FSSLWriteBuffer := nil;
FSSLReadBuffer := nil;
end;
destructor TgoOpenSSL.Destroy;
begin
Release;
ERR_remove_thread_state(0);
inherited Destroy;
end;
function TgoOpenSSL.Connect(const AALPN: Boolean): Boolean;
begin
Result := False;
{ create ssl context }
FSSLContext := SSL_CTX_new(SSLv23_method);
if FSSLContext <> nil then
begin
{ if we are connecting using the http2 protocol and TLS }
if AALPN then
begin
{ force TLS 1.2 }
SSL_CTX_set_options(FSSLContext,
SSL_OP_ALL + SSL_OP_NO_SSLv2 + SSL_OP_NO_SSLv3 + SSL_OP_NO_COMPRESSION);
{ enable Application-Layer Protocol Negotiation Extension }
SSL_CTX_set_alpn_protos(FSSLContext, #2'h2', 3);
end;
{ no certificate validation }
SSL_CTX_set_verify(FSSLContext, SSL_VERIFY_NONE, nil);
{ apply PEM Certificate }
if FCertificate <> nil then
begin
if FPrivateKey = nil then
TgoSSLHelper.SetCertificate(FSSLContext, FCertificate, FCertificate, FPassword)
else
TgoSSLHelper.SetCertificate(FSSLContext, FCertificate, FPrivateKey, FPassword);
{ Example loading certificate directly from a file:
S := ExtractFilePath(ParamStr(0)) + 'Grijjy.pem';
SSL_CTX_use_certificate_file(FSSLContext, PAnsiChar(S), 1);
SSL_CTX_use_RSAPrivateKey_file(FSSLContext, PAnsiChar(S), 1);
}
{ Example loading CA certificate directly from a file:
SSL_CTX_load_verify_locations(FSSLContext, 'entrust_2048_ca.cer', nil);
}
{ Example loading CA certificate into memory:
X509_Store := SSL_CTX_get_cert_store(FSSLContext);
ABIO := BIO_new(BIO_s_file);
BIO_read_filename(ABIO, PAnsiChar(AFile));
ACert := PEM_read_bio_X509(ABIO, nil, nil, nil);
X509_STORE_add_cert(X509_Store, ACert); }
end;
{ create an SSL struct for the connection }
FSSL := SSL_new(FSSLContext);
if FSSL <> nil then
begin
{ create the read and write BIO }
FBIORead := BIO_new(BIO_s_mem);
if FBIORead <> nil then
begin
FBIOWrite := BIO_new(BIO_s_mem);
if FBIOWrite <> nil then
begin
FHandshaking := True;
{ relate the BIO to the SSL object }
SSL_set_bio(FSSL, FBIORead, FBIOWrite);
{ ssl session should start the negotiation }
SSL_set_connect_state(FSSL);
{ allocate buffers }
FSSLWriteBuffer :=_MemBufferPool.RequestMem;
FSSLReadBuffer :=_MemBufferPool.RequestMem;
{ start ssl handshake sequence }
Read;
{ SSL success }
Result := True;
end;
end;
end;
end;
end;
procedure TgoOpenSSL.Release;
begin
{ free handle }
if FSSL <> nil then
begin
SSL_shutdown(FSSL);
SSL_free(FSSL);
FSSL := nil;
end;
{ free context }
if FSSLContext <> nil then
begin
SSL_CTX_free(FSSLContext);
FSSLContext := nil;
end;
{ release buffers }
if FSSLWriteBuffer <> nil then
begin
_MemBufferPool.ReleaseMem(FSSLWriteBuffer);
FSSLWriteBuffer := nil;
end;
if FSSLReadBuffer <> nil then
begin
_MemBufferPool.ReleaseMem(FSSLReadBuffer);
FSSLReadBuffer := nil;
end;
end;
procedure TgoOpenSSL.Read(const ABuffer: Pointer; const ASize: Integer);
var
Bytes: Integer;
Error: Integer;
begin
while True do
begin
BIO_write(FBIORead, ABuffer, ASize);
if not BIO_should_retry(FBIORead) then
Break;
end;
while True do
begin
Bytes := SSL_read(FSSL, FSSLReadBuffer, DEFAULT_BLOCK_SIZE);
if Bytes > 0 then
begin
if Assigned(FOnRead) then
FOnRead(FSSLReadBuffer, Bytes)
end
else
begin
Error := SSL_get_error(FSSL, Bytes);
if not ssl_is_fatal_error(Error) then
Break
else
Exit;
end;
end;
{ handshake data needs to be written? }
if BIO_pending(FBIOWrite) <> 0 then
begin
Bytes := BIO_read(FBIOWrite, FSSLWriteBuffer, DEFAULT_BLOCK_SIZE);
if Bytes > 0 then
begin
if Assigned(FOnWrite) then
FOnWrite(FSSLWriteBuffer, Bytes);
end
else
begin
Error := SSL_get_error(FSSL, Bytes);
if ssl_is_fatal_error(Error) then
Exit;
end;
end;
{ with ssl we are only connected and can write once the handshake is finished }
if FHandshaking then
if SSL_is_init_finished(FSSL) then
begin
FHandshaking := False;
if Assigned(FOnConnected) then
FOnConnected;
end
end;
function TgoOpenSSL.Write(const ABuffer: Pointer; const ASize: Integer): Boolean;
var
Bytes: Integer;
Error: Integer;
begin
Result := False;
Bytes := SSL_write(FSSL, ABuffer, ASize);
if Bytes <> ASize then
begin
Error := SSL_get_error(FSSL, Bytes);
if ssl_is_fatal_error(Error) then
Exit;
end;
while BIO_pending(FBIOWrite) <> 0 do
begin
Bytes := BIO_read(FBIOWrite, FSSLWriteBuffer, DEFAULT_BLOCK_SIZE);
if Bytes > 0 then
begin
Result := True;
if Assigned(FOnWrite) then
FOnWrite(FSSLWriteBuffer, Bytes);
end
else
begin
Error := SSL_get_error(FSSL, Bytes);
if ssl_is_fatal_error(Error) then
Exit;
end;
end;
end;
function TgoOpenSSL.ALPN: Boolean;
var
ALPN: MarshaledAString;
ALPNLen: Integer;
begin
SSL_get0_alpn_selected(FSSL, ALPN, ALPNLen);
Result := (ALPNLen = 2) and (ALPN[0] = 'h') and (ALPN[1] = '2');
end;
initialization
TgoSSLHelper.LoadSSL;
SSL_load_error_strings;
SSL_library_init;
_MemBufferPool := TgoMemoryPool.Create(DEFAULT_BLOCK_SIZE);
finalization
TgoSSLHelper.UnloadSSL;
_MemBufferPool.Free;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [PCP_SERVICO]
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
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit PcpServicoVO;
{$mode objfpc}{$H+}
interface
uses
VO, PcpServicoColaboradorVO, PcpServicoEquipamentoVO, Classes, SysUtils, FGL;
type
TPcpServicoVO = class(TVO)
private
FID: Integer;
FID_PCP_OP_DETALHE: Integer;
FINICIO_REALIZADO: TDateTime;
FTERMINO_REALIZADO: TDateTime;
FHORAS_REALIZADO: Integer;
FMINUTOS_REALIZADO: Integer;
FSEGUNDOS_REALIZADO: Integer;
FCUSTO_REALIZADO: Extended;
FINICIO_PREVISTO: TDateTime;
FTERMINO_PREVISTO: TDateTime;
FHORAS_PREVISTO: Integer;
FMINUTOS_PREVISTO: Integer;
FSEGUNDOS_PREVISTO: Integer;
FCUSTO_PREVISTO: Extended;
FListaPcpServicoColaboradorVO: TListaPcpServicoColaboradorVO;
FListaPcpServicoEquipamentoVO: TListaPcpServicoEquipamentoVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdPcpOpDetalhe: Integer read FID_PCP_OP_DETALHE write FID_PCP_OP_DETALHE;
property InicioRealizado: TDateTime read FINICIO_REALIZADO write FINICIO_REALIZADO;
property TerminoRealizado: TDateTime read FTERMINO_REALIZADO write FTERMINO_REALIZADO;
property HorasRealizado: Integer read FHORAS_REALIZADO write FHORAS_REALIZADO;
property MinutosRealizado: Integer read FMINUTOS_REALIZADO write FMINUTOS_REALIZADO;
property SegundosRealizado: Integer read FSEGUNDOS_REALIZADO write FSEGUNDOS_REALIZADO;
property CustoRealizado: Extended read FCUSTO_REALIZADO write FCUSTO_REALIZADO;
property InicioPrevisto: TDateTime read FINICIO_PREVISTO write FINICIO_PREVISTO;
property TerminoPrevisto: TDateTime read FTERMINO_PREVISTO write FTERMINO_PREVISTO;
property HorasPrevisto: Integer read FHORAS_PREVISTO write FHORAS_PREVISTO;
property MinutosPrevisto: Integer read FMINUTOS_PREVISTO write FMINUTOS_PREVISTO;
property SegundosPrevisto: Integer read FSEGUNDOS_PREVISTO write FSEGUNDOS_PREVISTO;
property CustoPrevisto: Extended read FCUSTO_PREVISTO write FCUSTO_PREVISTO;
property ListaPcpColabradorVO: TListaPcpServicoColaboradorVO read FListaPcpServicoColaboradorVO write FListaPcpServicoColaboradorVO;
property ListaPcpServicoEquipamentoVO: TListaPcpServicoEquipamentoVO read FListaPcpServicoEquipamentoVO write FListaPcpServicoEquipamentoVO;
end;
TListaPcpServicoVO = specialize TFPGObjectList<TPcpServicoVO>;
implementation
{ TPcpServicoVO }
constructor TPcpServicoVO.Create;
begin
inherited;
FListaPcpServicoColaboradorVO := TListaPcpServicoColaboradorVO.Create;
FListaPcpServicoEquipamentoVO := TListaPcpServicoEquipamentoVO.Create;
end;
destructor TPcpServicoVO.Destroy;
begin
if Assigned(FListaPcpServicoColaboradorVO) then
FreeAndNil(FListaPcpServicoColaboradorVO);
if Assigned(FListaPcpServicoEquipamentoVO) then
FreeAndNil(FListaPcpServicoEquipamentoVO);
inherited;
end;
initialization
Classes.RegisterClass(TPcpServicoVO);
finalization
Classes.UnRegisterClass(TPcpServicoVO);
end.
|
unit uPIOptionInterfase;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, cxContainer, cxEdit, cxRadioGroup, StdCtrls,
cxLookAndFeelPainters, cxButtons, ActnList, cxLabel;
type
TFormOptionInterfase = class(TForm)
ActionListKlassSpravEdit: TActionList;
ActionOK: TAction;
ActionCansel: TAction;
cxButtonOK: TcxButton;
cxButtonCansel: TcxButton;
GroupBoxMova: TGroupBox;
cxRadioButtonRus: TcxRadioButton;
cxRadioButtonUkr: TcxRadioButton;
GroupBoxColorShem: TGroupBox;
cxRadioButtonBlue: TcxRadioButton;
cxRadioButtonYellow: TcxRadioButton;
cxLabelMustOverload: TcxLabel;
procedure ActionOKExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ActionCanselExecute(Sender: TObject);
private
IndLang: Integer;
procedure InicCaption;
public
{ Public declarations }
end;
var
FormOptionInterfase: TFormOptionInterfase;
implementation
uses registry,uPI_Resources,uPI_Constants;
{$R *.dfm}
procedure TFormOptionInterfase.FormCreate(Sender: TObject);
begin
IndLang:=SelectLanguage;
case IndLang of
0: cxRadioButtonUkr.Checked:=true;
1: cxRadioButtonRus.Checked:=true;
end;
case SelectShemaColor of
0: cxRadioButtonYellow.Checked:=true;
1: cxRadioButtonBlue.Checked:=true;
end;
InicCaption;
end;
procedure TFormOptionInterfase.InicCaption;
begin
TFormOptionInterfase(self).Caption:= nFormOptionInterfase_Caption[IndLang];
cxLabelMustOverload.Caption :=ncxLabelMustOverload[IndLang];
GroupBoxMova.Caption :=nGroupBoxMova[IndLang];
GroupBoxColorShem.Caption :=nGroupBoxColorShem[IndLang];
cxRadioButtonUkr.Caption :=ncxRadioButtonUkr[IndLang];
cxRadioButtonRus.Caption :=ncxRadioButtonRus[IndLang];
cxRadioButtonYellow.Caption :=ncxRadioButtonYellow[IndLang];
cxRadioButtonBlue.Caption :=ncxRadioButtonBlue[IndLang];
//ActionOK.Caption :=nActiont_OK[IndLang];
//ActionCansel.Caption :=nActiont_Cansel[IndLang];
//ActionOK.Hint :=nHintActiont_OK[IndLang];
// ActionCansel.Hint :=nHintActiont_Cansel[IndLang];
end;
procedure TFormOptionInterfase.ActionOKExecute(Sender: TObject);
var
reg: TRegistry;
Languegies, ShemaColor: Integer;
begin
if cxRadioButtonRus.Checked=true
then Languegies:=1
else Languegies:=0;
if cxRadioButtonBlue.Checked=true
then ShemaColor:=1
else ShemaColor:=0;
reg:=TRegistry.Create;
try
reg.RootKey :=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\PI\Languages\',true) then
begin
reg.WriteInteger('Index', Languegies);
end;
finally
reg.Free;
end;
reg:=TRegistry.Create;
try
reg.RootKey :=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\PI\ShemaColor\',true) then
begin
reg.WriteInteger('Color', ShemaColor);
end;
finally
reg.Free;
end;
close;
end;
procedure TFormOptionInterfase.ActionCanselExecute(Sender: TObject);
begin
close;
end;
end.
|
{
Copyright (c) 2015 by Nikolay Nikolov
Copyright (c) 1998 by Peter Vreman
This is a replacement for GDBCon, implemented on top of GDB/MI,
instead of LibGDB. This allows integration of GDB/MI support in the
text mode IDE.
See the file COPYING.FPC, included in this distribution,
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.
**********************************************************************}
unit gdbmicon;
{$MODE fpc}{$H-}
interface
uses
gdbmiint, gdbmiwrap;
type
TBreakpointFlags = set of (bfTemporary, bfHardware);
TWatchpointType = (wtWrite, wtReadWrite, wtRead);
TGDBController = object(TGDBInterface)
private
procedure RunExecCommand(const Cmd: string);
protected
TBreakNumber,
start_break_number: LongInt;
in_command: LongInt;
procedure CommandBegin(const s: string); virtual;
procedure CommandEnd(const s: string); virtual;
public
constructor Init;
destructor Done;
procedure Command(const s: string);
procedure Reset; virtual;
{ tracing }
procedure StartTrace;
procedure Run; virtual;
procedure TraceStep;
procedure TraceNext;
procedure TraceStepI;
procedure TraceNextI;
procedure Continue; virtual;
procedure UntilReturn; virtual;
function BreakpointInsert(const location: string; BreakpointFlags: TBreakpointFlags): LongInt;
function WatchpointInsert(const location: string; WatchpointType: TWatchpointType): LongInt;
procedure SetTBreak(tbreakstring : string);
procedure Backtrace;
function LoadFile(var fn: string): Boolean;
procedure SetDir(const s: string);
procedure SetArgs(const s: string);
end;
implementation
uses
{$ifdef Windows}
Windebug,
{$endif Windows}
strings;
procedure UnixDir(var s : string);
var i : longint;
begin
for i:=1 to length(s) do
if s[i]='\' then
{$ifdef windows}
{ Don't touch at '\ ' used to escapes spaces in windows file names PM }
if (i=length(s)) or (s[i+1]<>' ') then
{$endif windows}
s[i]:='/';
{$ifdef windows}
{ if we are using cygwin, we need to convert e:\ into /cygdriveprefix/e/ PM }
if using_cygwin_gdb and (length(s)>2) and (s[2]=':') and (s[3]='/') then
s:=CygDrivePrefix+'/'+s[1]+copy(s,3,length(s));
{$endif windows}
end;
constructor TGDBController.Init;
begin
inherited Init;
end;
destructor TGDBController.Done;
begin
inherited Done;
end;
procedure TGDBController.CommandBegin(const s: string);
begin
end;
procedure TGDBController.Command(const s: string);
begin
Inc(in_command);
CommandBegin(s);
GDBOutputBuf.Reset;
GDBErrorBuf.Reset;
i_gdb_command(s);
CommandEnd(s);
Dec(in_command);
end;
procedure TGDBController.CommandEnd(const s: string);
begin
end;
procedure TGDBController.Reset;
begin
end;
procedure TGDBController.StartTrace;
begin
Command('-break-insert -t PASCALMAIN');
start_break_number := GDB.ResultRecord.Parameters['bkpt'].AsTuple['number'].AsLongInt;
Run;
end;
procedure TGDBController.RunExecCommand(const Cmd: string);
begin
UserScreen;
Command(Cmd);
WaitForProgramStop;
end;
procedure TGDBController.Run;
begin
RunExecCommand('-exec-run');
end;
procedure TGDBController.TraceStep;
begin
RunExecCommand('-exec-step');
end;
procedure TGDBController.TraceNext;
begin
RunExecCommand('-exec-next');
end;
procedure TGDBController.TraceStepI;
begin
RunExecCommand('-exec-step-instruction');
end;
procedure TGDBController.TraceNextI;
begin
RunExecCommand('-exec-next-instruction');
end;
procedure TGDBController.Continue;
begin
RunExecCommand('-exec-continue');
end;
procedure TGDBController.UntilReturn;
begin
RunExecCommand('-exec-finish');
end;
function TGDBController.BreakpointInsert(const location: string; BreakpointFlags: TBreakpointFlags): LongInt;
var
Options: string = '';
begin
if bfTemporary in BreakpointFlags then
Options := Options + '-t ';
if bfHardware in BreakpointFlags then
Options := Options + '-h ';
Command('-break-insert ' + Options + location);
if GDB.ResultRecord.Success then
BreakpointInsert := GDB.ResultRecord.Parameters['bkpt'].AsTuple['number'].AsLongInt
else
BreakpointInsert := 0;
end;
function TGDBController.WatchpointInsert(const location: string; WatchpointType: TWatchpointType): LongInt;
begin
case WatchpointType of
wtWrite:
Command('-break-watch ' + location);
wtReadWrite:
Command('-break-watch -a ' + location);
wtRead:
Command('-break-watch -r ' + location);
end;
if GDB.ResultRecord.Success then
WatchpointInsert := GDB.ResultRecord.Parameters['wpt'].AsTuple['number'].AsLongInt
else
WatchpointInsert := 0;
end;
procedure TGDBController.SetTBreak(tbreakstring : string);
begin
Command('-break-insert -t ' + tbreakstring);
TBreakNumber := GDB.ResultRecord.Parameters['bkpt'].AsTuple['number'].AsLongInt;
end;
procedure TGDBController.Backtrace;
var
FrameList: TGDBMI_ListValue;
I: LongInt;
begin
{ forget all old frames }
clear_frames;
Command('-stack-list-frames');
if not GDB.ResultRecord.Success then
exit;
FrameList := GDB.ResultRecord.Parameters['stack'].AsList;
frame_count := FrameList.Count;
frames := AllocMem(SizeOf(PFrameEntry) * frame_count);
for I := 0 to frame_count - 1 do
frames[I] := New(PFrameEntry, Init);
for I := 0 to FrameList.Count - 1 do
begin
frames[I]^.address := FrameList.ValueAt[I].AsTuple['addr'].AsPtrInt;
frames[I]^.level := FrameList.ValueAt[I].AsTuple['level'].AsLongInt;
if Assigned(FrameList.ValueAt[I].AsTuple['line']) then
frames[I]^.line_number := FrameList.ValueAt[I].AsTuple['line'].AsLongInt;
if Assigned(FrameList.ValueAt[I].AsTuple['func']) then
frames[I]^.function_name := StrNew(PChar(FrameList.ValueAt[I].AsTuple['func'].AsString));
if Assigned(FrameList.ValueAt[I].AsTuple['fullname']) then
frames[I]^.file_name := StrNew(PChar(FrameList.ValueAt[I].AsTuple['fullname'].AsString));
end;
end;
function TGDBController.LoadFile(var fn: string): Boolean;
var
cmd: string;
begin
getdir(0,cmd);
UnixDir(cmd);
Command('-environment-cd ' + cmd);
GDBOutputBuf.Reset;
GDBErrorBuf.Reset;
UnixDir(fn);
Command('-file-exec-and-symbols ' + fn);
LoadFile := True;
end;
procedure TGDBController.SetDir(const s: string);
var
hs: string;
begin
hs:=s;
UnixDir(hs);
Command('-environment-cd ' + hs);
end;
procedure TGDBController.SetArgs(const s: string);
begin
Command('-exec-arguments ' + s);
end;
end.
|
unit uSisPropertyEditorFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
uParentDialogFrm, DBCtrls, dxCntner, dxTL, dxDBGrid, StdCtrls, Buttons,
ExtCtrls, Db, DBTables, dxDBCtrl, ADODB, siComp, siLangRT;
type
TSisPropertyEditorFrm = class(TParentDialogFrm)
dxDBGrid1: TdxDBGrid;
quProperty: TADOQuery;
quValue: TADOQuery;
dsProperty: TDataSource;
dsValue: TDataSource;
dxDBGrid2: TdxDBGrid;
quPropertyProperty: TStringField;
dxDBGrid2Property: TdxDBGridMaskColumn;
quValuePropertyValue: TStringField;
dxDBGrid1PropertyValue: TdxDBGridMaskColumn;
pnlComando: TPanel;
btRemoveValue: TSpeedButton;
btNewValue: TSpeedButton;
Splitter1: TSplitter;
quValueProperty: TStringField;
Panel1: TPanel;
lblPTituloShadow: TLabel;
lblPTitulo: TLabel;
imgOn: TImage;
btNovaPropriedade: TSpeedButton;
btRemovePropriedade: TSpeedButton;
procedure btNewValueClick(Sender: TObject);
procedure btRemoveValueClick(Sender: TObject);
procedure quValueNewRecord(DataSet: TDataSet);
procedure btCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure quValueAfterPost(DataSet: TDataSet);
procedure dsValueDataChange(Sender: TObject; Field: TField);
procedure btNovaPropriedadeClick(Sender: TObject);
procedure btRemovePropriedadeClick(Sender: TObject);
private
{ Private declarations }
sEnter,
sProperty : String;
public
{ Public declarations }
end;
implementation
uses uDM, uMsgBox, uSisMain, uMsgConstant, uDMGlobal;
{$R *.DFM}
procedure TSisPropertyEditorFrm.btNewValueClick(Sender: TObject);
begin
inherited;
with quValue do
begin
if (State in dsEditModes) then
if(quValuePropertyValue.AsString <> '') then
Post
else
Cancel;
Append;
end;
end;
procedure TSisPropertyEditorFrm.btRemoveValueClick(Sender: TObject);
begin
inherited;
if MsgBox(MSG_QST_SURE, vbQuestion + vbYesNo) = vbYes then
quValue.Delete;
end;
procedure TSisPropertyEditorFrm.quValueNewRecord(DataSet: TDataSet);
begin
inherited;
with quValue do
FieldByName('Property').AsString := Parameters.ParamByName('Property').Value;
end;
procedure TSisPropertyEditorFrm.btCancelClick(Sender: TObject);
begin
inherited;
DM.PropertyValuesRefresh;
Close;
end;
procedure TSisPropertyEditorFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
quProperty.Close;
with quValue do
begin
if State in dsEditModes then
Post;
Close;
end;
Action := caFree;
end;
procedure TSisPropertyEditorFrm.FormCreate(Sender: TObject);
begin
inherited;
Self.Caption := Application.Title;
case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sEnter := 'Property editor';
sProperty := 'Enter the name of new property:';
end;
LANG_PORTUGUESE :
begin
sEnter := 'Editor de propriedades';
sProperty := 'Entre com a nova propriedade:';
end;
LANG_SPANISH :
begin
sEnter := 'Editor de propriedades';
sProperty := 'Entre com a nova propriedade:';
end;
end;
end;
procedure TSisPropertyEditorFrm.FormDestroy(Sender: TObject);
begin
inherited;
//quProperty.UnPrepare;
//quValue.UnPrepare;
end;
procedure TSisPropertyEditorFrm.FormShow(Sender: TObject);
begin
inherited;
quProperty.Open;
quValue.Open;
end;
procedure TSisPropertyEditorFrm.quValueAfterPost(DataSet: TDataSet);
var
PropertyValue: String;
begin
inherited;
// Dou o refresh para garantir a ordenação
with quValue do
begin
DisableControls;
PropertyValue := quValuePropertyValue.AsString;
Close;
Open;
Locate('PropertyValue', PropertyValue, []);
EnableControls;
end;
end;
procedure TSisPropertyEditorFrm.dsValueDataChange(Sender: TObject;
Field: TField);
begin
inherited;
btRemoveValue.Enabled := not quValue.IsEmpty;
end;
procedure TSisPropertyEditorFrm.btNovaPropriedadeClick(Sender: TObject);
var
NovaPropriedade: String;
begin
inherited;
// Incluo uma nova propriedade
NovaPropriedade := InputBox(sEnter, sProperty, '');
if NovaPropriedade <> '' then
begin
DM.RunSQL( 'INSERT Sis_PropertyDomain (Property, PropertyValue) ' +
'VALUES (' + #39 + NovaPropriedade + #39 + ', ' +
#39 + 'FirstValue' + #39 + ')');
quProperty.Close;
quProperty.Open;
quValue.Close;
quValue.Open;
end;
end;
procedure TSisPropertyEditorFrm.btRemovePropriedadeClick(Sender: TObject);
begin
inherited;
if MsgBox(MSG_QST_SURE, vbQuestion + vbYesNo) = vbYes then
begin
DM.RunSQL('DELETE Sis_PropertyDomain WHERE Property = ' + #39 + quPropertyProperty.AsString + #39);
quProperty.Close;
quProperty.Open;
quValue.Close;
quValue.Open;
end;
end;
Initialization
RegisterClass(TSisPropertyEditorFrm);
end.
|
unit unAtualizando;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ExtCtrls, StdCtrls;
type
TfrmAtualizando = class(TForm)
ProgressBar1: TProgressBar;
Panel1: TPanel;
Shape1: TShape;
Label1: TLabel;
Image1: TImage;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FMessage: string;
procedure SetMax(const Value: integer);
procedure SetPosition(const Value: integer);
procedure SetMessage(const Value: string);
{ Private declarations }
public
{ Public declarations }
property Max: integer write SetMax;
property Position: integer write SetPosition;
property Message: string read FMessage write SetMessage;
end;
implementation
{$R *.dfm}
procedure TfrmAtualizando.FormCreate(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
Caption := Application.Title;
end;
procedure TfrmAtualizando.FormDestroy(Sender: TObject);
begin
Screen.Cursor := crDefault;
end;
procedure TfrmAtualizando.FormShow(Sender: TObject);
begin
Application.ProcessMessages;
end;
procedure TfrmAtualizando.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmAtualizando.SetMax(const Value: integer);
begin
//Gauge1.MaxValue := Value;
ProgressBar1.Max := Value;
end;
procedure TfrmAtualizando.SetMessage(const Value: string);
begin
FMessage := Value;
Label1.Caption := FMessage;
Application.ProcessMessages;
end;
procedure TfrmAtualizando.SetPosition(const Value: integer);
begin
//Gauge1.Progress := Value;
ProgressBar1.Position := Value;
Application.ProcessMessages;
end;
end.
|
unit Servers;
interface
uses
LrProfiles;
type
TServerTarget = ( stDisk, stFTP );
TServerProfile = class(TLrProfile)
private
FRoot: string;
FHost: string;
FFTPHost: string;
FFTPPassword: string;
FFTPUser: string;
FTarget: TServerTarget;
protected
procedure SetFTPHost(const Value: string);
procedure SetFTPPassword(const Value: string);
procedure SetFTPUser(const Value: string);
procedure SetHost(const Value: string);
procedure SetRoot(const Value: string);
procedure SetTarget(const Value: TServerTarget);
published
property FTPHost: string read FFTPHost write SetFTPHost;
property FTPUser: string read FFTPUser write SetFTPUser;
property FTPPassword: string read FFTPPassword write SetFTPPassword;
property Host: string read FHost write SetHost;
property Root: string read FRoot write SetRoot;
property Target: TServerTarget read FTarget write SetTarget;
end;
//
TServerProfileMgr = class(TLrProfileMgr)
protected
function GetServers(inIndex: Integer): TServerProfile;
procedure SetServers(inIndex: Integer; const Value: TServerProfile);
public
constructor Create(const inFilename: string = ''); reintroduce;
function AddServer: TServerProfile;
property Servers[inIndex: Integer]: TServerProfile read GetServers write SetServers; default;
end;
implementation
uses
Globals;
{ TServerProfile }
procedure TServerProfile.SetFTPHost(const Value: string);
begin
FFTPHost := Value;
end;
procedure TServerProfile.SetFTPPassword(const Value: string);
begin
FFTPPassword := Value;
end;
procedure TServerProfile.SetFTPUser(const Value: string);
begin
FFTPUser := Value;
end;
procedure TServerProfile.SetHost(const Value: string);
begin
FHost := Value;
end;
procedure TServerProfile.SetRoot(const Value: string);
begin
FRoot := Value;
end;
procedure TServerProfile.SetTarget(const Value: TServerTarget);
begin
FTarget := Value;
end;
{ TServerProfileMgr }
constructor TServerProfileMgr.Create(const inFilename: string);
begin
inherited Create(TServerProfile, inFilename);
end;
function TServerProfileMgr.GetServers(inIndex: Integer): TServerProfile;
begin
Result := TServerProfile(Profiles[inIndex]);
end;
procedure TServerProfileMgr.SetServers(inIndex: Integer;
const Value: TServerProfile);
begin
Profiles[inIndex] := Value;
end;
function TServerProfileMgr.AddServer: TServerProfile;
begin
Result := TServerProfile(Profiles.Add);
end;
end.
|
unit Chapter07._06_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
AI.TreeNode,
DeepStar.Utils;
//235. Lowest Common Ancestor of a Binary Search Tree
//https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
//时间复杂度: O(lgn), 其中n为树的节点个数
//空间复杂度: O(h), 其中h为树的高度
type
TSolution = class(TObject)
public
function lowestCommonAncestor(root, p, q: TTreeNode): TTreeNode;
end;
procedure Main;
implementation
procedure Main;
var
a: TArr_int;
root, p, q, res: TTreeNode;
begin
a := [6, 2, 8, 0, 4, 7, 9, 3, 5];
with TSolution.Create do
begin
root := TTreeNode.Create(a);
p := TTreeNode.Create(2);
q := TTreeNode.Create(8);
res := lowestCommonAncestor(root, p, q);
WriteLn(res.Val);
q.Free;
p.Free;
p := TTreeNode.Create(2);
q := TTreeNode.Create(4);
res := lowestCommonAncestor(root, p, q);
WriteLn(res.Val);
q.Free;
p.Free;
root.ClearAndFree;
Free;
end;
end;
{ TSolution }
function TSolution.lowestCommonAncestor(root, p, q: TTreeNode): TTreeNode;
begin
if (p = nil) or (q = nil) then
raise Exception.Create('p or q can not be null.');
if root = nil then
Exit(nil);
if (p.Val < root.Val) and (q.Val < root.Val) then
Exit(lowestCommonAncestor(root.Left, p, q));
if (p.Val > root.Val) and (q.Val > root.Val) then
Exit(lowestCommonAncestor(root.Right, p, q));
Result := root;
end;
end.
|
unit uIStringConverter;
{$I ..\Include\IntXLib.inc}
interface
uses
uIntX,
uIntXLibTypes;
type
/// <summary>
/// ToString converter class interface.
/// </summary>
IIStringConverter = interface(IInterface)
['{EC961CBB-1DA0-492B-A68F-97D3F1A30484}']
/// <summary>
/// Returns string representation of <see cref="TIntX" /> object in given base.
/// </summary>
/// <param name="IntX">Big integer to convert.</param>
/// <param name="numberBase">Base of system in which to do output.</param>
/// <param name="alphabet">Alphabet which contains chars used to represent big integer, char position is coresponding digit value.</param>
/// <returns>Object string representation.</returns>
function ToString(IntX: TIntX; numberBase: UInt32;
alphabet: TIntXLibCharArray): String; overload;
/// <summary>
/// Converts digits from internal representation into given base.
/// </summary>
/// <param name="digits">Big integer digits.</param>
/// <param name="mlength">Big integer length.</param>
/// <param name="numberBase">Base to use for output.</param>
/// <param name="outputLength">Calculated output length (will be corrected inside).</param>
/// <returns>Conversion result (later will be transformed to string).</returns>
function ToString(digits: TIntXLibUInt32Array; mlength: UInt32;
numberBase: UInt32; var outputLength: UInt32)
: TIntXLibUInt32Array; overload;
end;
implementation
end.
|
unit AStarBlitzCodeH;
//Converted from C to Pascal from:
//===================================================================
//A* Pathfinder (Version 1.71a) by Patrick Lester. Used by permission.
//===================================================================
//http://www.policyalmanac.org/games/aStarTutorial.htm
//A* Pathfinding for Beginners
//some Heuristics and TieBreaker from Amit Patel
interface
uses AStarGlobals,//All data and Init destroy
//Dialogs, // showmessage
//sysutils, // inttostr
forms;//application.ProcessMessages;
Function BlitzFindPathH( pathfinderID, startingX, startingY,
targetX, targetY, mode:Integer):Integer;
implementation
uses AStarBlitzUnit;//for the other procedures
//---------------------------------------------------------------------------
// Name: FindPathH
// Desc: Finds a path using A*
//Added Heuristic Options
//---------------------------------------------------------------------------
Function BlitzFindPathH ( pathfinderID, startingX, startingY,
targetX, targetY, mode:Integer):Integer;
var
dx1,dx2,dy1,dy2,cross,//Tiebreakers
XDistance,YDistance,HDistance, //Heuristic options
startX,startY,x,y,
onOpenList, parentXval, parentYval,
a, b, m, u, v, temp, corner, numberOfOpenListItems,
addedGCost, tempGcost,
//path,//moved to global and made it PathStatus
tempx, pathX, pathY, cellPosition,
newOpenListItemID:Integer;
//13.If there is no path to the selected target, set the pathfinder's
//xPath and yPath equal to its current location
//and return that the path is nonexistent.
procedure noPath;
begin
UnitRecordArray[pathfinderID].xPath := startingX;
UnitRecordArray[pathfinderID].yPath := startingY;
result:= Targetunwalkable;//nonexistent;
end;
Begin
//onOpenList:=0; parentXval:=0; parentYval:=0;
//a:=0; b:=0; m:=0; u:=0; v:=0;
//temp:=0; corner:=0; numberOfOpenListItems:=0;
addedGCost:=0; tempGcost := 0;
// tempx:=0; pathX:=0; pathY:=0; cellPosition:=0;
newOpenListItemID:=0;
//1. Convert location data (in pixels)
//to coordinates in the walkability array.
startX := startingX div ProjectRecord.tileSize;
startY := startingY div ProjectRecord.tileSize;
targetX := targetX div ProjectRecord.tileSize;
targetY := targetY div ProjectRecord.tileSize;
//2.Quick Path Checks: Under the some circumstances no path needs to
// be generated ...
//If starting location and target are in the same location...
if ((startX = targetX) and (startY = targetY)
and (UnitRecordArray[pathfinderID].pathLocation > 0))
then result:= found;
if ((startX = targetX) and (startY = targetY)
and (UnitRecordArray[pathfinderID].pathLocation = 0))
then result:= nonexistent;
//If target square is unwalkable, return that it's a unwalkable path.
if (walkability[targetX][targetY] = unwalkable)then
begin noPath;exit;{current procedure} end;//goto noPath;
//3.Reset some variables that need to be cleared
if (onClosedList > 1000000)then //reset whichList occasionally
begin //Map Width Height has been converted to Global
for x := 0 to mapWidth-1 do
for y := 0 to mapHeight-1 do whichList [x][y] := 0;
onClosedList := 10;
end;
//changing the values of onOpenList and onClosed list
//is faster than redimming whichList() array
onClosedList := onClosedList+2;
onOpenList := onClosedList-1;
UnitRecordArray[pathfinderID].pathLength := notStarted;//i.e, = 0
UnitRecordArray[pathfinderID].pathLocation:= notStarted;//i.e, = 0
Gcost[startX][startY] := 0; //reset starting square's G value to 0
//4.Add the starting location to the open list of squares to be checked.
numberOfOpenListItems := 1;
//assign it as the top (and currently only) item in the open list,
// which is maintained as a binary heap (explained below)
openList[1] := 1;
openX[1] := startX ;
openY[1] := startY;
LostinaLoop:=True;
//5.Do the following until a path is found or deemed nonexistent.
while (LostinaLoop)//Do until path is found or deemed nonexistent
do
begin
Application.ProcessMessages;
// If () then LostinaLoop :=False;
//6.If the open list is not empty, take the first cell off of the list.
//This is the lowest F cost cell on the open list.
if (numberOfOpenListItems <> 0) then
begin
//7. Pop the first item off the open list.
parentXval := openX[openList[1]];
//record cell coordinates of the item
parentYval := openY[openList[1]];
//add the item to the closed list
whichList[parentXval][parentYval] := onClosedList;
//Open List = Binary Heap: Delete this item from the open list, which
//is maintained as a binary heap.
//For more information on binary heaps, see:
//http://www.policyalmanac.org/games/binaryHeaps.htm
//reduce number of open list items by 1
numberOfOpenListItems := numberOfOpenListItems - 1;
//Delete the top item in binary heap and reorder the heap,
//with the lowest F cost item rising to the top.
//move the last item in the heap up to slot #1
openList[1] := openList[numberOfOpenListItems+1];
v := 1;
//Repeat the following until the new item in slot #1
//sinks to its proper spot in the heap.
while LostinaLoop//(not KeyDown(27))//reorder the binary heap
do
begin
Application.ProcessMessages;
u := v;
//if both children exist
if (2*u+1 <= numberOfOpenListItems)then
begin
//Check if the F cost of the parent is greater than each child.
//Select the lowest of the two children.
if (Fcost[openList[u]] >= Fcost[openList[2*u]])then v := 2*u;
if (Fcost[openList[v]] >= Fcost[openList[2*u+1]])then v := 2*u+1;
end
else
begin //if only child #1 exists
if (2*u <= numberOfOpenListItems)then
begin
//Check if the F cost of the parent is greater than child #1
if (Fcost[openList[u]] >= Fcost[openList[2*u]])then
v := 2*u;
end;
end;
//!=
if (u <> v)then //if parent's F is > one of its children, swap them
begin
temp := openList[u];
openList[u] := openList[v];
openList[v] := temp;
end else break; //otherwise, exit loop
end;
//7.Check the adjacent squares. (Its "children" -- these path children
//are similar, conceptually, to the binary heap children mentioned
//above, but don't confuse them. They are different. Path children
//are portrayed in Demo 1 with grey pointers pointing toward
//their parents.) Add these adjacent child squares to the open list
//for later consideration if appropriate (see various if statements
//below).
for b := parentYval-1 to parentYval+1 do
begin
for a := parentXval-1 to parentXval+1do
begin
//If not off the map
//(do this first to avoid array out-of-bounds errors)
if ( (a <> -1) and (b <> -1)
and (a <> mapWidth) and (b <> mapHeight))then
begin
//If not already on the closed list (items on the closed list have
//already been considered and can now be ignored).
if (whichList[a][b] <> onClosedList)then
begin
//If not a wall/obstacle square.
if (walkability [a][b] <> unwalkable) then
begin
//Don't cut across corners
corner := walkable;
if (a = parentXval-1)then
begin
if (b = parentYval-1)then
begin
if ( (walkability[parentXval-1][parentYval] = unwalkable)
or (walkability[parentXval][parentYval-1] = unwalkable))
then corner := unwalkable;
end
else if (b = parentYval+1)then
begin
if ((walkability[parentXval][parentYval+1] = unwalkable)
or (walkability[parentXval-1][parentYval] = unwalkable))
then corner := unwalkable;
end;
end
else if (a = parentXval+1)then
begin
if (b = parentYval-1)then
begin
if ((walkability[parentXval][parentYval-1] = unwalkable)
or (walkability[parentXval+1][parentYval] = unwalkable))
then corner:= unwalkable;
end
else if (b = parentYval+1)then
begin
if ((walkability[parentXval+1][parentYval] = unwalkable)
or (walkability[parentXval][parentYval+1] = unwalkable))
then corner := unwalkable;
end;
end;
if (corner = walkable)then
begin
//If not already on the open list, add it to the open list.
if (whichList[a][b] <> onOpenList)then
begin
//Create a new open list item in the binary heap.
//each new item has a unique ID #
newOpenListItemID := newOpenListItemID + 1;
m := numberOfOpenListItems+1;
//place the new open list item
//(actually, its ID#) at the bottom of the heap
openList[m] := newOpenListItemID;
//record the x and y coordinates of the new item
openX[newOpenListItemID] := a;
openY[newOpenListItemID] := b;
//0.06 7..164 = <10 0.07 = > 10
//Figure out its G cost
if ((abs(a-parentXval) = 1) and (abs(b-parentYval) = 1))
//cost of going to diagonal squares
then addedGCost := 14
//cost of going to non-diagonal squares
else addedGCost := 10;
Gcost[a][b] := Gcost[parentXval][parentYval]
+Trunc((GCostData[a,b] *ProjectRecord.TerrainValueAlphaD))
+ addedGCost;
//Figure out its H and F costs and parent
//If useDijkstras then Hcost[openList[m]] :=0 else
Case UnitRecordArray[pathfinderID].SearchMode of
0:Hcost[openList[m]] :=Trunc(ProjectRecord.AverageTerrainD);//0; //Dijkstra
1://Diagonal
Begin
XDistance:=abs(a - targetX);
YDistance:=abs(b - targetY);
If XDistance > YDistance then
HDistance:=( (14*YDistance) + (10*(XDistance-YDistance)))
else HDistance:=( (14*XDistance) + (10*(YDistance-XDistance)));
Hcost[openList[m]] :=Trunc(HDistance+ProjectRecord.AverageTerrainD);
End;
2: //Manhattan
Hcost[openList[m]] := Trunc(ProjectRecord.AverageTerrainD+
(10*(abs(a - targetX) + abs(b - targetY))));
3: //BestFirst..Overestimated h
Hcost[openList[m]] := Trunc(ProjectRecord.AverageTerrainD+
(10*((a - targetX)*(a - targetX)
+ (b - targetY)*(b - targetY))));
4:
Hcost[openList[m]] := Trunc(ProjectRecord.AverageTerrainD+
(10*SQRT(((a - targetX)*(a - targetX)
+ (b - targetY)*(b - targetY)))));
End;
Case UnitRecordArray[pathfinderID].TieBreakerMode of
0:Fcost[openList[m]] := Gcost[a][b] + Hcost[openList[m]];
1:begin //straight
dx1:=(a - targetX);
dx2:=(b - targetY);
dy1:=(UnitRecordArray[pathfinderID].startXLoc-UnitRecordArray[pathfinderID].targetX);
dy2:=(UnitRecordArray[pathfinderID].startYLoc-UnitRecordArray[pathfinderID].targetY );
cross:=abs((dx1*dy2) - (dx2*dy1));
//Round or Trunc ? //*
Fcost[openList[m]] := Trunc(Gcost[a][b] + Hcost[openList[m]]+(cross/0.001));
end;
2:Fcost[openList[m]] := Trunc(Gcost[a][b] + Hcost[openList[m]]-(0.1*Hcost[openList[m]])); //close
3:Fcost[openList[m]] := Trunc(Gcost[a][b] + Hcost[openList[m]]+(0.1*Hcost[openList[m]])); //far
end;
parentX[a][b] := parentXval ;
parentY[a][b] := parentYval;
//Move the new open list item to the proper place
//in the binary heap. Starting at the bottom,
//successively compare to parent items,
//swapping as needed until
//the item finds its place in the heap
//or bubbles all the way to the top
//(if it has the lowest F cost).
//While item hasn't bubbled to the top (m=1)
while (m <> 1)do
begin
//Check if child's F cost is < parent's F cost.
//If so, swap them.
if (Fcost[openList[m]] <= Fcost[openList[m div 2]])then
begin
temp := openList[m div 2];//[m/2];
openList[m div 2]{[m/2]} := openList[m];
openList[m] := temp;
m := m div 2;//m/2;
end else break;
end;
//add one to the number of items in the heap
numberOfOpenListItems := numberOfOpenListItems+1;
//Change whichList to show
//that the new item is on the open list.
whichList[a][b] := onOpenList;
end
//8.If adjacent cell is already on the open list,
//check to see if this path to that cell
//from the starting location is a better one.
//If so, change the parent of the cell and its G and F costs
else //If whichList(a,b) = onOpenList
begin
//Figure out the G cost of this possible new path
if ((abs(a-parentXval) = 1) and (abs(b-parentYval) = 1))
//cost of going to diagonal tiles
then addedGCost := 14
//cost of going to non-diagonal tiles
else addedGCost := 10; //??add +GCostData[a,b]
tempGcost := Gcost[parentXval][parentYval]+Trunc(GCostData[a,b]*ProjectRecord.TerrainValueAlphaD) + addedGCost;
//If this path is shorter (G cost is lower) then change
//the parent cell, G cost and F cost.
if (tempGcost < Gcost[a][b])then //if G cost is less,
begin //change the square's parent
parentX[a][b] := parentXval;
parentY[a][b] := parentYval;
Gcost[a][b] := tempGcost;//change the G cost
//Because changing the G cost also changes the F cost,
//if the item is on the open list we need to change
//the item's recorded F cost
//and its position on the open list to make
//sure that we maintain a properly ordered open list.
//look for the item in the heap
for x := 1 to numberOfOpenListItems do
begin //item found
if ( (openX[openList[x]] = a)
and (openY[openList[x]] = b))then
begin //change the F cost
Fcost[openList[x]] :=
Gcost[a][b] + Hcost[openList[x]];
//See if changing the F score bubbles the item up
// from it's current location in the heap
m := x;
//While item hasn't bubbled to the top (m=1)
while (m <> 1)do
begin
//Check if child is < parent. If so, swap them.
if (Fcost[openList[m]] < Fcost[openList[m div 2]])
then
begin
temp := openList[m div 2]; //
openList[m div 2] := openList[m]; //m/2
openList[m] := temp;
m := m div 2;
end else break;
end;
break; //exit for x = loop
end; //If openX(openList(x)) = a
end; //For x = 1 To numberOfOpenListItems
end;//If tempGcost < Gcost(a,b)
end;//else If whichList(a,b) = onOpenList
end;//If not cutting a corner
end;//If not a wall/obstacle square.
end;//If not already on the closed list
end;//If not off the map
end;//for (a = parentXval-1; a <= parentXval+1; a++){
end;//for (b = parentYval-1; b <= parentYval+1; b++){
end//if (numberOfOpenListItems != 0)
//9.If open list is empty then there is no path.
else
begin //path
UnitRecordArray[pathfinderID].pathStatus := nonexistent;
break;
end;
//If target is added to open list then path has been found.
if (whichList[targetX][targetY] = onOpenList)then
begin //path
UnitRecordArray[pathfinderID].pathStatus := found;
break;
end;
end;
//10.Save the path if it exists.
if (UnitRecordArray[pathfinderID].pathStatus = found)then
begin
//showmessage('x');
//a.Working backwards from the target to the starting location by checking
//each cell's parent, figure out the length of the path.
pathX := targetX;
pathY := targetY;
{showmessage('targetX '+Inttostr(targetX)+' pathX '+Inttostr(pathX)
+' targety '+Inttostr(targety)+' pathy '+Inttostr(pathy) );}
while ((pathX <> startX) or (pathY <> startY))do
begin
//Look up the parent of the current cell.
tempx := parentX[pathX][pathY];
pathY := parentY[pathX][pathY];
pathX := tempx;
//Figure out the path length
UnitRecordArray[pathfinderID].pathLength := UnitRecordArray[pathfinderID].pathLength + 1;
end;
{;b. Resize the data bank to the right size (leave room to store step 0,
;which requires storing one more step than the length)
ResizeBank unit\pathBank,(unit\pathLength+1)*4}
//b.Resize the data bank to the right size in bytes
{pathBank[pathfinderID] :=
(int* ) realloc (pathBank[pathfinderID],
pathLength[pathfinderID]*8);} //8 ? 4 byte =int ? +1
//pathBank:Array[1..2]of Array of array
setlength(UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank,pathfinderID],(UnitRecordArray[pathfinderID].pathLength)*2);
//c. Now copy the path information over to the databank. Since we are
//working backwards from the target to the start location, we copy
//the information to the data bank in reverse order. The result is
//a properly ordered set of path data, from the first step to the last.
pathX := targetX;
pathY := targetY;
{showmessage('targetX '+Inttostr(targetX)+' pathX '+Inttostr(pathX)
+' targety '+Inttostr(targety)+' pathy '+Inttostr(pathy) );}
//954 478*2=956
cellPosition := ((UnitRecordArray[pathfinderID].pathLength)*2);//start at the end
//showmessage('cellPosition '+Inttostr(cellPosition));
while ((pathX <> startX) or (pathY <> startY))do
begin
cellPosition := cellPosition - 2;//work backwards 2 integers
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID][cellPosition] := pathX;
UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID][cellPosition+1] := pathY;
//d.Look up the parent of the current cell.
tempx := parentX[pathX][pathY];
pathY := parentY[pathX][pathY];
pathX := tempx;
//e.If we have reached the starting square, exit the loop.
end;
//11.Read the first path step into xPath/yPath arrays
//ReadPath(pathfinderID,startingX,startingY,1);
//Rerolled here to avoid a call to other unit
// yPath[pathfinderID] :=tileSize*pathBank[pathfinderID] [pathLocation[pathfinderID]*2-1];
// xPath[pathfinderID] :=tileSize*pathBank[pathfinderID] [pathLocation[pathfinderID]*2-2];
UnitRecordArray[pathfinderID].yPath :=
ProjectRecord.tileSize* UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID] [UnitRecordArray[pathfinderID].pathLocation*2-1];
UnitRecordArray[pathfinderID].xPath :=
ProjectRecord.tileSize*UnitpathBank[UnitRecordArray[pathfinderID].CurrentpathBank][pathfinderID] [UnitRecordArray[pathfinderID].pathLocation*2-2];
end;
result:= UnitRecordArray[pathfinderID].pathStatus;
End;
end.
|
unit Informe_View;
interface
uses
Classes, Controls, Forms, StdCtrls, ExtCtrls, Buttons, ComCtrls,
// EsperePorFavor,
Informe_ViewModel,
Informe_ViewModel_Implementation, Graphics;
type
TfmInforme_View = class(TForm)
pnlGeneral: TPanel;
Bevel2: TBevel;
lbl1: TLabel;
pnlFechas: TPanel;
lblDesdeFecha: TLabel;
lblHastaFecha: TLabel;
edtDesdeFecha: TDateTimePicker;
edtHastaFecha: TDateTimePicker;
pnlOkCancel: TPanel;
imgOK_CC_OkCancelPanel: TImage;
imgCancel_CC_OkCancelPanel: TImage;
btnOk: TBitBtn;
btnCancel: TBitBtn;
procedure btnOkClick(Sender: TObject);
procedure evtRevisarDatos(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
// FormEspera: TfmEsperePorFavor;
fViewModel: TInforme_ViewModel;
ViewModel: TInforme_ViewModel;
procedure CambiosEnViewModel(Sender:TObject);
procedure ActualizarInterface;
procedure TickInforme(Sender:TObject);
end;
procedure Informe(const aDesdeFecha,aHastaFecha:TDateTime;const aNombrePlantilla:string);
implementation
{$R *.DFM}
procedure Informe(const aDesdeFecha,aHastaFecha:TDateTime;const aNombrePlantilla:string);
var
AForm: TfmInforme_View;
begin
Application.CreateForm(TfmInforme_View, AForm);
with AForm do begin
try
ViewModel.TickInforme:=AForm.TickInforme;
ViewModel.Iniciar(CambiosEnViewModel,aDesdeFecha,aHastaFecha,aNombrePlantilla);
RevisarDatos;
AForm.ShowModal;
except
Release;
end
end
end;
procedure TfmInforme_View.btnOkClick(Sender: TObject);
begin
if ViewModel.EmitirInformeOK then begin
// FormEspera:=EsperaComenzarCreate('Calculando Informe...');
try
// FormEspera.AbortableRepetible;
// FormEspera.MostrarModal;
ViewModel.EmitirInforme;
finally
// FormEspera.Terminar;
end;
end;
ModalResult:=mrOK;
end;
procedure TfmInforme_View.evtRevisarDatos(Sender: TObject);
begin
RevisarDatos;
end;
procedure TfmInforme_View.ActualizarInterface;
begin
ViewModel.Actualizar(edtDesdeFecha.Date,edtHastaFecha.Date);
btnOk.Enabled:=ViewModel.EmitirInformeOK;
end;
procedure TfmInforme_View.FormCreate(Sender: TObject);
begin
fViewModel:=TInforme_ViewModel.Create;
ViewModel:=fViewModel;
end;
procedure TfmInforme_View.FormClose(Sender: TObject;var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TfmInforme_View.CambiosEnViewModel(Sender: TObject);
begin
if edtDesdeFecha.Date<>ViewModel.DesdeFecha then
edtDesdeFecha.Date:=ViewModel.DesdeFecha;
if edtHastaFecha.Date<>ViewModel.HastaFecha then
edtHastaFecha.Date:=ViewModel.HastaFecha;
end;
procedure TfmInforme_View.FormDestroy(Sender: TObject);
begin
fViewModel.Free;
fViewModel:=nil;
end;
procedure TfmInforme_View.TickInforme(Sender: TObject);
begin
// FormEspera.Avanzar;
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.Controls.VersionGrid;
interface
uses
System.Classes,
Generics.Collections,
WinApi.Windows,
WinApi.Messages,
Vcl.StdCtrls,
Vcl.Controls,
Vcl.Forms,
Vcl.Graphics,
Vcl.Styles,
Vcl.Themes,
Vcl.ImgList,
DPM.Core.Types;
//A control to show the list of projects and the package version installed when working with project groups.
//code heavily borrows from VSoft.VirtualListView
type
TVersionGridColumn = record
Index : integer;
Title : string;
Width : integer;
Left : integer;
Height : integer;
function GetBounds : TRect;
end;
TVersionGridRow = class
ProjectName : string;
InstalledVersion : TPackageVersion;
end;
TVersionGridPaintRowState = (rsNormal, rsHot, rsSelected, rsFocusedNormal, rsFocusedHot, rsFocusedSelected);
THitElement = (htRow, htColumnProject, htColumnInstalleVer, htColumnInstall, htColumnUpDn, htColumnRemove, htRowInstall, htRowUpDn, htRowRemove );
TOnInstallEvent = procedure(const project : string) of object;
TOnUnInstallEvent = procedure(const project : string) of object;
TOnUpgradeEvent = procedure(const project : string) of object;
TOnDowngradeEvent = procedure(const project : string) of object;
TVersionGrid = class(TCustomControl)
private
FBorderStyle : TBorderStyle;
FColumns : TArray<TVersionGridColumn>;
FRows : TObjectList<TVersionGridRow>;
FColumnWidths : TArray<integer>;
FPaintBmp : TBitmap;
FRowHeight : integer;
FTopRow : Integer; //this is the top row cursor .
FCurrentRow : Integer; //this is our currently selected row.
FHoverRow : integer; //mouse over row in view (add to top row to get index)
FUpdating : boolean;
FVScrollPos : integer;
FHScrollPos : integer;
FVertSBVisible : boolean;
FVertSBWidth : integer;
FVisibleRows : integer; //number of rows we can see
FSelectableRows : integer;
FIDEStyleServices : TCustomStyleServices;
FHitElement : THitElement;
FUpdateCount : integer;
FPackageVersion: TPackageVersion;
FSelectionChangedEvent : TNotifyEvent;
FImageList : TCustomImageList;
//events
FOnInstallEvent : TOnInstallEvent;
FOnUnInstallEvent : TOnUnInstallEvent;
FOnUpgradeEvent : TOnUpgradeEvent;
FOnDowngradeEvent : TOnDowngradeEvent;
procedure SetImageList(const Value: TCustomImageList);
protected
function GetProjectName(index: integer): string;
function GetRowCount : integer;
procedure SetPackageVersion(const value : TPackageVersion);
function GetProjectVersion(index: integer): TPackageVersion;
procedure SetProjectVersion(index: integer; const Value: TPackageVersion);
function GetTotalColumnWidth : integer;
procedure SetRowHeight(const Value: integer);
procedure SetBorderStyle(const Value: TBorderStyle);
procedure CreateHandle; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
function RowInView(const row: integer): boolean;
procedure UpdateVisibleRows;
procedure RowsChanged(Sender: TObject);
procedure ScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
function GetRowPaintState(const rowIdx : integer) : TVersionGridPaintRowState;
procedure ScrollInView(const index : integer);
function GetViewRow(const row : integer) : integer;
function IsAtTop : boolean;
function IsAtEnd : boolean;
function GetRowFromY(const Y : integer) : integer;
procedure UpdateHoverRow(const X, Y : integer);
procedure SetStyleServices(const Value: TCustomStyleServices);
procedure Loaded; override;
procedure Resize; override;
procedure Paint;override;
procedure DoPaintRow(const index : integer; const state : TVersionGridPaintRowState; const copyCanvas : boolean = true);
function GetButtonEnabled(const index : integer; const element : THitElement) : boolean;
procedure UpdateScrollBars;
procedure UpdateColumns;
procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
procedure WMHScroll(var Message: TWMVScroll); message WM_HSCROLL;
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure CMMouseEnter(var Msg: TMessage); message CM_MouseEnter;
procedure CMMouseLeave(var Msg: TMessage); message CM_MouseLeave;
procedure DoLineUp(const fromScrollBar : boolean);
procedure DoLineDown(const fromScrollBar : boolean);
procedure DoPageUp(const fromScrollBar : boolean; const newScrollPostition : integer);
procedure DoPageDown(const fromScrollBar : boolean; const newScrollPostition : integer);
procedure DoGoTop;
procedure DoGoBottom;
procedure DoTrack(const newScrollPostition : integer);
function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure DoSelectionChanged;
function GetHasAnyInstalled : boolean;
public
constructor Create(AOwner : TComponent);override;
destructor Destroy;override;
class constructor Create;
class destructor Destroy;
procedure Invalidate; override;
procedure BeginUpdate;
procedure EndUpdate;
procedure ChangeScale(M, D: Integer{$IF CompilerVersion > 33}; isDpiChange: Boolean{$IFEND} ); override;
procedure Clear;
procedure AddProject(const project : string; const version : string);
function GetInstalledProjects : TArray<string>;
function GetNotInstalledProjects : TArray<string>;
property CurrentRow : Integer read FCurrentRow;
property TopRow : Integer read FTopRow;
property HasAnyInstalled : boolean read GetHasAnyInstalled;
property ImageList : TCustomImageList read FImageList write SetImageList;
property ProjectName[index : integer] : string read GetProjectName;
property ProjectVersion[index : integer] : TPackageVersion read GetProjectVersion write SetProjectVersion;
property PackageVersion : TPackageVersion read FPackageVersion write SetPackageVersion;
property RowCount : integer read GetRowCount;
property OnSelectionChanged : TNotifyEvent read FSelectionChangedEvent write FSelectionChangedEvent;
//exposing this here so the IDE plugin can set this.
property StyleServices : TCustomStyleServices read FIDEStyleServices write SetStyleServices;
published
property Align;
property Anchors;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelKind;
property BevelWidth;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property BorderWidth;
property Color default clWindow;
property Enabled;
property Font;
property Height default 100;
property ParentBackground;
property ParentColor;
property ParentFont;
{$IF CompilerVersion >= 24.0}
{$LEGACYIFEND ON}
property StyleElements;
{$IFEND}
property TabOrder;
property TabStop default True;
property Width default 100;
property Visible;
property RowHeight : integer read FRowHeight write SetRowHeight default 24;
property OnInstallEvent : TOnInstallEvent read FOnInstallEvent write FOnInstallEvent;
property OnUnInstallEvent : TOnUnInstallEvent read FOnUnInstallEvent write FOnUnInstallEvent;
property OnUpgradeEvent : TOnUpgradeEvent read FOnUpgradeEvent write FOnUpgradeEvent;
property OnDowngradeEvent : TOnDowngradeEvent read FOnDowngradeEvent write FOnDowngradeEvent;
end;
implementation
uses
System.Math,
System.SysUtils,
Vcl.Dialogs,
DPM.Core.Utils.Strings;
{ TVersionGrid }
procedure TVersionGrid.AddProject(const project, version: string);
var
newProject : TVersionGridRow;
begin
newProject := TVersionGridRow.Create;
newProject.ProjectName := project;
newProject.InstalledVersion := TPackageVersion.Empty;
FRows.Add(newProject);
RowsChanged(Self);
end;
procedure TVersionGrid.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TVersionGrid.ChangeScale(M, D: Integer{$IF CompilerVersion > 33}; isDpiChange: Boolean{$IFEND} );
begin
inherited;
FRowHeight := MulDiv(FRowHeight, M, D);
//for some reason this is not happening in D11.x
Canvas.Font.Height := MulDiv(Canvas.Font.Height, M, D );
// FPaintBmp.Canvas.Font := Self.Font;
FColumnWidths[1] := MulDiv(FColumnWidths[1], M, D);
FColumnWidths[2] := MulDiv(FColumnWidths[2], M, D);
FColumnWidths[3] := MulDiv(FColumnWidths[3] , M, D);
FColumnWidths[4] := MulDiv(FColumnWidths[4] , M, D);
UpdateColumns;
UpdateVisibleRows;
end;
procedure TVersionGrid.Clear;
begin
FRows.Clear;
end;
procedure TVersionGrid.CMEnter(var Message: TCMEnter);
begin
inherited;
Invalidate;
end;
procedure TVersionGrid.CMExit(var Message: TCMExit);
begin
FHoverRow := -1;
FHitElement := htRow;
Invalidate;
inherited;
end;
procedure TVersionGrid.CMMouseEnter(var Msg: TMessage);
begin
inherited;
end;
procedure TVersionGrid.CMMouseLeave(var Msg: TMessage);
var
oldHoverRow : integer;
rowState : TVersionGridPaintRowState;
begin
if FHitElement in [htRow] then
begin
oldHoverRow := FHoverRow;
FHoverRow := -1;
FHitElement := htRow;
if (oldHoverRow <> -1) and RowInView(oldHoverRow) then
begin
rowState := GetRowPaintState(oldHoverRow);
DoPaintRow(oldHoverRow, rowState);
end;
end
else
begin
FHitElement := htRow;
Invalidate;
end;
inherited;
end;
const
cDefaultColumnWidth = 32;
cInstalledColumnWidth = 120;
constructor TVersionGrid.Create(AOwner: TComponent);
begin
inherited;
FUpdateCount := 0;
FBorderStyle := bsSingle;
FPaintBmp := TBitmap.Create;
FPaintBmp.PixelFormat := pf32bit;
FRowHeight := 24;
Color := clWindow;
//not published in older versions, so get removed when we edit in older versions.
{$IFDEF STYLEELEMENTS}
StyleElements := [seFont, seClient, seBorder];
{$ENDIF}
//IOTAIDEThemingServices added in 10.2
{$IFDEF THEMESERVICES}
ideThemeSvc := (BorlandIDEServices as IOTAIDEThemingServices);
ideThemeSvc.ApplyTheme(Self);
FIDEStyleServices := ideThemeSvc.StyleServices;
{$ELSE}
FIDEStyleServices := Vcl.Themes.StyleServices;
{$ENDIF}
FRows := TObjectList<TVersionGridRow>.Create(true);
SetLength(FColumns, 5);
SetLength(FColumnWidths, 5);
//col 0 takes up the rest of the space
FColumnWidths[1] := cInstalledColumnWidth;
FColumnWidths[2] := cDefaultColumnWidth;
FColumnWidths[3] := cDefaultColumnWidth;
FColumnWidths[4] := cDefaultColumnWidth;
FVertSBWidth := 0;
UpdateColumns;
ControlStyle := [csDoubleClicks, csCaptureMouse, csDisplayDragImage, csClickEvents, csPannable];
TabStop := true;
ParentBackground := true;
ParentColor := true;
ParentDoubleBuffered := false;
DoubleBuffered := false;
Width := 300;
Height := 250;
FVScrollPos := 0;
FHScrollPos := 0;
end;
class constructor TVersionGrid.Create;
begin
TCustomStyleEngine.RegisterStyleHook(TVersionGrid, TScrollingStyleHook);
end;
procedure TVersionGrid.CreateHandle;
begin
inherited;
Resize;
end;
procedure TVersionGrid.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
if (FBorderStyle = bsSingle) then
begin
Params.Style := Params.Style and not WS_BORDER;
Params.ExStyle := Params.ExStyle or WS_EX_CLIENTEDGE;
end;
Params.Style := Params.Style + WS_VSCROLL;
with Params do
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW);
end;
procedure TVersionGrid.CreateWnd;
begin
inherited;
UpdateVisibleRows;
Invalidate;
end;
destructor TVersionGrid.Destroy;
begin
FPaintBmp.Free;
FRows.Free;
inherited;
end;
class destructor TVersionGrid.Destroy;
begin
TCustomStyleEngine.UnRegisterStyleHook(TVersionGrid, TScrollingStyleHook);
end;
procedure TVersionGrid.DoGoBottom;
var
oldTopRow : integer;
oldCurrentRow : integer;
rowState : TVersionGridPaintRowState;
begin
if RowCount = 0 then
exit;
oldTopRow := FTopRow;
oldCurrentRow := FCurrentRow;
FCurrentRow := RowCount - 1;
FTopRow := RowCount - FSelectableRows;
FVScrollPos := RowCount -1;
if FTopRow <> oldTopRow then
//need a full repaint.
Invalidate
else if FCurrentRow <> oldCurrentRow then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow, rowState);
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
end;
//DoRowChanged(oldCurrentRow);
UpdateScrollBars;
end;
procedure TVersionGrid.DoGoTop;
var
oldCurrentRow : integer;
oldTopRow : integer;
rowState : TVersionGridPaintRowState;
begin
if RowCount = 0 then
exit;
oldCurrentRow := FCurrentRow;
oldTopRow := FTopRow;
if (oldTopRow <> 0) or (oldCurrentRow <> 0) then
begin
//some work to do.
if oldTopRow = 0 then
begin
//no scrolling so we can just paint the rows that changed.
FCurrentRow := 0;
FTopRow := 0;
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow + oldTopRow, rowState);
rowState := GetRowPaintState(0);
DoPaintRow(0 , rowState);
end
else
begin
FTopRow := 0;
FCurrentRow := 0;
Invalidate;
end;
FVScrollPos := 0;
UpdateScrollBars;
//DoRowChanged(oldCurrentRow);
end;
end;
procedure TVersionGrid.DoLineDown(const fromScrollBar: boolean);
var
oldCurrentRow : integer;
rowState : TVersionGridPaintRowState;
begin
if RowCount = 0 then
exit;
oldCurrentRow := FCurrentRow;
//behavior depends on whether we are using the keyboard or the mouse on the scrollbar.
//when we use the scrollbar, the current row doesn't change, we just scroll the view.
if fromScrollBar then
begin
if (FTopRow + FSelectableRows -1) < (RowCount -1) then
Inc(FTopRow)
else
exit;
if FHoverRow <> -1 then
Inc(FHoverRow);
FVScrollPos := FTopRow;
//we scrolled so full paint.
Invalidate;
UpdateScrollBars;
end
else //from keyboard
begin
if RowInView(FCurrentRow) then
begin
//if the currentRow is visible, then we can try to move the current row if it's not at the bottom.
if (FCurrentRow - FTopRow < FSelectableRows - 1) then
begin
Inc(FCurrentRow);
//no scrolling required so just paint the affected rows.
//there may not have been a current row before.
if (oldCurrentRow >= 0) and RowInView(oldCurrentRow) then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow , rowState);
end;
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
//DoRowChanged(oldCurrentRow);
FVScrollPos := FTopRow;
UpdateScrollBars;
end
else
begin
//Current Row isn't in the view, so we will need a full paint
if FCurrentRow < RowCount -1 then
begin
Inc(FCurrentRow);
Inc(FTopRow);
if FHoverRow <> -1 then
Inc(FHoverRow);
FVScrollPos := FTopRow;
//DoRowChanged(oldCurrentRow);
Invalidate;
UpdateScrollBars;
end;
end;
end
else
begin
if FCurrentRow < RowCount -1 then
begin
Inc(FCurrentRow);
FTopRow := FCurrentRow;
FVScrollPos := FTopRow;
//DoRowChanged(oldCurrentRow);
Invalidate;
UpdateScrollBars;
end;
end;
end;
end;
procedure TVersionGrid.DoLineUp(const fromScrollBar: boolean);
var
oldCurrentRow : integer;
rowState : TVersionGridPaintRowState;
begin
if RowCount = 0 then
exit;
oldCurrentRow := FCurrentRow;
if fromScrollBar then
begin
if FTopRow > 0 then
begin
Dec(FTopRow);
if FHoverRow > 0 then
Dec(FHoverRow);
FVScrollPos := FTopRow;
//we scrolled so full paint.
Invalidate;
UpdateScrollBars;
end;
end
else
begin
if RowInView(FCurrentRow) then
begin
//if the currentRow is visible, then we can try to move the current row if it's not at the bottom.
if ((FCurrentRow - FTopRow ) > 0) then
begin
Dec(FCurrentRow);
if FHoverRow > 0 then
Dec(FHoverRow);
//no scrolling required so just paint the affected rows.
//there may not have been a current row before.
if (oldCurrentRow >= 0) and RowInView(oldCurrentRow) then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow , rowState);
end;
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
//DoRowChanged(oldCurrentRow);
FVScrollPos := FTopRow;
UpdateScrollBars;
end
else
begin
//Current Row isn't in the view, so we will need a full paint
if (FCurrentRow > 0) and (FTopRow > 0) then
begin
Dec(FCurrentRow);
Dec(FTopRow);
if FHoverRow > 0 then
Dec(FHoverRow);
FVScrollPos := FTopRow;
//DoRowChanged(oldCurrentRow);
Invalidate;
UpdateScrollBars;
end;
end;
end
else
begin
if FCurrentRow > 0 then
begin
Dec(FCurrentRow);
if FCurrentRow < FTopRow then
FTopRow := FCurrentRow
else
FTopRow := Max(FCurrentRow - FSelectableRows - 1, 0);
FVScrollPos := FTopRow;
//DoRowChanged(oldCurrentRow);
Invalidate;
UpdateScrollBars;
end;
end;
end;
end;
function TVersionGrid.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean;
var
scrollPos : integer;
begin
result := true;
if RowCount = 0 then
exit;
if IsAtEnd then //nothing to do
exit;
scrollPos := Min(FVScrollPos + 1, RowCount - 1) ;
ScrollBarScroll(Self,TScrollCode.scLineDown, scrollPos );
end;
function TVersionGrid.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean;
var
scrollPos : integer;
begin
result := true;
if RowCount = 0 then
exit;
if IsAtTop then //nothing to do
exit;
scrollPos := Max(0, FVScrollPos - 1);
ScrollBarScroll(Self,TScrollCode.scLineUp, scrollPos );
end;
procedure TVersionGrid.DoPageDown(const fromScrollBar: boolean; const newScrollPostition: integer);
var
oldCurrentRow : integer;
oldTopRow : integer;
pageSize : integer;
rowState : TVersionGridPaintRowState;
fullRepaint : boolean;
delta : integer;
begin
if RowCount = 0 then
exit;
oldTopRow := FTopRow;
oldCurrentRow := FCurrentRow;
fullRepaint := false;
delta := 0;
if fromScrollBar then
begin
//we do not change current row here.
FTopRow := newScrollPostition;
if FTopRow > (RowCount - FSelectableRows) then
FTopRow := RowCount - FSelectableRows;
if oldTopRow <> FTopRow then
begin
delta := FTopRow - oldTopRow;
fullRepaint := true;
end
end
else
begin //from keyboard
pageSize := Min(FSelectableRows, RowCount -1);
if RowInView(FCurrentRow) and ((FCurrentRow + pageSize) <= (FTopRow + FSelectableRows)) then
begin
FCurrentRow := FTopRow + FSelectableRows -1;
end
else
begin
Inc(FCurrentRow, pageSize);
FCurrentRow := Min(FCurrentRow, RowCount -1);
//position current row at the bottom
FTopRow := Max(0,FCurrentRow - FSelectableRows + 1);
fullRepaint := true;
end;
delta := FCurrentRow - oldCurrentRow;
end;
if delta > 0 then
begin
if not fullRepaint then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow, rowState);
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
end
else
Invalidate;
//DoRowChanged(oldCurrentRow);
FVScrollPos := FTopRow;
UpdateScrollBars;
end;
end;
procedure TVersionGrid.DoPageUp(const fromScrollBar: boolean; const newScrollPostition: integer);
var
oldTopRow : integer;
oldCurrentRow : integer;
rowState : TVersionGridPaintRowState;
fullRepaint : boolean;
delta : integer;
pageSize : integer;
begin
if RowCount = 0 then
exit;
oldTopRow := FTopRow;
oldCurrentRow := FCurrentRow;
fullRepaint := false;
delta := 0;
if fromScrollBar then
begin
FTopRow := newScrollPostition;
FCurrentRow := 0;
if oldTopRow <> FTopRow then
begin
delta := FTopRow - oldTopRow;
fullRepaint := true;
end
else if oldCurrentRow <> FCurrentRow then
delta := FCurrentRow - oldCurrentRow;
end
else
begin
//from keyboard
pageSize := Min(FSelectableRows, RowCount -1);
if RowInView(FCurrentRow) and (FCurrentRow > FTopRow) then
begin
FCurrentRow := FTopRow;
end
else
begin
Dec(FTopRow, pageSize);
FTopRow := Max(FTopRow, 0);
FCurrentRow := FTopRow;
fullRepaint := true;
end;
delta := FCurrentRow - oldCurrentRow;
end;
if delta < 0 then
begin
if not fullRepaint then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow, rowState);
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
end
else
Invalidate;
//DoRowChanged(oldCurrentRow);
FVScrollPos := FTopRow;
UpdateScrollBars;
end;
end;
procedure TVersionGrid.DoPaintRow(const index: integer; const state: TVersionGridPaintRowState; const copyCanvas : boolean);
var
viewRow : integer;
rowRect : TRect;
destRect : TRect;
i: Integer;
colRect : TRect;
imgRect : TRect;
btnRect : TRect;
txt : string;
LCanvas : TCanvas;
backgroundColor : TColor;
fontColor : TColor;
btnColor : TColor;
project : TVersionGridRow;
procedure CenterRect(const outerRect : TRect; var innerRect : TRect);
var
iw, ih : Integer;
begin
iw := innerRect.Width;
ih := innerRect.Height;
innerRect.Left := outerRect.Left + ((outerRect.Width - innerRect.Width) div 2);
innerRect.Top := outerRect.Top + ((outerRect.Height - innerRect.Height) div 2);
innerRect.Width := iw;
innerRect.Height := ih;
end;
procedure DrawButton;
begin
LCanvas.Brush.Color := btnColor;
LCanvas.Pen.Color := btnColor;
LCanvas.RoundRect(btnRect,2,2);
end;
begin
if not HandleAllocated then
exit;
if FRows.Count = 0 then
exit;
if (index < 0) or (index > FRows.Count -1) then
exit;
LCanvas := FPaintBmp.Canvas;
LCanvas.Brush.Style := bsSolid;
viewRow := GetViewRow(index);
rowRect := ClientRect;
rowRect.Top := FRowHeight + viewRow * FRowHeight;
rowRect.Bottom := rowRect.Top + FRowHeight;
rowRect.Width := Max(rowRect.Width, FPaintBmp.Width);
project := FRows.Items[index];
if (state in [rsSelected, rsFocusedSelected, rsFocusedHot, rsHot]) then
begin
{$IF CompilerVersion < 32.0}
backgroundColor := $00FFF0E9;
fontcolor := FIDEStyleServices.GetSystemColor(clWindowText);
{$ELSE}
if state = TVersionGridPaintRowState.rsFocusedSelected then
backgroundColor := FIDEStyleServices.GetSystemColor(clBtnHighlight)
else
backgroundColor := FIDEStyleServices.GetSystemColor(clBtnShadow);
fontcolor := FIDEStyleServices.GetSystemColor(clHighlightText);
{$IFEND}
end
else
begin
backgroundColor := FIDEStyleServices.GetSystemColor(clWindow);
fontColor := FIDEStyleServices.GetSystemColor(clWindowText);
end;
btnColor := FIDEStyleServices.GetSystemColor(clBtnFace);
LCanvas.Brush.Color := backgroundColor;
LCanvas.Font.Color := fontColor;
LCanvas.FillRect(rowRect);
LCanvas.Brush.Style := bsClear;
for i := 0 to 4 do
begin
colRect := FColumns[i].GetBounds;
colRect.Top := rowRect.Top;
colRect.Bottom := rowRect.Bottom;
colRect.Inflate(-5, 0);
imgRect := TRect.Create(0,0,FImageList.Width, FImageList.Height);
CenterRect(colRect, imgRect);
btnRect := imgRect;
btnRect.Inflate(3,3);
txt := '';
case i of
0 : //project
begin
txt := ChangeFileExt(ExtractFileName(project.ProjectName),'');
end;
1 : //installed version
begin
if not project.InstalledVersion.IsEmpty then
txt := project.InstalledVersion.ToStringNoMeta;
end;
2 : //add
begin
if project.InstalledVersion.IsEmpty then
begin
DrawButton;
FImageList.Draw(LCanvas, imgRect.Left, imgRect.Top, 0, TDrawingStyle.dsTransparent, TImageType.itImage, true );
end;
end;
3 : //upgrade/downgrade
begin
if FPackageVersion.IsEmpty then
continue;
if (not project.InstalledVersion.IsEmpty) then //a version is installed already
begin
if FPackageVersion = project.InstalledVersion then
continue;
DrawButton;
if FPackageVersion > project.InstalledVersion then
FImageList.Draw(LCanvas, imgRect.Left, imgRect.Top, 2, TDrawingStyle.dsTransparent, TImageType.itImage, true )
else
FImageList.Draw(LCanvas, imgRect.Left, imgRect.Top, 3, TDrawingStyle.dsTransparent, TImageType.itImage, true );
end;
end;
4 :
begin
if not project.InstalledVersion.IsEmpty then
begin
DrawButton;
FImageList.Draw(LCanvas, imgRect.Left, imgRect.Top, 1, TDrawingStyle.dsTransparent, TImageType.itImage, true );
end;
end;
end;
if txt <> '' then
DrawText(LCanvas.Handle, PChar(txt),Length(txt), colRect, DT_SINGLELINE + DT_LEFT + DT_VCENTER );
end;
destRect := rowRect;
OffsetRect(rowRect, FHScrollPos,0);
if copyCanvas then
Canvas.CopyRect(destRect, LCanvas, rowRect);
end;
procedure TVersionGrid.DoSelectionChanged;
begin
if Assigned(FSelectionChangedEvent) then
FSelectionChangedEvent(Self);
end;
procedure TVersionGrid.DoTrack(const newScrollPostition: integer);
var
oldTopRow : integer;
begin
oldTopRow := FTopRow;
FTopRow := newScrollPostition;
FVScrollPos := FTopRow;
if oldTopRow <> FTopRow then
begin
Invalidate;
UpdateScrollBars;
end;
end;
procedure TVersionGrid.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount <= 0 then
begin
FUpdateCount := 0;
if HandleAllocated then
begin
UpdateVisibleRows;
Invalidate;
end;
end;
end;
function TVersionGrid.GetButtonEnabled(const index: integer; const element: THitElement): boolean;
var
row : TVersionGridRow;
begin
result := false;
if (index >= 0) and (index < FRows.Count) then
begin
row := FRows[index];
case element of
htRowInstall:
begin
result := row.InstalledVersion.IsEmpty;
end;
htRowUpDn:
begin
if FPackageVersion.IsEmpty or row.InstalledVersion.IsEmpty then
exit;
if (not row.InstalledVersion.IsEmpty) then
begin
result := FPackageVersion <> row.InstalledVersion;
end;
end;
htRowRemove:
begin
result := not row.InstalledVersion.IsEmpty;
end;
end;
end;
end;
function TVersionGrid.GetHasAnyInstalled: boolean;
var
i : integer;
begin
result := false;
for i := 0 to FRows.Count -1 do
begin
if not FRows[i].InstalledVersion.IsEmpty then
exit(true);
end;
end;
function TVersionGrid.GetNotInstalledProjects: TArray<string>;
var
list : TList<string>;
i : integer;
begin
SetLength(result, 0);
// result := [];
list := TList<string>.Create;
try
for i := 0 to FRows.Count -1 do
begin
if FRows[i].InstalledVersion.IsEmpty then
list.Add(FRows[i].ProjectName);
end;
finally
result := list.ToArray;
list.Free;
end;
end;
function TVersionGrid.GetInstalledProjects: TArray<string>;
var
list : TList<string>;
i : integer;
begin
SetLength(result, 0);
// result := [];
list := TList<string>.Create;
try
for i := 0 to FRows.Count -1 do
begin
if not FRows[i].InstalledVersion.IsEmpty then
list.Add(FRows[i].ProjectName);
end;
finally
result := list.ToArray;
list.Free;
end;
end;
function TVersionGrid.GetProjectName(index: integer): string;
begin
if (index >= 0) and (index < FRows.Count) then
result := FRows[index].ProjectName
else
result := '';
end;
function TVersionGrid.GetProjectVersion(index: integer): TPackageVersion;
begin
if (index >= 0) and (index < FRows.Count) then
result := FRows[index].InstalledVersion
else
result := TPackageVersion.Empty;
end;
function TVersionGrid.GetRowCount: integer;
begin
result := FRows.Count;
end;
function TVersionGrid.GetRowFromY(const Y: integer): integer;
begin
result := (Y div FRowHeight) -1; //this is probably not quite right.
end;
function TVersionGrid.GetRowPaintState(const rowIdx: integer): TVersionGridPaintRowState;
begin
if Self.Focused then
begin
result := rsFocusedNormal;
if RowInView(rowIdx) then
begin
if (rowIdx = FCurrentRow) then
result := rsFocusedSelected
else if rowIdx = FHoverRow then
result := rsFocusedHot;
end;
end
else
begin
result := rsNormal;
if RowInview(rowIdx) then
begin
if (rowIdx = FCurrentRow) then
result := rsSelected
else if rowIdx = FHoverRow then
result := rsHot;
end;
end;
end;
function TVersionGrid.GetTotalColumnWidth: integer;
begin
result := FColumns[3].Left + FColumns[3].Width;
end;
function TVersionGrid.GetViewRow(const row: integer): integer;
begin
result := row - FTopRow;
if result < 0 then
result := 0;
if result > FVisibleRows -1 then
result := FVisibleRows -1;
end;
procedure TVersionGrid.Invalidate;
begin
if FUpdateCount = 0 then
inherited;
end;
function TVersionGrid.IsAtEnd: boolean;
begin
result := FVScrollPos = RowCount - FSelectableRows;
end;
function TVersionGrid.IsAtTop: boolean;
begin
result := FVScrollPos = 0;
end;
procedure TVersionGrid.Loaded;
begin
inherited;
// Set the bmp to the size of the control.
FPaintBmp.SetSize(Width, Height);
end;
procedure TVersionGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
row : Integer;
begin
inherited;
if not Enabled then
exit;
if RowCount = 0 then
exit;
SetFocus;
row := GetRowFromY(Y);
if (row > FVisibleRows) or (row >= RowCount) then
exit;
if FTopRow + row <> FCurrentRow then
begin
FCurrentRow := FTopRow + row;
Invalidate;
UpdateScrollBars;
end;
end;
procedure TVersionGrid.MouseMove(Shift: TShiftState; X, Y: Integer);
var
r : TRect;
row : integer;
oldHit : THitElement;
begin
oldHit := FHitElement;
FHitElement := htRow;
row := GetRowFromY(Y);
try
if Y > FRowHeight then
begin
r := FColumns[2].GetBounds;
r.Offset(0, (row + 1) * FRowHeight);
if r.Contains(Point(X, Y)) then
begin
FHitElement := htRowInstall;
exit;
end;
r := FColumns[3].GetBounds;
r.Offset(0, (row + 1) * FRowHeight);
if r.Contains(Point(X, Y)) then
begin
FHitElement := htRowUpDn;
exit;
end;
r := FColumns[4].GetBounds;
r.Offset(0, (row + 1) * FRowHeight);
if r.Contains(Point(X, Y)) then
begin
FHitElement := htRowRemove;
exit;
end;
FHitElement := htRow;
end;
finally
if FHitElement <> oldHit then
Invalidate;
UpdateHoverRow(X, Y);
Self.Cursor := crDefault;
end;
end;
procedure TVersionGrid.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if not Enabled then
exit;
case FHitElement of
htRowInstall :
begin
if Assigned(FOnInstallEvent) then
begin
if GetButtonEnabled(FCurrentRow, FHitElement) then
FOnInstallEvent(FRows[FCurrentRow].ProjectName);
end;
end;
htRowUpDn :
begin
if GetButtonEnabled(FCurrentRow, FHitElement) then
begin
if FPackageVersion > FRows[FCurrentRow].InstalledVersion then
begin
if Assigned(FOnUpgradeEvent) then
FOnUpgradeEvent(FRows[FCurrentRow].ProjectName);
end
else
begin
if Assigned(FOnDowngradeEvent) then
FOnDowngradeEvent(FRows[FCurrentRow].ProjectName);
end;
end;
end;
htRowRemove :
begin
if Assigned(FOnUnInstallEvent) then
begin
if GetButtonEnabled(FCurrentRow, FHitElement) then
FOnUnInstallEvent(FRows[FCurrentRow].ProjectName);
end;
end;
end;
inherited;
end;
const
hightLightElements : array[0..4] of THitElement = (htColumnProject,htColumnInstalleVer,htColumnInstall, htColumnUpDn,htColumnRemove);
procedure TVersionGrid.Paint;
var
LCanvas : TCanvas;
HeaderTextColor : TColor;
HeaderBackgroundColor: TColor;
HeaderBorderColor: TColor;
backgroundColor : TColor;
columnHightlightColor : TColor;
r : TRect;
i: Integer;
rowIdx : integer;
rowState : TVersionGridPaintRowState;
begin
LCanvas := FPaintBmp.Canvas;
LCanvas.Font.Assign(Self.Font);
if FIDEStyleServices.Enabled {$IF CompilerVersion >= 24.0} and (seClient in StyleElements) {$IFEND} then
begin
//client
backgroundColor := FIDEStyleServices.GetSystemColor(clWindow);
//header
//TODO : When running in the IDE we will need to tweak this!
if FIDEStyleServices.Name = 'Windows' then
begin
if Enabled then
HeaderTextColor := FIDEStyleServices.GetStyleFontColor(sfHeaderSectionTextNormal)
else
HeaderTextColor := FIDEStyleServices.GetStyleFontColor(sfHeaderSectionTextDisabled);
FIDEStyleServices.GetElementColor(FIDEStyleServices.GetElementDetails(tgFixedCellNormal), ecBorderColor, HeaderBorderColor);
FIDEStyleServices.GetElementColor(FIDEStyleServices.GetElementDetails(tgFixedCellNormal ), ecFillColor, HeaderBackgroundColor);
//FIDEStyleServices.GetElementColor(FIDEStyleServices.GetElementDetails(tbPushButtonHot ), ecShadowColor, columnHightlightColor);
columnHightlightColor := FIDEStyleServices.GetSystemColor(clBtnShadow);
end
else
begin
if Enabled then
HeaderTextColor := FIDEStyleServices.GetSystemColor(clBtnText)
else
HeaderTextColor := FIDEStyleServices.GetSystemColor(clBtnShadow);
FIDEStyleServices.GetElementColor(FIDEStyleServices.GetElementDetails(tgClassicFixedCellNormal), ecBorderColor, HeaderBorderColor);
FIDEStyleServices.GetElementColor(FIDEStyleServices.GetElementDetails(tgClassicFixedCellNormal ), ecFillColor, HeaderBackgroundColor);
FIDEStyleServices.GetElementColor(FIDEStyleServices.GetElementDetails(tgClassicFixedCellHot ), ecFillColor, columnHightlightColor);
//FIDEStyleServices.GetElementColor(FIDEStyleServices.GetElementDetails(tbPushButtonNormal ), ecTextColor, HeaderTextColor);
end;
end
else
begin
//client
backgroundColor := clWindow;
//header
HeaderBackgroundColor := clBtnFace;
HeaderBorderColor := clWindowFrame;
if Enabled then
HeaderTextColor := clWindowText
else
HeaderTextColor := clBtnShadow;
columnHightlightColor := clBtnShadow;
end;
//paint background
r := Self.ClientRect;
r.Width := Max(FPaintBmp.Width, r.Width); //paintbmp may be wider than the client.
LCanvas.Brush.Style := bsSolid;
LCanvas.Brush.Color := backgroundColor;
LCanvas.FillRect(r);
//paint header
LCanvas.Font.Color := HeaderTextColor;
LCanvas.Brush.Color := HeaderBackgroundColor;
LCanvas.Pen.Color := HeaderBorderColor;
r.Bottom := r.Top + FRowHeight;
LCanvas.Rectangle(r);
r := FColumns[0].GetBounds;
InflateRect(r,-1,-1);
LCanvas.Brush.Style := bsClear;
LCanvas.Font.Assign(Canvas.Font);
LCanvas.Font.Color := HeaderTextColor;
for i := 0 to 4 do
begin
if FHitElement = hightLightElements[i] then
begin
LCanvas.Brush.Style := bsSolid;
LCanvas.Brush.Color := columnHightlightColor;
LCanvas.FillRect(FColumns[i].GetBounds);
end;
LCanvas.Brush.Style := bsClear;
LCanvas.MoveTo(FColumns[i].GetBounds.Right, 0);
LCanvas.LineTo(FColumns[i].GetBounds.Right,FColumns[i].Height);
if FColumns[i].Title <> '' then
begin
r := FColumns[i].GetBounds;
r.Inflate(-5, 0);
LCanvas.TextRect(r, FColumns[i].Title, [tfLeft, tfSingleLine, tfVerticalCenter]);
end;
end;
if Enabled then
begin
//paint all visible rows
for i := 0 to FVisibleRows - 1 do
begin
rowIdx := FTopRow + i;
if rowIdx >= RowCount then
break;
rowState := GetRowPaintState(rowIdx);
DoPaintRow(rowIdx, rowState, false);
end;
end;
r := ClientRect;
OffsetRect(r, FHScrollPos,0);
Canvas.CopyRect(ClientRect, FPaintBmp.Canvas, r);
end;
procedure TVersionGrid.Resize;
var
NewWidth, NewHeight: integer;
begin
if (not HandleAllocated) then
Exit;
if csDestroying in ComponentState then
Exit;
NewWidth := Max(ClientWidth, GetTotalColumnWidth);
NewHeight := ClientHeight;
if (NewWidth <> FPaintBmp.Width) or (NewHeight <> FPaintBmp.Height) then
begin
// TBitmap does some stuff to try and preserve contents
// which slows things down a lot - this avoids that
FPaintBmp.SetSize(0, 0);
FPaintBmp.SetSize(NewWidth, NewHeight);
end;
FHoverRow := -1;
UpdateVisibleRows;
UpdateScrollBars;
UpdateColumns;
if (RowCount > 0) and (FCurrentRow > -1) then
if not RowInView(FCurrentRow) then
ScrollInView(FCurrentRow);
//Repaint;
//RedrawWindow(Handle, nil, 0, RDW_ERASE or RDW_INVALIDATE or RDW_UPDATENOW);
//force repainting scrollbars
if sfHandleMessages in FIDEStyleServices.Flags then
SendMessage(Handle, WM_NCPAINT, 0, 0);
inherited;
end;
procedure TVersionGrid.RowsChanged(Sender: TObject);
begin
if not (csDesigning in ComponentState) then
begin
if (FUpdateCount = 0) and HandleAllocated then
begin
UpdateVisibleRows;
Invalidate;
end;
end;
end;
procedure TVersionGrid.ScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
case scrollCode of
TScrollCode.scLineUp: DoLineUp(true);
TScrollCode.scLineDown: DoLineDown(true);
TScrollCode.scPageUp:
begin
ScrollPos := FVScrollPos - FSelectableRows;
if ScrollPos < 0 then
ScrollPos := 0;
DoPageUp(true,ScrollPos);
end;
TScrollCode.scPageDown:
begin
ScrollPos := FVScrollPos + FSelectableRows;
if ScrollPos > RowCount -1 then
ScrollPos := RowCount - 1;
DoPageDown(true, ScrollPos);
end;
TScrollCode.scPosition,
TScrollCode.scTrack:
begin
DoTrack(ScrollPos);
end;
TScrollCode.scTop: DoGoTop;
TScrollCode.scBottom: DoGoBottom;
TScrollCode.scEndScroll: ;
end;
end;
procedure TVersionGrid.ScrollInView(const index: integer);
begin
if (RowCount = 0) or (index > RowCount -1) then
exit;
//Figure out what the top row should be to make the current row visible.
//current row below bottom of vieww
if index >= (FTopRow + FSelectableRows) then
FTopRow := Max(0, index - FSelectableRows + 1)
else //above
FTopRow := Min(index, RowCount - FVisibleRows );
FVScrollPos := FTopRow;
Invalidate;
UpdateScrollBars;
end;
procedure TVersionGrid.SetBorderStyle(const Value: TBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
RecreateWnd;
end;
end;
procedure TVersionGrid.SetImageList(const Value: TCustomImageList);
begin
FImageList := Value;
end;
procedure TVersionGrid.SetPackageVersion(const Value: TPackageVersion);
begin
FPackageVersion := Value;
Invalidate;
end;
procedure TVersionGrid.SetProjectVersion(index: integer; const Value: TPackageVersion);
begin
if (index >= 0) and (index < FRows.Count) then
FRows[index].InstalledVersion := value;
end;
procedure TVersionGrid.SetRowHeight(const Value: integer);
begin
if FRowHeight <> value then
begin
FRowHeight := Value;
UpdateVisibleRows;
Invalidate;
end;
end;
procedure TVersionGrid.SetStyleServices(const Value: TCustomStyleServices);
begin
FIDEStyleServices := Value;
Invalidate;
end;
procedure TVersionGrid.UpdateColumns;
begin
//remove button
FColumns[4].Index := 4;
FColumns[4].Title := '';
FColumns[4].Width := FColumnWidths[4];
FColumns[4].Left := Self.Width - FColumns[4].Width - 1;
FColumns[4].Height := FRowHeight;
if FVertSBVisible then
FColumns[4].Left := FColumns[4].Left - FVertSBWidth; //TODO : SB Width
//upgrade/downgrade
FColumns[3].Index := 3;
FColumns[3].Title := '';
FColumns[3].Width := FColumnWidths[3];
FColumns[3].Left := FColumns[4].Left - FColumns[3].Width - 1;
FColumns[3].Height := FRowHeight;
//install
FColumns[2].Index := 2;
FColumns[2].Title := '';
FColumns[2].Width := FColumnWidths[2];
FColumns[2].Left := FColumns[3].Left - FColumns[2].Width - 1;
FColumns[2].Height := FRowHeight;
FColumns[1].Index := 1;
FColumns[1].Title := 'Installed';
FColumns[1].Width := FColumnWidths[1];
FColumns[1].Left := FColumns[2].Left - FColumns[1].Width -1 ;
FColumns[1].Height := FRowHeight;
FColumns[0].Index := 0;
FColumns[0].Title := 'Project';
FColumns[0].Left := 0;
FColumns[0].Width := FColumns[1].Left - 2;
FColumns[0].Height := FRowHeight;
end;
procedure TVersionGrid.UpdateHoverRow(const X, Y: integer);
var
row : Integer;
oldHoverRow : integer;
rowState : TVersionGridPaintRowState;
begin
row := FTopRow + GetRowFromY(Y);
if row <> FHoverRow then
begin
oldHoverRow := FHoverRow;
FHoverRow := row;
if (oldHoverRow <> -1) and RowInView(oldHoverRow) then
begin
rowState := GetRowPaintState(oldHoverRow);
DoPaintRow(oldHoverRow, rowState);
end;
if (FHoverRow > -1) and RowInView(FHoverRow) then
begin
rowState := GetRowPaintState(FHoverRow);
DoPaintRow(FHoverRow , rowState);
end
end;
end;
procedure TVersionGrid.UpdateScrollBars;
var
sbInfo : TScrollInfo;
begin
if not HandleAllocated then
exit;
sbInfo.cbSize := SizeOf(TScrollInfo);
sbInfo.fMask := SIF_ALL;
sbInfo.nMin := 0;
//Note : this may trigger a resize if the visibility changes
if RowCount < FSelectableRows + 1 then
begin
sbInfo.nMax := 0;
sbInfo.nPage := 0;
sbInfo.nPos := 0;
FVertSBVisible := false;
SetScrollInfo(Handle, SB_VERT, sbInfo, True);
FVertSBWidth := 0
end
else
begin
sbInfo.nMax := Max(RowCount -1, 0);
sbInfo.nPage := Min(FSelectableRows, RowCount -1);
sbInfo.nPos := Min(FVScrollPos, RowCount -1) ;
FVertSBVisible := true;
SetScrollInfo(Handle, SB_VERT, sbInfo, True);
FVertSBWidth := GetSystemMetrics(SM_CXHSCROLL);
end;
sbInfo.cbSize := SizeOf(TScrollInfo);
sbInfo.fMask := SIF_ALL;
sbInfo.nMin := 0;
if FPaintBmp.Width <= ClientWidth then
begin
sbInfo.nMax := 0;
sbInfo.nPage := 0;
sbInfo.nPos := 0;
SetScrollInfo(Handle, SB_HORZ, sbInfo, True);
end
else
begin
sbInfo.nMax := Max(FPaintBmp.Width, 0);
sbInfo.nPage := ClientWidth;
sbInfo.nPos := Min(FHScrollPos, FPaintBmp.Width -1 ) ;
SetScrollInfo(Handle, SB_HORZ, sbInfo, True);
end;
end;
procedure TVersionGrid.UpdateVisibleRows;
begin
FHoverRow := -1;
if FUpdating then
exit;
FUpdating := true;
if HandleAllocated then
begin
FVisibleRows := ClientHeight div RowHeight - 1;
FSelectableRows := Min(FVisibleRows, RowCount); //the number of full rows
if (RowCount > FVisibleRows) and (ClientHeight mod RowHeight > 0) then
begin
//add 1 to ensure a partial row is painted.
FVisibleRows := FVisibleRows + 1;
end;
UpdateScrollBars;
end;
FUpdating := false;
end;
function TVersionGrid.RowInView(const row: integer): boolean;
begin
result := (row >= FTopRow) and (row < (FTopRow + FSelectableRows));
end;
procedure TVersionGrid.WMEraseBkgnd(var Message: TWmEraseBkgnd);
begin
Message.Result := 1; //we will paint the background
end;
procedure TVersionGrid.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := Message.Result or DLGC_WANTARROWS;
end;
procedure TVersionGrid.WMHScroll(var Message: TWMVScroll);
var
info : TScrollInfo;
begin
Message.Result := 0;
with Message do
begin
if ScrollCode = 8 then
exit;
info.cbSize := SizeOf(TScrollInfo);
info.fMask := SIF_TRACKPOS;
GetScrollInfo(Self.Handle,SB_HORZ, info);
case TScrollCode(scrollCode) of
TScrollCode.scLineUp: FHScrollPos := Max(0, FHScrollPos -1) ;
TScrollCode.scLineDown: FHScrollPos := Min(FPaintBmp.Width, FHScrollPos + 1) ;
TScrollCode.scPageUp:
begin
FHScrollPos := Max(0, FHScrollPos - ClientWidth)
end;
TScrollCode.scPageDown:
begin
FHScrollPos := Min(FHScrollPos + ClientWidth, FPaintBmp.Width );
// ScrollPos := FVScrollPos + FSelectableRows;
// if ScrollPos > RowCount -1 then
// ScrollPos := RowCount - 1;
// DoPageDown(true, ScrollPos);
end;
TScrollCode.scPosition,
TScrollCode.scTrack:
begin
FHScrollPos := info.nTrackPos;
// DoTrack(ScrollPos);
end;
TScrollCode.scTop: FHScrollPos := 0;
TScrollCode.scBottom: FHScrollPos := FPaintBmp.Width;
// TScrollCode.scEndScroll: ;
end;
UpdateScrollBars;
Invalidate;
//handle h scroll
end;
end;
procedure TVersionGrid.WMSize(var Message: TWMSize);
begin
inherited;
//force repaint during resizing rather than just after.
RedrawWindow(Handle, nil, 0, RDW_ERASE or RDW_INVALIDATE or RDW_UPDATENOW);
//Repaint;
end;
procedure TVersionGrid.WMVScroll(var Message: TWMVScroll);
var
info : TScrollInfo;
begin
Message.Result := 0;
with Message do
begin
if ScrollCode = 8 then
exit;
info.cbSize := SizeOf(TScrollInfo);
info.fMask := SIF_TRACKPOS;
GetScrollInfo(Self.Handle,SB_VERT, info);
Self.ScrollBarScroll(Self, TScrollCode(ScrollCode), info.nTrackPos);
end;
end;
{ TVersionGridColumn }
function TVersionGridColumn.GetBounds: TRect;
begin
result := Rect(Left,0,Left + Width, Height);
end;
end.
|
unit o_basenormlistobj;
interface
uses
SysUtils, Classes, Contnrs;
type
TBasenormListObj = class
private
function GetCount: Integer;
protected
fList: TList;
public
constructor Create; virtual;
destructor Destroy; override;
property Count: Integer read GetCount;
procedure Delete(aIndex: Integer);
procedure Clear;
end;
implementation
{ TBasenormListObj }
constructor TBasenormListObj.Create;
begin
fList := TList.Create;
end;
destructor TBasenormListObj.Destroy;
begin
FreeAndNil(fList);
inherited;
end;
procedure TBasenormListObj.Clear;
begin
fList.Clear;
end;
procedure TBasenormListObj.Delete(aIndex: Integer);
begin
if aIndex > fList.Count then
exit;
fList.Delete(aIndex);
end;
function TBasenormListObj.GetCount: Integer;
begin
Result := fList.Count;
end;
end.
|
unit AssociationListUtils;
interface
uses AssociationListConst, SySUtils;
procedure G_CopyLongs(Source, Dest: Pointer; Count: Cardinal);
function G_CompareText(P1, P2: PChar): Integer; overload;
function G_CompareText(const S1, S2: string): Integer; overload;
function G_CompareStr(const S1, S2: string): Integer;
function G_EnlargeCapacity(Capacity: Integer): Integer;
function G_IncPowerOfTwo(L: LongWord): LongWord;
procedure G_ReverseLongs(P: Pointer; Count: Cardinal);
procedure G_MoveLongs(Source, Dest: Pointer; Count: Cardinal);
function G_NormalizeCapacity(Capacity: Integer): Integer;
function G_CeilPowerOfTwo(L: LongWord): LongWord;
procedure RaiseErrorFmt(const msg, S: string);
procedure RaiseError(const msg: string);
implementation
procedure RaiseError(const msg: string);
begin
raise Exception.Create(msg);
end;
procedure RaiseErrorFmt(const msg, S: string);
begin
raise Exception.CreateFmt(msg, [S]);
end;
function G_CeilPowerOfTwo(L: LongWord): LongWord;
asm
TEST EAX,EAX
JE @@zq
BSR EDX,EAX
BSF ECX,EAX
CMP EDX,ECX
JNE @@nx
RET
@@zq: MOV EAX,1
RET
@@nx: INC EDX
TEST EAX,$80000000
JNE @@ov
MOV EAX,DWORD PTR [EDX*4+BitMasks32]
RET
@@ov: XOR EAX,EAX
end;
function G_NormalizeCapacity(Capacity: Integer): Integer;
begin
if Capacity <= 64 then
begin
if Capacity <= 16 then
Result := 16
else
Result := 64;
end
else if Capacity <= 1024 then
begin
if Capacity <= 256 then
Result := 256
else
Result := 1024;
end
else
Result := G_CeilPowerOfTwo(Capacity);
end;
procedure G_MoveLongs(Source, Dest: Pointer; Count: Cardinal);
asm
CMP EDX,EAX
JA @@bm
JE @@qt
CALL G_CopyLongs
@@qt: RET
@@bm: SHL ECX,2
ADD EAX,ECX
ADD EDX,ECX
@@lp: SUB ECX,64
JS @@nx
SUB EAX,64
SUB EDX,64
MOVQ MM0,[EAX]
MOVQ MM1,[EAX+8]
MOVQ MM2,[EAX+16]
MOVQ MM3,[EAX+24]
MOVQ MM4,[EAX+32]
MOVQ MM5,[EAX+40]
MOVQ MM6,[EAX+48]
MOVQ MM7,[EAX+56]
MOVQ [EDX],MM0
MOVQ [EDX+8],MM1
MOVQ [EDX+16],MM2
MOVQ [EDX+24],MM3
MOVQ [EDX+32],MM4
MOVQ [EDX+40],MM5
MOVQ [EDX+48],MM6
MOVQ [EDX+56],MM7
JMP @@lp
@@nx: ADD ECX,64
SUB EAX,ECX
SUB EDX,ECX
JMP DWORD PTR @@wV[ECX]
@@wV: DD @@w00, @@w01, @@w02, @@w03
DD @@w04, @@w05, @@w06, @@w07
DD @@w08, @@w09, @@w10, @@w11
DD @@w12, @@w13, @@w14, @@w15
@@w15: MOV ECX,[EAX+56]
MOV [EDX+56],ECX
@@w14: MOV ECX,[EAX+52]
MOV [EDX+52],ECX
@@w13: MOV ECX,[EAX+48]
MOV [EDX+48],ECX
@@w12: MOV ECX,[EAX+44]
MOV [EDX+44],ECX
@@w11: MOV ECX,[EAX+40]
MOV [EDX+40],ECX
@@w10: MOV ECX,[EAX+36]
MOV [EDX+36],ECX
@@w09: MOV ECX,[EAX+32]
MOV [EDX+32],ECX
@@w08: MOV ECX,[EAX+28]
MOV [EDX+28],ECX
@@w07: MOV ECX,[EAX+24]
MOV [EDX+24],ECX
@@w06: MOV ECX,[EAX+20]
MOV [EDX+20],ECX
@@w05: MOV ECX,[EAX+16]
MOV [EDX+16],ECX
@@w04: MOV ECX,[EAX+12]
MOV [EDX+12],ECX
@@w03: MOV ECX,[EAX+8]
MOV [EDX+8],ECX
@@w02: MOV ECX,[EAX+4]
MOV [EDX+4],ECX
@@w01: MOV ECX,[EAX]
MOV [EDX],ECX
@@w00: EMMS
end;
procedure G_ReverseLongs(P: Pointer; Count: Cardinal);
asm
PUSH EDI
ADD EAX,4
LEA EDI,[EAX+EDX*4-12]
@@lp: CMP EAX,EDI
JGE @@nx
MOV ECX,[EAX-4]
MOV EDX,[EDI+4]
MOV [EDI+4],ECX
MOV [EAX-4],EDX
MOV ECX,[EAX]
MOV EDX,[EDI]
MOV [EDI],ECX
MOV [EAX],EDX
ADD EAX,8
SUB EDI,8
JMP @@lp
@@nx: SUB EAX,4
CMP EAX,EDI
JG @@qt
MOV ECX,[EAX]
MOV EDX,[EDI+4]
MOV [EDI+4],ECX
MOV [EAX],EDX
@@qt: POP EDI
end;
function G_IncPowerOfTwo(L: LongWord): LongWord;
asm
TEST EAX,EAX
JE @@zq
TEST EAX,$80000000
JNE @@ov
BSR EDX,EAX
INC EDX
MOV EAX,DWORD PTR [EDX*4+BitMasks32]
RET
@@zq: MOV EAX,1
RET
@@ov: XOR EAX,EAX
end;
function G_EnlargeCapacity(Capacity: Integer): Integer;
begin
if Capacity < 54 then
begin
if Capacity < 6 then
Result := 16
else
Result := 64;
end
else if Capacity < 1014 then
begin
if Capacity < 246 then
Result := 256
else
Result := 1024;
end
else
Result := G_IncPowerOfTwo(Capacity + 10);
end;
function G_CompareStr(const S1, S2: string): Integer;
asm
CMP EAX,EDX
JE @@ex
TEST EAX,EAX
JE @@2
TEST EDX,EDX
JE @@3
PUSH EAX
MOVZX EAX,BYTE PTR [EAX]
MOVZX ECX,BYTE PTR [EDX]
SUB EAX,ECX
JE @@m
POP ECX
RET
@@ex: XOR EAX,EAX
RET
@@m: POP EAX
INC EAX
INC EDX
@@0: TEST CL,CL
JE @@5
MOV CL,BYTE PTR [EAX]
MOV CH,BYTE PTR [EDX]
CMP CL,CH
JNE @@ne
TEST CL,CL
JE @@5
MOV CL,BYTE PTR [EAX+1]
MOV CH,BYTE PTR [EDX+1]
CMP CL,CH
JNE @@ne
TEST CL,CL
JE @@5
MOV CL,BYTE PTR [EAX+2]
MOV CH,BYTE PTR [EDX+2]
CMP CL,CH
JNE @@ne
TEST CL,CL
JE @@5
MOV CL,BYTE PTR [EAX+3]
MOV CH,BYTE PTR [EDX+3]
ADD EAX,4
ADD EDX,4
CMP CL,CH
JE @@0
@@ne: MOVZX EAX,CL
MOVZX EDX,CH
SUB EAX,EDX
RET
@@2: TEST EDX,EDX
JE @@7
MOV CH,BYTE PTR [EDX]
TEST CH,CH
JE @@7
NOT EAX
RET
@@3: MOV CL,BYTE PTR [EAX]
TEST CL,CL
JE @@5
MOV EAX,1
RET
@@5: XOR EAX,EAX
@@7:
end;
function G_CompareText(const S1, S2: string): Integer;
asm
CMP EAX,EDX
JE @@ex
TEST EAX,EAX
JE @@2
TEST EDX,EDX
JE @@3
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
JMP @@1
@@ex: XOR EAX,EAX
RET
@@0: TEST AL,AL
JE @@4
INC ESI
INC EDI
@@1: MOVZX EAX,BYTE PTR [ESI]
MOVZX EDX,BYTE PTR [EDI]
CMP AL,DL
JE @@0
MOV AL,BYTE PTR [EAX+ToUpperChars]
MOV DL,BYTE PTR [EDX+ToUpperChars]
CMP AL,DL
JE @@0
MOVZX EAX,AL
MOVZX EDX,DL
SUB EAX,EDX
POP EDI
POP ESI
RET
@@2: TEST EDX,EDX
JE @@7
MOV CH,BYTE PTR [EDX]
TEST CH,CH
JE @@7
NOT EAX
RET
@@3: MOV CL,BYTE PTR [EAX]
TEST CL,CL
JE @@5
MOV EAX,1
RET
@@4: POP EDI
POP ESI
@@5: XOR EAX,EAX
@@7:
end;
function G_CompareText(P1, P2: PChar): Integer;
asm
CMP EAX,EDX
JE @@ex
TEST EAX,EAX
JE @@2
TEST EDX,EDX
JE @@3
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
JMP @@1
@@ex: XOR EAX,EAX
RET
@@0: TEST AL,AL
JE @@4
INC ESI
INC EDI
@@1: MOVZX EAX,BYTE PTR [ESI]
MOVZX EDX,BYTE PTR [EDI]
CMP AL,DL
JE @@0
MOV AL,BYTE PTR [EAX+ToUpperChars]
MOV DL,BYTE PTR [EDX+ToUpperChars]
CMP AL,DL
JE @@0
MOVZX EAX,AL
MOVZX EDX,DL
SUB EAX,EDX
POP EDI
POP ESI
RET
@@2: TEST EDX,EDX
JE @@7
MOV CH,BYTE PTR [EDX]
TEST CH,CH
JE @@7
NOT EAX
RET
@@3: MOV CL,BYTE PTR [EAX]
TEST CL,CL
JE @@5
MOV EAX,1
RET
@@4: POP EDI
POP ESI
@@5: XOR EAX,EAX
@@7:
end;
procedure G_CopyLongs(Source, Dest: Pointer; Count: Cardinal);
asm
@@lp: SUB ECX,16
JS @@nx
MOVQ MM0,[EAX]
MOVQ MM1,[EAX+8]
MOVQ MM2,[EAX+16]
MOVQ MM3,[EAX+24]
MOVQ MM4,[EAX+32]
MOVQ MM5,[EAX+40]
MOVQ MM6,[EAX+48]
MOVQ MM7,[EAX+56]
MOVQ [EDX],MM0
MOVQ [EDX+8],MM1
MOVQ [EDX+16],MM2
MOVQ [EDX+24],MM3
MOVQ [EDX+32],MM4
MOVQ [EDX+40],MM5
MOVQ [EDX+48],MM6
MOVQ [EDX+56],MM7
ADD EAX,64
ADD EDX,64
JMP @@lp
@@nx: ADD ECX,16
PUSH EBX
JMP DWORD PTR @@wV[ECX*4]
@@wV: DD @@w00, @@w01, @@w02, @@w03
DD @@w04, @@w05, @@w06, @@w07
DD @@w08, @@w09, @@w10, @@w11
DD @@w12, @@w13, @@w14, @@w15
@@w15: MOV EBX,[EAX+ECX*4-60]
MOV [EDX+ECX*4-60],EBX
@@w14: MOV EBX,[EAX+ECX*4-56]
MOV [EDX+ECX*4-56],EBX
@@w13: MOV EBX,[EAX+ECX*4-52]
MOV [EDX+ECX*4-52],EBX
@@w12: MOV EBX,[EAX+ECX*4-48]
MOV [EDX+ECX*4-48],EBX
@@w11: MOV EBX,[EAX+ECX*4-44]
MOV [EDX+ECX*4-44],EBX
@@w10: MOV EBX,[EAX+ECX*4-40]
MOV [EDX+ECX*4-40],EBX
@@w09: MOV EBX,[EAX+ECX*4-36]
MOV [EDX+ECX*4-36],EBX
@@w08: MOV EBX,[EAX+ECX*4-32]
MOV [EDX+ECX*4-32],EBX
@@w07: MOV EBX,[EAX+ECX*4-28]
MOV [EDX+ECX*4-28],EBX
@@w06: MOV EBX,[EAX+ECX*4-24]
MOV [EDX+ECX*4-24],EBX
@@w05: MOV EBX,[EAX+ECX*4-20]
MOV [EDX+ECX*4-20],EBX
@@w04: MOV EBX,[EAX+ECX*4-16]
MOV [EDX+ECX*4-16],EBX
@@w03: MOV EBX,[EAX+ECX*4-12]
MOV [EDX+ECX*4-12],EBX
@@w02: MOV EBX,[EAX+ECX*4-8]
MOV [EDX+ECX*4-8],EBX
@@w01: MOV EBX,[EAX+ECX*4-4]
MOV [EDX+ECX*4-4],EBX
@@w00: POP EBX
EMMS
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clSspiUtils;
interface
resourcestring
SclSimpleNotSupported = 'Not supported.';
SSPIErrorLoadLibrary = 'Could not load the dll (schannel.dll, security.dll or secur32.dll)';
SSPIErrorFuncTableInit = 'Could not get security initialization routine';
SSPIErrorSecPackage = 'Could not initialize the security package';
SSPIErrorAcquireFailed = 'AcquireCredentials failed';
SSPIErrorPackageNotFound = 'None of needed security package was found';
SSPIErrorQueryPackageInfoFailed = 'Could not query package information';
SSPIErrorCertificateNotFound = 'Error finding certificate chain';
SSPIErrorQueryRemoteCertificate = 'Error querying remote server certificate';
SSPIErrorQueryLocalCertificate = 'Error querying local certificate';
SSPIErrorRemoteCertificateNotTrusted = 'Error authenticating server credentials';
SSPIErrorWhileTrustPerforming = 'Error occured when authenticating server credentials';
SSPIErrorINVALIDHANDLE = 'The handle specified is invalid';
SSPIErrorUNSUPPORTED_FUNCTION = 'The function requested is not supported';
SSPIErrorTARGET_UNKNOWN = 'The specified target is unknown or unreachable';
SSPIErrorINTERNAL_ERROR = 'The Local Security Authority cannot be contacted';
SSPIErrorSECPKG_NOT_FOUND = 'The requested security package does not exist';
SSPIErrorNOT_OWNER = 'The caller is not the owner of the desired credentials';
SSPIErrorCANNOT_INSTALL = 'The security package failed to initialize, and cannot be installed';
SSPIErrorINVALID_TOKEN = 'The token supplied to the function is invalid';
SSPIErrorCANNOT_PACK = 'The security package is not able to marshall the logon buffer, so the logon attempt has failed';
SSPIErrorQOP_NOT_SUPPORTED = 'The per-message Quality of Protection is not supported by the security package';
SSPIErrorNO_IMPERSONATION = 'The security context does not allow impersonation of the client';
SSPIErrorLOGON_DENIED = 'The logon attempt failed';
SSPIErrorUNKNOWN_CREDENTIALS = 'The credentials supplied to the package were not recognized';
SSPIErrorNO_CREDENTIALS = 'No credentials are available in the security package';
SSPIErrorMESSAGE_ALTERED = 'The message supplied for verification has been altered';
SSPIErrorOUT_OF_SEQUENCE = 'The message supplied for verification is out of sequence';
SSPIErrorNO_AUTHENTICATING_AUTHORITY
= 'No authority could be contacted for authentication';
SSPIErrorBAD_PKGID = 'The requested security package does not exist';
SSPIErrorOUTOFMEMORY = 'Out of memory';
SSPIErrorUnknownError = 'The unknown error was occured: %x';
SSPIErrorCERTEXPIRED ='A required certificate is not within its validity ' +
'period when verifying against the current system clock or the timestamp in the signed file';
SSPIErrorCERTVALIDITYPERIODNESTING ='The validity periods of the certification chain do not ' +
'nest correctly';
SSPIErrorCERTROLE ='A certificate that can only be used as an end-entity '+
'is being used as a CA or visa versa';
SSPIErrorCERTPATHLENCONST ='A path length constraint in the certification chain has been violated';
SSPIErrorCERTCRITICAL ='A certificate contains an unknown extension that is marked ''critical''';
SSPIErrorCERTPURPOSE ='A certificate being used for a purpose other than the ones specified by its CA';
SSPIErrorCERTISSUERCHAINING ='A parent of a given certificate in fact did not issue that child certificate';
SSPIErrorCERTMALFORMED ='A certificate is missing or has an empty value for an important field, such as a subject or issuer name';
SSPIErrorCERTUNTRUSTEDROOT ='A certificate chain processed correctly, but terminated in a root certificate which is not trusted by the trust provider';
SSPIErrorCERTCHAINING ='An internal certificate chaining error has occurred';
SSPIErrorCERTFAIL ='Generic trust failure';
SSPIErrorCERTREVOKED ='A certificate was explicitly revoked by its issuer';
SSPIErrorCERTUNTRUSTEDTESTROOT ='The certification path terminates with the test root which is not trusted with the current policy settings';
SSPIErrorCERTREVOCATION_FAILURE='The revocation process could not continue - the certificate(s) could not be checked';
SSPIErrorCERTCN_NO_MATCH ='The certificate''s CN name does not match the passed value';
SSPIErrorCERTWRONG_USAGE ='The certificate is not valid for the requested usage';
implementation
end.
|
unit LanguageSetUnit;
interface
uses
Classes,
SysUtils,
LanguageStringMapUnit,
LanguageUnit, LanguageListUnit;
type
{ TLanguageSet }
TLanguageSet = class
protected
FLanguages: TLanguageList;
FLanguageIds: TStringList;
public
property Languages: TLanguageList read FLanguages;
property LanguageIds: TStringList read FLanguageIds;
constructor Create;
function ToDebugText: string;
function InconsistenciesToDebugText: string;
function FindLanguage(const aLanguageId: string): TLanguage;
destructor Destroy; override;
end;
implementation
{ TLanguageSet }
constructor TLanguageSet.Create;
begin
FLanguages := TLanguageList.Create;
FLanguageIds := TStringList.Create;
end;
function TLanguageSet.ToDebugText: string;
var
i: Integer;
begin
result :=
'Languages: '
+ '(ids: ' + IntToStr(LanguageIds.Count) + ', langs: ' + IntToStr(Languages.Count) + ')'
+ LineEnding;
for i := 0 to Languages.Count - 1 do
result += '[' + LanguageIds[i] + ']' + LineEnding + Languages[i].ToDebugText;
end;
function TLanguageSet.InconsistenciesToDebugText: string;
var
r: string;
procedure checkItBack(const aIterator: TStringMap.TIterator);
var
key, value: string;
begin
repeat
key := aIterator.Key;
value := aIterator.Value;
if not Languages[0].ItemExists[key] then
r += 'No such entry in the default language: "' + key + '"';
until not aIterator.Next;
end;
procedure checkBack(const aIndex: integer);
var
languageIterator: TStringMap.TIterator;
begin
languageIterator := Languages[aIndex].Storage.Iterator;
if
languageIterator <> nil
then
begin
checkItBack(languageIterator);
languageIterator.Free;
end;
end;
procedure checkItForward(const aKey: string);
var
i: Integer;
begin
for i := 0 to Languages.Count - 1 do
begin
if not Languages[i].ItemExists[aKey] then
r += LanguageIds[i] + ' does not contain "' + aKey + '"' + LineEnding;
end;
end;
procedure checkForward;
var
key: string;
languageIterator: TStringMap.TIterator;
begin
languageIterator := Languages[0].Storage.Iterator;
if
languageIterator <> nil
then
begin
repeat
key := languageIterator.Key;
checkItForward(key);
until not languageIterator.Next;
languageIterator.Free;
end;
end;
var
i: Integer;
begin
if
Languages.Count = 1
then
r :=
'There is only one language;'
+ ' it is impossible to search for inconsistencies.'
else
begin
r := '';
for i := 1 to Languages.Count - 1 do
checkBack(i);
if
r = ''
then
r := 'No reversed inconsistencies found.' + LineEnding;
checkForward;
end;
end;
function TLanguageSet.FindLanguage(const aLanguageId: string): TLanguage;
var
i: Integer;
begin
if
LanguageIds.Find(aLanguageId, i)
then
result := Languages[i]
else
result := nil;
end;
destructor TLanguageSet.Destroy;
begin
LanguageIds.Free;
Languages.ReleaseContent;
Languages.Free;
inherited Destroy;
end;
end.
|
unit DAW.Controller;
interface
uses
Types,
Menus,
Windows,
Graphics,
ImgList,
Dialogs,
DAW.View.Main,
Classes;
type
TDAWController = class(TInterfacedObject)
private
FMenuItem: TMenuItem;
FDialog: TForm2;
FIcon: TIcon;
procedure HandleClickDelphinus(Sender: TObject);
procedure InstallMenu();
procedure UninstallMenu();
function GetIndexOfConfigureTools(AToolsMenu: TMenuItem): Integer;
public
constructor Create();
destructor Destroy(); override;
end;
implementation
uses
ToolsAPI;
const
CToolsMenu = 'ToolsMenu';
CConfigureTools = 'ToolsToolsItem'; // heard you like tools....
{ TDelphinusController }
constructor TDAWController.Create;
var
LBitmap: TBitmap;
begin
inherited;
FIcon := TIcon.Create();
FIcon.SetSize(16, 16);
// FIcon.Handle := LoadImage(HInstance, Ico_Delphinus, IMAGE_ICON, 0, 0, 0);
LBitmap := TBitmap.Create();
try
LBitmap.SetSize(24, 24);
LBitmap.Canvas.Draw((24 - FIcon.Width) div 2,
(24 - FIcon.Height) div 2, FIcon);
// SplashScreenServices.AddPluginBitmap(CVersionedDelphinus, LBitmap.Handle);
finally
LBitmap.Free;
end;
InstallMenu();
FDialog := TForm2.Create(nil);
end;
destructor TDAWController.Destroy;
begin
UninstallMenu();
FDialog.Free;
FIcon.Free;
inherited;
end;
function TDAWController.GetIndexOfConfigureTools(AToolsMenu: TMenuItem)
: Integer;
var
i: Integer;
begin
Result := AToolsMenu.Count;
for i := 0 to AToolsMenu.Count - 1 do
begin
if AToolsMenu.Items[i].Name = CConfigureTools then
Exit(i);
end;
end;
procedure TDAWController.HandleClickDelphinus(Sender: TObject);
begin
FDialog.Show();
end;
procedure TDAWController.InstallMenu;
var
LItem: TMenuItem;
LService: INTAServices;
i, LIndex: Integer;
LImageList: TCustomImageList;
begin
LService := BorlandIDEServices as INTAServices;
for i := LService.MainMenu.Items.Count - 1 downto 0 do
begin
LItem := LService.MainMenu.Items[i];
if LItem.Name = CToolsMenu then
begin
FMenuItem := TMenuItem.Create(LService.MainMenu);
FMenuItem.Caption := 'Adb WiFi';
FMenuItem.Name := 'DelphiAdbWiFiMenu';
FMenuItem.OnClick := HandleClickDelphinus;
LIndex := GetIndexOfConfigureTools(LItem);
LItem.Insert(LIndex, FMenuItem);
LImageList := LItem.GetImageList;
if Assigned(LImageList) then
begin
FMenuItem.ImageIndex := LImageList.AddIcon(FIcon);
end;
Break;
end;
end;
end;
procedure TDAWController.UninstallMenu;
begin
if Assigned(FMenuItem) then
begin
FMenuItem.Free;
end;
end;
end.
|
unit typeDefBase;
{Модуль базового класса.}
interface
uses
SysUtils,
Classes;
// Windows;
type
TAppItem = class
private
_id : string;
_name : string;
public
// destructor Destroy();
published
property id : string read _id write _id;
property name : string read _name write _name;
end;
type
TAppFileBase = class
protected
_fileName : string; // Имя файла
_fileArray : TBytes; // Байтовый массив, считанный из вызываемого файла
_fileStrList : TStringList; // Строковый список, полученный из байтового массива
_firstByteFromArray : Byte; // Первый байт байтового массива
public
constructor Create(str: string); overload; virtual; abstract;
constructor Create(); overload; virtual; abstract;
destructor Destroy; override;
procedure CreateFileArray(); virtual;
procedure CreateListFromArray(); virtual; abstract;
published
property fileStrList: TStringList read _fileStrList;
end;
implementation
//********* TAppItem *******
//*******************************
//********* TAppFileBase *******
//*******************************
// Обязательно очищаем объект-поле, иначе получим утечку памяти.
destructor TAppFileBase.Destroy;
begin
FreeAndNil(_fileStrList);
inherited;
end;
// Процедура побайтно считывает файл в массив pArr типа TBytes и
// возвращает его через параметр.
procedure TAppFileBase.CreateFileArray();
var
pFS: TFileStream;
begin
pFS := TFileStream.Create(_fileName, fmOpenRead);
try
SetLength(_fileArray, pFS.Size);
pFS.ReadBuffer(Pointer(_fileArray)^, Length(_fileArray));
finally
pFS.Free;
end;
end;
end.
|
unit uContainer;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
Data.DB, FireDAC.Comp.Client, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef,
FireDAC.Phys.SQLite, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.Comp.DataSet;
type
TContainer = class(TDataModule)
SQLite: TFDConnection;
SQLiteDriver: TFDPhysSQLiteDriverLink;
ProdutosSource: TDataSource;
Produtos: TFDQuery;
CategoriasSource: TDataSource;
Categorias: TFDQuery;
Imagem: TFDQuery;
procedure SQLiteBeforeConnect(Sender: TObject);
procedure SQLiteAfterConnect(Sender: TObject);
procedure ProdutosBeforeInsert(DataSet: TDataSet);
procedure ProdutosAfterPost(DataSet: TDataSet);
procedure ProdutosBeforeDelete(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
function Categorias :String;
var
Container: TContainer;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
uses
System.IOUtils, uMain, VCL.Helpers, VCL.Image.Base64;
function Categorias :String;
begin
Result := Container.SQLite.ExecSQLScalar('SELECT COALESCE(Group_Concat(Categoria),"") Categorias FROM (SELECT Categoria FROM produtos GROUP BY Categoria)')
end;
procedure TContainer.ProdutosAfterPost(DataSet: TDataSet);
begin
Imagem.Open('SELECT * FROM imagem WHERE _id = ' + Produtos.Fields[0].AsString);
if Imagem.RecordCount = 0 then
Imagem.Append
else
Imagem.Edit;
Imagem.FieldByName('_id').AsString := Produtos.Fields[0].AsString;
Imagem.FieldByName('Base64').AsString := FormMain.ImagemProduto.Base64;
Imagem.Post;
FormMain.RT
.Collection('catalogo').Collection(Produtos.FieldByName('Categoria').AsString)
.Key(Produtos.Fields[0].AsString)
.AddPair('_id',Produtos.FieldByName('_id').AsString)
.AddPair('produto',Produtos.FieldByName('Produto').AsString)
.AddPair('descricao',Produtos.FieldByName('Descricao').AsString)
.AddPair('categoria',Produtos.FieldByName('Categoria').AsString)
.AddPair('destaque',Produtos.FieldByName('Destaque').AsBoolean)
.AddPair('valor',Produtos.FieldByName('Valor').AsCurrency)
.Update;
FormMain.RT
.Collection('imagens')
.Key(Produtos.Fields[0].AsString)
.AddPair('_id',Produtos.FieldByName('_id').AsString)
.AddPair('base64', Imagem.FieldByName('Base64').AsString)
.Update;
end;
procedure TContainer.ProdutosBeforeDelete(DataSet: TDataSet);
begin
FormMain.RT
.Collection('produtos')
.Key(Produtos.Fields[0].AsString).Delete;
FormMain.RT
.Collection('imagens')
.Key(Produtos.Fields[0].AsString).Delete;
end;
procedure TContainer.ProdutosBeforeInsert(DataSet: TDataSet);
begin
FormMain.CarregaCategoria;
end;
procedure TContainer.SQLiteAfterConnect(Sender: TObject);
begin
TFDConnection(Sender).ExecSQL('CREATE TABLE IF NOT EXISTS produtos ('+
' _id INTEGER PRIMARY KEY AUTOINCREMENT, '+
' Produto VARCHAR(50),'+
' Descricao VARCHAR(100),'+
' Categoria VARCHAR(50),'+
' Destaque BOOLEAN,'+
' Valor DECIMAL(15,2));');
TFDConnection(Sender).ExecSQL('CREATE TABLE IF NOT EXISTS imagem ('+
' _id INTEGER PRIMARY KEY AUTOINCREMENT, '+
' Base64 TEXT);');
Produtos.Open('SELECT * FROM produtos');
end;
procedure TContainer.SQLiteBeforeConnect(Sender: TObject);
begin
TFDConnection(Sender).Params.DriverID := 'SQLite';
TFDConnection(Sender).Params.Database := TPath.Combine(TPath.GetDocumentsPath, 'catalogo.db');
end;
end.
|
unit ActionsUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, ComObj, SPIClient_TLB;
type
TfrmActions = class(TForm)
pnlActions: TPanel;
btnAction1: TButton;
btnAction2: TButton;
lblAmount: TLabel;
edtAmount: TEdit;
pnlFlow: TPanel;
lblFlow: TLabel;
lblFlowStatus: TLabel;
lblFlowMessage: TLabel;
richEdtFlow: TRichEdit;
btnAction3: TButton;
procedure btnAction1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure btnAction2Click(Sender: TObject);
procedure btnAction3Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
constructor Create(AOwner: TComponent; _Spi: SPIClient_TLB.Spi); overload;
end;
var
Spi: SPIClient_TLB.Spi;
ComWrapper: SPIClient_TLB.ComWrapper;
implementation
{$R *.dfm}
uses MainUnit;
constructor TfrmActions.Create(AOwner: TComponent; _Spi: SPIClient_TLB.Spi);
begin
inherited Create(AOwner);
Spi := _Spi;
ComWrapper := CreateComObject(CLASS_ComWrapper) AS SPIClient_TLB.ComWrapper;
end;
procedure DoPurchase;
var
purchase: SPIClient_TLB.InitiateTxResult;
amount: Integer;
begin
amount := StrToInt(frmActions.edtAmount.Text);
purchase := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
purchase := Spi.InitiatePurchaseTx(ComWrapper.Get_Id('prchs'), amount);
if (purchase.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# Purchase Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate purchase: ' +
purchase.Message + '. Please Retry.');
end;
end;
procedure DoRefund;
var
refund: SPIClient_TLB.InitiateTxResult;
amount: Integer;
begin
amount := StrToInt(frmActions.edtAmount.Text);
refund := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
refund := Spi.InitiateRefundTx(ComWrapper.Get_Id('rfnd'), amount);
if (refund.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# Refund Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate refund: ' +
refund.Message + '. Please Retry.');
end;
end;
procedure TfrmActions.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmActions.FormCreate(Sender: TObject);
begin
ComWrapper := CreateComObject(CLASS_ComWrapper) AS SPIClient_TLB.ComWrapper;
end;
procedure TfrmActions.FormHide(Sender: TObject);
begin
frmMain.Enabled := True;
end;
procedure TfrmActions.FormShow(Sender: TObject);
begin
lblFlowStatus.Caption := ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow);
end;
procedure TfrmActions.btnAction1Click(Sender: TObject);
begin
if (btnAction1.Caption = 'Confirm Code') then
begin
Spi.PairingConfirmCode;
end
else if (btnAction1.Caption = 'Cancel Pairing') then
begin
Spi.PairingCancel;
frmMain.lblStatus.Color := clRed;
end
else if (btnAction1.Caption = 'Cancel') then
begin
Spi.CancelTransaction;
end
else if (btnAction1.Caption = 'OK') then
begin
Spi.AckFlowEndedAndBackToIdle;
frmActions.richEdtFlow.Lines.Clear;
frmActions.lblFlowMessage.Caption := 'Select from the options below';
TMyWorkerThread.Create(false);
frmMain.Enabled := True;
frmMain.btnPair.Enabled := True;
frmMain.edtPosID.Enabled := True;
frmMain.edtEftposAddress.Enabled := True;
Hide;
end
else if (btnAction1.Caption = 'OK-Unpaired') then
begin
Spi.AckFlowEndedAndBackToIdle;
frmActions.richEdtFlow.Lines.Clear;
frmMain.Enabled := True;
frmMain.btnPair.Enabled := True;
frmMain.edtPosID.Enabled := True;
frmMain.edtEftposAddress.Enabled := True;
frmMain.btnPair.Caption := 'Pair';
frmMain.pnlActions.Visible := False;
frmMain.lblStatus.Color := clRed;
Hide;
end
else if (btnAction1.Caption = 'Accept Signature') then
begin
Spi.AcceptSignature(True);
end
else if (btnAction1.Caption = 'Retry') then
begin
Spi.AckFlowEndedAndBackToIdle;
frmActions.richEdtFlow.Lines.Clear;
if (Spi.CurrentTxFlowState.type_ = TransactionType_Purchase) then
begin
DoPurchase;
end
else
begin
frmActions.lblFlowStatus.Caption :=
'Retry by selecting from the options';
TMyWorkerThread.Create(false);
end;
end
else if (btnAction1.Caption = 'Purchase') then
begin
DoPurchase;
end
else if (btnAction1.Caption = 'Refund') then
begin
DoRefund;
end;
end;
procedure TfrmActions.btnAction2Click(Sender: TObject);
begin
if (btnAction2.Caption = 'Cancel Pairing') then
begin
Spi.PairingCancel;
frmMain.lblStatus.Color := clRed;
end
else if (btnAction2.Caption = 'Decline Signature') then
begin
Spi.AcceptSignature(False);
end
else if (btnAction2.Caption = 'Cancel') then
begin
Spi.AckFlowEndedAndBackToIdle;
frmActions.richEdtFlow.Lines.Clear;
TMyWorkerThread.Create(false);
frmMain.Enabled := True;
Hide
end;
end;
procedure TfrmActions.btnAction3Click(Sender: TObject);
begin
if (btnAction3.Caption = 'Cancel') then
begin
Spi.CancelTransaction;
end;
end;
end.
|
unit VOpDivRecType07Form;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
VCustomRecordForm, StdCtrls, ExtCtrls, Mask, ComCtrls, ToolEdit, CurrEdit,
COpDivSystemRecord, COpDivRecType07, Menus, Buttons ;
type
TOpDivRecType07Form = class(TCustomRecordForm)
vencimientoLabel: TLabel;
Label6: TLabel;
IdSubsistemaPresentacionEdit: TMaskEdit;
Label7: TLabel;
RefInicSubsEdit: TMaskEdit;
Label8: TLabel;
Label9: TLabel;
FigEntidadPresentaEdit: TMaskEdit;
Label4: TLabel;
pagoParcialCheckBox: TCheckBox;
nominalInicialLabel: TLabel;
NominalInicialEdit: TRxCalcEdit;
ImportePagadoEdit: TRxCalcEdit;
Label12: TLabel;
vencimientoEdit: TDateEdit;
Label13: TLabel;
devolucionEdit: TDateEdit;
Label15: TLabel;
ComisionDevolucionEdit: TRxCalcEdit;
Label16: TLabel;
conceptoComplementarioEdit: TEdit;
vencimientoALaVistaCheckBox: TCheckBox;
procedure vencimientoEditExit(Sender: TObject);
procedure NominalInicialEditExit(Sender: TObject);
procedure IdSubsistemaPresentacionEditExit(Sender: TObject);
procedure RefInicSubsEditExit(Sender: TObject);
procedure pagoParcialCheckBoxClick(Sender: TObject);
procedure ImportePagadoEditExit(Sender: TObject);
procedure devolucionEditExit(Sender: TObject);
procedure ComisionDevolucionEditExit(Sender: TObject);
procedure conceptoComplementarioEditExit(Sender: TObject);
procedure FigEntidadPresentaEditExit(Sender: TObject);
procedure vencimientoALaVistaCheckBoxClick(Sender: TObject);
private
{ Private declarations }
protected
procedure onGeneralChange( SystemRecord: TOpDivSystemRecord ); override;
public
{ Public declarations }
end;
var
OpDivRecType07Form: TOpDivRecType07Form;
implementation
{$R *.DFM}
(*************
MÉTODOS PROTEGIDOS
*************)
procedure TOpDivRecType07Form.onGeneralChange( SystemRecord: TOpDivSystemRecord );
begin
inherited;
with TOpDivRecType07( SystemRecord ) do
begin
vencimientoALaVistaCheckBox.Checked := VencimientoALaVista;
if (FechaVencimiento > 0.0) and (not VencimientoALaVista) then
vencimientoEdit.Date := FechaVencimiento
else
vencimientoEdit.Clear();
vencimientoLabel.Enabled := not VencimientoALaVista;
vencimientoEdit.Enabled := not VencimientoALaVista;
NominalInicialEdit.Value := NominalInicial;
IdSubsistemaPresentacionEdit.Text := trim( IDSubsistemaPresentacion );
RefInicSubsEdit.Text := trim( RefInicialSubsistema );
pagoParcialCheckBox.Checked := ( PagoParcial = '1' );
ImportePagadoEdit.Value := ImportePagado;
if FechaDevolucion > 0.0 then
DevolucionEdit.Date := FechaDevolucion
else
DevolucionEdit.Clear();
ComisionDevolucionEdit.Value := ComisionDevolucion;
conceptoComplementarioEdit.Text := trim( ConceptoComplementario );
FigEntidadPresentaEdit.Text := trim( FigEntidadPresenta );
// activar/desactivar
NominalInicialLabel.Enabled := (PagoParcial = '1');
NominalInicialEdit.Enabled := (PagoParcial = '1');
end;
end;
(*************
EVENTOS
*************)
procedure TOpDivRecType07Form.vencimientoEditExit(Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).FechaVencimiento := TDateEdit( Sender ).Date;
end;
procedure TOpDivRecType07Form.NominalInicialEditExit(Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).NominalInicial := TRxCalcEdit( Sender ).Value;
end;
procedure TOpDivRecType07Form.IdSubsistemaPresentacionEditExit(
Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).IDSubsistemaPresentacion := TEdit( Sender ).Text;
end;
procedure TOpDivRecType07Form.RefInicSubsEditExit(Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).RefInicialSubsistema := TEdit( Sender ).Text ;
end;
procedure TOpDivRecType07Form.pagoParcialCheckBoxClick(Sender: TObject);
begin
inherited;
if TCheckBox( Sender ).Checked then
TOpDivRecType07( FSystemRecord ).PagoParcial := '1'
else
TOpDivRecType07( FSystemRecord ).PagoParcial := '2'
end;
procedure TOpDivRecType07Form.ImportePagadoEditExit(Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).ImportePagado := TRxCalcEdit( Sender ).Value;
end;
procedure TOpDivRecType07Form.devolucionEditExit(Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).FechaDevolucion := TDateEdit( Sender ).Date ;
end;
procedure TOpDivRecType07Form.ComisionDevolucionEditExit(Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).ComisionDevolucion := TRxCalcEdit( Sender ).Value;
end;
procedure TOpDivRecType07Form.conceptoComplementarioEditExit(
Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).ConceptoComplementario := TEdit( Sender ).Text;
end;
procedure TOpDivRecType07Form.FigEntidadPresentaEditExit(Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).FigEntidadPresenta := TEdit( Sender ).Text ;
end;
procedure TOpDivRecType07Form.vencimientoALaVistaCheckBoxClick(
Sender: TObject);
begin
inherited;
TOpDivRecType07( FSystemRecord ).VencimientoALaVista := TCheckBox( Sender ).Checked ;
end;
end.
|
// MMArchCompare unit and MMArchSimple class
// Part of mmarch
// Command line tool to handle Heroes 3 and Might and Magic 6, 7, 8
// resource archive files (e.g. lod files). Based on GrayFace's MMArchive.
// By Tom CHEN <tomchen.org@gmail.com> (tomchen.org)
// MIT License
// https://github.com/might-and-magic/mmarch
unit MMArchCompare;
interface
uses
Windows, SysUtils, StrUtils, Classes, RSLod, MMArchMain, MMArchPath, RSQ;
procedure colorWriteLn(str: string; color: word);
function compareFile(oldFile, newFile: string): boolean;
function compareInArchiveFile(oldRaw, newRaw: TRSMMFiles; oldIndex, newIndex: integer): boolean;
procedure compareArchive(oldArchive, newArchive: string; var addedFileList, modifiedFileList, deletedFileList: TStringList);
procedure generateScript(deletedFolderList, deletedNonResFileList, deletedResFileList, modifiedArchiveList: TStringList;
scriptFilePath, diffFileFolderName: string; isNsis: boolean);
function compareBase(oldArchiveOrFolder, newArchiveOrFolder, copyToFolder: string;
var deletedFolderList0, deletedNonResFileList, deletedResFileList, modifiedArchiveList: TStringList): boolean; overload;
function compareBase(oldArchiveOrFolder, newArchiveOrFolder: string; copyToFolder: string = ''): boolean; overload;
procedure getListFromDiffFiles(oldDiffFileFolder: string; var deletedFolderList, deletedNonResFileList, deletedResFileList, modifiedArchiveList: TStringList);
const
ToDeleteExt: string = '.todelete';
MMArchiveExt: string = '.mmarchive';
resourcestring
IncorrectMMArchive = 'Incorrect MM Archive files';
FilesAreSame = 'Files are exactly the same';
FoldersAreSame = 'Folders are exactly the same';
IncorrectFoldersOrMMArchives = 'Please specify two folders, or two MM Archive files';
implementation
procedure colorWriteLn(str: string; color: word);
var
ConOut: THandle;
BufInfo: TConsoleScreenBufferInfo;
begin
ConOut := TTextRec(Output).Handle;
GetConsoleScreenBufferInfo(ConOut, BufInfo);
SetConsoleTextAttribute(TTextRec(Output).Handle, color);
WriteLn(str);
SetConsoleTextAttribute(ConOut, BufInfo.wAttributes);
end;
// private
procedure colorPrintFileList(addedFileList, modifiedFileList, deletedFileList, addedFolderList, deletedFolderList: TStringList); overload;
var
allList: TStringList;
elTemp: string;
i: integer;
color: word;
begin
allList := TStringList.Create;
if addedFolderList <> nil then // addedFolderList, deletedFolderList are not nil
begin
for elTemp in addedFolderList do
allList.Add(elTemp + slash + ' +');
for elTemp in deletedFolderList do
allList.Add(elTemp + slash + ' -');
end;
for elTemp in addedFileList do
allList.Add(elTemp + ' +');
for elTemp in modifiedFileList do
allList.Add(elTemp + ' m');
for elTemp in deletedFileList do
allList.Add(elTemp + ' -');
allList.Sort;
for i := 0 to allList.Count - 1 do
begin
elTemp := allList[i];
allList[i] := '[' + elTemp[length(elTemp)] + '] ' +
System.Copy(elTemp, 1, length(elTemp) - 2);
end;
WriteLn;
for elTemp in allList do
begin
if System.Copy(elTemp, 1, 3) = '[+]' then
color := FOREGROUND_GREEN or FOREGROUND_INTENSITY
else
if System.Copy(elTemp, 1, 3) = '[-]' then
color := FOREGROUND_RED or FOREGROUND_INTENSITY
else // '[m]'
color := FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY;
if AnsiContainsStr(elTemp, archResSeparator) then
color := color or BACKGROUND_BLUE;
colorWriteLn(elTemp, color);
end;
allList.Free;
end;
// private
procedure colorPrintFileList(addedFileList, modifiedFileList, deletedFileList: TStringList); overload;
var
addedFolderList, deletedFolderList: TStringList;
begin
addedFolderList := nil;
deletedFolderList := nil;
colorPrintFileList(addedFileList, modifiedFileList, deletedFileList, addedFolderList, deletedFolderList);
end;
function compareFile(oldFile, newFile: string): boolean;
var
memOld, memNew: TMemoryStream;
begin
memOld := TMemoryStream.Create;
memNew := TMemoryStream.Create;
memOld.LoadFromFile(oldFile);
memNew.LoadFromFile(newFile);
Result := (memOld.Size = memNew.Size) and CompareMem(memOld.Memory, memNew.Memory, memOld.Size);
memOld.Free;
memNew.Free;
end;
function compareInArchiveFile(oldRaw, newRaw: TRSMMFiles; oldIndex, newIndex: integer): boolean;
// mostly from TForm1.DoCompare in Unit1.pas in GrayFace's LodCompare's source files
var
r: TStream;
mem1, mem2: TMemoryStream;
begin
mem1 := TMemoryStream.Create;
mem2 := TMemoryStream.Create;
Result := (newRaw.UnpackedSize[newIndex] = oldRaw.UnpackedSize[oldIndex]);
if Result then
begin
// raw compare
Result := newRaw.Size[newIndex] = oldRaw.Size[oldIndex];
if Result then
begin
mem1.SetSize(newRaw.Size[newIndex]);
r := newRaw.GetAsIsFileStream(newIndex);
try
r.ReadBuffer(mem1.Memory^, mem1.Size);
finally
newRaw.FreeAsIsFileStream(newIndex, r);
end;
mem2.SetSize(newRaw.Size[newIndex]);
r := oldRaw.GetAsIsFileStream(oldIndex);
try
r.ReadBuffer(mem2.Memory^, mem2.Size);
finally
oldRaw.FreeAsIsFileStream(oldIndex, r);
end;
Result := CompareMem(mem1.Memory, mem2.Memory, mem1.Size);
end;
// compare unpacked
if not Result and (newRaw.IsPacked[newIndex] or oldRaw.IsPacked[oldIndex]) then
try
if newRaw.IsPacked[newIndex] then
begin
mem1.SetSize(newRaw.UnpackedSize[newIndex]);
mem1.Position := 0;
newRaw.RawExtract(newIndex, mem1);
end;
if oldRaw.IsPacked[oldIndex] then
begin
mem2.SetSize(oldRaw.UnpackedSize[oldIndex]);
mem2.Position := 0;
oldRaw.RawExtract(oldIndex, mem2);
end;
Result := (mem1.Size = mem2.Size) and CompareMem(mem1.Memory, mem2.Memory, mem1.Size);
except
Result := false;
end;
end;
mem1.Free;
mem2.Free;
end;
procedure compareArchive(oldArchive, newArchive: string; var addedFileList, modifiedFileList, deletedFileList: TStringList);
var
oldArchi, newArchi: TRSMMArchive;
oldFFiles, newFFiles: TRSMMFiles;
oldFileNameList, oldFileNameListTemp: TStringList;
i, nTemp: integer;
elTemp: string;
begin
oldArchi := RSLoadMMArchive(oldArchive);
oldFFiles := oldArchi.RawFiles;
oldFileNameList := TStringList.Create;
for i := 0 to oldFFiles.Count - 1 do
oldFileNameList.Add(oldFFiles.Name[i]);
newArchi := RSLoadMMArchive(newArchive);
newFFiles := newArchi.RawFiles;
oldFileNameListTemp := TStringList.Create;
oldFileNameListTemp.Assign(oldFileNameList);
for i := 0 to newFFiles.Count - 1 do
begin
elTemp := newFFiles.Name[i];
nTemp := oldFileNameList.IndexOf(elTemp);
if nTemp = -1 then
addedFileList.Add(elTemp)
else
begin
oldFileNameList.Delete(nTemp);
if not compareInArchiveFile(oldArchi.RawFiles, newArchi.RawFiles, oldFileNameListTemp.IndexOf(elTemp), i) then
modifiedFileList.Add(elTemp);
end;
end;
for elTemp in oldFileNameList do
deletedFileList.Add(elTemp);
oldFileNameList.Free;
oldFileNameListTemp.Free;
end;
procedure generateScript(deletedFolderList, deletedNonResFileList, deletedResFileList, modifiedArchiveList: TStringList;
scriptFilePath, diffFileFolderName: string; isNsis: boolean);
// isNsis is true : NSIS
// isNsis is false: Batch
var
scriptString, elTemp, strTemp: string;
tslTemp: TStringList;
noRes: boolean;
begin
deletedFolderList.Sort;
deletedNonResFileList.Sort;
deletedResFileList.Sort;
modifiedArchiveList.Sort;
noRes := (deletedResFileList.Count = 0) and (modifiedArchiveList.Count = 0);
if isNsis then // NSIS
begin
scriptString := #13#10 +
';--------------------------------'#13#10 +
';Include Modern UI'#13#10 +
'!include "MUI2.nsh"'#13#10 +
#13#10 +
';--------------------------------'#13#10 +
';General'#13#10 +
#13#10 +
';Name and file'#13#10 +
'Name "Might and Magic Patch"'#13#10 +
'OutFile "patch.exe"'#13#10 +
'Unicode True'#13#10 +
'; AutoCloseWindow true'#13#10 +
#13#10 +
'BrandingText "NWC/3DO; Ubisoft"'#13#10 +
#13#10 +
'; !define MUI_ICON "icon.ico"'#13#10 +
#13#10 +
';--------------------------------'#13#10 +
';Default installation folder'#13#10 +
'InstallDir $EXEDIR'#13#10 +
#13#10 +
';Request application privileges for Windows Vista'#13#10 +
'RequestExecutionLevel user'#13#10 +
#13#10 +
';--------------------------------'#13#10 +
';Pages'#13#10 +
#13#10 +
'!insertmacro MUI_PAGE_INSTFILES'#13#10 +
#13#10 +
';--------------------------------'#13#10 +
';Languages'#13#10 +
#13#10 +
'!insertmacro MUI_LANGUAGE "English"'#13#10 +
#13#10 +
';--------------------------------'#13#10 +
';Installer Sections'#13#10 +
#13#10 +
'Section'#13#10 +
#13#10 +
';-----FILE COPYING (MODIFYING, DELETING) STARTS HERE-----'#13#10 +
#13#10 +
' SetOutPath $INSTDIR'#13#10;
if not noRes then
scriptString := scriptString + ' File mmarch.exe'#13#10;
scriptString := scriptString + #13#10;
if deletedFolderList.Count > 0 then
begin
for elTemp in deletedFolderList do
begin
scriptString := scriptString + ' RMDir /r /REBOOTOK "$INSTDIR\' + elTemp + '"'#13#10;
end;
scriptString := scriptString + #13#10;
end;
scriptString := scriptString +' File /r /x *' + ToDeleteExt + ' /x *' + EmptyFolderKeep + ' ' + withTrailingSlash(beautifyPath(diffFileFolderName)) + '*.*'#13#10 +
#13#10;
if deletedNonResFileList.Count > 0 then
begin
for elTemp in deletedNonResFileList do
begin
scriptString := scriptString + ' Delete "' + elTemp + '"'#13#10;
end;
scriptString := scriptString + #13#10;
end;
if deletedResFileList.Count > 0 then
begin
for elTemp in deletedResFileList do
begin
tslTemp := TStringList.Create;
Split(archResSeparator, elTemp, tslTemp);
scriptString := scriptString +
' nsExec::Exec ''mmarch delete "' + tslTemp[0] + '" "' + tslTemp[1] + '"'''#13#10;
end;
scriptString := scriptString + #13#10;
end;
if modifiedArchiveList.Count > 0 then
begin
for elTemp in modifiedArchiveList do
begin
strTemp := System.Copy(elTemp, 1, length(elTemp) - 1);
scriptString := scriptString +
' nsExec::Exec ''mmarch add "' + strTemp + '" "' + strTemp + MMArchiveExt + '\*.*"'''#13#10 +
' RMDir /r /REBOOTOK "$INSTDIR\' + strTemp + MMArchiveExt + '"'#13#10;
end;
scriptString := scriptString + #13#10;
end;
if not noRes then
scriptString := scriptString + ' Delete "mmarch.exe"'#13#10;
scriptString := scriptString +
#13#10 +
';-----FILE COPYING (MODIFYING, DELETING) ENDS HERE-----'#13#10 +
#13#10 +
'SectionEnd'#13#10;
end
else // Batch
begin
scriptString := 'cd %~dp0'#13#10 +
#13#10;
for elTemp in deletedFolderList do
begin
scriptString := scriptString + 'rmdir /s /q "' + elTemp + '"'#13#10;
end;
scriptString := scriptString + #13#10;
scriptString := scriptString +
'(echo ' + ToDeleteExt + ' && echo ' + EmptyFolderKeep + ')>excludelist.txt'#13#10 +
'Xcopy files . /s /e /y /EXCLUDE:excludelist.txt'#13#10 +
'del excludelist.txt'#13#10 +
#13#10;
for elTemp in deletedNonResFileList do
begin
scriptString := scriptString + 'del "' + elTemp + '"'#13#10;
end;
scriptString := scriptString + #13#10;
for elTemp in deletedResFileList do
begin
tslTemp := TStringList.Create;
Split(archResSeparator, elTemp, tslTemp);
scriptString := scriptString +
'mmarch delete "' + tslTemp[0] + '" "' + tslTemp[1] + '"'#13#10;
end;
scriptString := scriptString + #13#10;
for elTemp in modifiedArchiveList do
begin
strTemp := System.Copy(elTemp, 1, length(elTemp) - 1);
scriptString := scriptString +
'mmarch add "' + strTemp + '" "' + strTemp + MMArchiveExt + '\*.*"'#13#10 +
'rmdir /s /q "' + strTemp + MMArchiveExt + '"'#13#10;
end;
end;
StrToFile(scriptFilePath, scriptString);
end;
function hasToDeletedParentFolder(copyToFolder, fileOrFolderPath: string; deletedFolderList: TStringList): boolean;
var
parentFolder: string;
begin
parentFolder := fileOrFolderPath;
repeat
parentFolder := trimCharsRight(ExtractFilePath(parentFolder), '\', '/');
Result := (deletedFolderList.IndexOf(parentFolder) <> -1);
until (parentFolder = '') or Result;
end;
// procedure cleanUpAllParentFolders(copyToFolder, innermostFolderPath: string); // including current folder
// var
// elTemp: string;
// begin
// innermostFolderPath := beautifyPath(innermostFolderPath);
// elTemp := trimCharsRight(innermostFolderPath, '\', '/');
// while elTemp <> '' do
// begin
// if DirectoryExists(copyToFolder + elTemp + ToDeleteExt) then
// begin
// delDir(copyToFolder + elTemp + ToDeleteExt);
// end;
// elTemp := trimCharsRight(ExtractFilePath(elTemp), '\', '/');
// end;
// end;
procedure cleanUpOldFolder(copyToFolder, fileOrFolderPath: string; fileType: integer);
// type:
// 1: [+/m] folder
// 2: [-] folder
// 3: [+/m] file
// 4: [-] file
// 5: [+/m] resourcefile
// 6: [-] resourcefile
var
strTemp: string;
begin
copyToFolder := withTrailingSlash(copyToFolder);
Case fileType of
//1: // folderPath
// cleanUpAllParentFolders(copyToFolder, fileOrFolderPath);
2: // folderPath (without .todelete)
delDir(copyToFolder + fileOrFolderPath);
3: // filePath (or archiveFilePath without .mmarchive)
begin
DeleteFile(copyToFolder + fileOrFolderPath + ToDeleteExt);
// cleanUpAllParentFolders(copyToFolder, fileOrFolderPath);
if MatchStr(AnsiLowerCase(ExtractFileExt(fileOrFolderPath)), supportedExts) then
delDir(copyToFolder + fileOrFolderPath + MMArchiveExt);
end;
4: // filePath (or archiveFilePath without .mmarchive)
begin
DeleteFile(copyToFolder + fileOrFolderPath);
if MatchStr(AnsiLowerCase(ExtractFileExt(fileOrFolderPath)), supportedExts) then
delDir(copyToFolder + fileOrFolderPath + MMArchiveExt);
end;
5: // resourceFilePath (archiveFilePath.mmarchive\resourceFileName)
begin
DeleteFile(copyToFolder + fileOrFolderPath + ToDeleteExt);
strTemp := trimCharsRight(ExtractFilePath(fileOrFolderPath), '\', '/'); // with '.mmarchive'
System.Delete(strTemp, length(strTemp) - 9, 10); // remove '.mmarchive'
DeleteFile(copyToFolder + strTemp + ToDeleteExt);
// cleanUpAllParentFolders(copyToFolder, ExtractFilePath(strTemp));
end;
6: // resourceFilePath (archiveFilePath.mmarchive\resourceFileName without .todelete)
DeleteFile(copyToFolder + fileOrFolderPath);
end;
end;
function compareBase(oldArchiveOrFolder, newArchiveOrFolder, copyToFolder: string;
var deletedFolderList0, deletedNonResFileList, deletedResFileList, modifiedArchiveList: TStringList): boolean; overload;
var
oldFolderList,
newFolderList,
oldFileList,
newFileList,
addedFolderList,
deletedFolderList,
addedFileList,
modifiedFileList,
deletedFileList,
addedFileListTemp,
modifiedFileListTemp,
deletedFileListTemp: TStringList;
elTemp, elTemp2, nameTemp,
oldArchivePath, newArchivePath: string;
oldArchiveOrFolderLen, newArchiveOrFolderLen,
i, nTemp: integer;
archSimpNew: MMArchSimple;
copyToFolderExists : boolean;
begin
oldArchiveOrFolder := beautifyPath(oldArchiveOrFolder);
newArchiveOrFolder := beautifyPath(newArchiveOrFolder);
copyToFolderExists := DirectoryExists(copyToFolder);
if DirectoryExists(oldArchiveOrFolder) and DirectoryExists(newArchiveOrFolder) then // oldArchiveOrFolder and newArchiveOrFolder are folders
begin
oldArchiveOrFolderLen := length(withTrailingSlash(oldArchiveOrFolder));
newArchiveOrFolderLen := length(withTrailingSlash(newArchiveOrFolder));
oldFolderList := TStringList.Create;
newFolderList := TStringList.Create;
addAllFilesToFileList(oldFolderList, oldArchiveOrFolder, 1, true, false);
addAllFilesToFileList(newFolderList, newArchiveOrFolder, 1, true, false);
for i := 0 to oldFolderList.Count - 1 do // remove root from path
begin
elTemp := oldFolderList[i];
System.Delete(elTemp, 1, oldArchiveOrFolderLen);
oldFolderList[i] := elTemp;
end;
for i := 0 to newFolderList.Count - 1 do // remove root from path
begin
elTemp := newFolderList[i];
System.Delete(elTemp, 1, newArchiveOrFolderLen);
newFolderList[i] := elTemp;
end;
oldFileList := TStringList.Create;
newFileList := TStringList.Create;
addAllFilesToFileList(oldFileList, oldArchiveOrFolder, 1, false, false);
addAllFilesToFileList(newFileList, newArchiveOrFolder, 1, false, false);
for i := 0 to oldFileList.Count - 1 do // remove root from path
begin
elTemp := oldFileList[i];
System.Delete(elTemp, 1, oldArchiveOrFolderLen);
oldFileList[i] := elTemp;
end;
for i := 0 to newFileList.Count - 1 do // remove root from path
begin
elTemp := newFileList[i];
System.Delete(elTemp, 1, newArchiveOrFolderLen);
newFileList[i] := elTemp;
end;
addedFolderList := TStringList.Create;
deletedFolderList := TStringList.Create;
for elTemp in newFolderList do // add to added & modified list
begin
nTemp := oldFolderList.IndexOf(elTemp);
if nTemp = -1 then
begin
addedFolderList.Add(elTemp);
if copyToFolder <> '' then // if needs file copy
begin
createDirRecur(withTrailingSlash(copyToFolder) + elTemp);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, elTemp, 1); // [+/m] folder
end;
end
else
oldFolderList.Delete(nTemp);
end;
for elTemp in oldFolderList do // add to deleted list
begin
if not hasToDeletedParentFolder(copyToFolder, elTemp, deletedFolderList) then
deletedFolderList.Add(elTemp);
if copyToFolder <> '' then // if needs file copy
begin
if not hasToDeletedParentFolder(copyToFolder, elTemp, deletedFolderList) then
createDirRecur(withTrailingSlash(copyToFolder) + elTemp + ToDeleteExt);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, elTemp, 2); // [-] folder
end;
end;
addedFileList := TStringList.Create;
modifiedFileList := TStringList.Create;
deletedFileList := TStringList.Create;
for elTemp in newFileList do // add to added & modified list
begin
nTemp := oldFileList.IndexOf(elTemp);
if nTemp = -1 then
begin
addedFileList.Add(elTemp);
if copyToFolder <> '' then // if needs file copy
begin
copyFile0(withTrailingSlash(newArchiveOrFolder) + elTemp, withTrailingSlash(copyToFolder) + elTemp);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, elTemp, 3); // [+/m] file
end;
end
else
begin
oldFileList.Delete(nTemp);
oldArchivePath := withTrailingSlash(beautifyPath(oldArchiveOrFolder)) + elTemp;
newArchivePath := withTrailingSlash(beautifyPath(newArchiveOrFolder)) + elTemp;
if not compareFile(oldArchivePath, newArchivePath) then
if MatchStr(AnsiLowerCase(ExtractFileExt(elTemp)), supportedExts) then // has MM Archive extension and likely MM Archive file
begin
addedFileListTemp := TStringList.Create;
modifiedFileListTemp := TStringList.Create;
deletedFileListTemp := TStringList.Create;
try // try it as if it's MM Archive file
compareArchive(oldArchivePath, newArchivePath,
addedFileListTemp, modifiedFileListTemp, deletedFileListTemp);
archSimpNew := MMArchSimple.load(newArchivePath);
for elTemp2 in addedFileListTemp do
begin
addedFileList.Add(elTemp + archResSeparator + elTemp2);
if copyToFolder <> '' then // if needs file copy
begin
archSimpNew.extract(withTrailingSlash(copyToFolder) + elTemp + MMArchiveExt, elTemp2);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, withTrailingSlash(elTemp + MMArchiveExt) + elTemp2, 5); // [+/m] resourcefile
end;
end;
for elTemp2 in modifiedFileListTemp do
begin
modifiedFileList.Add(elTemp + archResSeparator + elTemp2);
if copyToFolder <> '' then // if needs file copy
begin
archSimpNew.extract(withTrailingSlash(copyToFolder) + elTemp + MMArchiveExt, elTemp2);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, withTrailingSlash(elTemp + MMArchiveExt) + elTemp2, 5); // [+/m] resourcefile
end;
end;
for elTemp2 in deletedFileListTemp do
begin
deletedFileList.Add(elTemp + archResSeparator + elTemp2);
if copyToFolder <> '' then // if needs file copy
begin
createEmptyFile(withTrailingSlash(withTrailingSlash(copyToFolder) + elTemp + MMArchiveExt) + elTemp2 + ToDeleteExt);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, withTrailingSlash(elTemp + MMArchiveExt) + elTemp2, 6); // [-] resourcefile
end;
end;
modifiedFileList.Add(elTemp + archResSeparator);
except // very unlikely to be MM Archive file
modifiedFileList.Add(elTemp);
if copyToFolder <> '' then // if needs file copy
begin
copyFile0(withTrailingSlash(newArchiveOrFolder) + elTemp, withTrailingSlash(copyToFolder) + elTemp);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, elTemp, 3); // [+/m] file
end;
end;
addedFileListTemp.Free;
modifiedFileListTemp.Free;
deletedFileListTemp.Free;
end
else // doesn't have MM Archive extension therefore not MM Archive file
begin
modifiedFileList.Add(elTemp);
if copyToFolder <> '' then // if needs file copy
begin
copyFile0(withTrailingSlash(newArchiveOrFolder) + elTemp, withTrailingSlash(copyToFolder) + elTemp);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, elTemp, 3); // [+/m] file
end;
end;
end;
end;
for elTemp in oldFileList do // add to deleted list
begin
if not hasToDeletedParentFolder(copyToFolder, elTemp, deletedFolderList) then
deletedFileList.Add(elTemp);
if copyToFolder <> '' then // if needs file copy
if not hasToDeletedParentFolder(copyToFolder, elTemp, deletedFolderList) then
createEmptyFile(withTrailingSlash(copyToFolder) + elTemp + ToDeleteExt);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, elTemp, 4); // [-] file
end;
if (addedFileList.Count = 0) and
(modifiedFileList.Count = 0) and
(deletedFileList.Count = 0) and
(addedFolderList.Count = 0) and
(deletedFolderList.Count = 0) then
begin
WriteLn(FoldersAreSame);
Result := true;
end
else
begin
colorPrintFileList(addedFileList, modifiedFileList, deletedFileList, addedFolderList, deletedFolderList);
Result := false;
end;
if deletedFolderList0 <> nil then // send results to deletedFolderList0, deletedNonResFileList, deletedResFileList, modifiedArchiveList
begin
deletedFolderList0.Assign(deletedFolderList);
for elTemp in deletedFileList do
if AnsiContainsStr(elTemp, archResSeparator) then
deletedResFileList.Add(elTemp)
else
if deletedFolderList.IndexOf(trimCharsRight(ExtractFilePath(elTemp), '\', '/')) = -1 then
deletedNonResFileList.Add(elTemp);
for elTemp in modifiedFileList do
if AnsiRightStr(elTemp, 1) = archResSeparator then
modifiedArchiveList.Add(elTemp);
end;
oldFolderList.Free;
newFolderList.Free;
oldFileList.Free;
newFileList.Free;
addedFolderList.Free;
deletedFolderList.Free;
addedFileList.Free;
modifiedFileList.Free;
deletedFileList.Free;
end
else
begin
if FileExists(oldArchiveOrFolder) and FileExists(newArchiveOrFolder) and
MatchStr(AnsiLowerCase(ExtractFileExt(oldArchiveOrFolder)), supportedExts) and
MatchStr(AnsiLowerCase(ExtractFileExt(newArchiveOrFolder)), supportedExts)
then // oldArchiveOrFolder and newArchiveOrFolder are likely MM Archive files
begin
Result := compareFile(oldArchiveOrFolder, newArchiveOrFolder);
if not Result then
begin
addedFileList := TStringList.Create;
modifiedFileList := TStringList.Create;
deletedFileList := TStringList.Create;
try // try it as if it's MM Archive file
compareArchive(oldArchiveOrFolder, newArchiveOrFolder,
addedFileList, modifiedFileList, deletedFileList);
archSimpNew := MMArchSimple.load(newArchiveOrFolder);
nameTemp := ExtractFileName(newArchiveOrFolder);
for elTemp in addedFileList do
begin
if copyToFolder <> '' then // if needs file copy
begin
archSimpNew.extract(withTrailingSlash(copyToFolder) + nameTemp + MMArchiveExt, elTemp);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, withTrailingSlash(nameTemp + MMArchiveExt) + elTemp, 5); // [+/m] resourcefile
end;
end;
for elTemp in modifiedFileList do
begin
if copyToFolder <> '' then // if needs file copy
begin
archSimpNew.extract(withTrailingSlash(copyToFolder) + nameTemp + MMArchiveExt, elTemp);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, withTrailingSlash(nameTemp + MMArchiveExt) + elTemp, 5); // [+/m] resourcefile
end;
end;
for elTemp in deletedFileList do
begin
if copyToFolder <> '' then // if needs file copy
begin
createEmptyFile(withTrailingSlash(withTrailingSlash(copyToFolder) + nameTemp + MMArchiveExt) + elTemp + ToDeleteExt);
if copyToFolderExists and (deletedFolderList0 = nil) then // (deletedFolderList0 = nil) means it's `filesonly`
cleanUpOldFolder(copyToFolder, withTrailingSlash(nameTemp + MMArchiveExt) + elTemp, 6); // [-] resourcefile
end;
end;
// whether `FilesAreSame` has already been checked
colorPrintFileList(addedFileList, modifiedFileList, deletedFileList);
if deletedFolderList0 <> nil then // send results to deletedFolderList0, deletedNonResFileList, deletedResFileList, modifiedArchiveList
begin
// add nothing to deletedFolderList0 and deletedNonResFileList
for elTemp in deletedFileList do
deletedResFileList.Add(nameTemp + archResSeparator + elTemp);
if (addedFileList.Count > 0) and (modifiedFileList.Count > 0) then
modifiedArchiveList.Add(nameTemp + archResSeparator);
end;
except // very unlikely to be MM Archive file
raise Exception.Create(IncorrectMMArchive);
end;
addedFileList.Free;
modifiedFileList.Free;
deletedFileList.Free;
end
else // compareFile(oldArchiveOrFolder, newArchiveOrFolder) = true
begin
WriteLn(FilesAreSame);
end;
end
else // oldArchiveOrFolder and newArchiveOrFolder are not folders, and not MMArchive files
begin
raise Exception.Create(IncorrectFoldersOrMMArchives);
end;
end;
end;
function compareBase(oldArchiveOrFolder, newArchiveOrFolder: string; copyToFolder: string = ''): boolean; overload;
var
deletedFolderList, deletedNonResFileList, deletedResFileList, modifiedArchiveList: TStringList;
begin
deletedFolderList := nil;
deletedNonResFileList := nil;
deletedResFileList := nil;
modifiedArchiveList := nil;
Result := compareBase(oldArchiveOrFolder, newArchiveOrFolder, copyToFolder,
deletedFolderList, deletedNonResFileList, deletedResFileList, modifiedArchiveList);
end;
procedure getListFromDiffFiles(oldDiffFileFolder: string; var deletedFolderList, deletedNonResFileList, deletedResFileList, modifiedArchiveList: TStringList);
var
elTemp: string;
extListTemp: TStringList;
oldDiffFileFolderLen, i: integer;
begin
extListTemp := TStringList.Create;
oldDiffFileFolderLen := length(withTrailingSlash(oldDiffFileFolder));
// deletedFolderList: .todelete [folder]
extListTemp.Add(ToDeleteExt);
addAllFilesToFileList(deletedFolderList, oldDiffFileFolder, 1, true, false, extListTemp);
for i := 0 to deletedFolderList.Count - 1 do
begin
elTemp := deletedFolderList[i];
System.Delete(elTemp, 1, oldDiffFileFolderLen);
System.Delete(elTemp, length(elTemp) - 8, 9);
deletedFolderList[i] := elTemp;
end;
// deletedNonResFileList: .todelete [file, not in .mmarchive folder]
addAllFilesToFileList(deletedNonResFileList, oldDiffFileFolder, 1, false, false, extListTemp);
for i := deletedNonResFileList.Count - 1 downto 0 do
begin
elTemp := deletedNonResFileList[i];
System.Delete(elTemp, 1, oldDiffFileFolderLen);
System.Delete(elTemp, length(elTemp) - 8, 9);
deletedNonResFileList[i] := elTemp;
// deletedResFileList: .todelete [file, in .mmarchive folder]
if AnsiContainsStr(elTemp, MMArchiveExt + '\') then
begin
elTemp := StringReplace(elTemp, MMArchiveExt + '\', archResSeparator, [rfReplaceAll, rfIgnoreCase]);
deletedResFileList.Add(elTemp);
deletedNonResFileList.Delete(i);
end
end;
// modifiedArchiveList: .mmarchive [folder]
extListTemp.Delete(0);
extListTemp.Add(MMArchiveExt);
addAllFilesToFileList(modifiedArchiveList, oldDiffFileFolder, 1, true, false, extListTemp);
for i := 0 to modifiedArchiveList.Count - 1 do
begin
elTemp := modifiedArchiveList[i];
System.Delete(elTemp, 1, oldDiffFileFolderLen);
System.Delete(elTemp, length(elTemp) - 9, 10);
modifiedArchiveList[i] := elTemp + archResSeparator;
end;
extListTemp.Free;
end;
end.
|
unit cnFormPrintPreview;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, mcmPrinter, ComCtrls, ToolWin, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxControls, cxContainer, cxEdit, cxLabel, cxImage,
StdCtrls, umcmIntE, ImgList;
type
TFormPrintPreview = class(TForm)
mcmPrinter: TmcmPrinter;
mcmPrintPreview: TmcmPrintPreview;
StatusBar: TStatusBar;
ToolBar: TToolBar;
tbClose: TToolButton;
tbPageMargin: TToolButton;
tbPrint: TToolButton;
tbSetupPrinter: TToolButton;
tbFirstPage: TToolButton;
ToolButton5: TToolButton;
tbPreviousPage: TToolButton;
tbNextPage: TToolButton;
tbLastPage: TToolButton;
ToolButton3: TToolButton;
tbCentre: TToolButton;
ToolButton2: TToolButton;
tbFitToPage: TToolButton;
PrinterSetupDialog: TPrinterSetupDialog;
ToolButton1: TToolButton;
cbZoom: TcxComboBox;
lZoom: TcxLabel;
eScaleImage: TmcmIntSpin;
MenuImageList: TImageList;
procedure tbCloseClick(Sender: TObject);
procedure cbZoomChange(Sender: TObject);
procedure tbFirstPageClick(Sender: TObject);
procedure tbPreviousPageClick(Sender: TObject);
procedure tbNextPageClick(Sender: TObject);
procedure tbLastPageClick(Sender: TObject);
procedure tbPrintClick(Sender: TObject);
procedure tbSetupPrinterClick(Sender: TObject);
procedure PrinterSetupDialogClose(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure mcmPrinterNewPage(Sender: TObject);
procedure tbCentreClick(Sender: TObject);
procedure tbFitToPageClick(Sender: TObject);
procedure seScaleImageChange(Sender: TObject);
procedure tbPageMarginClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses cnFormMargin;
//uses uFormMargin;
{$R *.DFM}
procedure TFormPrintPreview.FormCreate(Sender : TObject);
begin
cbZoom.ItemIndex := 0;
mcmPrintPreview.ZoomToFit;
// Initialise browser buttons.
tbFirstPage.Enabled := False;
tbPreviousPage.Enabled := False;
tbNextPage.Enabled := (mcmPrinter.PageCount > 1);
tbLastPage.Enabled := (mcmPrinter.PageCount > 1);
StatusBar.SimpleText := 'Сторінка ' + IntToStr(mcmPrintPreview.PageIndex) +
' з ' + IntToStr(mcmPrinter.PageCount);
mcmPrinter.ImageFitToPage := True;
mcmPrinter.ImageCenter := True;
mcmPrinter.ForceMargin := true;
mcmPrinter.MarginLeft := 0;
mcmPrinter.MarginTop := 0;
mcmPrinter.MarginRight := 0;
mcmPrinter.MarginBottom := 0;
end;
procedure TFormPrintPreview.tbCloseClick(Sender : TObject);
begin
Close;
end; // TFormPrintPreview.tbCloseClick.
procedure TFormPrintPreview.cbZoomChange(Sender : TObject);
begin
// Change zoom factor for preview window.
case cbZoom.ItemIndex of
0 : mcmPrintPreview.ZoomToFit;
1 : mcmPrintPreview.ZoomToWidth;
2 : mcmPrintPreview.ZoomToHeight;
3 : mcmPrintPreview.ZoomPercent := 25;
4 : mcmPrintPreview.ZoomPercent := 50;
5 : mcmPrintPreview.ZoomPercent := 75;
6 : mcmPrintPreview.ZoomPercent := 100;
7 : mcmPrintPreview.ZoomPercent := 150;
8 : mcmPrintPreview.ZoomPercent := 200;
end;
end;
procedure TFormPrintPreview.tbFirstPageClick(Sender: TObject);
begin
// Go to first page.
mcmPrintPreview.PageIndex := 1;
tbFirstPage.Enabled := False;
tbPreviousPage.Enabled := False;
tbNextPage.Enabled := (mcmPrinter.PageCount > 1);
tbLastPage.Enabled := (mcmPrinter.PageCount > 1);
end;
procedure TFormPrintPreview.tbPreviousPageClick(Sender: TObject);
begin
// Got to previous page.
if (mcmPrintPreview.PageIndex > 1)
then begin
mcmPrintPreview.PageIndex := mcmPrintPreview.PageIndex - 1;
tbNextPage.Enabled := True;
tbLastPage.Enabled := True;
if (mcmPrintPreview.PageIndex = 1)
then begin
tbFirstPage.Enabled := False;
tbPreviousPage.Enabled := False;
end;
end;
StatusBar.SimpleText := 'Page ' + IntToStr(mcmPrintPreview.PageIndex) +
' of ' + IntToStr(mcmPrinter.PageCount);
end;
procedure TFormPrintPreview.tbNextPageClick(Sender: TObject);
begin
// Go to next page.
if (mcmPrintPreview.PageIndex <= mcmPrinter.PageCount)
then begin
mcmPrintPreview.PageIndex := mcmPrintPreview.PageIndex + 1;
tbFirstPage.Enabled := True;
tbPreviousPage.Enabled := True;
if (mcmPrintPreview.PageIndex = mcmPrinter.PageCount)
then begin
tbNextPage.Enabled := False;
tbLastPage.Enabled := False;
end;
end;
StatusBar.SimpleText := 'Page ' + IntToStr(mcmPrintPreview.PageIndex) +
' of ' + IntToStr(mcmPrinter.PageCount);
end;
procedure TFormPrintPreview.tbLastPageClick(Sender: TObject);
begin
// Go to last page.
mcmPrintPreview.PageIndex := mcmPrinter.PageCount;
tbFirstPage.Enabled := (mcmPrintPreview.PageIndex > 1);
tbPreviousPage.Enabled := (mcmPrintPreview.PageIndex > 1);
tbNextPage.Enabled := False;
tbLastPage.Enabled := False;
StatusBar.SimpleText := 'Page ' + IntToStr(mcmPrintPreview.PageIndex) +
' of ' + IntToStr(mcmPrinter.PageCount);
end;
procedure TFormPrintPreview.tbPrintClick(Sender: TObject);
begin
// Print pages.
if (mcmPrinter.PageCount > 0)
then mcmPrinter.Print;
end;
procedure TFormPrintPreview.tbSetupPrinterClick(Sender: TObject);
begin
// Access printer set-up dialogue.
if PrinterSetupDialog.Execute
then mcmPrinter.RefreshProperties;
InvalidateRect(Handle, Nil, True);
end;
procedure TFormPrintPreview.PrinterSetupDialogClose(Sender: TObject);
begin
// mcmPrinter.
end;
procedure TFormPrintPreview.mcmPrinterNewPage(Sender : TObject);
begin
tbNextPage.Enabled := (mcmPrinter.PageCount > 1);
tbLastPage.Enabled := (mcmPrinter.PageCount > 1);
StatusBar.SimpleText := 'Page ' + IntToStr(mcmPrintPreview.PageIndex) +
' of ' + IntToStr(mcmPrinter.PageCount);
end;
procedure TFormPrintPreview.tbCentreClick(Sender : TObject);
begin
{$IFDEF DCB3_6}
tbCentre.Down := Not tbCentre.Down;
{$ENDIF}
mcmPrinter.ImageCenter := tbCentre.Down;
end;
procedure TFormPrintPreview.tbFitToPageClick(Sender : TObject);
begin
{$IFDEF DCB3_6}
tbFitToPage.Down := Not tbFitToPage.Down;
{$ENDIF}
mcmPrinter.ImageFitToPage := tbFitToPage.Down;
end;
procedure TFormPrintPreview.seScaleImageChange(Sender : TObject);
begin
try
if (eScaleImage.Text <> '') and Assigned(mcmPrinter)
then mcmPrinter.ImageScale := eScaleImage.Value;
except
end;
end;
procedure TFormPrintPreview.tbPageMarginClick(Sender: TObject);
begin
FormPageMargin := TFormPageMargin.Create(Self);
FormPageMargin.ForceMargin := mcmPrinter.ForceMargin;
FormPageMargin.MarginLeft := mcmPrinter.MarginLeft;
FormPageMargin.MarginTop := mcmPrinter.MarginTop;
FormPageMargin.MarginRight := mcmPrinter.MarginRight;
FormPageMargin.MarginBottom := mcmPrinter.MarginBottom;
if (FormPageMargin.ShowModal = mrOK)
then begin
mcmPrinter.ForceMargin := FormPageMargin.ForceMargin;
mcmPrinter.MarginLeft := FormPageMargin.MarginLeft;
mcmPrinter.MarginTop := FormPageMargin.MarginTop;
mcmPrinter.MarginRight := FormPageMargin.MarginRight;
mcmPrinter.MarginBottom := FormPageMargin.MarginBottom;
end;
FormPageMargin.Free;
end;
end.
|
unit AStarCode;
//Degenerated from:
//===================================================================
//A* Pathfinder (Version 1.71a) by Patrick Lester. Used by permission.
//===================================================================
//http://www.policyalmanac.org/games/aStarTutorial.htm
//A* Pathfinding for Beginners
interface
uses AStarGlobals,//All data and Init destroy
forms;//application.ProcessMessages;
Function ReadPathX( pathfinderID, pathLocation:Integer):Integer;
Function ReadPathY( pathfinderID, pathLocation:Integer):Integer;
Procedure ReadPath( pathfinderID, currentX, currentY,
pixelsPerFrame:Integer);
Function FindPath ( pathfinderID, startingX, startingY,
targetX, targetY:Integer):Integer;
implementation
//==========================================================
//READ PATH DATA: These functions read the path data and convert
//it to screen pixel coordinates.
//The following two functions read the raw path data from the pathBank.
//You can call these functions directly and skip the readPath function
//above if you want. Make sure you know what your current pathLocation is.
//---------------------------------------------------------------------------
// Name: ReadPathX
// Desc: Reads the x coordinate of the next path step
//---------------------------------------------------------------------------
Function ReadPathX( pathfinderID, pathLocation:Integer):Integer;
var x:Integer;
Begin x :=0;
if (pathLocation <= pathLength[pathfinderID]) then
begin //Read coordinate from bank
x := pathBank[pathfinderID,((pathLocation*2)-2)];
//Adjust the coordinates so they align with the center
//of the path square (optional). This assumes that you are using
//sprites that are centered -- i.e., with the midHandle command.
//Otherwise you will want to adjust this.
//and make everything Doubles !!!
x := (tileSize*x) ;//+ (0.5*tileSize);
end;
Result:=x;
end;
//---------------------------------------------------------------------------
// Name: ReadPathY
// Desc: Reads the y coordinate of the next path step
//---------------------------------------------------------------------------
Function ReadPathY( pathfinderID, pathLocation:Integer):Integer;
var y:Integer;
Begin y :=0;
if (pathLocation <= pathLength[pathfinderID])then
begin
//Read coordinate from bank
y := pathBank[pathfinderID] [pathLocation*2-1];
//Adjust the coordinates so they align with the center
//of the path square (optional). This assumes that you are using
//sprites that are centered -- i.e., with the midHandle command.
//Otherwise you will want to adjust this.
y := tileSize*y ;//+ .5*tileSize;
end;
Result:=y;
end;
Procedure ReadPath( pathfinderID, currentX, currentY,
pixelsPerFrame:Integer);
//Note on PixelsPerFrame: The need for this parameter probably isn't
//that obvious, so a little explanation is in order. This
//parameter is used to determine if the pathfinder has gotten close
//enough to the center of a given path square to warrant looking up
//the next step on the path.
//This is needed because the speed of certain sprites can
//make reaching the exact center of a path square impossible.
//In Demo #2, the chaser has a velocity of 3 pixels per frame. Our
//tile size is 50 pixels, so the center of a tile will be at location
//25, 75, 125, etc. Some of these are not evenly divisible by 3, so
//our pathfinder has to know how close is close enough to the center.
//It calculates this by seeing if the pathfinder is less than
//pixelsPerFrame # of pixels from the center of the square.
//
//This could conceivably cause problems if you have a *really* fast
//sprite and/or really small tiles, in which case you may need to
//adjust the formula a bit. But this should almost never be a problem
//for games with standard sized tiles and normal speeds. Our smiley
//in Demo #4 moves at a pretty fast clip and it isn't even close
//to being a problem.
var ID:Integer;
Begin
ID := pathfinderID; //redundant, but makes the following easier to read
//If a path has been found for the pathfinder ...
if (pathStatus[ID] = found) then
begin
//If path finder is just starting a new path or has reached the
//center of the current path square (and the end of the path
//hasn't been reached), look up the next path square.
if (pathLocation[ID] < pathLength[ID]) then
begin
//if just starting or if close enough to center of square
if ( (pathLocation[ID] = 0)
or( (abs(currentX - xPath[ID])< pixelsPerFrame)
and (abs(currentY - yPath[ID]) < pixelsPerFrame)) )
then pathLocation[ID] := (pathLocation[ID] + 1);
end;
//Read the path data.
xPath[ID] := ReadPathX(ID,pathLocation[ID]);
yPath[ID] := ReadPathY(ID,pathLocation[ID]);
//If the center of the last path square on the path has been
//reached then reset.
if (pathLocation[ID] = pathLength[ID]) then
begin //if close enough to center of square
if ( (abs(currentX - xPath[ID]) < pixelsPerFrame)
and (abs(currentY - yPath[ID]) < pixelsPerFrame))
then pathStatus[ID] := notStarted;
end;
end
//If there is no path for this pathfinder,
//simply stay in the current location.
else
begin
xPath[ID] := currentX;
yPath[ID] := currentY;
end;
End;
//---------------------------------------------------------------------------
// Name: FindPath
// Desc: Finds a path using A*
//---------------------------------------------------------------------------
Function FindPath ( pathfinderID, startingX, startingY,
targetX, targetY:Integer):Integer;
var
startX,startY,x,y,
onOpenList, parentXval, parentYval,
a, b, m, u, v, temp, corner, numberOfOpenListItems,
addedGCost, tempGcost,
//path,//moved to global
tempx, pathX, pathY, cellPosition,
newOpenListItemID:Integer;
//13.If there is no path to the selected target, set the pathfinder's
//xPath and yPath equal to its current location
//and return that the path is nonexistent.
procedure noPath;
begin
xPath[pathfinderID] := startingX;
yPath[pathfinderID] := startingY;
result:= nonexistent;
end;
Begin
//onOpenList:=0; parentXval:=0; parentYval:=0;
//a:=0; b:=0; m:=0; u:=0; v:=0;
//temp:=0; corner:=0; numberOfOpenListItems:=0;
addedGCost:=0; tempGcost := 0;
//path := 0;
// tempx:=0; pathX:=0; pathY:=0; cellPosition:=0;
newOpenListItemID:=0;
//1. Convert location data (in pixels)
//to coordinates in the walkability array.
startX := startingX div tileSize;
startY := startingY div tileSize;
targetX := targetX div tileSize;
targetY := targetY div tileSize;
//2.Quick Path Checks: Under the some circumstances no path needs to
// be generated ...
//If starting location and target are in the same location...
if ((startX = targetX) and (startY = targetY)
and (pathLocation[pathfinderID] > 0))
then result:= found;
if ((startX = targetX) and (startY = targetY)
and (pathLocation[pathfinderID] = 0))
then result:= nonexistent;
//If target square is unwalkable, return that it's a nonexistent path.
if (walkability[targetX][targetY] = unwalkable)then
begin noPath;exit;{current procedure} end;//goto noPath;
//3.Reset some variables that need to be cleared
if (onClosedList > 1000000)then //reset whichList occasionally
begin
for x := 0 to mapWidth-1 do
for y := 0 to mapHeight-1 do whichList [x][y] := 0;
onClosedList := 10;
end;
//changing the values of onOpenList and onClosed list
//is faster than redimming whichList() array
onClosedList := onClosedList+2;
onOpenList := onClosedList-1;
// tempUnwalkable := onClosedList-2;
pathLength [pathfinderID] := notStarted;//i.e, = 0
pathLocation [pathfinderID] := notStarted;//i.e, = 0
Gcost[startX][startY] := 0; //reset starting square's G value to 0
//4.Add the starting location to the open list of squares to be checked.
numberOfOpenListItems := 1;
//assign it as the top (and currently only) item in the open list,
// which is maintained as a binary heap (explained below)
openList[1] := 1;
openX[1] := startX ;
openY[1] := startY;
LostinaLoop:=True;
//5.Do the following until a path is found or deemed nonexistent.
while (LostinaLoop)//Do until path is found or deemed nonexistent
do
begin
Application.ProcessMessages;
// If () then LostinaLoop :=False;
//6.If the open list is not empty, take the first cell off of the list.
//This is the lowest F cost cell on the open list.
if (numberOfOpenListItems <> 0) then
begin
//7. Pop the first item off the open list.
parentXval := openX[openList[1]];
//record cell coordinates of the item
parentYval := openY[openList[1]];
//add the item to the closed list
whichList[parentXval][parentYval] := onClosedList;
//Open List = Binary Heap: Delete this item from the open list, which
//is maintained as a binary heap.
//For more information on binary heaps, see:
//http://www.policyalmanac.org/games/binaryHeaps.htm
//reduce number of open list items by 1
numberOfOpenListItems := numberOfOpenListItems - 1;
//Delete the top item in binary heap and reorder the heap,
//with the lowest F cost item rising to the top.
//move the last item in the heap up to slot #1
openList[1] := openList[numberOfOpenListItems+1];
v := 1;
//Repeat the following until the new item in slot #1
//sinks to its proper spot in the heap.
while LostinaLoop//(not KeyDown(27))//reorder the binary heap
do
begin
Application.ProcessMessages;
u := v;
//if both children exist
if (2*u+1 <= numberOfOpenListItems)then
begin
//Check if the F cost of the parent is greater than each child.
//Select the lowest of the two children.
if (Fcost[openList[u]] >= Fcost[openList[2*u]])then v := 2*u;
if (Fcost[openList[v]] >= Fcost[openList[2*u+1]])then v := 2*u+1;
end
else
begin //if only child #1 exists
if (2*u <= numberOfOpenListItems)then
begin
//Check if the F cost of the parent is greater than child #1
if (Fcost[openList[u]] >= Fcost[openList[2*u]])then
v := 2*u;
end;
end;
//!=
if (u <> v)then //if parent's F is > one of its children, swap them
begin
temp := openList[u];
openList[u] := openList[v];
openList[v] := temp;
end else break; //otherwise, exit loop
end;
//7.Check the adjacent squares. (Its "children" -- these path children
//are similar, conceptually, to the binary heap children mentioned
//above, but don't confuse them. They are different. Path children
//are portrayed in Demo 1 with grey pointers pointing toward
//their parents.) Add these adjacent child squares to the open list
//for later consideration if appropriate (see various if statements
//below).
for b := parentYval-1 to parentYval+1 do
begin
for a := parentXval-1 to parentXval+1do
begin
//If not off the map
//(do this first to avoid array out-of-bounds errors)
if ( (a <> -1) and (b <> -1)
and (a <> mapWidth) and (b <> mapHeight))then
begin
//If not already on the closed list (items on the closed list have
//already been considered and can now be ignored).
if (whichList[a][b] <> onClosedList)then
begin
//If not a wall/obstacle square.
if (walkability [a][b] <> unwalkable) then
begin
//Don't cut across corners
corner := walkable;
if (a = parentXval-1)then
begin
if (b = parentYval-1)then
begin
if ( (walkability[parentXval-1][parentYval] = unwalkable)
or (walkability[parentXval][parentYval-1] = unwalkable))
then corner := unwalkable;
end
else if (b = parentYval+1)then
begin
if ((walkability[parentXval][parentYval+1] = unwalkable)
or (walkability[parentXval-1][parentYval] = unwalkable))
then corner := unwalkable;
end;
end
else if (a = parentXval+1)then
begin
if (b = parentYval-1)then
begin
if ((walkability[parentXval][parentYval-1] = unwalkable)
or (walkability[parentXval+1][parentYval] = unwalkable))
then corner:= unwalkable;
end
else if (b = parentYval+1)then
begin
if ((walkability[parentXval+1][parentYval] = unwalkable)
or (walkability[parentXval][parentYval+1] = unwalkable))
then corner := unwalkable;
end;
end;
if (corner = walkable)then
begin
//If not already on the open list, add it to the open list.
if (whichList[a][b] <> onOpenList)then
begin
//Create a new open list item in the binary heap.
//each new item has a unique ID #
newOpenListItemID := newOpenListItemID + 1;
m := numberOfOpenListItems+1;
//place the new open list item
//(actually, its ID#) at the bottom of the heap
openList[m] := newOpenListItemID;
//record the x and y coordinates of the new item
openX[newOpenListItemID] := a;
openY[newOpenListItemID] := b;
//Figure out its G cost
if ((abs(a-parentXval) = 1) and (abs(b-parentYval) = 1))
//cost of going to diagonal squares
then addedGCost := 14
//cost of going to non-diagonal squares
else addedGCost := 10;
Gcost[a][b] := Gcost[parentXval][parentYval] + addedGCost;
//Figure out its H and F costs and parent
//If useDijkstras then Hcost[openList[m]] :=0 else
Hcost[openList[m]] :=
10*(abs(a - targetX) + abs(b - targetY));
Fcost[openList[m]] := Gcost[a][b] + Hcost[openList[m]];
parentX[a][b] := parentXval ;
parentY[a][b] := parentYval;
//Move the new open list item to the proper place
//in the binary heap. Starting at the bottom,
//successively compare to parent items,
//swapping as needed until
//the item finds its place in the heap
//or bubbles all the way to the top
//(if it has the lowest F cost).
//While item hasn't bubbled to the top (m=1)
while (m <> 1)do
begin
//Check if child's F cost is < parent's F cost.
//If so, swap them.
if (Fcost[openList[m]] <= Fcost[openList[m div 2]])then
begin
temp := openList[m div 2];//[m/2];
openList[m div 2]{[m/2]} := openList[m];
openList[m] := temp;
m := m div 2;//m/2;
end else break;
end;
//add one to the number of items in the heap
numberOfOpenListItems := numberOfOpenListItems+1;
//Change whichList to show
//that the new item is on the open list.
whichList[a][b] := onOpenList;
end
//8.If adjacent cell is already on the open list,
//check to see if this path to that cell
//from the starting location is a better one.
//If so, change the parent of the cell and its G and F costs
else //If whichList(a,b) = onOpenList
begin
//Figure out the G cost of this possible new path
if ((abs(a-parentXval) = 1) and (abs(b-parentYval) = 1))
//cost of going to diagonal tiles
then addedGCost := 14
//cost of going to non-diagonal tiles
else addedGCost := 10;
tempGcost := Gcost[parentXval][parentYval] + addedGCost;
//If this path is shorter (G cost is lower) then change
//the parent cell, G cost and F cost.
if (tempGcost < Gcost[a][b])then //if G cost is less,
begin //change the square's parent
parentX[a][b] := parentXval;
parentY[a][b] := parentYval;
Gcost[a][b] := tempGcost;//change the G cost
//Because changing the G cost also changes the F cost,
//if the item is on the open list we need to change
//the item's recorded F cost
//and its position on the open list to make
//sure that we maintain a properly ordered open list.
//look for the item in the heap
for x := 1 to numberOfOpenListItems do
begin //item found
if ( (openX[openList[x]] = a)
and (openY[openList[x]] = b))then
begin //change the F cost
Fcost[openList[x]] :=
Gcost[a][b] + Hcost[openList[x]];
//See if changing the F score bubbles the item up
// from it's current location in the heap
m := x;
//While item hasn't bubbled to the top (m=1)
while (m <> 1)do
begin
//Check if child is < parent. If so, swap them.
if (Fcost[openList[m]] < Fcost[openList[m div 2]])
then
begin
temp := openList[m div 2]; //
openList[m div 2] := openList[m]; //m/2
openList[m] := temp;
m := m div 2;
end else break;
end;
break; //exit for x = loop
end; //If openX(openList(x)) = a
end; //For x = 1 To numberOfOpenListItems
end;//If tempGcost < Gcost(a,b)
end;//else If whichList(a,b) = onOpenList
end;//If not cutting a corner
end;//If not a wall/obstacle square.
end;//If not already on the closed list
end;//If not off the map
end;//for (a = parentXval-1; a <= parentXval+1; a++){
end;//for (b = parentYval-1; b <= parentYval+1; b++){
end//if (numberOfOpenListItems != 0)
//9.If open list is empty then there is no path.
else
begin //path
pathStatus[pathfinderID] := nonexistent;
break;
end;
//If target is added to open list then path has been found.
if (whichList[targetX][targetY] = onOpenList)then
begin //path
pathStatus[pathfinderID] := found;
break;
end;
end;
//10.Save the path if it exists.
if (pathStatus[pathfinderID] = found)then
begin
//a.Working backwards from the target to the starting location by checking
//each cell's parent, figure out the length of the path.
pathX := targetX;
pathY := targetY;
while ((pathX <> startX) or (pathY <> startY))do
begin
//Look up the parent of the current cell.
tempx := parentX[pathX][pathY];
pathY := parentY[pathX][pathY];
pathX := tempx;
//Figure out the path length
pathLength[pathfinderID] := pathLength[pathfinderID] + 1;
end;
{;b. Resize the data bank to the right size (leave room to store step 0,
;which requires storing one more step than the length)
ResizeBank unit\pathBank,(unit\pathLength+1)*4}
//b.Resize the data bank to the right size in bytes
{pathBank[pathfinderID] :=
(int* ) realloc (pathBank[pathfinderID],
pathLength[pathfinderID]*8);} //8 ? 4 byte =int ? +1
setlength(pathBank[pathfinderID],(pathLength[pathfinderID])*2);
//c. Now copy the path information over to the databank. Since we are
//working backwards from the target to the start location, we copy
//the information to the data bank in reverse order. The result is
//a properly ordered set of path data, from the first step to the last.
pathX := targetX;
pathY := targetY;
cellPosition := pathLength[pathfinderID]*2;//start at the end
while ((pathX <> startX) or (pathY <> startY))do
begin
cellPosition := cellPosition - 2;//work backwards 2 integers
pathBank[pathfinderID] [cellPosition] := pathX;
pathBank[pathfinderID] [cellPosition+1] := pathY;
//d.Look up the parent of the current cell.
tempx := parentX[pathX][pathY];
pathY := parentY[pathX][pathY];
pathX := tempx;
//e.If we have reached the starting square, exit the loop.
end;
//11.Read the first path step into xPath/yPath arrays
// ReadPath(pathfinderID,startingX,startingY,1);
yPath[pathfinderID] :=tileSize*pathBank[pathfinderID] [pathLocation[pathfinderID]*2-1];
xPath[pathfinderID] :=tileSize*pathBank[pathfinderID] [pathLocation[pathfinderID]*2-2];
end;
result:= pathStatus[pathfinderID];
End;
end.
|
unit ThZoomAnimation;
interface
uses
System.Classes, System.Types,
FMX.Types, FMX.Controls, FMX.Graphics, FMX.Ani;
type
TZoomAni = class(TControl)
private
FZoomAni: TFloatAnimation;
FDiffuse: Single;
procedure SetDiffuse(const Value: Single);
procedure FinishAni(Sender: TObject);
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ZoomIn(ATargetPos: TPointF);
procedure ZoomOut(ATargetPos: TPointF);
property Diffuse: Single read FDiffuse write SetDiffuse;
end;
TZoomCircleAni = class(TZoomAni)
protected
procedure Paint; override;
end;
implementation
uses
System.UIConsts, DebugUtils;
{ TZoomAni }
constructor TZoomAni.Create(AOwner: TComponent);
begin
inherited;
// Locked := False;
Hittest := False;
FZoomAni := TFloatAnimation.Create(Self);
FZoomAni.Parent := Self;
FZoomAni.AnimationType := TAnimationType.Out;
FZoomAni.Interpolation := TInterpolationType.Quadratic;
FZoomAni.PropertyName := 'Diffuse';
FZoomAni.StartFromCurrent := False;
FZoomAni.Delay := 0;
FZoomAni.Duration := 0.5;
FZoomAni.OnFinish := FinishAni;
Width := 100;
Height := 100;
Visible := False;
end;
destructor TZoomAni.Destroy;
begin
FZoomAni.Free;
inherited;
end;
procedure TZoomAni.FinishAni(Sender: TObject);
begin
Visible := False;
end;
procedure TZoomAni.Paint;
begin
inherited;
end;
procedure TZoomAni.SetDiffuse(const Value: Single);
begin
FDiffuse := Value;
Repaint;
end;
procedure TZoomAni.ZoomIn(ATargetPos: TPointF);
begin
Position.Point := ATargetPos - PointF(Width / 2, Height / 2);
if FZoomAni.Running then
FZoomAni.Stop;
Visible := True;
FZoomAni.StartValue := 10;
FZoomAni.StopValue := 100;
FZoomAni.Start;
end;
procedure TZoomAni.ZoomOut(ATargetPos: TPointF);
begin
Position.Point := ATargetPos - PointF(Width / 2, Height / 2);
if FZoomAni.Running then
FZoomAni.Stop;
Visible := True;
FZoomAni.StartValue := 100;
FZoomAni.StopValue := 10;
FZoomAni.Start;
end;
{ TZoomCircleAni }
procedure TZoomCircleAni.Paint;
var
Radius: Single;
R, R2: TRectF;
P: TPointF;
State: TCanvasSaveState;
begin
inherited;
Radius := (Width / 2) * (FDiffuse / 100);
P := ClipRect.CenterPoint;
R := RectF(P.X, P.Y, P.X, P.Y);
R2 := RectF(P.X, P.Y, P.X, P.Y);
InflateRect(R, Radius, Radius);
State := Canvas.SaveState;
try
Canvas.Stroke.Thickness := 3;
Canvas.Stroke.Dash := TStrokeDash.Dot;
Canvas.Stroke.Color := claDarkGray;
Canvas.DrawEllipse(R, 1);
// 원이 크면 서브 원 표시
if Radius > (Width / 4) then
begin
InflateRect(R2, Radius / 2, Radius / 2);
Canvas.DrawEllipse(R2, 1);
end;
finally
Canvas.RestoreState(State);
end;
end;
end.
|
unit MyLabel;
interface
uses
Classes,
StdCtrls;
type
TMyLabel = class(TLabel)
private
FDescription: String;
FExcludeMe: String;
published
property Description: String read FDescription write FDescription;
property ExcludeMe: String read FExcludeMe write FExcludeMe;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('My label', [TMyLabel]);
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado à tabela [R01]
The MIT License
Copyright: Copyright (C) 2010 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>
Albert Eije (T2Ti.COM)
@version 2.0
*******************************************************************************}
{*******************************************************************************
Observações importantes
Registro tipo R01 - Identificação do ECF, do Usuário, do PAF-ECF e da Empresa Desenvolvedora;
Registro tipo R02 - Relação de Reduções Z;
Registro tipo R03 - Detalhe da Redução Z;
Registro tipo R04 - Cupom Fiscal, Nota Fiscal de Venda a Consumidor ou Bilhete de Passagem;
Registro tipo R05 - Detalhe do Cupom Fiscal, da Nota Fiscal de Venda a Consumidor ou Bilhete de Passagem;
Registro tipo R06 - Demais documentos emitidos pelo ECF;
Registro tipo R07 - Detalhe do Cupom Fiscal e do Documento Não Fiscal - Meio de Pagamento;
Registro EAD - Assinatura digital.
Numa venda com cartão teremos:
-Um R04 referente ao Cupom Fiscal (já gravamos no venda_cabecalho)
-Um R05 para cada item vendido (já gravamos no venda_detalhe)
-Um R06 para o Comprovante de Crédito ou Débito (o CCD se encaixa como "outros documentos emitidos");
-Um R07 referente à forma de pagamento utilizada no Cupom Fiscal, no caso, Cartão.
*******************************************************************************}
unit R01Controller;
interface
uses
Classes, SysUtils, Windows, Forms, Controller,
VO, R01VO;
type
TR01Controller = class(TController)
private
public
class function ConsultaObjeto(pFiltro: String): TR01VO;
end;
implementation
uses UDataModule, T2TiORM;
class function TR01Controller.ConsultaObjeto(pFiltro: String): TR01VO;
begin
try
Result := TR01VO.Create;
Result := TR01VO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
finally
end;
end;
end.
|
unit progress;
{ Exports procedure ShowProgress and type TProgressProc.
Useful for giving user feedback during lengthy operations.
The programmer can assign his own progress procedure to ShowProgress
when he wants. By default, under DOS, procedure EmptyProgressProc
is assigned to progressproc and under Delphi ProgressForm.ShowProgress
(see unit FmProgr),
Another procedure which can be used is available: WritePercentage
R.P. Sterkenburg, TNO PML Rijswijk, The Netherlands
30 Aug 95: - created
12 Nov 96: - converted all keywords to lowercase
4 Dec 96: - renamed progressproc to ShowProgress
- added Delphi compiler directives to let it
automatically use ShowProgress from FmProgr
11 Dec 96: - improved comments
- default EmptyProgressPorc in stead of WritePercentage
9 Feb 97: - changed compiler directives so that the unit also works under
Delphi 2
}
interface
{$IFDEF ver70}
uses
Crt; { Imports GotoXY }
{$ELSE}
uses
FmProgr; { Imports ShowProgress }
{$ENDIF ver70}
type
TProgressProc = procedure(frac: single);
var
ShowProgress: TProgressProc;
procedure EmptyProgressProc(frac: single);
{$IFNDEF ver70}
procedure ShowAsGauge(frac: single);
{$ENDIF}
{$IFDEF ver70}
procedure WritePercentage(frac: single);
{$ENDIF}
implementation
{$F+}
procedure EmptyProgressProc(frac: single);
begin end;
{$F-}
{$IFDEF ver70}
{$F+}
procedure WritePercentage(frac: single);
begin
GotoXY(1, WhereY);
write('Finished: ', frac*100:6:2, ' % ');
if frac >= 1
then Writeln;
end;
{$F-}
{$ENDIF ver70}
{$IFNDEF ver70}
{$F+}
procedure ShowAsGauge(frac: single);
begin
FmProgr.ShowProgress(frac)
end;
{$F-}
{$ENDIF ver70}
begin
{$IFDEF ver70}
ShowProgress := EmptyProgressProc;
{$ELSE}
ShowProgress := ShowAsGauge;
{$ENDIF ver70}
end.
|
{
Role
Interaction
Layers management
Freedraw
Shapes
Viewer(Display received datas)
}
unit ThCanvas;
interface
uses
System.Classes, System.Types,
Vcl.Controls, Vcl.Graphics,
GR32,
GR32_Image,
GR32_Layers,
ThTypes,
ThItemStyle,
ThCanvasLayers;
type
TScaleChangeEvent = procedure(Sender: TObject; Scale: Single) of object;
TThCustomCanvas = class(TCustomControl)
private
FImgView: TImgView32;
FPenLayer: TPenDrawLayer;
FShapeLayer: TShapeDrawLayer;
FBackgroundLayer: TThBackgroundLayer;
FPenStyle: TThPenStyle;
FOnScaleChange: TScaleChangeEvent;
FDrawMode: TThDrawMode;
FShapeId: string;
procedure DoScaleChage(Scale: Single);
procedure SetScale(const Value: Single);
function GetScale: Single;
////////////////////////////
// Event
procedure ImgViewResize(Sender: TObjecT);
// Mouse
procedure ImgViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
procedure ImgViewMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
procedure ImgViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
// Wheel
procedure ImgViewMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure ImgViewMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure ImgViewMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure SetDrawMode(const Value: TThDrawMode);
procedure SetShapeId(const Value: string);
protected
procedure CreateWnd; override;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CreatePage(AWidth: Integer = 0; AHeight: Integer = 0);
property DrawMode: TThDrawMode read FDrawMode write SetDrawMode;
// Link PenStyleChange
property PenStyle: TThPenStyle read FPenStyle;
property ShapeId: string read FShapeId write SetShapeId;
property Scale: Single read GetScale write SetScale;
property OnScaleChange: TScaleChangeEvent read FOnScaleChange write FOnScaleChange;
procedure Clear;
procedure DeleteSelected;
end;
TThCanvas = class(TThCustomCanvas)
public
property OnScaleChange;
end;
implementation
{ TThCanvas }
procedure TThCustomCanvas.Clear;
begin
FPenLayer.Clear;
end;
constructor TThCustomCanvas.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FImgView := TImgView32.Create(nil);
FImgView.Name := 'ThImageView';
FImgView.Parent := Self;
FImgView.Align := alClient;
FImgView.Color := clSilver;
FImgView.Centered := False;
FImgView.OnResize := ImgViewResize;
FImgView.OnMouseDown := ImgViewMouseDown;
FImgView.OnMouseMove := ImgViewMouseMove;
FImgView.OnMouseUp := ImgViewMouseUp;
FImgView.OnMouseWheelUp := ImgViewMouseWheelUp;
FImgView.OnMouseWheel := ImgViewMouseWheel;
FImgView.OnMouseWheelDown := ImgViewMouseWheelDown;
end;
procedure TThCustomCanvas.CreateWnd;
begin
inherited;
end;
procedure TThCustomCanvas.DeleteSelected;
begin
FShapeLayer.DeleteSelectedItems;
end;
destructor TThCustomCanvas.Destroy;
begin
FImgView.Free;
inherited;
end;
procedure TThCustomCanvas.CreatePage(AWidth, AHeight: Integer);
begin
if (AWidth = 0) or (AWidth = 0) then
begin
AWidth := 2480;
AHeight := 3508;
end;
FImgView.Bitmap.SetSize(AWidth, AHeight);
FImgView.Bitmap.Clear(clGray32);
FBackgroundLayer := TThBackgroundLayer.Create(FImgView.Layers);
FBackgroundLayer.Location := FloatRect(0, 0, AWidth, AHeight);
FBackgroundLayer.Bitmap.SetSize(AWidth, AHeight);
FBackgroundLayer.Bitmap.Clear(clWhite32);
FBackgroundLayer.Scaled := True;
FShapeLayer := TShapeDrawLayer.Create(FImgView.Layers);
FShapeLayer.Location := FloatRect(0, 0, AWidth, AHeight);
FShapeLayer.HitTest := False;
FShapeLayer.Scaled := True;
FShapeLayer.MouseEvents := True;
FPenLayer := TPenDrawLayer.Create(FImgView.Layers);
FPenLayer.Location := FloatRect(0, 0, AWidth, AHeight);
FPenLayer.Scaled := True;
FPenLayer.HitTest := True;
FImgView.Layers.MouseListener := FPenLayer;
FPenStyle := FPenLayer.PenDrawObj.DrawStyle as TThPenStyle;
end;
procedure TThCustomCanvas.DoScaleChage(Scale: Single);
begin
if Assigned(FOnScaleChange) then
FOnScaleChange(Self, Scale);
end;
function TThCustomCanvas.GetScale: Single;
begin
Result := FImgView.Scale;
end;
procedure TThCustomCanvas.SetShapeId(const Value: string);
begin
FShapeId := Value;
FShapeLayer.ShapeId := Value;
end;
procedure TThCustomCanvas.SetDrawMode(const Value: TThDrawMode);
begin
case Value of
dmSelect, dmDraw:
begin
FPenLayer.HitTest := False;
FShapeLayer.HitTest := True;
FShapeLayer.DrawMode := Value;
FImgView.Layers.MouseListener := FShapeLayer;
end;
dmPen, dmEraser:
begin
FPenLayer.HitTest := True;
FShapeLayer.HitTest := False;
FPenLayer.DrawMode := Value;
FImgView.Layers.MouseListener := FPenLayer;
end;
end;
FDrawMode := Value;
end;
procedure TThCustomCanvas.SetScale(const Value: Single);
var
LScale: Single;
begin
if Value < TH_SCALE_MIN then LScale := TH_SCALE_MIN
else if Value > TH_SCALE_MAX then LScale := TH_SCALE_MAX
else LScale := Value;
if GetScale = LScale then
Exit;
FImgView.Scale := LScale;
FImgView.Invalidate;
// FShapeDrawLayer.Scale := FloatPoint(LScale, LScale);
DoScaleChage(LScale);
end;
procedure TThCustomCanvas.ImgViewResize(Sender: TObjecT);
begin
end;
procedure TThCustomCanvas.Loaded;
begin
inherited;
if HandleAllocated then
FImgView.ScrollBars.Visibility := svAuto;
end;
procedure TThCustomCanvas.ImgViewMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
begin
end;
procedure TThCustomCanvas.ImgViewMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer; Layer: TCustomLayer);
begin
end;
procedure TThCustomCanvas.ImgViewMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
begin
end;
procedure TThCustomCanvas.ImgViewMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
FImgView.Scroll(0, -WheelDelta);
FImgView.Update;
end;
procedure TThCustomCanvas.ImgViewMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
// if ssCtrl in Shift then
Scale := Scale + 0.1;
end;
procedure TThCustomCanvas.ImgViewMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
// if ssCtrl in Shift then
Scale := Scale - 0.1;
end;
end.
|
Unit FastIoRequest;
Interface
Uses
Windows,
IRPMonRequest, IRPMonDll;
Type
TFastIoRequest = Class (TDriverRequest)
Private
FPreviousMode : Byte;
FFastIoType : EFastIoOperationType;
FArg1 : Pointer;
FArg2 : Pointer;
FArg3 : Pointer;
FArg4 : Pointer;
Public
Constructor Create(Var ARequest:REQUEST_FASTIO); Overload;
Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override;
Class Function FastIoTypeToString(AFastIoType:EFastIoOperationType):WideString;
Property PreviousMode : Byte Read FPreviousMode;
Property FastIoType : EFastIoOperationType Read FFastIoType;
end;
Implementation
Uses
SysUtils;
Constructor TFastIoRequest.Create(Var ARequest:REQUEST_FASTIO);
Var
d : Pointer;
begin
Inherited Create(ARequest.Header);
d := PByte(@ARequest) + SizeOf(ARequest);
AssignData(d, ARequest.DataSize);
FFastIoType := ARequest.FastIoType;
FPreviousMode := ARequest.PreviousMode;
SetFileObject(ARequest.FileObject);
FArg1 := ARequest.Arg1;
FArg2 := ARequest.Arg2;
FArg3 := ARequest.Arg3;
FArg4 := ARequest.Arg4;
end;
Function TFastIoRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean;
begin
Result := True;
Case AColumnType Of
rlmctSubType : AResult := FastIoTypeToString(FFastIoType);
rlmctPreviousMode : AResult := AccessModeToString(FPreviousMode);
rlmctArg1,
rlmctArg2,
rlmctArg3,
rlmctArg4 : begin
Result := False;
If (FFastIoType = FastIoDeviceControl) Then
begin
Case AColumnType Of
rlmctArg1: AResult := Format('O: %u (0x%p)', [Cardinal(FArg1), FArg1]);
rlmctArg2: AResult := Format('I: %u (0x%p)', [Cardinal(FArg2), FArg2]);
rlmctArg3: AResult := IOCTLToString(Cardinal(FArg3));
end;
end;
end;
rlmctIOSBStatusValue : begin
Result := False;
Case FFastIoType Of
FastIoCheckIfPossible,
FastIoRead,
FastIoWrite,
FastIoQueryBasicInfo,
FastIoQueryStandardInfo,
FastIoLock,
FastIoUnlockSingle,
FastIoUnlockAll,
FastIoUnlockAllByKey,
FastIoDeviceControl,
FastIoQueryNetworkOpenInfo,
MdlRead,
PrepareMdlWrite,
FastIoReadCompressed,
FastIoWriteCompressed : AResult := Format('0x%x', [FIOSBStatus]);
end;
end;
rlmctIOSBStatusConstant : begin
Result := False;
Case FFastIoType Of
FastIoCheckIfPossible,
FastIoRead,
FastIoWrite,
FastIoQueryBasicInfo,
FastIoQueryStandardInfo,
FastIoLock,
FastIoUnlockSingle,
FastIoUnlockAll,
FastIoUnlockAllByKey,
FastIoDeviceControl,
FastIoQueryNetworkOpenInfo,
MdlRead,
PrepareMdlWrite,
FastIoReadCompressed,
FastIoWriteCompressed : AResult := Format('%s', [NTSTATUSToString(FIOSBStatus)]);
end;
end;
rlmctIOSBInformation : begin
Result := False;
Case FFastIoType Of
FastIoCheckIfPossible,
FastIoRead,
FastIoWrite,
FastIoQueryBasicInfo,
FastIoQueryStandardInfo,
FastIoLock,
FastIoUnlockSingle,
FastIoUnlockAll,
FastIoUnlockAllByKey,
FastIoDeviceControl,
FastIoQueryNetworkOpenInfo,
MdlRead,
PrepareMdlWrite,
FastIoReadCompressed,
FastIoWriteCompressed : AResult := Format('%u (0x%p)', [FIOSBInformation, Pointer(FIOSBInformation)]);
end;
end;
Else Result := Inherited GetColumnValue(AColumnType, AResult);
end;
end;
Class Function TFastIoRequest.FastIoTypeToString(AFastIoType:EFastIoOperationType):WideString;
begin
Case AFastIoType Of
FastIoCheckIfPossible : Result := 'CheckIfPossible';
FastIoRead : Result := 'Read';
FastIoWrite : Result := 'Write';
FastIoQueryBasicInfo : Result := 'QueryBasicInfo';
FastIoQueryStandardInfo : Result := 'QueryStandardInfo';
FastIoLock : Result := 'Lock';
FastIoUnlockSingle : Result := 'UnlockSingle';
FastIoUnlockAll : Result := 'UnlockAll';
FastIoUnlockAllByKey : Result := 'UnlockAllByKey';
FastIoDeviceControl : Result := 'DeviceControl';
AcquireFileForNtCreateSection : Result := 'AcquireFileForNtCreateSection';
ReleaseFileForNtCreateSection : Result := 'ReleaseFileForNtCreateSection';
FastIoDetachDevice : Result := 'DetachDevice';
FastIoQueryNetworkOpenInfo : Result := 'QueryNetworkOpenInfo';
AcquireForModWrite : Result := 'AcquireForModWrite';
MdlRead : Result := 'MdlRead';
MdlReadComplete : Result := 'MdlReadComplete';
PrepareMdlWrite : Result := 'PrepareMdlWrite';
MdlWriteComplete : Result := 'MdlWriteComplete';
FastIoReadCompressed : Result := 'FastIoReadCompressed';
FastIoWriteCompressed : Result := 'FastIoWriteCompressed';
MdlReadCompleteCompressed : Result := 'MdlReadCompleteCompressed';
MdlWriteCompleteCompressed : Result := 'MdlWriteCompleteCompressed';
FastIoQueryOpen : Result := 'FastIoQueryOpen';
ReleaseForModWrite : Result := 'ReleaseForModWrite';
AcquireForCcFlush : Result := 'AcquireForCcFlush';
ReleaseForCcFlush : Result := 'ReleaseForCcFlush';
Else Result := Format('%d', [Ord(AFastIoType)]);
end;
end;
End.
|
{
@abstract(TSynUniSyn rules source)
@authors(Fantasist [walking_in_the_sky@yahoo.com], Vit [nevzorov@yahoo.com],
Vitalik [2vitalik@gmail.com], Quadr0 [quadr02005@gmail.com])
@created(2003)
@lastmod(01.08.2005 17:24:09)
}
{$IFNDEF QSYNUNIREG}
unit SynUniReg;
{$ENDIF}
interface
{$I SynUniHighlighter.inc}
uses
{$IFDEF SYN_COMPILER_6_UP}
DesignIntf,
DesignEditors,
{$ELSE}
DsgnIntf,
{$ENDIF}
{$IFDEF SYN_CLX}
Qt,
QDialogs,
QSynEditStrConst,
QSynUniHighlighter;
{$ELSE}
Classes,
Dialogs,
SynEditStrConst,
SynUniHighlighter,
{$IFDEF INTERNAL_DESIGNER}
SynUniDesigner,
{$ENDIF}
Windows;
{$ENDIF}
type
TSynUniEditor = class(TDefaultEditor)
procedure Edit; override;
procedure Load;
procedure Clear;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
resourcestring
sEdit = 'Edit...';
sLoadFromFile = 'Load From File...';
sClear = 'Clear';
procedure Register;
implementation
//------------------------------------------------------------------------------
procedure Register;
begin
RegisterComponents(SYNS_ComponentsPage, [TSynUniSyn]);
RegisterComponentEditor(TSynUniSyn, TSynUniEditor);
end;
//------------------------------------------------------------------------------
{* * * * * * * * * * * * * * TSynUniEditor * * * * * * * * * * * * * * * * * * }
//------------------------------------------------------------------------------
procedure TSynUniEditor.Edit;
begin
{$IFDEF INTERNAL_DESIGNER}
if TSynUniDesigner.EditHighlighter( Component as TSynUniSyn ) then
Designer.Modified();
{$IFDEF UNIDESIGNER20}Designer.Modified();{$ENDIF}
{$ELSE}
MessageBox(0, 'Sorry, internal SynUniDesigner is disabled', 'Information', MB_ICONINFORMATION);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TSynUniEditor.Load;
var
OpenDlg: TOpenDialog;
begin
OpenDlg := TOpenDialog.Create(nil);
if OpenDlg.Execute then
begin
(Component as TSynUniSyn).LoadFromFile(OpenDlg.FileName);
Designer.Modified();
end;
OpenDlg.Free;
end;
//------------------------------------------------------------------------------
procedure TSynUniEditor.Clear;
begin
(Component as TSynUniSyn).Clear;
Designer.Modified();
end;
//------------------------------------------------------------------------------
procedure TSynUniEditor.ExecuteVerb(Index: Integer);
begin
if GetVerb(Index) = 'Edit...' then
Edit
else
if GetVerb(Index) = 'Load From File...' then
Load
else
if GetVerb(Index) = 'Clear' then
Clear;
end;
//------------------------------------------------------------------------------
function TSynUniEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := sEdit;
1: Result := sLoadFromFile;
2: Result := sClear;
end;
end;
//------------------------------------------------------------------------------
function TSynUniEditor.GetVerbCount: Integer;
begin
Result := 3;
end;
end.
|
unit Objekt.Allgemein;
interface
uses
SysUtils, Classes, Winapi.Windows, Objekt.Ini, Objekt.DHLSend;
type
TAllgemeinObj = class
private
fIni: TIni;
fDHLSend: TDHLSend;
fDownloadPath: string;
protected
public
constructor Create;
destructor Destroy; override;
procedure Init;
property Ini: TIni read fIni write fIni;
property DHLSend: TDHLSend read fDHLSend write fDHLSend;
property DownloadPath: string read fDownloadPath;
end;
var
AllgemeinObj: TAllgemeinObj;
implementation
{ TAllgemeinObj }
constructor TAllgemeinObj.Create;
begin
init;
fIni := TIni.Create;
fDHLSend := TDHLSend.Create;
fDHLSend.Username := fIni.Authentication_User;
fDHLSend.Password := fIni.Authentication_Password;
fDHLSend.cisUser := fIni.cis_User;
fDHLSend.cisSignature := fIni.cis_Password;
fDHLSend.Url := fIni.Url;
fDownloadPath := ExtractFilePath(ParamStr(0));
end;
destructor TAllgemeinObj.Destroy;
begin
FreeAndNil(fIni);
FreeAndNil(fDHLSend);
inherited;
end;
procedure TAllgemeinObj.Init;
begin
end;
end.
|
unit uMRPinPad;
interface
uses Windows, SysUtils, Dialogs, VER1000XLib_TLB, VER2000XLib_TLB, uXML, uCreditCardFunction, uOperationSystem,
dbClient, classes, uSystemConst, OleCtrls, OleServer;
const
ctab = Chr(9);
ccrlf = Chr(13) + Chr(10);
type
TMRPinPad = class
private
FVer1000X : TVer1000X;
FComPort : String;
FMsg : String;
AXMLContent : TXMLContent;
FDataBits: String;
FBaud: String;
FComm: String;
FParity: String;
FDevice: String;
FEncryptMethod: String;
FTimeOut: String;
function ProcessRequest(FXML : WideString):String;
public
Constructor Create;
Destructor Destroy; override;
property Device : String read FDevice write FDevice;
property Baud : String read FBaud write FBaud;
property Parity : String read FParity write FParity;
property Comm : String read FComm write FComm;
property DataBits : String read FDataBits write FDataBits;
property EncryptMethod: String read FEncryptMethod write FEncryptMethod;
property TimeOut : String read FTimeOut write FTimeOut;
property Comport: String read FComport write FComport;
function GetDevice : String;
function InitializePinPad : Boolean;
function SetBaudRate : Boolean;
function GetPin(FAccountNo : String; FAmount: Currency; var FPINBlock, FDervdKey : String):Boolean;
function CancelRequest : Boolean;
function ResetPinPad : Boolean;
end;
implementation
{ TMRPinPad }
function TMRPinPad.CancelRequest: Boolean;
begin
try
FVer1000X.CancelRequest;
Result := True;
except
Result := False;
end;
end;
constructor TMRPinPad.Create;
begin
FVer1000X := TVer1000x.Create(nil);
AXMLContent := TXMLContent.Create;
end;
destructor TMRPinPad.Destroy;
begin
FreeAndNil(FVer1000X);
FreeAndNil(AXMLContent);
inherited;
end;
function TMRPinPad.GetDevice: String;
begin
if FDevice = 'Verifone' then
Result := '0'
else if FDevice = 'Ingenico' then
Result := '1'
else if FDevice = '550/5000' then
Result := '1'
else
Result := '0';
end;
function TMRPinPad.GetPin(FAccountNo: String; FAmount: Currency;
var FPINBlock, FDervdKey: String): Boolean;
var
strRequest, AResult: string;
begin
try
strRequest := '<?xml version="1.0"?>' + ccrlf + '<RequestStream>' + ccrlf +
ctab + ctab + '<ComPort>' + FComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Command>GetPin</Command>' + ccrlf +
ctab + ctab + '<Timeout>' + FTimeout + '</Timeout>' + ccrlf +
ctab + ctab + '<AccountNo>' + FAccountNo + '</AccountNo>' + ccrlf +
ctab + ctab + '<Amount>' + FormatFloat('0.00', FAmount) + '</Amount>' + ccrlf +
'</RequestStream>';
FMsg := '';
AXMLContent.XML := ProcessRequest(strRequest);
AResult := AXMLContent.GetAttributeString('CmdStatus');
if AResult <> 'Success' then
begin
FMsg := AResult + ' ' + AXMLContent.GetAttributeString('CmdStatus') + '. '+
AXMLContent.GetAttributeString('TextResponse');
Result := False;
end
else
begin
FPINBlock := AXMLContent.GetAttributeString('PINBlock');
FDervdKey := AXMLContent.GetAttributeString('DervdKey');
Result := True;
end;
finally
ReseTPinPad;
end;
end;
function TMRPinPad.InitializePinPad: Boolean;
var
strRequest, AResult: string;
begin
strRequest := '<?xml version="1.0"?>' + ccrlf + '<RequestStream>' + ccrlf +
ctab + ctab + '<ComPort>' + FComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Command>Init</Command>' + ccrlf +
ctab + ctab + '<IdlePrompt>' + 'MainRetail' + '</IdlePrompt>' + ccrlf +
'</RequestStream>';
FMsg := '';
AXMLContent.XML := ProcessRequest(strRequest);
AResult := AXMLContent.GetAttributeString('CmdStatus');
if AResult <> 'Success' then
begin
FMsg := AResult + ' ' + AXMLContent.GetAttributeString('CmdStatus') + '. '+
AXMLContent.GetAttributeString('TextResponse');
Result := False;
end
else
Result := True;
end;
function TMRPinPad.ProcessRequest(FXML: WideString): String;
begin
Result := FVer1000X.ProcessRequest(FXML, 0);
end;
function TMRPinPad.ResetPinPad: Boolean;
var
strRequest, AResult: string;
begin
strRequest := '<?xml version="1.0"?>' + ccrlf + '<RequestStream>' + ccrlf +
ctab + ctab + '<ComPort>' + FComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Command>ReseTPinPadDevice</Command>' + ccrlf +
'</RequestStream>';
FMsg := '';
AXMLContent.XML := ProcessRequest(strRequest);
AResult := AXMLContent.GetAttributeString('CmdStatus');
if AResult <> 'Success' then
begin
FMsg := AResult + ' ' + AXMLContent.GetAttributeString('CmdStatus') + '. '+
AXMLContent.GetAttributeString('TextResponse');
Result := False;
end
else
Result := True;
end;
function TMRPinPad.SetBaudRate: Boolean;
var
strRequest, AResult: string;
begin
strRequest := '<?xml version="1.0"?>' + ccrlf + '<RequestStream>' + ccrlf +
ctab + ctab + '<ComPort>' + FComPort + '</ComPort>' + ccrlf +
ctab + ctab + '<Command>SetBaudRate</Command>' + ccrlf +
'</RequestStream>';
FMsg := '';
AXMLContent.XML := ProcessRequest(strRequest);
AResult := AXMLContent.GetAttributeString('CmdStatus');
if AResult <> 'Success' then
begin
FMsg := AResult + ' ' + AXMLContent.GetAttributeString('CmdStatus') + '. '+
AXMLContent.GetAttributeString('TextResponse');
Result := False;
end
else
Result := True;
end;
end.
|
unit DocHostUIHandler;
interface
uses
Windows, ActiveX;
const
DOCHOSTUIFLAG_DIALOG = $00000001;
DOCHOSTUIFLAG_DISABLE_HELP_MENU = $00000002;
DOCHOSTUIFLAG_NO3DBORDER = $00000004;
DOCHOSTUIFLAG_SCROLL_NO = $00000008;
DOCHOSTUIFLAG_DISABLE_SCRIPT_INACTIVE = $00000010;
DOCHOSTUIFLAG_OPENNEWWIN = $00000020;
DOCHOSTUIFLAG_DISABLE_OFFSCREEN = $00000040;
DOCHOSTUIFLAG_FLAT_SCROLLBAR = $00000080;
DOCHOSTUIFLAG_DIV_BLOCKDEFAULT = $00000100;
DOCHOSTUIFLAG_ACTIVATE_CLIENTHIT_ONLY = $00000200;
DOCHOSTUIFLAG_OVERRIDEBEHAVIORFACTORY = $00000400;
DOCHOSTUIFLAG_CODEPAGELINKEDFONTS = $00000800;
DOCHOSTUIFLAG_URL_ENCODING_DISABLE_UTF8 = $00001000;
DOCHOSTUIFLAG_URL_ENCODING_ENABLE_UTF8 = $00002000;
DOCHOSTUIFLAG_ENABLE_FORMS_AUTOCOMPLETE = $00004000;
DOCHOSTUIFLAG_ENABLE_INPLACE_NAVIGATION = $00010000;
DOCHOSTUIFLAG_IME_ENABLE_RECONVERSION = $00020000;
DOCHOSTUIFLAG_THEME = $00040000;
DOCHOSTUIFLAG_NOTHEME = $00080000;
DOCHOSTUIFLAG_NOPICS = $00100000;
DOCHOSTUIFLAG_NO3DOUTERBORDER = $00200000;
DOCHOSTUIFLAG_DISABLE_EDIT_NS_FIXUP = $1;
DOCHOSTUIFLAG_LOCAL_MACHINE_ACCESS_CHECK = $1;
DOCHOSTUIFLAG_DISABLE_UNTRUSTEDPROTOCOL = $1;
DOCHOSTUIDBLCLK_DEFAULT = 0;
DOCHOSTUIDBLCLK_SHOWPROPERTIES = 1;
DOCHOSTUIDBLCLK_SHOWCODE = 2;
DOCHOSTUITYPE_BROWSE = 0;
DOCHOSTUITYPE_AUTHOR = 1;
type
TDocHostUIInfo = record
cbSize: ULONG;
dwFlags: DWORD;
dwDoubleClick: DWORD;
pchHostCss: PWChar;
pchHostNS: PWChar;
end;
PDocHostUIInfo = ^TDocHostUIInfo;
IDocHostUIHandler = interface(IUnknown)
['{bd3f23c0-d43e-11cf-893b-00aa00bdce1a}']
function ShowContextMenu(const dwID: DWORD; const ppt: PPOINT;
const pcmdtReserved: IUnknown; const pdispReserved: IDispatch): HResult;
stdcall;
function GetHostInfo(var pInfo: TDocHostUIInfo): HResult; stdcall;
function ShowUI(const dwID: DWORD;
const pActiveObject: IOleInPlaceActiveObject;
const pCommandTarget: IOleCommandTarget; const pFrame: IOleInPlaceFrame;
const pDoc: IOleInPlaceUIWindow): HResult; stdcall;
function HideUI: HResult; stdcall;
function UpdateUI: HResult; stdcall;
function EnableModeless(const fEnable: BOOL): HResult; stdcall;
function OnDocWindowActivate(const fActivate: BOOL): HResult; stdcall;
function OnFrameWindowActivate(const fActivate: BOOL): HResult; stdcall;
function ResizeBorder(const prcBorder: PRECT;
const pUIWindow: IOleInPlaceUIWindow; const fFrameWindow: BOOL): HResult;
stdcall;
function TranslateAccelerator(const lpMsg: PMSG; const pguidCmdGroup: PGUID;
const nCmdID: DWORD): HResult; stdcall;
function GetOptionKeyPath(var pchKey: POLESTR; const dw: DWORD ): HResult;
stdcall;
function GetDropTarget(const pDropTarget: IDropTarget;
out ppDropTarget: IDropTarget): HResult; stdcall;
function GetExternal(out ppDispatch: IDispatch): HResult; stdcall;
function TranslateUrl(const dwTranslate: DWORD; const pchURLIn: POLESTR;
var ppchURLOut: POLESTR): HResult; stdcall;
function FilterDataObject(const pDO: IDataObject;
out ppDORet: IDataObject): HResult; stdcall;
end;
implementation
end.
|
unit fPrint;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Buttons,
Vcl.ExtCtrls,
Vcl.Printers,
uGlobal;
type
TPrintForm = class(TForm)
Panel: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
EditScale: TEdit;
EditLeft: TEdit;
EditTop: TEdit;
EditWidth: TEdit;
EditHeight: TEdit;
UnitRG: TRadioGroup;
CloseBitBtn: TBitBtn;
OKBitBtn: TBitBtn;
Image: TImage;
FitToPageButton: TSpeedButton;
PageCentreButton: TSpeedButton;
ColorDialog: TColorDialog;
ColorButton: TSpeedButton;
Label6: TLabel;
EditBorder: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FloatKeyPress(Sender: TObject; var Key: Char);
procedure ScaleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure numKeyPress(Sender: TObject; var Key: Char);
procedure LeftKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure TopKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure WidthKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure HeightKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure UnitRGClick(Sender: TObject);
procedure FitToPageButtonClick(Sender: TObject);
procedure PageCentreButtonClick(Sender: TObject);
procedure ColorButtonClick(Sender: TObject);
procedure CloseBitBtnClick(Sender: TObject);
procedure EditBorderKeyPress(Sender: TObject; var Key: Char);
procedure EditBorderKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
bmpScale: double;
bmpLeft: integer; { as pixels }
bmpTop: integer; { as pixels }
bmpWidth: integer; { as pixels }
bmpHeight: integer; { as pixels }
BorderWidth: integer;
BorderColor: TColor;
vubmp: TBitMap;
procedure PaintImage;
procedure ShowData(Sender: TObject);
function PixelTomm(const v, t: integer): double;
function PixelTocm(const v, t: integer): double;
function PixelToInch(const v, t: integer): double;
function mmToPixel(const v: double; const t: integer): integer;
function cmToPixel(const v: double; const t: integer): integer;
function InchToPixel(const v: double; const t: integer): integer;
end;
var
PrintForm: TPrintForm;
//========================================================================
implementation
//========================================================================
uses
fMain;
{$R *.dfm}
procedure TPrintForm.FormCreate(Sender: TObject);
begin
with Layout do
begin
if bmpScale = 0 then
begin
Left := (Screen.Width - Width) div 2;
Top := (Screen.Height - Height) div 2;
UnitRG.ItemIndex := 0;
bmpScale := 1;
BorderColor := ClRed;
BorderWidth := 10;
end
else
begin
Left := PrintLeft;
Top := PrintTop;
UnitRG.ItemIndex := PrintUnit;
bmpScale := PrintScale;
BorderColor := PrintBorderColor;
BorderWidth := PrintBorderWidth;
end;
end;
bmpWidth := round(bmpScale*MainForm.GLViewer.Width);
bmpHeight := round(bmpScale*MainForm.GLViewer.Height);
ShowData(Sender);
vubmp := TBitMap.Create;
vubmp.Width := Image.Width;
vubmp.Height := Image.Height;
end;
procedure TPrintForm.FormShow(Sender: TObject);
begin
with MainForm.GLMemoryViewer do
begin
Width := vubmp.Width;
Height := vubmp.Height;
Buffer.BackgroundColor := GraphData.BackColor;
Render;
vubmp := Buffer.CreateSnapShotBitmap;
end;
UnitRG.SetFocus;
UnitRG.ItemIndex := 0;
UnitRGClick(Sender);
EditScale.SetFocus;
end;
procedure TPrintForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
BorderRect: TRect;
GraphRect: TRect;
bmp: TBitmap;
begin
if ModalResult = mrOK then
begin
BorderRect := Rect(bmpLeft + BorderWidth div 2, bmpTop + BorderWidth div 2,
bmpLeft + bmpWidth - BorderWidth div 2 + 1,
bmpTop + bmpHeight - BorderWidth div 2 + 1);
GraphRect := Rect(0, 0, bmpWidth - 2*BorderWidth,
bmpHeight - 2*BorderWidth);
Printer.Title := MainForm.Caption;
Printer.BeginDoc;
bmp := TBitmap.Create;
try
bmp.PixelFormat := pf32bit;
{ bmp is a device-independent true-color 32 bits per pixel bitmap. }
with GraphRect do
begin
bmp.Width := Right - Left;
bmp.Height := Bottom - Top;
end;
with MainForm.GLMemoryViewer do
begin
Width := bmp.Width;
Height := bmp.Height;
Buffer.BackgroundColor := GraphData.BackColor;
Render;
bmp := Buffer.CreateSnapShotBitmap;
end;
Printer.Canvas.Pen.Color := BorderColor;
Printer.Canvas.Pen.Width := BorderWidth;
Printer.Canvas.Rectangle(BorderRect);
Printer.Canvas.Draw(bmpLeft + BorderWidth, bmpTop + BorderWidth, bmp);
finally
Printer.EndDoc;
bmp.Free;
end;
end;
vubmp.Free;
with Layout do
begin
PrintLeft := Left;
PrintTop := Top;
PrintUnit := UnitRG.ItemIndex;
PrintScale := bmpScale;
PrintBorderColor := BorderColor;
PrintBorderWidth := BorderWidth;
end;
end;
procedure TPrintForm.FloatKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
if not CharInSet(Key, ['0'..'9', '.', #8]) then Key := #0
end;
procedure TPrintForm.ScaleKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
try
bmpScale := StrToFloat(EditScale.Text);
except
bmpScale := 1.0;
end;
bmpWidth := round(bmpScale*MainForm.GLViewer.Width);
if bmpWidth > PrinterInfo.xRes then
begin
bmpWidth := PrinterInfo.xRes;
bmpScale := bmpWidth/MainForm.GLViewer.Width;
bmpHeight := round(bmpScale*MainForm.GLViewer.Height);
ShowData(Sender);
Exit;
end;
bmpHeight := round(bmpScale*MainForm.GLViewer.Height);
if bmpHeight > PrinterInfo.yRes then
begin
bmpHeight := PrinterInfo.yRes;
bmpScale := bmpHeight/MainForm.GLViewer.Height;
bmpWidth := round(bmpScale*MainForm.GLViewer.Width);
ShowData(Sender);
Exit;
end;
ShowData(Sender);
end;
procedure TPrintForm.numKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
begin
if UnitRG.ItemIndex = 0 then
begin
if not CharInSet(Key, ['0'..'9', #8]) then Key := #0
end
else if not CharInSet(Key, ['0'..'9', '.', #8]) then Key := #0
end;
end;
procedure TPrintForm.LeftKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
v: double;
begin
try
v := StrToFloat(EditLeft.Text);
except
v := 10;
end;
case UnitRG.ItemIndex of
0:bmpLeft := round(v);
1:bmpLeft := mmToPixel(v, 0);
2:bmpLeft := cmToPixel(v, 0);
3:bmpLeft := InchToPixel(v, 0);
end;
ShowData(Sender);
end;
procedure TPrintForm.TopKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
v: double;
begin
try
v := StrToFloat(EditTop.Text);
except
v := 10;
end;
case UnitRG.ItemIndex of
0:bmpTop := round(v);
1:bmpTop := mmToPixel(v, 0);
2:bmpTop := cmToPixel(v, 0);
3:bmpTop := InchToPixel(v, 0);
end;
ShowData(Sender);
end;
procedure TPrintForm.WidthKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
v: double;
begin
try
v := StrToFloat(EditWidth.Text);
except
v := bmpScale*MainForm.GLViewer.Width;
end;
case UnitRG.ItemIndex of
0:bmpWidth := round(v);
1:bmpWidth := mmToPixel(v, 0);
2:bmpWidth := cmToPixel(v, 0);
3:bmpWidth := InchToPixel(v, 0);
end;
if bmpWidth > PrinterInfo.xRes then
begin
bmpWidth := PrinterInfo.xRes;
end;
bmpScale := bmpWidth/MainForm.GLViewer.Width;
bmpHeight := round(bmpScale*MainForm.GLViewer.Height);
ShowData(Sender);
end; { TPrintForm.WidthKeyUp }
procedure TPrintForm.HeightKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
v: double;
begin
try
v := StrToFloat(EditHeight.Text);
except
v := bmpScale*MainForm.GLViewer.Height;
end;
case UnitRG.ItemIndex of
0:bmpHeight := round(v);
1:bmpHeight := mmToPixel(v, 0);
2:bmpHeight := cmToPixel(v, 0);
3:bmpHeight := InchToPixel(v, 0);
end;
if bmpHeight > PrinterInfo.yRes then
begin
bmpHeight := PrinterInfo.yRes;
end;
bmpScale := bmpHeight/MainForm.GLViewer.Height;
bmpWidth := round(bmpScale*MainForm.GLViewer.Width);
ShowData(Sender);
end;
procedure TPrintForm.UnitRGClick(Sender: TObject);
begin
ShowData(Sender);
end;
procedure TPrintForm.FitToPageButtonClick(Sender: TObject);
var
i: integer;
begin
UnitRG.SetFocus;
i := UnitRG.ItemIndex;
UnitRG.ItemIndex := 0;
bmpScale := 1;
bmpLeft := 0;
bmpTop := 0;
bmpHeight := MainForm.GLViewer.Height;
bmpWidth := MainForm.GLViewer.Width;
bmpWidth := Printer.PageWidth - 2*bmpLeft;
bmpScale := bmpWidth/MainForm.GLViewer.Width;
bmpHeight := round(bmpScale*MainForm.GLViewer.Height);
if bmpHeight > Printer.PageHeight - 2*bmpTop then
begin
bmpHeight := Printer.PageHeight - 2*bmpTop;
bmpScale := bmpHeight/MainForm.GLViewer.Height;
bmpWidth := round(bmpScale*MainForm.GLViewer.Width);
end;
ShowData(Sender);
UnitRG.SetFocus;
UnitRG.ItemIndex := i
end;
procedure TPrintForm.PageCentreButtonClick(Sender: TObject);
var
i: integer;
begin
UnitRG.SetFocus;
i := UnitRG.ItemIndex;
UnitRG.ItemIndex := 0;
if bmpLeft + bmpWidth > Printer.PageWidth then bmpLeft := 0;
if bmpTop + bmpHeight > Printer.PageHeight then bmpTop := 0;
if bmpWidth > Printer.PageWidth then
begin
bmpWidth := Printer.PageWidth;
bmpScale := bmpWidth/MainForm.GLViewer.Width;
bmpHeight := round(bmpScale*MainForm.GLViewer.Height);
end;
if bmpHeight > Printer.PageHeight then
begin
bmpHeight := Printer.PageHeight;
bmpScale := bmpHeight/MainForm.GLViewer.Height;
bmpWidth := round(bmpScale*MainForm.GLViewer.Width);
end;
bmpLeft := (Printer.PageWidth - bmpWidth) div 2;
bmpTop := (Printer.PageHeight - bmpHeight) div 2;
ShowData(Sender);
UnitRG.SetFocus;
UnitRG.ItemIndex := i
end;
procedure TPrintForm.ColorButtonClick(Sender: TObject);
begin
ColorDialog.Color := BorderColor;
if ColorDialog.Execute then
begin
BorderColor := ColorDialog.Color;
PaintImage;
end;
end;
procedure TPrintForm.EditBorderKeyPress(Sender: TObject; var Key: Char);
begin
if not CharInSet(Key, ['0'..'9', #8]) then Key := #0
end;
procedure TPrintForm.EditBorderKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
v: integer;
begin
try
v := StrToInt(EditBorder.Text);
except
v := 10;
end;
BorderWidth := v;
ShowData(Sender);
end;
procedure TPrintForm.PaintImage;
var
PaperWidthPix: integer;
PaperHeightPix: integer;
PrintAreaWidthPix: integer;
PrintAreaHeightPix: integer;
dx, dy: integer;
Scale: double;
Shade: TRect;
Paper: TRect;
PrintArea: TRect;
Graph: TRect;
begin
{ calculations }
PaperWidthPix := PrinterInfo.xRes+2*PrinterInfo.xOffset;
PaperHeightPix := PrinterInfo.yRes+2*PrinterInfo.yOffset;
if PaperWidthPix > PaperHeightPix
then Scale := 0.95*Image.Width/PaperWidthPix
else Scale := 0.95*Image.Height/PaperHeightPix;
PaperHeightPix := round(Scale*PaperHeightPix);
PaperWidthPix := round(Scale*PaperWidthPix);
PrintAreaWidthPix := round(Scale*PrinterInfo.xRes);
PrintAreaHeightPix := round(Scale*PrinterInfo.yRes);
Paper.Top := (Image.Height - PaperHeightPix) div 2 - 3;
Paper.Left := (Image.Width - PaperWidthPix) div 2 - 3;
Paper.Bottom := Paper.Top + PaperHeightPix;
Paper.Right := Paper.Left + PaperWidthPix;
dx := round(Scale*PrinterInfo.xOffset);
dy := round(Scale*PrinterInfo.yOffset);
PrintArea.Top := Paper.Top + dy;
PrintArea.Left := Paper.Left + dx;
PrintArea.Bottom := PrintArea.Top + PrintAreaHeightPix;
PrintArea.Right := PrintArea.Left + PrintAreaWidthPix;
Shade := Paper;
Inc(Shade.Top, 6);
Inc(Shade.Left, 6);
Inc(Shade.Bottom, 6);
Inc(Shade.Right, 6);
if bmpWidth < 100 then bmpWidth := 100;
if bmpHeight < 100 then bmpHeight := 100;
Graph.Left := PrintArea.Left + round(Scale*bmpLeft);
Graph.Top := PrintArea.Top + round(Scale*bmpTop);
Graph.Right := Graph.Left + round(Scale*bmpWidth);
Graph.Bottom := Graph.Top + round(Scale*bmpHeight);
with Image.Canvas do
begin
with Brush do
begin
Style := bsSolid;
Color := clCream;
end;
FillRect(Rect(0, 0, Image.Width, Image.Height));
Brush.Color := clSilver;
Pen.Color := clBlack;
FillRect(Shade);
Brush.Color := clWhite;
FillRect(Paper);
Rectangle(Paper);
Pen.Color := clBlue;
Rectangle(PrintArea);
StretchDraw(Graph, vubmp);
if BorderWidth > 0 then
begin
Brush.Color := BorderColor;
FrameRect(Graph);
end;
end;
end;
procedure TPrintForm.ShowData(Sender: TObject);
procedure TagIsZero;
begin
EditScale.Text := FloatToStrF(bmpScale, ffFixed, 6, 3);
case UnitRg.ItemIndex of
0:begin { pixels }
EditLeft.Text := IntToStr(bmpLeft);
EditTop.Text := IntToStr(bmpTop);
EditWidth.Text := IntToStr(bmpWidth);
EditHeight.Text := IntToStr(bmpHeight);
end;
1:begin { mm }
EditLeft.Text :=
FloatToStrF(PixelTomm(bmpLeft, 0), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelTomm(bmpTop, 0), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelTomm(bmpWidth, 0), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelTomm(bmpHeight, 0), ffFixed, 6, 3);
end;
2:begin { cm }
EditLeft.Text :=
FloatToStrF(PixelTocm(bmpLeft, 0), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelTocm(bmpTop, 0), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelTocm(bmpWidth, 0), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelTocm(bmpHeight, 0), ffFixed, 6, 3);
end;
3:begin { inch }
EditLeft.Text :=
FloatToStrF(PixelToInch(bmpLeft, 0), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelToInch(bmpTop, 0), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelToInch(bmpWidth, 0), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelToInch(bmpHeight, 0), ffFixed, 6, 3);
end;
end;
end; { TagIsZero }
begin
if Sender is TEdit then
begin
with Sender as TEdit do
case Tag of
0:TagIsZero; { Factor etc. }
1:begin { Scale }
case UnitRg.ItemIndex of
0:begin { pixels }
EditLeft.Text := IntToStr(bmpLeft);
EditTop.Text := IntToStr(bmpTop);
EditWidth.Text := IntToStr(bmpWidth);
EditHeight.Text := IntToStr(bmpHeight);
end;
1:begin { mm }
EditLeft.Text :=
FloatToStrF(PixelTomm(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelTomm(bmpTop, Tag), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelTomm(bmpWidth, Tag), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelTomm(bmpHeight, Tag), ffFixed, 6, 3);
end;
2:begin { cm }
EditLeft.Text :=
FloatToStrF(PixelTocm(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelTocm(bmpTop, Tag), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelTocm(bmpWidth, Tag), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelTocm(bmpHeight, Tag), ffFixed, 6, 3);
end;
3:begin { inch }
EditLeft.Text :=
FloatToStrF(PixelToInch(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelToInch(bmpTop, Tag), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelToInch(bmpWidth, Tag), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelToInch(bmpHeight, Tag), ffFixed, 6, 3);
end;
end;
end;
4:begin { Width }
EditScale.Text := FloatToStrF(bmpScale, ffFixed, 6, 3);
case UnitRg.ItemIndex of
0:EditHeight.Text := IntToStr(bmpHeight);
1:begin { mm }
EditLeft.Text :=
FloatToStrF(PixelTomm(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelTomm(bmpTop, Tag), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelTomm(bmpHeight, Tag), ffFixed, 6, 3);
end;
2:begin { cm }
EditLeft.Text :=
FloatToStrF(PixelTocm(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelTocm(bmpTop, Tag), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelTocm(bmpHeight, Tag), ffFixed, 6, 3);
end;
3:begin { inch }
EditLeft.Text :=
FloatToStrF(PixelToInch(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelToInch(bmpTop, Tag), ffFixed, 6, 3);
EditHeight.Text :=
FloatToStrF(PixelToInch(bmpHeight, Tag), ffFixed, 6, 3);
end;
end;
end;
5:begin { Height }
EditScale.Text := FloatToStrF(bmpScale, ffFixed, 6, 3);
case UnitRg.ItemIndex of
0:EditWidth.Text := IntToStr(bmpWidth);
1:begin { mm }
EditLeft.Text :=
FloatToStrF(PixelTomm(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelTomm(bmpTop, Tag), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelTomm(bmpWidth, Tag), ffFixed, 6, 3);
end;
2:begin { cm }
EditLeft.Text :=
FloatToStrF(PixelTocm(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelTocm(bmpTop, Tag), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelTocm(bmpWidth, Tag), ffFixed, 6, 3);
end;
3:begin { inch }
EditLeft.Text :=
FloatToStrF(PixelToInch(bmpLeft, Tag), ffFixed, 6, 3);
EditTop.Text :=
FloatToStrF(PixelToInch(bmpTop, Tag), ffFixed, 6, 3);
EditWidth.Text :=
FloatToStrF(PixelToInch(bmpWidth, Tag), ffFixed, 6, 3);
end;
end;
end;
end;
end
else TagIsZero; { UnitRG }
EditBorder.Text := IntToStr(BorderWidth);
PaintImage;
end;
function TPrintForm.PixelTomm(const v, t: integer): double;
begin
if odd(t)
then Result := 25.4*v/PrinterInfo.yPixPerInch
else Result := 25.4*v/PrinterInfo.xPixPerInch;
end;
function TPrintForm.PixelTocm(const v, t: integer): double;
begin
if odd(t)
then Result := 2.54*v/PrinterInfo.yPixPerInch
else Result := 2.54*v/PrinterInfo.xPixPerInch;
end;
function TPrintForm.PixelToInch(const v, t: integer): double;
begin
if odd(t)
then Result := v/PrinterInfo.yPixPerInch
else Result := v/PrinterInfo.xPixPerInch;
end;
function TPrintForm.mmToPixel(const v: double; const t: integer): integer;
begin
if odd(t)
then Result := round(PrinterInfo.yPixPerInch*v/25.4)
else Result := round(PrinterInfo.xPixPerInch*v/25.4);
end;
function TPrintForm.cmToPixel(const v: double; const t: integer): integer;
begin
if odd(t)
then Result := round(PrinterInfo.yPixPerInch*v/2.54)
else Result := round(PrinterInfo.xPixPerInch*v/2.54);
end;
function TPrintForm.InchToPixel(const v: double; const t: integer): integer;
begin
if odd(t)
then Result := round(PrinterInfo.yPixPerInch*v)
else Result := round(PrinterInfo.xPixPerInch*v);
end;
procedure TPrintForm.CloseBitBtnClick(Sender: TObject);
begin
Close;
end;
end.
|
unit Data;
interface
uses
SysUtils,
Classes;
type
TResourceItem = class(TObject)
private
FResourceType: String;
FResourceName: String;
function GetData: TBytes;
public
constructor Create(const resourceType, resourceName: String);
function GetStream: TResourceStream;
property Data: TBytes read GetData;
property ResourceType: String read FResourceType write FResourceType;
property ResourceName: String read FResourceName write FResourceName;
end;
TResourceItems = class(TObject)
private
FItems: TList;
FIndex: Integer;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Add(const resourceType, resourceName: String);
function Current: TResourceItem;
function Next: TResourceItem;
function Previous: TResourceItem;
property Count: Integer read GetCount;
property Index: Integer read FIndex;
end;
implementation
uses
NtBase;
// TResourceItem
constructor TResourceItem.Create(const resourceType, resourceName: String);
begin
inherited Create;
FResourceType := resourceType;
FResourceName := resourceName;
end;
function TResourceItem.GetData: TBytes;
begin
Result := TNtResources.LoadResource(PChar(FResourceType), PChar(FResourceName));
end;
function TResourceItem.GetStream: TResourceStream;
begin
Result := TNtResources.GetResourceStream(PChar(FResourceType), PChar(FResourceName));
end;
// TResourceItems
constructor TResourceItems.Create;
begin
inherited;
FItems := TList.Create;
FIndex := -1;
end;
destructor TResourceItems.Destroy;
begin
FItems.Free;
inherited;
end;
function TResourceItems.GetCount: Integer;
begin
result := FItems.Count;
end;
procedure TResourceItems.Add(const resourceType, resourceName: String);
begin
FItems.Add(TResourceItem.Create(resourceType, resourceName));
if FIndex = -1 then
FIndex := 0;
end;
function TResourceItems.Current: TResourceItem;
begin
if FIndex >= 0 then
Result := FItems[FIndex]
else
Result := nil;
end;
function TResourceItems.Next: TResourceItem;
begin
if FIndex < FItems.Count - 1 then
Inc(FIndex)
else
FIndex := 0;
Result := Current;
end;
function TResourceItems.Previous: TResourceItem;
begin
if FIndex > 0 then
Dec(FIndex)
else
FIndex := FItems.Count - 1;
Result := Current;
end;
end.
|
unit form_findleftovers;
interface
uses Classes, Windows, SysUtils, DBCtrls, Forms, appconfig, form_dbtable, strtools, docparam;
type
TDbForm_findleftovers = class(TDbForm)
private
FConfig: TAppConfig;
protected
procedure FormClose(Sender: TObject; var Action: TCloseAction); override;
procedure SetConfig(AConfig: TAppConfig);
public
constructor Create(AOwner: TComponent); override;
procedure SetParams(Sender: TGoods); reintroduce;
procedure DataSetOpen(Sender: TObject); override;
procedure DataSetClose(Sender: TObject); override;
property Config: TAppConfig read FConfig write SetConfig;
end;
implementation
constructor TDbForm_findleftovers.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Position := poDesigned;
Caption := 'Поиск товаров для списания';
Grid.ReadOnly := true;
Navigator.VisibleButtons := [nbFirst, nbPrior, nbNext, nbLast, nbRefresh];
FConfig := nil;
end;
procedure TDbForm_findleftovers.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(FConfig) then
begin
FConfig.Write(ClassName, 'position', Self);
if DataSetActive then
begin
FConfig.Write(ClassName, 'grid', Grid);
end;
FConfig.Close;
end;
inherited;
end;
procedure TDbForm_findleftovers.SetConfig(AConfig: TAppConfig);
begin
FConfig := AConfig;
if Assigned(FConfig) then
begin
FConfig.Read(ClassName, 'position', Self);
if DataSetActive then
begin
FConfig.Read(ClassName, 'grid', Grid);
end;
FConfig.Close;
end;
end;
procedure TDbForm_findleftovers.DataSetOpen(Sender: TObject);
begin
inherited;
if Assigned(FConfig) then
begin
FConfig.Read(ClassName, 'grid', Grid);
FConfig.Close;
end;
end;
procedure TDbForm_findleftovers.DataSetClose(Sender: TObject);
begin
if Assigned(FConfig) then
if DataSetActive then
begin
FConfig.Write(ClassName, 'grid', Grid);
FConfig.Close;
end;
inherited;
end;
procedure TDbForm_findleftovers.SetParams(Sender: TGoods);
var
conn: boolean;
begin
if Assigned(DataSet) then
begin
conn := DataSet.Active;
DataSetClose(Self);
with DataSet do
begin
Params.ParamValues['PLIMIT'] := 200;
Params.ParamValues['PGOODS'] := Sender.Id;
Params.ParamValues['PARTICLE'] := Sender.Article;
Params.ParamValues['PNAME'] := Sender.Name;
Params.ParamValues['PDATE'] := round(int(Now()));
Params.ParamValues['PPLACE'] := Sender.PlaceId;
Params.ParamValues['PWAREHOUSE'] := Sender.WarehouseId;
Params.ParamValues['PSHIPMENT'] := Sender.ShipmentId;
end;
if conn then
DataSetOpen(Self);
end;
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.Actions, System.IOUtils, System.Math,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListBox,
FMX.Layouts, FMX.StdCtrls, FMX.TabControl, FMX.Objects, System.UIConsts,
FMX.Gestures, FMX.ActnList, FMX.Memo, FMX.Edit,
NetworkState, OpenViewUrl, SendMail, BarCodeReader,
ToastMessage
{$IFDEF ANDROID}
, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge;
{$ENDIF}
{$IFDEF IOS}
;
{$ENDIF}
const
bufferSize = 500; // BLUETOOTH receive buffer
type
TMainForm = class(TForm)
TabControlMain: TTabControl;
tabOpenURL: TTabItem;
tabNetworkStatus: TTabItem;
ToolBar1: TToolBar;
butOpen: TSpeedButton;
lsbMain: TListBox;
ListBoxGroupHeader1: TListBoxGroupHeader;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
ListBoxItem6: TListBoxItem;
ListBoxItem7: TListBoxItem;
ListBoxItem8: TListBoxItem;
ListBoxGroupHeader2: TListBoxGroupHeader;
ListBoxItem5: TListBoxItem;
ListBoxGroupHeader3: TListBoxGroupHeader;
ListBoxItem9: TListBoxItem;
ListBoxItem10: TListBoxItem;
ListBoxItem11: TListBoxItem;
ListBoxItem12: TListBoxItem;
ToolBar2: TToolBar;
CircleNET: TCircle;
CircleWiFi: TCircle;
Circle3G: TCircle;
timNetwork: TTimer;
SwitchNetwork: TSwitch;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
GestureManager1: TGestureManager;
ActionList1: TActionList;
ChangeTabAction0: TChangeTabAction;
ChangeTabAction1: TChangeTabAction;
tabSendMail: TTabItem;
edtTo: TEdit;
edtSubject: TEdit;
memBody: TMemo;
butSend: TButton;
ChangeTabAction2: TChangeTabAction;
tabBarCode: TTabItem;
ToolBar3: TToolBar;
butBarcode: TButton;
lstBarCode: TListBox;
butQRCode: TSpeedButton;
ChangeTabAction3: TChangeTabAction;
tabToast: TTabItem;
Button1: TButton;
ChangeTabAction4: TChangeTabAction;
procedure butOpenClick(Sender: TObject);
procedure timNetworkTimer(Sender: TObject);
procedure SwitchNetworkSwitch(Sender: TObject);
procedure TabControlMainGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
procedure FormCreate(Sender: TObject);
procedure butSendClick(Sender: TObject);
procedure butBarcodeClick(Sender: TObject);
procedure butQRCodeClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
fZBarReader: TBarCodeReader;
fNetworkStatus: TMobileNetworkStatus;
procedure MyZBarReaderGetResult(Sender: TBarCodeReader; AResult: string);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
{$IFDEF ANDROID}
uses uSplashScreen;
{$ENDIF}
procedure TMainForm.butOpenClick(Sender: TObject);
begin
if lsbMain.Selected <> nil then
if lsbMain.Selected.Text <> '' then
OpenURL(lsbMain.Selected.Text);
end;
procedure TMainForm.butBarcodeClick(Sender: TObject);
begin
fZBarReader.Show;
end;
procedure TMainForm.butQRCodeClick(Sender: TObject);
begin
fZBarReader.Show(True);
end;
procedure TMainForm.butSendClick(Sender: TObject);
begin
CreateEmail(edtTo.Text, edtSubject.Text, memBody.Text, '');
end;
procedure TMainForm.Button1Click(Sender: TObject);
begin
AndroidToast('Using Native Toast for Android!', ShortToast);
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
{$IFDEF ANDROID}
ShowSplashScreen;
butQRCode.Visible := True;
{$ENDIF}
fZBarReader := TBarCodeReader.Create(Self);
fZBarReader.OnGetResult := MyZBarReaderGetResult;
fNetworkStatus := TMobileNetworkStatus.Create;
end;
procedure TMainForm.MyZBarReaderGetResult(Sender: TBarCodeReader;
AResult: string);
begin
lstBarCode.Items.Insert(0, AResult);
end;
procedure TMainForm.SwitchNetworkSwitch(Sender: TObject);
begin
timNetwork.Enabled := SwitchNetwork.Enabled;
end;
procedure TMainForm.TabControlMainGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
case EventInfo.GestureID of
sgiLeft:
begin
if TabControlMain.TabIndex = 0 then
begin
ChangeTabAction1.ExecuteTarget(Self);
Handled := True;
end
else if TabControlMain.TabIndex = 1 then
begin
ChangeTabAction2.ExecuteTarget(Self);
Handled := True;
end
else if TabControlMain.TabIndex = 2 then
begin
ChangeTabAction3.ExecuteTarget(Self);
Handled := True;
end
else if TabControlMain.TabIndex = 3 then
begin
ChangeTabAction4.ExecuteTarget(Self);
Handled := True;
end;
end;
sgiRight:
begin
if TabControlMain.TabIndex = 4 then
begin
ChangeTabAction3.ExecuteTarget(Self);
Handled := True;
end
else if TabControlMain.TabIndex = 3 then
begin
ChangeTabAction2.ExecuteTarget(Self);
Handled := True;
end
else if TabControlMain.TabIndex = 2 then
begin
ChangeTabAction1.ExecuteTarget(Self);
Handled := True;
end
else if TabControlMain.TabIndex = 1 then
begin
ChangeTabAction0.ExecuteTarget(Self);
Handled := True;
end;
end;
end;
end;
procedure TMainForm.timNetworkTimer(Sender: TObject);
begin
if fNetworkStatus.isConnected then
CircleNET.Fill.Color := claGreen
else
CircleNET.Fill.Color := claRed;
if fNetworkStatus.IsWiFiConnected then
CircleWiFi.Fill.Color := claGreen
else
CircleWiFi.Fill.Color := claRed;
if fNetworkStatus.IsMobileConnected then
Circle3G.Fill.Color := claGreen
else
Circle3G.Fill.Color := claRed;
end;
end.
|
unit AST.Delphi.Operators;
interface
{$I compilers.inc}
uses SysUtils, Classes;
type
TOperatorID = (
// not oveloaded: //////////////////
opNone,
opOpenRound,
opCloseRound,
opSubExpression,
opCall,
opDereference,
opPeriod,
opAddr,
opIs,
opAs,
// oveloaded: //////////////////////
opAssignment,
// unar:
opImplicit,
opExplicit,
opNegative,
opPositive,
opNot,
// binar:
opIn,
opEqual,
opNotEqual,
opGreater,
opGreaterOrEqual,
opLess,
opLessOrEqual,
opAdd,
opSubtract,
opMultiply,
opDivide,
opIntDiv,
opModDiv,
opShiftLeft,
opShiftRight,
opAnd,
opOr,
opXor
);
TOperatorType =
(
opSpecial,
opBinary,
opUnarPrefix,
opUnarSufix
);
{ signatures of operators:
|--------------------|------------|------------------------------------------------|-------------------|
| Operator | Category | Declaration Signature | Symbol Mapping |
|--------------------|------------|------------------------------------------------|-------------------|
| Implicit | Conversion | Implicit(a : type) : resultType; | implicit typecast |
| Explicit | Conversion | Explicit(a: type) : resultType; | explicit typecast |
| Negative | Unary | Negative(a: type) : resultType; | - |
| Positive | Unary | Positive(a: type): resultType; | + |
| LogicalNot | Unary | LogicalNot(a: type): resultType; | not |
| In | Set | In(a: type; b: type) : Boolean; | in |
| Eq | Comparison | Equal(a: type; b: type) : Boolean; | = |
| NotEqual | Comparison | NotEqual(a: type; b: type): Boolean; | <> |
| GreaterThan | Comparison | GreaterThan(a: type; b: type) Boolean; | > |
| GreaterThanOrEqual | Comparison | GreaterThanOrEqual(a: type; b: type): Boolean; | >= |
| LessThan | Comparison | LessThan(a: type; b: type): Boolean; | < |
| LessThanOrEqual | Comparison | LessThanOrEqual(a: type; b: type): Boolean; | <= |
| Add | Binary | Add(a: type; b: type): resultType; | + |
| Subtract | Binary | Subtract(a: type; b: type) : resultType; | - |
| Multiply | Binary | Multiply(a: type; b: type) : resultType; | * |
| Divide | Binary | Divide(a: type; b: type) : resultType; | / |
| IntDivide | Binary | IntDivide(a: type; b: type): resultType; | div |
| Modulus | Binary | Modulus(a: type; b: type): resultType; | mod |
| LeftShift | Binary | LeftShift(a: type; b: type): resultType; | shl |
| RightShift | Binary | RightShift(a: type; b: type): resultType; | shr |
| LogicalAnd | Binary | LogicalAnd(a: type; b: type): resultType; | and |
| LogicalOr | Binary | LogicalOr(a: type; b: type): resultType; | or |
| LogicalXor | Binary | LogicalXor(a: type; b: type): resultType; | xor |
| BitwiseAnd | Binary | BitwiseAnd(a: type; b: type): resultType; | and |
| BitwiseOr | Binary | BitwiseOr(a: type; b: type): resultType; | or |
| BitwiseXor | Binary | BitwiseXor(a: type; b: type): resultType; | xor |
|--------------------|------------|------------------------------------------------|-------------------|}
function OperatorFullName(&Operator: TOperatorID): string;
function OperatorShortName(&Operator: TOperatorID): string;
function GetOperatorID(const Name: string): TOperatorID; inline;
// todo:
// 1. ( ).
// 2. not.
// 3. *, /, div, mod, and, shl, shr, as.
// 4. +, –, or, xor.
// 5. =, <>, <, >, <=, >=, in, is.
const
// Приоритеты операций (-1 - низший приоритет, 10 - высшый приоритет)
cOperatorPriorities: array [TOperatorID] of Integer = (
{opNone} -1,
{opOpenRound} 10,
{opCloseRound} 10,
{opSubExpression} -1,
{opCall} 9,
{opDereference} 8,
{opPeriod} 2,
{opAddr} 8,
{opIS} 8,
{opAS} 8,
{opAssign} 0,
{opImplicit} -1,
{opExplicit} -1,
{opNegative} 8,
{opPositive} 2,
{opLogicalNot} 8,
{opIn} 1,
{opEqual} 4,
{opNotEqual} 4,
{opGreaterThan} 4,
{opGreaterThanOrEqual} 4,
{opLessThan} 4,
{opLessThanOrEqual} 4,
{opAdd} 6,
{opSubtract} 6,
{opMultiply} 7,
{opDivide} 7,
{opIntDiv} 7,
{opModDiv} 7,
{opLeftShift} 7,
{opRightShift} 7,
{opLogicalAnd} 7,
{opLogicalOr} 5,
{opLogicalXor} 5
);
const
// Приоритеты операций (-1 - низший приоритет, 10 - высшый приоритет)
cOperatorTypes: array [TOperatorID] of TOperatorType = (
{opNone} opSpecial,
{opOpenRound} opSpecial,
{opCloseRound} opSpecial,
{opSubExpression} opSpecial,
{opCall} opSpecial,
{opDereference} opUnarSufix,
{opPeriod} opBinary,
{opAddr} opUnarPrefix,
{opIS} opBinary,
{opAS} opBinary,
{opAssign} opBinary,
{opImplicit} opSpecial,
{opExplicit} opSpecial,
{opNegative} opUnarPrefix,
{opPositive} opUnarPrefix,
{opLogicalNot} opUnarPrefix,
{opIn} opBinary,
{opEqual} opBinary,
{opNotEqual} opBinary,
{opGreaterThan} opBinary,
{opGreaterThanOrEqual} opBinary,
{opLessThan} opBinary,
{opLessThanOrEqual} opBinary,
{opAdd} opBinary,
{opSubtract} opBinary,
{opMultiply} opBinary,
{opDivide} opBinary,
{opIntDiv} opBinary,
{opModDiv} opBinary,
{opLeftShift} opBinary,
{opRightShift} opBinary,
{opLogicalAnd} opBinary,
{opLogicalOr} opBinary,
{opLogicalXor} opBinary
);
function NeedRValue(Op: TOperatorID): Boolean; inline;
var
_operators: TStringList = nil;
implementation
const
cOpFullNames: array [TOperatorID] of string = (
{opNone} '',
{opOpenRound} '(',
{opCloseRound} ')',
{opSubExpression} '',
{opCall} 'call',
{opDereference} 'Dereference',
{opPeriod} 'period',
{opAddr} 'Addr',
{opIS} 'IS',
{opAS} 'AS',
{opAssign} 'Assign',
{opImplicit} 'Implicit',
{opExplicit} 'Explicit',
{opNegative} 'Negative',
{opPositive} 'Positive',
{opLogicalNot} 'Not',
{opIn} 'In',
{opEqual} 'Equal',
{opNotEqual} 'NotEqual',
{opGreater} 'GreaterThan',
{opGreaterOrEqual} 'GreaterThanOrEqual',
{opLess} 'LessThan',
{opLessOrEqual} 'LessThanOrEqual',
{opAdd} 'Add',
{opSubtract} 'Subtract',
{opMultiply} 'Multiply',
{opDivide} 'Divide',
{opIntDiv} 'IntDivide',
{opModDiv} 'Modulus',
{opLeftShift} 'LeftShift',
{opRightShift} 'RightShift',
{opLogicalAnd} 'And',
{opLogicalOr} 'Or',
{opLogicalXor} 'Xor'
);
cOpShortNames: array [TOperatorID] of string = (
{opNone} '',
{opOpenRound} '(',
{opCloseRound} ')',
{opSubExpression} '',
{opCall} 'call',
{opDereference} '^',
{opPeriod} '..',
{opAddr} '@',
{opIs} 'is',
{opAs} 'as',
{opAssign} ':=',
{opImplicit} 'Implicit',
{opExplicit} 'Explicit',
{opNegative} 'Negative',
{opPositive} 'Positive',
{opLogicalNot} 'not',
{opIn} 'in',
{opEqual} '=',
{opNotEqual} '<>',
{opGreater} '>',
{opGreaterOrEqual} '>=',
{opLess} '<',
{opLessOrEqual} '<=',
{opAdd} '+',
{opSubtract} '-',
{opMultiply} '*',
{opDivide} '/',
{opIntDiv} 'div',
{opModDiv} 'mod',
{opLeftShift} 'shl',
{opRightShift} 'shr',
{opLogicalAnd} 'and',
{opLogicalOr} 'or',
{opLogicalXor} 'xor'
);
function NeedRValue(Op: TOperatorID): Boolean; inline;
begin
Result := (Op >= opPeriod);
end;
function OperatorFullName(&Operator: TOperatorID): string;
begin
Result := cOpFullNames[&Operator];
end;
function OperatorShortName(&Operator: TOperatorID): string;
begin
Result := cOpShortNames[&Operator];
end;
function GetOperatorID(const Name: string): TOperatorID; inline;
var
idx: Integer;
begin
idx := _operators.IndexOf(Name);
if idx >= 0 then
Result := TOperatorID(_operators.Objects[idx])
else
Result := opNone;
end;
initialization
_operators := TStringList.Create;
_operators.AddObject('Assignment', TObject(opAssignment));
_operators.AddObject('Implicit', TObject(opImplicit));
_operators.AddObject('Explicit', TObject(opExplicit));
_operators.AddObject('Negative', TObject(opNegative));
_operators.AddObject('Positive', TObject(opPositive));
_operators.AddObject('BitwiceNot', TObject(opNot));
_operators.AddObject('In', TObject(opIn));
_operators.AddObject('Equal', TObject(opEqual));
_operators.AddObject('NotEqual', TObject(opNotEqual));
_operators.AddObject('GreaterThan', TObject(opGreater));
_operators.AddObject('GreaterThanOrEqual', TObject(opGreaterOrEqual));
_operators.AddObject('LessThan', TObject(opLess));
_operators.AddObject('LessThanOrEqual', TObject(opLessOrEqual));
_operators.AddObject('Add', TObject(opAdd));
_operators.AddObject('Subtract', TObject(opSubtract));
_operators.AddObject('Multiply', TObject(opMultiply));
_operators.AddObject('Divide', TObject(opDivide));
_operators.AddObject('IntDiv', TObject(opIntDiv));
_operators.AddObject('ModDiv', TObject(opModDiv));
_operators.AddObject('ShiftLeft', TObject(opShiftLeft));
_operators.AddObject('ShiftRight', TObject(opShiftRight));
_operators.AddObject('BitwiceAnd', TObject(opAnd));
_operators.AddObject('BitwiceOr', TObject(opOr));
_operators.AddObject('BitwiceXor', TObject(opXor));
_operators.Sort;
finalization
_operators.Free;
end.
|
unit eduDialog;
interface
uses
Windows, Messages, SysUtils, Classes, Variants, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Vcl.ImgList, System.Actions, Vcl.ActnList,
cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore,
dxSkinOffice2013White, cxButtons, cxClasses;
type
TedDialog = class(TForm)
paBottom: TPanel;
ActionCommon: TActionList;
acClose: TAction;
acSuccess: TAction;
buCancel: TcxButton;
buOK: TcxButton;
procedure FormResize(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure acCloseExecute(Sender: TObject);
procedure acSuccessExecute(Sender: TObject);
private
protected
function Validate(var vMessage: String): Boolean; virtual;
procedure ErrorMessage(const Error: string);
procedure OKAction; virtual;
{означивание редактируемых переменных}
procedure SetValues(); virtual;
{запись отредактированных значений}
procedure PostValues(); virtual;
procedure CenterButtons(); virtual;
public
constructor Create(Owner: TComponent); override;
function Execute(): Boolean; virtual;
end;
implementation
uses
uServiceUtils, dmuSysImages;
{$R *.DFM}
constructor TedDialog.Create(Owner: TComponent);
begin
inherited Create(Owner);
{означивание редактируемых переменных}
SetValues;
end;
procedure TedDialog.FormResize(Sender: TObject);
begin
CenterButtons;
end;
procedure TedDialog.FormShow(Sender: TObject);
begin
FormResize(Sender);
end;
procedure TedDialog.acCloseExecute(Sender: TObject);
begin
Close;
end;
procedure TedDialog.acSuccessExecute(Sender: TObject);
var
ErrorText: String;
begin
if not Validate(ErrorText) then
begin
ErrorMessage(ErrorText);
ModalResult := mrNone;
Exit;
end;
{запись отредактированных значений}
PostValues();
OKAction;
end;
function TedDialog.Validate(var vMessage: String): Boolean;
begin
Result := False;
vMessage := 'Has error';
{$IFDEF ASProtect}
{$I include\aspr_crypt_begin1.inc}
if not Result then
begin
Result := True;
vMessage := '';
end;
{$I include\aspr_crypt_end1.inc}
{$I include\aspr_crypt_begin5.inc}
if not Result then
begin
Result := True;
vMessage := '';
end;
{$I include\aspr_crypt_end5.inc}
{$I include\aspr_crypt_begin15.inc}
if Result then
begin
Result := False;
vMessage := '';
end;
{$I include\aspr_crypt_end15.inc}
{$ELSE}
Result := True;
vMessage := '';
{$ENDIF}
end;
procedure TedDialog.ErrorMessage(const Error: string);
begin
uServiceUtils.ErrorMessage(Error);
end;
procedure TedDialog.OKAction;
begin
end;
procedure TedDialog.SetValues;
begin
end;
procedure TedDialog.PostValues;
begin
end;
procedure TedDialog.CenterButtons;
begin
uServiceUtils.CenterButtons(Self.Width, buOK, buCancel);
end;
function TedDialog.Execute: Boolean;
begin
Result := ShowModal = mrOK;
end;
end.
|
unit NSqlDbHandler;
{$I ..\NSql.Inc}
interface
uses
NSqlSys,
NSqlComponentsIntf,
NSqlIntf,
{$IFDEF NSQL_XE2UP}
System.SysUtils,
System.Types,
{$ELSE}
SysUtils,
Types,
{$ENDIF}
NSqlTypes,
NSqlFirebirdApiHelpersIntf;
type
ITransactionPool = interface
['{F7CAB06B-1F0A-458B-96FF-8A1EF6088171}']
function Get(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger): ITransaction;
procedure Return(Trans: ITransaction);
procedure MarkAsBad(Trans: ITransaction);
procedure StopWorking;
end;
ITransactionInfo = interface
['{7CE0FD50-10AE-4AE7-B24D-B00975449234}']
function GetInWork: Boolean;
procedure SetInWork(Value: Boolean);
// function GetStartTickCount: Cardinal;
// procedure SetStartTickCount(Value: Cardinal);
// procedure StartNotification;
// procedure CommitNotification;
// procedure RollbackNotification;
property InWork: Boolean read GetInWork write SetInWork;
// property StartTickCount: Cardinal read GetStartTickCount write SetStartTickCount;
end;
TDbHandler = class(TInterfacedObject, IDbHandler)
private
FTransactionPool: ITransactionPool;
FMaxConnections: Integer;
FLogger: ISqlLogger;
FDbAccessComponents: IDbAccessComponents;
FSqlConnectionConfig: ISqlConnectionConfig;
procedure InitTransactionPool;
function InternalCreateConnectionWrapper: ISqlConnectionWrapper;
protected
function CreateConnectionWrapper: ISqlConnectionWrapper;
function OnNewTransNeededFunc(Num: Integer): ITransaction;
{ IDbHandler }
procedure DisconnectAll;
function GetLogger: ISqlLogger;
function Tx(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger = nil): ITransaction; overload;
function Tx(TpbBuilder: ITpbBuilder; TransactionStartTrigger: ITransactionStartTrigger = nil): ITransaction; overload;
function Tx(const Dpb: AnsiString; TransactionStartTrigger: ITransactionStartTrigger = nil): ITransaction; overload;
procedure CreateDatabase(const ConnectionString: AnsiString; DpbBuilder: IDpbBuilder);
function GetConnectionConfig: IBaseSqlConnectionConfig;
// procedure CreateDatabase(const Dpb: AnsiString = '');
function Backup(const BackupFileName: UnicodeString; const UserName, Password: UnicodeString; out Log: UnicodeString; out Error: UnicodeString): Boolean;
function Restore(const BackupFileName: UnicodeString; const UserName, Password: UnicodeString; out Log: UnicodeString; out Error: UnicodeString; ReplaceDbIfExists: Boolean): Boolean;
// function CheckRestore(const BackupFileName: UnicodeString; out Log: UnicodeString; out Error: UnicodeString): Boolean;
public
constructor Create(ALogger: ISqlLogger; AMaxConnections: Integer; ADbAccessComponents: IDbAccessComponents; ASqlConnectionConfig: ISqlConnectionConfig);
destructor Destroy; override;
property TransactionPool: ITransactionPool read FTransactionPool;
property Logger: ISqlLogger read FLogger;
end;
TTransaction = class(TAdvInterfacedObject, IInterface, ITransaction, ITransactionInfo)
private
FTransactionPool: ITransactionPool;
FInWork: Boolean;
FLogger: ISqlLogger;
FLock: INSqlCriticalSection;
// FTransactionFinishProc: TTransactionFinishProc;
// FTransactionFinishProcParam: IInterface;
FStartTickCount: Cardinal;
FConnWrapper: ISqlConnectionWrapper;
// FIsolationLevel: TTransactionIsolationLevel;
FParams: ITransactionParams;
// FIsReadOnly: Boolean;
FTransactionStartTrigger: ITransactionStartTrigger;
// procedure MakeEmptyClientDataSet(cds: TClientDataSet; const SelectableArray: TSelectableIntfArray);
// procedure InternalBindFieldsToClientDataSet(
// const Selectables: TSelectableIntfArray; cds: TClientDataSet);
// function Gen_Id(const GenName: UnicodeString; Increment: Int64): Int64;
function CheckBeforeLoad(Table: ITable): IField;
function SplitInsertQuery(Query: IBaseInsertQuery): TInsertQueryArray;
function SplitUpdateQuery(Query: IBaseUpdateQuery): TUpdateQueryArray;
function InternalExecInsert(Query: IBaseInsertQuery): IInsertQueryResult;
function InternalExecUpdate(Query: IBaseUpdateQuery): IUpdateQueryResult;
procedure InternalStart(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger);
function Gen_Id(const GenName: UnicodeString; Increment: Int64): Int64;
function InternalExecuteInsertQuery(qry: IQueryWrapper; const Sql: UnicodeString; const Params: TSqlParamIntfArray; const Returns: TSelectableIntfArray): IInsertQueryResult; //override;
protected
function GetUseRefCounting: Boolean; override;
procedure StartNotification;
procedure CommitNotification;
procedure RollbackNotification;
// function GetTableInheritanceOfField(Field: IField): TTableIntfArray;
function InTransaction: Boolean;
function InternalGetTransactionId: Int64;
procedure ShutdownConnection;
{ IInterface }
function _Release: Integer; stdcall;
{ ITransactionInfo }
function GetInWork: Boolean;
procedure SetInWork(Value: Boolean);
function IsReadOnly: Boolean;
{ ITransaction }
function GetTransactionId: Int64;
procedure Start;
procedure StartOnGetFromPool(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger); // calls from TTransactionPool.Get
procedure Commit;
procedure Rollback(Silent: Boolean = False);
// function GetIsolationLevel: TTransactionIsolationLevel;
function GetActive: Boolean;
// procedure SetTransactionFinishProc(ATransactionFinishProc: TTransactionFinishProc; Param: IInterface);
function GetLogger: ISqlLogger;
function GetWorkTimeInMilliseconds: Cardinal;
// { ITransaction }
function OpenQuery(Query: IBaseSelectQuery; RecordMakeHelper: IRecordMakeHelper = nil; Cache: Boolean = False): IRecordSet;
function OpenAsDataSet(Query: IBaseSelectQuery; RecordMakeHelper: IRecordMakeHelper = nil; Cache: Boolean = False): IDataSet;
function ExecQuery(Query: IExecutableQuery): IExecQueryResult;
function ExecInsert(Query: IBaseInsertQuery): IInsertQueryResult;
function ExecUpdate(Query: IBaseUpdateQuery): IUpdateQueryResult;
procedure ExecOneRowUpdate(Query: IBaseUpdateQuery);
function ExecDelete(Query: IBaseDeleteQuery): IDeleteQueryResult;
procedure ExecOneRowDelete(Query: IBaseDeleteQuery);
procedure ExecuteProcedure(Proc: IExecutableStoredProcedure);
procedure ExecuteSql(const Sql: UnicodeString); overload;
procedure ExecuteSql(const Sql: UnicodeString; const SqlParams: array of ISqlParam); overload;
procedure ExecuteSql(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray); overload;
function ExecInsertAndReturnId(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray; const IdFieldName: UnicodeString = 'ID'): Int64; overload;
function ExecInsertAndReturnId(const Sql: UnicodeString; const SqlParams: array of ISqlParam; const IdFieldName: UnicodeString = 'ID'): Int64; overload;
function ExecInsertAndReturnId(const Sql: UnicodeString; const IdFieldName: UnicodeString = 'ID'): Int64; overload;
// sql without returning clause
procedure ExecInsertWithReturn(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray; const ReturnFields: TStringDynArray; out ReturnValues: TNSVariantDynArray); overload;
procedure ExecInsertWithReturn(const Sql: UnicodeString; const SqlParams: array of ISqlParam; const ReturnFields: TStringDynArray; out ReturnValues: TNSVariantDynArray); overload;
procedure ExecInsertWithReturn(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray; const ReturnFields: array of string; out ReturnValues: TNSVariantDynArray); overload;
procedure ExecInsertWithReturn(const Sql: UnicodeString; const SqlParams: array of ISqlParam; const ReturnFields: array of string; out ReturnValues: TNSVariantDynArray); overload;
// sql with returning clause
procedure ExecInsertWithReturn(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray; out ReturnTypes: TSqlDataTypeArray; out ReturnFields: TStringDynArray; out ReturnValues: TNSVariantDynArray); overload;
function PrepareSql(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray): IPreparedSql; overload;
function PrepareSql(const Sql: UnicodeString; const SqlParams: array of ISqlParam): IPreparedSql; overload;
function PrepareSelectSql(const Sql: UnicodeString; const SqlParams: array of ISqlParam): IPreparedSelect; overload;
function PrepareSelectSql(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray): IPreparedSelect; overload;
// function PrepareInsertSql(const Sql: UnicodeString; const SqlParams: array of ISqlParam): IPreparedInsert; overload;
// function PrepareInsertSql(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray): IPreparedInsert; overload; virtual; abstract;
function PrepareInsertWithReturn(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray; const ReturnFields: TStringDynArray): IPreparedInsertWithReturn; overload;
function PrepareInsertWithReturn(const Sql: UnicodeString; const SqlParams: array of ISqlParam; const ReturnFields: array of string): IPreparedInsertWithReturn; overload;
function PrepareSqlNative(const Sql: UnicodeString): TObject; // TUIBStatement
// procedure ExecuteSql(const Sql: UnicodeString; Params: TParams); overload;
function ExecuteSqlAndGetRowsAffected(const Sql: UnicodeString; const SqlParams: array of ISqlParam): Int64; overload;
function ExecuteSqlAndGetRowsAffected(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray): Int64; overload;
function ExecuteSqlAndGetRowsAffected(const Sql: UnicodeString): Int64; overload;
// function ExecuteSqlAndGetRowsAffected(const Sql: UnicodeString; Params: TParams): Int64; overload;
// procedure MakeClientDataSet(cds: TClientDataSet; Query: IBaseSelectQuery; RecordMakeHelper: IRecordMakeHelper = nil); overload;
// procedure MakeClientDataSet(cds: TClientDataSet; const Sql: UnicodeString; const Params: TSqlParamIntfArray = nil); overload;
//// procedure MakeClientDataSet(cds: TClientDataSet; const Sql: UnicodeString; Params: TParams = nil); overload;
// function CreateClientDataSet(Query: IBaseSelectQuery; RecordMakeHelper: IRecordMakeHelper = nil): TClientDataSet;
// procedure BindFieldsToClientDataset(const Selectables: array of ISelectable; Ds: TClientDataSet);
function MakeDataSet(const Sql: UnicodeString; Cached: Boolean = False): ISqlDataSet; overload;
function MakeDataSet(const Sql: UnicodeString; const SqlParams: array of ISqlParam; Cached: Boolean = False): ISqlDataSet; overload;
function MakeDataSet(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray; Cached: Boolean = False): ISqlDataSet; overload;
function MakeDataSet(Query: IBaseSelectQuery; Cached: Boolean = False): ISqlDataSet; overload;
// function MakeDataSet(const Sql: UnicodeString; Params: TParams; Cached: Boolean = False): ISqlDataSet; overload;
function GetServerTime: TDateTime;
procedure InsertRecord(Table: ITable; ReturnKeyValues: Boolean = True);
procedure InsertRecordWithReturn(Table: ITable; const ReturnFields: TSelectableIntfArray = nil);
procedure UpdateRecord(Table: ITable); overload;
procedure UpdateRecord(Table: ITable; const UpdFields: array of IField); overload;
procedure DeleteRecord(Table: ITable);
function LoadRecord(Table: ITable; Id: Int64): Boolean; overload;
function LoadRecord(Table: ITable; const Id: UnicodeString): Boolean; overload;
function LoadRecord(Table: ITable; const Id: TSqlBinaryStringValue): Boolean; overload;
function Prepare(Query: IBaseUpdateQuery): IPreparedUpdate; overload;
function Prepare(Query: IBaseDeleteQuery): IPreparedDelete; overload;
function Prepare(Query: IBaseInsertQuery): IPreparedInsert; overload;
// function GenId(const Generator: UnicodeString; Increment: Int64): Int64;
function IsExists(Query: IBaseSelectQuery): Boolean;
function GetEngine: TNativeSqlEngine;
function ReturnNativeQuery: TObject;
function GenId(const Generator: UnicodeString; Increment: Int64): Int64;
public
constructor Create(AConnWrapper: ISqlConnectionWrapper; ATransactionPool: ITransactionPool; ALogger: ISqlLogger);
destructor Destroy; override;
procedure StartDestroy; override;
property Logger: ISqlLogger read FLogger;
property TransactionId: Int64 read GetTransactionId;
end;
procedure LogSqlErrorAndRaiseException(Logger: ISqlLogger; const LogStr: UnicodeString; E: Exception);
procedure AddToStr(var Dest: UnicodeString; const Src: UnicodeString);
procedure AddParamValues(var Dest: UnicodeString; const Params: TSqlParamIntfArray);
function CreateDbHandler(DbAccessComponents: IDbAccessComponents; SqlConnectionConfig: ISqlConnectionConfig; MaxConnCount: Integer; Logger: ISqlLogger): IDbHandler;
//function CreateConnectionParams(DpbBuilder: IDpbBuilder; DefaultSqlDialect: Integer): IConnectionParams; overload;
function CreateConnectionParams(const Dpb: AnsiString; DefaultSqlDialect: Integer; const ConnectionCharSet: UnicodeString; Description: UnicodeString): IConnectionParams;
//function CreateTransactionParams(const Dpb: AnsiString; DefaultSqlDialect: Integer; Description: UnicodeString): IConnectionParams; overload;
function GetSelectablesValuesAsString(const Selectables: TSelectableIntfArray; const Delimiter: UnicodeString = #13#10): UnicodeString;
implementation
uses
{$IFDEF NSQL_XE2UP}
Data.FmtBcd,
WinApi.Windows,
System.Classes,
System.TypInfo,
System.DateUtils,
System.Variants,
{$ELSE}
FmtBcd,
Windows,
Classes,
TypInfo,
DateUtils,
Variants,
{$ENDIF}
NSqlRenderer,
NSqlConditions,
NSqlQueries,
NSqlParams;
const
PRINT_PARAMS_DELIMITER: UnicodeString = #13#10;
PRINT_RETURNS_DELIMITER: UnicodeString = #13#10;
type
TOnNewTransNeededFunc = function(Num: Integer): ITransaction of object;
TTransactionPool = class(TInterfacedObject, ITransactionPool)
private
FMax: Integer;
FList: IInterfaceList;
FInHandleList: IInterfaceList;
FOnNewTransNeededFunc: TOnNewTransNeededFunc;
FLock: INSqlCriticalSection;
protected
function Get(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger): ITransaction;
procedure Return(Trans: ITransaction);
procedure StopWorking;
procedure MarkAsBad(Trans: ITransaction);
public
constructor Create(AMax: Integer; AOnNewTransNeededFunc: TOnNewTransNeededFunc);
destructor Destroy; override;
end;
TRecordSet = class(TInterfacedObject, IRecordSet)
private
FTrans: ITransactionWrapper;
FQuery: IBaseSelectQuery;
FRecordSet: IRecordSetWrapper;
FLogger: ISqlLogger;
FRecordMakeHelper: IRecordMakeHelper;
FCache: Boolean;
FAllSelectableArray: TSelectableIntfArray;
FNonCalculatedSelectableArray: TSelectableIntfArray;
FCalculatedSelectableArray: TCalculatedIntfArray;
// FIsDataSetUnlinked: Boolean;
procedure TransferDataSetRecordToSqlFields;
procedure CreateRecordSet(Ds: IRecordSetWrapper);
procedure Open;
procedure SetStingFieldsSizes;
protected
function InternalMakeRecordSetWrapper: IRecordSetWrapper; virtual;
{ IRecordSet }
function GetEod: Boolean;
procedure Next;
function GetRecordCount: Int64;
procedure FetchAll;
procedure Close;
function FieldByName(const Name: UnicodeString): ISelectable;
public
constructor Create(ATrans: ITransactionWrapper; AQuery: IBaseSelectQuery; ALogger: ISqlLogger; ARecordMakeHelper: IRecordMakeHelper; ACache: Boolean);
destructor Destroy; override;
property Logger: ISqlLogger read FLogger;
end;
TDataSetImpl = class(TRecordSet, IDataSet)
protected
function InternalMakeRecordSetWrapper: IRecordSetWrapper; override;
{ IDataSet }
function GetDatasetAndUnlink: ISqlDataSet;
end;
// TDataSetImpl = class(TInterfacedObject, IDataSet)
// private
// FTrans: ITransactionWrapper;
// FQuery: IBaseSelectQuery;
// FRecordSet: IRecordSetWrapper;
// FLogger: ISqlLogger;
// FRecordMakeHelper: IRecordMakeHelper;
// FCache: Boolean;
// FAllSelectableArray: TSelectableIntfArray;
// FNonCalculatedSelectableArray: TSelectableIntfArray;
// FCalculatedSelectableArray: TCalculatedIntfArray;
//// FIsDataSetUnlinked: Boolean;
// procedure TransferDataSetRecordToSqlFields;
// procedure CreateRecordSet(Ds: IRecordSetWrapper);
// procedure Open;
// procedure SetStingFieldsSizes;
// protected
// { IDataSet }
// function GetEod: Boolean;
// procedure Next;
// function GetRecordCount: Integer;
// procedure FetchAll;
// procedure Close;
// function FieldByName(const Name: UnicodeString): ISelectable;
// function GetDatasetAndUnlink: ISqlDataSet;
// public
// constructor Create(ATrans: ITransactionWrapper; AQuery: IBaseSelectQuery; ALogger: ISqlLogger; ARecordMakeHelper: IRecordMakeHelper; ACache: Boolean);
// destructor Destroy; override;
// property Logger: ISqlLogger read FLogger;
// end;
TStatementType = (stInsert, stUpdate, stDelete);
TPreparedExecutableStatement = class(TInterfacedObject, IPreparedExecutableStatement, IPreparedUpdate, IPreparedInsert, IPreparedDelete)
private
FTransaction: TTransaction;
FTransIntf: ITransaction;
FQuery: IExecutableQuery;
FStatementType: TStatementType;
FQry: IQueryWrapperForPreparedStatement;
FParams: TSqlParamIntfArray;
FSql: UnicodeString;
FTransWrapper: ITransactionWrapper;
FLogger: ISqlLogger;
FReturnTypes: TSqlDataTypeArray;
FReturnFields: TStringDynArray;
FReturnElements: TSelectableIntfArray;
procedure Prepare;
protected
{ IPreparedExecutableStatement }
function Execute: IExecQueryResult;
{ IPreparedUpdate }
function ExecuteUpdate: IUpdateQueryResult;
function IPreparedUpdate.Execute = ExecuteUpdate;
{ IPreparedInsert }
function ExecuteInsert: IInsertQueryResult;
// function ExecuteAndReturnId: Integer; virtual; abstract;
function IPreparedInsert.Execute = ExecuteInsert;
// procedure ExecWithReturn(out ReturnValues: TNSVariantDynArray);
{ IPreparedDelete }
function ExecuteDelete: IDeleteQueryResult;
function IPreparedDelete.Execute = ExecuteDelete;
public
constructor Create(ATransWrapper: ITransactionWrapper; ATransaction: TTransaction; AQuery: IExecutableQuery; AStatementType: TStatementType; ALogger: ISqlLogger);
property Logger: ISqlLogger read FLogger;
end;
TPreparedSql = class(TInterfacedObject, IPreparedSql)
private
FTransaction: TTransaction;
FTransIntf: ITransaction;
FQry: IQueryWrapperForPreparedStatement;
FParams: TSqlParamIntfArray;
FSql: UnicodeString;
FTransWrapper: ITransactionWrapper;
FLogger: ISqlLogger;
FReturnTypes: TSqlDataTypeArray;
FReturnFields: TStringDynArray;
procedure Prepare;
protected
{ IPreparedSql }
procedure Execute;
function ExecuteAndGetRowsAffected: Int64;
public
constructor Create(ATransWrapper: ITransactionWrapper; ATransaction: TTransaction; const ASql: UnicodeString; const AParams: TSqlParamIntfArray; ALogger: ISqlLogger);
property Logger: ISqlLogger read FLogger;
end;
TPreparedSelect = class(TInterfacedObject, IPreparedSelect)
private
FTransaction: TTransaction;
FTransIntf: ITransaction;
FQry: IWrapperForPreparedSelectStatement;
FParams: TSqlParamIntfArray;
FSql: UnicodeString;
FTransWrapper: ITransactionWrapper;
FLogger: ISqlLogger;
procedure Prepare;
protected
{ IPreparedSelect }
function GetDataSet: ISqlDataSet;
procedure Open;
function GetParamNames: TStringDynArray;
public
constructor Create(ATransWrapper: ITransactionWrapper; ATransaction: TTransaction; const ASql: UnicodeString; const AParams: TSqlParamIntfArray; ALogger: ISqlLogger);
property Logger: ISqlLogger read FLogger;
end;
// TPreparedInsertSql = class(TInterfacedObject, IPreparedInsert)
// private
// FTransaction: TTransaction;
// FTransIntf: ITransaction;
// FQry: IQueryWrapperForPreparedStatement;
// FParams: TSqlParamIntfArray;
// FSql: UnicodeString;
// FTransWrapper: ITransactionWrapper;
// FLogger: ISqlLogger;
// procedure Prepare;
// protected
// { IPreparedInsertSql }
// function Execute: IInsertQueryResult;
// function ExecuteAndReturnId: Integer;
// public
// constructor Create(ATransWrapper: ITransactionWrapper; ATransaction: TTransaction; const ASql: UnicodeString; const AParams: TSqlParamIntfArray; ALogger: ISqlLogger);
// property Logger: ISqlLogger read FLogger;
// end;
TPreparedInsertWithReturnSql = class(TInterfacedObject, IPreparedInsertWithReturn)
private
FTransaction: TTransaction;
FTransIntf: ITransaction;
FQry: IQueryWrapperForPreparedInsertWithReturnStatement;
FParams: TSqlParamIntfArray;
FSql: UnicodeString;
FTransWrapper: ITransactionWrapper;
FLogger: ISqlLogger;
FReturnTypes: TSqlDataTypeArray;
FReturnFields: TStringDynArray;
procedure Prepare;
protected
{ IPreparedInsertWithReturn }
function Execute: TNSVariantDynArray;
public
constructor Create(ATransWrapper: ITransactionWrapper; ATransaction: TTransaction; const ASql: UnicodeString; const AParams: TSqlParamIntfArray; const AReturnFields: TStringDynArray; ALogger: ISqlLogger);
property Logger: ISqlLogger read FLogger;
end;
TTransactionParams = class(TInterfacedObject, ITransactionParams)
private
FTpb: AnsiString;
FDescription: UnicodeString;
FIsReadOnly: Boolean;
protected
{ ITransactionParams }
function GetTpb: AnsiString;
function GetDescription: UnicodeString;
function GetIsReadOnly: Boolean;
public
constructor Create(const ATpb: AnsiString; const ADescription: UnicodeString; AIsReadOnly: Boolean);
end;
TConnectionParams = class(TInterfacedObject, IConnectionParams)
private
FDpb: AnsiString;
FDescription: UnicodeString;
FDefaultSqlDialect: Integer;
FConnectionCharSet: UnicodeString;
protected
{ IConnectionParams }
function GetDpb: AnsiString;
function GetDescription: UnicodeString;
function GetDefaultSqlDialect: Integer;
function GetConnectionCharSet: UnicodeString;
public
constructor Create(const ADpb: AnsiString; const ADescription: UnicodeString; ADefaultSqlDialect: Integer; const AConnectionCharSet: UnicodeString);
end;
function CreateTransactionParams(TpbBuilder: ITpbBuilder): ITransactionParams; overload;
begin
Result := TTransactionParams.Create(TpbBuilder.Get, TpbBuilder.GetDescription, TpbBuilder.GetIsReadOnly);
end;
function CreateTransactionParams(const Tpb: AnsiString): ITransactionParams; overload;
begin
Result := TTransactionParams.Create(Tpb, '', False);
end;
//function CreateConnectionParams(DpbBuilder: IDpbBuilder; DefaultSqlDialect: Integer): IConnectionParams; overload;
//begin
// Result := TConnectionParams.Create(DpbBuilder.Get, DpbBuilder.GetDescription, DefaultSqlDialect);
//end;
function CreateConnectionParams(const Dpb: AnsiString; DefaultSqlDialect: Integer; const ConnectionCharSet: UnicodeString; Description: UnicodeString): IConnectionParams;
begin
Result := TConnectionParams.Create(Dpb, Description, DefaultSqlDialect, ConnectionCharSet);
end;
function CreateDbHandler(DbAccessComponents: IDbAccessComponents; SqlConnectionConfig: ISqlConnectionConfig; MaxConnCount: Integer; Logger: ISqlLogger): IDbHandler;
begin
Assert(Assigned(DbAccessComponents));
Assert(Assigned(SqlConnectionConfig));
Assert(Assigned(Logger));
Result := TDbHandler.Create(Logger, MaxConnCount, DbAccessComponents, SqlConnectionConfig);
end;
var
FLastTransId: Integer;
function MakeTransId: Int64;
begin
Result := {$IFDEF NSQL_XE2UP}WinApi.{$ENDIF}Windows.InterlockedIncrement(FLastTransId);
end;
function TicksToTimeStr(Ticks: Cardinal): UnicodeString;
var
Ms: Integer;
MsStr: UnicodeString;
Seconds: Integer;
begin
Ms := Ticks mod 1000;
Seconds := Ticks div 1000;
MsStr := IntToStr(Ms);
while Length(MsStr) < 3 do
MsStr := '0' + MsStr;
Result := IntToStr(Seconds) + '.' + MsStr + ' sec';
end;
function TicksBetween(B, E: DWORD): DWORD;
begin
if E >= B then
Result := E - B
else
Result := Cardinal(-1) - B + E;
if Result > Cardinal(-1) div 2 then
Result := Cardinal(-1) - Result;
end;
function VarTypeToStr(VT: Word): UnicodeString;
begin
if VT = varEmpty then
Result := 'varEmpty'
else if VT = varNull then
Result := 'varNull'
else if VT = varSmallint then
Result := 'varSmallint'
else if VT = varInteger then
Result := 'varInteger'
else if VT = varSingle then
Result := 'varSingle'
else if VT = varDouble then
Result := 'varDouble'
else if VT = varCurrency then
Result := 'varCurrency'
else if VT = varDate then
Result := 'varDate'
else if VT = varOleStr then
Result := 'varOleStr'
else if VT = varDispatch then
Result := 'varDispatch'
else if VT = varError then
Result := 'varError'
else if VT = varBoolean then
Result := 'varBoolean'
else if VT = varVariant then
Result := 'varVariant'
else if VT = varUnknown then
Result := 'varUnknown'
else if VT = varShortInt then
Result := 'varShortInt'
else if VT = varByte then
Result := 'varByte'
else if VT = varWord then
Result := 'varWord'
else if VT = varLongWord then
Result := 'varLongWord'
else if VT = varInt64 then
Result := 'varInt64'
{$IFDEF NSQL_XE2UP}
else if VT = varRecord then
Result := 'varRecord'
{$ENDIF}
else if VT = varStrArg then
Result := 'varStrArg'
{$IFDEF NSQL_XE2UP}
else if VT = varObject then
Result := 'varObject'
{$ENDIF}
{$IFDEF NSQL_XE2UP}
else if VT = varUStrArg then
Result := 'varUStrArg'
{$ENDIF}
else if VT = varString then
Result := 'varString'
else if VT = varAny then
Result := 'varAny'
else if VT = varUString then
Result := 'varUString'
else
Result := 'unknown(' + IntToStr(VT) + ')';
end;
function ConvertResVariantToStr(SqlDataType: TSqlDataType; const V: Variant): UnicodeString;
var
VT: Word;
// S: UnicodeString;
begin
if VarIsNull(V) then
Result := 'Null'
else
begin
case SqlDataType of
dtInteger: Result := IntToStr(V);
dtString: Result := V;
dtBinaryString: Result := UnicodeString(NSqlBinToHex(AnsiString(V)));
dtFloat: Result := FloatToStrF(Double(V), ffGeneral, 15, 15);
dtBcd: Result := BcdToStrF(VarToBcd(V), ffFixed, 18, 18);
dtBoolean:
begin
VT := VarType(V);
if VT = varBoolean then
begin
Result := V;
end
else if VT = varInteger then
begin
if V = 1 then
Result := 'True'
else
Result := 'False'
end
else
begin
Assert(False, IntToStr(VT));
Result := Null;
end;
end;
dtDate: Result := DateToStr(V);
dtTime: Result := TimeToStr(V);
dtDateTime: Result := DateTimeToStr(V);
dtMemo, dtBlob:
begin
Result := V;
if Length(Result) > 4000 then
Result := Format('%d bytes of data', [Length(Result)]);
end;
else
Result := 'Null';
Assert(False, VarTypeToStr(VarType(V)));
end;
end;
// VT := VarType(V);
// if VT = varInteger then
// Result := IntToStr(V)
// else if VT = varDouble then
// Result := FloatToStrF(V, ffGeneral, 15, 15)
// else if VT = varDate then
// Result := DateTimeToStr(V)
// else if VT = varBoolean then
// begin
// if V = 1 then
// Result := 'True'
// else
// Result := 'False'
// end
// else if (VT = varString) or (VT = varUString) then
// begin
// S := V;
// if Length(S) > 1000 then
// Result := Format('%d bytes of data', [Length(S)])
// else
// Result := S;
// end
// else
// begin
// Result := 'Null';
// Assert(False, VarTypeToStr(VT));
// end;
// end;
end;
function CreateReturningSql(const Sql: UnicodeString; const ReturnFields: TStringDynArray): UnicodeString;
var
I: Integer;
begin
Result := Sql;
if Assigned(ReturnFields) then
begin
Result := Result + ' RETURNING';
for I := 0 to High(ReturnFields) do
Result := Result + ' "' + ReturnFields[I] + '",';
SetLength(Result, Length(Result) - 1);
end;
end;
procedure LogSqlErrorAndRaiseException(Logger: ISqlLogger; const LogStr: UnicodeString; E: Exception);
begin
if Logger.Use then
Logger.Log(LogStr + #13#10 + 'Error:' + #13#10 + E.Message);
// Exception.RaiseOuterException(E);
// raise Exception.Create(E.Message);
raise TObject(AcquireExceptionObject);
end;
procedure LogSqlError(Logger: ISqlLogger; const LogStr: UnicodeString; E: Exception);
begin
if Logger.Use then
Logger.Log(LogStr + #13#10 + 'Error:' + #13#10 + E.Message);
end;
function MakeParamArray(const SqlParams: array of ISqlParam): TSqlParamIntfArray;
var
I: Integer;
begin
SetLength(Result, Length(SqlParams));
for I := 0 to High(Result) do
Result[I] := SqlParams[I];
end;
function MakeStrArray(const Values: array of string): TStringDynArray;
var
I: Integer;
begin
SetLength(Result, Length(Values));
for I := 0 to High(Result) do
Result[I] := Values[I];
end;
function GetRange(const V1, V2: Cardinal): Cardinal;
begin
if V1 >= V2 then
Result := V1 - V2
else
Result := High(Cardinal) - V2 + V1;
end;
function SelfEQCondition(Field: IField): ISqlCondition;
begin
if Field.IsNull then
Result := IsNull(Field)
else
begin
case Field.DataType of
dtInteger: Result := EQ((Field as IIntegerSelectable), (Field as IIntegerSelectable).Value);
// dtInt64: Result := EQ((Field as IInt64Selectable), (Field as IInt64Selectable).Value);
dtString: Result := EQ((Field as IStringSelectable), (Field as IStringSelectable).Value);
dtBinaryString: Result := EQ((Field as IBinaryStringSelectable), (Field as IBinaryStringSelectable).Value);
dtFloat: Result := EQ((Field as IFloatSelectable), (Field as IFloatSelectable).Value);
dtBcd: Result := EQ((Field as IBcdSelectable), (Field as IBcdSelectable).Value);
dtBoolean: Result := EQ((Field as IBooleanSelectable), (Field as IBooleanSelectable).Value);
dtDate: Result := EQ((Field as IDateSelectable), (Field as IDateSelectable).Value);
dtTime: Result := EQ((Field as ITimeSelectable), (Field as ITimeSelectable).Value);
dtDateTime: Result := EQ((Field as IDateTimeSelectable), (Field as IDateTimeSelectable).Value);
dtMemo: Result := EQ((Field as IMemoSelectable), (Field as IMemoSelectable).Value);
dtBlob: Result := EQ((Field as IBlobSelectable), (Field as IBlobSelectable).Value);
// dtSmallInt: Result := EQ((Field as ISmallIntSelectable), (Field as ISmallIntSelectable).Value);
else
Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(Field.DataType)));
end;
end;
end;
//function HasBinaryCharacters(const S: AnsiString): Boolean;
//const
// TextChars: set of AnsiChar = [#9, #13, #10, #32..#126, 'à'..'ÿ', 'À'..'ß', '¸', '¨'];
//var
// I: Integer;
//begin
// Result := True;
// for I := 1 to Length(S) do
// if not S[I] in TextChars) then
// Exit;
// Result := False;
//end;
function GetParamsValuesAsString(const Params: TSqlParamIntfArray; const Delimiter: UnicodeString): UnicodeString; overload;
var
I: Integer;
Param: ISqlParam;
Line: UnicodeString;
begin
Result := '';
for I := 0 to High(Params) do
begin
Param := Params[I];
if not Param.UseAsConst then
begin
if Param.IsNull then
Line := 'NULL'
else
begin { TODO : implement format converter }
case Param.DataType of
dtInteger: Line := IntToStr((Param as IIntegerSqlParam).Value);
// dtInt64: Line := IntToStr((Param as IInt64SqlParam).Value);
dtString: Line := '''' + (Param as IStringSqlParam).Value + '''';
dtBinaryString: Line := '''' + UnicodeString(NSqlBinToHex((Param as IBinaryStringSqlParam).Value)) + '''';
dtFloat: Line := FloatToStrF((Param as IFloatSqlParam).Value, ffGeneral, 15, 15);
dtBcd: Line := BcdToStrF((Param as IBcdSqlParam).Value, ffFixed, 18, 18);
dtBoolean:
begin
if (Param as IBooleanSqlParam).Value then
Line := 'True'
else
Line := 'False';
end;
dtDate: Line := DateToStr((Param as IDateSqlParam).Value);
dtTime: Line := TimeToStr((Param as ITimeSqlParam).Value);
dtDateTime: Line := DateTimeToStr((Param as IDateTimeSqlParam).Value);
dtMemo: Line := (Param as IMemoSqlParam).Value;
// begin
// if HasBinaryCharacters((Param as IMemoSqlParam).Value) then
// Line := Format('%d bytes of binary data', [Length((Param as IMemoSqlParam).Value)])
// else
// Line := (Param as IMemoSqlParam).Value;
// end;
dtBlob: Line := Format('%d bytes of binary data', [Length((Param as IBlobSqlParam).Value)]);
// dtSmallInt: Line := IntToStr((Param as ISmallIntSqlParam).Value);
else
Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(Param.DataType)));
Line := '';
end;
end;
Result := Result + Param.Name + ' = ' + Line + Delimiter;
end;
end;
if Result <> '' then
SetLength(Result, Length(Result) - Length(Delimiter));
end;
function GetSelectablesValuesAsString(const Selectables: TSelectableIntfArray; const Delimiter: UnicodeString = #13#10): UnicodeString;
var
I: Integer;
Selectable: ISelectable;
StrValue: UnicodeString;
begin
Result := '';
for I := 0 to High(Selectables) do
begin
Selectable := Selectables[I];
// if not Selectable.UseAsConst then
begin
if Selectable.IsNull then
StrValue := 'NULL'
else
begin { TODO : implement format converter }
case Selectable.DataType of
dtInteger: StrValue := IntToStr((Selectable as IIntegerSelectable).Value);
// dtInt64: StrValue := IntToStr((Selectable as IInt64Selectable).Value);
dtString: StrValue := '''' + (Selectable as IStringSelectable).Value + '''';
dtBinaryString: StrValue := '''' + UnicodeString(NSqlBinToHex((Selectable as IBinaryStringSelectable).Value)) + '''';
dtFloat: StrValue := FloatToStrF((Selectable as IFloatSelectable).Value, ffFixed, 15, 15);
dtBcd: StrValue := BcdToStrF((Selectable as IBcdSelectable).Value, ffFixed, 18, 18);
dtBoolean:
begin
if (Selectable as IBooleanSelectable).Value then
StrValue := 'True'
else
StrValue := 'False';
end;
dtDate: StrValue := DateToStr((Selectable as IDateSelectable).Value);
dtTime: StrValue := TimeToStr((Selectable as ITimeSelectable).Value);
dtDateTime: StrValue := DateTimeToStr((Selectable as IDateTimeSelectable).Value);
dtMemo: StrValue := (Selectable as IMemoSelectable).Value;
// begin
// if HasBinaryCharacters((Selectable as IMemoSelectable).Value) then
// StrValue := Format('%d bytes of binary data', [Length((Selectable as IMemoSelectable).Value)])
// else
// StrValue := (Selectable as IMemoSelectable).Value;
// end;
dtBlob: StrValue := Format('%d bytes of binary data', [Length((Selectable as IBlobSelectable).Value)]);
// dtSmallInt: StrValue := IntToStr((Selectable as ISmallIntSelectable).Value);
else
Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(Selectable.DataType)));
StrValue := '';
end;
end;
Result := Result + Selectable.Alias + ' = ' + StrValue + Delimiter;
end;
end;
if Result <> '' then
SetLength(Result, Length(Result) - Length(Delimiter));
end;
//function GetParamsValuesAsString(Params: TParams; const Delimiter: UnicodeString): UnicodeString; overload;
//var
// I: Integer;
// Param: TParam;
// Line: UnicodeString;
//begin
// Result := '';
// for I := 0 to Params.Count - 1 do
// begin
// Param := Params[I];
// if Param.IsNull then
// Line := 'NULL'
// else
// begin
// Line := Param.AsString;
// end;
// Result := Result + Param.Name + ' = ' + Line + Delimiter;
// end;
// if Result <> '' then
// SetLength(Result, Length(Result) - Length(Delimiter));
//end;
procedure AddToStr(var Dest: UnicodeString; const Src: UnicodeString);
begin
if Src <> '' then
Dest := Dest + #13#10 + Src;
end;
procedure AddParamValues(var Dest: UnicodeString; const Params: TSqlParamIntfArray);
begin
AddToStr(Dest, GetParamsValuesAsString(Params, PRINT_PARAMS_DELIMITER));
end;
procedure AddSelectablesValues(var Dest: UnicodeString; const Selectables: TSelectableIntfArray);
begin
AddToStr(Dest, GetSelectablesValuesAsString(Selectables, PRINT_RETURNS_DELIMITER));
end;
//procedure AddParamValues(var Dest: UnicodeString; Params: TParams); overload;
//begin
// AddToStr(Dest, GetParamsValuesAsString(Params, PRINT_PARAMS_DELIMITER));
//end;
{ TDbHandler }
//function TDbHandler.Backup(const BackupFileName: UnicodeString; out Log: UnicodeString; out Error: UnicodeString): Boolean;
//var
// ConnWrapper: ISqlConnectionWrapper;
//begin
// ConnWrapper := FDbAccessComponents.MakeConnectionWrapper(FSqlConnectionConfig);
// Result := ConnWrapper.Backup(BackupFileName, Logger, Log, Error);
//end;
//
//function TDbHandler.CheckRestore(const BackupFileName: UnicodeString; out Log,
// Error: UnicodeString): Boolean;
//var
// ConnWrapper: ISqlConnectionWrapper;
//begin
// ConnWrapper := FDbAccessComponents.MakeConnectionWrapper(FSqlConnectionConfig);
// Result := ConnWrapper.CheckRestore(BackupFileName, Logger, Log, Error);
//end;
//constructor TDbHandler.Create(ALogger: ISqlLogger; AMaxConnections: Integer; ADbAccessComponents: IFirebirdDbAccessComponents; ASqlConnectionConfig: IFirebirdSqlConnectionConfig);
//begin
// inherited Create(AMaxConnections, ALogger);
// FDbAccessComponents := ADbAccessComponents;
// FSqlConnectionConfig := ASqlConnectionConfig;
//end;
//procedure TDbHandler.CreateDatabase(const CharacterSet: UnicodeString; PageSize: Integer);
//var
// ConnWrapper: ISqlConnectionWrapper;
//begin
// ConnWrapper := FDbAccessComponents.MakeConnectionWrapper(FSqlConnectionConfig);
// ConnWrapper.CreateDatabase(FSqlConnectionConfig.CharSet, PageSize);
//end;
//function TDbHandler.GetEngine: TNativeSqlEngine;
//begin
// Result := nseFirebird;
//end;
//function TDbHandler.OnNewTransNeededFunc(Num: Integer): ITransaction;
//var
// ConnWrapper: ISqlConnectionWrapper;
//begin
//// ConnWrapper := FDbAccessComponents.MakeConnectionWrapper(FSqlConnectionConfig);
// ConnWrapper := CreateConnectionWrapper;
// ConnWrapper.Connect;
// Result := TTransaction.Create(ConnWrapper, TransactionPool, Logger);
//end;
//function TDbHandler.Restore(const BackupFileName: UnicodeString; out Log: UnicodeString; out Error: UnicodeString): Boolean;
//var
// ConnWrapper: ISqlConnectionWrapper;
//begin
// ConnWrapper := FDbAccessComponents.MakeConnectionWrapper(FSqlConnectionConfig);
// Result := ConnWrapper.Restore(BackupFileName, Logger, Log, Error);
//end;
function TDbHandler.Backup(const BackupFileName: UnicodeString; const UserName, Password: UnicodeString; out Log,
Error: UnicodeString): Boolean;
var
ConnWrapper: ISqlConnectionWrapper;
begin
ConnWrapper := InternalCreateConnectionWrapper;
Result := ConnWrapper.Backup(BackupFileName, UserName, Password, Logger, Log, Error);
end;
//function TDbHandler.CheckRestore(const BackupFileName: UnicodeString; out Log,
// Error: UnicodeString): Boolean;
//var
// ConnWrapper: ISqlConnectionWrapper;
//begin
// ConnWrapper := InternalCreateConnectionWrapper;
// Result := ConnWrapper.CheckRestore(BackupFileName, Logger, Log, Error);
//end;
constructor TDbHandler.Create(ALogger: ISqlLogger; AMaxConnections: Integer; ADbAccessComponents: IDbAccessComponents; ASqlConnectionConfig: ISqlConnectionConfig);
begin
inherited Create;
Assert(Assigned(ALogger));
FMaxConnections := AMaxConnections;
FLogger := ALogger;
FDbAccessComponents := ADbAccessComponents;
FSqlConnectionConfig := ASqlConnectionConfig;
InitTransactionPool;
end;
function TDbHandler.CreateConnectionWrapper: ISqlConnectionWrapper;
begin
Result := InternalCreateConnectionWrapper;
end;
procedure TDbHandler.CreateDatabase(const ConnectionString: AnsiString;
DpbBuilder: IDpbBuilder);
var
ConnWrapper: ISqlConnectionWrapper;
begin
ConnWrapper := InternalCreateConnectionWrapper;
ConnWrapper.CreateDatabase(ConnectionString, DpbBuilder.Get);
end;
//procedure TDbHandler.CreateDatabase(const Dpb: AnsiString = '');
//var
// ConnWrapper: ISqlConnectionWrapper;
//begin
// ConnWrapper := InternalCreateConnectionWrapper;
// ConnWrapper.CreateDatabase(FSqlConnectionConfig.CharSet, PageSize);
//end;
destructor TDbHandler.Destroy;
begin
FTransactionPool.StopWorking;
inherited;
end;
procedure TDbHandler.DisconnectAll;
begin
FTransactionPool.StopWorking;
FTransactionPool := nil;
InitTransactionPool;
end;
function TDbHandler.GetConnectionConfig: IBaseSqlConnectionConfig;
begin
Result := FSqlConnectionConfig;
end;
function TDbHandler.GetLogger: ISqlLogger;
begin
Result := FLogger;
end;
procedure TDbHandler.InitTransactionPool;
begin
FTransactionPool := TTransactionPool.Create(FMaxConnections, OnNewTransNeededFunc);
end;
function TDbHandler.InternalCreateConnectionWrapper: ISqlConnectionWrapper;
begin
Result := FDbAccessComponents.MakeConnectionWrapper(FSqlConnectionConfig);
end;
function TDbHandler.OnNewTransNeededFunc(Num: Integer): ITransaction;
var
ConnWrapper: ISqlConnectionWrapper;
begin
// ConnWrapper := FDbAccessComponents.MakeConnectionWrapper(FSqlConnectionConfig);
ConnWrapper := InternalCreateConnectionWrapper;
ConnWrapper.Connect;
Result := TTransaction.Create(ConnWrapper, TransactionPool, Logger);
end;
function TDbHandler.Tx(TpbBuilder: ITpbBuilder;
TransactionStartTrigger: ITransactionStartTrigger): ITransaction;
begin
Result := Tx(CreateTransactionParams(TpbBuilder), TransactionStartTrigger);
end;
function TDbHandler.Tx(const Dpb: AnsiString;
TransactionStartTrigger: ITransactionStartTrigger): ITransaction;
begin
Result := Tx(CreateTransactionParams(Dpb), TransactionStartTrigger);
end;
function TDbHandler.Restore(const BackupFileName: UnicodeString; const UserName, Password: UnicodeString; out Log,
Error: UnicodeString; ReplaceDbIfExists: Boolean): Boolean;
var
ConnWrapper: ISqlConnectionWrapper;
begin
ConnWrapper := InternalCreateConnectionWrapper;
Result := ConnWrapper.Restore(BackupFileName, UserName, Password, Logger, Log, Error, ReplaceDbIfExists);
end;
function TDbHandler.Tx(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger = nil): ITransaction;
begin
Result := FTransactionPool.Get(Params, TransactionStartTrigger);
end;
{ TTransaction }
constructor TTransaction.Create(AConnWrapper: ISqlConnectionWrapper; ATransactionPool: ITransactionPool; ALogger: ISqlLogger);
begin
inherited Create;
FConnWrapper := AConnWrapper;
FTransactionPool := ATransactionPool;
FLogger := ALogger;
FLock := NSqlCriticalSectionGuard;
end;
procedure TTransaction.SetInWork(Value: Boolean);
begin
FInWork := Value;
end;
procedure TTransaction.ShutdownConnection;
begin
if Assigned(FConnWrapper) then
begin
if Assigned(FConnWrapper.Trans) then
begin
if FConnWrapper.Trans.InTransaction then
Rollback(True);
end;
try
FConnWrapper.Disconnect;
except
end;
FConnWrapper := nil;
end;
end;
function TTransaction.SplitInsertQuery(
Query: IBaseInsertQuery): TInsertQueryArray;
begin
SetLength(Result, 1);
Result[0] := Query;
end;
function TTransaction.SplitUpdateQuery(
Query: IBaseUpdateQuery): TUpdateQueryArray;
begin
SetLength(Result, 1);
Result[0] := Query;
end;
procedure TTransaction.Start;
begin
// Assert(FIsolationLevel <> tilInvalid);
InternalStart(FParams, FTransactionStartTrigger);
end;
procedure TTransaction.StartDestroy;
begin
// calls from TransactionPool
if FInWork then
begin
try
try
if InTransaction then
Rollback(True);
except
end;
finally
FInWork := False;
end;
end;
ShutdownConnection;
inherited;
end;
procedure TTransaction.StartNotification;
begin
FStartTickCount := GetTickCount;
end;
procedure TTransaction.StartOnGetFromPool(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger);
begin
FParams := Params;
// FIsReadOnly := RunReadOnly;
FTransactionStartTrigger := TransactionStartTrigger;
InternalStart(Params, FTransactionStartTrigger);
end;
function TTransaction.CheckBeforeLoad(Table: ITable): IField;
var
Field: IField;
I: Integer;
begin
Result := nil;
for I := 0 to Table.FieldCount - 1 do
begin
Field := Table.FieldList[I];
if Table.FieldList[I].InPrimaryKey then
begin
if Assigned(Result) then
raise Exception.CreateFmt('there are too many fields in primary key for table %s(%s, %s)',
[Table.TableName, Result.Name, Field.Name]);
Result := Table.FieldList[I]
end;
end;
if not Assigned(Result) then
raise Exception.CreateFmt('primary key field not found in %s', [Table.TableName]);
end;
procedure TTransaction.Commit;
var
LogStr: UnicodeString;
TransId: Int64;
WorkTimeInMs: DWORD;
S, E, CommitTime: DWORD;
begin
try
if Logger.Use then
begin
LogStr := 'Commit Transaction ';
try
TransId := TransactionId;
WorkTimeInMs := GetWorkTimeInMilliseconds;
LogStr := LogStr + Format('[Id = %d, WorkTime = %s] ', [TransId, TicksToTimeStr(WorkTimeInMs)]);
except
on E: Exception do
begin
LogStr := LogStr + #13#10'Exception on GetTransactionId:'#13#10 + E.Message;
end;
end;
end;
S := GetTickCount;
FConnWrapper.Trans.Commit;
E := GetTickCount;
CommitNotification;
if Logger.Use then
begin
CommitTime := TicksBetween(S, E);
if CommitTime <> 0 then
LogStr := LogStr + '[CommitTime = ' + TicksToTimeStr(CommitTime) + '] ';
LogStr := LogStr + 'Ok';
end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
procedure TTransaction.CommitNotification;
begin
end;
function TTransaction.OpenAsDataSet(Query: IBaseSelectQuery;
RecordMakeHelper: IRecordMakeHelper; Cache: Boolean): IDataSet;
begin
Result := TDataSetImpl.Create(FConnWrapper.Trans, Query, Logger, RecordMakeHelper, Cache);
end;
function TTransaction.OpenQuery(Query: IBaseSelectQuery; RecordMakeHelper: IRecordMakeHelper = nil; Cache: Boolean = False): IRecordSet;
begin
Result := TRecordSet.Create(FConnWrapper.Trans, Query, Logger, RecordMakeHelper, Cache);
end;
function TTransaction.ReturnNativeQuery: TObject;
begin
Result := FConnWrapper.Trans.ReturnNativeQuery;
end;
procedure TTransaction.Rollback(Silent: Boolean = False);
var
LogStr: UnicodeString;
TransId: Int64;
begin
try
if Logger.Use then
begin
if Silent then
LogStr := 'Rollback Transaction (Silent) '
else
LogStr := 'Rollback Transaction ';
try
if InTransaction then
TransId := TransactionId
else
TransId := 0;
// LogStr := LogStr + Format('[Id = %d] ', [TransId]);
LogStr := LogStr + Format('[Id = %d, WorkTime = %s] ', [TransId, TicksToTimeStr(GetWorkTimeInMilliseconds)]);
except
on E: Exception do
begin
LogStr := LogStr + #13#10'Exception on GetTransactionId:'#13#10 + E.Message;
end;
end;
end;
FConnWrapper.Trans.Rollback(Silent);
RollbackNotification;
if Logger.Use then
LogStr := LogStr + 'Ok';
except
on E: Exception do
begin
if not Silent then
LogSqlErrorAndRaiseException(Logger, LogStr, E)
else
LogSqlError(Logger, LogStr, E);
end;
end;
if Logger.Use then
Logger.Log(LogStr);
end;
procedure TTransaction.RollbackNotification;
begin
end;
destructor TTransaction.Destroy;
begin
FConnWrapper := nil;
FTransactionPool := nil;
inherited;
end;
function TTransaction.InTransaction: Boolean;
begin
Result := FConnWrapper.Trans.InTransaction;
end;
function TTransaction.ExecQuery(
Query: IExecutableQuery): IExecQueryResult;
var
UpdQuery: IBaseUpdateQuery;
InsQuery: IBaseInsertQuery;
DelQuery: IBaseDeleteQuery;
begin
if Supports(Query, IBaseUpdateQuery, UpdQuery) then
Result := ExecUpdate(UpdQuery)
else if Supports(Query, IBaseInsertQuery, InsQuery) then
Result := ExecInsert(InsQuery)
else if Supports(Query, IBaseDeleteQuery, DelQuery) then
Result := ExecDelete(DelQuery)
else
Assert(False, Query.ImplObjectClassName);
end;
function TTransaction.ExecUpdate(
Query: IBaseUpdateQuery): IUpdateQueryResult;
var
QueryArray: TUpdateQueryArray;
I: Integer;
begin
QueryArray := SplitUpdateQuery(Query);
for I := 0 to High(QueryArray) do
Result := InternalExecUpdate(QueryArray[I]);
end;
procedure TTransaction.ExecuteSql(const Sql: UnicodeString);
var
qry: IQueryWrapper;
LogStr: UnicodeString;
begin
qry := FConnWrapper.Trans.MakeQueryWrapper;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
qry.Execute(Sql);
if Logger.Use then
AddToStr(LogStr, 'Ok.');
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
procedure TTransaction.ExecuteSql(const Sql: UnicodeString;
const SqlParams: array of ISqlParam);
//var
// ParamArray: TSqlParamIntfArray;
// I: Integer;
begin
// SetLength(ParamArray, Length(SqlParams));
// for I := 0 to High(ParamArray) do
// ParamArray[I] := SqlParams[I];
ExecuteSql(Sql, MakeParamArray(SqlParams));
end;
procedure TTransaction.ExecuteProcedure(Proc: IExecutableStoredProcedure);
var
Wrapper: IExecutableStoredProcedureWrapper;
Sql: UnicodeString;
LogStr: UnicodeString;
SqlParams: TSqlParamIntfArray;
Returns: TSelectableIntfArray;
begin
Wrapper := FConnWrapper.Trans.MakeExecutableStoredProcedureWrapper;
Sql := NewSqlRenderer(GetEngine).StrOfExecutableProcedure(Proc);
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
// Wrapper.SetParamNamesFromQuery(SqlParams);
SqlParams := Proc.GetParams;
if Logger.Use then
AddParamValues(LogStr, SqlParams);
Returns := Proc.All;
Wrapper.Execute(Sql, SqlParams, Returns);
if Logger.Use then
begin
if Assigned(Returns) then
begin
AddToStr(LogStr, 'Returns: ');
AddSelectablesValues(LogStr, Returns);
end;
AddToStr(LogStr, 'Ok.');
end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
procedure TTransaction.ExecuteSql(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray);
var
qry: IQueryWrapper;
LogStr: UnicodeString;
begin
qry := FConnWrapper.Trans.MakeQueryWrapper;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
// qry.SetParamNamesFromQuery(SqlParams);
if Logger.Use then
AddParamValues(LogStr, SqlParams);
qry.Execute(Sql, SqlParams, True);
if Logger.Use then
AddToStr(LogStr, 'Ok.');
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TTransaction.ExecuteSqlAndGetRowsAffected(const Sql: UnicodeString;
const SqlParams: array of ISqlParam): Int64;
begin
Result := ExecuteSqlAndGetRowsAffected(Sql, MakeParamArray(SqlParams));
end;
function TTransaction.ExecuteSqlAndGetRowsAffected(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray): Int64;
var
qry: IQueryWrapper;
LogStr: UnicodeString;
begin
Result := 0;
qry := FConnWrapper.Trans.MakeQueryWrapper;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
if Logger.Use then
AddParamValues(LogStr, SqlParams);
Result := qry.ExecuteAndGetRowsAffected(Sql, SqlParams);
if Logger.Use then
AddToStr(LogStr, 'Ok.');
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TTransaction.ExecuteSqlAndGetRowsAffected(const Sql: UnicodeString): Int64;
var
qry: IQueryWrapper;
LogStr: UnicodeString;
begin
Result := 0;
qry := FConnWrapper.Trans.MakeQueryWrapper;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
Result := qry.ExecuteAndGetRowsAffected(Sql);
if Logger.Use then
AddToStr(LogStr, 'Ok.');
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TTransaction.ExecInsert(
Query: IBaseInsertQuery): IInsertQueryResult;
var
QueryArray: TInsertQueryArray;
I: Integer;
begin
QueryArray := SplitInsertQuery(Query);
for I := 0 to High(QueryArray) do
Result := InternalExecInsert(QueryArray[I]);
end;
function TTransaction.ExecInsertAndReturnId(const Sql: UnicodeString;
const SqlParams: array of ISqlParam;
const IdFieldName: UnicodeString): Int64;
begin
Result := ExecInsertAndReturnId(Sql, MakeParamArray(SqlParams), IdFieldName);
end;
function TTransaction.ExecInsertAndReturnId(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray; const IdFieldName: UnicodeString): Int64;
var
ReturnValues: TNSVariantDynArray;
begin
ExecInsertWithReturn(Sql, SqlParams, [IdFieldName], ReturnValues);
Result := ReturnValues[0]
end;
function TTransaction.ExecInsertAndReturnId(const Sql: UnicodeString; const IdFieldName: UnicodeString = 'ID'): Int64;
begin
Result := ExecInsertAndReturnId(Sql, nil, IdFieldName);
end;
procedure TTransaction.ExecInsertWithReturn(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray; const ReturnFields: array of string;
out ReturnValues: TNSVariantDynArray);
begin
ExecInsertWithReturn(Sql, SqlParams, MakeStrArray(ReturnFields), ReturnValues);
end;
procedure TTransaction.ExecInsertWithReturn(const Sql: UnicodeString;
const SqlParams: array of ISqlParam; const ReturnFields: array of string;
out ReturnValues: TNSVariantDynArray);
begin
ExecInsertWithReturn(Sql, MakeParamArray(SqlParams), MakeStrArray(ReturnFields), ReturnValues);
end;
procedure TTransaction.ExecInsertWithReturn(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray; const ReturnFields: TStringDynArray;
out ReturnValues: TNSVariantDynArray);
var
qry: IQueryWrapper;
LogStr: UnicodeString;
NewSql: UnicodeString;
OutReturnFields: TStringDynArray;
ReturnTypes: TSqlDataTypeArray;
// FirebirdQuery: IFirebirdQueryWrapper;
// ReturnValues: TNSVariantDynArray;
I: Integer;
begin
qry := FConnWrapper.Trans.MakeQueryWrapper;
NewSql := CreateReturningSql(Sql, ReturnFields);
// if Assigned(ReturnFields) then
// begin
// NewSql := Sql + ' RETURNING';
// for I := 0 to High(ReturnFields) do
// NewSql := NewSql + ' "' + ReturnFields[I] + '",';
// SetLength(NewSql, Length(NewSql) - 1);
// end;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + NewSql;
end;
try
if Assigned(ReturnFields) then
begin
qry.ExecInsertWithReturn(NewSql, SqlParams, ReturnTypes, OutReturnFields, ReturnValues, True);
if Length(ReturnValues) <> Length(ReturnFields) then
Assert(False);
if Logger.Use then
begin
for I := 0 to High(ReturnFields) do
AddToStr(LogStr, Format('Return: %s(%s) = %s', [ReturnFields[I], GetEnumName(TypeInfo(TSqlDataType), Ord(ReturnTypes[I])), ConvertResVariantToStr(ReturnTypes[I], ReturnValues[I])]));
AddToStr(LogStr, 'Ok.');
end;
end
else
begin
qry.Execute(NewSql, SqlParams, True);
ReturnValues := nil;
end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
// Result := ReturnValues[0];
// if Logger.Use then
// begin
// AddToStr(LogStr, Format('Return: ID = %d', [Result]));
// AddToStr(LogStr, 'Ok.');
// end;
// ExecInsertWithReturn(Sql, SqlParams, ['ID'], ReturnValues);
// Result := ReturnValues[0];
// qry := FConnWrapper.Trans.MakeQueryWrapper;
// FirebirdQuery := qry as IFirebirdQueryWrapper;
// try
//// qry.SetParamNamesFromQuery(SqlParams);
// if Logger.Use then
// AddParamValues(LogStr, SqlParams);
// qry.ExecInsertWithReturn(NewSql, SqlParams, ReturnValues, True);
// if Length(ReturnValues) <> 1 then
// Assert(False);
// Result := ReturnValues[0];
// if Logger.Use then
// begin
// AddToStr(LogStr, Format('Return: ID = %d', [Result]));
// AddToStr(LogStr, 'Ok.');
// end;
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
end;
procedure TTransaction.ExecInsertWithReturn(const Sql: UnicodeString;
const SqlParams: array of ISqlParam; const ReturnFields: TStringDynArray;
out ReturnValues: TNSVariantDynArray);
begin
ExecInsertWithReturn(Sql, MakeParamArray(SqlParams), ReturnFields, ReturnValues);
end;
procedure TTransaction.ExecOneRowDelete(Query: IBaseDeleteQuery);
var
RowsAffected: Int64;
begin
RowsAffected := ExecDelete(Query).RowsAffected;
if RowsAffected = 0 then
raise Exception.Create('no records deleted in ExecOneRowDelete')
else if RowsAffected <> 1 then
raise Exception.CreateFmt('%d records deleted in ExecOneRowDelete', [RowsAffected]);
end;
procedure TTransaction.ExecOneRowUpdate(Query: IBaseUpdateQuery);
var
RowsAffected: Int64;
begin
RowsAffected := ExecUpdate(Query).RowsAffected;
if RowsAffected = 0 then
raise Exception.Create('no records updated in ExecOneRowUpdate')
else if RowsAffected <> 1 then
raise Exception.CreateFmt('%d records updated in ExecOneRowUpdate', [RowsAffected]);
end;
function TTransaction.ExecDelete(
Query: IBaseDeleteQuery): IDeleteQueryResult;
var
qry: IQueryWrapper;
Sql: UnicodeString;
LogStr: UnicodeString;
RowsAffected: Int64;
Params: TSqlParamIntfArray;
begin
qry := FConnWrapper.Trans.MakeQueryWrapper;
Sql := NewSqlRenderer(GetEngine).StrOfDeleteQuery(Query);
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
Params := Query.GetParams;
if Logger.Use then
AddParamValues(LogStr, Params);
RowsAffected := qry.ExecuteAndGetRowsAffected(Sql, Params);
Result := TDeleteQueryResult.Create(RowsAffected);
if Logger.Use then
AddToStr(LogStr, 'Rows Affected: ' + IntToStr(RowsAffected));
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
//procedure TTransaction.InsertRecord(Table: ITable;
// ReturnAutoGeneratedValues: Boolean);
//var
// I{, J}: Integer;
// Field: IField;
// Elements: TUpdateElementIntfArray;
// AutoIncField: IAutoIncField;
// TableList: TTableIntfArray;
//// IntField: IIntegerSelectable;
//// FirstField: IField;
//// FirstFieldAsSelectable: IIntegerSelectable;
// SecondField: IField;
//// E: ITable;
//// IdValue: Integer;
// AutoIncFields: TFieldIntfArray;
//begin
// Table.BeforeInsert;
// Assert(Table.FieldCount > 0);
// if Table.FieldCount > 1 then
// begin
// SecondField := Table.FieldList[1];
// TableList := GetTableInheritanceOfField(SecondField);
// end
// else
// TableList := nil;
//
// AutoIncFields := nil;
//
//// AutoIncField := nil;
//
// if Length(TableList) <= 1 then
// begin
// for I := 0 to Table.FieldCount - 1 do
// begin
// Field := Table.FieldList[I];
// if ReturnAutoGeneratedValues then
// begin
// if Supports(Field, IAutoIncField, AutoIncField) then
// begin
// SetLength(AutoIncFields, Length(AutoIncFields) + 1);
// AutoIncFields[High(AutoIncFields)] := AutoIncField;
// // if AutoIncField.GeneratorName = '' then
// // raise Exception.CreateFmt('Generator is empty for %s.%s', [Table.Name, AutoIncField.Name]);
// if AutoIncField.IsNull then
// begin
// // case AutoIncField.DataType of
// // dtInteger: (AutoIncField as IIntegerSelectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// // dtInt64: (AutoIncField as IInt64Selectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// // dtSmallInt: (AutoIncField as ISmallIntSelectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// // else
// // Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(AutoIncField.DataType)));
// // end;
// end;
// end
// else if Field.InPrimaryKey then
// begin
//// if Field.IsNull then
//// raise Exception.CreateFmt('primary key field %s.%s must be filled before insert', [Table.Name, Field.Name]);
// end;
// end;
//
//// Assert(False, 'AutoInc');
//
// SetLength(Elements, Length(Elements) + 1);
// Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
// end;
// Assert(Assigned(Elements), Table.Name);
// if ReturnAutoGeneratedValues then
// begin
// if Assigned(AutoIncFields) then
// ExecInsert(Insert(Elements).Returns(AutoIncFields))
// else
// ExecInsert(Insert(Elements))
// end
//// else if ReturnAllFieldValues then
//// begin
//// Assert(False);
//// end
// else
// ExecInsert(Insert(Elements));
// end
// else
// begin
// Assert(False);
////// SecondField.Table.InheritanceIdField
//// FirstField := Table.FieldList[0];
//// Assert(FirstField.InPrimaryKey);
//// if FirstField.DataType <> dtInteger then
//// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Ord(FirstField.DataType)));
////
//// Assert(FirstField.Table as IInterface = Table as IInterface);
//// Assert(Table.InheritanceIdField as IInterface = FirstField as IInterface);
//// Assert(SecondField.Table.InheritanceIdField as IInterface = TableList[0].InheritanceIdField as IInterface);
////
//// FirstFieldAsSelectable := Table.InheritanceIdField as IIntegerSelectable;
//// Assert(Assigned(FirstFieldAsSelectable));
////// SecondField.Table.InheritanceIdField;
////// Assert(Assigned(SecondField));
////
//// Assert(UpperCase(FirstField.Name) = 'ID', FirstField.Name);
//// if Supports(FirstField, IAutoIncField, AutoIncField) then
//// begin
//// Assert(False, 'AutoInc');
////// if AutoIncField.GeneratorName = '' then
////// raise Exception.CreateFmt('Generator is empty for %s.%s', [Table.Name, AutoIncField.Name]);
////// if AutoIncField.IsNull then
////// FirstFieldAsSelectable.Value := Gen_Id(AutoIncField.GeneratorName, 1);
//// end
//// else
//// begin
//// Assert(False); // for first time
//// if FirstField.IsNull then
//// begin
//// raise Exception.CreateFmt('primary key field %s.%s must be filled before insert', [Table.Name, FirstField.Name])
//// end;
//// end;
////
////// case FirstField.DataType of
////// dtInteger: IdValue := (FirstField as IIntegerSelectable).Value;
////// else
////// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(FirstField.DataType)));
////// IdValue := 0;
////// end;
////
//// for J := 0 to High(TableList) do
//// begin
//// E := TableList[J];
//// Elements := nil;
//// if J <> High(TableList) then
//// begin
////// SetLength(Elements, 1);
//// if FirstFieldAsSelectable.IsNull then
//// E.InheritanceIdField.Clear
//// else
//// (E.InheritanceIdField as IIntegerSelectable).Value := FirstFieldAsSelectable.Value;
////// Elements[High(Elements)] := E.InheritanceIdField.MakeSelfValueUpdateElement;
//// end;
////
//// for I := 0 to E.FieldCount - 1 do
//// begin
//// Field := E.FieldList[I];
//// if Field.Table = E then
//// begin
//// SetLength(Elements, Length(Elements) + 1);
//// Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
//// end;
//// end;
//// Assert(Assigned(Elements), E.Name);
//// ExecInsert(Insert(Elements));
//// end;
// end;
//end;
procedure TTransaction.InsertRecord(Table: ITable; ReturnKeyValues: Boolean = True);
var
I{, J}: Integer;
Field: IField;
Elements: TUpdateElementIntfArray;
// AutoIncField: IAutoIncField;
// TableList: TTableIntfArray;
// IntField: IIntegerSelectable;
// FirstField: IField;
// FirstFieldAsSelectable: IIntegerSelectable;
// SecondField: IField;
// E: ITable;
// IdValue: Integer;
// AutoGeneratedFields: TSelectableIntfArray;
TheReturnFields: TSelectableIntfArray;
begin
// Table.BeforeInsert;
Assert(Table.FieldCount > 0);
// if Table.FieldCount > 1 then
// begin
// SecondField := Table.FieldList[1];
// TableList := GetTableInheritanceOfField(SecondField);
// end
// else
// TableList := nil;
TheReturnFields := nil;
for I := 0 to Table.FieldCount - 1 do
begin
Field := Table.FieldList[I];
if Field.HasValue then
begin
SetLength(Elements, Length(Elements) + 1);
Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
end;
// Assert(False, 'AutoInc');
if ReturnKeyValues and Field.InPrimaryKey then
begin
SetLength(TheReturnFields, Length(TheReturnFields) + 1);
TheReturnFields[High(TheReturnFields)] := Field;
end;
end;
Assert(Assigned(Elements), Table.TableName);
if Assigned(TheReturnFields) then
ExecInsert(BaseInsert(Elements).Returns(TheReturnFields))
else
ExecInsert(BaseInsert(Elements));
// end
// else
// begin
// Assert(False);
//// SecondField.Table.InheritanceIdField
// FirstField := Table.FieldList[0];
// Assert(FirstField.InPrimaryKey);
// if FirstField.DataType <> dtInteger then
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Ord(FirstField.DataType)));
//
// Assert(FirstField.Table as IInterface = Table as IInterface);
// Assert(Table.InheritanceIdField as IInterface = FirstField as IInterface);
// Assert(SecondField.Table.InheritanceIdField as IInterface = TableList[0].InheritanceIdField as IInterface);
//
// FirstFieldAsSelectable := Table.InheritanceIdField as IIntegerSelectable;
// Assert(Assigned(FirstFieldAsSelectable));
//// SecondField.Table.InheritanceIdField;
//// Assert(Assigned(SecondField));
//
// Assert(UpperCase(FirstField.Name) = 'ID', FirstField.Name);
// if Supports(FirstField, IAutoIncField, AutoIncField) then
// begin
// Assert(False, 'AutoInc');
//// if AutoIncField.GeneratorName = '' then
//// raise Exception.CreateFmt('Generator is empty for %s.%s', [Table.Name, AutoIncField.Name]);
//// if AutoIncField.IsNull then
//// FirstFieldAsSelectable.Value := Gen_Id(AutoIncField.GeneratorName, 1);
// end
// else
// begin
// Assert(False); // for first time
// if FirstField.IsNull then
// begin
// raise Exception.CreateFmt('primary key field %s.%s must be filled before insert', [Table.Name, FirstField.Name])
// end;
// end;
//
//// case FirstField.DataType of
//// dtInteger: IdValue := (FirstField as IIntegerSelectable).Value;
//// else
//// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(FirstField.DataType)));
//// IdValue := 0;
//// end;
//
// for J := 0 to High(TableList) do
// begin
// E := TableList[J];
// Elements := nil;
// if J <> High(TableList) then
// begin
//// SetLength(Elements, 1);
// if FirstFieldAsSelectable.IsNull then
// E.InheritanceIdField.Clear
// else
// (E.InheritanceIdField as IIntegerSelectable).Value := FirstFieldAsSelectable.Value;
//// Elements[High(Elements)] := E.InheritanceIdField.MakeSelfValueUpdateElement;
// end;
//
// for I := 0 to E.FieldCount - 1 do
// begin
// Field := E.FieldList[I];
// if Field.Table = E then
// begin
// SetLength(Elements, Length(Elements) + 1);
// Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
// end;
// end;
// Assert(Assigned(Elements), E.Name);
// ExecInsert(Insert(Elements));
// end;
// end;
end;
procedure TTransaction.InsertRecordWithReturn(Table: ITable;
const ReturnFields: TSelectableIntfArray);
var
I{, J}: Integer;
Field: IField;
Elements: TUpdateElementIntfArray;
// AutoIncField: IAutoIncField;
// TableList: TTableIntfArray;
// IntField: IIntegerSelectable;
// FirstField: IField;
// FirstFieldAsSelectable: IIntegerSelectable;
// SecondField: IField;
// E: ITable;
// IdValue: Integer;
// AutoGeneratedFields: TSelectableIntfArray;
TheReturnFields: TSelectableIntfArray;
begin
// Table.BeforeInsert;
Assert(Table.FieldCount > 0);
// if Table.FieldCount > 1 then
// begin
// SecondField := Table.FieldList[1];
// TableList := GetTableInheritanceOfField(SecondField);
// end
// else
// TableList := nil;
if Assigned(ReturnFields) then
TheReturnFields := ReturnFields
else
TheReturnFields := Table.All;
// AutoGeneratedFields := nil;
// AutoIncField := nil;
// if Length(TableList) <= 1 then
// begin
for I := 0 to Table.FieldCount - 1 do
begin
Field := Table.FieldList[I];
// if Field.HasGenerator then
// begin
// if Field.IsNull then
// begin
// if Supports(Field, IAutoIncField, AutoIncField) then
// begin
// if AutoIncField.GeneratorName = '' then
// raise Exception.CreateFmt('Generator is empty for %s.%s', [Table.TableName, Field.Name]);
//
// case AutoIncField.DataType of
// dtInteger: (AutoIncField as IIntegerSelectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// dtInt64: (AutoIncField as IInt64Selectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// dtSmallInt: (AutoIncField as ISmallIntSelectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// else
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(AutoIncField.DataType)));
// end;
// end
// else
// Assert(False, Field.ImplObjectClassName);
// end;
// end;
// AutoIncField := nil;
// if ReturnAutoGeneratedValues then
// begin
// if Field.IsAutoGenerated then
// begin
// SetLength(AutoGeneratedFields, Length(AutoGeneratedFields) + 1);
// AutoGeneratedFields[High(AutoGeneratedFields)] := Field;
// // if AutoIncField.GeneratorName = '' then
// // raise Exception.CreateFmt('Generator is empty for %s.%s', [Table.Name, AutoIncField.Name]);
// if not Field.IsNull then
// begin
// end
// else
// begin
// // case AutoIncField.DataType of
// // dtInteger: (AutoIncField as IIntegerSelectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// // dtInt64: (AutoIncField as IInt64Selectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// // dtSmallInt: (AutoIncField as ISmallIntSelectable).Value := Gen_Id(AutoIncField.GeneratorName, 1);
// // else
// // Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(AutoIncField.DataType)));
// // end;
// end;
// end
// else if Field.InPrimaryKey then
// begin
//// if Field.IsNull then
//// raise Exception.CreateFmt('primary key field %s.%s must be filled before insert', [Table.Name, Field.Name]);
// end
// end;
// if (not Field.IsAutoGenerated) or (not Field.IsNull) then
// begin
// SetLength(Elements, Length(Elements) + 1);
// Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
// end;
if Field.HasValue then
begin
SetLength(Elements, Length(Elements) + 1);
Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
end;
// Assert(False, 'AutoInc');
end;
Assert(Assigned(Elements), Table.TableName);
// if ReturnAutoGeneratedValues then
// begin
// if Assigned(AutoGeneratedFields) then
ExecInsert(BaseInsert(Elements).Returns(TheReturnFields));
// else
// ExecInsert(BaseInsert(Elements))
// end
//// else if ReturnAllFieldValues then
//// begin
//// Assert(False);
//// end
// else
// ExecInsert(BaseInsert(Elements));
// end
// else
// begin
// Assert(False);
//// SecondField.Table.InheritanceIdField
// FirstField := Table.FieldList[0];
// Assert(FirstField.InPrimaryKey);
// if FirstField.DataType <> dtInteger then
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Ord(FirstField.DataType)));
//
// Assert(FirstField.Table as IInterface = Table as IInterface);
// Assert(Table.InheritanceIdField as IInterface = FirstField as IInterface);
// Assert(SecondField.Table.InheritanceIdField as IInterface = TableList[0].InheritanceIdField as IInterface);
//
// FirstFieldAsSelectable := Table.InheritanceIdField as IIntegerSelectable;
// Assert(Assigned(FirstFieldAsSelectable));
//// SecondField.Table.InheritanceIdField;
//// Assert(Assigned(SecondField));
//
// Assert(UpperCase(FirstField.Name) = 'ID', FirstField.Name);
// if Supports(FirstField, IAutoIncField, AutoIncField) then
// begin
// Assert(False, 'AutoInc');
//// if AutoIncField.GeneratorName = '' then
//// raise Exception.CreateFmt('Generator is empty for %s.%s', [Table.Name, AutoIncField.Name]);
//// if AutoIncField.IsNull then
//// FirstFieldAsSelectable.Value := Gen_Id(AutoIncField.GeneratorName, 1);
// end
// else
// begin
// Assert(False); // for first time
// if FirstField.IsNull then
// begin
// raise Exception.CreateFmt('primary key field %s.%s must be filled before insert', [Table.Name, FirstField.Name])
// end;
// end;
//
//// case FirstField.DataType of
//// dtInteger: IdValue := (FirstField as IIntegerSelectable).Value;
//// else
//// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(FirstField.DataType)));
//// IdValue := 0;
//// end;
//
// for J := 0 to High(TableList) do
// begin
// E := TableList[J];
// Elements := nil;
// if J <> High(TableList) then
// begin
//// SetLength(Elements, 1);
// if FirstFieldAsSelectable.IsNull then
// E.InheritanceIdField.Clear
// else
// (E.InheritanceIdField as IIntegerSelectable).Value := FirstFieldAsSelectable.Value;
//// Elements[High(Elements)] := E.InheritanceIdField.MakeSelfValueUpdateElement;
// end;
//
// for I := 0 to E.FieldCount - 1 do
// begin
// Field := E.FieldList[I];
// if Field.Table = E then
// begin
// SetLength(Elements, Length(Elements) + 1);
// Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
// end;
// end;
// Assert(Assigned(Elements), E.Name);
// ExecInsert(Insert(Elements));
// end;
// end;
end;
//procedure TTransaction.InternalBindFieldsToClientDataSet(
// const Selectables: TSelectableIntfArray; cds: TClientDataSet);
//var
// I: Integer;
// Selectable: ISelectable;
// DsField: TField;
//begin
// for I := 0 to High(Selectables) do
// begin
// Selectable := Selectables[I];
// DsField := cds.FieldByName(Selectable.Alias);
//
// if Selectable.IsNull then
// DsField.Clear
// else
// begin
// case Selectable.DataType of
// dtInteger: (DsField as TIntegerField).Value := (Selectable as IIntegerSelectable).Value;
// dtInt64: (DsField as TLargeintField).Value := (Selectable as IInt64Selectable).Value;
// dtString: (DsField as TWideStringField).Value := (Selectable as IStringSelectable).Value;
// dtFloat: (DsField as TFloatField).Value := (Selectable as IFloatSelectable).Value;
// dtBoolean: (DsField as TBooleanField).Value := (Selectable as IBooleanSelectable).Value;
// dtDate: (DsField as TDateField).Value := (Selectable as IDateSelectable).Value;
// dtTime: (DsField as TTimeField).Value := (Selectable as ITimeSelectable).Value;
// dtDateTime: (DsField as TDateTimeField).Value := (Selectable as IDateTimeSelectable).Value;
// dtMemo: (DsField as TWideMemoField).Value := (Selectable as IMemoSelectable).Value;
// dtBlob: (DsField as TBlobField).AsAnsiString := (Selectable as IBlobSelectable).Value;
// dtSmallInt: (DsField as TSmallintField).Value := (Selectable as ISmallIntSelectable).Value;
// else
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(Selectable.DataType)));
// end;
// end;
// end;
//end;
function TTransaction.InternalExecInsert(
Query: IBaseInsertQuery): IInsertQueryResult;
var
qry: IQueryWrapper;
Sql: UnicodeString;
LogStr: UnicodeString;
// RowsAffected: Int64;
Params: TSqlParamIntfArray;
begin
qry := FConnWrapper.Trans.MakeQueryWrapper;
Sql := NewSqlRenderer(GetEngine).StrOfInsertQuery(Query);
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
Params := Query.GetParams;
if Logger.Use then
AddParamValues(LogStr, Params);
// RowsAffected := qry.ExecuteAndGetRowsAffected(Sql, Params);
// Result := TInsertQueryResult.Create(RowsAffected);
Result := InternalExecuteInsertQuery(qry, Sql, Params, Query.GetReturnsElements);
if Logger.Use then
AddToStr(LogStr, 'Rows Affected: ' + IntToStr(Result.RowsAffected));
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TTransaction.InternalExecUpdate(
Query: IBaseUpdateQuery): IUpdateQueryResult;
var
qry: IQueryWrapper;
Sql: UnicodeString;
LogStr: UnicodeString;
RowsAffected: Int64;
Params: TSqlParamIntfArray;
begin
qry := FConnWrapper.Trans.MakeQueryWrapper;
Sql := NewSqlRenderer(GetEngine).StrOfUpdateQuery(Query);
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
Params := Query.GetParams;
if Logger.Use then
AddParamValues(LogStr, Params);
RowsAffected := qry.ExecuteAndGetRowsAffected(Sql, Params);
Result := TUpdateQueryResult.Create(RowsAffected);
if Logger.Use then
AddToStr(LogStr, 'Rows Affected: ' + IntToStr(RowsAffected));
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
procedure TransferReturnFieldValue(const V: Variant; ReturnType: TSqlDataType; Dest: ISelectable);
begin
if VarIsNull(V) then
Dest.Clear
else
begin
case Dest.DataType of
dtInteger:
begin
Assert(ReturnType = dtInteger);
(Dest as IIntegerSelectable).Value := V;
end;
dtString:
begin
Assert(ReturnType = dtString);
(Dest as IStringSelectable).Value := V;
end;
dtBinaryString:
begin
Assert(ReturnType = dtBinaryString);
(Dest as IBinaryStringSelectable).Value := AnsiString(V);
end;
dtFloat:
begin
Assert(ReturnType = dtFloat);
(Dest as IFloatSelectable).Value := V;
end;
dtBcd:
begin
Assert(ReturnType = dtBcd);
(Dest as IBcdSelectable).Value := VarToBcd(V);
end;
dtBoolean:
begin
if ReturnType = dtBoolean then
(Dest as IBooleanSelectable).Value := V
else if ReturnType = dtInteger then
(Dest as IBooleanSelectable).Value := V = 1
else
Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(ReturnType)));
end;
dtDate:
begin
Assert(ReturnType = dtDate);
{$IFDEF FPC}
(Dest as IDateSelectable).Value := VarToDateTime(V);
{$ELSE}
(Dest as IDateSelectable).Value := V;
{$ENDIF}
end;
dtTime:
begin
Assert(ReturnType = dtTime);
{$IFDEF FPC}
(Dest as ITimeSelectable).Value := VarToDateTime(V);
{$ELSE}
(Dest as ITimeSelectable).Value := V;
{$ENDIF}
end;
dtDateTime:
begin
Assert(ReturnType = dtDateTime);
(Dest as IDateTimeSelectable).Value := V;
end;
dtMemo:
begin
Assert(ReturnType = dtMemo);
(Dest as IMemoSelectable).Value := V;
end;
// dtSmallInt:
// begin
// Assert(ReturnType = dtSmallInt);
// (Dest as ISmallIntSelectable).Value := V;
// end;
dtBlob:
begin
Assert(ReturnType = dtBlob);
(Dest as IBlobSelectable).Value := AnsiString(V);
end;
// dtInt64:
// begin
// Assert(ReturnType = dtInt64);
// (Dest as IInt64Selectable).Value := V;
// end;
else
Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(Dest.DataType)));
end;
end;
end;
function TTransaction.InternalExecuteInsertQuery(qry: IQueryWrapper;
const Sql: UnicodeString; const Params: TSqlParamIntfArray;
const Returns: TSelectableIntfArray): IInsertQueryResult;
var
// RowsAffected: Int64;
// FirebirdQueryWrapper: IFirebirdQueryWrapper;
ReturnTypes: TSqlDataTypeArray;
ReturnFields: TStringDynArray;
ReturnValues: TNSVariantDynArray;
// Field: ISelectable;
// V: Variant;
I: Integer;
// ReturnType: TSqlDataType;
begin
// FirebirdQueryWrapper := qry as IFirebirdQueryWrapper;
qry.ExecInsertWithReturn(Sql, Params, ReturnTypes, ReturnFields, ReturnValues, False);
if Length(ReturnValues) <> Length(Returns) then
Assert(False);
for I := 0 to High(Returns) do
begin
TransferReturnFieldValue(ReturnValues[I], ReturnTypes[I], Returns[I]);
// Field := Returns[I];
// V := ReturnValues[I];
// if VarIsNull(V) then
// Field.Clear
// else
// begin
// ReturnType := ReturnTypes[I];;
// case Field.DataType of
// dtInteger:
// begin
// Assert(ReturnType = dtInteger);
// (Field as IIntegerSelectable).Value := V;
// end;
// dtString:
// begin
// Assert(ReturnType = dtString);
// (Field as IStringSelectable).Value := V;
// end;
// dtFloat:
// begin
// Assert(ReturnType = dtFloat);
// (Field as IFloatSelectable).Value := V;
// end;
// dtBcd:
// begin
// Assert(ReturnType = dtBcd);
// (Field as IBcdSelectable).Value := VarToBcd(V);
// end;
// dtBoolean:
// begin
// if ReturnType = dtBoolean then
// (Field as IBooleanSelectable).Value := V
// else if ReturnType = dtInteger then
// (Field as IBooleanSelectable).Value := V = 1
// else
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(ReturnType)));
// end;
// dtDate:
// begin
// Assert(ReturnType = dtDate);
// (Field as IDateSelectable).Value := V;
// end;
// dtTime:
// begin
// Assert(ReturnType = dtTime);
// (Field as ITimeSelectable).Value := V;
// end;
// dtDateTime:
// begin
// Assert(ReturnType = dtDateTime);
// (Field as IDateTimeSelectable).Value := V;
// end;
// dtMemo:
// begin
// Assert(ReturnType = dtMemo);
// (Field as IMemoSelectable).Value := V;
// end;
//// dtSmallInt:
//// begin
//// Assert(ReturnType = dtSmallInt);
//// (Field as ISmallIntSelectable).Value := V;
//// end;
// dtBlob:
// begin
// Assert(ReturnType = dtBlob);
// (Field as IBlobSelectable).Value := V;
// end;
//// dtInt64:
//// begin
//// Assert(ReturnType = dtInt64);
//// (Field as IInt64Selectable).Value := V;
//// end;
// else
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(Field.DataType)));
// end;
// end;
end;
Result := TInsertQueryResult.Create(1);
end;
//function TTransaction.InternalExecuteInsertQuery(qry: IQueryWrapper; const Sql: UnicodeString; const Params: TSqlParamIntfArray; const Returns: TFieldIntfArray): IInsertQueryResult;
//var
// RowsAffected: Int64;
//begin
// RowsAffected := qry.ExecuteAndGetRowsAffected(Sql, Params);
// Result := TInsertQueryResult.Create(RowsAffected);
//end;
function TTransaction.InternalGetTransactionId: Int64;
begin
Result := FConnWrapper.Trans.GetTransactionId;
end;
procedure TTransaction.InternalStart(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger);
var
LogStr: UnicodeString;
begin
if Logger.Use then
begin
if not Params.IsReadOnly then
LogStr := Format('Start Transaction (%s): ', [Params.Description])
else
LogStr := Format('Start ReadOnly Transaction (%s): ', [Params.Description]);
end;
try
FConnWrapper.Trans.Start(Params);
StartNotification;
if Logger.Use then
LogStr := LogStr + Format('Ok, Id = %d', [TransactionId]);
if Assigned(TransactionStartTrigger) then
TransactionStartTrigger.Execute(Self);
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
//procedure TTransaction.BindFieldsToClientDataSet(const Selectables: array of ISelectable; Ds: TClientDataSet);
//var
// I: Integer;
// SelectableArray: TSelectableIntfArray;
//begin
// SetLength(SelectableArray, Length(Selectables));
// for I := 0 to High(Selectables) do
// SelectableArray[I] := Selectables[I];
//
// InternalBindFieldsToClientDataSet(SelectableArray, Ds);
//end;
//function TTransaction.CreateClientDataSet(
// Query: IBaseSelectQuery; RecordMakeHelper: IRecordMakeHelper = nil): TClientDataSet;
//begin
// Result := TClientDataSet.Create(nil);
// try
// MakeClientDataSet(Result, Query, RecordMakeHelper);
// except
// Result.Free;
// raise;
// end;
//end;
//
//procedure TTransaction.MakeClientDataSet(cds: TClientDataSet;
// Query: IBaseSelectQuery; RecordMakeHelper: IRecordMakeHelper = nil);
//var
// Rs: IRecordSet;
// Selectables: TSelectableIntfArray;
// AfterScroll, BeforeScroll: TDataSetNotifyEvent;
//// I: Integer;
//begin
// Selectables := Query.GetSelectables;
// cds.DisableControls;
// try
// AfterScroll := cds.AfterScroll;
// BeforeScroll := cds.BeforeScroll;
// cds.AfterScroll := nil;
// cds.BeforeScroll := nil;
// try
// Rs := OpenQuery(Query, RecordMakeHelper);
// MakeEmptyClientDataSet(cds, Selectables);
// Rs.FetchAll;
// while not Rs.Eod do
// begin
// cds.Append;
// InternalBindFieldsToClientDataSet(Selectables, cds);
// cds.Post;
// Rs.Next;
// end;
// finally
// cds.AfterScroll := AfterScroll;
// cds.BeforeScroll := BeforeScroll;
// end;
// cds.First;
// finally
// cds.EnableControls;
// end;
//end;
function NowAsStr: UnicodeString;
var
D: TDateTime;
MSec: Word;
begin
D := Now;
MSec := {$IFDEF NSQL_XE2UP}System.{$ENDIF}DateUtils.MilliSecondOf(D);
Result := DateTimeToStr(D) + '.' + IntToStr(MSec);
end;
//procedure TTransaction.MakeClientDataSet(cds: TClientDataSet;
// const Sql: UnicodeString; const Params: TSqlParamIntfArray);
//var
//// Rs: IRecordSet;
// // Selectables: TSelectableIntfArray;
// AfterScroll, BeforeScroll: TDataSetNotifyEvent;
//// I: Integer;
//begin
//// Selectables := Query.GetSelectables;
// cds.DisableControls;
// try
// AfterScroll := cds.AfterScroll;
// BeforeScroll := cds.BeforeScroll;
// cds.AfterScroll := nil;
// cds.BeforeScroll := nil;
// try
// FConnWrapper.Trans.MakeClientDataSet(cds, Sql, Params);
//// Rs := OpenQuery(Query, RecordMakeHelper);
//// MakeEmptyClientDataSet(cds, Selectables);
//// Rs.FetchAll;
//// while not Rs.Eod do
//// begin
//// cds.Append;
//// InternalBindFieldsToClientDataSet(Selectables, cds);
//// cds.Post;
//// Rs.Next;
//// end;
// finally
// cds.AfterScroll := AfterScroll;
// cds.BeforeScroll := BeforeScroll;
// end;
// cds.First;
// finally
// cds.EnableControls;
// end;
//end;
function TTransaction.MakeDataSet(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray; Cached: Boolean = False): ISqlDataSet;
var
LogStr: UnicodeString;
StartTicks: Cardinal;
OpenTicks: Cardinal;
// StartStr: UnicodeString;
begin
Result := nil;
StartTicks := 0;
if Logger.Use then
StartTicks := GetTickCount;
if Logger.Use then
begin
// StartStr := NowAsStr;
LogStr := NowAsStr + #13#10 + Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
if Logger.Use then
AddParamValues(LogStr, SqlParams);
Result := FConnWrapper.Trans.MakeDataSet(Sql, SqlParams, Cached);
if Logger.Use then
begin
OpenTicks := GetRange(GetTickCount, StartTicks);
LogStr := LogStr + #13#10 + NowAsStr + #13#10 + Format('[OpenTime = %d ms]', [OpenTicks]);
end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr, False);
end;
//function TTransaction.MakeDataSet(const Sql: UnicodeString;
// const SqlParams: TSqlParamIntfArray; Cached: Boolean = False): ISqlDataSet;
//var
//// LogStr: UnicodeString;
// LogHeader: UnicodeString;
//begin
// Result := nil;
// if Logger.Use then
// begin
// LogHeader := Format('[TransId = %d]', [TransactionId]);
//// LogStr := Sql;
// Logger.Log(LogHeader + #13#10 + Sql, True, False, True);
// end;
// try
// if Logger.Use then
// Logger.Log(GetParamsValuesAsString(SqlParams, PRINT_PARAMS_DELIMITER), False, False);
// Result := FConnWrapper.Trans.MakeDataSet(Sql, SqlParams, Cached);
// if Logger.Use then
// Logger.Log(LogHeader + ' - Ok');
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogHeader, E);
// end;
//// if Logger.Use then
//// Logger.Log(LogStr);
//end;
function TTransaction.MakeDataSet(const Sql: UnicodeString;
const SqlParams: array of ISqlParam; Cached: Boolean = False): ISqlDataSet;
begin
Result := MakeDataSet(Sql, MakeParamArray(SqlParams), Cached);
end;
function TTransaction.MakeDataSet(const Sql: UnicodeString; Cached: Boolean = False): ISqlDataSet;
var
LogStr: UnicodeString;
StartTicks: Cardinal;
OpenTicks: Cardinal;
begin
StartTicks := 0;
Result := nil;
// try
if Logger.Use then
begin
StartTicks := GetTickCount;
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
Result := FConnWrapper.Trans.MakeDataSet(Sql, Cached);
if Logger.Use then
begin
OpenTicks := GetRange(GetTickCount, StartTicks);
LogStr := LogStr + #13#10 + Format('[OpenTime = %d ms]', [OpenTicks]);
end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
// except
// Result.Free;
// raise;
// end;
end;
//procedure TTransaction.MakeEmptyClientDataSet(cds: TClientDataSet; const SelectableArray: TSelectableIntfArray);
//var
// I: Integer;
// Selectable: ISelectable;
// FD: TFieldDef;
// F: TField;
// StringSelectable: IStringSelectable;
//begin
// cds.Close;
// cds.Fields.Clear;
// cds.FieldDefs.Clear;
// for I := 0 to High(SelectableArray) do
// begin
// Selectable := SelectableArray[I];
//
// FD := cds.FieldDefs.AddFieldDef;
// case Selectable.DataType of
// dtInteger: FD.DataType := ftInteger;
// dtInt64: FD.DataType := ftLargeint;
// dtString: FD.DataType := ftWideString;
// dtFloat: FD.DataType := ftFloat;
// dtBoolean: FD.DataType := ftBoolean;
// dtDate: FD.DataType := ftDate;
// dtTime: FD.DataType := ftTime;
// dtDateTime: FD.DataType := ftDateTime;
// dtMemo: FD.DataType := ftWideMemo;
// dtBlob: FD.DataType := ftBlob;
// dtSmallInt: FD.DataType := ftSmallInt;
// else
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Integer(Selectable.DataType)));
// end;
//
// if FD.DataType = ftWideString then
// begin
// Assert(Supports(Selectable, IStringSelectable, StringSelectable));
// FD.Size := StringSelectable.FieldSize;
// Assert(FD.Size > 0, Selectable.Alias);
// end;
// FD.Name := Selectable.Alias;
// F := FD.CreateField(cds);
// F.FieldName := FD.Name;
//
// if Selectable.DisplayLabel <> '' then
// F.DisplayLabel := Selectable.DisplayLabel
// else
// F.DisplayLabel := Selectable.Alias;
// F.DisplayWidth := Selectable.DisplayWidth;
// case Selectable.Alignment of
// faLeft: F.Alignment := taLeftJustify;
// faRight: F.Alignment := taRightJustify;
// faCenter: F.Alignment := taCenter;
// end;
//// F.Alignment := Selectable.Alignment;
// F.Visible := Selectable.Visible;
// F.DefaultExpression := Selectable.DefaultExpression;
// if F is TNumericField then
// TNumericField(F).DisplayFormat := Selectable.DisplayFormat
// else if F is TDateTimeField then
// TDateTimeField(F).DisplayFormat := Selectable.DisplayFormat
// else if F is TTimeField then
// TTimeField(F).DisplayFormat := Selectable.DisplayFormat
// else if F is TDateField then
// TDateField(F).DisplayFormat := Selectable.DisplayFormat;
// end;
//
// cds.CreateRecordSet;
//end;
//function TTransaction.GetActive: Boolean;
//begin
// Result := InTransaction;
//end;
//function TTransaction.GetTableInheritanceOfField(
// Field: IField): TTableIntfArray;
//var
// Table: ITable;
//begin
// Result := nil;
// Table := Field.Table;
// SetLength(Result, Length(Result) + 1);
// Result[High(Result)] := Table;
// while Assigned(Table.InheritedByTable) do
// begin
// Table := Table.InheritedByTable;
// SetLength(Result, Length(Result) + 1);
// Result[High(Result)] := Table;
// end;
//end;
function TTransaction.GenId(const Generator: UnicodeString;
Increment: Int64): Int64;
begin
Result := Gen_Id(Generator, Increment);
end;
function TTransaction.Gen_Id(const GenName: UnicodeString;
Increment: Int64): Int64;
var
LogStr: UnicodeString;
begin
Result := 0;
if Logger.Use then
LogStr := Format('GEN_ID("%s", %s)', [GenName, IntToStr(Increment)]);
try
Result := FConnWrapper.Trans.Gen_Id(GenName, Increment);
if Logger.Use then
LogStr := LogStr + ' = ' + IntToStr(Result);
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TTransaction.GetActive: Boolean;
begin
Result := InTransaction;
end;
function TTransaction.GetEngine: TNativeSqlEngine;
begin
Result := FConnWrapper.GetEngine;
end;
function TTransaction.GetInWork: Boolean;
begin
Result := FInWork;
end;
function TTransaction.GetTransactionId: Int64;
begin
if not InTransaction then
raise Exception.Create('not in transaction');
Result := InternalGetTransactionId;
end;
function TTransaction.GetUseRefCounting: Boolean;
begin
Result := False;
end;
function TTransaction.GetWorkTimeInMilliseconds: Cardinal;
begin
Result := GetTickCount;
if Result >= FStartTickCount then
Result := Result - FStartTickCount
else
Result := High(Cardinal) - FStartTickCount + Result;
end;
//function TTransaction.GetIsolationLevel: TTransactionIsolationLevel;
//begin
// Result := FIsolationLevel;
//end;
function TTransaction.GetLogger: ISqlLogger;
begin
Result := FLogger;
end;
function TTransaction.GetServerTime: TDateTime;
var
Ds: ISqlDataSet;
begin
Ds := MakeDataSet('SELECT CURRENT_TIMESTAMP FROM RDB$DATABASE');
// try
Result := Ds[0].AsDateTime;
// finally
// Ds.Free;
// end;
end;
//function TTransaction.Gen_Id(const GenName: UnicodeString;
// Increment: Int64): Int64;
//var
// LogStr: UnicodeString;
//begin
// Result := 0;
// if Logger.Use then
// LogStr := Format('GEN_ID("%s", %s)', [GenName, IntToStr(Increment)]);
// try
// Result := FConnWrapper.Trans.Gen_Id(GenName, Increment);
// if Logger.Use then
// LogStr := LogStr + ' = ' + IntToStr(Result);
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
procedure TTransaction.UpdateRecord(Table: ITable);
begin
UpdateRecord(Table, []);
end;
procedure TTransaction.UpdateRecord(Table: ITable;
const UpdFields: array of IField);
var
I{, J}: Integer;
Field: IField;
Elements: TUpdateElementIntfArray;
Condition: ISqlCondition;
// TableList: TTableIntfArray;
// FirstField: IField;
// E: ITable;
// IdValue: Integer;
// FirstField: IField;
// FirstFieldAsSelectable: IIntegerSelectable;
// SecondField: IField;
begin
// Table.BeforeUpdate;
Assert(Table.FieldCount > 0);
// if Table.FieldCount > 1 then
// begin
// SecondField := Table.FieldList[1];
// TableList := GetTableInheritanceOfField(SecondField);
// end
// else
// TableList := nil;
// if Length(TableList) <= 1 then
// begin
if Length(UpdFields) = 0 then
begin
for I := 0 to Table.FieldCount - 1 do
begin
Field := Table.FieldList[I];
if not Field.InPrimaryKey then
begin
SetLength(Elements, Length(Elements) + 1);
Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
end;
end;
end
else
begin
for I := 0 to High(UpdFields) do
begin
Field := UpdFields[I];
if Field.InPrimaryKey then
Assert(False, (Field.Structure as ITable).TableName + '.' + Field.Name)
else
begin
SetLength(Elements, Length(Elements) + 1);
Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
end;
end;
end;
for I := 0 to Table.FieldCount - 1 do
begin
Field := Table.FieldList[I];
if Field.InPrimaryKey then
begin
if Field.IsNull then
Assert(False, (Field.Structure as ITable).TableName + '.' + Field.Name) // primary-key fields must be filled before update
else
if Assigned(Condition) then
Condition := AllTrue([Condition, SelfEQCondition(Field)])
else
Condition := SelfEQCondition(Field);
end;
end;
Assert(Assigned(Elements), Table.TableName);
Assert(Assigned(Condition), Table.TableName);
Assert(ExecUpdate(BaseUpdate(Elements).Where(Condition)).RowsAffected = 1);
// end
// else
// begin
// FirstField := Table.FieldList[0];
// Assert(FirstField.InPrimaryKey);
// if FirstField.DataType <> dtInteger then
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Ord(FirstField.DataType)));
//
// Assert(FirstField.Table as IInterface = Table as IInterface);
// Assert(Table.InheritanceIdField as IInterface = FirstField as IInterface);
// Assert(SecondField.Table.InheritanceIdField as IInterface = TableList[0].InheritanceIdField as IInterface);
//
// FirstFieldAsSelectable := Table.InheritanceIdField as IIntegerSelectable;
// Assert(Assigned(FirstFieldAsSelectable));
//
// Assert(UpperCase(FirstField.Name) = 'ID', FirstField.Name);
//
// for J := 0 to High(TableList) do
// begin
// E := TableList[J];
// Elements := nil;
// if J <> High(TableList) then
// begin
// if FirstFieldAsSelectable.IsNull then
// E.InheritanceIdField.Clear
// else
// (E.InheritanceIdField as IIntegerSelectable).Value := FirstFieldAsSelectable.Value;
// end;
//
// Condition := SelfEQCondition(E.InheritanceIdField);
//
// for I := 0 to E.FieldCount - 1 do
// begin
// Field := E.FieldList[I];
// if Field.Table = E then
// begin
// if I <> 0 then
// Assert(not Field.InPrimaryKey, Field.Name);
// if not Field.InPrimaryKey then
// begin
// SetLength(Elements, Length(Elements) + 1);
// Elements[High(Elements)] := Field.MakeSelfValueUpdateElement;
// end;
// end;
// end;
// if Assigned(Elements) then
// begin
//// Assert(Assigned(Elements), E.Name);
// Assert(Assigned(Condition), E.Name);
// Assert(ExecUpdate(BaseUpdate(Elements).Where(Condition)).RowsAffected = 1);
// end;
// end;
// end;
end;
function TTransaction._Release: Integer;
var
WasError: Boolean;
begin
// not calls from StartDestroy; StartDestroy calls inherited _Release
Result := InterlockedDecrement(FRefCount);
if Result = 0 then
begin
// if InDestroyProcess then
// begin
// ShutdownConnection;
Free;
// end;
// implement normal transaction shutdown on getted tx and shutdown of thread pool
end
else
if (Result = 1) and (FInWork) then
begin
WasError := False;
try
try
if InTransaction then
Rollback(True);
except
on E: Exception do
begin
WasError := True;
{ TODO : implement this }
end;
end;
finally
FInWork := False;
end;
if not WasError then
FTransactionPool.Return(Self)
else
FTransactionPool.MarkAsBad(Self);
end;
end;
function TTransaction.LoadRecord(Table: ITable; Id: Int64): Boolean;
var
IdField: IField;
begin
IdField := CheckBeforeLoad(Table);
Assert(Supports(IdField, IIntegerSelectable));
Result := IsExists(BaseSelect(Table.All).From(Table).Where(EQImpl(IdField, MakeIntConst(Id))));
end;
function TTransaction.LoadRecord(Table: ITable; const Id: UnicodeString): Boolean;
var
IdField: IField;
begin
IdField := CheckBeforeLoad(Table);
Assert(Supports(IdField, IStringSelectable));
Result := IsExists(BaseSelect(Table.All).From(Table).Where(EQImpl(IdField, MakeStringConst(Id))));
end;
function TTransaction.MakeDataSet(Query: IBaseSelectQuery;
Cached: Boolean): ISqlDataSet;
var
DataSet: IDataSet;
begin
DataSet := TDataSetImpl.Create(FConnWrapper.Trans, Query, Logger, nil, Cached);
Result := DataSet.GetDatasetAndUnlink;
end;
procedure TTransaction.DeleteRecord(Table: ITable);
var
I: Integer;
Field: IField;
Condition: ISqlCondition;
// TableList: TTableIntfArray;
// FirstField: IField;
// FirstFieldAsSelectable: IIntegerSelectable;
// SecondField: IField;
// E: ITable;
begin
Assert(Table.FieldCount > 0);
// if Table.FieldCount > 1 then
// begin
// SecondField := Table.FieldList[1];
// TableList := GetTableInheritanceOfField(SecondField);
// end
// else
// TableList := nil;
// if Length(TableList) <= 1 then
// begin
for I := 0 to Table.FieldCount - 1 do
begin
Field := Table.FieldList[I];
if Field.InPrimaryKey then
begin
if Field.IsNull then
Assert(False, Format('primary key field %s.%s is null on delete Table', [(Field.Structure as ITable).TableName, Field.Name]))
else
if Assigned(Condition) then
Condition := AllTrue([Condition, SelfEQCondition(Field)])
else
Condition := SelfEQCondition(Field);
end;
end;
Assert(Assigned(Condition), Table.TableName);
Assert(ExecDelete(BaseDeleteFrom(Table).Where(Condition)).RowsAffected = 1);
// end
// else
// begin
// FirstField := Table.FieldList[0];
// Assert(FirstField.InPrimaryKey);
// if FirstField.DataType <> dtInteger then
// Assert(False, GetEnumName(TypeInfo(TSqlDataType), Ord(FirstField.DataType)));
//
// Assert(FirstField.Table as IInterface = Table as IInterface);
// Assert(Table.InheritanceIdField as IInterface = FirstField as IInterface);
// Assert(SecondField.Table.InheritanceIdField as IInterface = TableList[0].InheritanceIdField as IInterface);
//
// FirstFieldAsSelectable := Table.InheritanceIdField as IIntegerSelectable;
// Assert(Assigned(FirstFieldAsSelectable));
//
// Assert(UpperCase(FirstField.Name) = 'ID', FirstField.Name);
//
// if FirstFieldAsSelectable.IsNull then
// Assert(False, Format('primary key field %s.%s is null on delete Table', [FirstField.Table.Name, FirstField.Name]));
//
// for I := 0 to High(TableList) do
// begin
// E := TableList[I];
//// Elements := nil;
// if I <> High(TableList) then
// (E.InheritanceIdField as IIntegerSelectable).Value := FirstFieldAsSelectable.Value;
//
// Condition := SelfEQCondition(E.InheritanceIdField);
// Assert(Assigned(Condition), E.Name);
// Assert(ExecDelete(BaseDeleteFrom(E).Where(Condition)).RowsAffected = 1);
// end;
// end;
end;
function TTransaction.Prepare(Query: IBaseUpdateQuery): IPreparedUpdate;
begin
Result := TPreparedExecutableStatement.Create(FConnWrapper.Trans, Self, Query, stUpdate, Logger);
end;
function TTransaction.Prepare(Query: IBaseDeleteQuery): IPreparedDelete;
begin
Result := TPreparedExecutableStatement.Create(FConnWrapper.Trans, Self, Query, stDelete, Logger);
end;
function TTransaction.Prepare(Query: IBaseInsertQuery): IPreparedInsert;
begin
Result := TPreparedExecutableStatement.Create(FConnWrapper.Trans, Self, Query, stInsert, Logger);
end;
function TTransaction.PrepareInsertWithReturn(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray;
const ReturnFields: TStringDynArray): IPreparedInsertWithReturn;
begin
Result := TPreparedInsertWithReturnSql.Create(FConnWrapper.Trans, Self, Sql, SqlParams, ReturnFields, Logger);
end;
function TTransaction.PrepareInsertWithReturn(const Sql: UnicodeString;
const SqlParams: array of ISqlParam;
const ReturnFields: array of string): IPreparedInsertWithReturn;
begin
Result := PrepareInsertWithReturn(Sql, MakeParamArray(SqlParams), MakeStrArray(ReturnFields));
end;
//function TTransaction.PrepareInsertSql(const Sql: UnicodeString;
// const SqlParams: TSqlParamIntfArray): IPreparedInsert;
//begin
// Assert(False);
//// Result := TPreparedSelect.Create(FConnWrapper.Trans, Self, Sql, SqlParams, Logger);
//end;
//function TTransaction.PrepareInsertSql(const Sql: UnicodeString;
// const SqlParams: array of ISqlParam): IPreparedInsert;
//begin
// Result := PrepareInsertSql(Sql, MakeParamArray(SqlParams));
//end;
function TTransaction.PrepareSelectSql(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray): IPreparedSelect;
begin
Result := TPreparedSelect.Create(FConnWrapper.Trans, Self, Sql, SqlParams, Logger);
end;
function TTransaction.PrepareSelectSql(const Sql: UnicodeString;
const SqlParams: array of ISqlParam): IPreparedSelect;
begin
Result := PrepareSelectSql(Sql, MakeParamArray(SqlParams));
end;
function TTransaction.PrepareSql(const Sql: UnicodeString;
const SqlParams: TSqlParamIntfArray): IPreparedSql;
begin
Result := TPreparedSql.Create(FConnWrapper.Trans, Self, Sql, SqlParams, Logger);
//var
// qry: IQueryWrapper;
// LogStr: UnicodeString;
//begin
// qry := FConnWrapper.Trans.MakeQueryWrapper;
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
// LogStr := LogStr + Sql;
// end;
// try
//// qry.SetParamNamesFromQuery(SqlParams);
// if Logger.Use then
// AddParamValues(LogStr, SqlParams);
// qry.Execute(Sql, SqlParams, True);
// if Logger.Use then
// AddToStr(LogStr, 'Ok.');
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
end;
function TTransaction.PrepareSql(const Sql: UnicodeString;
const SqlParams: array of ISqlParam): IPreparedSql;
begin
Result := PrepareSql(Sql, MakeParamArray(SqlParams));
end;
function TTransaction.PrepareSqlNative(const Sql: UnicodeString): TObject;
begin
Result := FConnWrapper.Trans.MakePreparedNativeStatement(Sql);
end;
//function TTransaction.GenId(const Generator: UnicodeString;
// Increment: Int64): Int64;
//begin
// Result := Gen_Id(Generator, Increment);
//end;
function TTransaction.IsExists(Query: IBaseSelectQuery): Boolean;
begin
Result := not OpenQuery(Query).Eod;
end;
function TTransaction.IsReadOnly: Boolean;
begin
Result := FParams.IsReadOnly;
end;
function TTransaction.LoadRecord(Table: ITable;
const Id: TSqlBinaryStringValue): Boolean;
var
IdField: IField;
begin
IdField := CheckBeforeLoad(Table);
Assert(Supports(IdField, IBinaryStringSelectable));
Result := IsExists(BaseSelect(Table.All).From(Table).Where(EQImpl(IdField, MakeBinaryStringConst(Id))));
end;
//procedure TTransaction.MakeClientDataSet(cds: TClientDataSet;
// const Sql: UnicodeString; Params: TParams);
//begin
// FConnWrapper.Trans.MakeClientDataSet(cds, Sql, Params);
//end;
//function TTransaction.MakeDataSet(const Sql: UnicodeString;
// Params: TParams; Cached: Boolean = False): ISqlDataSet;
//var
// LogStr: UnicodeString;
// StartTicks: Cardinal;
// OpenTicks: Cardinal;
//begin
// if not Assigned(Params) then
// begin
// Result := MakeDataSet(Sql, Cached);
// Exit;
// end;
// StartTicks := 0;
// Result := nil;
// try
// if Logger.Use then
// begin
// StartTicks := GetTickCount;
// LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
// LogStr := LogStr + Sql;
// end;
// try
// if Logger.Use then
// AddParamValues(LogStr, Params);
// Result := FConnWrapper.Trans.MakeDataSet(Sql, Params, Cached);
// if Logger.Use then
// begin
// OpenTicks := GetRange(GetTickCount, StartTicks);
// LogStr := LogStr + #13#10 + Format('[OpenTime = %d ms]', [OpenTicks]);
// end;
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
// except
// Result.Free;
// raise;
// end;
//end;
//procedure TTransaction.ExecuteSql(const Sql: UnicodeString; Params: TParams);
//var
// LogStr: UnicodeString;
// qry: IQueryWrapper;
//begin
// qry := FConnWrapper.Trans.MakeQueryWrapper;
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
// LogStr := LogStr + Sql;
// end;
// try
// if Logger.Use then
// AddParamValues(LogStr, Params);
// qry.Execute(Sql, Params, True);
// if Logger.Use then
// AddToStr(LogStr, 'Ok.');
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
//
//function TTransaction.ExecuteSqlAndGetRowsAffected(const Sql: UnicodeString;
// Params: TParams): Int64;
//var
// qry: IQueryWrapper;
// LogStr: UnicodeString;
//begin
// if not Assigned(Params) then
// begin
// Result := ExecuteSqlAndGetRowsAffected(Sql);
// Exit;
// end;
// Result := 0;
// qry := FConnWrapper.Trans.MakeQueryWrapper;
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
// LogStr := LogStr + Sql;
// end;
// try
// if Logger.Use then
// AddParamValues(LogStr, Params);
// Result := qry.ExecuteAndGetRowsAffected(Sql, Params, True);
// if Logger.Use then
// AddToStr(LogStr, 'Ok.');
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
procedure TTransaction.ExecInsertWithReturn(const Sql: UnicodeString; const SqlParams: TSqlParamIntfArray; out ReturnTypes: TSqlDataTypeArray; out ReturnFields: TStringDynArray; out ReturnValues: TNSVariantDynArray);
var
qry: IQueryWrapper;
LogStr: UnicodeString;
// NewSql: UnicodeString;
// FirebirdQuery: IFirebirdQueryWrapper;
// ReturnTypes: TSqlDataTypeArray;
// ReturnFields: TStringDynArray;
I: Integer;
begin
qry := FConnWrapper.Trans.MakeQueryWrapper;
// NewSql := CreateReturningSql(Sql, ReturnFields);
// if Assigned(ReturnFields) then
// begin
// NewSql := Sql + ' RETURNING';
// for I := 0 to High(ReturnFields) do
// NewSql := NewSql + ' "' + ReturnFields[I] + '",';
// SetLength(NewSql, Length(NewSql) - 1);
// end;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [TransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
// if Assigned(ReturnFields) then
// begin
qry.ExecInsertWithReturn(Sql, SqlParams, ReturnTypes, ReturnFields, ReturnValues, True);
// if Length(ReturnValues) <> Length(ReturnFields) then
// Assert(False);
if Logger.Use then
begin
for I := 0 to High(ReturnFields) do
AddToStr(LogStr, Format('Return: %s(%s) = %s', [ReturnFields[I], GetEnumName(TypeInfo(TSqlDataType), Ord(ReturnTypes[I])), ConvertResVariantToStr(ReturnTypes[I], ReturnValues[I])]));
AddToStr(LogStr, 'Ok.');
end;
// end
// else
// begin
// qry.Execute(Sql, SqlParams, True);
// ReturnValues := nil;
// end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
{ TRecordSet }
procedure TRecordSet.TransferDataSetRecordToSqlFields;
var
I: Integer;
// SelectableArray: TSelectableIntfArray;
Selectable: ISelectable;
Calculated: ICalculated;
begin
// SelectableArray := FQuery.GetSelectables;
for I := 0 to High(FNonCalculatedSelectableArray) do
begin
Selectable := FNonCalculatedSelectableArray[I];
// if not Supports(Selectable, ICalculated) then
FRecordSet.TransferDataToSelectable(Selectable, I);
end;
if Assigned(FRecordMakeHelper) then
FRecordMakeHelper.MakeRecord(FAllSelectableArray);
for I := 0 to High(FCalculatedSelectableArray) do
begin
Calculated := FCalculatedSelectableArray[I];
Calculated.Calculate;
end;
end;
procedure TRecordSet.Close;
begin
FRecordSet.Close;
end;
constructor TRecordSet.Create(ATrans: ITransactionWrapper; AQuery: IBaseSelectQuery; ALogger: ISqlLogger; ARecordMakeHelper: IRecordMakeHelper; ACache: Boolean);
begin
inherited Create;
FTrans := ATrans;
FQuery := AQuery;
FLogger := ALogger;
FRecordMakeHelper := ARecordMakeHelper;
FCache := ACache;
Open;
end;
procedure TRecordSet.CreateRecordSet(Ds: IRecordSetWrapper);
var
Sql: UnicodeString;
LogStr: UnicodeString;
Params: TSqlParamIntfArray;
StartTicks: Cardinal;
OpenTicks: Cardinal;
begin
StartTicks := 0;
Ds.Close;
if Logger.Use then
StartTicks := GetTickCount;
Sql := NewSqlRenderer(FTrans.Engine).StrOfSelectQuery(FQuery);
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTrans.GetTransactionId]) + #13#10;
LogStr := LogStr + Sql;
end;
try
Params := FQuery.GetParams;
if Logger.Use then
AddParamValues(LogStr, Params);
Ds.Open(Sql, Params, Length(FNonCalculatedSelectableArray){FQuery.GetSelectables)});
if Logger.Use then
begin
OpenTicks := GetRange(GetTickCount, StartTicks);
LogStr := LogStr + #13#10 + Format('[OpenTime = %d ms]', [OpenTicks]);
end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
destructor TRecordSet.Destroy;
begin
FRecordSet := nil;
inherited;
end;
procedure TRecordSet.FetchAll;
var
LogStr: UnicodeString;
StartTicks: Cardinal;
FetchTicks: Cardinal;
C: Integer;
begin
StartTicks := 0;
FetchTicks := 0;
LogStr := Format('[TransId = %d]', [FTrans.GetTransactionId]) + #13#10;
// LogStr := LogStr + Sql;
if Logger.Use then
StartTicks := GetTickCount;
try
FRecordSet.FetchAll;
if Logger.Use then
FetchTicks := GetRange(GetTickCount, StartTicks);
except
on E: Exception do
begin
LogStr := LogStr + '[Fetch] ';
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
end;
try
if Logger.Use then
begin
C := GetRecordCount;
LogStr := LogStr + Format('[Fetch %d records, FetchTime = %d ms]', [C, FetchTicks]);
end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TRecordSet.FieldByName(const Name: UnicodeString): ISelectable;
var
I: Integer;
// SelectableArray: TSelectableIntfArray;
begin
// SelectableArray := FQuery.GetSelectables;
for I := 0 to High(FAllSelectableArray) do
begin
Result := FAllSelectableArray[I];
if NSqlSameTextUnicode(Result.Alias, Name) then
Exit;
end;
Result := nil;
end;
//function TRecordSet.GetDatasetAndUnlink: ISqlDataSet;
//begin
// Result := FRecordSet.GetDatasetAndUnlink;
//end;
function TRecordSet.GetEod: Boolean;
begin
Result := FRecordSet.Eod;
end;
function TRecordSet.GetRecordCount: Int64;
begin
Result := FRecordSet.RecordCount;
end;
function TRecordSet.InternalMakeRecordSetWrapper: IRecordSetWrapper;
begin
Result := FTrans.MakeRecordSetWrapper(FCache);
end;
procedure TRecordSet.Next;
begin
FRecordSet.Next;
TransferDataSetRecordToSqlFields;
end;
procedure TRecordSet.Open;
var
I: Integer;
CalculatedLastIdx: Integer;
NonCalculatedLastIdx: Integer;
Selectable: ISelectable;
Calculated: ICalculated;
begin
FRecordSet := InternalMakeRecordSetWrapper;
FAllSelectableArray := FQuery.GetSelectables;
SetLength(FCalculatedSelectableArray, Length(FAllSelectableArray));
SetLength(FNonCalculatedSelectableArray, Length(FAllSelectableArray));
CalculatedLastIdx := -1;
NonCalculatedLastIdx := -1;
for I := 0 to High(FAllSelectableArray) do
begin
Selectable := FAllSelectableArray[I];
if Supports(Selectable, ICalculated, Calculated) then
begin
Inc(CalculatedLastIdx);
FCalculatedSelectableArray[CalculatedLastIdx] := Calculated;
end
else
begin
Inc(NonCalculatedLastIdx);
FNonCalculatedSelectableArray[NonCalculatedLastIdx] := Selectable;
end;
end;
SetLength(FCalculatedSelectableArray, CalculatedLastIdx + 1);
SetLength(FNonCalculatedSelectableArray, NonCalculatedLastIdx + 1);
CreateRecordSet(FRecordSet);
for I := 0 to High(FNonCalculatedSelectableArray) do
FRecordSet.CreateBindingForSelectable(FNonCalculatedSelectableArray[I], I);
// FRecordSet.Open;
SetStingFieldsSizes;
TransferDataSetRecordToSqlFields; // must be for no garbage in Selectable fields data
end;
procedure TRecordSet.SetStingFieldsSizes;
var
I: Integer;
// SelectableArray: TSelectableIntfArray;
Selectable: ISelectable;
begin
// SelectableArray := FQuery.GetSelectables;
for I := 0 to High(FNonCalculatedSelectableArray) do
begin
Selectable := FNonCalculatedSelectableArray[I];
if Selectable.DataType = dtString then
begin
// if not Supports(Selectable, ICalculated) then
FRecordSet.SetStringSizeOfSelectableFromField(Selectable, I);
end;
if Selectable.DataType = dtBinaryString then
begin
// if not Supports(Selectable, ICalculated) then
FRecordSet.SetStringSizeOfSelectableFromField(Selectable, I);
end;
end;
end;
{ TPreparedExecutableStatement }
constructor TPreparedExecutableStatement.Create(ATransWrapper: ITransactionWrapper; ATransaction: TTransaction;
AQuery: IExecutableQuery; AStatementType: TStatementType; ALogger: ISqlLogger);
begin
inherited Create;
FTransWrapper := ATransWrapper;
FTransaction := ATransaction;
FQuery := AQuery;
FTransIntf := FTransaction;
FStatementType := AStatementType;
FLogger := ALogger;
Prepare;
end;
function TPreparedExecutableStatement.Execute: IExecQueryResult;
begin
case FStatementType of
stInsert: Result := ExecuteInsert;
stUpdate: Result := ExecuteUpdate;
stDelete: Result := ExecuteDelete;
else
Result := nil;
Assert(False);
end;
end;
function TPreparedExecutableStatement.ExecuteDelete: IDeleteQueryResult;
var
LogStr: UnicodeString;
RowsAffected: Int64;
ReturnValues: TNSVariantDynArray;
begin
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Execute prepared'#13#10 + FSql;
end;
try
if Logger.Use then
AddParamValues(LogStr, FParams);
// FQry.ApplyParams;
RowsAffected := FQry.ExecuteAndGetRowsAffected(ReturnValues);
Result := TDeleteQueryResult.Create(RowsAffected);
if Logger.Use then
AddToStr(LogStr, 'Rows Affected: ' + IntToStr(RowsAffected));
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TPreparedExecutableStatement.ExecuteInsert: IInsertQueryResult;
var
LogStr: UnicodeString;
RowsAffected: Int64;
ReturnValues: TNSVariantDynArray;
I: Integer;
begin
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
if Assigned(FReturnElements) then
LogStr := LogStr + 'Execute prepared with return'#13#10 + FSql
else
LogStr := LogStr + 'Execute prepared'#13#10 + FSql;
end;
try
if Logger.Use then
AddParamValues(LogStr, FParams);
RowsAffected := FQry.ExecuteAndGetRowsAffected(ReturnValues);
if Assigned(FReturnFields) then
begin
if Length(ReturnValues) <> Length(FReturnFields) then
Assert(False);
if Logger.Use then
begin
for I := 0 to High(FReturnFields) do
AddToStr(LogStr, Format('Return: %s(%s) = %s', [FReturnFields[I], GetEnumName(TypeInfo(TSqlDataType), Ord(FReturnTypes[I])), ConvertResVariantToStr(FReturnTypes[I], ReturnValues[I])]));
AddToStr(LogStr, 'Ok.');
end;
for I := 0 to High(FReturnElements) do
begin
TransferReturnFieldValue(ReturnValues[I], FReturnTypes[I], FReturnElements[I]);
end;
end;
Result := TInsertQueryResult.Create(RowsAffected);
if Logger.Use then
AddToStr(LogStr, 'Rows Affected: ' + IntToStr(RowsAffected));
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TPreparedExecutableStatement.ExecuteUpdate: IUpdateQueryResult;
var
LogStr: UnicodeString;
RowsAffected: Int64;
ReturnValues: TNSVariantDynArray;
begin
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Execute prepared'#13#10 + FSql;
end;
try
if Logger.Use then
AddParamValues(LogStr, FParams);
RowsAffected := FQry.ExecuteAndGetRowsAffected(ReturnValues);
Result := TUpdateQueryResult.Create(RowsAffected);
if Logger.Use then
AddToStr(LogStr, 'Rows Affected: ' + IntToStr(RowsAffected));
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
//procedure TPreparedExecutableStatement.ExecWithReturn(
// out ReturnValues: TNSVariantDynArray);
//var
// LogStr: UnicodeString;
//begin
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
// LogStr := LogStr + 'Execute prepared insert with return'#13#10 + FSql;
// end;
// try
// if Logger.Use then
// AddParamValues(LogStr, FParams);
// FQry.ExecInsertWithReturn(ReturnValues);
//// RowsAffected := FQry.ExecuteAndGetRowsAffected;
//// Result := TInsertQueryResult.Create(1);
//// if Logger.Use then
//// AddToStr(LogStr, 'Rows Affected: ' + IntToStr(RowsAffected));
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
procedure TPreparedExecutableStatement.Prepare;
var
LogStr: UnicodeString;
// HasReturns: Boolean;
// ReturnsElements: TSelectableIntfArray;
InsertQuery: IBaseInsertQuery;
UpdateQuery: IBaseUpdateQuery;
DeleteQuery: IBaseDeleteQuery;
begin
FReturnElements := nil;
FQry := FTransWrapper.MakeQueryWrapperForPreparedStatement;
// FQry := FTransWrapper.MakeQueryWrapperForPreparedInsertWithReturnStatement;
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
// LogStr := LogStr + 'Prepare insert with return'#13#10 + FSql;
// end;
// try
// FQry.Prepare(FSql, FParams, FReturnTypes, FReturnFields);
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr + #13#10'Prepared');
case FStatementType of
stInsert:
begin
InsertQuery := FQuery as IBaseInsertQuery;
FReturnElements := InsertQuery.GetReturnsElements;
FSql := NewSqlRenderer(FTransIntf.Engine).StrOfInsertQuery(InsertQuery);
end;
stUpdate:
begin
UpdateQuery := FQuery as IBaseUpdateQuery;
FReturnElements := UpdateQuery.GetReturnsElements;
FSql := NewSqlRenderer(FTransIntf.Engine).StrOfUpdateQuery(FQuery as IBaseUpdateQuery);
end;
stDelete:
begin
DeleteQuery := FQuery as IBaseDeleteQuery;
FReturnElements := DeleteQuery.GetReturnsElements;
FSql := NewSqlRenderer(FTransIntf.Engine).StrOfDeleteQuery(FQuery as IBaseDeleteQuery);
end;
else
FSql := '';
Assert(False);
end;
FSql := FSql;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Prepare'#13#10 + FSql;
end;
FParams := FQuery.GetParams;
try
// if not Assigned(ReturnsElements) then
FQry.Prepare(FSql, FParams, FReturnTypes, FReturnFields);
if Length(FReturnElements) <> Length(FReturnTypes) then
Assert(False);
if Length(FReturnElements) <> Length(FReturnFields) then
Assert(False);
// else
// begin
// FQry.Prepare(FSql, FParams);
// end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr + #13#10'Prepared');
end;
{ TPreparedSql }
constructor TPreparedSql.Create(ATransWrapper: ITransactionWrapper;
ATransaction: TTransaction; const ASql: UnicodeString;
const AParams: TSqlParamIntfArray; ALogger: ISqlLogger);
begin
inherited Create;
FTransWrapper := ATransWrapper;
FTransaction := ATransaction;
FTransIntf := FTransaction;
FSql := ASql;
FParams := APArams;
FLogger := ALogger;
Prepare;
end;
procedure TPreparedSql.Execute;
var
LogStr: UnicodeString;
ReturnValues: TNSVariantDynArray;
begin
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Execute prepared'#13#10 + FSql;
end;
try
if Logger.Use then
AddParamValues(LogStr, FParams);
FQry.Execute(ReturnValues);
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
function TPreparedSql.ExecuteAndGetRowsAffected: Int64;
var
LogStr: UnicodeString;
RowsAffected: Int64;
ReturnValues: TNSVariantDynArray;
begin
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Execute prepared'#13#10 + FSql;
end;
Result := 0;
try
if Logger.Use then
AddParamValues(LogStr, FParams);
RowsAffected := FQry.ExecuteAndGetRowsAffected(ReturnValues);
Result := RowsAffected;
if Logger.Use then
AddToStr(LogStr, 'Rows Affected: ' + IntToStr(RowsAffected));
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
procedure TPreparedSql.Prepare;
var
// Sql: UnicodeString;
LogStr: UnicodeString;
begin
FQry := FTransWrapper.MakeQueryWrapperForPreparedStatement;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Prepare'#13#10 + FSql;
end;
try
FQry.Prepare(FSql, FParams, FReturnTypes, FReturnFields);
Assert(not Assigned(FReturnTypes));
Assert(not Assigned(FReturnFields));
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr + #13#10'Prepared');
end;
{ TPreparedSelect }
constructor TPreparedSelect.Create(ATransWrapper: ITransactionWrapper;
ATransaction: TTransaction; const ASql: UnicodeString;
const AParams: TSqlParamIntfArray; ALogger: ISqlLogger);
begin
inherited Create;
FTransWrapper := ATransWrapper;
FTransaction := ATransaction;
FTransIntf := FTransaction;
FSql := ASql;
FParams := APArams;
FLogger := ALogger;
Prepare;
end;
function TPreparedSelect.GetDataSet: ISqlDataSet;
begin
Result := FQry.DataSet;
end;
function TPreparedSelect.GetParamNames: TStringDynArray;
begin
Result := FQry.GetParamNames;
end;
procedure TPreparedSelect.Open;
var
LogStr: UnicodeString;
begin
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Open prepared'#13#10 + FSql;
end;
try
if Logger.Use then
AddParamValues(LogStr, FParams);
FQry.Open;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
//function TPreparedSelect.ExecuteAndGetRowsAffected: Int64;
//var
// LogStr: UnicodeString;
// RowsAffected: Int64;
//begin
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
// LogStr := LogStr + 'open prepared'#13#10 + FSql;
// end;
// Result := 0;
// try
// if Logger.Use then
// AddParamValues(LogStr, FParams);
// RowsAffected := FQry.ExecuteAndGetRowsAffected;
// Result := RowsAffected;
// if Logger.Use then
// AddToStr(LogStr, 'Rows Affected: ' + IntToStr(RowsAffected));
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
procedure TPreparedSelect.Prepare;
var
// Sql: UnicodeString;
LogStr: UnicodeString;
begin
FQry := FTransWrapper.MakeWrapperForPreparedSelectStatement;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Prepare'#13#10 + FSql;
end;
try
FQry.Prepare(FSql, FParams);
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr + #13#10'Prepared');
end;
//{ TPreparedInsertSql }
//
//constructor TPreparedInsertSql.Create(ATransWrapper: ITransactionWrapper;
// ATransaction: TTransaction; const ASql: UnicodeString;
// const AParams: TSqlParamIntfArray; ALogger: ISqlLogger);
//begin
// inherited Create;
// FTransWrapper := ATransWrapper;
// FTransaction := ATransaction;
// FTransIntf := FTransaction;
// FSql := ASql;
// FParams := APArams;
// FLogger := ALogger;
//
// Prepare;
//end;
//
//procedure TPreparedInsertSql.Execute;
//var
// LogStr: UnicodeString;
//begin
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
// LogStr := LogStr + 'Execute prepared insert sql'#13#10 + FSql;
// end;
// try
// if Logger.Use then
// AddParamValues(LogStr, FParams);
// FQry.Execute;
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
//
//function TPreparedInsertSql.ExecuteAndReturnId: Integer;
//var
// LogStr: UnicodeString;
//begin
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
// LogStr := LogStr + 'Execute prepared insert sql and return Id'#13#10 + FSql;
// end;
// try
// if Logger.Use then
// AddParamValues(LogStr, FParams);
// FQry.Execute;
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
//
//procedure TPreparedInsertSql.Prepare;
//var
//// Sql: UnicodeString;
// LogStr: UnicodeString;
//begin
// FQry := FTransWrapper.MakeQueryWrapperForPreparedStatement;
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
// LogStr := LogStr + 'Prepare'#13#10 + FSql;
// end;
// try
// FQry.Prepare(FSql, FParams);
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr + #13#10'Prepared');
//end;
{ TTransactionPool }
constructor TTransactionPool.Create(AMax: Integer; AOnNewTransNeededFunc: TOnNewTransNeededFunc);
begin
inherited Create;
FMax := AMax;
FOnNewTransNeededFunc := AOnNewTransNeededFunc;
FList := TInterfaceList.Create;
FInHandleList := TInterfaceList.Create;
FLock := NSqlCriticalSectionGuard;
end;
destructor TTransactionPool.Destroy;
begin
StopWorking;
inherited;
end;
function TTransactionPool.Get(Params: ITransactionParams; TransactionStartTrigger: ITransactionStartTrigger): ITransaction;
var
WasGetFromPool: Boolean;
BreakTryCycle: Boolean;
begin
Result := nil; // to force call of Result._Release
FLock.Enter;
try
BreakTryCycle := False;
while not BreakTryCycle do
begin
Assert(Assigned(FList));
Assert(Assigned(FInHandleList));
WasGetFromPool := False;
if FList.Count = 0 then
begin
if FInHandleList.Count >= FMax then
raise Exception.CreateFmt('number of concurrent connections exceeded [%d]', [FMax])
else
Result := FOnNewTransNeededFunc(FList.Count + FInHandleList.Count + 1)
end
else
begin
Result := FList[FList.Count - 1] as ITransaction;
FList.Delete(FList.Count - 1);
WasGetFromPool := True;
end;
FInHandleList.Add(Result);
try
Result.StartOnGetFromPool(Params, TransactionStartTrigger);
BreakTryCycle := True;
except
MarkAsBad(Result);
if not WasGetFromPool then
raise;
end;
end;
(Result as ITransactionInfo).InWork := True;
finally
FLock.Leave;
end;
end;
procedure TTransactionPool.MarkAsBad(Trans: ITransaction);
begin
FLock.Enter;
try
if Assigned(FInHandleList) then
FInHandleList.Remove(Trans);
finally
FLock.Leave;
end;
end;
procedure TTransactionPool.Return(Trans: ITransaction);
begin
FLock.Enter;
try
if Assigned(FInHandleList) then
FInHandleList.Remove(Trans);
if Assigned(FList) then
FList.Add(Trans);
finally
FLock.Leave;
end;
end;
procedure TTransactionPool.StopWorking;
var
I: Integer;
AdvDestroy: IAdvDestroy;
begin
if Assigned(FLock) then
FLock.Enter;
try
if Assigned(FList) then
for I := 0 to FList.Count - 1 do
begin
Assert(Supports(FList[I], IAdvDestroy, AdvDestroy));
AdvDestroy.StartDestroy;
end;
if Assigned(FInHandleList) then
for I := 0 to FInHandleList.Count - 1 do
begin
Assert(Supports(FInHandleList[I], IAdvDestroy, AdvDestroy));
AdvDestroy.StartDestroy;
end;
FList := nil;
FInHandleList := nil;
finally
if Assigned(FLock) then
FLock.Leave;
end;
end;
{ TPreparedInsertWithReturnSql }
constructor TPreparedInsertWithReturnSql.Create(ATransWrapper: ITransactionWrapper;
ATransaction: TTransaction; const ASql: UnicodeString;
const AParams: TSqlParamIntfArray; const AReturnFields: TStringDynArray; ALogger: ISqlLogger);
begin
inherited Create;
FTransWrapper := ATransWrapper;
FTransaction := ATransaction;
FTransIntf := FTransaction;
FSql := ASql;
FParams := APArams;
FLogger := ALogger;
FReturnFields := AReturnFields;
Prepare;
end;
function TPreparedInsertWithReturnSql.Execute: TNSVariantDynArray;
var
LogStr: UnicodeString;
I: Integer;
begin
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Execute prepared insert with return:'#13#10 + FSql;
end;
try
if Logger.Use then
AddParamValues(LogStr, FParams);
if Assigned(FReturnFields) then
begin
Result := FQry.Execute;
if Length(Result) <> Length(FReturnFields) then
Assert(False);
if Logger.Use then
begin
for I := 0 to High(FReturnFields) do
AddToStr(LogStr, Format('Return: %s(%s) = %s', [FReturnFields[I], GetEnumName(TypeInfo(TSqlDataType), Ord(FReturnTypes[I])), ConvertResVariantToStr(FReturnTypes[I], Result[I])]));
AddToStr(LogStr, 'Ok.');
end;
end
else
begin
Result := FQry.Execute;
// Result := nil;
end;
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr);
end;
//function TPreparedInsertWithReturnSql.ExecuteAndReturnId: Integer;
//var
// LogStr: UnicodeString;
// ReturnValues: TNSVariantDynArray;
//begin
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
// LogStr := LogStr + 'Execute prepared insert:'#13#10 + FSql;
// end;
// try
// if Logger.Use then
// AddParamValues(LogStr, FParams);
// FQry.ExecInsertWithReturn(ReturnValues);
// if Length(ReturnValues) <> 1 then
// raise Exception.CreateFmt('return values count = %d, instead of 1', [Length(ReturnValues)]);
// Result := ReturnValues[0];
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
//function TPreparedInsertWithReturnSql.ExecuteInsert: IInsertQueryResult;
//var
// LogStr: UnicodeString;
//begin
// if Logger.Use then
// begin
// LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
// LogStr := LogStr + 'Execute prepared insert:'#13#10 + FSql;
// end;
// try
// if Logger.Use then
// AddParamValues(LogStr, FParams);
// Result := TInsertQueryResult.Create(FQry.ExecuteAndGetRowsAffected);
// except
// on E: Exception do
// LogSqlErrorAndRaiseException(Logger, LogStr, E);
// end;
// if Logger.Use then
// Logger.Log(LogStr);
//end;
procedure TPreparedInsertWithReturnSql.Prepare;
var
LogStr: UnicodeString;
// I: Integer;
begin
FSql := CreateReturningSql(FSql, FReturnFields);
// if Assigned(FReturnFields) then
// begin
// FSql := FSql + ' RETURNING';
// for I := 0 to High(FReturnFields) do
// FSql := FSql + ' "' + FReturnFields[I] + '",';
// SetLength(FSql, Length(FSql) - 1);
// end;
FQry := FTransWrapper.MakeQueryWrapperForPreparedInsertWithReturnStatement;
if Logger.Use then
begin
LogStr := Format('[TransId = %d]', [FTransaction.TransactionId]) + #13#10;
LogStr := LogStr + 'Prepare insert with return'#13#10 + FSql;
end;
try
FQry.Prepare(FSql, FParams, FReturnTypes, FReturnFields);
except
on E: Exception do
LogSqlErrorAndRaiseException(Logger, LogStr, E);
end;
if Logger.Use then
Logger.Log(LogStr + #13#10'Prepared');
end;
{ TDataSetImpl }
function TDataSetImpl.GetDatasetAndUnlink: ISqlDataSet;
begin
Result := (FRecordSet as IDataSet).GetDatasetAndUnlink;
end;
function TDataSetImpl.InternalMakeRecordSetWrapper: IRecordSetWrapper;
begin
Result := FTrans.MakeDataSetWrapper(FCache);
end;
{ TTransactionParams }
constructor TTransactionParams.Create(const ATpb: AnsiString; const ADescription: UnicodeString; AIsReadOnly: Boolean);
begin
inherited Create;
FTpb := ATpb;
FDescription := ADescription;
FIsReadOnly := AIsReadOnly;
// FTpb := ATpbBuilder.Get;
// FDescription := ATpbBuilder.GetDescription;
// FIsReadOnly := ATpbBuilder.GetIsReadOnly;
end;
function TTransactionParams.GetDescription: UnicodeString;
begin
Result := FDescription;
end;
function TTransactionParams.GetIsReadOnly: Boolean;
begin
Result := FIsReadOnly;
end;
function TTransactionParams.GetTpb: AnsiString;
begin
Result := FTpb;
end;
{ TConnectionParams }
constructor TConnectionParams.Create(const ADpb: AnsiString;
const ADescription: UnicodeString; ADefaultSqlDialect: Integer; const AConnectionCharSet: UnicodeString);
begin
inherited Create;
FDpb := ADpb;
FDescription := ADescription;
FDefaultSqlDialect := ADefaultSqlDialect;
FConnectionCharSet := AConnectionCharSet;
end;
function TConnectionParams.GetConnectionCharSet: UnicodeString;
begin
Result := FConnectionCharSet;
end;
function TConnectionParams.GetDefaultSqlDialect: Integer;
begin
Result := FDefaultSqlDialect;
end;
function TConnectionParams.GetDescription: UnicodeString;
begin
Result := FDescription;
end;
function TConnectionParams.GetDpb: AnsiString;
begin
Result := FDpb;
end;
end.
|
unit uWAccReportParams;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uWAccDM, uCharControl, uIntControl, uFControl, uLabeledFControl,
uSpravControl, StdCtrls, Buttons, uCommonSp;
type
TfmWAccReportParams = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
Department: TqFSpravControl;
PCard: TqFSpravControl;
From_Year: TqFIntControl;
From_Month: TqFIntControl;
To_Year: TqFIntControl;
To_Month: TqFIntControl;
Label1: TLabel;
Label2: TLabel;
procedure DepartmentOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure PCardOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
DM: TdmWAccReport;
DesignReport: Boolean;
public
constructor Create(AOwner: TComponent; DM: TdmWAccReport; DesignReport: Boolean);
reintroduce;
end;
var
fmWAccReportParams: TfmWAccReportParams;
implementation
uses DateUtils, qFTools;
{$R *.dfm}
constructor TfmWAccReportParams.Create(AOwner: TComponent; DM: TdmWAccReport;
DesignReport: Boolean);
begin
inherited Create(AOwner);
Self.DM := DM;
Self.DesignReport := DesignReport;
DM.AsupParamsDS.Close;
DM.AsupParamsDS.Open;
try
qFAutoLoadFromRegistry(Self);
except
end;
if VarIsNull(Department.Value) then
begin
Department.Value := DM.AsupParamsDS['Local_Department'];
Department.DisplayText := DM.AsupParamsDS['Local_Department_Name'];
end;
if VarIsNull(From_Year.Value) then From_Year.Value := YearOf(Date);
if VarIsNull(From_Month.Value) then From_Month.Value := MonthOf(Date);
if VarIsNull(To_Year.Value) then To_Year.Value := YearOf(Date);
if VarIsNull(To_Month.Value) then To_Month.Value := MonthOf(Date);
end;
procedure TfmWAccReportParams.DepartmentOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(DM.Database.Handle);
FieldValues['Actual_Date'] := Date;
Post;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty then
begin
Value := sp.Output['Id_Department'];
DisplayText := sp.Output['Name_Full'];
end;
sp.Free;
end;
end;
procedure TfmWAccReportParams.PCardOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('asup\PCardsList');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(DM.Database.Handle);
FieldValues['ActualDate'] := Date;
FieldValues['SecondDate'] := 0;
FieldValues['ShowWorking'] := True;
FieldValues['CanRemoveFilter'] := True;
Post;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty then
begin
Value := sp.Output['ID_PCARD'];
DisplayText := sp.Output['FIO'];
end;
sp.Free;
end;
end;
procedure TfmWAccReportParams.OkButtonClick(Sender: TObject);
begin
with DM.ReportDS do
begin
Close;
ParamByName('Filter_Department').AsVariant := Department.Value;
ParamByName('Filter_PCard').AsVariant := PCard.Value;
ParamByName('From_Year').AsInteger := From_Year.Value;
ParamByName('From_Month').AsInteger := From_Month.Value;
ParamByName('To_Year').AsInteger := To_Year.Value;
ParamByName('To_Month').AsInteger := To_Month.Value;
Open;
with DM.TotalsDS do
begin
Close;
ParamByName('Filter_Department').AsVariant := Department.Value;
ParamByName('Filter_PCard').AsVariant := PCard.Value;
ParamByName('From_Year').AsInteger := From_Year.Value;
ParamByName('From_Month').AsInteger := From_Month.Value;
ParamByName('To_Year').AsInteger := To_Year.Value;
ParamByName('To_Month').AsInteger := To_Month.Value;
Open;
end;
DM.frxReport.LoadFromFile('Reports\Asup\AsupWAccReport.fr3');
if VarIsNull(PCard.Value) then
DM.frxReport.Variables['Show_Totals'] := 1
else DM.frxReport.Variables['Show_Totals'] := 0;
DM.frxReport.Variables['Filter_Department'] := Department.Value;
DM.frxReport.Variables['Filter_Department_Name'] := QuotedStr(Department.DisplayText);
DM.frxReport.Variables['Filter_PCard'] := PCard.Value;
DM.frxReport.Variables['Filter_PCard_Name'] := QuotedStr(PCard.DisplayText);
DM.frxReport.Variables['From_Year'] := From_Year.Value;
DM.frxReport.Variables['From_Month'] := From_Month.Value;
DM.frxReport.Variables['To_Year'] := From_Year.Value;
DM.frxReport.Variables['To_Month'] := From_Month.Value;
DM.frxReport.Variables['Id_PCard'] := PCard.Value;
DM.frxReport.Variables['Id_PCard'] := PCard.Value;
if DesignReport then
DM.frxReport.DesignReport
else
DM.frxReport.ShowReport;
end;
end;
procedure TfmWAccReportParams.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure TfmWAccReportParams.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
try
qFAutoSaveIntoRegistry(Self);
except
end;
end;
end.
|
unit uFrmSearchSOItem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDialogParent, siComp, siLangRT, StdCtrls, ExtCtrls, Buttons,
Mask, SuperComboADO, SuperEdit, SuperEditCurrency, SubListPanel, DB,
ADODB, uFrmBarcodeSearch;
type
TFrmSearchSOItem = class(TDialogParent)
Label4: TLabel;
cmbModel: TSuperComboADO;
btnPicture: TSpeedButton;
lbQty: TLabel;
EditQty: TEdit;
Label2: TLabel;
EditSalePrice: TSuperEditCurrency;
lbTotal: TLabel;
EditTotal: TSuperEdit;
SubQty: TSubListPanel;
spSalePrice: TADOStoredProc;
cdmAddItem: TADOCommand;
lbCategory: TLabel;
scCategoria: TSuperComboADO;
lbSearch: TLabel;
rbServices: TRadioButton;
rbProducts: TRadioButton;
cmdAddInvMov: TADOCommand;
btnSearchDesc: TBitBtn;
lbComissionado: TLabel;
scMRUser: TSuperComboADO;
procedure FormCreate(Sender: TObject);
procedure btnPictureClick(Sender: TObject);
procedure cmbModelSelectItem(Sender: TObject);
procedure AplicarClick(Sender: TObject);
procedure EditQtyKeyPress(Sender: TObject; var Key: Char);
procedure EditSalePriceEnter(Sender: TObject);
procedure EditSalePriceKeyPress(Sender: TObject; var Key: Char);
procedure EditSalePriceClick(Sender: TObject);
procedure EditSalePriceCurrChange(Sender: TObject);
procedure EditQtyChange(Sender: TObject);
procedure CancelarClick(Sender: TObject);
procedure scCategoriaSelectItem(Sender: TObject);
procedure rbServicesClick(Sender: TObject);
procedure rbProductsClick(Sender: TObject);
procedure btnSearchDescClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FResult : Boolean;
FIDSOItem, FIDCustomer, FIDUser : Integer;
FSalePrice, FCostPrice, FOriginalSalePrice,
FAvgCost, FCustomerDiscount : Currency;
fOnHand, fOnPreSale, fOnPrePurchase, fOnAvailable : Double;
FAddKitItems : Boolean;
fFrmBarcodeSearch : TFrmBarcodeSearch;
procedure RefreshQty;
procedure SelectModel;
procedure RefreshType;
function ValidadateFields : Boolean;
procedure ValidateWarning;
function InsertItem : Boolean;
public
function Start(AIDSOItem, AIDCustomer, AIDUser : Integer):Boolean;
end;
implementation
uses uDM, uDMGlobal, uFrmModelPicture, uNumericFunctions, uMsgConstant, uMsgBox,
uSystemConst, uCharFunctions, uPassword;
{$R *.dfm}
{ TFrmSearchSOItem }
function TFrmSearchSOItem.Start(AIDSOItem, AIDCustomer, AIDUser : Integer): Boolean;
begin
FIDSOItem := AIDSOItem;
FIDCustomer := AIDCustomer;
FIDUser := AIDUser;
scCategoria.LookUpValue := DM.fCashRegister.DefaulServOrderCat;
if scMRUser.LookUpValue = '' then
scMRUser.LookUpValue := IntToStr(AIDUser);
RefreshType;
FResult := False;
ShowModal;
Result := FResult;
end;
procedure TFrmSearchSOItem.FormCreate(Sender: TObject);
begin
inherited;
DM.imgSmall.GetBitmap(BTN18_CAMERA, btnPicture.Glyph);
DM.imgSmall.GetBitmap(BTN18_SEARCH, btnSearchDesc.Glyph);
fFrmBarcodeSearch := TFrmBarcodeSearch.Create(Self);
SubQty.CreateSubList;
end;
procedure TFrmSearchSOItem.btnPictureClick(Sender: TObject);
begin
inherited;
if cmbModel.LookUpValue <> '' then
with TFrmModelPicture.Create(Self) do
Start(cmbModel.LookUpValue);
end;
procedure TFrmSearchSOItem.RefreshQty;
begin
if cmbModel.LookUpValue <> '' then
begin
SubQty.Param := 'IDModel='+cmbModel.LookUpValue+';';
DM.fPOS.GetQty(StrToInt(cmbModel.LookUpValue), DM.fStore.IDStoreSale, fOnHand, fOnPreSale, fOnPrePurchase, fOnAvailable);
end;
end;
procedure TFrmSearchSOItem.cmbModelSelectItem(Sender: TObject);
begin
inherited;
SelectModel;
end;
procedure TFrmSearchSOItem.SelectModel;
var
cCostValue, cStoreCost, cStoreAvg, cStoreSell, cPromotionPrice: Currency;
begin
if cmbModel.LookUpValue = '' then
Exit;
RefreshQty;
FCustomerDiscount := 0;
with spSalePrice do
begin
Parameters.ParambyName('@ModelID').Value := StrToInt(cmbModel.LookUpValue);
Parameters.ParambyName('@IDStore').Value := DM.fStore.ID;
Parameters.ParambyName('@IDCustomer').Value := FIDCustomer;
Parameters.ParambyName('@Discount').Value := FCustomerDiscount;
Parameters.ParambyName('@SpecialPriceID').Value := 0;
ExecProc;
cStoreCost := Parameters.ParambyName('@StoreCostPrice').Value;
cStoreSell := Parameters.ParambyName('@StoreSalePrice').Value;
cStoreAvg := Parameters.ParambyName('@StoreAvgCost').Value;
FCustomerDiscount := Parameters.ParambyName('@Discount').Value;
FAddKitItems := Parameters.ParambyName('@AddKitItems').Value;
cPromotionPrice := Parameters.ParambyName('@PromotionPrice').Value;
if DM.fStore.Franchase then
FSalePrice := cStoreSell
else
begin
if (cStoreSell <> 0) then
FSalePrice := cStoreSell
else
FSalePrice := Parameters.ParambyName('@SalePrice').Value;
end;
FOriginalSalePrice := FSalePrice;
// Seta o valor do sale price
try
if (cPromotionPrice < (FSalePrice - FCustomerDiscount)) and (cPromotionPrice <> 0) then
EditSalePrice.Text := MyFloatToStr(cPromotionPrice)
else
EditSalePrice.Text := MyFloatToStr(FSalePrice - FCustomerDiscount);
finally
end;
if DM.fStore.Franchase then
begin
FCostPrice := cStoreCost;
if cStoreAvg = 0 then
FAvgCost := cStoreCost
else
FAvgCost := cStoreAvg;
end
else
begin
//utilizado para salvar o custo futuro
if DM.fSystem.SrvParam[PARAM_USE_ESTIMATED_COST] then
FCostPrice := Parameters.ParambyName('@ReplacementCost').Value
else
FCostPrice := Parameters.ParambyName('@CostPrice').Value;
FAvgCost := Parameters.ParambyName('@AvgCostPrice').Value;
end;
end;
end;
procedure TFrmSearchSOItem.RefreshType;
begin
EditQty.Text := '1';
cmbModel.LookUpValue := '';
EditSalePrice.Text := '0.00';
EditTotal.Text := '';
lbCategory.Visible := False;
scCategoria.Visible := False;
cmbModel.SpcWhereClause := '';
if rbServices.Checked then
begin
cmbModel.LookUpSource := DM.dsLookUpModelService;
EditQty.Visible := False;
EditTotal.Visible := False;
lbQty.Visible := False;
lbTotal.Visible := False;
end
else
begin
cmbModel.LookUpSource := DM.dsLookUpModelPack;
lbCategory.Visible := True;
scCategoria.Visible := True;
EditQty.Visible := True;
EditTotal.Visible := True;
lbQty.Visible := True;
lbTotal.Visible := True;
if scCategoria.LookUpValue <> '' then
cmbModel.SpcWhereClause := 'GroupID = ' + scCategoria.LookUpValue;
end;
end;
procedure TFrmSearchSOItem.AplicarClick(Sender: TObject);
begin
inherited;
if ValidadateFields then
begin
FResult := InsertItem;
ValidateWarning;
ModalResult := mrNone;
RefreshType;
if cmbModel.Visible then
cmbModel.SetFocus;
end
else
begin
ModalResult := mrNone;
FResult := False;
end;
end;
function TFrmSearchSOItem.InsertItem: Boolean;
var
iID : Integer;
begin
try
DM.ADODBConnect.BeginTrans;
iID := DM.GetNextID('Ser_SOItemProduct.IDSOItemProduct');
with cdmAddItem do
begin
Parameters.ParamByName('IDSOItemProduct').Value := iID;
Parameters.ParamByName('IDUser').Value := FIDUser;
Parameters.ParamByName('IDSOItem').Value := FIDSOItem;
Parameters.ParamByName('IDModel').Value := StrToInt(cmbModel.LookUpValue);
Parameters.ParamByName('IDStore').Value := DM.fStore.ID;
Parameters.ParamByName('Qty').Value := MyStrToDouble(EditQty.Text);
Parameters.ParamByName('CostPrice').Value := FCostPrice;
Parameters.ParamByName('SalePrice').Value := FSalePrice;
Parameters.ParamByName('MovDate').Value := Now;
Parameters.ParamByName('IDCustomer').Value := FIDCustomer;
Execute;
end;
with cmdAddInvMov do
begin
Parameters.ParamByName('IDInventoryMov').Value := DM.GetNextID(MR_INVENTORY_MOV_ID);
Parameters.ParamByName('InventMovTypeID').Value := 50;
Parameters.ParamByName('DocumentID').Value := iID;
Parameters.ParamByName('StoreID').Value := DM.fStore.ID;
Parameters.ParamByName('ModelID').Value := StrToInt(cmbModel.LookUpValue);
Parameters.ParamByName('MovDate').Value := Now;
Parameters.ParamByName('Qty').Value := MyStrToDouble(EditQty.Text);
Parameters.ParamByName('CostPrice').Value := FCostPrice;
Parameters.ParamByName('SalePrice').Value := FSalePrice;
Parameters.ParamByName('Discount').Value := 0;
Parameters.ParamByName('IDUser').Value := StrToIntDef(scMRUser.LookUpValue, FIDUser);
Parameters.ParamByName('IDDepartment').Value := 0;
Parameters.ParamByName('IDPessoa').Value := FIDCustomer;
Execute;
end;
DM.ADODBConnect.CommitTrans;
Result := True;
except
on E: Exception do
begin
DM.ADODBConnect.RollbackTrans;
Result := False;
ShowMessage(E.Message);
end;
end;
end;
function TFrmSearchSOItem.ValidadateFields: Boolean;
begin
Result := False;
if scMRUser.LookUpValue = '' then
begin
MsgBox(MSG_INF_SELECT_USER, vbOkOnly + vbCritical);
scMRUser.SetFocus;
Exit;
end;
if cmbModel.LookUpValue = '' then
begin
MsgBox(MSG_EXC_SELECT_A_MODEL, vbOkOnly + vbCritical);
cmbModel.SetFocus;
Exit;
end;
if MyStrToDouble(EditQty.Text) < 0 then
begin
MsgBox(MSG_INF_QTY_MUST_BIGGER_ZERO, vbOkOnly + vbCritical);
EditQty.SetFocus;
Exit;
end;
Result := True;
end;
procedure TFrmSearchSOItem.EditQtyKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
Key := ValidateDouble(Key);
end;
procedure TFrmSearchSOItem.EditSalePriceEnter(Sender: TObject);
begin
inherited;
EditSalePrice.SelectAll;
end;
procedure TFrmSearchSOItem.EditSalePriceKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := ValidatePositiveCurrency(Key);
end;
procedure TFrmSearchSOItem.EditSalePriceClick(Sender: TObject);
begin
inherited;
EditSalePrice.SelectAll;
end;
procedure TFrmSearchSOItem.EditSalePriceCurrChange(Sender: TObject);
var
Code : Integer;
begin
inherited;
try
FSalePrice := MyStrToMoney(EditSalePrice.Text);
EditTotal.Text := MyFloatToStr(TruncMoney(FSalePrice * MyStrToFloat(EditQty.Text), 2));
finally
end;
end;
procedure TFrmSearchSOItem.EditQtyChange(Sender: TObject);
var
IsKit, bEmpty: Boolean;
begin
inherited;
if Trim(EditQty.Text) = '-' then
Exit;
FSalePrice := DM.fPOS.GetKitPrice(StrToIntDef(cmbModel.LookUpValue, 0), MyStrToDouble(EditQty.Text), FOriginalSalePrice, bEmpty);
FOriginalSalePrice := FSalePrice;
if (not bEmpty) then
begin
try
EditSalePrice.Text := MyFloatToStr(FSalePrice - FCustomerDiscount);
finally
end;
end
else if FSalePrice <> MyStrToMoney(EditSalePrice.Text) then
FSalePrice := MyStrToMoney(EditSalePrice.Text);
try
EditTotal.Text := MyFloatToStr(TruncMoney(MyStrToFloat(EditQty.Text) * MyStrToMoney(EditSalePrice.Text), 2));
finally
end;
end;
procedure TFrmSearchSOItem.CancelarClick(Sender: TObject);
begin
inherited;
FResult := True;
Close;
end;
procedure TFrmSearchSOItem.scCategoriaSelectItem(Sender: TObject);
begin
inherited;
if scCategoria.LookUpValue <> '' then
cmbModel.SpcWhereClause := 'GroupID = ' + scCategoria.LookUpValue
else
cmbModel.SpcWhereClause := '';
end;
procedure TFrmSearchSOItem.rbServicesClick(Sender: TObject);
begin
inherited;
RefreshType;
end;
procedure TFrmSearchSOItem.rbProductsClick(Sender: TObject);
begin
inherited;
RefreshType;
end;
procedure TFrmSearchSOItem.ValidateWarning;
var
fQtyTest : Double;
begin
if not rbServices.Checked then
begin
fQtyTest := fOnAvailable;
if DM.fSystem.SrvParam[PARAM_INCLUDEPREPURCHASE] then
fQtyTest := fQtyTest + fOnPrePurchase;
if (fQtyTest - MyStrToDouble(EditQty.Text)) <= 0 then
MsgBox(MSG_CRT_INVENTORY_IS_ZERO, vbOKOnly + vbInformation);
end;
end;
procedure TFrmSearchSOItem.btnSearchDescClick(Sender: TObject);
var
R: integer;
begin
inherited;
with fFrmBarcodeSearch do
begin
R := Start;
if R <> -1 then
begin
cmbModel.LookUpValue := IntToStr(R);
cmbModelSelectItem(Self);
end;
end;
end;
procedure TFrmSearchSOItem.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(fFrmBarcodeSearch);
end;
end.
|
unit uBillDistributionFrm;
{按单配货}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBaseEditFrm, DB, DBClient,uListFormBaseFrm, Menus,
cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxPC, cxControls,
cxGraphics, cxDropDownEdit, cxCalendar, cxTextEdit, cxButtonEdit,
cxContainer, cxEdit, cxMaskEdit, cxLookupEdit, cxDBLookupEdit,
cxDBLookupComboBox, cxLabel, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxDBData, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid,DateUtils,
cxGroupBox, cxCheckBox,StringUtilClass, cxSpinEdit,
cxGridBandedTableView, cxGridDBBandedTableView, ADODB;
type
TBillDistributionFrm = class(TListFormBaseFrm)
mPage: TcxPageControl;
cxTabSheet1: TcxTabSheet;
cxTabSheet2: TcxTabSheet;
cxTabSheet3: TcxTabSheet;
Panel1: TPanel;
Panel2: TPanel;
btUP: TcxButton;
btDown: TcxButton;
btn_CreateBill: TcxButton;
Panel3: TPanel;
Panel4: TPanel;
cxGrid3: TcxGrid;
cxSleectBill: TcxGridDBTableView;
cxGridLevel4: TcxGridLevel;
dsSaleType: TDataSource;
dsInputWay: TDataSource;
gb_Querycondition: TcxGroupBox;
txt_Years: TcxButtonEdit;
txt_warehouse: TcxButtonEdit;
txt_InputWay: TcxLookupComboBox;
txt_Customer: TcxButtonEdit;
txt_Crateor: TcxButtonEdit;
txt_Brand: TcxButtonEdit;
txt_Attribute: TcxButtonEdit;
Label5: TLabel;
Label4: TLabel;
Label3: TLabel;
Label2: TLabel;
Label1: TLabel;
EndDate: TcxDateEdit;
cxLabel5: TcxLabel;
cxLabel4: TcxLabel;
cxLabel3: TcxLabel;
cxLabel2: TcxLabel;
cxLabel1: TcxLabel;
cxButton1: TcxButton;
beginDate: TcxDateEdit;
cxGroupBox2: TcxGroupBox;
Label6: TLabel;
txt_OutWarehouse: TcxButtonEdit;
Label7: TLabel;
txt_Des: TcxTextEdit;
Splitter1: TSplitter;
Panel5: TPanel;
cxButton3: TcxButton;
cxButton4: TcxButton;
cdsBilllist: TClientDataSet;
dsBilllist: TDataSource;
cdsBilllistBillFID: TStringField;
cdsBilllistBillNumber: TStringField;
cdsBilllistfbizdate: TStringField;
cdsBilllistFOrderType: TStringField;
cdsBilllistFPriceType: TStringField;
cdsBilllistFqty: TIntegerField;
cdsBilllistFTOTALSHIPPINGQTY: TIntegerField;
cdsBilllistFTOTALUNSHIPBASEQTY: TIntegerField;
cdsBilllistFTOTALISSUEBASEQTY: TIntegerField;
cdsBilllistFTOTALUNISSUEQTY: TIntegerField;
cdsBilllistfdescription: TStringField;
cxSleectBillBillFID: TcxGridDBColumn;
cxSleectBillBillNumber: TcxGridDBColumn;
cxSleectBillfbizdate: TcxGridDBColumn;
cxSleectBillFOrderType: TcxGridDBColumn;
cxSleectBillFPriceType: TcxGridDBColumn;
cxSleectBillFqty: TcxGridDBColumn;
cxSleectBillFTOTALSHIPPINGQTY: TcxGridDBColumn;
cxSleectBillFTOTALUNSHIPBASEQTY: TcxGridDBColumn;
cxSleectBillFTOTALISSUEBASEQTY: TcxGridDBColumn;
cxSleectBillFTOTALUNISSUEQTY: TcxGridDBColumn;
cxSleectBillfdescription: TcxGridDBColumn;
cdsBilllistSelected: TBooleanField;
cxSleectBillSelected: TcxGridDBColumn;
Label8: TLabel;
txtBillNumber: TcxTextEdit;
Panel6: TPanel;
Panel7: TPanel;
Panel8: TPanel;
Panel9: TPanel;
cxGrid1: TcxGrid;
cxMaterialList: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cxGrid2: TcxGrid;
cxEntry: TcxGridDBTableView;
cxGridLevel2: TcxGridLevel;
Splitter2: TSplitter;
Label9: TLabel;
txt_Material: TcxTextEdit;
Label10: TLabel;
txt_billMaterList: TcxTextEdit;
Label11: TLabel;
cb_DownDataType: TcxComboBox;
cdsMaterial: TClientDataSet;
dsMaterial: TDataSource;
cdsMaterialselected: TBooleanField;
Panel10: TPanel;
cxButton2: TcxButton;
cxButton5: TcxButton;
cdsMaterialMaterialFID: TStringField;
cdsMaterialMaterialNumber: TStringField;
cdsMaterialMaterialName: TStringField;
cdsMaterialFqty: TIntegerField;
cdsMaterialFTOTALSHIPPINGQTY: TIntegerField;
cdsMaterialFTOTALUNSHIPBASEQTY: TIntegerField;
cdsMaterialFTOTALISSUEBASEQTY: TIntegerField;
cdsMaterialFTOTALUNISSUEQTY: TIntegerField;
cdsMaterialfbaseqty: TIntegerField;
cdsMaterialCFAllocStockQty: TIntegerField;
cdsMaterialbrandName: TStringField;
cdsMaterialyearsName: TStringField;
cdsMaterialattbName: TStringField;
cxMaterialListselected: TcxGridDBColumn;
cxMaterialListMaterialFID: TcxGridDBColumn;
cxMaterialListMaterialNumber: TcxGridDBColumn;
cxMaterialListMaterialName: TcxGridDBColumn;
cxMaterialListFqty: TcxGridDBColumn;
cxMaterialListFTOTALSHIPPINGQTY: TcxGridDBColumn;
cxMaterialListFTOTALUNSHIPBASEQTY: TcxGridDBColumn;
cxMaterialListFTOTALISSUEBASEQTY: TcxGridDBColumn;
cxMaterialListFTOTALUNISSUEQTY: TcxGridDBColumn;
cxMaterialListfbaseqty: TcxGridDBColumn;
cxMaterialListCFAllocStockQty: TcxGridDBColumn;
cxMaterialListbrandName: TcxGridDBColumn;
cxMaterialListyearsName: TcxGridDBColumn;
cxMaterialListattbName: TcxGridDBColumn;
btn_Reset: TcxButton;
cdsEntry: TClientDataSet;
dsEntry: TDataSource;
cxButton6: TcxButton;
cdsPubEntry: TClientDataSet;
Panel11: TPanel;
Panel12: TPanel;
Splitter3: TSplitter;
pnlStock: TPanel;
Panel13: TPanel;
cxPageStock: TcxPageControl;
cxTabSendStock: TcxTabSheet;
cxgird2: TcxGrid;
cxgridInStock: TcxGridDBTableView;
cxgridInStockCFColorCode: TcxGridDBColumn;
cxgridInStockCFColorName: TcxGridDBColumn;
cxgridInStockCFCupName: TcxGridDBColumn;
cxgridInStockCFPackName: TcxGridDBColumn;
cxgridInStockcfpackNum: TcxGridDBColumn;
cxgridInStockfAmount_1: TcxGridDBColumn;
cxgridInStockfAmount_2: TcxGridDBColumn;
cxgridInStockfAmount_3: TcxGridDBColumn;
cxgridInStockfAmount_4: TcxGridDBColumn;
cxgridInStockfAmount_5: TcxGridDBColumn;
cxgridInStockfAmount_6: TcxGridDBColumn;
cxgridInStockfAmount_7: TcxGridDBColumn;
cxgridInStockfAmount_8: TcxGridDBColumn;
cxgridInStockfAmount_9: TcxGridDBColumn;
cxgridInStockfAmount_10: TcxGridDBColumn;
cxgridInStockfAmount_11: TcxGridDBColumn;
cxgridInStockfAmount_12: TcxGridDBColumn;
cxgridInStockfAmount_13: TcxGridDBColumn;
cxgridInStockfAmount_14: TcxGridDBColumn;
cxgridInStockfAmount_15: TcxGridDBColumn;
cxgridInStockfAmount_16: TcxGridDBColumn;
cxgridInStockfAmount_17: TcxGridDBColumn;
cxgridInStockfAmount_18: TcxGridDBColumn;
cxgridInStockfAmount_19: TcxGridDBColumn;
cxgridInStockfAmount_20: TcxGridDBColumn;
cxgridInStockfAmount_21: TcxGridDBColumn;
cxgridInStockfAmount_22: TcxGridDBColumn;
cxgridInStockfAmount_23: TcxGridDBColumn;
cxgridInStockfAmount_24: TcxGridDBColumn;
cxgridInStockfAmount_25: TcxGridDBColumn;
cxgridInStockfAmount_26: TcxGridDBColumn;
cxgridInStockfAmount_27: TcxGridDBColumn;
cxgridInStockfAmount_28: TcxGridDBColumn;
cxgridInStockfAmount_29: TcxGridDBColumn;
cxgridInStockfAmount_30: TcxGridDBColumn;
cxgridInStockfTotaLQty: TcxGridDBColumn;
cxgird2Level1: TcxGridLevel;
cxTabBalStock: TcxTabSheet;
cxGrid4: TcxGrid;
cxGridBalStock: TcxGridDBTableView;
cxGridBalStockCFColorCode: TcxGridDBColumn;
cxGridBalStockCFColorName: TcxGridDBColumn;
cxGridBalStockCFCupName: TcxGridDBColumn;
cxGridBalStockCFPackName: TcxGridDBColumn;
cxGridBalStockcfpackNum: TcxGridDBColumn;
cxGridBalStockfAmount_1: TcxGridDBColumn;
cxGridBalStockfAmount_2: TcxGridDBColumn;
cxGridBalStockfAmount_3: TcxGridDBColumn;
cxGridBalStockfAmount_4: TcxGridDBColumn;
cxGridBalStockfAmount_5: TcxGridDBColumn;
cxGridBalStockfAmount_6: TcxGridDBColumn;
cxGridBalStockfAmount_7: TcxGridDBColumn;
cxGridBalStockfAmount_8: TcxGridDBColumn;
cxGridBalStockfAmount_9: TcxGridDBColumn;
cxGridBalStockfAmount_10: TcxGridDBColumn;
cxGridBalStockfAmount_11: TcxGridDBColumn;
cxGridBalStockfAmount_12: TcxGridDBColumn;
cxGridBalStockfAmount_13: TcxGridDBColumn;
cxGridBalStockfAmount_14: TcxGridDBColumn;
cxGridBalStockfAmount_15: TcxGridDBColumn;
cxGridBalStockfAmount_16: TcxGridDBColumn;
cxGridBalStockfAmount_17: TcxGridDBColumn;
cxGridBalStockfAmount_18: TcxGridDBColumn;
cxGridBalStockfAmount_19: TcxGridDBColumn;
cxGridBalStockfAmount_20: TcxGridDBColumn;
cxGridBalStockfAmount_21: TcxGridDBColumn;
cxGridBalStockfAmount_22: TcxGridDBColumn;
cxGridBalStockfAmount_23: TcxGridDBColumn;
cxGridBalStockfAmount_24: TcxGridDBColumn;
cxGridBalStockfAmount_25: TcxGridDBColumn;
cxGridBalStockfAmount_26: TcxGridDBColumn;
cxGridBalStockfAmount_27: TcxGridDBColumn;
cxGridBalStockfAmount_28: TcxGridDBColumn;
cxGridBalStockfAmount_29: TcxGridDBColumn;
cxGridBalStockfAmount_30: TcxGridDBColumn;
cxGridBalStockfTotaLQty: TcxGridDBColumn;
cxGridLevel3: TcxGridLevel;
Panel14: TPanel;
cxpageReceive: TcxPageControl;
cxTabRecStock: TcxTabSheet;
cxGrid5: TcxGrid;
cxgridDestStock: TcxGridDBTableView;
cxgridDestStockCFColorCode: TcxGridDBColumn;
cxgridDestStockCFColorName: TcxGridDBColumn;
cxgridDestStockCFCupName: TcxGridDBColumn;
cxgridDestStockCFPackName: TcxGridDBColumn;
cxgridDestStockcfpackNum: TcxGridDBColumn;
cxgridDestStockfAmount_1: TcxGridDBColumn;
cxgridDestStockfAmount_2: TcxGridDBColumn;
cxgridDestStockfAmount_3: TcxGridDBColumn;
cxgridDestStockfAmount_4: TcxGridDBColumn;
cxgridDestStockfAmount_5: TcxGridDBColumn;
cxgridDestStockfAmount_6: TcxGridDBColumn;
cxgridDestStockfAmount_7: TcxGridDBColumn;
cxgridDestStockfAmount_8: TcxGridDBColumn;
cxgridDestStockfAmount_9: TcxGridDBColumn;
cxgridDestStockfAmount_10: TcxGridDBColumn;
cxgridDestStockfAmount_11: TcxGridDBColumn;
cxgridDestStockfAmount_12: TcxGridDBColumn;
cxgridDestStockfAmount_13: TcxGridDBColumn;
cxgridDestStockfAmount_14: TcxGridDBColumn;
cxgridDestStockfAmount_15: TcxGridDBColumn;
cxgridDestStockfAmount_16: TcxGridDBColumn;
cxgridDestStockfAmount_17: TcxGridDBColumn;
cxgridDestStockfAmount_18: TcxGridDBColumn;
cxgridDestStockfAmount_19: TcxGridDBColumn;
cxgridDestStockfAmount_20: TcxGridDBColumn;
cxgridDestStockfAmount_21: TcxGridDBColumn;
cxgridDestStockfAmount_22: TcxGridDBColumn;
cxgridDestStockfAmount_23: TcxGridDBColumn;
cxgridDestStockfAmount_24: TcxGridDBColumn;
cxgridDestStockfAmount_25: TcxGridDBColumn;
cxgridDestStockfAmount_26: TcxGridDBColumn;
cxgridDestStockfAmount_27: TcxGridDBColumn;
cxgridDestStockfAmount_28: TcxGridDBColumn;
cxgridDestStockfAmount_29: TcxGridDBColumn;
cxgridDestStockfAmount_30: TcxGridDBColumn;
cxgridDestStockfTotaLQty: TcxGridDBColumn;
cxGridLevel5: TcxGridLevel;
cxTabRecSale: TcxTabSheet;
cxGrid6: TcxGrid;
cxgridDestSale: TcxGridDBTableView;
cxgridDestSaleCFColorCode: TcxGridDBColumn;
cxgridDestSaleCFColorName: TcxGridDBColumn;
cxgridDestSaleCFCupName: TcxGridDBColumn;
cxgridDestSaleCFPackName: TcxGridDBColumn;
cxgridDestSalecfpackNum: TcxGridDBColumn;
cxgridDestSalefAmount_1: TcxGridDBColumn;
cxgridDestSalefAmount_2: TcxGridDBColumn;
cxgridDestSalefAmount_3: TcxGridDBColumn;
cxgridDestSalefAmount_4: TcxGridDBColumn;
cxgridDestSalefAmount_5: TcxGridDBColumn;
cxgridDestSalefAmount_6: TcxGridDBColumn;
cxgridDestSalefAmount_7: TcxGridDBColumn;
cxgridDestSalefAmount_8: TcxGridDBColumn;
cxgridDestSalefAmount_9: TcxGridDBColumn;
cxgridDestSalefAmount_10: TcxGridDBColumn;
cxgridDestSalefAmount_11: TcxGridDBColumn;
cxgridDestSalefAmount_12: TcxGridDBColumn;
cxgridDestSalefAmount_13: TcxGridDBColumn;
cxgridDestSalefAmount_14: TcxGridDBColumn;
cxgridDestSalefAmount_15: TcxGridDBColumn;
cxgridDestSalefAmount_16: TcxGridDBColumn;
cxgridDestSalefAmount_17: TcxGridDBColumn;
cxgridDestSalefAmount_18: TcxGridDBColumn;
cxgridDestSalefAmount_19: TcxGridDBColumn;
cxgridDestSalefAmount_20: TcxGridDBColumn;
cxgridDestSalefAmount_21: TcxGridDBColumn;
cxgridDestSalefAmount_22: TcxGridDBColumn;
cxgridDestSalefAmount_23: TcxGridDBColumn;
cxgridDestSalefAmount_24: TcxGridDBColumn;
cxgridDestSalefAmount_25: TcxGridDBColumn;
cxgridDestSalefAmount_26: TcxGridDBColumn;
cxgridDestSalefAmount_27: TcxGridDBColumn;
cxgridDestSalefAmount_28: TcxGridDBColumn;
cxgridDestSalefAmount_29: TcxGridDBColumn;
cxgridDestSalefAmount_30: TcxGridDBColumn;
cxgridDestSalefTotaLQty: TcxGridDBColumn;
cxGridLevel6: TcxGridLevel;
cxGrid7: TcxGrid;
Panel15: TPanel;
Label12: TLabel;
txt_Filter: TcxTextEdit;
cxButton7: TcxButton;
cxButton8: TcxButton;
cdsAllocation: TClientDataSet;
dsAllocation: TDataSource;
cdsAllocationBILLFID: TWideStringField;
cdsAllocationFNUMBER: TWideStringField;
cdsAllocationCUSTFID: TWideStringField;
cdsAllocationCUSTNUMBER: TWideStringField;
cdsAllocationCUSTNAME: TWideStringField;
cdsAllocationOUTWARHFID: TWideStringField;
cdsAllocationOUTWARHNUMBER: TWideStringField;
cdsAllocationOUTWARHNAME: TWideStringField;
cdsAllocationINWARHFID: TWideStringField;
cdsAllocationINWARHNUMBER: TWideStringField;
cdsAllocationINWARHNAME: TWideStringField;
cdsAllocationMATERNUMBER: TWideStringField;
cdsAllocationMATERNAME: TWideStringField;
cdsAllocationCOLORNUMBER: TWideStringField;
cdsAllocationCOLORNAME: TWideStringField;
cdsAllocationPACKNAME: TWideStringField;
cdsAllocationCUPNAME: TWideStringField;
cdsAllocationBRANDNAME: TWideStringField;
cdsAllocationYEARSNAME: TWideStringField;
cdsAllocationATTBNAME: TWideStringField;
cdsAllocationFMATERIALID: TWideStringField;
cdsAllocationCFCOLORID: TWideStringField;
cdsAllocationCFPACKID: TWideStringField;
cdsAllocationCFCUPID: TWideStringField;
cdsAllocationCFPACKNUM: TFloatField;
cdsAllocationFPRICE: TFloatField;
cdsAllocationCFDPPRICE: TFloatField;
cdsAllocationFDISCOUNT: TFloatField;
cdsAllocationFACTUALPRICE: TFloatField;
cdsAllocationCFNotPACKNUM: TFloatField;
cdsAllocationFAmount: TFloatField;
cdsAllocationFDpAmount: TFloatField;
cdsAllocationFNotAmount: TFloatField;
cdsAllocationFDpNotAmount: TFloatField;
cdsAllocationFQty_1: TIntegerField;
cdsAllocationFQty_2: TIntegerField;
cdsAllocationFQty_3: TIntegerField;
cdsAllocationFQty_4: TIntegerField;
cdsAllocationFQty_5: TIntegerField;
cdsAllocationFQty_6: TIntegerField;
cdsAllocationFQty_7: TIntegerField;
cdsAllocationFQty_9: TIntegerField;
cdsAllocationFQty_10: TIntegerField;
cdsAllocationFQty_8: TIntegerField;
cdsAllocationFQty_11: TIntegerField;
cdsAllocationFQty_12: TIntegerField;
cdsAllocationFQty_13: TIntegerField;
cdsAllocationFQty_14: TIntegerField;
cdsAllocationFQty_15: TIntegerField;
cdsAllocationFQty_16: TIntegerField;
cdsAllocationFQty_17: TIntegerField;
cdsAllocationFQty_18: TIntegerField;
cdsAllocationFQty_19: TIntegerField;
cdsAllocationFQty_20: TIntegerField;
cdsAllocationFQty_21: TIntegerField;
cdsAllocationFQty_22: TIntegerField;
cdsAllocationFQty_23: TIntegerField;
cdsAllocationFQty_24: TIntegerField;
cdsAllocationFQty_25: TIntegerField;
cdsAllocationFQty_26: TIntegerField;
cdsAllocationFQty_27: TIntegerField;
cdsAllocationFQty_28: TIntegerField;
cdsAllocationFQty_29: TIntegerField;
cdsAllocationFQty_30: TIntegerField;
cdsAllocationFNotQty_1: TIntegerField;
cdsAllocationFNotQty_2: TIntegerField;
cdsAllocationFNotQty_3: TIntegerField;
cdsAllocationFNotQty_4: TIntegerField;
cdsAllocationFNotQty_5: TIntegerField;
cdsAllocationFNotQty_6: TIntegerField;
cdsAllocationFNotQty_8: TIntegerField;
cdsAllocationFNotQty_82: TIntegerField;
cdsAllocationFNotQty_9: TIntegerField;
cdsAllocationFNotQty_10: TIntegerField;
cdsAllocationFNotQty_11: TIntegerField;
cdsAllocationFNotQty_12: TIntegerField;
cdsAllocationFNotQty_13: TIntegerField;
cdsAllocationFNotQty_14: TIntegerField;
cdsAllocationFNotQty_15: TIntegerField;
cdsAllocationFNotQty_16: TIntegerField;
cdsAllocationFNotQty_17: TIntegerField;
cdsAllocationFNotQty_18: TIntegerField;
cdsAllocationFNotQty_19: TIntegerField;
cdsAllocationFNotQty_20: TIntegerField;
cdsAllocationFNotQty_21: TIntegerField;
cdsAllocationFNotQty_22: TIntegerField;
cdsAllocationFNotQty_23: TIntegerField;
cdsAllocationFNotQty_24: TIntegerField;
cdsAllocationFNotQty_25: TIntegerField;
cdsAllocationFNotQty_26: TIntegerField;
cdsAllocationFNotQty_27: TIntegerField;
cdsAllocationFNotQty_28: TIntegerField;
cdsAllocationFNotQty_29: TIntegerField;
cdsAllocationFNotQty_30: TIntegerField;
cdsAllocationFTotalQty: TIntegerField;
cdsAllocationFNotTotalQty: TIntegerField;
cdsAllocationselected: TBooleanField;
cxAllocationselected: TcxGridDBColumn;
cxAllocationBILLFID: TcxGridDBColumn;
cxAllocationFNUMBER: TcxGridDBColumn;
cxAllocationCUSTFID: TcxGridDBColumn;
cxAllocationCUSTNUMBER: TcxGridDBColumn;
cxAllocationCUSTNAME: TcxGridDBColumn;
cxAllocationOUTWARHFID: TcxGridDBColumn;
cxAllocationOUTWARHNUMBER: TcxGridDBColumn;
cxAllocationOUTWARHNAME: TcxGridDBColumn;
cxAllocationINWARHFID: TcxGridDBColumn;
cxAllocationINWARHNUMBER: TcxGridDBColumn;
cxAllocationINWARHNAME: TcxGridDBColumn;
cxAllocationMATERNUMBER: TcxGridDBColumn;
cxAllocationMATERNAME: TcxGridDBColumn;
cxAllocationCOLORNUMBER: TcxGridDBColumn;
cxAllocationCOLORNAME: TcxGridDBColumn;
cxAllocationPACKNAME: TcxGridDBColumn;
cxAllocationCUPNAME: TcxGridDBColumn;
cxAllocationBRANDNAME: TcxGridDBColumn;
cxAllocationYEARSNAME: TcxGridDBColumn;
cxAllocationATTBNAME: TcxGridDBColumn;
cxAllocationFMATERIALID: TcxGridDBColumn;
cxAllocationCFCOLORID: TcxGridDBColumn;
cxAllocationCFPACKID: TcxGridDBColumn;
cxAllocationCFCUPID: TcxGridDBColumn;
cxAllocationCFPACKNUM: TcxGridDBColumn;
cxAllocationCFNotPACKNUM: TcxGridDBColumn;
cxAllocationCFDPPRICE: TcxGridDBColumn;
cxAllocationFPRICE: TcxGridDBColumn;
cxAllocationFDISCOUNT: TcxGridDBColumn;
cxAllocationFACTUALPRICE: TcxGridDBColumn;
cxAllocationFQty_1: TcxGridDBColumn;
cxAllocationFQty_2: TcxGridDBColumn;
cxAllocationFQty_3: TcxGridDBColumn;
cxAllocationFQty_4: TcxGridDBColumn;
cxAllocationFQty_5: TcxGridDBColumn;
cxAllocationFQty_6: TcxGridDBColumn;
cxAllocationFQty_7: TcxGridDBColumn;
cxAllocationFQty_8: TcxGridDBColumn;
cxAllocationFQty_9: TcxGridDBColumn;
cxAllocationFQty_10: TcxGridDBColumn;
cxAllocationFQty_11: TcxGridDBColumn;
cxAllocationFQty_12: TcxGridDBColumn;
cxAllocationFQty_13: TcxGridDBColumn;
cxAllocationFQty_14: TcxGridDBColumn;
cxAllocationFQty_15: TcxGridDBColumn;
cxAllocationFQty_16: TcxGridDBColumn;
cxAllocationFQty_17: TcxGridDBColumn;
cxAllocationFQty_18: TcxGridDBColumn;
cxAllocationFQty_19: TcxGridDBColumn;
cxAllocationFQty_20: TcxGridDBColumn;
cxAllocationFQty_21: TcxGridDBColumn;
cxAllocationFQty_22: TcxGridDBColumn;
cxAllocationFQty_23: TcxGridDBColumn;
cxAllocationFQty_24: TcxGridDBColumn;
cxAllocationFQty_25: TcxGridDBColumn;
cxAllocationFQty_26: TcxGridDBColumn;
cxAllocationFQty_27: TcxGridDBColumn;
cxAllocationFQty_28: TcxGridDBColumn;
cxAllocationFQty_29: TcxGridDBColumn;
cxAllocationFQty_30: TcxGridDBColumn;
cxAllocationFTotalQty: TcxGridDBColumn;
cxAllocationFAmount: TcxGridDBColumn;
cxAllocationFDpAmount: TcxGridDBColumn;
cxAllocationFNotQty_1: TcxGridDBColumn;
cxAllocationFNotQty_2: TcxGridDBColumn;
cxAllocationFNotQty_3: TcxGridDBColumn;
cxAllocationFNotQty_4: TcxGridDBColumn;
cxAllocationFNotQty_5: TcxGridDBColumn;
cxAllocationFNotQty_6: TcxGridDBColumn;
cxAllocationFNotQty_7: TcxGridDBColumn;
cxAllocationFNotQty_8: TcxGridDBColumn;
cxAllocationFNotQty_9: TcxGridDBColumn;
cxAllocationFNotQty_10: TcxGridDBColumn;
cxAllocationFNotQty_11: TcxGridDBColumn;
cxAllocationFNotQty_12: TcxGridDBColumn;
cxAllocationFNotQty_13: TcxGridDBColumn;
cxAllocationFNotQty_14: TcxGridDBColumn;
cxAllocationFNotQty_15: TcxGridDBColumn;
cxAllocationFNotQty_16: TcxGridDBColumn;
cxAllocationFNotQty_17: TcxGridDBColumn;
cxAllocationFNotQty_18: TcxGridDBColumn;
cxAllocationFNotQty_19: TcxGridDBColumn;
cxAllocationFNotQty_20: TcxGridDBColumn;
cxAllocationFNotQty_21: TcxGridDBColumn;
cxAllocationFNotQty_22: TcxGridDBColumn;
cxAllocationFNotQty_23: TcxGridDBColumn;
cxAllocationFNotQty_24: TcxGridDBColumn;
cxAllocationFNotQty_25: TcxGridDBColumn;
cxAllocationFNotQty_26: TcxGridDBColumn;
cxAllocationFNotQty_27: TcxGridDBColumn;
cxAllocationFNotQty_28: TcxGridDBColumn;
cxAllocationFNotQty_29: TcxGridDBColumn;
cxAllocationFNotQty_30: TcxGridDBColumn;
cxAllocationFNotTotalQty: TcxGridDBColumn;
cxAllocationFNotAmount: TcxGridDBColumn;
cxAllocationFDpNotAmount: TcxGridDBColumn;
cdsBillDetail: TClientDataSet;
cdsInStock: TClientDataSet;
cdsInStockCFCOLORID: TWideStringField;
cdsInStockCFPackID: TStringField;
cdsInStockCFCUPID: TWideStringField;
cdsInStockCFColorCode: TStringField;
cdsInStockCFColorName: TStringField;
cdsInStockCFCupName: TStringField;
cdsInStockCFPackName: TStringField;
cdsInStockcfpackNum: TIntegerField;
cdsInStockfAmount_1: TFloatField;
cdsInStockfAmount_2: TFloatField;
cdsInStockfAmount_3: TFloatField;
cdsInStockfAmount_4: TFloatField;
cdsInStockfAmount_5: TFloatField;
cdsInStockfAmount_6: TFloatField;
cdsInStockfAmount_7: TFloatField;
cdsInStockfAmount_8: TFloatField;
cdsInStockfAmount_9: TFloatField;
cdsInStockfAmount_10: TFloatField;
cdsInStockfAmount_11: TFloatField;
cdsInStockfAmount_12: TFloatField;
cdsInStockfAmount_13: TFloatField;
cdsInStockfAmount_14: TFloatField;
cdsInStockfAmount_15: TFloatField;
cdsInStockfAmount_16: TFloatField;
cdsInStockfAmount_17: TFloatField;
cdsInStockfAmount_18: TFloatField;
cdsInStockfAmount_19: TFloatField;
cdsInStockfAmount_20: TFloatField;
cdsInStockfAmount_21: TFloatField;
cdsInStockfAmount_22: TFloatField;
cdsInStockfAmount_23: TFloatField;
cdsInStockfAmount_24: TFloatField;
cdsInStockfAmount_25: TFloatField;
cdsInStockfAmount_26: TFloatField;
cdsInStockfAmount_27: TFloatField;
cdsInStockfAmount_28: TFloatField;
cdsInStockfAmount_29: TFloatField;
cdsInStockfAmount_30: TFloatField;
cdsInStockfTotaLQty: TFloatField;
dsInStock: TDataSource;
cdsBalStock: TClientDataSet;
cdsBalStockCFCOLORID: TWideStringField;
cdsBalStockCFCUPID: TWideStringField;
cdsBalStockCFPackID: TStringField;
cdsBalStockCFColorCode: TStringField;
cdsBalStockCFColorName: TStringField;
cdsBalStockCFCupName: TStringField;
cdsBalStockCFPackName: TStringField;
cdsBalStockcfpackNum: TIntegerField;
cdsBalStockfAmount_1: TFloatField;
cdsBalStockfAmount_2: TFloatField;
cdsBalStockfAmount_3: TFloatField;
cdsBalStockfAmount_4: TFloatField;
cdsBalStockfAmount_5: TFloatField;
cdsBalStockfAmount_6: TFloatField;
cdsBalStockfAmount_7: TFloatField;
cdsBalStockfAmount_8: TFloatField;
cdsBalStockfAmount_9: TFloatField;
cdsBalStockfAmount_10: TFloatField;
cdsBalStockfAmount_11: TFloatField;
cdsBalStockfAmount_12: TFloatField;
cdsBalStockfAmount_13: TFloatField;
cdsBalStockfAmount_14: TFloatField;
cdsBalStockfAmount_15: TFloatField;
cdsBalStockfAmount_16: TFloatField;
cdsBalStockfAmount_17: TFloatField;
cdsBalStockfAmount_18: TFloatField;
cdsBalStockfAmount_19: TFloatField;
cdsBalStockfAmount_20: TFloatField;
cdsBalStockfAmount_21: TFloatField;
cdsBalStockfAmount_22: TFloatField;
cdsBalStockfAmount_23: TFloatField;
cdsBalStockfAmount_24: TFloatField;
cdsBalStockfAmount_25: TFloatField;
cdsBalStockfAmount_26: TFloatField;
cdsBalStockfAmount_27: TFloatField;
cdsBalStockfAmount_28: TFloatField;
cdsBalStockfAmount_29: TFloatField;
cdsBalStockfAmount_30: TFloatField;
cdsBalStockfTotaLQty: TFloatField;
dsBalStock: TDataSource;
cdsRecStock: TClientDataSet;
cdsRecStockCFCOLORID: TWideStringField;
cdsRecStockCFCUPID: TWideStringField;
cdsRecStockCFPackID: TStringField;
cdsRecStockCFColorCode: TStringField;
cdsRecStockCFColorName: TStringField;
cdsRecStockCFCupName: TStringField;
cdsRecStockCFPackName: TStringField;
cdsRecStockcfpackNum: TIntegerField;
cdsRecStockfAmount_1: TFloatField;
cdsRecStockfAmount_2: TFloatField;
cdsRecStockfAmount_3: TFloatField;
cdsRecStockfAmount_4: TFloatField;
cdsRecStockfAmount_5: TFloatField;
cdsRecStockfAmount_6: TFloatField;
cdsRecStockfAmount_7: TFloatField;
cdsRecStockfAmount_8: TFloatField;
cdsRecStockfAmount_9: TFloatField;
cdsRecStockfAmount_10: TFloatField;
cdsRecStockfAmount_11: TFloatField;
cdsRecStockfAmount_12: TFloatField;
cdsRecStockfAmount_13: TFloatField;
cdsRecStockfAmount_14: TFloatField;
cdsRecStockfAmount_15: TFloatField;
cdsRecStockfAmount_16: TFloatField;
cdsRecStockfAmount_17: TFloatField;
cdsRecStockfAmount_18: TFloatField;
cdsRecStockfAmount_19: TFloatField;
cdsRecStockfAmount_20: TFloatField;
cdsRecStockfAmount_21: TFloatField;
cdsRecStockfAmount_22: TFloatField;
cdsRecStockfAmount_23: TFloatField;
cdsRecStockfAmount_24: TFloatField;
cdsRecStockfAmount_25: TFloatField;
cdsRecStockfAmount_26: TFloatField;
cdsRecStockfAmount_27: TFloatField;
cdsRecStockfAmount_28: TFloatField;
cdsRecStockfAmount_29: TFloatField;
cdsRecStockfAmount_30: TFloatField;
cdsRecStockfTotaLQty: TFloatField;
dsRecStock: TDataSource;
cdsSaleQty: TClientDataSet;
cdsSaleQtyCFCOLORID: TWideStringField;
cdsSaleQtyCFCUPID: TWideStringField;
cdsSaleQtyCFPackID: TStringField;
cdsSaleQtyCFColorCode: TStringField;
cdsSaleQtyCFColorName: TStringField;
cdsSaleQtyCFCupName: TStringField;
cdsSaleQtyCFPackName: TStringField;
cdsSaleQtycfpackNum: TIntegerField;
cdsSaleQtyfAmount_1: TFloatField;
cdsSaleQtyfAmount_2: TFloatField;
cdsSaleQtyfAmount_3: TFloatField;
cdsSaleQtyfAmount_4: TFloatField;
cdsSaleQtyfAmount_5: TFloatField;
cdsSaleQtyfAmount_6: TFloatField;
cdsSaleQtyfAmount_7: TFloatField;
cdsSaleQtyfAmount_8: TFloatField;
cdsSaleQtyfAmount_9: TFloatField;
cdsSaleQtyfAmount_10: TFloatField;
cdsSaleQtyfAmount_11: TFloatField;
cdsSaleQtyfAmount_12: TFloatField;
cdsSaleQtyfAmount_13: TFloatField;
cdsSaleQtyfAmount_14: TFloatField;
cdsSaleQtyfAmount_15: TFloatField;
cdsSaleQtyfAmount_16: TFloatField;
cdsSaleQtyfAmount_17: TFloatField;
cdsSaleQtyfAmount_18: TFloatField;
cdsSaleQtyfAmount_19: TFloatField;
cdsSaleQtyfAmount_20: TFloatField;
cdsSaleQtyfAmount_21: TFloatField;
cdsSaleQtyfAmount_22: TFloatField;
cdsSaleQtyfAmount_23: TFloatField;
cdsSaleQtyfAmount_24: TFloatField;
cdsSaleQtyfAmount_25: TFloatField;
cdsSaleQtyfAmount_26: TFloatField;
cdsSaleQtyfAmount_27: TFloatField;
cdsSaleQtyfAmount_28: TFloatField;
cdsSaleQtyfAmount_29: TFloatField;
cdsSaleQtyfAmount_30: TFloatField;
cdsSaleQtyfTotaLQty: TFloatField;
dsSaleQty: TDataSource;
Panel16: TPanel;
Panel17: TPanel;
lb_materInfo: TLabel;
cdsStockData: TClientDataSet;
cdsStockDatafwarehouseid: TStringField;
cdsStockDatafmaterialid: TStringField;
cdsStockDatacfcolorid: TStringField;
cdsStockDatacfsizesid: TStringField;
cdsStockDatacfpackid: TStringField;
cdsStockDatacfcupid: TStringField;
cdsStockDataFQty: TIntegerField;
cdsStockDataFUsableQty: TIntegerField;
matreialImg: TImage;
Label13: TLabel;
spe_SaleDays: TcxSpinEdit;
Label14: TLabel;
cdsImg: TClientDataSet;
cdsStock_tmp: TClientDataSet;
cdsSaleQty_tmp: TClientDataSet;
cdsRecStock_tmp: TClientDataSet;
cxGrid7Level1: TcxGridLevel;
cxAllocation_bands: TcxGridDBBandedTableView;
cxAllocation_bandsselected: TcxGridDBBandedColumn;
cxAllocation_bandsBILLFID: TcxGridDBBandedColumn;
cxAllocation_bandsFNUMBER: TcxGridDBBandedColumn;
cxAllocation_bandsCUSTFID: TcxGridDBBandedColumn;
cxAllocation_bandsCUSTNUMBER: TcxGridDBBandedColumn;
cxAllocation_bandsCUSTNAME: TcxGridDBBandedColumn;
cxAllocation_bandsOUTWARHFID: TcxGridDBBandedColumn;
cxAllocation_bandsOUTWARHNUMBER: TcxGridDBBandedColumn;
cxAllocation_bandsOUTWARHNAME: TcxGridDBBandedColumn;
cxAllocation_bandsINWARHFID: TcxGridDBBandedColumn;
cxAllocation_bandsINWARHNUMBER: TcxGridDBBandedColumn;
cxAllocation_bandsINWARHNAME: TcxGridDBBandedColumn;
cxAllocation_bandsMATERNUMBER: TcxGridDBBandedColumn;
cxAllocation_bandsMATERNAME: TcxGridDBBandedColumn;
cxAllocation_bandsCOLORNUMBER: TcxGridDBBandedColumn;
cxAllocation_bandsCOLORNAME: TcxGridDBBandedColumn;
cxAllocation_bandsPACKNAME: TcxGridDBBandedColumn;
cxAllocation_bandsCUPNAME: TcxGridDBBandedColumn;
cxAllocation_bandsBRANDNAME: TcxGridDBBandedColumn;
cxAllocation_bandsYEARSNAME: TcxGridDBBandedColumn;
cxAllocation_bandsATTBNAME: TcxGridDBBandedColumn;
cxAllocation_bandsFMATERIALID: TcxGridDBBandedColumn;
cxAllocation_bandsCFCOLORID: TcxGridDBBandedColumn;
cxAllocation_bandsCFPACKID: TcxGridDBBandedColumn;
cxAllocation_bandsCFCUPID: TcxGridDBBandedColumn;
cxAllocation_bandsCFPACKNUM: TcxGridDBBandedColumn;
cxAllocation_bandsCFNotPACKNUM: TcxGridDBBandedColumn;
cxAllocation_bandsCFDPPRICE: TcxGridDBBandedColumn;
cxAllocation_bandsFPRICE: TcxGridDBBandedColumn;
cxAllocation_bandsFDISCOUNT: TcxGridDBBandedColumn;
cxAllocation_bandsFACTUALPRICE: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_1: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_2: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_3: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_4: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_5: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_6: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_7: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_8: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_9: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_10: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_11: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_12: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_13: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_14: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_15: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_16: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_17: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_18: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_19: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_20: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_21: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_22: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_23: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_24: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_25: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_26: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_27: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_28: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_29: TcxGridDBBandedColumn;
cxAllocation_bandsFQty_30: TcxGridDBBandedColumn;
cxAllocation_bandsFTotalQty: TcxGridDBBandedColumn;
cxAllocation_bandsFAmount: TcxGridDBBandedColumn;
cxAllocation_bandsFDpAmount: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_1: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_2: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_3: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_4: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_5: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_6: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_7: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_8: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_9: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_10: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_11: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_12: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_13: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_14: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_15: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_16: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_17: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_18: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_19: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_20: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_21: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_22: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_23: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_24: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_25: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_26: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_27: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_28: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_29: TcxGridDBBandedColumn;
cxAllocation_bandsFNotQty_30: TcxGridDBBandedColumn;
cxAllocation_bandsFNotTotalQty: TcxGridDBBandedColumn;
cxAllocation_bandsFNotAmount: TcxGridDBBandedColumn;
cxAllocation_bandsFDpNotAmount: TcxGridDBBandedColumn;
btn_RefDownData: TcxButton;
QrySizeGroupEntry: TADOQuery;
cdsMaster: TClientDataSet;
cdsMasterFID: TWideStringField;
cdsMasterCFCustName: TStringField;
cdsMasterWideStringField2: TWideStringField;
cdsMasterWideStringField3: TWideStringField;
cdsMasterDateTimeField: TDateTimeField;
cdsMasterWideStringField4: TWideStringField;
cdsMasterDateTimeField2: TDateTimeField;
cdsMasterWideStringField5: TWideStringField;
cdsMasterDateTimeField3: TDateTimeField;
cdsMasterWideStringField6: TWideStringField;
cdsMasterWideStringField7: TWideStringField;
cdsMasterFloatField: TFloatField;
cdsMasterWideStringField8: TWideStringField;
cdsMasterWideStringField9: TWideStringField;
cdsMasterWideStringField10: TWideStringField;
cdsMasterDateTimeField4: TDateTimeField;
cdsMasterFloatField2: TFloatField;
cdsMasterWideStringField11: TWideStringField;
cdsMasterWideStringField12: TWideStringField;
cdsMasterWideStringField13: TWideStringField;
cdsMasterWideStringField14: TWideStringField;
cdsMasterWideStringField15: TWideStringField;
cdsMasterWideStringField16: TWideStringField;
cdsMasterFloatField3: TFloatField;
cdsMasterFloatField4: TFloatField;
cdsMasterDateTimeField5: TDateTimeField;
cdsMasterWideStringField17: TWideStringField;
cdsMasterWideStringField18: TWideStringField;
cdsMasterWideStringField19: TWideStringField;
cdsMasterFloatField5: TFloatField;
cdsMasterFloatField6: TFloatField;
cdsMasterFloatField7: TFloatField;
cdsMasterWideStringField20: TWideStringField;
cdsMasterWideStringField21: TWideStringField;
cdsMasterWideStringField22: TWideStringField;
cdsMasterWideStringField23: TWideStringField;
cdsMasterWideStringField24: TWideStringField;
cdsMasterWideStringField25: TWideStringField;
cdsMasterWideStringField26: TWideStringField;
cdsMasterWideStringField27: TWideStringField;
cdsMasterWideStringField28: TWideStringField;
cdsMasterWideStringField29: TWideStringField;
cdsMasterWideStringField30: TWideStringField;
cdsMasterWideStringField31: TWideStringField;
cdsMasterWideStringField32: TWideStringField;
cdsMasterFCreatorName: TStringField;
cdsMasterCFModifierName: TStringField;
cdsMasterFAuditorName: TStringField;
cdsMasterCFReceivWareName: TStringField;
cdsMasterCFSendWareName: TStringField;
cdsDetail: TClientDataSet;
cdsDetailFID: TWideStringField;
cdsDetailFSEQ: TFloatField;
cdsDetailFMATERIALID: TWideStringField;
cdsDetailFASSISTPROPERTYID: TWideStringField;
cdsDetailFUNITID: TWideStringField;
cdsDetailFSOURCEBILLNUMBER: TWideStringField;
cdsDetailFSOURCEBILLENTRYSEQ: TFloatField;
cdsDetailFASSCOEFFICIENT: TFloatField;
cdsDetailFBASESTATUS: TFloatField;
cdsDetailFASSOCIATEQTY: TFloatField;
cdsDetailFSOURCEBILLTYPEID: TWideStringField;
cdsDetailFBASEUNITID: TWideStringField;
cdsDetailFASSISTUNITID: TWideStringField;
cdsDetailFREMARK: TWideStringField;
cdsDetailFREASONCODEID: TWideStringField;
cdsDetailFPARENTID: TWideStringField;
cdsDetailFDELIVERYDATE: TDateTimeField;
cdsDetailFDELIVERYADDRESS: TWideStringField;
cdsDetailFTRANSLEADTIME: TFloatField;
cdsDetailFISPRESENT: TFloatField;
cdsDetailFCUSTPURNUMBER: TWideStringField;
cdsDetailFQTY: TFloatField;
cdsDetailFASSISTQTY: TFloatField;
cdsDetailFSHIPPEDQTY: TFloatField;
cdsDetailFUNSHIPPEDQTY: TFloatField;
cdsDetailFPRICE: TFloatField;
cdsDetailFORDERCUSTOMERID: TWideStringField;
cdsDetailFSALEPERSONID: TWideStringField;
cdsDetailFAMOUNT: TFloatField;
cdsDetailFDELIVERYTYPEID: TWideStringField;
cdsDetailFSALEGROUPID: TWideStringField;
cdsDetailFADMINORGUNITID: TWideStringField;
cdsDetailFSENDDATE: TDateTimeField;
cdsDetailFWAREHOUSEID: TWideStringField;
cdsDetailFSALEORDERID: TWideStringField;
cdsDetailFSALEORDERENTRYID: TWideStringField;
cdsDetailFSALEORDERNUMBER: TWideStringField;
cdsDetailFSALEORDERENTRYSEQ: TFloatField;
cdsDetailFBASEQTY: TFloatField;
cdsDetailFSHIPPEDBASEQTY: TFloatField;
cdsDetailFLOCALAMOUNT: TFloatField;
cdsDetailFREASON: TWideStringField;
cdsDetailFTOTALREVERSEDQTY: TFloatField;
cdsDetailFTOTALREVERSEDBASEQTY: TFloatField;
cdsDetailFSTOCKTRANSFERBILLID: TWideStringField;
cdsDetailFSTOCKTRANSFERBILLENTRYID: TWideStringField;
cdsDetailFSTOCKTRANSFERBILLNUMBER: TWideStringField;
cdsDetailFSTOCKTRANSFERBILLENTRYSEQ: TFloatField;
cdsDetailFLOCATIONID: TWideStringField;
cdsDetailFLOT: TWideStringField;
cdsDetailFPLANDELIVERYQTY: TFloatField;
cdsDetailFDELIVERYCUSTOMERID: TWideStringField;
cdsDetailFRECEIVECUSTOMERID: TWideStringField;
cdsDetailFPAYMENTCUSTOMERID: TWideStringField;
cdsDetailFSOURCEBILLID: TWideStringField;
cdsDetailFSOURCEBILLENTRYID: TWideStringField;
cdsDetailFNETORDERBILLNUMBER: TWideStringField;
cdsDetailFNETORDERBILLID: TWideStringField;
cdsDetailFNETORDERBILLENTRYID: TWideStringField;
cdsDetailFPROJECTID: TWideStringField;
cdsDetailFTRACKNUMBERID: TWideStringField;
cdsDetailCFCUPID: TWideStringField;
cdsDetailCFMUTILSOURCEBILL: TWideStringField;
cdsDetailCFPACKID: TWideStringField;
cdsDetailCFSIZESID: TWideStringField;
cdsDetailCFCOLORID: TWideStringField;
cdsDetailCFPACKNUM: TFloatField;
cdsDetailCFSIZEGROUPID: TWideStringField;
cdsDetailCFUNITPRICE: TFloatField;
cdsDetailCFDISCOUNT: TFloatField;
cdsDetailCFCANCELQTY: TFloatField;
cdsDetailCFSTOPNUM: TFloatField;
cdsDetailCFISPURIN: TFloatField;
cdsDetailCFPURINQTY: TFloatField;
cdsDetailFACTUALPRICE: TFloatField;
cdsDetailCFDPPRICE: TFloatField;
cdsBOTP: TClientDataSet;
qrySizegrouppackallot: TADOQuery;
cdsAllocationcfsizegroupid: TStringField;
dsShipType: TDataSource;
Label15: TLabel;
lcb_ShopType: TcxLookupComboBox;
txt_SaleOrg: TcxButtonEdit;
procedure FormCreate(Sender: TObject);
procedure txt_CustomerKeyPress(Sender: TObject; var Key: Char);
procedure txt_warehouseKeyPress(Sender: TObject; var Key: Char);
procedure txt_CrateorKeyPress(Sender: TObject; var Key: Char);
procedure txt_BrandKeyPress(Sender: TObject; var Key: Char);
procedure txt_YearsKeyPress(Sender: TObject; var Key: Char);
procedure txt_AttributeKeyPress(Sender: TObject; var Key: Char);
procedure txt_CustomerPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure txt_warehousePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure txt_CrateorPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure txt_BrandPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure txt_YearsPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure txt_AttributePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure txt_OutWarehouseKeyPress(Sender: TObject; var Key: Char);
procedure txt_OutWarehousePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxButton1Click(Sender: TObject);
procedure cxButton3Click(Sender: TObject);
procedure cxButton4Click(Sender: TObject);
procedure mPageChange(Sender: TObject);
procedure btDownClick(Sender: TObject);
procedure btn_ResetClick(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure cxButton5Click(Sender: TObject);
procedure txt_MaterialPropertiesChange(Sender: TObject);
procedure cdsMaterialFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
procedure cdsMaterialAfterPost(DataSet: TDataSet);
procedure cxButton6Click(Sender: TObject);
procedure btUPClick(Sender: TObject);
procedure txt_billMaterListPropertiesChange(Sender: TObject);
procedure cdsEntryFilterRecord(DataSet: TDataSet; var Accept: Boolean);
procedure FormResize(Sender: TObject);
procedure txt_FilterPropertiesChange(Sender: TObject);
procedure cdsAllocationFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
procedure matreialImgDblClick(Sender: TObject);
procedure cxAllocationFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure cdsAllocationCalcFields(DataSet: TDataSet);
procedure cdsInStockCalcFields(DataSet: TDataSet);
procedure cxButton7Click(Sender: TObject);
procedure cxButton8Click(Sender: TObject);
procedure btn_RefDownDataClick(Sender: TObject);
procedure btn_CreateBillClick(Sender: TObject);
procedure cdsMasterNewRecord(DataSet: TDataSet);
procedure cdsDetailNewRecord(DataSet: TDataSet);
procedure cxAllocation_bandsEditing(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; var AAllow: Boolean);
procedure cdsAllocationFQty_1Change(Sender: TField);
procedure cdsAllocationCFPACKNUMChange(Sender: TField);
procedure cdsAllocationCFPACKNUMValidate(Sender: TField);
procedure txt_InputWayPropertiesChange(Sender: TObject);
procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure txt_SaleOrgKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
IsSupeControl:Boolean ;//超数控制,加载时字段顺序不一致,不控制
FSaleType : string;
FSaleOrgFID,CustFID,WarehouseFID,CreateFID,SelectedMaterFID:string;
BrandFID,YearsFID,AttributeFID,CrateorFID,OutWarehouseFID:string;
CheckedBillFIDList,CheckedMaterFIDList:TStringList;
MaxSizeCount:Integer;
procedure GetMaxSizeCount;
procedure QueryBillList;
function QueryChk:Boolean;
procedure DisableCompnet(_Enabled:Boolean);
procedure GetMaterialList;
procedure NextStep(index:Integer);
procedure UpStep(index:Integer);
procedure QueryEntryList;
Procedure I3UserMessageResult(var msg:TMessage);override;
procedure setcxEntry;
procedure setGridSizeTitle; //设置网格尺码格式
procedure GetAllocationList;
procedure DetailToHorizontal; //竖排转横排
Procedure GetStockData;
function GetPHQty(cdsBill:TClientDataSet):Integer; //取默认配货数
Procedure GetDownInfo; //查询下方信息
procedure showImg;
procedure SetNotPackCompent;
procedure SetDownGridData(_cdsQuery:TClientDataSet;cdsDown,cdsBalDown:TClientDataSet;Ftype:Integer);
procedure HorizontalToDetail(cdsHorizontal,cdsDetail:TClientDataSet); //横排转竖排
procedure GetSizeGroupEntry;
function GetSizeFID(FMaterFID:string;ShowIndex:Integer):string;
procedure CreateBill(cdsSaleOrderList:TClientDataSet);
procedure GetqrySizegrouppackallot;//取配码
function GetPackAllotAmount(FSizegroupFID:string;ShowIndex:Integer):Integer; //取分配数
function GetSaleType(FSaleOrgID,FCustmerID:string):string;
function GetAllocationTable(SaleType:string):string;
end;
var
BillDistributionFrm: TBillDistributionFrm;
implementation
uses FrmCliDM,Pub_Fun,uMaterDataSelectHelper,uBillEditPostReq,Frm_BillEditBase,uDrpHelperClase,jpeg,Maximage;
{$R *.dfm}
function GetSqlForList(list: TstringList): string;
var i: Integer;
rest: string;
begin
result := '';
rest := '';
if List.Count = 0 then Exit;
for i := 0 to List.Count - 1 do
begin
rest := rest + QuotedStr(trim(List[i])) + ',';
end;
rest := Copy(rest, 1, Length(trim(rest)) - 1);
if rest <> '' then
result := rest;
end;
procedure TBillDistributionFrm.FormCreate(Sender: TObject);
begin
inherited;
IsSupeControl := True;
CheckedBillFIDList := TStringList.Create;
CheckedMaterFIDList := TStringList.Create;
GetMaxSizeCount;
end;
procedure TBillDistributionFrm.txt_CustomerKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.CustFID := '';
txt_Customer.Text := '';
end;
end;
procedure TBillDistributionFrm.txt_warehouseKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.WarehouseFID := '';
txt_warehouse.Text := '';
end;
end;
procedure TBillDistributionFrm.txt_CrateorKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.CrateorFID := '';
txt_Crateor.Text := '';
end;
end;
procedure TBillDistributionFrm.txt_BrandKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.BrandFID := '';
txt_Brand.Text := '';
end;
end;
procedure TBillDistributionFrm.txt_YearsKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.YearsFID := '';
txt_Years.Text := '';
end;
end;
procedure TBillDistributionFrm.txt_AttributeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.AttributeFID := '';
txt_Attribute.Text := '';
end;
end;
procedure TBillDistributionFrm.txt_CustomerPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
with Select_Customer('','','') do
begin
if not IsEmpty then
begin
Self.CustFID := fieldbyname('FID').AsString;
txt_Customer.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TBillDistributionFrm.txt_warehousePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
with Select_shop('','') do
begin
if not IsEmpty then
begin
Self.WarehouseFID := fieldbyname('FID').AsString;
txt_warehouse.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TBillDistributionFrm.txt_CrateorPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
with Select_BaseData('t_pm_user','制单人','','') do
begin
if not IsEmpty then
begin
Self.CreateFID := fieldbyname('FID').AsString;
txt_Crateor.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TBillDistributionFrm.txt_BrandPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
with Select_BaseData('ct_bas_brand','品牌','','') do
begin
if not IsEmpty then
begin
Self.BrandFID := fieldbyname('FID').AsString;
txt_Brand.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TBillDistributionFrm.txt_YearsPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
with Select_BaseData('ct_bas_years','年份','','') do
begin
if not IsEmpty then
begin
Self.YearsFID := fieldbyname('FID').AsString;
txt_Years.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TBillDistributionFrm.txt_AttributePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
with Select_BaseData('ct_bd_attribute','波段','','') do
begin
if not IsEmpty then
begin
Self.AttributeFID := fieldbyname('FID').AsString;
txt_Attribute.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TBillDistributionFrm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
//
end;
procedure TBillDistributionFrm.FormShow(Sender: TObject);
var i:Integer;
FieldName : string;
begin
inherited;
beginDate.Date := DateUtils.IncYear(Now,-1);
EndDate.Date := DateUtils.IncDay(now,1);
txt_InputWay.ItemIndex := 0;
cdsBilllist.CreateDataSet;
cdsMaterial.CreateDataSet;
cdsAllocation.CreateDataSet;
cdsStockData.CreateDataSet;
cdsBalStock.CreateDataSet;
cdsInStock.CreateDataSet;
cdsRecStock.CreateDataSet;
cdsSaleQty.CreateDataSet;
mPage.ActivePageIndex := 0;
btUP.Enabled := False;
btn_CreateBill.Enabled := False;
SelectedMaterFID := '';
try
cxAllocation_bands.BeginUpdate;
for i := 0 to cxAllocation_bands.ColumnCount -1 do
begin
FieldName := cxAllocation_bands.Columns[i].DataBinding.FieldName;
case cxAllocation_bands.DataController.DataSource.DataSet.FieldByName(FieldName).DataType of
ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftBCD, ftLargeint:
begin
with cxAllocation_bands.DataController.Summary.FooterSummaryItems.Add do
begin
ItemLink := cxAllocation_bands.GetColumnByFieldName(FieldName);
Position := spFooter;
Kind := skSum;
if cxAllocation_bands.DataController.DataSource.DataSet.FieldByName(FieldName).DataType in [ftSmallint, ftInteger] then
Format := '0';
end;
end;
end;
end;
finally
cxAllocation_bands.EndUpdate;
end;
end;
procedure TBillDistributionFrm.txt_OutWarehouseKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.OutWarehouseFID := '';
txt_OutWarehouse.Text := '';
end;
end;
procedure TBillDistributionFrm.txt_OutWarehousePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
with Select_Warehouse('','') do
begin
if not IsEmpty then
begin
Self.OutWarehouseFID := fieldbyname('FID').AsString;
txt_Outwarehouse.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TBillDistributionFrm.QueryBillList;
var _SQL,ErrMsg:string;
cds : TClientDataSet;
i:Integer;
allTable:string;
begin
if not QueryChk then Exit;
FSaleType := GetSaleType(Self.FSaleOrgFID,Self.CustFID);
if FSaleType = '' then
begin
Gio.AddShow('错误:没有取到销售类型...');
Exit;
end;
allTable := GetAllocationTable(FSaleType);
_SQL :=' select a.fid as BillFID,a.fnumber as BillNumber ,to_char(a.fbizdate,''yyyy-MM-dd'') as fbizdate,'
+' oty.fname_l2 as FOrderType, '
+' pty.fname_l2 as FPriceType, '
+' sum(nvl(b.fqty,0)) as Fqty, '
+' sum(nvl(pty.PostQty,0)) as FTOTALSHIPPINGQTY ,' // --已配数
+' sum(nvl(b.fqty,0))-sum(nvl(pty.PostQty,0)) as FTOTALUNSHIPBASEQTY ,'// --未配数
+' sum(nvl(b.FTOTALISSUEBASEQTY,0)) as FTOTALISSUEBASEQTY ,' // --已出库数
+' sum(nvl(b.FTOTALUNISSUEQTY,0)) as FTOTALUNISSUEQTY, ' // --未出库数
+' max(a.fdescription) as fdescription '
+' from t_Sd_Saleorder a '
+' left join t_Sd_Saleorderentry b on a.fid = b.fparentid '
+' left join (select sum(nvl(Fqty,0)) as PostQty, fsourcebillentryid '
+' from '+allTable+' group by fsourcebillentryid ) pty on b.fid = pty.fsourcebillentryid '
+' left join ct_bas_ordertype oty on a.cfordertypeid = oty.fid '
+' left join t_scm_pricetype pty on a.cfpricetypeid = pty.fid '
+' left join t_bd_material m on b.fmaterialid=m.fid where a.fbasestatus = 4 and b.FTOTALUNSHIPBASEQTY>0'
+' and a.fsaleorgunitid = '+Quotedstr(self.FSaleOrgFID)
+' and a.cfinputway = '+Quotedstr(txt_InputWay.EditingValue)
+' and to_char(a.fbizdate,''yyyy-MM-dd'') >='+Quotedstr(formatdatetime('yyyy-MM-dd',beginDate.Date))
+' and to_char(a.fbizdate,''yyyy-MM-dd'') <='+Quotedstr(formatdatetime('yyyy-MM-dd',EndDate.Date))
;
if self.CustFID <> '' then
begin
_SQL := _SQL + ' and a.fordercustomerid = '+Quotedstr(CustFID);
end;
if Self.WarehouseFID <> '' then
begin
_SQL := _SQL + ' and a.cfinwarehouseid = '+Quotedstr(WarehouseFID);
end;
if Self.BrandFID <> '' then
begin
_SQL := _SQL + ' and m.cfbrandid = '+Quotedstr(BrandFID);
end;
if Self.YearsFID <> '' then
begin
_SQL := _SQL + ' and m.cfyearsid = '+Quotedstr(YearsFID);
end;
if Self.AttributeFID <> '' then
begin
_SQL := _SQL + ' and m.Cfattributeid = '+Quotedstr(AttributeFID);
end;
if Self.CreateFID <> '' then
begin
_SQL := _SQL + ' and a.fcreatorid = '+Quotedstr(CreateFID);
end;
if Trim(txtBillNumber.Text) <> '' then
begin
_SQL := _SQL + ' and a.fnumber = '+Quotedstr(Trim(txtBillNumber.Text));
end;
_SQL := _SQL + ' group by a.fid,a.fnumber,a.fbizdate,oty.fname_l2,pty.fname_l2 order by a.fbizdate ';
try
cdsBilllist.DisableControls;
cdsBilllist.EmptyDataSet;
cds := TClientDataSet.Create(nil);
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
ShowMsg(Self.Handle, '查询订单出错:'+ErrMsg+','+_SQL,[]);
Gio.AddShow('查询订单出错:'+ErrMsg+','+_SQL);
Abort;
end;
if not cds.IsEmpty then
begin
cds.First;
while not cds.Eof do
begin
cdsBilllist.Append;
cdsBilllist.FieldByName('selected').AsBoolean := True;
for i := 0 to cds.FieldCount - 1 do
begin
cdsBilllist.FieldByName(cds.Fields[i].FieldName).Value := cds.Fields[i].Value;
end;
cdsBilllist.Post;
cds.Next;
end;
cdsBilllist.First;
DisableCompnet(False);
end;
finally
cds.Free;
cdsBilllist.EnableControls;
end;
end;
procedure TBillDistributionFrm.cxButton1Click(Sender: TObject);
begin
inherited;
QueryBillList;
end;
procedure TBillDistributionFrm.cxButton3Click(Sender: TObject);
begin
inherited;
try
cdsBilllist.DisableControls;
cdsBilllist.First;
while not cdsBilllist.Eof do
begin
cdsBilllist.Edit;
cdsBilllist.FieldByName('selected').AsBoolean := True;
cdsBilllist.Post;
cdsBilllist.Next;
end;
finally
cdsBilllist.EnableControls;
end;
end;
procedure TBillDistributionFrm.cxButton4Click(Sender: TObject);
begin
inherited;
try
cdsBilllist.DisableControls;
cdsBilllist.First;
while not cdsBilllist.Eof do
begin
cdsBilllist.Edit;
cdsBilllist.FieldByName('selected').AsBoolean := not cdsBilllist.FieldByName('selected').AsBoolean;
cdsBilllist.Post;
cdsBilllist.Next;
end;
finally
cdsBilllist.EnableControls;
end;
end;
procedure TBillDistributionFrm.mPageChange(Sender: TObject);
begin
inherited;
if mPage.ActivePageIndex = 0 then
begin
btUP.Enabled := False;
btDown.Enabled := True;
btn_CreateBill.Enabled := False;
end
else
if mPage.ActivePageIndex = 1 then
begin
btUP.Enabled := True;
btDown.Enabled := True;
btn_CreateBill.Enabled := False;
end
else
if mPage.ActivePageIndex = 2 then
begin
btUP.Enabled := True;
btDown.Enabled := False;
btn_CreateBill.Enabled := True;
end;
Label11.Visible := mPage.ActivePageIndex = 1;
cb_DownDataType.Visible := mPage.ActivePageIndex = 1;
lb_materInfo.Visible := mPage.ActivePageIndex = 2;
end;
function TBillDistributionFrm.QueryChk: Boolean;
begin
Result := False;
if (Self.FSaleOrgFID = '') then
begin
txt_SaleOrg.SetFocus;
ShowMsg(Self.Handle,'销售组织不能为空!',[]);
Exit;
end;
if (Self.WarehouseFID = '') and (Self.CustFID = '') then
begin
if Self.WarehouseFID = '' then
txt_Customer.SetFocus
else
txt_Warehouse.SetFocus;
ShowMsg(Self.Handle,'订货客户或收货仓库不能全为空,必须输入一个条件!',[]);
Exit;
end;
if Self.OutWarehouseFID = '' then
begin
txt_OutWarehouse.SetFocus;
ShowMsg(Self.Handle,'配货仓库不能为空',[]);
Exit;
end;
if lcb_ShopType.Text = '' then
begin
lcb_ShopType.SetFocus;
ShowMsg(Self.Handle,'发货类型不能为空',[]);
Exit;
end;
if beginDate.Text = '' then
begin
beginDate.SetFocus;
ShowMsg(Self.Handle,'订单业务开始日期不能为空',[]);
Exit;
end;
if EndDate.Text = '' then
begin
EndDate.SetFocus;
ShowMsg(Self.Handle,'订单业务截止日期不能为空',[]);
Exit;
end;
if DateUtils.YearsBetween(beginDate.Date,EndDate.Date) > 2 then
begin
ShowMsg(Self.Handle,'查询日期跨度不能超过2年',[]);
Exit;
end;
Result := True;
end;
procedure TBillDistributionFrm.DisableCompnet(_Enabled: Boolean);
begin
txt_SaleOrg.Enabled := _Enabled;
txt_Customer.Enabled := _Enabled;
beginDate.Enabled := _Enabled;
EndDate.Enabled := _Enabled;
txt_InputWay.Enabled := _Enabled;
txt_warehouse.Enabled := _Enabled;
txtBillNumber.Enabled := _Enabled;
txt_Brand.Enabled := _Enabled;
txt_Years.Enabled := _Enabled;
txt_Attribute.Enabled := _Enabled;
txt_Crateor.Enabled := _Enabled;
txt_OutWarehouse.Enabled := _Enabled;
end;
procedure TBillDistributionFrm.GetMaterialList;
var _SQL,ErrMsg : string;
cds : TClientDataSet;
i:Integer;
allTable:string;
begin
allTable := GetAllocationTable(Self.FSaleType);
_SQL := 'select m.fid as MaterialFID,m.fnumber as MaterialNumber,m.fname_l2 as MaterialName, '
+' sum(nvl(b.fqty,0)) as Fqty, '
+' sum(nvl(pty.PostQty,0)) as FTOTALSHIPPINGQTY , ' //已配数
+' sum(nvl(b.fqty,0))-sum(nvl(pty.PostQty,0)) as FTOTALUNSHIPBASEQTY ,'//未配数
+' sum(nvl(b.FTOTALISSUEBASEQTY,0)) as FTOTALISSUEBASEQTY , ' //已出库数
+' sum(nvl(b.FTOTALUNISSUEQTY,0)) as FTOTALUNISSUEQTY, ' //未出库数
+' sum(inv.FQty) as fbaseqty , ' //在库数
+' sum(FUsableQty) as CFAllocStockQty, ' //可用库存
+' brand.Fname_L2 as brandName,'
+' years.fname_l2 as yearsName,'
+' attb.fname_l2 as attbName '
+' from t_Sd_Saleorder a '
+' left join t_Sd_Saleorderentry b on a.fid = b.fparentid'
+' left join (select sum(Fqty) as PostQty, fsourcebillentryid '
+' from '+allTable+' group by fsourcebillentryid ) pty on b.fid = pty.fsourcebillentryid '
+' left join t_bd_material m on b.fmaterialid = m.fid '
+' left join ct_bas_brand brand on brand.fid = m.cfbrandid'
+' left join ct_bas_years years on years.fid = m.cfyearsid '
+' left join ct_bd_attribute attb on attb.fid=m.cfattributeid '
+' left join '
+' (select fwarehouseid, fmaterialid,fassistpropertyid , '
+' sum(FQty) as FQty,sum(FUsableQty) as FUsableQty '
+' from ( '
+' select iv.fwarehouseid, iv.fmaterialid, '
+' iv.fassistpropertyid,'
+' iv.fcurstoreqty as FQty,iv.fcurstoreqty-iv.cfallocstockqty as FUsableQty '
+' from t_Im_Inventory iv '
+' where 1=1 and iv.fwarehouseid = '+quotedstr(self.OutWarehouseFID)
+' union all '
+' select rtpos.cfstorageid as fwarehouseid , '
+' rtEntry.Cfmaterialid as fmaterialid ,pass.fid as fassistpropertyid,-rtEntry.Cfamount as Fqty,0 as FUsableQty '
+' from ct_bil_retailpos rtpos '
+' left join ct_bil_retailposEntry rtEntry '
+' on rtpos.fid = rtEntry.Fparentid '
+' left join t_bd_asstattrvalue pass on rtEntry.cfassistnum=pass.fnumber'
+' where rtpos.cfissaleout=0 and rtpos.cfstate = 2 and rtpos.cfstorageid = '+quotedstr(self.OutWarehouseFID)
+' ) Inventory '
+' group by fwarehouseid, fmaterialid,fassistpropertyid) '
+' inv on b.fmaterialid = inv.fmaterialid and b.fassistpropertyid=inv.fassistpropertyid '
+' and inv.fwarehouseid = '+quotedstr(self.OutWarehouseFID)
+' where b.FTOTALUNSHIPBASEQTY>0 and a.FID in ('+GetSqlForList(CheckedBillFIDList)+')'
+' group by m.fid,m.fnumber,m.fname_l2 ,Brand.Fname_L2 ,years.fname_l2,attb.fname_l2 ';
try
cdsMaterial.DisableControls;
cdsMaterial.AfterPost := nil;
cdsMaterial.EmptyDataSet;
cds := TClientDataSet.Create(nil);
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
ShowMsg(Self.Handle, '查询物料出错:'+ErrMsg+','+_SQL,[]);
Gio.AddShow('查询物料出错:'+ErrMsg+','+_SQL);
Abort;
end;
if not cds.IsEmpty then
begin
cds.First;
while not cds.Eof do
begin
cdsMaterial.Append;
for i := 0 to cds.FieldCount - 1 do
begin
cdsMaterial.FieldByName(cds.Fields[i].FieldName).Value := cds.Fields[i].Value;
end;
cdsMaterial.Post;
cds.Next;
end;
cdsMaterial.First;
end;
finally
cds.Free;
cdsMaterial.AfterPost := cdsMaterialAfterPost;
cdsMaterial.EnableControls;
end;
end;
procedure TBillDistributionFrm.btDownClick(Sender: TObject);
begin
inherited;
NextStep(mPage.ActivePageIndex);
end;
procedure TBillDistributionFrm.NextStep(index: Integer);
begin
try
Screen.Cursor := crHourGlass;
cdsBilllist.DisableControls;
cdsMaterial.DisableControls;
if cdsBilllist.State in DB.dsEditModes then cdsBilllist.Post;
if index = 0 then
begin
CheckedBillFIDList.Clear;
cdsBilllist.First;
while not cdsBilllist.Eof do
begin
if cdsBilllist.FieldByName('selected').AsBoolean then
begin
CheckedBillFIDList.Add(cdsBilllist.FieldByName('BillFID').AsString);
end;
cdsBilllist.Next;
end;
if CheckedBillFIDList.Count = 0 then
begin
ShowMsg(self.Handle,'请选择要要配货的单据! ',[]);
Abort;
end;
GetMaterialList;//查询物料信息
if cdsPubEntry.Active then cdsEntry.EmptyDataSet;
mPage.ActivePageIndex := 1;
end;
if index = 1 then
begin
if cdsMaterial.State in DB.dsEditModes then cdsMaterial.Post;
cdsMaterial.Filtered := False;
if cdsMaterial.IsEmpty then Exit;
cdsMaterial.First;
CheckedMaterFIDList.Clear;
while not cdsMaterial.Eof do
begin
if cdsMaterial.FieldByName('selected').AsBoolean then
begin
CheckedMaterFIDList.Add(cdsMaterial.FieldByName('MaterialFID').AsString);
end;
cdsMaterial.Next;
end;
if CheckedMaterFIDList.Count = 0 then
begin
ShowMsg(self.Handle,'请选择要配货的物料! ',[]);
Abort;
end;
GetqrySizegrouppackallot;
GetAllocationList;
SetNotPackCompent;
mPage.ActivePageIndex := 2;
end;
finally
cdsMaterial.EnableControls;
cdsBilllist.EnableControls;
Screen.Cursor := crDefault;
end;
end;
procedure TBillDistributionFrm.btn_ResetClick(Sender: TObject);
begin
inherited;
cdsBilllist.EmptyDataSet;
DisableCompnet(True);
end;
procedure TBillDistributionFrm.cxButton2Click(Sender: TObject);
begin
inherited;
try
cdsMaterial.DisableControls;
cdsMaterial.AfterPost := nil;
cdsMaterial.First;
while not cdsMaterial.Eof do
begin
cdsMaterial.Edit;
cdsMaterial.FieldByName('selected').AsBoolean := True;
cdsMaterial.Post;
cdsMaterial.Next;
end;
finally
cdsMaterial.AfterPost := cdsMaterialAfterPost;
cdsMaterial.EnableControls;
end;
QueryEntryList;
end;
procedure TBillDistributionFrm.cxButton5Click(Sender: TObject);
begin
inherited;
try
cdsMaterial.AfterPost := nil;
cdsMaterial.DisableControls;
cdsMaterial.First;
while not cdsMaterial.Eof do
begin
cdsMaterial.Edit;
cdsMaterial.FieldByName('selected').AsBoolean := not cdsMaterial.FieldByName('selected').AsBoolean;
cdsMaterial.Post;
cdsMaterial.Next;
end;
finally
cdsMaterial.AfterPost := cdsMaterialAfterPost;
cdsMaterial.EnableControls;
end;
QueryEntryList;
end;
procedure TBillDistributionFrm.txt_MaterialPropertiesChange(
Sender: TObject);
var inputTxt:string;
begin
inputTxt := Trim(txt_Material.Text);
cdsMaterial.Filtered := False;
if (inputTxt <> '' ) then
cdsMaterial.Filtered := True
else
cdsMaterial.Filtered := False;
end;
procedure TBillDistributionFrm.cdsMaterialFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
inherited;
Accept:=((Pos(Trim(UpperCase(txt_Material.Text)),UpperCase(DataSet.fieldbyname('MaterialNumber').AsString))>0) or
(Pos(Trim(UpperCase(txt_Material.Text)),UpperCase(DataSet.fieldbyname('MaterialName').AsString))>0) or
(Pos(Trim(UpperCase(txt_Material.Text)),ChnToPY(UpperCase(DataSet.fieldbyname('MaterialNumber').AsString)))>0) or
(Pos(Trim(UpperCase(txt_Material.Text)),ChnToPY(UpperCase(DataSet.fieldbyname('MaterialName').AsString)))>0)
)
end;
procedure TBillDistributionFrm.QueryEntryList;
var _SQL,ErrMsg : string;
cds : TClientDataSet;
i:Integer;
allTable:string;
begin
if cdsMaterial.State in DB.dsEditModes then cdsMaterial.Post;
if cdsMaterial.IsEmpty then Exit;
cdsMaterial.First;
CheckedMaterFIDList.Clear;
while not cdsMaterial.Eof do
begin
if cdsMaterial.FieldByName('selected').AsBoolean then
begin
CheckedMaterFIDList.Add(cdsMaterial.FieldByName('MaterialFID').AsString);
end;
cdsMaterial.Next;
end;
if CheckedMaterFIDList.Count = 0 then
begin
ShowMsg(self.Handle,'请选择要配货的物料! ',[]);
Abort;
end;
allTable := GetAllocationTable(self.FSaleType);
_SQL := 'select a.fnumber as BillNumber, m.fid as MaterialFID,m.fnumber as MaterialNumber,m.fname_l2 as MaterialName, '
+' max(ass.ff21) as ColorNumber, max(ass.ff11) as ColorName,max(ass.ff12) as SizeName,'
+' max(ass.ff13) as cupName,'
+' sum(nvl(b.fqty,0)) as Fqty, '
+' sum(nvl(pty.PostQty,0)) as FTOTALSHIPPINGQTY , ' //已配数
+' sum(nvl(b.fqty,0))-sum(nvl(pty.PostQty,0)) as FTOTALUNSHIPBASEQTY ,'//未配数
+' sum(nvl(b.FTOTALISSUEBASEQTY,0)) as FTOTALISSUEBASEQTY , ' //已出库数
+' sum(nvl(b.FTOTALUNISSUEQTY,0)) as FTOTALUNISSUEQTY, ' //未出库数
+' sum(inv.FQty) as fbaseqty , ' //在库数
+' sum(FUsableQty) as FUsableQty, ' //可用库存
+' brand.Fname_L2 as brandName,'
+' years.fname_l2 as yearsName,'
+' attb.fname_l2 as attbName '
+' from t_Sd_Saleorder a '
+' left join t_Sd_Saleorderentry b on a.fid = b.fparentid'
+' left join (select sum(Fqty) as PostQty, fsourcebillentryid '
+' from '+allTable+' group by fsourcebillentryid ) pty on b.fid = pty.fsourcebillentryid '
+' left join t_bd_material m on b.fmaterialid = m.fid '
+' left join ct_bas_brand brand on brand.fid = m.cfbrandid'
+' left join ct_bas_years years on years.fid = m.cfyearsid '
+' left join ct_bd_attribute attb on attb.fid=m.cfattributeid '
+' left join t_bd_asstattrvalue ass on ass.fid=b.fassistpropertyid'
+' left join '
+' (select fwarehouseid, fmaterialid,fassistpropertyid , '
+' sum(FQty) as FQty,sum(FUsableQty) as FUsableQty '
+' from ( '
+' select iv.fwarehouseid, iv.fmaterialid, '
+' iv.fassistpropertyid,'
+' iv.fcurstoreqty as FQty,iv.fcurstoreqty-iv.cfallocstockqty as FUsableQty '
+' from t_Im_Inventory iv '
+' where 1=1 and iv.fwarehouseid = '+quotedstr(self.OutWarehouseFID)
+' union all '
+' select rtpos.cfstorageid as fwarehouseid , '
+' rtEntry.Cfmaterialid as fmaterialid ,pass.fid as fassistpropertyid,-rtEntry.Cfamount as Fqty,0 as FUsableQty '
+' from ct_bil_retailpos rtpos '
+' left join ct_bil_retailposEntry rtEntry '
+' on rtpos.fid = rtEntry.Fparentid '
+' left join t_bd_asstattrvalue pass on rtEntry.cfassistnum=pass.fnumber'
+' where rtpos.cfissaleout=0 and rtpos.cfstate = 2 and rtpos.cfstorageid = '+quotedstr(self.OutWarehouseFID)
+' ) Inventory '
+' group by fwarehouseid, fmaterialid,fassistpropertyid) '
+' inv on b.fmaterialid = inv.fmaterialid and inv.fwarehouseid = '+quotedstr(self.OutWarehouseFID)
+' and inv.fassistpropertyid=b.fassistpropertyid'
+' where a.FID in ('+GetSqlForList(CheckedBillFIDList)+')'
+' and b.fmaterialid in ('+GetSqlForList(CheckedMaterFIDList)+')'
+' group by a.fnumber, m.fid,m.fnumber,m.fname_l2 ,Brand.Fname_L2 ,years.fname_l2,attb.fname_l2, '
+' b.cfcolorid,b.cfsizesid,b.cfcupid'
+' order by a.fnumber, m.fid, b.cfcolorid, b.cfsizesid,b.cfcupid';
Thread_OpenSQL(self.Handle,cdsPubEntry,_SQL,20001);
end;
procedure TBillDistributionFrm.I3UserMessageResult(var msg: TMessage);
begin
inherited;
//查询第二个页面的物料明细进度
if msg.WParam = 20001 then
begin
cdsEntry.Data := cdsPubEntry.Data;
setcxEntry;
end;
//查询物料图片
if msg.WParam = 20002 then
begin
showImg;
end;
//查询发货方库存,可用库存
if msg.WParam = 20003 then
begin
SetDownGridData(cdsStock_tmp,cdsInStock,cdsBalStock,1);
end;
//查询收货方库存
if msg.WParam = 20004 then
begin
SetDownGridData(cdsRecStock_tmp,cdsRecStock,nil,2);
end;
//查询收货方销售数据
if msg.WParam = 20005 then
begin
SetDownGridData(cdsSaleQty_tmp,cdsSaleQty,nil,3);
end;
end;
procedure TBillDistributionFrm.cdsMaterialAfterPost(DataSet: TDataSet);
begin
inherited;
QueryEntryList;
end;
procedure TBillDistributionFrm.setcxEntry;
var i:Integer;
FieldName:string;
begin
try
cxEntry.BeginUpdate;
if cxEntry.ColumnCount = 0 then
begin
cxEntry.DataController.CreateAllItems();
for i := 0 to cxEntry.ColumnCount -1 do
begin
cxEntry.Columns[i].Width := 100;
FieldName := cxEntry.Columns[i].DataBinding.FieldName;
case cxEntry.DataController.DataSource.DataSet.FieldByName(FieldName).DataType of
ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftBCD, ftLargeint:
begin
with cxEntry.DataController.Summary.FooterSummaryItems.Add do
begin
ItemLink := cxEntry.GetColumnByFieldName(FieldName);
Position := spFooter;
Kind := skSum;
end;
cxEntry.Columns[i].Width := 55;
end;
end;
end;
cxEntry.GetColumnByFieldName('BillNumber').Caption := '销售订单号';
cxEntry.GetColumnByFieldName('MaterialFID').Visible := False;
cxEntry.GetColumnByFieldName('MaterialNumber').Caption := '物料编号';
cxEntry.GetColumnByFieldName('MaterialName').Caption := '物料名称';
cxEntry.GetColumnByFieldName('ColorNumber').Caption := '颜色编号';
cxEntry.GetColumnByFieldName('ColorNumber').Width := 60;
cxEntry.GetColumnByFieldName('ColorName').Caption := '颜色名称';
cxEntry.GetColumnByFieldName('SizeName').Caption := '尺码';
cxEntry.GetColumnByFieldName('SizeName').Width := 50;
cxEntry.GetColumnByFieldName('cupName').Caption := '内长';
cxEntry.GetColumnByFieldName('cupName').Width := 50;
cxEntry.GetColumnByFieldName('Fqty').Caption := '订单数量';
cxEntry.GetColumnByFieldName('FTOTALSHIPPINGQTY').Caption := '已配数';
cxEntry.GetColumnByFieldName('FTOTALUNSHIPBASEQTY').Caption := '未配数';
cxEntry.GetColumnByFieldName('FTOTALISSUEBASEQTY').Caption := '已出库数';
cxEntry.GetColumnByFieldName('FTOTALUNISSUEQTY').Caption := '未出库数';
cxEntry.GetColumnByFieldName('fbaseqty').Caption := '库存数量';
cxEntry.GetColumnByFieldName('FUsableQty').Caption := '可用库存';
cxEntry.GetColumnByFieldName('brandName').Caption := '品牌';
cxEntry.GetColumnByFieldName('yearsName').Caption := '年份';
cxEntry.GetColumnByFieldName('attbName').Caption := '波段';
end;
finally
cxEntry.EndUpdate;
end;
end;
procedure TBillDistributionFrm.cxButton6Click(Sender: TObject);
begin
inherited;
QueryEntryList;
end;
procedure TBillDistributionFrm.UpStep(index: Integer);
begin
if index = 2 then
begin
mPage.ActivePageIndex := 1;
end;
if index = 1 then
begin
mPage.ActivePageIndex := 0;
end;
end;
procedure TBillDistributionFrm.btUPClick(Sender: TObject);
begin
inherited;
UpStep(mPage.ActivePageIndex);
end;
procedure TBillDistributionFrm.txt_billMaterListPropertiesChange(
Sender: TObject);
var inputTxt:string;
begin
if not cdsEntry.Active then Exit;
inputTxt := Trim(txt_billMaterList.Text);
cdsEntry.Filtered := False;
if (inputTxt <> '' ) then
cdsEntry.Filtered := True
else
cdsEntry.Filtered := False;
end;
procedure TBillDistributionFrm.cdsEntryFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
inherited;
Accept:=((Pos(Trim(UpperCase(txt_billMaterList.Text)),UpperCase(DataSet.fieldbyname('BillNumber').AsString))>0) or
(Pos(Trim(UpperCase(txt_billMaterList.Text)),UpperCase(DataSet.fieldbyname('MaterialNumber').AsString))>0) or
(Pos(Trim(UpperCase(txt_billMaterList.Text)),UpperCase(DataSet.fieldbyname('MaterialName').AsString))>0) or
(Pos(Trim(UpperCase(txt_billMaterList.Text)),ChnToPY(UpperCase(DataSet.fieldbyname('BillNumber').AsString)))>0) or
(Pos(Trim(UpperCase(txt_billMaterList.Text)),ChnToPY(UpperCase(DataSet.fieldbyname('MaterialNumber').AsString)))>0) or
(Pos(Trim(UpperCase(txt_billMaterList.Text)),ChnToPY(UpperCase(DataSet.fieldbyname('MaterialName').AsString)))>0)
)
end;
procedure TBillDistributionFrm.GetMaxSizeCount;
begin
MaxSizeCount := CliDM.Client_QueryReturnVal('select max(FSEQ) as FSEQ from CT_BAS_SIZEGROUPENTRY');
end;
procedure TBillDistributionFrm.setGridSizeTitle;
var i,index:Integer;
_SQL,title,MatFID:string;
begin
try
cxAllocation_bands.BeginUpdate;
cxgridInStock.BeginUpdate;
cxGridBalStock.BeginUpdate;
cxgridDestStock.BeginUpdate;
cxgridDestSale.BeginUpdate;
for i := 1 to 30 do
begin
cxAllocation_bands.GetColumnByFieldName('FQty_'+inttostr(i)).Caption := '';
cxAllocation_bands.GetColumnByFieldName('FQty_'+inttostr(i)).Visible := i <= self.MaxSizeCount;
cxAllocation_bands.GetColumnByFieldName('FNotQty_'+inttostr(i)).Caption := '';
cxAllocation_bands.GetColumnByFieldName('FNotQty_'+inttostr(i)).Visible := i <= self.MaxSizeCount;
//下方
cxgridInStock.GetColumnByFieldName('fAmount_'+inttostr(i)).Caption := '';
cxgridInStock.GetColumnByFieldName('fAmount_'+inttostr(i)).Visible := False;
cxGridBalStock.GetColumnByFieldName('fAmount_'+inttostr(i)).Caption := '';
cxGridBalStock.GetColumnByFieldName('fAmount_'+inttostr(i)).Visible := False;
cxgridDestStock.GetColumnByFieldName('fAmount_'+inttostr(i)).Caption := '';
cxgridDestStock.GetColumnByFieldName('fAmount_'+inttostr(i)).Visible := False;
cxgridDestSale.GetColumnByFieldName('fAmount_'+inttostr(i)).Caption := '';
cxgridDestSale.GetColumnByFieldName('fAmount_'+inttostr(i)).Visible := False;
end;
if cdsAllocation.IsEmpty then Exit;
MatFID := cdsAllocation.fieldbyname('FMATERIALID').AsString;
if MatFID = '' then Exit;
_SQL :=' select a.FSEQ as showIndex,ass.FNAME_L2 as SizeName from CT_BAS_SIZEGROUPENTRY a '
+' left join T_BD_ASSTATTRVALUE ass on a.CFSIZEID = ass.FID '
+' left join T_BD_MATERIAL m on a.FPARENTID = m.CFSIZEGROUPID '
+' where m.fid = '+Quotedstr(MatFID);
with CliDM.Client_QuerySQL(_SQL) do
begin
if not IsEmpty then
begin
First;
while not Eof do
begin
index := fieldbyname('showIndex').AsInteger;
title := fieldbyname('SizeName').AsString;
cxAllocation_bands.GetColumnByFieldName('FQty_'+inttostr(index)).Caption := title;
cxAllocation_bands.GetColumnByFieldName('FQty_'+inttostr(index)).Visible := True;
cxAllocation_bands.GetColumnByFieldName('FNotQty_'+inttostr(index)).Caption := title;
cxAllocation_bands.GetColumnByFieldName('FNotQty_'+inttostr(index)).Visible := True;
//下方
cxgridInStock.GetColumnByFieldName('fAmount_'+inttostr(index)).Caption := title;
cxgridInStock.GetColumnByFieldName('fAmount_'+inttostr(index)).Visible := True;
cxGridBalStock.GetColumnByFieldName('fAmount_'+inttostr(index)).Caption := title;
cxGridBalStock.GetColumnByFieldName('fAmount_'+inttostr(index)).Visible := True;
cxgridDestStock.GetColumnByFieldName('fAmount_'+inttostr(index)).Caption := title;
cxgridDestStock.GetColumnByFieldName('fAmount_'+inttostr(index)).Visible := True;
cxgridDestSale.GetColumnByFieldName('fAmount_'+inttostr(index)).Caption := title;
cxgridDestSale.GetColumnByFieldName('fAmount_'+inttostr(index)).Visible := True;
Next;
end;
end;
end;
finally
cxAllocation_bands.EndUpdate;
cxgridInStock.EndUpdate;
cxGridBalStock.EndUpdate;
cxgridDestStock.EndUpdate;
cxgridDestSale.EndUpdate;
end;
end;
procedure TBillDistributionFrm.GetAllocationList;
var _SQL,ErrMsg:string;
cds:TClientDataSet;
allTable:string;
begin
try
cds := TClientDataSet.Create(nil);
allTable := GetAllocationTable(Self.FSaleType);
_SQL :=' select a.fid as BillFID,a.fnumber,cust.fid as custFID, cust.fnumber as custNumber,cust.fname_l2 as custName, '
+' a.cfinputway,a.cfsaletype,a.cfordertypeid,a.cfpricetypeid,b.funitid,b.fseq as EntrySeq,'
+' a.fbilltypeid, m.cfsizegroupid,'
+' outWarh.Fid as outWarhFID, outWarh.Fnumber as outWarhNumber,outWarh.Fname_L2 as outWarhName, '
+' inWarh.Fid as inWarhFID, inWarh.Fnumber as inWarhNumber,inWarh.Fname_L2 as inWarhName, '
+' m.fnumber as MaterNumber,m.fname_l2 as MaterName, '
+' gp.fseq as SizeShowIndex,ass.ff21 as colorNumber,ass.ff11 as colorName, '
+' ass.ff12 as sizeName,ass.ff14 as packName,ass.ff13 as cupName, '
+' brand.fname_l2 as brandName,years.fname_l2 as yearsName,attb.fname_l2 as attbName, '
+' b.fid as EntryFID ,b.fmaterialid,b.cfcolorid,b.cfsizesid,b.cfpackid,b.cfcupid,b.cfpacknum,b.fqty,'
+' b.fprice,b.cfdpprice,b.fdiscount,b.FActualPrice, '
+' b.fqty-nvl(pty.PostQty,0) as FTOTALUNSHIPBASEQTY '
+' from t_sd_saleorder a left join t_sd_saleorderentry b '
+' on a.fid=b.fparentid '
+' left join (select sum(nvl(Fqty,0)) as PostQty, fsourcebillentryid '
+' from '+allTable+' group by fsourcebillentryid ) pty on b.fid = pty.fsourcebillentryid '
+' left join t_bd_material m '
+' on b.fmaterialid = m.fid '
+' left join t_bd_asstattrvalue ass on ass.fid=b.fassistpropertyid '
+' left join ct_bas_sizegroupentry gp on m.cfsizegroupid=gp.fparentid and ass.ff2=gp.cfsizeid '
+' left join ct_bas_brand brand on brand.fid = m.cfbrandid '
+' left join ct_bas_years years on years.fid = m.cfyearsid '
+' left join ct_bd_attribute attb on attb.fid=m.cfattributeid '
+' left join t_bd_customer cust on a.fordercustomerid = cust.fid '
+' left join t_db_warehouse outWarh on outWarh.fid=a.fwarehouseid '
+' left join t_db_warehouse inWarh on inWarh.fid=a.cfinwarehouseid '
+' where b.FTOTALUNSHIPBASEQTY>0 and a.fid in ('+GetSqlForList(CheckedBillFIDList)+') and b.fmaterialid in ('+getsqlForList(CheckedMaterFIDList)+')';
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
ShowMsg(self.Handle,'查询配货明细出错:'+ErrMsg+':'+_SQL,[]);
Gio.AddShow('查询配货明细出错:'+ErrMsg+':'+_SQL);
Abort;
end;
CopyDataset(cds,cdsBillDetail);
cdsBillDetail.ReadOnly := False;
cdsAllocation.EmptyDataSet;
DetailToHorizontal;
setGridSizeTitle;
finally
cds.Free;
end;
end;
procedure TBillDistributionFrm.DetailToHorizontal;
var isExists:Boolean;
i,PHQty,PackRate:Integer;
begin
if cdsBillDetail.IsEmpty then Exit;
try
IsSupeControl := False;
cdsAllocation.DisableControls;
cdsBillDetail.First;
while not cdsBillDetail.Eof do
begin
isExists := False;
cdsAllocation.First;
while not cdsAllocation.Eof do
begin
if (cdsBillDetail.FieldByName('BillFID').AsString = cdsAllocation.FieldByName('BillFID').AsString) and
(cdsBillDetail.FieldByName('fmaterialid').AsString = cdsAllocation.FieldByName('fmaterialid').AsString) and
(cdsBillDetail.FieldByName('cfcolorid').AsString = cdsAllocation.FieldByName('cfcolorid').AsString) and
(cdsBillDetail.FieldByName('cfpackid').AsString = cdsAllocation.FieldByName('cfpackid').AsString) and
(cdsBillDetail.FieldByName('cfcupid').AsString = cdsAllocation.FieldByName('cfcupid').AsString)
then
begin
isExists := True;
Break;
end;
cdsAllocation.Next;
end;
if isExists then
begin
cdsAllocation.Edit;
end
else
begin
cdsAllocation.Append;
end;
for i := 0 to cdsAllocation.FieldCount -1 do
begin
if cdsBillDetail.FindField(cdsAllocation.Fields[i].FieldName) <> nil then
begin
cdsAllocation.Fields[i].Value := cdsBillDetail.fieldbyname(cdsAllocation.Fields[i].FieldName).Value;
end;
end;
cdsAllocation.FieldByName('FNotQty_'+cdsBillDetail.FieldByName('SizeShowIndex').AsString).Value := cdsBillDetail.FieldByName('FTOTALUNSHIPBASEQTY').Value;
PHQty := GetPHQty(cdsBillDetail);
cdsAllocation.FieldByName('FQty_'+cdsBillDetail.FieldByName('SizeShowIndex').AsString).Value := PHQty;
if (txt_InputWay.EditingValue <> 'NOTPACK') then
begin
PackRate := cdsBillDetail.FieldByName('Fqty').AsInteger div cdsBillDetail.FieldByName('cfpacknum').AsInteger;
cdsAllocation.FieldByName('CFNotPACKNUM').AsInteger := cdsBillDetail.FieldByName('FTOTALUNSHIPBASEQTY').AsInteger div PackRate;
cdsAllocation.FieldByName('cfpacknum').AsInteger := PHQty div PackRate;
end;
cdsAllocation.Post;
cdsBillDetail.Next;
end;
finally
IsSupeControl := True;
cdsAllocation.EnableControls;
end;
end;
procedure TBillDistributionFrm.GetStockData; //查库存
var _SQL,ErrMsg:string;
cds:TClientDataSet;
i:Integer;
begin
if cb_DownDataType.ItemIndex < 2 then Exit;
_SQL :=' select fwarehouseid, fmaterialid,b.ff1 as cfcolorid,b.ff2 as cfsizesid,b.ff4 as cfpackid,b.ff3 as cfcupid ,'
+' sum(FQty) as FQty,sum(FUsableQty) as FUsableQty '
+' from ( '
+' select iv.fwarehouseid, iv.fmaterialid,iv.fassistpropertyid '
+' iv.fcurstoreqty as FQty,iv.fcurstoreqty-iv.cfallocstockqty as FUsableQty '
+' from t_Im_Inventory iv'
+' where iv.fmaterialid in ('+getsqlForList(CheckedMaterFIDList)+') and iv.fwarehouseid='+Quotedstr(self.OutWarehouseFID)
+' union all '
+' select rtpos.cfstorageid as fwarehouseid , '
+' rtEntry.Cfmaterialid as fmaterialid ,pass.fid as fassistpropertyid,-rtEntry.Cfamount as Fqty,0 as FUsableQty '
+' from ct_bil_retailpos rtpos '
+' left join ct_bil_retailposEntry rtEntry '
+' on rtpos.fid = rtEntry.Fparentid left join t_bd_asstattrvalue pass on rtEntry.cfassistnum=pass.fnumber '
+' where rtpos.cfissaleout=0 and rtpos.cfstate = 2 and rtEntry.Cfmaterialid in ('+getsqlForList(CheckedMaterFIDList)+') and rtpos.cfstorageid='+Quotedstr(self.OutWarehouseFID)
+' ) Inventory left join t_bd_asstattrvalue b on Inventory.fassistpropertyid=b.fid'
+' group by fwarehouseid, fmaterialid,fassistpropertyid, b.ff1 ,b.ff2,b.ff4,b.ff3 ';
try
cds := TClientDataSet.Create(nil);
cdsStockData.EmptyDataSet;
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
ShowMsg(self.Handle,'查询库存数据出错:'+ErrMsg+':'+_SQL,[]);
Gio.AddShow('查询库存数据出错:'+ErrMsg+':'+_SQL);
Abort;
end;
if not cds.IsEmpty then
begin
cds.First;
cdsStockData.Append;
for i := 0 to cds.FieldCount -1 do
begin
cdsStockData.FieldByName(cds.Fields[i].FieldName).Value := cds.Fields[i].Value;
end;
cdsStockData.Post;
cds.Next;
end;
finally
cds.Free;
end;
end;
function TBillDistributionFrm.GetPHQty(cdsBill: TClientDataSet): Integer;
var isExists:Boolean;
StockQty,UsableQty,uFqty:Integer;//库存数,可用库存数 ,未配数
begin
{
未配数量
空数量
可用库存数
在库数量
}
Result := 0;
if cb_DownDataType.ItemIndex = 0 then
begin
Result := cdsBill.fieldbyname('FTOTALUNSHIPBASEQTY').AsInteger;
Exit;
end;
if cb_DownDataType.ItemIndex = 1 then
begin
Result := 0;
Exit;
end;
if cdsStockData.IsEmpty then Exit;
cdsStockData.First;
isExists := False;
while not cdsStockData.Eof do
begin
if (cdsStockData.FieldByName('cfsizesid').AsString = cdsBill.FieldByName('cfsizesid').AsString) and
(cdsStockData.FieldByName('fmaterialid').AsString = cdsBill.FieldByName('fmaterialid').AsString) and
(cdsStockData.FieldByName('cfcolorid').AsString = cdsBill.FieldByName('cfcolorid').AsString) and
(cdsStockData.FieldByName('cfpackid').AsString = cdsBill.FieldByName('cfpackid').AsString) and
(cdsStockData.FieldByName('cfcupid').AsString = cdsBill.FieldByName('cfcupid').AsString)
then
begin
isExists := True;
Break;
end;
cdsAllocation.Next;
end;
if not isExists then Exit;
StockQty := cdsStockData.fieldbyname('FQty').AsInteger;
UsableQty:= cdsStockData.fieldbyname('FUsableQty').AsInteger;
uFqty := cdsBill.fieldbyname('FTOTALUNSHIPBASEQTY').AsInteger;
if (cb_DownDataType.ItemIndex = 2) then
begin
if UsableQty <= 0 then
begin
Result := 0;
Exit;
end;
if UsableQty <= uFqty then
begin
Result := UsableQty;
cdsStockData.Edit;
cdsStockData.FieldByName('FUsableQty').AsInteger := 0;
cdsStockData.Post;
end
else
begin
Result := uFqty;
cdsStockData.Edit;
cdsStockData.FieldByName('FUsableQty').AsInteger := UsableQty-uFqty;
cdsStockData.Post;
end;
end;
if (cb_DownDataType.ItemIndex = 3) then
begin
if StockQty <= 0 then
begin
Result := 0;
Exit;
end;
if StockQty <= uFqty then
begin
Result := StockQty;
cdsStockData.Edit;
cdsStockData.FieldByName('FQty').AsInteger := 0;
cdsStockData.Post;
end
else
begin
Result := uFqty;
cdsStockData.Edit;
cdsStockData.FieldByName('FQty').AsInteger := StockQty-uFqty;
cdsStockData.Post;
end;
end;
end;
procedure TBillDistributionFrm.FormResize(Sender: TObject);
begin
inherited;
Panel13.Width := (self.Width-Panel17.Width) div 2;
end;
procedure TBillDistributionFrm.txt_FilterPropertiesChange(Sender: TObject);
var inputTxt:string;
begin
if not cdsAllocation.Active then Exit;
inputTxt := Trim(txt_Filter.Text);
cdsAllocation.Filtered := False;
if (inputTxt <> '' ) then
cdsAllocation.Filtered := True
else
cdsAllocation.Filtered := False;
end;
procedure TBillDistributionFrm.cdsAllocationFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
inherited;
Accept:=((Pos(Trim(UpperCase(txt_Filter.Text)),UpperCase(DataSet.fieldbyname('FNUMBER').AsString))>0) or
(Pos(Trim(UpperCase(txt_Filter.Text)),UpperCase(DataSet.fieldbyname('MATERNUMBER').AsString))>0) or
(Pos(Trim(UpperCase(txt_Filter.Text)),UpperCase(DataSet.fieldbyname('MATERNAME').AsString))>0) or
(Pos(Trim(UpperCase(txt_Filter.Text)),ChnToPY(UpperCase(DataSet.fieldbyname('FNUMBER').AsString)))>0) or
(Pos(Trim(UpperCase(txt_Filter.Text)),ChnToPY(UpperCase(DataSet.fieldbyname('MATERNUMBER').AsString)))>0) or
(Pos(Trim(UpperCase(txt_Filter.Text)),ChnToPY(UpperCase(DataSet.fieldbyname('MATERNAME').AsString)))>0)
)
end;
procedure TBillDistributionFrm.GetDownInfo;
var _SQL,MatFID,InWarehouseFID,SaleDate:string;
begin
lb_materInfo.Caption := '';
Label13.Caption := '订货客户:'+txt_Customer.Text;
if Trim(txt_warehouse.Text) <> '' then
Label13.Caption := Label13.Caption +' 收货仓:'+txt_warehouse.Text;
if cdsAllocation.IsEmpty then
begin
Exit;
end;
lb_materInfo.Caption := cdsAllocation.fieldbyname('MATERNUMBER').AsString+'-'+cdsAllocation.fieldbyname('MATERNAME').AsString;
MatFID := cdsAllocation.fieldbyname('FMATERIALID').AsString;
if SelectedMaterFID = MatFID then Exit;
cdsInStock.EmptyDataSet;
cdsBalStock.EmptyDataSet;
cdsRecStock.EmptyDataSet;
cdsSaleQty.EmptyDataSet;
//查图片
_SQL := 'select a.FAttachmentID,b.ffile,a.FBoID from T_BAS_BoAttchAsso a '
+' inner join T_BAS_Attachment b on a.FAttachmentID=b.FID'
+' where a.FBoID='''+MatFID+'''';
Thread_OpenSQL(self.Handle,cdsImg,_SQL,20002);
//查库存
_SQL :='select fwarehouseid,fmaterialid,ass.ff1 as cfcolorid,ass.ff2 as cfsizesid, '
+' ass.ff4 as cfpackid,ass.ff3 as cfcupid, max(ass.ff21) as CFColorCode, '
+' max(ass.ff11) as CFColorName, max(ass.ff14) as cfPackName,max(ass.ff13) as cfCupName, '
+' max(gp.fseq) as ShowIndex,sum(FQty) as FQty,sum(FUsableQty) as FUsableQty, max(allot.cfiamount) as allotQty '
+' from (select iv.fwarehouseid,iv.fmaterialid,iv.fassistpropertyid,'
+' iv.fcurstoreqty as FQty,iv.fcurstoreqty - iv.cfallocstockqty as FUsableQty '
+' from t_Im_Inventory iv '
+' where iv.fwarehouseid='+Quotedstr(self.OutWarehouseFID)+' and iv.fmaterialid='+Quotedstr(MatFID)
+' union all '
+' select rtpos.cfstorageid as fwarehouseid, rtEntry.Cfmaterialid as fmaterialid,'
+' pass.fid as fassistpropertyid, -rtEntry.Cfamount as Fqty, 0 as FUsableQty '
+' from ct_bil_retailpos rtpos '
+' left join ct_bil_retailposEntry rtEntry '
+' on rtpos.fid = rtEntry.Fparentid left join t_bd_asstattrvalue pass on rtEntry.cfassistnum=pass.fnumber '
+' where rtpos.cfissaleout = 0 and rtpos.cfstate = 2 '
+' and rtpos.cfstorageid='+Quotedstr(self.OutWarehouseFID)+' and rtEntry.Cfmaterialid='+Quotedstr(MatFID) +') Inventory'
+' left join t_bd_asstattrvalue ass '
+' on ass.FID = Inventory.fassistpropertyid '
+' left join t_bd_material m on m.fid = Inventory.fmaterialid '
+' left join ct_bas_sizegroupentry gp on gp.fparentid = m.cfsizegroupid and gp.cfsizeid = ass.ff2'
+' left join ct_bas_sizegrouppackallot allot on allot.fparentid = m.cfsizegroupid '
+' and allot.cfpackid = ass.ff4 and allot.cfsizeid = ass.ff2 '
+' group by fwarehouseid,fmaterialid,fassistpropertyid,ass.ff1 ,ass.ff2 ,ass.ff4 ,ass.ff3';
Thread_OpenSQL(self.Handle,cdsStock_tmp,_SQL,20003);
InWarehouseFID := cdsAllocation.fieldbyname('INWARHFID').AsString;
if trim(InWarehouseFID) <> '' then
begin
//查收货方库存
_SQL :='select fwarehouseid,fmaterialid,ass.ff1 as cfcolorid,ass.ff2 as cfsizesid, '
+' ass.ff4 as cfpackid,ass.ff3 as cfcupid, max(ass.ff21) as CFColorCode, '
+' max(ass.ff11) as CFColorName, max(ass.ff14) as cfPackName,max(ass.ff13) as cfCupName, '
+' max(gp.fseq) as ShowIndex,sum(FQty) as FQty,sum(FUsableQty) as FUsableQty, max(allot.cfiamount) as allotQty '
+' from (select iv.fwarehouseid,iv.fmaterialid,iv.fassistpropertyid,'
+' iv.fcurstoreqty as FQty,iv.fcurstoreqty - iv.cfallocstockqty as FUsableQty '
+' from t_Im_Inventory iv '
+' where iv.fwarehouseid='+Quotedstr(InWarehouseFID)+' and iv.fmaterialid='+Quotedstr(MatFID)
+' union all '
+' select rtpos.cfstorageid as fwarehouseid, rtEntry.Cfmaterialid as fmaterialid,'
+' pass.fid as fassistpropertyid, -rtEntry.Cfamount as Fqty, 0 as FUsableQty '
+' from ct_bil_retailpos rtpos '
+' left join ct_bil_retailposEntry rtEntry '
+' on rtpos.fid = rtEntry.Fparentid left join t_bd_asstattrvalue pass on rtEntry.cfassistnum=pass.fnumber '
+' where rtpos.cfissaleout = 0 and rtpos.cfstate = 2 '
+' and rtpos.cfstorageid='+Quotedstr(InWarehouseFID)+' and rtEntry.Cfmaterialid='+Quotedstr(MatFID)+') Inventory'
+' left join t_bd_asstattrvalue ass '
+' on ass.FID = Inventory.fassistpropertyid '
+' left join t_bd_material m on m.fid = Inventory.fmaterialid '
+' left join ct_bas_sizegroupentry gp on gp.fparentid = m.cfsizegroupid and gp.cfsizeid = ass.ff2'
+' left join ct_bas_sizegrouppackallot allot on allot.fparentid = m.cfsizegroupid '
+' and allot.cfpackid = ass.ff4 and allot.cfsizeid = ass.ff2 '
+' group by fwarehouseid,fmaterialid,fassistpropertyid,ass.ff1 ,ass.ff2 ,ass.ff4 ,ass.ff3';
Thread_OpenSQL(self.Handle,cdsRecStock_tmp,_SQL,20004);
//查收货仓销售
if spe_SaleDays.EditingValue > 0 then
begin
SaleDate := FormatDateTime('yyyy-MM-dd', DateUtils.IncDay(Now , -spe_SaleDays.EditingValue));
_SQL :=' select fwarehouseid, fmaterialid,ass.ff1 as cfcolorid,ass.ff2 as cfsizesid,ass.ff4 as cfpackid,ass.ff3 as cfcupid , '
+' max(ass.ff21) as CFColorCode,max(ass.ff11) as CFColorName, '
+' max(ass.ff14) as cfPackName,max(ass.ff13) as cfCupName,'
+' max(gp.fseq) as ShowIndex,'
+' sum(FQty) as FQty,sum(FUsableQty) as FUsableQty,max(allot.cfiamount) as allotQty '
+' from ( '
+' select rtpos.cfstorageid as fwarehouseid , '
+' rtEntry.Cfmaterialid as fmaterialid ,rtEntry.cfassistnum, rtEntry.Cfamount as Fqty,0 as FUsableQty '
+' from ct_bil_retailpos rtpos '
+' left join ct_bil_retailposEntry rtEntry'
+' on rtpos.fid = rtEntry.Fparentid '
+' where rtpos.cfstate = 2 and rtpos.cfstorageid='+Quotedstr(InWarehouseFID)+' and rtEntry.Cfmaterialid='+Quotedstr(MatFID)
+' and to_char(rtpos.fbizdate,''yyyy-MM-dd'') > '+Quotedstr(SaleDate)
+' ) sale '
+' left join t_bd_asstattrvalue Ass on ass.fnumber = sale.cfassistnum '
+' left join t_bd_material m on m.fid = sale.fmaterialid '
+' left join ct_bas_sizegroupentry gp on gp.fparentid=m.cfsizegroupid and gp.cfsizeid=ass.ff2 '
+' left join ct_bas_sizegrouppackallot allot on allot.fparentid = m.cfsizegroupid and allot.cfpackid = ass.ff4 '
+' and allot.cfsizeid = ass.ff2'
+' group by fwarehouseid, fmaterialid,ass.ff1,ass.ff2,ass.ff4,ass.ff3 ';
Thread_OpenSQL(self.Handle,cdsSaleQty_tmp,_SQL,20005);
end;
end;
SelectedMaterFID := MatFID;
end;
procedure TBillDistributionFrm.showImg;
var sql,errmsg,MatFID:string;
Stream: TMemoryStream;
Jpg: TJpegImage;
begin
if not cdsImg.IsEmpty then
begin
try
if Trim(cdsImg.FieldByName('ffile').AsString)='' then Exit;
try
Stream := TMemoryStream.Create;
TBlobField(cdsImg.FieldByName('ffile')).SaveToStream(Stream);
Stream.Position := 0;
jpg := TJpegImage.Create;
jpg.LoadFromStream(Stream);
matreialImg.Picture.Assign(jpg);
Panel17.Caption := '';
except
on e:exception do
begin
ShowMsg(Handle, '加载图片出错,请确认上传的图片为JPG或JPEG格式!错误提示:'+e.Message,[]);
abort;
end;
end;
finally
if Stream <> nil then
FreeAndNil(Stream);
if jpg <> nil then
FreeAndNil(jpg);
end;
end
else
begin
matreialImg.Picture := nil;
Panel17.Caption := '无图片';
end;
end;
procedure TBillDistributionFrm.matreialImgDblClick(Sender: TObject);
begin
inherited;
if not cdsImg.Active then Exit;
if cdsImg.IsEmpty then Exit;
if Trim(cdsImg.FieldByName('ffile').AsString)='' then Exit;
showMaterialMaxImage(cdsImg,lb_materInfo.Caption);
end;
procedure TBillDistributionFrm.cxAllocationFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
begin
inherited;
GetDownInfo;
lb_materInfo.Caption := cdsAllocation.fieldbyname('MATERNUMBER').AsString+':'+cdsAllocation.fieldbyname('MATERNAME').AsString;
end;
procedure TBillDistributionFrm.SetNotPackCompent;
var IsPack:Boolean;
begin
IsPack := txt_InputWay.EditingValue <> 'NOTPACK';
cxAllocation_bands.GetColumnByFieldName('PACKNAME').Visible := IsPack;
cxAllocation_bands.GetColumnByFieldName('CFPACKNUM').Visible := IsPack;
cxAllocation_bands.GetColumnByFieldName('CFNotPACKNUM').Visible := IsPack;
{
cxgridInStock.GetColumnByFieldName('CFPackName').Visible := IsPack;
cxgridInStock.GetColumnByFieldName('cfpackNum').Visible := IsPack;
cxGridBalStock.GetColumnByFieldName('CFPackName').Visible := IsPack;
cxGridBalStock.GetColumnByFieldName('cfpackNum').Visible := IsPack;
cxgridDestSale.GetColumnByFieldName('CFPackName').Visible := IsPack;
cxgridDestSale.GetColumnByFieldName('cfpackNum').Visible := IsPack;
cxgridDestStock.GetColumnByFieldName('CFPackName').Visible := IsPack;
cxgridDestStock.GetColumnByFieldName('cfpackNum').Visible := IsPack;
}
end;
procedure TBillDistributionFrm.cdsAllocationCalcFields(DataSet: TDataSet);
var i,qry,notqty:Integer;
begin
inherited;
qry := 0;
notqty := 0;
for i:= 1 to self.MaxSizeCount do
begin
qry := qry+ DataSet.fieldbyname('FQty_'+Inttostr(i)).AsInteger;
notqty := notqty+ DataSet.fieldbyname('FNotQty_'+Inttostr(i)).AsInteger;
end;
DataSet.fieldbyname('FTotalQty').AsInteger := qry;
DataSet.fieldbyname('FNotTotalQty').AsInteger:= notqty;
DataSet.fieldbyname('FAmount').AsInteger := qry * DataSet.fieldbyname('FACTUALPRICE').AsInteger ;
DataSet.fieldbyname('FDpAmount').AsInteger := qry * DataSet.fieldbyname('CFDPPRICE').AsInteger ;
DataSet.fieldbyname('FNotAmount').AsInteger := notqty * DataSet.fieldbyname('FACTUALPRICE').AsInteger ;
DataSet.fieldbyname('FDpNotAmount').AsInteger:= notqty * DataSet.fieldbyname('CFDPPRICE').AsInteger ;
end;
//Ftype 1发货方库存,2发货方可用库存,3收货方库存,4收货方销售数
procedure TBillDistributionFrm.SetDownGridData(_cdsQuery,
cdsDown,cdsBalDown: TClientDataSet; Ftype: Integer);
var isExists:Boolean;
i,FQty:Integer;
cdsQuery : TClientDataSet;
begin
try
cdsQuery := TClientDataSet.Create(nil);
if _cdsQuery = nil then Exit;
if not _cdsQuery.Active then Exit;
if _cdsQuery.FieldCount = 0 then Exit;
cdsQuery.Data := _cdsQuery.Data;
cdsDown.DisableControls;
if Ftype = 1 then cdsBalDown.DisableControls;
cdsDown.EmptyDataSet;
if cdsQuery.IsEmpty then Exit;
cdsQuery.First;
while not cdsQuery.Eof do
begin
isExists := False;
cdsDown.First;
while not cdsDown.Eof do
begin
if //(cdsQuery.FieldByName('fmaterialid').AsString = cdsDown.FieldByName('fmaterialid').AsString) and
(cdsQuery.FieldByName('cfcolorid').AsString = cdsDown.FieldByName('cfcolorid').AsString) and
(cdsQuery.FieldByName('cfpackid').AsString = cdsDown.FieldByName('cfpackid').AsString) and
(cdsQuery.FieldByName('cfcupid').AsString = cdsDown.FieldByName('cfcupid').AsString)
then
begin
isExists := True;
Break;
end;
cdsDown.Next;
end;
if isExists then
begin
cdsDown.Edit;
end
else
begin
cdsDown.Append;
end;
for i := 0 to cdsDown.FieldCount -1 do
begin
if cdsQuery.FindField(cdsDown.Fields[i].FieldName) <> nil then
begin
cdsDown.Fields[i].Value := cdsQuery.fieldbyname(cdsDown.Fields[i].FieldName).Value;
end;
end;
FQty := cdsQuery.FieldByName('FQty').AsInteger;
cdsDown.FieldByName('fAmount_'+cdsQuery.FieldByName('ShowIndex').AsString).Value := FQty;
if txt_InputWay.EditingValue <> 'NOTPACK' then
begin
if cdsQuery.FieldByName('allotQty').AsInteger <= 0 then
cdsDown.FieldByName('cfpackNum').Value := 0
else
cdsDown.FieldByName('cfpackNum').Value := FQty div cdsQuery.FieldByName('allotQty').AsInteger;
end;
cdsDown.Post;
//可用库存
if Ftype = 1 then
begin
isExists := False;
cdsBalDown.First;
while not cdsBalDown.Eof do
begin
if //(cdsQuery.FieldByName('fmaterialid').AsString = cdsBalDown.FieldByName('fmaterialid').AsString) and
(cdsQuery.FieldByName('cfcolorid').AsString = cdsBalDown.FieldByName('cfcolorid').AsString) and
(cdsQuery.FieldByName('cfpackid').AsString = cdsBalDown.FieldByName('cfpackid').AsString) and
(cdsQuery.FieldByName('cfcupid').AsString = cdsBalDown.FieldByName('cfcupid').AsString)
then
begin
isExists := True;
Break;
end;
cdsBalDown.Next;
end;
if isExists then
begin
cdsBalDown.Edit;
end
else
begin
cdsBalDown.Append;
end;
for i := 0 to cdsBalDown.FieldCount -1 do
begin
if cdsQuery.FindField(cdsBalDown.Fields[i].FieldName) <> nil then
begin
cdsBalDown.Fields[i].Value := cdsQuery.fieldbyname(cdsBalDown.Fields[i].FieldName).Value;
end;
end;
FQty := cdsQuery.FieldByName('FUsableQty').AsInteger;
cdsBalDown.FieldByName('fAmount_'+cdsQuery.FieldByName('ShowIndex').AsString).Value := FQty;
if txt_InputWay.EditingValue <> 'NOTPACK' then
begin
if cdsQuery.FieldByName('allotQty').AsInteger <= 0 then
cdsBalDown.FieldByName('cfpackNum').Value := 0
else
cdsBalDown.FieldByName('cfpackNum').Value := FQty div cdsQuery.FieldByName('allotQty').AsInteger;
end;
cdsBalDown.Post;
end;
cdsQuery.Next;
end;
finally
cdsDown.EnableControls;
if Ftype = 1 then cdsBalDown.EnableControls;
cdsQuery.Free;
end;
end;
procedure TBillDistributionFrm.cdsInStockCalcFields(DataSet: TDataSet);
var i,qry,notqty:Integer;
begin
qry := 0;
for i:= 1 to self.MaxSizeCount do
begin
qry := qry+ DataSet.fieldbyname('fAmount_'+Inttostr(i)).AsInteger;
end;
DataSet.fieldbyname('fTotaLQty').AsInteger := qry;
end;
procedure TBillDistributionFrm.cxButton7Click(Sender: TObject);
begin
inherited;
try
cdsAllocation.DisableControls;
cxAllocation_bands.OnFocusedRecordChanged := nil;
cdsAllocation.First;
while not cdsAllocation.Eof do
begin
cdsAllocation.Edit;
cdsAllocation.FieldByName('selected').AsBoolean := True;
cdsAllocation.Post;
cdsAllocation.Next;
end;
finally
cdsAllocation.EnableControls;
cxAllocation_bands.OnFocusedRecordChanged := cxAllocationFocusedRecordChanged;
GetDownInfo;
end;
end;
procedure TBillDistributionFrm.cxButton8Click(Sender: TObject);
begin
inherited;
try
cdsAllocation.DisableControls;
cxAllocation_bands.OnFocusedRecordChanged := nil;
cdsAllocation.First;
while not cdsAllocation.Eof do
begin
cdsAllocation.Edit;
cdsAllocation.FieldByName('selected').AsBoolean := not cdsAllocation.FieldByName('selected').AsBoolean;
cdsAllocation.Post;
cdsAllocation.Next;
end;
finally
cdsAllocation.EnableControls;
cxAllocation_bands.OnFocusedRecordChanged := cxAllocationFocusedRecordChanged;
GetDownInfo;
end;
end;
procedure TBillDistributionFrm.btn_RefDownDataClick(Sender: TObject);
begin
inherited;
GetDownInfo;
end;
procedure TBillDistributionFrm.btn_CreateBillClick(Sender: TObject);
begin
inherited;
cdsAllocation.Filtered := False;
if MessageBox(Handle, PChar('确认生成配货单?'), 'GA集团ERP提示', MB_YESNO) = IDNO then Exit;
CreateBill(cdsBillDetail);
end;
procedure TBillDistributionFrm.HorizontalToDetail(cdsHorizontal,
cdsDetail: TClientDataSet);
var HBillFID,HMaterFID,HColorFID,HSizeFID,HPackFID,HCupFID:string;
HQty,i:Integer;
begin
if CheckedMaterFIDList.Count = 0 then
begin
ShowMsg(self.Handle,'配货物料为空! ',[]);
Abort;
end;
//横排没有就直接清空竖排
if cdsHorizontal.IsEmpty then
begin
cdsDetail.EmptyDataSet;
Exit;
end;
GetSizeGroupEntry;
try
cdsHorizontal.DisableControls;
cdsDetail.DisableControls;
cdsHorizontal.Filtered := False;
cdsDetail.Filtered := False;
cdsDetail.First;
while not cdsDetail.Eof do //把竖排数据都设为0
begin
cdsDetail.Edit;
cdsDetail.FieldByName('FQty').AsInteger := 0;
cdsDetail.Post;
cdsDetail.Next;
end;
cdsHorizontal.First;
while not cdsHorizontal.Eof do
begin
if cdsHorizontal.FieldByName('selected').AsBoolean then
begin
HBillFID := cdsHorizontal.fieldbyname('BILLFID').AsString;
HMaterFID:= cdsHorizontal.fieldbyname('FMATERIALID').AsString;
HColorFID:= cdsHorizontal.fieldbyname('CFCOLORID').AsString;
HSizeFID := '';
HPackFID := cdsHorizontal.fieldbyname('CFPACKID').AsString;
HCupFID := cdsHorizontal.fieldbyname('CFCUPID').AsString;
for i := 1 to Self.MaxSizeCount do
begin
HQty := cdsHorizontal.fieldbyname('FQty_'+Inttostr(i)).AsInteger;
if HQty > 0 then
begin
HSizeFID := GetSizeFID(HMaterFID,i);
cdsDetail.First;
while not cdsDetail.Eof do
begin
if (HBillFID = cdsDetail.fieldbyname('BILLFID').AsString) and
(HMaterFID = cdsDetail.fieldbyname('FMATERIALID').AsString) and
(HColorFID = cdsDetail.fieldbyname('CFCOLORID').AsString) and
(HSizeFID = cdsDetail.fieldbyname('CFSizesID').AsString) and
(HPackFID = cdsDetail.fieldbyname('CFPACKID').AsString) and
(HCupFID = cdsDetail.fieldbyname('CFCUPID').AsString)
then
begin
cdsDetail.Edit;
cdsDetail.FieldByName('FQty').ReadOnly := False;
cdsDetail.FieldByName('Fqty').AsInteger := HQty;
cdsDetail.Post;
Break;
end;
cdsDetail.Next;
end;
end;
end;
end;
cdsHorizontal.Next;
end;
finally
cdsHorizontal.EnableControls;
cdsDetail.EnableControls;
end;
end;
procedure TBillDistributionFrm.GetSizeGroupEntry;
var _SQL : string;
begin
_SQL :=' select a.FSEQ,a.CFSIZEID,m.FID from CT_BAS_SIZEGROUPENTRY a left join T_BD_MATERIAL m '
+' on a.FPARENTID = m.CFSIZEGROUPID where m.fid in ('+GetSqlForList(CheckedMaterFIDList)+')';
QrySizeGroupEntry := TADOQuery(CliDM.Client_QuerySQL(_SQL));
end;
function TBillDistributionFrm.GetSizeFID(FMaterFID: string;
ShowIndex: Integer): string;
begin
Result := '';
QrySizeGroupEntry.First;
while not QrySizeGroupEntry.Eof do
begin
if (QrySizeGroupEntry.fieldbyname('FID').AsString = FMaterFID)
and (QrySizeGroupEntry.fieldbyname('FSEQ').AsInteger = ShowIndex)
then
begin
Result := QrySizeGroupEntry.fieldbyname('CFSIZEID').AsString;
Exit;
end;
QrySizeGroupEntry.Next;
end;
end;
procedure TBillDistributionFrm.CreateBill(
cdsSaleOrderList: TClientDataSet);
var SaleOrderFID,ErrMsg:string;
i,FQty:Integer;
_cdsSave: array[0..2] of TClientDataSet;
_SQLSave: array[0..2] of String;
BillNumberList:TStringList;
begin
Gio.AddShow('开始竖排转横排...');
HorizontalToDetail(cdsAllocation,cdsBillDetail);
Gio.AddShow('完成竖排转横排...');
if cdsSaleOrderList.IsEmpty then
begin
ShowMsg(self.Handle,'没有可以生成单据的数据...',[]);
Exit;
end;
try
Screen.Cursor := crHourGlass;
BillNumberList := TStringList.Create;
for i := 0 to CheckedBillFIDList.Count -1 do
begin
SaleOrderFID := CheckedBillFIDList[i];
cdsSaleOrderList.Filtered := False;
cdsSaleOrderList.Filter := '(FQty>0) and (BILLFID='+Quotedstr(SaleOrderFID)+')';
cdsSaleOrderList.Filtered := True;
if not cdsSaleOrderList.IsEmpty then
begin
if Self.FSaleType = 'QD' then
begin
//取发货通知单表结构
_cdsSave[0] := cdsMaster;
_cdsSave[1] := cdsDetail;
_cdsSave[2] := cdsBOTP;
_SQLSave[0] := 'select * from t_Sd_Postrequisition where 1<>1 ';
_SQLSave[1] := 'select * from t_Sd_Postrequisitionentry where 1<>1 ';
_SQLSave[2] := 'select * from t_bot_relation where 1<>1 ';
if not (CliDM.Get_OpenClients_E('',_cdsSave,_SQLSave,ErrMsg)) then
begin
showmsg(self.Handle,'取配货单表结构出错:'+ErrMsg,[]);
Exit;
end;
//主表
cdsMaster.Append;
cdsMaster.FieldByName('fdescription').AsString := txt_Des.Text;
cdsMaster.FieldByName('CFINPUTWAY').AsString := cdsSaleOrderList.FieldByName('CFINPUTWAY').AsString;
cdsMaster.FieldByName('fsourcebillid').AsString := cdsSaleOrderList.FieldByName('BILLFID').AsString;
cdsMaster.FieldByName('FORDERCUSTOMERID').AsString := cdsSaleOrderList.fieldbyname('custFID').AsString; //客户
cdsMaster.FieldByName('FWAREHOUSEID').AsString := Self.OutWarehouseFID ; //发货仓
cdsMaster.FieldByName('FINWAREHOUSEID').AsString := cdsSaleOrderList.FieldByName('inWarhFID').AsString; //收货仓
cdsMaster.FieldByName('CFSALETYPE').AsString := cdsSaleOrderList.FieldByName('CFSALETYPE').AsString; //销售类型
cdsMaster.FieldByName('CFORDERTYPEID').AsString := cdsSaleOrderList.FieldByName('CFORDERTYPEID').AsString; //订单类型
cdsMaster.FieldByName('CFPRICETYPEID').AsString := cdsSaleOrderList.FieldByName('CFPRICETYPEID').AsString; //价格类型
cdsMaster.FieldByName('CFSHIPTYPE').AsString := lcb_ShopType.EditingValue; //发货类型
cdsMaster.Post;
//明细表
cdsSaleOrderList.First;
while not cdsSaleOrderList.Eof do
begin
FQty := cdsSaleOrderList.fieldbyname('FQty').AsInteger;
cdsDetail.Append;
cdsDetail.FieldByName('FMATERIALID').Value := cdsSaleOrderList.FieldByName('FMATERIALID').Value;
cdsDetail.FieldByName('FUNITID').Value := cdsSaleOrderList.FieldByName('FUNITID').Value;
cdsDetail.FieldByName('Fsourcebillid').AsString := cdsSaleOrderList.FieldByName('BILLFID').AsString;
cdsDetail.FieldByName('FSOURCEBILLNUMBER').Value := cdsSaleOrderList.FieldByName('fnumber').Value;
cdsDetail.FieldByName('FSOURCEBILLENTRYSEQ').Value := cdsSaleOrderList.FieldByName('EntrySeq').Value;
cdsDetail.FieldByName('FSOURCEBILLTYPEID').Value := cdsSaleOrderList.FieldByName('FBILLTYPEID').Value;
cdsDetail.FieldByName('fsourcebillentryid').Value := cdsSaleOrderList.FieldByName('EntryFID').Value;
cdsDetail.FieldByName('FWAREHOUSEID').Value := cdsSaleOrderList.FieldByName('outWarhFID').Value;
cdsDetail.FieldByName('CFCOLORID').Value := cdsSaleOrderList.FieldByName('CFCOLORID').Value;
cdsDetail.FieldByName('CFSIZESID').Value := cdsSaleOrderList.FieldByName('CFSIZESID').Value;
cdsDetail.FieldByName('CFPACKID').Value := cdsSaleOrderList.FieldByName('CFPACKID').Value;
cdsDetail.FieldByName('CFCUPID').Value := cdsSaleOrderList.FieldByName('CFCUPID').Value;
cdsDetail.FieldByName('FQTY').Value := FQty;
cdsDetail.FieldByName('FASSISTQTY').Value := FQty;
cdsDetail.FieldByName('FPRICE').Value := cdsSaleOrderList.FieldByName('FPRICE').Value;
cdsDetail.FieldByName('FAMOUNT').Value := cdsSaleOrderList.FieldByName('FActualPrice').AsFloat*FQty;
cdsDetail.FieldByName('CFPACKNUM').Value := cdsSaleOrderList.FieldByName('cfpacknum').Value;
cdsDetail.FieldByName('CFDPPRICE').Value := cdsSaleOrderList.FieldByName('CFDPPRICE').Value;
cdsDetail.FieldByName('cfdiscount').Value := cdsSaleOrderList.FieldByName('FDiscount').Value;
cdsDetail.FieldByName('FActualPrice').Value := cdsSaleOrderList.FieldByName('FActualPrice').Value;
cdsDetail.Post;
cdsSaleOrderList.Next;
end;
//BOTP关系表
cdsBOTP.Append;
cdsBOTP.FieldByName('FID').AsString := CliDM.GetEASSID('59302EC6');
cdsBOTP.FieldByName('FSRCENTITYID').AsString := 'C48A423A';
cdsBOTP.FieldByName('FDESTENTITYID').AsString := '9CA9D08F';
cdsBOTP.FieldByName('FSRCOBJECTID').AsString := SaleOrderFID;
cdsBOTP.FieldByName('FDESTOBJECTID').AsString := cdsMaster.fieldbyname('FID').AsString;
cdsBOTP.FieldByName('FDATE').AsDateTime := CliDM.Get_ServerTime;
cdsBOTP.FieldByName('FOPERATORID').AsString := UserInfo.LoginUser_FID;
cdsBOTP.FieldByName('FISEFFECTED').Value := 0 ;
//cdsBOTP.FieldByName('FBOTMAPPINGID').AsString :=
cdsBOTP.FieldByName('FTYPE').Value := 0 ;
cdsBOTP.FieldByName('FSRCBILLTYPEID').AsString := cdsSaleOrderList.fieldbyname('FBILLTYPEID').AsString;
cdsBOTP.FieldByName('FDESTBILLTYPEID').AsString := BillConst.BILLTYPE_AM;
cdsBOTP.Post;
//提交数据
try
if CliDM.Apply_Delta_Ex(_cdsSave,['t_Sd_Postrequisition','t_Sd_Postrequisitionentry','t_bot_relation'],ErrMsg) then
begin
Gio.AddShow('发货通知单'+cdsMaster.fieldbyname('Fnumber').AsString+'提交成功!');
BillNumberList.Add(cdsMaster.fieldbyname('fnumber').AsString);
end
else
begin
ShowMsg(Handle, '发货通知单'+cdsMaster.fieldbyname('Fnumber').AsString+'提交失败'+ErrMsg,[]);
Gio.AddShow('发货通知单'+cdsMaster.fieldbyname('Fnumber').AsString+'提交失败'+ErrMsg);
Exit;
end;
except
on E: Exception do
begin
ShowMsg(Handle, Self.Caption+'提交失败:'+e.Message,[]);
Abort;
end;
end;
end
else
if Self.FSaleType = 'ZY' then
begin
end
else
if Self.FSaleType = 'NB' then
begin
end;
end;
end;
cdsAllocation.EmptyDataSet;
cdsBillDetail.EmptyDataSet;
cdsMaterial.EmptyDataSet;
cdsEntry.EmptyDataSet;
cdsBilllist.EmptyDataSet;
btn_Reset.Click; //重置
if BillNumberList.Count > 0 then
begin
ShowListMsg('生成下流单据成功,共计生成 '+inttostr(BillNumberList.Count)+' 张单据,单据编号如下!',BillNumberList);
CheckedBillFIDList.Clear;
CheckedMaterFIDList.Clear;
mPage.ActivePageIndex := 0;
end
else
ShowMsg(Handle, '没有生成单据!',[]);
finally
BillNumberList.Free;
Screen.Cursor := crDefault;
end;
end;
procedure TBillDistributionFrm.cdsMasterNewRecord(DataSet: TDataSet);
var sBillFlag,ErrMsg:string;
begin
inherited;
if FindRecord1(CliDM.cdsBillType,'FID',BillConst.BILLTYPE_AM,1) then
begin
sBillFlag := CliDM.cdsBillType.FieldByName('FBOSType').AsString ;
end;
with cdsMaster do
begin
FieldByName('FID').AsString := CliDM.GetEASSID('9CA9D08F');
FieldByName('FCREATETIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FNUMBER').AsString := CliDM.GetSCMBillNum(BillConst.BILLTYPE_AM,UserInfo.Branch_Flag,sBillFlag,true,ErrMsg);
FieldByName('FBIZDATE').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FCREATORID').AsString := UserInfo.LoginUser_FID;
FieldByName('FBASESTATUS').AsInteger := 1; //保存状态
FieldByName('FLASTUPDATEUSERID').AsString := UserInfo.LoginUser_FID;
FieldByName('FLASTUPDATETIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FMODIFIERID').AsString := UserInfo.LoginUser_FID;
FieldByName('FMODIFICATIONTIME').AsDateTime := CliDM.Get_ServerTime;
FieldByName('FCONTROLUNITID').AsString := UserInfo.FCONTROLUNITID; //控制单元,从服务器获取
FieldByName('FBILLTYPEID').AsString := BillConst.BILLTYPE_AM; ///单据类型
FieldByName('FBIZTYPEID').AsString := '00000000-0000-0000-0000-000000000000CCE7AED4'; //业务类型:210 普通销售
FieldByName('fstorageorgunitid').AsString := UserInfo.Branch_ID; //库存组织
FieldByName('fsaleorgunitid').AsString := UserInfo.Branch_ID; //销售组织
FieldByName('Fcompanyorgunitid').AsString := UserInfo.Branch_ID; //
FieldByName('FCurrencyID').AsString := BillConst.FCurrency; //币别
FieldByName('FExchangeRate').AsFloat := 1;
//FieldByName('CFINPUTWAY').AsString := 'NOTPACK';
end;
end;
procedure TBillDistributionFrm.cdsDetailNewRecord(DataSet: TDataSet);
begin
inherited;
DataSet.FieldByName('FID').AsString := CliDM.GetEASSID('CCFD4923');
DataSet.FieldByName('FParentID').AsString := cdsMaster.FieldByName('FID').AsString;
DataSet.FieldByName('FBaseStatus').AsInteger := 1;
DataSet.FieldByName('FOrderCustomerID').AsString := cdsMaster.fieldbyname('FORDERCUSTOMERID').AsString; //订货客户
DataSet.FieldByName('FDeliveryCustomerID').AsString := cdsMaster.fieldbyname('FORDERCUSTOMERID').AsString; //送货客户
DataSet.FieldByName('FReceiveCustomerID').AsString := cdsMaster.fieldbyname('FORDERCUSTOMERID').AsString; //应收客户
DataSet.FieldByName('FPaymentCustomerID').AsString := cdsMaster.fieldbyname('FORDERCUSTOMERID').AsString; //收款客户
DataSet.FieldByName('FIspresent').AsInteger := 0;
end;
procedure TBillDistributionFrm.cxAllocation_bandsEditing(
Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
var AAllow: Boolean);
var FocuField : string;
begin
inherited;
FocuField:= TcxGridDBBandedTableView(Sender).Columns[AItem.Index].DataBinding.FieldName;
if PosEx('FQTY_',FocuField) > 0 then
begin
if txt_InputWay.EditingValue = 'PACK' then
AAllow := False;
end;
if SameText(FocuField,'CFPACKNUM') then
begin
if (txt_InputWay.EditingValue = 'NOTPACK') then
AAllow := False;
end;
end;
procedure TBillDistributionFrm.cdsAllocationFQty_1Change(Sender: TField);
var index:string;
begin
inherited;
if (IsSupeControl) and (txt_InputWay.EditingValue='NOTPACK') then
begin
index := Copy(Sender.FieldName,6,Length(Sender.FieldName));
if Integer(Sender.NewValue) > cdsAllocation.FieldByName('FNotQty_'+index).AsInteger then
begin
Sender.DataSet.Cancel;
Application.ProcessMessages;
ShowMessage('配货数不能大于未配数:'+inttostr(cdsAllocation.FieldByName('FNotQty_'+index).AsInteger)+' ! ');
end;
end;
end;
procedure TBillDistributionFrm.cdsAllocationCFPACKNUMChange(
Sender: TField);
begin
inherited;
if IsSupeControl then
begin
if Integer(Sender.NewValue) > cdsAllocation.FieldByName('CFNotPACKNUM').AsInteger then
begin
Sender.DataSet.Cancel;
Application.ProcessMessages;
ShowMessage('配货箱数不能大于未配箱数:'+inttostr(cdsAllocation.FieldByName('CFNotPACKNUM').AsInteger)+' ! ');
end;
end;
end;
procedure TBillDistributionFrm.GetqrySizegrouppackallot;
var _SQL : string;
begin
_SQL :=' select m.cfsizegroupid, a.cfsizeid, a.cfiamount,a.fseq as showIndex from ct_bas_sizegrouppackallot a '
+' left join t_bd_material m on a.fparentid=m.cfsizegroupid '
+' where m.fid in ('+GetSqlForList(CheckedMaterFIDList)+')';
qrySizegrouppackallot := TADOQuery(CliDM.Client_QuerySQL(_SQL));
end;
function TBillDistributionFrm.GetPackAllotAmount(FSizegroupFID: string;
ShowIndex: Integer): Integer;
begin
Result := 0;
qrySizegrouppackallot.First;
while not qrySizegrouppackallot.Eof do
begin
if (qrySizegrouppackallot.fieldbyname('cfsizegroupid').AsString = FSizegroupFID)
and (qrySizegrouppackallot.fieldbyname('showIndex').AsInteger = ShowIndex)
then
begin
Result := qrySizegrouppackallot.fieldbyname('cfiamount').AsInteger;
Exit;
end;
qrySizegrouppackallot.Next;
end;
end;
procedure TBillDistributionFrm.cdsAllocationCFPACKNUMValidate(
Sender: TField);
var i:Integer;
begin
inherited;
if txt_InputWay.EditingValue <> 'NOTPACK' then
begin
cdsAllocation.Edit;
for i := 1 to Self.MaxSizeCount do
begin
cdsAllocation.FieldByName('FQty_'+inttostr(i)).AsInteger := Sender.AsInteger*GetPackAllotAmount(cdsAllocation.fieldbyname('cfsizegroupid').AsString,i);
end;
end;
end;
procedure TBillDistributionFrm.txt_InputWayPropertiesChange(
Sender: TObject);
begin
inherited;
SetNotPackCompent;
end;
procedure TBillDistributionFrm.cxButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
with Get_BIZSALEORG_Show('销售组织','') do
begin
if not IsEmpty then
begin
Self.FSaleOrgFID := fieldbyname('FID').AsString;
txt_SaleOrg.Text := fieldbyname('fname_l2').AsString;
end;
end;
end;
procedure TBillDistributionFrm.txt_SaleOrgKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key <> #8 then Key := #0
else
begin
self.FSaleOrgFID := '';
txt_SaleOrg.Text := '';
end;
end;
function TBillDistributionFrm.GetSaleType(FSaleOrgID,
FCustmerID: string): string;
var CompanyID,CustmerCompanyID,_SQL,ErrMsg:string;
cds:TClientDataSet;
begin
try
cds := TClientDataSet.Create(nil);
Get_BizFindFinOrg(2,FSaleOrgID,'T_ORg_sale',ErrMsg,cds);
if ErrMsg <> '' then
begin
ShowMsg(self.Handle,'获取财务组织出错:'+ErrMsg,[]);
Exit;
end;
CompanyID := cds.fieldbyname('FID').AsString;
_SQL := 'select finternalcompanyid from t_bd_customer where fid='+Quotedstr(FCustmerID);
if not CliDM.Get_OpenSQL(cds,_SQL,ErrMsg) then
begin
ShowMsg(self.Handle,'获取客户对应的财务组织出错:'+ErrMsg,[]);
Exit;
end;
CustmerCompanyID := '';
if not cds.IsEmpty then
begin
CustmerCompanyID := cds.fieldbyname('finternalcompanyid').AsString;
end;
if CompanyID = CustmerCompanyID then
Result := 'ZY' //直营单据,一般用于备货及直营单店订货
else
if CustmerCompanyID <> '' then
Result := 'NB' //内部客户单据
else
if CustmerCompanyID = '' then
Result := 'QD'; //外部客户单据
finally
cds.Free;
end;
end;
function TBillDistributionFrm.GetAllocationTable(SaleType:string): string;
begin
if SaleType = 'ZY' then
Result := 't_im_stocktransferbillentry' //直营单据,一般用于备货及直营单店订货
else
if SaleType = 'NB' then
Result := 'T_IM_TransferOrderBillEntry' //内部客户单据
else
if SaleType = 'QD' then
Result := 't_Sd_Postrequisitionentry'; //外部客户单据
end;
end.
|
unit GetImage;
interface
uses
System.Classes;
type
{$METHODINFO ON}
TPegaImagem = class
private
procedure SendContent(AContent: TStringStream);
public
procedure RotinaOriginal(const AID: string);
procedure RotinaProposta(const AID: string);
procedure RotinaNovaImagem;
end;
{$METHODINFO OFF}
implementation
{ TPegaImagem }
uses
Data.DBXPlatform,
System.SysUtils,
Rules,
Original,
Proposal;
procedure TPegaImagem.RotinaNovaImagem;
var
oContent: TStringStream;
begin
oContent := TStringStream.Create(EmptyStr, TEncoding.GetEncoding('iso-8859-1'));
oContent.LoadFromFile('E:\exemplo_sismic_image\images\nova_imagem.jpg');
Self.SendContent(oContent);
end;
procedure TPegaImagem.RotinaOriginal(const AID: string);
var
sImagem : string;
fHandler: TextFile;
begin
AssignFile(fHandler, Format('E:\exemplo_sismic_image\images\%s.txt', [AID]));
try
Reset(fHandler);
Readln(fHandler, sImagem);
Self.SendContent(Original.SendImageWithMIMEType(sImagem));
finally
CloseFile(fHandler);
end;
end;
procedure TPegaImagem.RotinaProposta(const AID: string);
var
sImagem: string;
begin
sImagem := Proposal.Bytes2TXT(Format('E:\exemplo_sismic_image\images\%s.jpg', [AID]));
Self.SendContent(Proposal.TXT2Bytes(sImagem));
end;
procedure TPegaImagem.SendContent(AContent: TStringStream);
var
oRetorno: TDSInvocationMetadata;
begin
AContent.Seek(0, 0);
oRetorno := GetInvocationMetadata;
oRetorno.ResponseMessage := 'OK';
oRetorno.ResponseCode := 200;
oRetorno.ResponseContentType := 'image/jpeg';
oRetorno.ResponseContent := AContent.DataString;
AContent.Free;
end;
end.
|
unit uHolidays;
interface
uses
Classes, ADODB;
type
THolidayItem = class(TCollectionItem)
private
FDate: TDateTime;
FIsRestday: boolean;
FIsHoliday: boolean;
public
property Date: TDateTime read FDate write FDate;
property IsRestday: boolean read FIsRestday write FIsRestday;
property IsHoliday: boolean read FIsHoliday write FIsHoliday;
end;
THolidayCollection = class(TCollection)
private
function GetItems(Index: integer): THolidayItem;
public
property Items[Index: integer]: THolidayItem read GetItems; default;
function Add: THolidayItem;
function FindItemByDate(ADate: TDateTime): THolidayItem;
end;
TYearItem = class(TCollectionItem)
private
FHolidays: THolidayCollection;
FLoadedFromDB: boolean;
FYear: integer;
protected
HolidaysTmp: THolidayCollection;
public
property Year: integer read FYear write FYear;
property Holidays: THolidayCollection read FHolidays;
property LoadedFromDB: boolean read FLoadedFromDB;
procedure LoadFromDB;
procedure SaveToDB;
procedure CreateNewItems;
procedure BeginEdit;
procedure ApplyEdit;
procedure RollbackEdit;
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
end;
TYearCollection = class(TCollection)
private
function GetItems(Index: integer): TYearItem;
public
property Items[Index: integer]: TYearItem read GetItems; default;
function Add: TYearItem;
procedure LoadFromDB;
end;
TCalendar = class
private
FYears: TYearCollection;
FCurrentYearIndex: integer;
function GetCurrentYear: TYearItem;
public
property Years: TYearCollection read FYears;
property CurrentYearIndex: integer read FCurrentYearIndex write FCurrentYearIndex;
property CurrentYear: TYearItem read GetCurrentYear;
function YearExists(AYear: integer; var AYearIndex: integer): boolean;
constructor Create; virtual;
destructor Destroy; override;
end;
implementation
uses SysUtils, DateUtils, GlobalVars, uCommonUtils;
{ THolidayCollection }
function THolidayCollection.Add: THolidayItem;
begin
result:=THolidayItem(inherited Add);
end;
function THolidayCollection.FindItemByDate(ADate: TDateTime): THolidayItem;
var
i: integer;
begin
result:=nil;
for i:=0 to Count-1 do
if Items[i].Date=ADate then begin
result:=Items[i];
break;
end;
end;
function THolidayCollection.GetItems(Index: integer): THolidayItem;
begin
result:=THolidayItem(inherited Items[Index]);
end;
{ TYearItem }
constructor TYearItem.Create(Collection: TCollection);
begin
inherited;
FLoadedFromDB:=false;
FHolidays:=THolidayCollection.Create(THolidayItem);
HolidaysTmp:=THolidayCollection.Create(THolidayItem);
end;
destructor TYearItem.Destroy;
begin
FHolidays.Free;
HolidaysTmp.Free;
inherited;
end;
procedure TYearItem.LoadFromDB;
var
qry: TAdoQuery;
hi: THolidayItem;
begin
qry:=CreateQuery('sp_sys_КалендарьДаты_получить @Год = '+IntToStr(Year));
try
Holidays.Clear;
qry.Open;
while not qry.Eof do begin
hi:=Holidays.Add;
hi.Date:=qry['Дата'];
hi.IsRestday:=true;
hi.IsHoliday:=false;
qry.Next;
end;
FLoadedFromDB:=true;
finally
qry.Free;
end;
end;
procedure TYearItem.SaveToDB;
var
i: integer;
sp: TAdoStoredProc;
begin
Connection.BeginTrans;
try
ExecSQL('sp_sys_КалендарьГода_удалить @Год = '+IntToStr(Year));
ExecSQL('sp_sys_КалендарьГода_добавить @Год = '+IntToStr(Year));
sp:=TADOStoredProc.Create(nil);
try
sp.Connection:=Connection;
sp.ProcedureName:='sp_sys_КалендарьДаты_добавить';
sp.Parameters.Refresh;
for i:=0 to Holidays.Count-1 do begin
sp.Parameters.FindParam('@Год').Value:=Year;
sp.Parameters.FindParam('@Дата').Value:=Holidays[i].Date;
sp.ExecProc;
end;
finally
sp.Free;
end;
Connection.CommitTrans;
except
Connection.RollbackTrans;
raise;
end;
end;
procedure TYearItem.CreateNewItems;
var
d1: TDateTime;
Item: THolidayItem;
begin
self.Holidays.Clear;
d1:=EncodeDate(Year, 1, 1);
while YearOf(d1)=Year do begin
if DayOfTheWeek(d1) in [6, 7] then begin
Item:=Holidays.Add;
Item.Date:=d1;
Item.IsRestday:=true;
Item.IsHoliday:=false;
// if DayOfTheWeek(d1)=6 then
// Item.IsHoliday:=true;
end;
d1:=IncDay(d1);
end;
FLoadedFromDB:=true;
SaveToDB;
end;
procedure TYearItem.BeginEdit;
var
i: integer;
hi: THolidayItem;
begin
HolidaysTmp.Clear;
for i:=0 to Holidays.Count-1 do begin
hi:=HolidaysTmp.Add;
hi.Date:=Holidays[i].Date;
hi.IsRestday:=Holidays[i].IsRestday;
hi.IsHoliday:=Holidays[i].IsHoliday;
end;
end;
procedure TYearItem.ApplyEdit;
begin
HolidaysTmp.Clear;
end;
procedure TYearItem.RollbackEdit;
var
i: integer;
hi: THolidayItem;
begin
Holidays.Clear;
for i:=0 to HolidaysTmp.Count-1 do begin
hi:=Holidays.Add;
hi.Date:=HolidaysTmp[i].Date;
hi.IsRestday:=HolidaysTmp[i].IsRestday;
hi.IsHoliday:=HolidaysTmp[i].IsHoliday;
end;
end;
{ TYearCollection }
function TYearCollection.Add: TYearItem;
begin
result:=TYearItem(inherited Add);
end;
function TYearCollection.GetItems(Index: integer): TYearItem;
begin
result:=TYearItem(inherited Items[Index]);
end;
procedure TYearCollection.LoadFromDB;
var
qry: TAdoQuery;
y: TYearItem;
begin
qry:=CreateQuery('sp_sys_КалендарьГода_получить');
try
qry.Open;
Clear;
while not qry.Eof do begin
y:=Add;
y.Year:=qry['Год'];
y.LoadFromDB;
qry.Next;
end;
finally
qry.Free;
end;
end;
{ TCalendar }
constructor TCalendar.Create;
begin
inherited;
FYears:=TYearCollection.Create(TYearItem);
end;
destructor TCalendar.Destroy;
begin
FYears.Free;
inherited;
end;
function TCalendar.GetCurrentYear: TYearItem;
begin
result:=nil;
if Years.Count>=1 then
result:=Years[self.CurrentYearIndex];
end;
function TCalendar.YearExists(AYear: integer; var AYearIndex: integer): boolean;
var
i: integer;
begin
result:=false;
AYearIndex:=-1;
for i:=0 to Years.Count-1 do
if Years[i].Year=AYear then begin
result:=true;
AYearIndex:=i;
break;
end;
end;
end.
|
// Bitmap Distribution Format
unit fi_bdf;
interface
uses
fi_common;
const
BDF_COPYRIGHT = 'COPYRIGHT';
BDF_FACE_NAME = 'FACE_NAME';
BDF_FAMILY_NAME = 'FAMILY_NAME';
BDF_FONT = 'FONT';
BDF_FONT_VERSION = 'FONT_VERSION';
BDF_FOUNDRY = 'FOUNDRY';
BDF_FULL_NAME = 'FULL_NAME';
BDF_WEIGHT_NAME = 'WEIGHT_NAME';
{
Fill empty family, style, and fullName with information from existing fields.
}
procedure BDF_FillEmpty(var info: TFontInfo);
implementation
uses
fi_info_reader,
line_reader,
classes,
strutils,
sysutils;
const
BDF_SIGN = 'STARTFONT';
NUM_FIELDS = 7;
MAX_LINES = 30;
procedure BDF_FillEmpty(var info: TFontInfo);
begin
if (info.family = '') and (info.psName <> '') then
info.family := info.psName;
if info.style = '' then
info.style := 'Medium';
if info.fullName = '' then
if info.style = 'Medium' then
info.fullName := info.family
else
info.fullName := info.family + ' ' + info.style;
end;
procedure ReadBDF(lineReader: TLineReader; var info: TFontInfo);
var
i: LongInt;
s: String;
sLen: SizeInt;
key: String;
p: SizeInt;
dst: PString;
numFound: LongInt;
begin
repeat
if not lineReader.ReadLine(s) then
raise EStreamError.Create('BDF is empty');
s := Trim(s);
until s <> '';
p := Pos(' ', s);
if (p = 0) or (Copy(s, 1, p - 1) <> BDF_SIGN) then
raise EStreamError.Create('Not a BDF font');
while s[p + 1] = ' ' do
Inc(p);
info.format := 'BDF' + Copy(s, p, Length(s) - p + 1);
i := 1;
numFound := 0;
while
(numFound < NUM_FIELDS)
and (i <= MAX_LINES)
and lineReader.ReadLine(s) do
begin
s := Trim(s);
case s of
'': continue;
'ENDPROPERTIES': break;
end;
if StartsStr('COMMENT', s) then
continue;
p := Pos(' ', s);
if p = 0 then
{
Assuming that global info goes before glyphs, all lines
(except comments, which can be empty) should be key-value
pairs separated by spaces.
}
raise EStreamError.CreateFmt('BDF has no space in line "%s"', [s]);
Inc(i);
key := Copy(s, 1, p - 1);
case key of
BDF_COPYRIGHT: dst := @info.copyright;
BDF_FAMILY_NAME: dst := @info.family;
BDF_FONT: dst := @info.psName;
BDF_FONT_VERSION: dst := @info.version;
BDF_FOUNDRY: dst := @info.manufacturer;
BDF_FULL_NAME, BDF_FACE_NAME: dst := @info.fullName;
BDF_WEIGHT_NAME: dst := @info.style;
'CHARS': break;
else
continue;
end;
repeat
Inc(p);
until s[p] <> ' ';
sLen := Length(s);
if (s[p] = '"') and (s[sLen] = '"') then
begin
Inc(p);
Dec(sLen);
end;
dst^ := Copy(s, p, sLen - (p - 1));
Inc(numFound);
end;
BDF_FillEmpty(info);
end;
procedure ReadBDFInfo(stream: TStream; var info: TFontInfo);
var
lineReader: TLineReader;
begin
lineReader := TLineReader.Create(stream);
try
ReadBDF(lineReader, info);
finally
lineReader.Free;
end;
end;
initialization
RegisterReader(@ReadBDFInfo, ['.bdf']);
end.
|
unit mrConfigFch;
interface
uses
SysUtils, Classes, uSystemTypes;
type
TmrConfigFch = class(TComponent)
private
FProviderName: String;
FConnection: String;
FConfirmApply: Boolean;
FConfirmCancel: Boolean;
FOnAfterAppend: TNotifyEvent;
FOnAfterApplyChanges: TNotifyEvent;
FOnAfterBrowse: TNotifyEvent;
FOnAfterEdit: TNotifyEvent;
FOnAfterNavigation: TNotifyEvent;
FOnAfterStart: TNotifyEvent;
FOnBeforeAppend: TNotifyEvent;
FOnBeforeApplyChanges: TOnBeforeApplyChanges;
FOnBeforeBrowse: TNotifyEvent;
FOnBeforeCancelChanges: TNotifyEvent;
FOnBeforeCommitTransaction: TNotifyEvent;
FOnBeforeEdit: TNotifyEvent;
FOnBeforeStart: TNotifyEvent;
FOnCreateLinks: TNotifyEvent;
FOnDestroyFch: TNotifyEvent;
FOnSetActiveTab: TOnSetActiveTab;
FOnSetPermissions: TNotifyEvent;
FOnVersionMode: TOnVersionModeEvent;
protected
{ Protected declarations }
public
procedure DoAfterStart;
procedure DoBeforeStart;
function DoBeforeApplyChanges: Boolean;
procedure DoAfterApplyChanges;
procedure DoBeforeCancelChanges;
procedure DoBeforeCommitTransaction;
procedure DoBeforeAppend;
procedure DoAfterNavigation;
procedure DoActiveTab(var TabIndex: Integer);
procedure DoDestroyFch;
published
property Connection: String read FConnection write FConnection;
property ProviderName: String read FProviderName write FProviderName;
property ConfirmApply: Boolean read FConfirmApply write FConfirmApply default False;
property ConfirmCancel: Boolean read FConfirmCancel write FConfirmCancel default False;
property OnAfterAppend: TNotifyEvent read FOnAfterAppend write FOnAfterAppend;
property OnAfterApplyChanges: TNotifyEvent read FOnAfterApplyChanges write FOnAfterApplyChanges;
property OnAfterBrowse: TNotifyEvent read FOnAfterBrowse write FOnAfterBrowse;
property OnAfterEdit: TNotifyEvent read FOnAfterEdit write FOnAfterEdit;
property OnAfterNavigation: TNotifyEvent read FOnAfterNavigation write FOnAfterNavigation;
property OnAfterStart: TNotifyEvent read FOnAfterStart write FOnAfterStart;
property OnBeforeAppend: TNotifyEvent read FOnBeforeAppend write FOnbeforeAppend;
property OnBeforeApplyChanges: TOnBeforeApplyChanges read FOnBeforeApplyChanges write FOnBeforeApplyChanges;
property OnBeforeBrowse: TNotifyEvent read FOnBeforeBrowse write FOnbeforeBrowse;
property OnBeforeCancelChanges: TNotifyEvent read FOnBeforeCancelChanges write FOnBeforeCancelChanges;
property OnBeforeCommitTransaction: TNotifyEvent read FOnBeforeCommitTransaction write FOnBeforeCommitTransaction;
property OnBeforeEdit: TNotifyEvent read FOnBeforeEdit write FOnbeforeEdit;
property OnBeforeStart: TNotifyEvent read FOnBeforeStart write FOnBeforeStart;
property OnCreateLinks: TNotifyEvent read FOnCreateLinks write FOnCreateLinks;
property OnDestroyFch: TNotifyEvent read FOnDestroyFch write FOnDestroyFch;
property OnSetActiveTab: TOnSetActiveTab read FOnSetActiveTab write FOnSetActiveTab;
property OnSetPermissions: TNotifyEvent read FOnSetPermissions write FOnSetPermissions;
property OnVersionMode: TOnVersionModeEvent read FOnVersionMode write FOnVersionMode;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('MultiTierLib', [TmrConfigFch]);
end;
{ TmrConfigFch }
procedure TmrConfigFch.DoDestroyFch;
begin
if Assigned(OnDestroyFch) then
OnDestroyFch(Self);
end;
procedure TmrConfigFch.DoBeforeCommitTransaction;
begin
if Assigned(OnBeforeCommitTransaction) then
OnBeforeCommitTransaction(Self);
end;
procedure TmrConfigFch.DoAfterApplyChanges;
begin
if Assigned(OnAfterApplyChanges) then
OnAfterApplyChanges(Self);
end;
procedure TmrConfigFch.DoBeforeStart;
begin
if Assigned(OnBeforeStart) then
OnBeforeStart(Self);
end;
procedure TmrConfigFch.DoAfterNavigation;
begin
if Assigned(OnAfterNavigation) then
OnAfterNavigation(Self);
end;
procedure TmrConfigFch.DoBeforeCancelChanges;
begin
if Assigned(OnBeforeCancelChanges) then
OnBeforeCancelChanges(Self);
end;
procedure TmrConfigFch.DoBeforeAppend;
begin
if Assigned(OnBeforeAppend) then
OnBeforeAppend(Self);
end;
function TmrConfigFch.DoBeforeApplyChanges: Boolean;
begin
Result := True;
if Assigned(OnBeforeApplyChanges) then
OnBeforeApplyChanges(Self, Result);
end;
procedure TmrConfigFch.DoAfterStart;
begin
if Assigned(OnAfterStart) then
OnAfterStart(Self);
end;
procedure TmrConfigFch.DoActiveTab(var TabIndex: Integer);
begin
if Assigned(FOnSetActiveTab) then
OnSetActiveTab(Self, TabIndex);
end;
end.
|
unit SynHighlighterVCP;
{$I SynEdit.inc}
interface
uses
SysUtils, Classes,
{$IFDEF SYN_KYLIX}
Qt, QControls, QGraphics,
{$ELSE}
Windows, Messages, Controls, Graphics, Registry,
{$ENDIF}
SynEditTypes, SynEditHighlighter;
type
TtkTokenKind = (tkNone,
tkKeyword,
tkInternalVar, tkLocalVar, tkGlobalVar, tkIOVar,
tkInternalConst, tkLocalConst, tkConst,
tkInternalFunc, tkLocalFunc, tkFunc,
tkComment, tkIdentifier, tkNull, tkNumber, tkSpace, tkString, tkSymbol, tkUnknown);
TCommentStyle = (csAnsiStyle, csPasStyle, csCStyle, csAsmStyle, csBasStyle);
CommentStyles = set of TCommentStyle;
TRangeState = (rsANil, rsAnsi, rsPasStyle, rsCStyle, rsUnKnown);
TStringDelim = (sdSingleQuote, sdDoubleQuote);
TProcTableProc = procedure of object;
type
TSynVCPSyn = class(TSynCustomHighlighter)
private
fRange: TRangeState;
fLine: PChar;
fProcTable: array[#0..#255] of TProcTableProc;
Run: LongInt;
fTokenPos: Integer;
fTokenID: TtkTokenKind;
fLineNumber : Integer;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fNumberAttri: TSynHighlighterAttributes;
fKeywordAttri: TSynHighlighterAttributes;
fVarsAttri: TSynHighlighterAttributes;
fInternalVarsAttri: TSynHighlighterAttributes;
fLocalVarsAttri: TSynHighlighterAttributes;
fGlobalVarsAttri: TSynHighlighterAttributes;
fIOVarsAttri: TSynHighlighterAttributes;
fInternalConstAttri: TSynHighlighterAttributes;
fLocalConstAttri: TSynHighlighterAttributes;
fConstAttri: TSynHighlighterAttributes;
fInternalFuncAttri: TSynHighlighterAttributes;
fLocalFuncAttri: TSynHighlighterAttributes;
fFuncAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
fSymbolAttri: TSynHighlighterAttributes;
fHLItems: TStrings;
fComments: CommentStyles;
fStringDelimCh: char;
fIdentChars: TSynIdentChars;
procedure AsciiCharProc;
procedure BraceOpenProc;
procedure PointCommaProc;
procedure CRProc;
procedure IdentProc;
procedure IntegerProc;
procedure LFProc;
procedure NullProc;
procedure NumberProc;
procedure RoundOpenProc;
procedure SlashProc;
procedure SpaceProc;
procedure StringProc;
procedure UnknownProc;
procedure MakeMethodTables;
procedure AnsiProc;
procedure PasStyleProc;
procedure CStyleProc;
procedure SetHLItems(const Value: TStrings);
procedure SetComments(Value: CommentStyles);
function GetStringDelim: TStringDelim;
procedure SetStringDelim(const Value: TStringDelim);
function GetIdentifierChars: string;
procedure SetIdentifierChars(const Value: string);
protected
function GetIdentChars: TSynIdentChars; override;
public
{$IFNDEF SYN_CPPB_1} class {$ENDIF}
function GetLanguageName: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
override;
function GetEol: Boolean; override;
function GetRange: Pointer; override;
function GetTokenID: TtkTokenKind;
function GetToken: String; override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: integer; override;
function GetTokenPos: Integer; override;
function IsKeyword(const AKeyword: string): boolean; override; //mh 2000-11-08
procedure Next; override;
procedure ResetRange; override;
procedure SetRange(Value: Pointer); override;
procedure SetLine(NewValue: String; LineNumber: Integer); override;
published
property Comments: CommentStyles read fComments write SetComments;
property IdentifierChars: string read GetIdentifierChars write SetIdentifierChars;
property HLItems: TStrings read fHLItems write SetHLItems;
property StringDelim: TStringDelim read GetStringDelim write SetStringDelim default sdSingleQuote;
property CommentAttri: TSynHighlighterAttributes read fCommentAttri write fCommentAttri;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri;
property NumberAttri: TSynHighlighterAttributes read fNumberAttri write fNumberAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri write fStringAttri;
property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri write fSymbolAttri;
property KeywordAttri: TSynHighlighterAttributes read fKeywordAttri write fKeywordAttri;
property VarsAttri: TSynHighlighterAttributes read fVarsAttri write fVarsAttri;
property InternalVarsAttri: TSynHighlighterAttributes read fInternalVarsAttri write fInternalVarsAttri;
property LocalVarsAttri: TSynHighlighterAttributes read fLocalVarsAttri write fLocalVarsAttri;
property GlobalVarsAttri: TSynHighlighterAttributes read fGlobalVarsAttri write fGlobalVarsAttri;
property IOVarsAttri: TSynHighlighterAttributes read fIOVarsAttri write fIOVarsAttri;
property InternalConstAttri: TSynHighlighterAttributes read fInternalConstAttri write fInternalConstAttri;
property LocalConstAttri: TSynHighlighterAttributes read fLocalConstAttri write fLocalConstAttri;
property ConstAttri: TSynHighlighterAttributes read fConstAttri write fConstAttri;
property InternalFuncAttri: TSynHighlighterAttributes read fInternalFuncAttri write fInternalFuncAttri;
property LocalFuncAttri: TSynHighlighterAttributes read fLocalFuncAttri write fLocalFuncAttri;
property FuncAttri: TSynHighlighterAttributes read fFuncAttri write fFuncAttri;
end;
implementation
uses
SynEditStrConst;
var
Identifiers: array[#0..#255] of ByteBool;
mHashTable: array[#0..#255] of Integer;
procedure MakeIdentTable;
var
I, J: Char;
begin
for I := #0 to #255 do
begin
Case I of
'_', '0'..'9', 'a'..'z', 'A'..'Z': Identifiers[I] := True;
else Identifiers[I] := False;
end;
J := UpCase(I);
Case I in ['_', 'a'..'z', 'A'..'Z'] of
True: mHashTable[I] := Ord(J) - 64
else mHashTable[I] := 0;
end;
end;
end;
function TSynVCPSyn.IsKeyword(const AKeyword: string): boolean;
var
First, Last, I, Compare: Integer;
Token: String;
begin
First := 0;
Last := fHLItems.Count - 1;
Result := False;
Token := UpperCase(AKeyword);
while First <= Last do
begin
I := (First + Last) shr 1;
Compare := CompareStr(fHLItems[i], Token);
if Compare = 0 then
begin
Result := True;
break;
end else
if Compare < 0 then First := I + 1 else Last := I - 1;
end;
end;
procedure TSynVCPSyn.MakeMethodTables;
var
I: Char;
begin
for I := #0 to #255 do
case I of
'#': fProcTable[I] := AsciiCharProc;
'{': fProcTable[I] := BraceOpenProc;
';': fProcTable[I] := PointCommaProc;
#13: fProcTable[I] := CRProc;
'A'..'Z', 'a'..'z', '_': fProcTable[I] := IdentProc;
'$': fProcTable[I] := IntegerProc;
#10: fProcTable[I] := LFProc;
#0: fProcTable[I] := NullProc;
'0'..'9': fProcTable[I] := NumberProc;
'(': fProcTable[I] := RoundOpenProc;
'/': fProcTable[I] := SlashProc;
#1..#9, #11, #12, #14..#32: fProcTable[I] := SpaceProc;
else fProcTable[I] := UnknownProc;
end;
fProcTable[fStringDelimCh] := StringProc;
end;
constructor TSynVCPSyn.Create(AOwner: TComponent);
function CreateKWList:TStringList;
begin
result:=TStringList.Create;
result.Sorted:=True;
result.Duplicates:=dupIgnore;
end;
function CreateAttri(Name:string; Fg,Bg:TColor; FontStyle:TFontStyles):TSynHighlighterAttributes;
begin
result:=TSynHighlighterAttributes.Create(Name);
result.Style:=FontStyle;
result.Foreground:=Fg;
result.Background:=Bg;
AddAttribute(result);
end;
begin
inherited Create(AOwner);
fHLItems:=CreateKWList;
fCommentAttri:=CreateAttri(SYNS_AttrComment,clGray,clWindow,[fsItalic]);
fIdentifierAttri:=CreateAttri(SYNS_AttrIdentifier,clBlack,clWindow,[]);
fKeywordAttri:=CreateAttri('Keyword',clBlue,clWindow,[]);
fVarsAttri:=CreateAttri('Variable',clGreen,clWindow,[]);
fInternalVarsAttri:=CreateAttri('Internal variable',clOlive,clWindow,[]);
fLocalVarsAttri:=CreateAttri('Local variable',clPurple,clWindow,[]);
fGlobalVarsAttri:=CreateAttri('Global variable',clTeal,clWindow,[]);
fIOVarsAttri:=CreateAttri('I/O variable',clLime,clWindow,[]);
fInternalConstAttri:=CreateAttri('Internal constant',clFuchsia,clWindow,[]);
fLocalConstAttri:=CreateAttri('Local constant',clAqua,clWindow,[]);
fConstAttri:=CreateAttri('Constant',clRed,clWindow,[]);
fInternalFuncAttri:=CreateAttri('Internal function',clSilver,clWindow,[]);
fLocalFuncAttri:=CreateAttri('Local function',clGray,clWindow,[]);
fFuncAttri:=CreateAttri('Function',clYellow,clWindow,[]);
fNumberAttri:=CreateAttri(SYNS_AttrNumber,clRed,clWindow,[]);
fSpaceAttri:=CreateAttri(SYNS_AttrSpace,clWindowText,clWindow,[]);
fStringAttri:=CreateAttri(SYNS_AttrString,clMaroon,clWindow,[]);
fSymbolAttri:=CreateAttri(SYNS_AttrSymbol,clGray,clWindow,[]);
SetAttributesOnChange(DefHighlightChange);
fStringDelimCh := '''';
fIdentChars := inherited GetIdentChars;
MakeMethodTables;
fRange := rsUnknown;
end; { Create }
destructor TSynVCPSyn.Destroy;
begin
fHLItems.Free;
inherited Destroy;
end; { Destroy }
procedure TSynVCPSyn.SetLine(NewValue: String; LineNumber:Integer);
begin
fLine := PChar(NewValue);
Run := 0;
fLineNumber := LineNumber;
Next;
end; { SetLine }
procedure TSynVCPSyn.AnsiProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else
fTokenID := tkComment;
repeat
if (fLine[Run] = '*') and (fLine[Run + 1] = ')') then begin
fRange := rsUnKnown;
Inc(Run, 2);
break;
end;
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
end;
procedure TSynVCPSyn.PasStyleProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else
fTokenID := tkComment;
repeat
if fLine[Run] = '}' then begin
fRange := rsUnKnown;
Inc(Run);
break;
end;
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
end;
procedure TSynVCPSyn.CStyleProc;
begin
case fLine[Run] of
#0: NullProc;
#10: LFProc;
#13: CRProc;
else
fTokenID := tkComment;
repeat
if (fLine[Run] = '*') and (fLine[Run + 1] = '/') then begin
fRange := rsUnKnown;
Inc(Run, 2);
break;
end;
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
end;
procedure TSynVCPSyn.AsciiCharProc;
begin
fTokenID := tkString;
repeat
inc(Run);
until not (fLine[Run] in ['0'..'9']);
end;
procedure TSynVCPSyn.BraceOpenProc;
begin
if csPasStyle in fComments then
begin
fTokenID := tkComment;
fRange := rsPasStyle;
inc(Run);
while FLine[Run] <> #0 do
case FLine[Run] of
'}':
begin
fRange := rsUnKnown;
inc(Run);
break;
end;
#10: break;
#13: break;
else inc(Run);
end;
end else
begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
procedure TSynVCPSyn.PointCommaProc;
begin
if (csASmStyle in fComments) or (csBasStyle in fComments) then
begin
fTokenID := tkComment;
fRange := rsUnknown;
inc(Run);
while FLine[Run] <> #0 do
begin
fTokenID := tkComment;
inc(Run);
end;
end else
begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
procedure TSynVCPSyn.CRProc;
begin
fTokenID := tkSpace;
Inc(Run);
if fLine[Run] = #10 then Inc(Run);
end;
procedure TSynVCPSyn.IdentProc;
function FindWhatIs(const AKeyword: string):TtkTokenKind;
var
First, Last, I, Compare: Integer;
Token: String;
begin
First := 0;
Last := fHLItems.Count - 1;
Result := tkIdentifier;
Token := UpperCase(AKeyword);
while First <= Last do
begin
I := (First + Last) shr 1;
Compare := CompareStr(fHLItems[i], Token);
if Compare = 0 then
begin
Result:=TtkTokenKind(fHLItems.Objects[i]);
BREAK;
end else
if Compare < 0 then First := I + 1 else Last := I - 1;
end;
end;
begin
while Identifiers[fLine[Run]] do inc(Run);
fTokenId:=FindWhatIs(GetToken);
end;
procedure TSynVCPSyn.IntegerProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in ['0'..'9', 'A'..'F', 'a'..'f'] do inc(Run);
end;
procedure TSynVCPSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TSynVCPSyn.NullProc;
begin
fTokenID := tkNull;
end;
procedure TSynVCPSyn.NumberProc;
begin
inc(Run);
fTokenID := tkNumber;
while FLine[Run] in ['0'..'9', '.', 'e', 'E', 'x'] do
begin
case FLine[Run] of
'x': begin // handle C style hex numbers
IntegerProc;
break;
end;
'.':
if FLine[Run + 1] = '.' then break;
end;
inc(Run);
end;
end;
procedure TSynVCPSyn.RoundOpenProc;
begin
inc(Run);
if csAnsiStyle in fComments then
begin
case fLine[Run] of
'*':
begin
fTokenID := tkComment;
fRange := rsAnsi;
inc(Run);
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = ')' then
begin
fRange := rsUnKnown;
inc(Run, 2);
break;
end else inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end;
'.':
begin
inc(Run);
fTokenID := tkSymbol;
end;
else
begin
FTokenID := tkSymbol;
end;
end;
end else fTokenId := tkSymbol;
end;
procedure TSynVCPSyn.SlashProc;
begin
case FLine[Run + 1] of
'/':
begin
inc(Run, 2);
fTokenID := tkComment;
while FLine[Run] <> #0 do
begin
case FLine[Run] of
#10, #13: break;
end;
inc(Run);
end;
end;
'*':
begin
if csCStyle in fComments then
begin
fTokenID := tkComment;
fRange := rsCStyle;
inc(Run);
while fLine[Run] <> #0 do
case fLine[Run] of
'*':
if fLine[Run + 1] = '/' then
begin
fRange := rsUnKnown;
inc(Run, 2);
break;
end else inc(Run);
#10: break;
#13: break;
else inc(Run);
end;
end
else
begin
inc(Run);
fTokenId := tkSymbol;
end;
end;
else
begin
inc(Run);
fTokenID := tkSymbol;
end;
end;
end;
procedure TSynVCPSyn.SpaceProc;
begin
inc(Run);
fTokenID := tkSpace;
while FLine[Run] in [#1..#9, #11, #12, #14..#32] do inc(Run);
end;
procedure TSynVCPSyn.StringProc;
begin
fTokenID := tkString;
if (fLine[Run + 1] = fStringDelimCh) and (fLine[Run + 2] = fStringDelimCh) then
Inc(Run, 2);
repeat
case FLine[Run] of
#0, #10, #13: break;
end;
inc(Run);
until FLine[Run] = fStringDelimCh;
if FLine[Run] <> #0 then inc(Run);
end;
procedure TSynVCPSyn.UnknownProc;
begin
inc(Run);
fTokenID := tkUnKnown;
end;
procedure TSynVCPSyn.Next;
begin
fTokenPos := Run;
case fRange of
rsAnsi: AnsiProc;
rsPasStyle: PasStyleProc;
rsCStyle: CStyleProc;
else
fProcTable[fLine[Run]];
end;
end;
function TSynVCPSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_KEYWORD: Result := fKeywordAttri;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
else
Result := nil;
end;
end;
function TSynVCPSyn.GetEol: Boolean;
begin
Result := fTokenId = tkNull;
end;
function TSynVCPSyn.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
function TSynVCPSyn.GetToken: String;
var
Len: LongInt;
begin
Len := Run - fTokenPos;
SetString(Result, (FLine + fTokenPos), Len);
end;
function TSynVCPSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TSynVCPSyn.GetTokenAttribute: TSynHighlighterAttributes;
begin
case fTokenID of
tkComment: Result := fCommentAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKeyword: Result := fKeywordAttri;
tkInternalVar: Result := fInternalVarsAttri;
tkLocalVar: Result := fLocalVarsAttri;
tkGlobalVar: Result := fGlobalVarsAttri;
tkIOVar: Result := fIOVarsAttri;
tkInternalConst: Result := fInternalConstAttri;
tkLocalConst: Result := fLocalConstAttri;
tkConst: Result := fConstAttri;
tkInternalFunc: Result := fInternalFuncAttri;
tkLocalFunc: Result := fLocalFuncAttri;
tkFunc: Result := fFuncAttri;
tkNumber: Result := fNumberAttri;
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkUnknown: Result := fSymbolAttri;
else
Result := nil;
end;
end;
function TSynVCPSyn.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
function TSynVCPSyn.GetTokenPos: Integer;
begin
Result := fTokenPos;
end;
procedure TSynVCPSyn.ReSetRange;
begin
fRange := rsUnknown;
end;
procedure TSynVCPSyn.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
procedure TSynVCPSyn.SetHLItems(const Value: TStrings);
var
i: Integer;
begin
(*
if Value <> nil then
begin
Value.BeginUpdate;
for i := 0 to Value.Count - 1 do
Value[i] := UpperCase(Value[i]);
Value.EndUpdate;
end;
*)
fHLItems.Assign(Value);
DefHighLightChange(nil);
end;
procedure TSynVCPSyn.SetComments(Value: CommentStyles);
begin
fComments := Value;
DefHighLightChange(nil);
end;
{$IFNDEF SYN_CPPB_1} class {$ENDIF}
function TSynVCPSyn.GetLanguageName: string;
begin
Result := SYNS_LangGeneral;
end;
function TSynVCPSyn.GetStringDelim: TStringDelim;
begin
if fStringDelimCh = '''' then
Result := sdSingleQuote
else
Result := sdDoubleQuote;
end;
procedure TSynVCPSyn.SetStringDelim(const Value: TStringDelim);
var
newCh: char;
begin
case Value of
sdSingleQuote: newCh := '''';
else newCh := '"';
end; //case
if newCh <> fStringDelimCh then begin
fStringDelimCh := newCh;
MakeMethodTables;
end;
end;
function TSynVCPSyn.GetIdentifierChars: string;
var
ch: char;
s: shortstring;
begin
s := '';
for ch := #0 to #255 do
if ch in fIdentChars then s := s + ch;
Result := s;
end;
procedure TSynVCPSyn.SetIdentifierChars(const Value: string);
var
i: integer;
begin
fIdentChars := [];
for i := 1 to Length(Value) do begin
fIdentChars := fIdentChars + [Value[i]];
end; //for
end;
function TSynVCPSyn.GetIdentChars: TSynIdentChars;
begin
Result := fIdentChars;
end;
initialization
MakeIdentTable;
{$IFNDEF SYN_CPPB_1}
RegisterPlaceableHighlighter(TSynVCPSyn);
{$ENDIF}
end.
|
unit ComDllPub;
interface
uses Forms,Windows,COMObj,FNMFacade_TLB,DBClient,FNMDAO_TLB, Variants,XMLIntf, XMLDoc,SysUtils,StrUtils;
{$WARN SYMBOL_PLATFORM OFF}
function GetLibraryFullPath(sLibraryName: string): string;
function GetConnectionString(sLibraryName: string;sSystemId: string): string;
function GetHostName():string;
function ComConnect(ClassID: TGUID): IDispatch; // 创建联接
function ServerObj:IFNMFacadeLibDisp;
function FNMDAOInfo:IFNMDAOInfoDisp;
function FNMDAOUpt:IFNMDAOUptDisp;
function ThirdDAOInfo:IThirdDAOInfoDisp;
function ThirdDAOUpt:IThirdDAOUptDisp;
implementation
//获取当前机器名称
function GetHostName():string ;
var
HostName: PChar;
Size: DWord;
begin
GetMem(HostName, 255);
Size := 255;
try
try
if GetComputerName(HostName, Size) = False then
begin
FreeMem(HostName);
Exit;
end;
result:= HostName;
except
raise Exception.Create('获取服务器名称失败!');
end;
finally
FreeMem(HostName);
end;
end;
//该函数根据com+执行的库文件名称,找到该库文件物理路经,再找到放置连接
//属性的xml文件(该文件相对库文件路径的位置是 ..\Configer\系统名称.XML),
//最后读出连接属性构造一个完整的连接字符串
function GetConnectionString(sLibraryName: string;sSystemId: string): string;
var
ANode: IXMLNode;
xmlDoc: TXMLDocument;
iStringLength:integer;
connXMLFile,ConfigerFilePath,LibraryFullPath,ServerName,DatabaseName,UserID,Password,TimeOut: string;
begin
LibraryFullPath:=GetLibraryFullPath(sLibraryName);
if Rightstr(LibraryFullPath,1)=':' then
ConfigerFilePath:=LibraryFullPath+'\Configer\'
else
begin
iStringLength:=Length(LibraryFullPath);
while (iStringLength>=1) do
begin
if Midstr(LibraryFullPath,iStringLength,1)='\' then
break
else
iStringLength:=iStringLength-1;
end;
ConfigerFilePath:=Copy(LibraryFullPath,1,iStringLength-1)+'\Configer\';
end;
connXMLFile:=ConfigerFilePath+sSystemId+'.XML';
xmlDoc := TXMLDocument.Create(Application);
xmlDoc.FileName :=connXMLFile;
xmlDoc.Active :=true;
try
ANode:=xmlDoc.ChildNodes.FindNode('WMIS');
ANode:=ANode.ChildNodes.FindNode('Connection');
ServerName:=ANode.Attributes['ServerName'];
DatabaseName:=ANode.Attributes['DatabaseName'];
UserId:=ANode.Attributes['UserId'];
Password:=Anode.Attributes['Password'];
TimeOut:=inttostr(ANode.Attributes['TimeOut']);
finally
xmlDoc.Active := False;
xmlDoc.Free;
end;
Result :=
'Provider=SQLOLEDB.1;Password=' + Password +
';Persist Security Info=True;User ID=' + UserID +
';Initial Catalog=' + DatabaseName +
';Data Source=' + ServerName +
';Connect TimeOut='+TimeOut+
';Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;' +
'Use Encryption for Data=False;Tag with column collation when possible=False';
end;
//该函数根据com+组件实际调用的动态库文件名称,返回该文件的物理路径
function GetLibraryFullPath(sLibraryName: string): string;
var
hModule: THandle;
buff: array[0..255] of Char;
sFullName:string;
begin
hModule := GetModuleHandle(pChar(sLibraryName));
GetModuleFileName(hModule, buff, sizeof(buff));
sFullName:=buff;
result:=Copy(sFullName,1,Length(sFullName)-Length(sLibraryName)-1);
end;
function ComConnect(ClassID: TGUID): IDispatch;
begin
Result := CreateRemoteComObject(GetHostName, ClassID) as IDispatch;
end;
function ServerObj:IFNMFacadeLibDisp;
begin
Result := IFNMFacadeLibDisp(ComConnect(CLASS_FNMFacadeLib));
end;
function FNMDAOInfo:IFNMDAOInfoDisp;
begin
Result := IFNMDAOInfoDisp(ComConnect(CLASS_FNMDAOInfo));
end;
function FNMDAOUpt:IFNMDAOUptDisp;
begin
Result := IFNMDAOUptDisp(ComConnect(CLASS_FNMDAOUpt));
end;
function ThirdDAOInfo:IThirdDAOInfoDisp;
begin
Result := IThirdDAOInfoDisp(ComConnect(CLASS_ThirdDAOInfo));
end;
function ThirdDAOUpt:IThirdDAOUptDisp;
begin
Result := IThirdDAOUptDisp(ComConnect(CLASS_ThirdDAOUpt));
end;
end.
|
// ----------- Parse::Easy::Runtime -----------
// https://github.com/MahdiSafsafi/Parse-Easy
// --------------------------------------------
unit Parse.Easy.Parser.GLR;
interface
uses
System.SysUtils,
System.Classes,
Parse.Easy.StackPtr,
Parse.Easy.Lexer.CustomLexer,
Parse.Easy.Lexer.Token,
Parse.Easy.Parser.CustomParser,
Parse.Easy.Parser.State,
Parse.Easy.Parser.Rule,
Parse.Easy.Parser.Action;
type
TGLR = class;
PFrame = ^TFrame;
TFrame = record
public
function Peek(): TToken;
function Advance(): TToken;
var
Parser: TGLR;
Alive: Boolean;
Reduce: Boolean;
Link: PFrame;
Parent: PFrame;
State: TState;
TokenCacheIndex: Integer;
NumberOfChilds: Integer;
case Boolean { Reduce } of
False: (Token: TToken);
True: (Rule: TRule);
end;
TGLR = class(TCustomParser)
private
FFramePool: PFrame;
FNumberOfFrameInCurrentPool: Integer;
FStop: PFrame;
FConflicts: Integer;
FGarbageFrameList: TStackPtr;
FFramePoolList: TList;
FTokenCache: TList;
FFrames: TList;
FShiftActionList: TList;
FPostponedRules: TList;
protected
procedure Merge(Frame: PFrame);
procedure Vanish(Frame: PFrame);
procedure NewFramePool();
procedure CleanFramePools();
function NewFrame(): PFrame;
function Consume(): TToken;
function Reduce(Frame: PFrame; Rule: TRule): Boolean;
function Shift(Frame: PFrame; State: TState): Boolean;
public
constructor Create(ALexer: TCustomLexer); override;
destructor Destroy(); override;
function Parse(): Boolean; override;
end;
implementation
const
SizeOfFramePool = 1040;
NumberOfFramePerPool = SizeOfFramePool div SizeOf(TFrame);
{ TGLR }
constructor TGLR.Create(ALexer: TCustomLexer);
begin
inherited;
FFramePoolList := TList.Create;
FTokenCache := TList.Create;
FFrames := TList.Create;
FShiftActionList := TList.Create;
FPostponedRules := TList.Create;
FGarbageFrameList := TStackPtr.Create;
FFramePool := nil;
end;
destructor TGLR.Destroy();
begin
CleanFramePools();
FFramePoolList.Free();
FTokenCache.Free();
FFrames.Free();
FShiftActionList.Free();
FPostponedRules.Free();
FGarbageFrameList.Free();
inherited;
end;
procedure TGLR.CleanFramePools();
var
I: Integer;
P: Pointer;
begin
for I := 0 to FFramePoolList.Count - 1 do
begin
P := FFramePoolList[I];
if Assigned(P) then
FreeMem(P, SizeOfFramePool);
end;
FFramePoolList.Clear();
FFramePool := nil;
end;
function TGLR.Consume(): TToken;
begin
Lexer.Advance();
Result := Lexer.Peek();
FTokenCache.Add(Result);
end;
function TGLR.NewFrame(): PFrame;
begin
if FGarbageFrameList.Count > 0 then
Exit(FGarbageFrameList.Pop());
if not Assigned(FFramePool) then
NewFramePool();
Result := FFramePool;
Inc(FNumberOfFrameInCurrentPool);
Inc(FFramePool);
if (FNumberOfFrameInCurrentPool = NumberOfFramePerPool) then
begin
NewFramePool();
end;
end;
procedure TGLR.NewFramePool();
begin
FNumberOfFrameInCurrentPool := 0;
FFramePool := GetMemory(SizeOfFramePool);
FFramePoolList.Add(FFramePool);
end;
procedure TGLR.Vanish(Frame: PFrame);
begin
Dec(FConflicts);
while (Assigned(Frame)) do
begin
if Frame^.NumberOfChilds > 1 then
Break;
Frame^.Alive := False;
Frame := Frame^.Parent;
end;
end;
function TGLR.Reduce(Frame: PFrame; Rule: TRule): Boolean;
var
PopCount: Integer;
Target: PFrame;
State: TState;
Actions: TList;
Action: TAction;
LFrame: PFrame;
begin
if (rfAccept in Rule.Flags) then
begin
// this is the axiom rule.
Exit(True);
end;
Target := Frame;
PopCount := Rule.NumberOfItems;
while (PopCount <> 0) do
begin
if not Assigned(Target) then
Exit(False);
Target := Target^.Link;
Dec(PopCount);
end;
if (not Assigned(Target) or (not Target^.Alive)) then
Exit(False);
State := Target^.State;
Actions := State.NoTerms[Rule.Id];
Assert(Actions.Count = 1);
Action := Actions[0];
Assert(Action.ActionType = atJump);
State := States[Action.ActionValue];
Result := Shift(Frame, State);
LFrame := FFrames.Last();
LFrame^.Link := Target; // link to the stack of the previous frame.
LFrame^.Reduce := True; // mark the frame as reduce.
LFrame^.Rule := Rule;
end;
function TGLR.Shift(Frame: PFrame; State: TState): Boolean;
var
New: PFrame;
begin
New := Self.NewFrame();
New^.Alive := True;
New^.Reduce := False;
New^.Parser := Self;
New^.Parent := Frame;
New^.State := State;
New^.TokenCacheIndex := Frame^.TokenCacheIndex;
New^.NumberOfChilds := 0;
New^.Link := Frame;
New^.Token := Frame^.Peek();
FFrames.Add(New);
Result := True;
end;
procedure TGLR.Merge(Frame: PFrame);
var
LFrame: PFrame;
I, J: Integer;
PopCount: Integer;
Rule: TRule;
Value: PValue;
begin
// we dont merge if things are not clear yet.
if FConflicts > 0 then
Exit;
FPostponedRules.Clear;
LFrame := Frame;
while (Assigned(LFrame) and (LFrame <> FStop)) do
begin
if (LFrame^.Alive) then
begin
if (LFrame^.Reduce) then
begin
FPostponedRules.Add(LFrame);
end
else
begin
Value := NewValue();
Value^.AsToken := LFrame^.Token;
Values.Push(Value);
end;
end
else
begin
// fixme
FGarbageFrameList.Push(LFrame);
end;
// go back to the caller.
LFrame := LFrame^.Parent;
end;
// now everything is clear, we are safe
// to execute rule's action.
for I := 0 to FPostponedRules.Count - 1 do
begin
LFrame := FPostponedRules[I];
Rule := LFrame^.Rule;
PopCount := Rule.NumberOfItems;
if (Rule.ActionIndex <> -1) then
begin
ReturnValue := NewValue();
UserAction(Rule.ActionIndex);
end;
// remove rule's items from the stack values.
for J := 0 to PopCount - 1 do
begin
Values.Pop();
end;
Values.Push(ReturnValue);
end;
// the next merge session will stop when it sees this frame.
FStop := Frame;
end;
function TGLR.Parse(): Boolean;
var
Frame: PFrame;
State: TState;
Token: TToken;
Actions: TList;
Action: TAction;
I: Integer;
J: Integer;
Rule: TRule;
LFrame: PFrame;
EFrame: PFrame;
begin
Result := False;
if States.Count = 0 then
Exit;
FConflicts := 0;
I := 0;
FStop := nil;
EFrame := nil;
Token := nil;
CleanFramePools();
FFrames.Clear();
FTokenCache.Clear();
ExceptList.Clear();
Consume();
// init starting frame F0.
Frame := NewFrame();
Frame^.Alive := True;
Frame^.Reduce := False;
Frame^.Parser := Self;
Frame^.Parent := nil;
Frame^.Link := nil;
Frame^.Token := nil;
Frame^.State := States[0];
Frame^.TokenCacheIndex := 0;
FFrames.Add(Frame);
ReturnValue := NewValue();
while (I < FFrames.Count) do
begin
FShiftActionList.Clear();
Frame := FFrames[I];
Inc(I);
Token := Frame^.Peek();
State := Frame^.State;
Actions := State.Terms[Token.TokenType];
if not Assigned(Actions) then
begin
EFrame := Frame;
Vanish(Frame);
Continue;
end;
Frame^.NumberOfChilds := Actions.Count;
Inc(FConflicts, Actions.Count - 1);
{ reduce actions }
for J := 0 to Actions.Count - 1 do
begin
Action := Actions[J];
case Action.ActionType of
atReduce:
begin
Rule := Rules[Action.ActionValue];
if not Reduce(Frame, Rule) then
begin
// invalid reduce action.
EFrame := Frame;
Vanish(Frame);
Continue;
end;
if rfAccept in Rule.Flags then
begin
// axiom rule.
Result := True;
Break;
end;
end;
atShift:
begin
// we shift later.
FShiftActionList.Add(Action);
end;
else
begin
raise Exception.Create('Error Message');
end;
end;
end;
if Result then
Break;
{ shift actions }
for J := 0 to FShiftActionList.Count - 1 do
begin
Action := FShiftActionList[J];
State := States[Action.ActionValue];
if not Shift(Frame, State) then
begin
raise Exception.Create('Error Message');
end
else
begin
LFrame := FFrames.Last();
LFrame^.Advance();
end;
end;
Merge(Frame);
end;
if Result then
Exit;
if Assigned(EFrame) then
begin
State := EFrame^.State;
for J := 0 to State.Terms.Count - 1 do
begin
Actions := State.Terms[J];
if Assigned(Actions) then
ExceptList.Add(Pointer(J));
end;
ExceptError(Token);
end;
end;
{ TFrame }
function TFrame.Peek(): TToken;
begin
Result := Parser.FTokenCache[TokenCacheIndex];
end;
function TFrame.Advance(): TToken;
begin
Result := Peek();
Inc(TokenCacheIndex);
if TokenCacheIndex >= Parser.FTokenCache.Count then
Parser.Consume();
end;
end.
|
unit Main_U;
// Description: Named Pipes Test Application
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls,
SDUNamedPipe_U, ExtCtrls;
type
TMain_F = class(TForm)
pbConnectClient: TButton;
reReport: TRichEdit;
edPipeName: TEdit;
pbSend: TButton;
Label1: TLabel;
edMessage: TEdit;
Label2: TLabel;
pbClose: TButton;
ckServer: TCheckBox;
pbReceive: TButton;
RichEdit1: TRichEdit;
pbCreatePipe: TButton;
pbConnectServer: TButton;
pbDisconnect: TButton;
Bevel1: TBevel;
Bevel2: TBevel;
Label4: TLabel;
Label5: TLabel;
Bevel3: TBevel;
Bevel4: TBevel;
Bevel5: TBevel;
Label3: TLabel;
procedure pbConnectClientClick(Sender: TObject);
procedure pbSendClick(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure pbReceiveClick(Sender: TObject);
procedure pbCreatePipeClick(Sender: TObject);
procedure ckServerClick(Sender: TObject);
procedure pbConnectServerClick(Sender: TObject);
procedure pbDisconnectClick(Sender: TObject);
private
SendPipe: TSDUNamedPipe;
public
{ Public declarations }
end;
var
Main_F: TMain_F;
implementation
{$R *.DFM}
uses
SDUGeneral;
procedure TMain_F.pbConnectClientClick(Sender: TObject);
var
oksofar: boolean;
begin
oksofar:= SendPipe.ClientConnect(edPipeName.text);
if oksofar then
begin
reReport.lines.add('PIPE: Connected OK');
end
else
begin
reReport.lines.add('PIPE: Failed to connect');
exit;
end;
end;
procedure TMain_F.pbSendClick(Sender: TObject);
var
oksofar: boolean;
begin
oksofar:= SendPipe.WriteString(edMessage.text);
if oksofar then
begin
reReport.lines.add('PIPE: Sent OK');
end
else
begin
reReport.lines.add('PIPE: Send failed');
exit;
end;
end;
procedure TMain_F.pbCloseClick(Sender: TObject);
var
oksofar: boolean;
begin
oksofar:= SendPipe.Close();
if oksofar then
begin
reReport.lines.add('PIPE: Closed OK');
end
else
begin
reReport.lines.add('PIPE: Close failed');
exit;
end;
end;
procedure TMain_F.FormShow(Sender: TObject);
begin
SendPipe:= TSDUNamedPipe.Create(nil);
end;
procedure TMain_F.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
SendPipe.Free();
end;
procedure TMain_F.pbReceiveClick(Sender: TObject);
var
oksofar: boolean;
msg: string;
begin
oksofar:= SendPipe.ReadString(msg);
if oksofar then
begin
reReport.lines.add('PIPE: Received OK');
reReport.lines.Add(msg);
end
else
begin
reReport.lines.add('PIPE: Receive failed');
exit;
end;
end;
procedure TMain_F.pbCreatePipeClick(Sender: TObject);
var
oksofar: boolean;
begin
oksofar:= SendPipe.CreatePipe(edPipeName.text);
if oksofar then
begin
reReport.lines.add('PIPE: Created OK');
end
else
begin
reReport.lines.add('PIPE: Create failed');
exit;
end;
end;
procedure TMain_F.ckServerClick(Sender: TObject);
begin
SDUEnableControl(pbConnectClient, not(ckServer.checked));
SDUEnableControl(pbCreatePipe, ckServer.checked);
SDUEnableControl(pbConnectServer, ckServer.checked);
SDUEnableControl(pbDisconnect, ckServer.checked);
end;
procedure TMain_F.pbConnectServerClick(Sender: TObject);
var
oksofar: boolean;
begin
oksofar:= SendPipe.ServerConnect();
if oksofar then
begin
reReport.lines.add('PIPE: Connected OK');
end
else
begin
reReport.lines.add('PIPE: Failed to connect');
exit;
end;
end;
procedure TMain_F.pbDisconnectClick(Sender: TObject);
var
oksofar: boolean;
begin
oksofar:= SendPipe.Disconnect();
if oksofar then
begin
reReport.lines.add('PIPE: Disconnected OK');
end
else
begin
reReport.lines.add('PIPE: Failed to disconnect');
exit;
end;
end;
END.
|
unit MainUView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DataModule, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxControls,
cxGridCustomView, cxGridLevel, cxGrid, FIBDataSet, pFIBDataSet,
cxCheckBox, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxMemo, cxLookAndFeelPainters, StdCtrls, cxButtons, cxTL,
cxInplaceContainer, cxTLData, cxDBTL, FIBQuery, pFIBQuery, Buttons,
cxSplitter, ExtCtrls;
type
TFieldLinksRecord = packed record
_Name_Field : string;
_Value : string;
end;
TFieldLinksArray = array of TFieldLinksRecord;
TMainForm = class(TForm)
TableDataSet: TpFIBDataSet;
TableDataSource: TDataSource;
DateEdit: TcxDateEdit;
DateCheckBox: TcxCheckBox;
DataSet: TpFIBDataSet;
ServersPopupEdit: TcxPopupEdit;
ServerCheckBox: TcxCheckBox;
ServGrid: TcxGrid;
TableView: TcxGridDBTableView;
ID_SERVER_COLUMN: TcxGridDBColumn;
NAME_SERVER_COLUMN: TcxGridDBColumn;
NAME_DEPARTMENT_COLUMN: TcxGridDBColumn;
ServGridLevel: TcxGridLevel;
ServersDataSet: TpFIBDataSet;
ServersDataSource: TDataSource;
SubjGrid: TcxGrid;
SubjectTableView: TcxGridDBTableView;
SubjGridLevel: TcxGridLevel;
SubjectDataSet: TpFIBDataSet;
SubjectDataSource: TDataSource;
ID_SUBJECT_AREA_COLUMN: TcxGridDBColumn;
NAME_SUBJECT_AREA_COLUMN: TcxGridDBColumn;
SubjectPopupEdit: TcxPopupEdit;
SubjectCheckBox: TcxCheckBox;
Query: TpFIBQuery;
SelectButton: TSpeedButton;
Panel: TPanel;
DataTreeList: TcxTreeList;
NameTableTreeList: TcxDBTreeList;
ID_SUBJECT_AREA_PARAM_COLUMN: TcxDBTreeListColumn;
LINK_TO_PARAM_COLUMN: TcxDBTreeListColumn;
NAME_TABLE_PARAM_COLUMN: TcxDBTreeListColumn;
COUNT_PARAM_COLUMN: TcxDBTreeListColumn;
EXPRESSION_FIELDS_PARAM_COLUMN: TcxDBTreeListColumn;
IS_USE_END_PARAM_COLUMN: TcxDBTreeListColumn;
cxSplitter1: TcxSplitter;
COMMENT_COLUMN: TcxDBTreeListColumn;
WaitPanel: TPanel;
Image1: TImage;
Bevel1: TBevel;
Label1: TLabel;
cxStyleRepository1: 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;
cxTreeListStyleSheet1: TcxTreeListStyleSheet;
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;
cxGridTableViewStyleSheet1: TcxGridTableViewStyleSheet;
procedure DataTableViewFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure ServersPopupEditPropertiesPopup(Sender: TObject);
procedure ServersPopupEditPropertiesCloseUp(Sender: TObject);
procedure SubjectPopupEditPropertiesPopup(Sender: TObject);
procedure SubjectPopupEditPropertiesCloseUp(Sender: TObject);
procedure DateCheckBoxPropertiesChange(Sender: TObject);
procedure ServerCheckBoxPropertiesChange(Sender: TObject);
procedure SubjectCheckBoxPropertiesChange(Sender: TObject);
procedure NameTableTreeListFocusedNodeChanged(Sender: TObject;
APrevFocusedNode, AFocusedNode: TcxTreeListNode);
procedure SelectButtonClick(Sender: TObject);
procedure TableViewDblClick(Sender: TObject);
procedure SubjectTableViewDblClick(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
public
procedure SelectAll;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
var
id_Server : integer;
id_Subj : integer;
function CreateFieldLinks(Fields, Values : string) : TFieldLinksArray;
var
i : integer;
k, p : integer;
TempArray : TFieldLinksArray;
TempArray2 : TFieldLinksArray;
begin
TempArray := nil;
TempArray2 := nil;
if Length(Fields) = 0 then Exit;
SetLength(TempArray, 1);
k := pos(';', Fields);
p := pos(';', Values);
if k = 0 then
TempArray[0]._Name_Field := Fields
else
TempArray[0]._Name_Field := Copy(Fields, 1, k - 1);
if p = 0 then
TempArray[0]._Value := Values
else
TempArray[0]._Value := Copy(Values, 1, p - 1);
if k = 0 then begin
Result := TempArray;
Exit;
end;
TempArray2 := nil;
TempArray2 := CreateFieldLinks(Copy(Fields, k + 1, Length(Fields) - 1), Copy(Values, p + 1, Length(Values) - 1));
for i := 0 to Length(TempArray2) - 1 do begin
SetLength(TempArray, Length(TempArray) + 1);
TempArray[Length(TempArray) - 1] := TempArray2[i];
end;
Result := TempArray;
end;
procedure TMainForm.DataTableViewFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
var
NameTable : string;
ExprFields : string;
begin
if AFocusedRecord = nil then Exit;
NameTable := AFocusedRecord.Values[0];
ExprFields := AFocusedRecord.Values[2];
end;
procedure TMainForm.SelectAll;
var
QueryText : string;
begin
WaitPanel.Visible := True;
Application.ProcessMessages;
TableDataSet.Close;
QueryText := 'select * from EXCH_PROC_VIEW_COUNT(';
if DateCheckBox.Checked then
QueryText := QueryText + QuotedStr(DateToStr(DateEdit.Date)) + ','
else
QueryText := QueryText + 'null,';
if ServerCheckBox.Checked then
QueryText := QueryText + IntToStr(id_Server) + ','
else
QueryText := QueryText + 'null,';
if SubjectCheckBox.Checked then
QueryText := QueryText + IntToStr(id_Subj) + ')'
else
QueryText := QueryText + 'null)';
TableDataSet.SelectSQL.Text := QueryText;
TableDataSet.Open;
WaitPanel.Visible := False;
end;
procedure TMainForm.ServersPopupEditPropertiesPopup(Sender: TObject);
begin
ServersDataSet.Open;
end;
procedure TMainForm.ServersPopupEditPropertiesCloseUp(Sender: TObject);
begin
if TableView.DataController.FocusedRecordIndex < 0 then Exit;
id_Server := TableView.ViewData.Records[TableView.DataController.FocusedRecordIndex].Values[0];
ServersPopupEdit.Text := TableView.ViewData.Records[TableView.DataController.FocusedRecordIndex].Values[1];
ServersDataSet.Close;
end;
procedure TMainForm.SubjectPopupEditPropertiesPopup(Sender: TObject);
begin
SubjectDataSet.Open;
end;
procedure TMainForm.SubjectPopupEditPropertiesCloseUp(Sender: TObject);
begin
if SubjectTableView.DataController.FocusedRecordIndex < 0 then Exit;
id_Subj := SubjectTableView.ViewData.Records[SubjectTableView.DataController.FocusedRecordIndex].Values[0];
SubjectPopupEdit.Text := SubjectTableView.ViewData.Records[SubjectTableView.DataController.FocusedRecordIndex].Values[1];
SubjectDataSet.Close;
end;
procedure TMainForm.DateCheckBoxPropertiesChange(Sender: TObject);
begin
DateEdit.Enabled := DateCheckBox.Checked;
end;
procedure TMainForm.ServerCheckBoxPropertiesChange(Sender: TObject);
begin
ServersPopupEdit.Enabled := ServerCheckBox.Checked;
end;
procedure TMainForm.SubjectCheckBoxPropertiesChange(Sender: TObject);
begin
SubjectPopupEdit.Enabled := SubjectCheckBox.Checked;
end;
procedure TMainForm.NameTableTreeListFocusedNodeChanged(Sender: TObject;
APrevFocusedNode, AFocusedNode: TcxTreeListNode);
var
QueryText : string;
NameTable : string;
ExprFields : string;
is_Use_End : boolean;
ValueExpr : string;
Server : string;
j : integer;
Node : TcxTreeListNode;
LinksArray : TFieldLinksArray;
begin
DataTreeList.Clear;
DataTreeList.DeleteAllColumns;
if AFocusedNode = nil then Exit;
if VarIsNull(AFocusedNode.Values[3]) then Exit;
WaitPanel.Visible := True;
Application.ProcessMessages;
DataTreeList.BeginUpdate;
NameTable := AFocusedNode.Values[2];
ExprFields := AFocusedNode.Values[4];
is_Use_End := ('1' = AFocusedNode.Values[6]);
QueryText := 'select * from EXCH_PROC_INI_LOG_REC_SEL_VIEW(';
if DateCheckBox.Checked then
QueryText := QueryText + QuotedStr(DateToStr(DateEdit.Date)) + ','
else
QueryText := QueryText + 'null,';
if ServerCheckBox.Checked then
QueryText := QueryText + IntToStr(id_Server) + ','
else
QueryText := QueryText + 'null,';
QueryText := QueryText + QuotedStr(NameTable) + ')';
DataSet.Close;
DataSet.SelectSQL.Text := QueryText;
DataSet.Open;
while not DataSet.Eof do begin
ValueExpr := DataSet['VALUE_EXPRESSIONS_PARAM'];
Server := DataSet['NAME_SERVER_PARAM'];
QueryText := 'select * from ' + UpperCase(NameTable) + ' where ';
LinksArray := CreateFieldLinks(ExprFields, ValueExpr);
if Length(LinksArray) = 0 then begin
DataSet.Next;
Continue;
end;
for j := 0 to Length(LinksArray) - 1 do begin
if j > 0 then QueryText := QueryText + ' and ';
QueryText := QueryText + UpperCase(LinksArray[j]._Name_Field) + '='
+ QuotedStr(LinksArray[j]._Value);
end;
if is_Use_End then QueryText := QueryText + ' and ' + QuotedStr(DateTimeToStr(Now)) + ' between USE_BEG and USE_END';
Query.SQL.Text := QueryText;
Query.ExecQuery;
if Query.RecordCount = 0 then begin
Query.Close;
DataSet.Next;
Continue;
end;
if DataTreeList.ColumnCount <= 0 then begin
for j := 0 to Query.FieldCount - 1 do
with DataTreeList.CreateColumn do begin
Name := Query.Fields[j].Name;
Caption.Text := Query.Fields[j].Name;
Caption.AlignHorz := taCenter;
end;
with DataTreeList.CreateColumn do begin
Name := 'NameServer';
Caption.Text := 'Від серверу';
Caption.AlignHorz := taCenter;
end;
end;
while not Query.Eof do begin
Node := DataTreeList.Add;
for j := 0 to Query.FieldCount - 1 do
Node.Values[j] := Query.Fields[j].AsVariant;
Node.Values[DataTreeList.ColumnCount - 1] := Server;
Query.Next;
end;
Query.Close;
DataSet.Next;
end;
DataSet.Close;
DataTreeList.EndUpdate;
WaitPanel.Visible := False;
end;
procedure TMainForm.SelectButtonClick(Sender: TObject);
begin
SelectAll;
end;
procedure TMainForm.TableViewDblClick(Sender: TObject);
begin
ServersPopupEdit.DroppedDown := False;
end;
procedure TMainForm.SubjectTableViewDblClick(Sender: TObject);
begin
SubjectPopupEdit.DroppedDown := False;
end;
procedure TMainForm.FormResize(Sender: TObject);
begin
WaitPanel.Left := (Width - WaitPanel.Width) div 2;
WaitPanel.Top := (Height - WaitPanel.Height) div 2;
end;
end.
|
unit uProgressBarStyleHookMarquee;
interface
uses
Windows,
uMemory,
Themes,
Graphics,
Classes,
Controls,
Vcl.Styles,
Vcl.ComCtrls,
Vcl.ExtCtrls;
type
TProgressBarStyleHookMarquee = class(TProgressBarStyleHook)
private
Timer: TTimer;
FStep: Integer;
procedure TimerAction(Sender: TObject);
protected
procedure PaintBar(Canvas: TCanvas); override;
public
constructor Create(AControl: TWinControl); override;
destructor Destroy; override;
end;
implementation
{ TProgressBarStyleHookMarquee }
constructor TProgressBarStyleHookMarquee.Create(AControl: TWinControl);
begin
inherited;
FStep := 0;
Timer := TTimer.Create(nil);
Timer.Interval := TProgressBar(Control).MarqueeInterval;
Timer.OnTimer := TimerAction;
Timer.Enabled := True
end;
destructor TProgressBarStyleHookMarquee.Destroy;
begin
F(Timer);
inherited;
end;
procedure TProgressBarStyleHookMarquee.PaintBar(Canvas: TCanvas);
var
FillR, R: TRect;
W, Pos: Integer;
Details: TThemedElementDetails;
begin
if (TProgressBar(Control).Style = pbstMarquee) and StyleServices.Enabled then
begin
R := BarRect;
InflateRect(R, -1, -1);
if Orientation = pbHorizontal then
W := R.Width
else
W := R.Height;
Pos := Round(W * 0.1);
FillR := R;
if Orientation = pbHorizontal then
begin
FillR.Right := FillR.Left + Pos;
Details := StyleServices.GetElementDetails(tpChunk);
end else
begin
FillR.Top := FillR.Bottom - Pos;
Details := StyleServices.GetElementDetails(tpChunkVert);
end;
FillR.SetLocation(Round((FStep / 10) * FillR.Width), FillR.Top);
StyleServices.DrawElement(Canvas.Handle, Details, FillR);
end else
inherited;
end;
procedure TProgressBarStyleHookMarquee.TimerAction(Sender: TObject);
var
Canvas: TCanvas;
begin
if StyleServices.Available and (TProgressBar(Control).Style = pbstMarquee) and Control.Visible then
begin
Inc(FStep, 1);
if FStep mod 100 = 0 then
FStep := 0;
Canvas := TCanvas.Create;
try
Canvas.Handle := GetWindowDC(Control.Handle);
PaintFrame(Canvas);
PaintBar(Canvas);
finally
ReleaseDC(Handle, Canvas.Handle);
Canvas.Handle := 0;
F(Canvas);
end;
end;
end;
initialization
TStyleManager.Engine.RegisterStyleHook(TProgressBar, TProgressBarStyleHookMarquee);
end.
|
unit BCEditor.Editor.Undo;
interface
uses
System.Classes, BCEditor.Consts, BCEditor.Types;
type
TBCEditorUndo = class(TPersistent)
strict private
FMaxActions: Integer;
FOnChange: TNotifyEvent;
FOptions: TBCEditorUndoOptions;
procedure DoChange;
procedure SetMaxActions(AValue: Integer);
procedure SetOptions(const AValue: TBCEditorUndoOptions);
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property MaxActions: Integer read FMaxActions write SetMaxActions default BCEDITOR_MAX_UNDO_ACTIONS;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property Options: TBCEditorUndoOptions read FOptions write SetOptions default [uoGroupUndo];
end;
implementation
constructor TBCEditorUndo.Create;
begin
inherited;
FMaxActions := BCEDITOR_MAX_UNDO_ACTIONS;
FOptions := [uoGroupUndo];
end;
procedure TBCEditorUndo.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorUndo.Assign(ASource: TPersistent);
begin
if ASource is TBCEditorUndo then
with ASource as TBCEditorUndo do
begin
Self.FMaxActions := FMaxActions;
Self.FOptions := FOptions;
Self.DoChange;
end
else
inherited Assign(ASource);
end;
procedure TBCEditorUndo.SetMaxActions(AValue: Integer);
begin
if FMaxActions <> AValue then
begin
FMaxActions := AValue;
DoChange;
end;
end;
procedure TBCEditorUndo.SetOptions(const AValue: TBCEditorUndoOptions);
begin
if FOptions <> AValue then
begin
FOptions := AValue;
DoChange;
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ Simple.IoC }
{ }
{ Copyright (C) 2013 Vincent Parrett }
{ }
{ http://www.finalbuilder.com }
{ }
{ }
{ *************************************************************************** }
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{ *************************************************************************** }
unit MVCBr.IoC;
/// A Simple IoC container. Does not do Dependency Injects.
interface
uses
Generics.Collections,
TypInfo,
Rtti,
MVCBr.Interf,
SysUtils;
{ .$I 'SimpleIoC.inc' }
{$DEFINE DELPHI_XE_UP }
type
TResolveResult = (Unknown, Success, InterfaceNotRegistered, ImplNotRegistered,
DeletegateFailedCreate);
TActivatorDelegate<TInterface: IInterface> = reference to function
: TInterface;
TMVCBrIoC = class
private
FRaiseIfNotFound: boolean;
type
TIoCRegistration<T: IInterface> = class
Guid: TGuid;
name: string;
IInterface: PTypeInfo;
ImplClass: TClass;
ActivatorDelegate: TActivatorDelegate<T>;
IsSingleton: boolean;
Instance: IInterface;
end;
private
FContainerInfo: TDictionary<string, TObject>;
class var FDefault: TMVCBrIoC;
class procedure ClassDestroy;
protected
function GetInterfaceKey<TInterface>(const AName: string = ''): string;
function InternalResolve<TInterface: IInterface>(out AInterface: TInterface;
const AName: string = ''): TResolveResult;
procedure InternalRegisterType<TInterface: IInterface>(const singleton
: boolean; const AImplementation: TClass;
const delegate: TActivatorDelegate<TInterface>; const name: string = '');
public
constructor Create;
destructor Destroy; override;
// Default Container
class function DefaultContainer: TMVCBrIoC;
{$IFDEF DELPHI_XE_UP}
// Exe's compiled with D2010 will crash when these are used.
// NOTES: The issue is due to the two generics included in the functions. The constaints also seem to be an issue.
procedure RegisterType<TInterface: IInterface; TImplementation: class>
(const name: string = ''); overload;
procedure RegisterType<TInterface: IInterface; TImplementation: class>
(const singleton: boolean; const name: string = ''); overload;
{$ENDIF}
procedure RegisterType<TInterface: IInterface>(const delegate
: TActivatorDelegate<TInterface>; const name: string = ''); overload;
procedure RegisterType<TInterface: IInterface>(const singleton: boolean;
const delegate: TActivatorDelegate<TInterface>;
const name: string = ''); overload;
procedure RevokeInstance(AInstance: IInterface);
// Register an instance as a signleton. If there is more than one instance that implements the interface
// then use the name parameter
procedure RegisterSingleton<TInterface: IInterface>(const Instance
: TInterface; const name: string = '');
// Resolution
function Resolve<TInterface: IInterface>(const name: string = '')
: TInterface;
function GetName(AGuid: TGuid): string;
procedure RegisterInterfaced<TInterface: IInterface>(AII: TGuid;
AClass: TInterfacedClass; AName: String; bSingleton: boolean); overload;
// Returns true if we have such a service.
function HasService<T: IInterface>: boolean;
// Empty the Container.. usefull for testing only!
procedure Clear;
property RaiseIfNotFound: boolean read FRaiseIfNotFound
write FRaiseIfNotFound;
property ContainerInfo: TDictionary<string, TObject> read FContainerInfo;
end;
EIoCException = class(Exception);
EIoCRegistrationException = class(EIoCException);
EIoCResolutionException = class(EIoCException);
// Makes sure virtual constructors are called correctly. Just using a class reference will not call the overriden constructor!
// See http://stackoverflow.com/questions/791069/how-can-i-create-an-delphi-object-from-a-class-reference-and-ensure-constructor
TClassActivator = class
private
class var FRttiCtx: TRttiContext;
public
constructor Create;
class function CreateInstance(const AClass: TClass): IInterface;
end;
function GetInterfaceIID(const I: IInterface; var IID: TGuid): boolean;
implementation
{ TActivator }
constructor TClassActivator.Create;
begin
TClassActivator.FRttiCtx := TRttiContext.Create;
end;
class function TClassActivator.CreateInstance(const AClass: TClass): IInterface;
var
rType: TRttiType;
method: TRttiMethod;
begin
result := nil;
rType := FRttiCtx.GetType(AClass);
if not(rType is TRttiInstanceType) then
exit;
for method in TRttiInstanceType(rType).GetMethods do
begin
if method.IsConstructor and (Length(method.GetParameters) = 0) then
begin
result := method.Invoke(TRttiInstanceType(rType).MetaclassType, [])
.AsInterface;
Break;
end;
end;
end;
function TMVCBrIoC.HasService<T>: boolean;
begin
result := Resolve<T> <> nil;
end;
{$IFDEF DELPHI_XE_UP}
procedure TMVCBrIoC.RegisterType<TInterface, TImplementation>
(const name: string);
begin
InternalRegisterType<TInterface>(false, TImplementation, nil, name);
end;
procedure TMVCBrIoC.RegisterType<TInterface, TImplementation>(const singleton
: boolean; const name: string);
begin
InternalRegisterType<TInterface>(singleton, TImplementation, nil, name);
end;
{$ENDIF}
procedure TMVCBrIoC.RegisterType<TInterface>(const delegate
: TActivatorDelegate<TInterface>; const name: string);
begin
InternalRegisterType<TInterface>(false, nil, delegate, name);
end;
procedure TMVCBrIoC.InternalRegisterType<TInterface>(const singleton: boolean;
const AImplementation: TClass; const delegate: TActivatorDelegate<TInterface>;
const name: string = '');
var
key: string;
pInfo: PTypeInfo;
rego: TIoCRegistration<TInterface>;
o: TObject;
newName: string;
newSingleton: boolean;
begin
newSingleton := singleton;
newName := name;
pInfo := TypeInfo(TInterface);
{$IFDEF ANDROID}
if newName = '' then
key := pInfo.name.ToString
else
key := pInfo.name.ToString + '_' + newName;
{$ELSE}
if newName = '' then
key := string(pInfo.name{$ifdef LINUX}.toString{$endif})
else
key := string(pInfo.name{$ifdef LINUX}.toString{$endif}) + '_' + newName;
{$ENDIF}
key := LowerCase(key);
if not FContainerInfo.TryGetValue(key, o) then
begin
rego := TIoCRegistration<TInterface>.Create;
rego.IInterface := pInfo;
rego.ActivatorDelegate := delegate;
rego.ImplClass := AImplementation;
rego.IsSingleton := newSingleton;
FContainerInfo.Add(key, rego);
end
else
begin
rego := TIoCRegistration<TInterface>(o);
// cannot replace a singleton that has already been instanciated.
if rego.IsSingleton and (rego.Instance <> nil) then
raise EIoCException.Create
(Format('An implementation for type %s with name %s is already registered with IoC',
[pInfo.name, newName]));
rego.IInterface := pInfo;
rego.ActivatorDelegate := delegate;
rego.ImplClass := AImplementation;
rego.IsSingleton := newSingleton;
FContainerInfo.AddOrSetValue(key, rego);
end;
end;
class procedure TMVCBrIoC.ClassDestroy;
begin
if FDefault <> nil then
FDefault.Free;
end;
procedure TMVCBrIoC.Clear;
begin
FContainerInfo.Clear;
end;
constructor TMVCBrIoC.Create;
begin
FContainerInfo := TDictionary<string, TObject>.Create;
FRaiseIfNotFound := false;
end;
class function TMVCBrIoC.DefaultContainer: TMVCBrIoC;
begin
if FDefault = nil then
FDefault := TMVCBrIoC.Create;
result := FDefault;
end;
destructor TMVCBrIoC.Destroy;
var
o: TObject;
begin
if FContainerInfo <> nil then
begin
for o in FContainerInfo.Values do
if o <> nil then
o.Free;
FContainerInfo.Free;
end;
inherited;
end;
function TMVCBrIoC.GetInterfaceKey<TInterface>(const AName: string): string;
var
pInfo: PTypeInfo;
begin
// By default the key is the interface name unless otherwise found.
pInfo := TypeInfo(TInterface);
{$IFDEF ANDROID}
result := pInfo.name.ToString;
{$ELSE}
result := string(pInfo.name{$ifdef LINUX}.toString{$endif});
{$ENDIF}
if (AName <> '') then
result := result + '_' + AName;
// All keys are stored in lower case form.
result := LowerCase(result);
end;
function TMVCBrIoC.GetName(AGuid: TGuid): string;
var
LName: string;
rogo: TIoCRegistration<IController>;
achei: string;
begin
achei := '';
for LName in FContainerInfo.keys do
begin
rogo := TIoCRegistration<IController>(FContainerInfo.items[LName]);
if rogo.Guid = AGuid then
begin
achei := rogo.name;
Break;
end;
end;
result := achei;
end;
function TMVCBrIoC.InternalResolve<TInterface>(out AInterface: TInterface;
const AName: string): TResolveResult;
var
key: string;
errorMsg: string;
container: TDictionary<string, TObject>;
registrationObj: TObject;
registration: TIoCRegistration<TInterface>;
resolvedInf: IInterface;
resolvedObj: TInterface;
bIsSingleton: boolean;
bInstanciate: boolean;
begin
AInterface := Default (TInterface);
result := TResolveResult.Unknown;
// Get the key for the interace we are resolving and locate the container for that key.
key := GetInterfaceKey<TInterface>(AName);
container := FContainerInfo;
if not container.TryGetValue(key, registrationObj) then
begin
result := TResolveResult.InterfaceNotRegistered;
exit;
end;
// Get the interface registration class correctly.
registration := TIoCRegistration<TInterface>(registrationObj);
bIsSingleton := registration.IsSingleton;
bInstanciate := true;
if bIsSingleton then
begin
// If a singleton was registered with this interface then check if it's already been instanciated.
if registration.Instance <> nil then
begin
// Get AInterface as TInterface
if registration.Instance.QueryInterface(GetTypeData(TypeInfo(TInterface))
.Guid, AInterface) <> 0 then
begin
result := TResolveResult.ImplNotRegistered;
exit;
end;
bInstanciate := false;
end;
end;
if bInstanciate then
begin
// If the instance hasn't been instanciated then we need to lock and instanciate
MonitorEnter(container);
try
// If we have a implementing class then used this to activate.
if registration.ImplClass <> nil then
resolvedInf := TClassActivator.CreateInstance(registration.ImplClass)
// Otherwise if there is a activate delegate use this to activate.
else if registration.ActivatorDelegate <> nil then
begin
resolvedInf := registration.ActivatorDelegate();
if resolvedInf = nil then
begin
result := TResolveResult.DeletegateFailedCreate;
exit;
end;
end;
// Get AInterface as TInterface
if resolvedInf.QueryInterface(GetTypeData(TypeInfo(TInterface)).Guid,
resolvedObj) <> 0 then
begin
result := TResolveResult.ImplNotRegistered;
exit;
end;
AInterface := resolvedObj;
if bIsSingleton then
begin
registration.Instance := resolvedObj;
// Reset the registration to show the instance which was created.
container.AddOrSetValue(key, registration);
end;
finally
MonitorExit(container);
end;
end;
end;
procedure TMVCBrIoC.RegisterSingleton<TInterface>(const Instance: TInterface;
const name: string);
var
key: string;
pInfo: PTypeInfo;
rego: TIoCRegistration<TInterface>;
o: TObject;
begin
pInfo := TypeInfo(TInterface);
key := GetInterfaceKey<TInterface>(name);
if not FContainerInfo.TryGetValue(key, o) then
begin
rego := TIoCRegistration<TInterface>.Create;
rego.IInterface := pInfo;
rego.ActivatorDelegate := nil;
rego.ImplClass := nil;
rego.IsSingleton := true;
rego.Instance := Instance;
FContainerInfo.Add(key, rego);
end
else
raise EIoCException.Create
(Format('An implementation for type %s with name %s is already registered with IoC',
[pInfo.name, name]));
end;
procedure TMVCBrIoC.RegisterInterfaced<TInterface>(AII: TGuid;
AClass: TInterfacedClass; AName: String; bSingleton: boolean);
var
Interf: PInterfaceEntry;
rego: TIoCRegistration<IUnknown>;
key: string;
begin
Interf := GetInterfaceEntry(AII);
key := GetInterfaceKey<TInterface>(AName);
rego := TIoCRegistration<IUnknown>.Create;
rego.Guid := AII;
rego.name := AName;
rego.IInterface := nil;
rego.ImplClass := AClass;
rego.IsSingleton := bSingleton;
rego.Instance := nil;
rego.ActivatorDelegate := function: IUnknown
var
obj: TInterfacedObject;
begin
obj := AClass.Create;
Supports(obj, AII, result);
end;
FContainerInfo.Add(key, rego);
end;
procedure TMVCBrIoC.RegisterType<TInterface>(const singleton: boolean;
const delegate: TActivatorDelegate<TInterface>; const name: string);
begin
InternalRegisterType<TInterface>(singleton, nil, delegate, name);
end;
procedure TMVCBrIoC.RevokeInstance(AInstance: IInterface);
var
LName: string;
rogo: TIoCRegistration<IUnknown>;
achei: string;
AOrigem, ALocal: TObject;
begin
achei := '';
AOrigem := AInstance as TObject;
for LName in FContainerInfo.keys do
begin
rogo := TIoCRegistration<IUnknown>(FContainerInfo.items[LName]);
if assigned(rogo) and assigned(rogo.Instance) and (rogo.IsSingleton) then
begin
ALocal := rogo.Instance as TObject;
if AOrigem.ClassName = ALocal.ClassName then
begin
rogo.Instance := nil;
Break;
end;
end;
end;
end;
function TMVCBrIoC.Resolve<TInterface>(const name: string = ''): TInterface;
var
resolveResult: TResolveResult;
errorMsg: string;
pInfo: PTypeInfo;
begin
pInfo := TypeInfo(TInterface);
resolveResult := InternalResolve<TInterface>(result, name);
// If we don't have a resolution and the caller wants an exception then throw one.
if (result = nil) and (FRaiseIfNotFound) then
begin
case resolveResult of
TResolveResult.Success:
;
TResolveResult.InterfaceNotRegistered:
errorMsg := Format('No implementation registered for type %s',
[pInfo.name]);
TResolveResult.ImplNotRegistered:
errorMsg :=
Format('The Implementation registered for type %s does not actually implement %s',
[pInfo.name, pInfo.name]);
TResolveResult.DeletegateFailedCreate:
errorMsg :=
Format('The Implementation registered for type %s does not actually implement %s',
[pInfo.name, pInfo.name]);
else
// All other error types are treated as unknown until defined here.
errorMsg :=
Format('An Unknown Error has occurred for the resolution of the interface %s %s. This is either because a new error type isn''t being handled, '
+ 'or it''s an bug.', [pInfo.name, name]);
end;
raise EIoCResolutionException.Create(errorMsg);
end;
end;
function GetInterfaceEntry2(const I: IInterface): PInterfaceEntry;
var
Instance: TObject;
InterfaceTable: PInterfaceTable;
j: integer;
CurrentClass: TClass;
begin
Instance := I as TObject;
if assigned(Instance) then
begin
CurrentClass := Instance.ClassType;
while assigned(CurrentClass) do
begin
InterfaceTable := CurrentClass.GetInterfaceTable;
if assigned(InterfaceTable) then
for j := 0 to InterfaceTable.EntryCount - 1 do
begin
result := @InterfaceTable.Entries[j];
if result.IOffset <> 0 then
begin
if Pointer(NativeInt(Instance) + result^.IOffset) = Pointer(I) then
exit;
end;
// TODO: implement checking interface implemented via implements delegation
// see System.TObject.GetInterface/System.InvokeImplGetter
end;
CurrentClass := CurrentClass.ClassParent
end;
end;
result := nil;
end;
function GetInterfaceIID(const I: IInterface; var IID: TGuid): boolean;
var
InterfaceEntry: PInterfaceEntry;
begin
InterfaceEntry := GetInterfaceEntry2(I);
result := assigned(InterfaceEntry);
if result then
IID := InterfaceEntry.IID;
end;
initialization
finalization
TMVCBrIoC.ClassDestroy;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
GLWin32Viewer, GLCadencer, GLTexture, GLScene, GLTerrainRenderer,
GLHeightData, GLObjects, VectorGeometry, GLTree, JPEG, TGA, GLKeyboard,
VectorLists, GLBitmapFont, GLContext, GLWindowsFont, GLHUDObjects, GLSkydome,
GLImposter, GLParticleFX, GLGraphics, PersistentClasses, OpenGL1x, ExtCtrls,
GLUtils, GLTextureCombiners, XOpenGL, GLHeightTileFileHDS, GLMaterial,
GLCoordinates, GLCrossPlatform, BaseClasses, GLRenderContextInfo;
type
TForm1 = class(TForm)
SceneViewer: TGLSceneViewer;
GLScene: TGLScene;
MLTrees: TGLMaterialLibrary;
MLTerrain: TGLMaterialLibrary;
GLCadencer: TGLCadencer;
Terrain: TGLTerrainRenderer;
Camera: TGLCamera;
Light: TGLLightSource;
GLHUDText1: TGLHUDText;
GLWindowsBitmapFont1: TGLWindowsBitmapFont;
EarthSkyDome: TGLEarthSkyDome;
GLRenderPoint: TGLRenderPoint;
SIBTree: TGLStaticImposterBuilder;
DOTrees: TGLDirectOpenGL;
PFXTrees: TGLCustomPFXManager;
RenderTrees: TGLParticleFXRenderer;
Timer1: TTimer;
MLWater: TGLMaterialLibrary;
DOInitializeReflection: TGLDirectOpenGL;
DOGLSLWaterPlane: TGLDirectOpenGL;
DOClassicWaterPlane: TGLDirectOpenGL;
GLHeightTileFileHDS: TGLHeightTileFileHDS;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure TerrainGetTerrainBounds(var l, t, r, b: Single);
procedure GLCadencerProgress(Sender: TObject; const deltaTime,
newTime: Double);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DOTreesRender(Sender: TObject; var rci: TRenderContextInfo);
procedure PFXTreesBeginParticles(Sender: TObject;
var rci: TRenderContextInfo);
procedure PFXTreesCreateParticle(Sender: TObject;
aParticle: TGLParticle);
procedure PFXTreesEndParticles(Sender: TObject;
var rci: TRenderContextInfo);
procedure PFXTreesRenderParticle(Sender: TObject;
aParticle: TGLParticle; var rci: TRenderContextInfo);
procedure SIBTreeImposterLoaded(Sender: TObject;
impostoredObject: TGLBaseSceneObject; destImposter: TImposter);
function SIBTreeLoadingImposter(Sender: TObject;
impostoredObject: TGLBaseSceneObject;
destImposter: TImposter): TGLBitmap32;
procedure Timer1Timer(Sender: TObject);
procedure PFXTreesProgress(Sender: TObject;
const progressTime: TProgressTimes; var defaultProgress: Boolean);
function PFXTreesGetParticleCountEvent(Sender: TObject): Integer;
procedure FormResize(Sender: TObject);
procedure DOInitializeReflectionRender(Sender: TObject;
var rci: TRenderContextInfo);
procedure DOGLSLWaterPlaneRender(Sender: TObject;
var rci: TRenderContextInfo);
procedure DOClassicWaterPlaneRender(Sender: TObject;
var rci: TRenderContextInfo);
procedure FormDeactivate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
// hscale, mapwidth, mapheight : Single;
lmp : TPoint;
camPitch, camTurn, camTime, curPitch, curTurn : Single;
procedure SetupReflectionMatrix;
public
{ Public declarations }
TestTree : TGLTree;
TreesShown : Integer;
nearTrees : TPersistentObjectList;
imposter : TImposter;
densityBitmap : TBitmap;
mirrorTexture : TGLTextureHandle;
mirrorTexType : TGLEnum;
reflectionProgram : TGLProgramHandle;
supportsGLSL : Boolean;
enableGLSL : Boolean;
enableRectReflection, enableTex2DReflection : Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses GLScreen, GLState;
const
cImposterCacheFile : String = 'media\imposters.bmp';
cMapWidth : Integer = 1024;
cMapHeight : Integer = 1024;
cBaseSpeed : Single = 50;
procedure TForm1.FormCreate(Sender: TObject);
var
density : TPicture;
begin
// go to 1024x768x32
SetFullscreenMode(GetIndexFromResolution(800, 600, 32), 85);
Application.OnDeactivate:=FormDeactivate;
SetCurrentDir(ExtractFilePath(Application.ExeName));
with MLTerrain.AddTextureMaterial('Terrain', 'media\volcano_TX_low.jpg') do
Texture2Name:='Detail';
with MLTerrain.AddTextureMaterial('Detail', 'media\detailmap.jpg') do begin
Material.Texture.TextureMode:=tmModulate;
TextureScale.SetPoint(128,128,128);
end;
Terrain.Material.MaterialLibrary:=MLTerrain;
Terrain.Material.LibMaterialName:='Terrain';
// Load tree textures
with MLTrees.AddTextureMaterial('Leaf','media\leaf.tga') do begin
Material.Texture.TextureFormat:=tfRGBA;
Material.Texture.TextureMode:=tmModulate;
Material.Texture.MinFilter:=miNearestMipmapNearest;
Material.BlendingMode:=bmAlphaTest50;
end;
with MLTrees.AddTextureMaterial('Bark','media\zbark_016.jpg') do
Material.Texture.TextureMode:=tmModulate;
// Create test tree
Randomize;
TestTree:=TGLTree(GLScene.Objects.AddNewChild(TGLTree));
with TestTree do begin
Visible:=False;
MaterialLibrary:=MLTrees;
LeafMaterialName:='Leaf';
LeafBackMaterialName:='Leaf';
BranchMaterialName:='Bark';
Up.SetVector(ZHmgVector);
Direction.SetVector(YHmgVector);
Depth:=9;
BranchFacets:=6;
LeafSize:=0.50;
BranchAngle:=0.65;
BranchTwist:=135;
ForceTotalRebuild;
end;
SIBTree.RequestImposterFor(TestTree);
densityBitmap:=TBitmap.Create;
try
densityBitmap.PixelFormat:=pf24bit;
Density:=TPicture.Create;
try
Density.LoadFromFile('media\volcano_trees.jpg');
densityBitmap.Width:=Density.Width;
densityBitmap.Height:=Density.Height;
densityBitmap.Canvas.Draw(0, 0, Density.Graphic);
finally
Density.Free;
end;
PFXTrees.CreateParticles(10000);
finally
densityBitmap.Free;
end;
TreesShown:=2000;
Light.Pitch(30);
Camera.Position.Y:=Terrain.InterpolatedHeight(Camera.Position.AsVector)+10;
lmp:=ClientToScreen(Point(Width div 2, Height div 2));
SetCursorPos(lmp.X, lmp.Y);
ShowCursor(False);
nearTrees:=TPersistentObjectList.Create;
camTurn:=-60;
enableRectReflection:=False;
enableTex2DReflection:=False;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
RestoreDefaultMode;
ShowCursor(True);
nearTrees.Free;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
Camera.FocalLength:=Width*50/800;
end;
procedure TForm1.FormDeactivate(Sender: TObject);
begin
Close;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
SetFocus;
end;
procedure TForm1.GLCadencerProgress(Sender: TObject; const deltaTime,
newTime: Double);
var
speed, z : Single;
nmp : TPoint;
begin
// Camera movement
if IsKeyDown(VK_SHIFT) then
speed:=deltaTime*cBaseSpeed*10
else speed:=deltaTime*cBaseSpeed;
if IsKeyDown(VK_UP) or IsKeyDown('W') or IsKeyDown('Z') then
Camera.Move(speed)
else if IsKeyDown(VK_DOWN) or IsKeyDown('S') then
Camera.Move(-speed);
if IsKeyDown(VK_LEFT) or IsKeyDown('A') or IsKeyDown('Q') then
Camera.Slide(-speed)
else if IsKeyDown(VK_RIGHT) or IsKeyDown('D') then
Camera.Slide(speed);
z:=Terrain.Position.Y+Terrain.InterpolatedHeight(Camera.Position.AsVector);
if z<0 then z:=0;
z:=z+10;
if Camera.Position.Y<z then
Camera.Position.Y:=z;
GetCursorPos(nmp);
camTurn:=camTurn-(lmp.X-nmp.X)*0.2;
camPitch:=camPitch+(lmp.Y-nmp.Y)*0.2;
camTime:=camTime+deltaTime;
while camTime>0 do begin
curTurn:=Lerp(curTurn, camTurn, 0.2);
curPitch:=Lerp(curPitch, camPitch, 0.2);
Camera.Position.Y:=Lerp(Camera.Position.Y, z, 0.2);
camTime:=camTime-0.01;
end;
Camera.ResetRotations;
Camera.Turn(curTurn);
Camera.Pitch(curPitch);
SetCursorPos(lmp.X, lmp.Y);
SceneViewer.Invalidate;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case key of
VK_ESCAPE : Form1.Close;
VK_ADD : if TreesShown<PFXTrees.Particles.ItemCount then
TreesShown:=TreesShown+100;
VK_SUBTRACT : if TreesShown>0 then
TreesShown:=TreesShown-100;
Word('R') : enableTex2DReflection:=not enableTex2DReflection;
Word('G') : if supportsGLSL then begin
enableGLSL:=not enableGLSL;
enableTex2DReflection:=True;
end;
end;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
hud : String;
begin
hud:=Format('%.1f FPS - %d trees'#13#10'Tree sort: %f ms',
[SceneViewer.FramesPerSecond, TreesShown, RenderTrees.LastSortTime]);
if enableTex2DReflection then begin
hud:=hud+#13#10+'Water reflections';
if enableRectReflection then
hud:=hud+' (RECT)';
end;
if enableGLSL and enableTex2DReflection then
hud:=hud+#13#10+'GLSL water';
GLHUDText1.Text:=hud;
SceneViewer.ResetPerformanceMonitor;
Caption:=Format('%.2f', [RenderTrees.LastSortTime]);
end;
procedure TForm1.PFXTreesCreateParticle(Sender: TObject;
aParticle: TGLParticle);
var
u, v, p : Single;
// x, y, i, j, dark : Integer;
pixelX, pixelY : Integer;
begin
repeat
repeat
u:=Random*0.88+0.06;
v:=Random*0.88+0.06;
pixelX:=Round(u*densityBitmap.Width);
pixelY:=Round(v*densityBitmap.Height);
p:=((densityBitmap.Canvas.Pixels[pixelX, pixelY] shr 8) and 255)/255;
until p>Random;
aParticle.PosX:=(0.5-u)*Terrain.Scale.X*cMapWidth;
aParticle.PosY:=0;
aParticle.PosZ:=(0.5-(1-v))*Terrain.Scale.Y*cMapHeight;
aParticle.PosY:=Terrain.Position.Y+Terrain.InterpolatedHeight(aParticle.Position);
until aParticle.PosY>=0;
aParticle.Tag:=Random(360);
// Remove probablility for current location
// densityBitmap.Canvas.Pixels[pixelX, pixelY]:=
// RGB(0, GetRValue(densityBitmap.Canvas.Pixels[pixelX, pixelY]) div 2, 0);
// Blob shadow beneath tree
{ with MLTerrain.Materials[0].Material.Texture do begin
with Image.GetBitmap32(GL_TEXTURE_2D) do begin
x:=Round(u*(Image.Width-1));
y:=Round((1-v)*(Image.Height-1));
for i:=-8 to 8 do
for j:=-8 to 8 do with ScanLine[y+j][x+i] do begin
dark:=20;
r:=MaxInteger(r-dark,0);
g:=MaxInteger(g-dark,0);
b:=MaxInteger(b-dark,0);
end;
end;
end;}
end;
procedure TForm1.PFXTreesBeginParticles(Sender: TObject;
var rci: TRenderContextInfo);
begin
imposter:=SIBTree.ImposterFor(TestTree);
imposter.BeginRender(rci);
end;
procedure TForm1.PFXTreesRenderParticle(Sender: TObject;
aParticle: TGLParticle; var rci: TRenderContextInfo);
const
cTreeCenteringOffset : TAffineVector = (0, 30, 0);
var
d : Single;
camPos : TVector;
begin
if not IsVolumeClipped(VectorAdd(aParticle.Position, cTreeCenteringOffset), 30, rci.rcci.frustum) then begin;
VectorSubtract(rci.cameraPosition, aParticle.Position, camPos);
d:=VectorNorm(camPos);
if d>Sqr(180) then begin
RotateVectorAroundY(PAffineVector(@camPos)^, aParticle.Tag*cPIdiv180);
imposter.Render(rci, VectorMake(aParticle.Position), camPos, 10);
end else begin
nearTrees.Add(aParticle);
end;
end;
end;
procedure TForm1.PFXTreesEndParticles(Sender: TObject;
var rci: TRenderContextInfo);
var
aParticle : TGLParticle;
camPos : TVector;
begin
// Only 20 trees max rendered at full res, force imposter'ing the others
while nearTrees.Count>20 do begin
aParticle:=TGLParticle(nearTrees.First);
VectorSubtract(rci.cameraPosition, aParticle.Position, camPos);
RotateVectorAroundY(PAffineVector(@camPos)^, aParticle.Tag*cPIdiv180);
imposter.Render(rci, VectorMake(aParticle.Position), camPos, 10);
nearTrees.Delete(0);
end;
imposter.EndRender(rci);
end;
procedure TForm1.DOTreesRender(Sender: TObject;
var rci: TRenderContextInfo);
var
i : Integer;
particle : TGLParticle;
begin
rci.GLStates.Disable(stBlend);
for i:=0 to nearTrees.Count-1 do begin
particle:=TGLParticle(nearTrees[i]);
glPushMatrix;
glTranslatef(particle.PosX, particle.PosY, particle.PosZ);
glScalef(10, 10, 10);
glRotatef(-particle.Tag, 0, 1, 0);
glRotatef(Cos(GLCadencer.CurrentTime+particle.ID*15)*0.2, 1, 0, 0);
glRotatef(Cos(GLCadencer.CurrentTime*1.3+particle.ID*15)*0.2, 0, 0, 1);
TestTree.Render(rci);
glPopMatrix;
end;
nearTrees.Clear;
end;
procedure TForm1.TerrainGetTerrainBounds(var l, t, r, b: Single);
begin
l:=0;
t:=cMapHeight;
r:=cMapWidth;
b:=0;
end;
function TForm1.SIBTreeLoadingImposter(Sender: TObject;
impostoredObject: TGLBaseSceneObject;
destImposter: TImposter): TGLBitmap32;
var
bmp : TBitmap;
cacheAge, exeAge : TDateTime;
begin
Tag:=1;
Result:=nil;
if not FileExists(cImposterCacheFile) then Exit;
cacheAge:=FileDateToDateTime(FileAge(cImposterCacheFile));
exeAge:=FileDateToDateTime(FileAge(Application.ExeName));
if cacheAge<exeAge then Exit;
Tag:=0;
bmp:=TBitmap.Create;
bmp.LoadFromFile(cImposterCacheFile);
Result:=TGLBitmap32.Create;
Result.Assign(bmp);
bmp.Free;
end;
procedure TForm1.SIBTreeImposterLoaded(Sender: TObject;
impostoredObject: TGLBaseSceneObject; destImposter: TImposter);
var
bmp32 : TGLBitmap32;
bmp : TBitmap;
begin
if Tag=1 then begin
bmp32:=TGLBitmap32.Create;
bmp32.AssignFromTexture2D(SIBTree.ImposterFor(TestTree).Texture);
bmp:=bmp32.Create32BitsBitmap;
bmp.SaveToFile(cImposterCacheFile);
bmp.Free;
bmp32.Free;
end;
end;
function TForm1.PFXTreesGetParticleCountEvent(Sender: TObject): Integer;
begin
Result:=TreesShown;
end;
procedure TForm1.PFXTreesProgress(Sender: TObject;
const progressTime: TProgressTimes; var defaultProgress: Boolean);
begin
defaultProgress:=False;
end;
procedure TForm1.DOInitializeReflectionRender(Sender: TObject;
var rci: TRenderContextInfo);
var
w, h : Integer;
refMat, curMat : TMatrix;
cameraPosBackup, cameraDirectionBackup : TVector;
frustumBackup : TFrustum;
clipPlane : TDoubleHmgPlane;
begin
supportsGLSL:=GL_ARB_shader_objects and GL_ARB_fragment_shader and GL_ARB_vertex_shader;
enableRectReflection:=GL_NV_texture_rectangle and ((not enableGLSL) or GL_EXT_Cg_shader);
if not enableTex2DReflection then Exit;
if not Assigned(mirrorTexture) then
mirrorTexture:=TGLTextureHandle.Create;
glPushAttrib(GL_ENABLE_BIT);
glPushMatrix;
// Mirror coordinates
glLoadMatrixf(@TGLSceneBuffer(rci.buffer).ViewMatrix);
refMat:=MakeReflectionMatrix(NullVector, YVector);
glMultMatrixf(@refMat);
glGetFloatv(GL_MODELVIEW_MATRIX, @curMat);
glLoadMatrixf(@TGLSceneBuffer(rci.buffer).ViewMatrix);
TGLSceneBuffer(rci.buffer).PushViewMatrix(curMat);
glFrontFace(GL_CW);
glEnable(GL_CLIP_PLANE0);
SetPlane(clipPlane, PlaneMake(AffineVectorMake(0, 1, 0), VectorNegate(YVector)));
glClipPlane(GL_CLIP_PLANE0, @clipPlane);
cameraPosBackup:=rci.cameraPosition;
cameraDirectionBackup:=rci.cameraDirection;
frustumBackup:=rci.rcci.frustum;
rci.cameraPosition:=VectorTransform(rci.cameraPosition, refMat);
rci.cameraDirection:=VectorTransform(rci.cameraDirection, refMat);
with rci.rcci.frustum do begin
pLeft:=VectorTransform(pLeft, refMat);
pRight:=VectorTransform(pRight, refMat);
pTop:=VectorTransform(pTop, refMat);
pBottom:=VectorTransform(pBottom, refMat);
pNear:=VectorTransform(pNear, refMat);
pFar:=VectorTransform(pFar, refMat);
end;
glLoadIdentity;
Camera.Apply;
glMultMatrixf(@refMat);
EarthSkyDome.DoRender(rci, True, False);
glMultMatrixf(PGLFloat(Terrain.AbsoluteMatrixAsAddress));
Terrain.DoRender(rci, True, False);
rci.cameraPosition:=cameraPosBackup;
rci.cameraDirection:=cameraDirectionBackup;
rci.rcci.frustum:=frustumBackup;
// Restore to "normal"
TGLSceneBuffer(rci.buffer).PopViewMatrix;
glLoadMatrixf(@TGLSceneBuffer(rci.buffer).ViewMatrix);
GLScene.SetupLights(TGLSceneBuffer(rci.buffer).LimitOf[limLights]);
glFrontFace(GL_CCW);
glPopMatrix;
glPopAttrib;
if enableRectReflection then begin
mirrorTexType:=GL_TEXTURE_RECTANGLE_NV;
w:=SceneViewer.Width;
h:=SceneViewer.Height;
end else begin
mirrorTexType:=GL_TEXTURE_2D;
w:=RoundUpToPowerOf2(SceneViewer.Width);
h:=RoundUpToPowerOf2(SceneViewer.Height);
end;
if mirrorTexture.Handle=0 then begin
mirrorTexture.AllocateHandle;
glBindTexture(mirrorTexType, mirrorTexture.Handle);
glTexParameteri(mirrorTexType, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(mirrorTexType, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(mirrorTexType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(mirrorTexType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glCopyTexImage2d(mirrorTexType, 0, GL_RGBA8,
0, 0, w, h, 0);
end else begin
glBindTexture(mirrorTexType, mirrorTexture.Handle);
glCopyTexSubImage2D(mirrorTexType, 0, 0, 0,
0, 0, w, h);
end;
glClear(GL_COLOR_BUFFER_BIT+GL_DEPTH_BUFFER_BIT+GL_STENCIL_BUFFER_BIT);
end;
procedure TForm1.DOClassicWaterPlaneRender(Sender: TObject;
var rci: TRenderContextInfo);
const
cWaveScale = 7;
cWaveSpeed = 0.02;
cSinScale = 0.02;
var
tex0Matrix, tex1Matrix : TMatrix;
tWave : Single;
pos : TAffineVector;
tex : TTexPoint;
x, y : Integer;
begin
if enableGLSL and enableTex2DReflection then Exit;
tWave:=GLCadencer.CurrentTime*cWaveSpeed;
glPushAttrib(GL_ENABLE_BIT);
glMatrixMode(GL_TEXTURE);
tex0Matrix:=IdentityHmgMatrix;
tex0Matrix[0][0]:=3*cWaveScale;
tex0Matrix[1][1]:=4*cWaveScale;
tex0Matrix[3][0]:=tWave*1.1;
tex0Matrix[3][1]:=tWave*1.06;
glLoadMatrixf(@tex0Matrix);
glBindTexture(GL_TEXTURE_2D, MLWater.Materials[0].Material.Texture.Handle);
glEnable(GL_TEXTURE_2D);
glActiveTextureARB(GL_TEXTURE1_ARB);
tex1Matrix:=IdentityHmgMatrix;
tex1Matrix[0][0]:=cWaveScale;
tex1Matrix[1][1]:=cWaveScale;
tex1Matrix[3][0]:=tWave*0.83;
tex1Matrix[3][1]:=tWave*0.79;
glLoadMatrixf(@tex1Matrix);
glBindTexture(GL_TEXTURE_2D, MLWater.Materials[0].Material.Texture.Handle);
glEnable(GL_TEXTURE_2D);
if enableTex2DReflection then begin
glActiveTextureARB(GL_TEXTURE2_ARB);
glBindTexture(mirrorTexType, mirrorTexture.Handle);
glEnable(mirrorTexType);
SetupReflectionMatrix;
end;
glActiveTextureARB(GL_TEXTURE0_ARB);
glMatrixMode(GL_MODELVIEW);
if enableTex2DReflection then begin
SetupTextureCombiners( 'Tex0:=Tex1*Tex0;'#13#10
+'Tex1:=Tex0+Col;'#13#10
+'Tex2:=Tex1+Tex2-0.5;');
glColor4f(0.0, 0.3, 0.3, 1);
end else begin
SetupTextureCombiners( 'Tex0:=Tex1*Tex0;'#13#10
+'Tex1:=Tex0+Col;');
glColor4f(0.0, 0.4, 0.7, 1);
end;
glDisable(GL_CULL_FACE);
for y:=-10 to 10-1 do begin
glBegin(GL_QUAD_STRIP);
for x:=-10 to 10 do begin
SetVector(pos, x*1500, 0, y*1500);
tex:=TexPointMake(x, y);
glMultiTexCoord2fvARB(GL_TEXTURE0_ARB, @tex);
glMultiTexCoord2fvARB(GL_TEXTURE1_ARB, @tex);
glMultiTexCoord3fvARB(GL_TEXTURE2_ARB, @pos);
glVertex3fv(@pos);
SetVector(pos, x*1500, 0, (y+1)*1500);
tex:=TexPointMake(x, (y+1));
glMultiTexCoord3fvARB(GL_TEXTURE0_ARB, @tex);
glMultiTexCoord3fvARB(GL_TEXTURE1_ARB, @tex);
glMultiTexCoord3fvARB(GL_TEXTURE2_ARB, @pos);
glVertex3fv(@pos);
end;
glEnd;
end;
glMatrixMode(GL_TEXTURE);
if enableTex2DReflection then begin
glActiveTextureARB(GL_TEXTURE2_ARB);
glLoadIdentity;
end;
glActiveTextureARB(GL_TEXTURE1_ARB);
glLoadIdentity;
glActiveTextureARB(GL_TEXTURE0_ARB);
glLoadIdentity;
glMatrixMode(GL_MODELVIEW);
glPopAttrib;
end;
procedure TForm1.DOGLSLWaterPlaneRender(Sender: TObject;
var rci: TRenderContextInfo);
var
x, y : Integer;
begin
if not (enableGLSL and enableTex2DReflection) then Exit;
if not Assigned(reflectionProgram) then begin
reflectionProgram:=TGLProgramHandle.CreateAndAllocate;
reflectionProgram.AddShader(TGLVertexShaderHandle, LoadAnsiStringFromFile('media\water_vp.glsl'));
reflectionProgram.AddShader(TGLFragmentShaderHandle, LoadAnsiStringFromFile('media\water_fp.glsl'));
if not reflectionProgram.LinkProgram then
raise Exception.Create(reflectionProgram.InfoLog);
if not reflectionProgram.ValidateProgram then
raise Exception.Create(reflectionProgram.InfoLog);
end;
{ glEnable(GL_STENCIL_TEST);
glColorMask(False, False, False, False);
glStencilFunc(GL_ALWAYS, 255, 255);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
for y:=-5 to 5-1 do begin
glBegin(GL_QUAD_STRIP);
for x:=-5 to 5 do begin
glVertex3f(x*1500, 0, y*1500);
glVertex3f(x*1500, 0, (y+1)*1500);
end;
glEnd;
end;
glColorMask(True, True, True, True);
glStencilFunc(GL_EQUAL, 255, 255);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glDisable(GL_DEPTH_TEST); }
glBindTexture(mirrorTexType, mirrorTexture.Handle);
glMatrixMode(GL_TEXTURE);
SetupReflectionMatrix;
glMatrixMode(GL_MODELVIEW);
reflectionProgram.UseProgramObject;
reflectionProgram.Uniform1f['Time']:=GLCadencer.CurrentTime;
reflectionProgram.Uniform4f['EyePos']:=Camera.AbsolutePosition;
reflectionProgram.Uniform1i['ReflectionMap']:=0;
glActiveTextureARB(GL_TEXTURE1_ARB);
glBindTexture(GL_TEXTURE_2D, MLWater.Materials[1].Material.Texture.Handle);
reflectionProgram.Uniform1i['WaveMap']:=1;
glActiveTextureARB(GL_TEXTURE0_ARB);
// reflectionProgram.EndUseProgramObject;
for y:=-10 to 10-1 do begin
glBegin(GL_QUAD_STRIP);
for x:=-10 to 10 do begin
glVertex3f(x*1500, 0, y*1500);
glVertex3f(x*1500, 0, (y+1)*1500);
end;
glEnd;
end;
reflectionProgram.EndUseProgramObject;
glMatrixMode(GL_TEXTURE);
glLoadIdentity;
glMatrixMode(GL_MODELVIEW);
glDisable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
end;
// SetupReflectionMatrix
//
procedure TForm1.SetupReflectionMatrix;
var
w, h : Single;
begin
if mirrorTexType=GL_TEXTURE_2D then begin
w:=0.5*SceneViewer.Width/RoundUpToPowerOf2(SceneViewer.Width);
h:=0.5*SceneViewer.Height/RoundUpToPowerOf2(SceneViewer.Height);
end else begin
w:=0.5*SceneViewer.Width;
h:=0.5*SceneViewer.Height;
end;
glLoadIdentity;
glTranslatef(w, h, 0);
glScalef(w, h, 0);
Camera.ApplyPerspective(SceneViewer.Buffer.ViewPort, SceneViewer.Width, SceneViewer.Height, 96);
Camera.Apply;
glScalef(1, -1, 1);
end;
end.
|
unit Pospolite.View.CSS.MediaQuery;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
custom variables in media queries are not supported
or = comma
}
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
{$goto on}
interface
uses
Classes, SysUtils, Pospolite.View.Basics, Pospolite.View.CSS.Declaration,
Pospolite.View.DOM.Screen, Pospolite.View.DOM.Window, LCLType, LCLProc,
LCLIntf, Printers, OSPrinters, Graphics, Forms, strutils;
type
// - Media Queries Level 4 and some 5 - //
// https://www.w3.org/TR/mediaqueries-4/
// https://developer.mozilla.org/en-US/docs/Web/CSS/@media
// actual values
{ TPLCSSMediaQueriesEnvironment }
TPLCSSMediaQueriesEnvironment = packed record
public
function IsTouchDevicePresent: TPLBool;
function IsDeviceUsedAsATablet: TPLBool;
function FeatureAnyHover: TPLStringArray;
function FeatureAnyPointer: TPLStringArray;
function FeatureAspectRatio: TPLFloat;
function FeatureColor: TPLInt;
function FeatureColorGamut: TPLString;
function FeatureColorIndex: TPLUInt;
function FeatureDeviceAspectRatio: TPLFloat;
function FeatureDeviceHeight: TPLInt;
function FeatureDeviceWidth: TPLInt;
function FeatureDisplayMode: TPLString;
function FeatureGrid: TPLBool;
function FeatureHeight: TPLInt;
function FeatureHover: TPLBool;
function FeatureMonochrome: TPLInt;
function FeatureOrientation: TPLString;
function FeaturePointer: TPLString;
function FeaturePrefersColorScheme: TPLString;
function FeaturePrefersReducedMotion: TPLString;
function FeatureResolution: TPLFloat; // in dpi
function FeatureScan: TPLString;
function FeatureUpdate: TPLString;
function FeatureWidth: TPLInt;
public
Screen: TPLDOMScreen;
Hook: TPLDOMWindow;
DocumentBody: TPLHTMLObject;
Viewport: record
Width, Height: TPLInt;
end;
PreferredColorScheme: TPLString;
PreferredReducedMotion: TPLBool;
UsePrinter: TPLBool;
constructor Create(AVWidth, AVHeight: TPLInt);
end;
TPLCSSMediaExpressionBase = class;
{ TPLCSSMediaExpressionBase }
TPLCSSMediaExpressionBase = class(TInterfacedObject, specialize IPLCloneable<TPLCSSMediaExpressionBase>)
protected
FFeature: TPLString;
public
function IsCorrect: TPLBool; virtual;
function Clone: TPLCSSMediaExpressionBase; virtual;
function Evaluate(const {%H-}AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool; virtual;
function AsString: TPLString; virtual;
property Feature: TPLString read FFeature;
end;
{ TPLCSSMediaExpression }
TPLCSSMediaExpression = class(TPLCSSMediaExpressionBase)
private
FValue: TPLCSSPropertyValuePart;
public
constructor Create(const AFeature: TPLString);
constructor Create(const AFeature: TPLString; const AValue: TPLCSSPropertyValuePart);
destructor Destroy; override;
function IsCorrect: TPLBool; override;
function HasValue: TPLBool; inline;
function Clone: TPLCSSMediaExpressionBase; override;
function Evaluate(const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
override;
function AsString: TPLString; override;
property Value: TPLCSSPropertyValuePart read FValue;
end;
TPLCSSMediaExpressionRangeOperator = (meroEqual, meroLess, meroLessEqual,
meroGreater, meroGreaterEqual);
{ TPLCSSMediaExpressionRange }
// https://www.w3.org/TR/mediaqueries-4/#mq-range-context
TPLCSSMediaExpressionRange = class(TPLCSSMediaExpressionBase)
private
FOperatorFirst: TPLCSSMediaExpressionRangeOperator;
FOperatorSecond: TPLCSSMediaExpressionRangeOperator;
FValueFirst: TPLCSSPropertyValuePart;
FValueSecond: TPLCSSPropertyValuePart;
public
constructor Create(const AFeature: TPLString; const AOperator: TPLCSSMediaExpressionRangeOperator;
const AValue: TPLCSSPropertyValuePart);
constructor Create( const AFeature: TPLString; const AOperator1, AOperator2: TPLCSSMediaExpressionRangeOperator;
const AValue1, AValue2: TPLCSSPropertyValuePart);
destructor Destroy; override;
function IsCorrect: TPLBool; override;
function HasOneSide: TPLBool; inline;
function HasTwoSides: TPLBool; inline;
function Clone: TPLCSSMediaExpressionBase; override;
function Evaluate(const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
override;
function AsString: TPLString; override;
property ValueFirst: TPLCSSPropertyValuePart read FValueFirst;
property ValueSecond: TPLCSSPropertyValuePart read FValueSecond;
property OperatorFirst: TPLCSSMediaExpressionRangeOperator read FOperatorFirst;
property OperatorSecond: TPLCSSMediaExpressionRangeOperator read FOperatorSecond;
end;
{ TPLCSSMediaExpressions }
TPLCSSMediaExpressions = class(specialize TPLObjectList<TPLCSSMediaExpressionBase>);
TPLCSSMediaQualifier = (mqOnly, mqNot, mqNone);
{ TPLCSSMediaQuery }
TPLCSSMediaQuery = class(TObject)
private
FExpressions: TPLCSSMediaExpressions;
FMediaType: TPLString;
FQualifier: TPLCSSMediaQualifier;
public
constructor Create;
destructor Destroy; override;
function Evaluate(const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
function AsString: TPLString;
property Qualifier: TPLCSSMediaQualifier read FQualifier write FQualifier;
property MediaType: TPLString read FMediaType write FMediaType;
property Expressions: TPLCSSMediaExpressions read FExpressions;
end;
{ TPLCSSMediaQueries }
TPLCSSMediaQueries = class(specialize TPLObjectList<TPLCSSMediaQuery>)
public
function Evaluate(const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
function AsString: TPLString;
end;
{ TPLCSSMediaQueriesList }
TPLCSSMediaQueriesList = class(specialize TPLObjectList<TPLCSSMediaQueries>);
{ TPLCSSMediaQueryParser }
TPLCSSMediaQueryParser = packed class sealed
public
class procedure ParseMediaQueries(ASource: TPLString; var AMediaQueries: TPLCSSMediaQueries); static;
end;
implementation
{$ifdef windows}
uses
windows, Win32Proc;
type
TAR_STATE = (
AR_ENABLED = $0,
AR_DISABLED = $1,
AR_SUPPRESSED = $2,
AR_REMOTESESSION = $4,
AR_MULTIMON = $8,
AR_NOSENSOR = $10,
AR_NOT_SUPPORTED = $20,
AR_DOCKED = $40,
AR_LAPTOP = $80
);
//PAR_STATE = ^TAR_STATE;
POWER_PLATFORM_ROLE = (
PlatformRoleUnspecified = 0,
PlatformRoleDesktop = 1,
PlatformRoleMobile = 2,
PlatformRoleWorkstation = 3,
PlatformRoleEnterpriseServer = 4,
PlatformRoleSOHOServer = 5,
PlatformRoleAppliancePC = 6,
PlatformRolePerformanceServer = 7,
PlatformRoleSlate = 8,
PlatformRoleMaximum
);
const
//POWER_PLATFORM_ROLE_V1 = ULONG($00000001);
POWER_PLATFORM_ROLE_V2 = ULONG($00000002);
function GetAutoRotationState(out pState: TAR_STATE): LongBool; stdcall; external user32;
function PowerDeterminePlatformRoleEx(Version: ULONG): POWER_PLATFORM_ROLE; stdcall; external 'PowrProf.dll';
{$endif}
operator := (a: TPLCSSMediaExpressionRangeOperator) r: TPLString;
begin
case a of
meroEqual: r := '=';
meroGreater: r := '>';
meroGreaterEqual: r := '>=';
meroLess: r := '<';
meroLessEqual: r := '<=';
end;
end;
{ TPLCSSMediaQueriesEnvironment }
function TPLCSSMediaQueriesEnvironment.IsTouchDevicePresent: TPLBool;
const
NID_READY = $00000080;
NID_INTEGRATED_TOUCH = $00000001;
NID_EXTERNAL_TOUCH = $00000002;
var
w: TPLInt;
begin
{$ifdef windows}
w := GetSystemMetrics(SM_DIGITIZER);
Result := (w and NID_READY <> 0) and ((w and NID_INTEGRATED_TOUCH <> 0) or (w and NID_EXTERNAL_TOUCH <> 0));
{$else}
Result := false;
{$endif}
end;
function TPLCSSMediaQueriesEnvironment.IsDeviceUsedAsATablet: TPLBool;
const
SM_SYSTEMDOCKED = $2004;
SM_CONVERTIBLESLATEMODE = $2003;
var
{$ifdef windows}
ts: TAR_STATE = TAR_STATE.AR_ENABLED;
r: POWER_PLATFORM_ROLE;
{$endif}
ist: TPLBool = false;
begin
Result := false;
{$ifdef windows}
if (WindowsVersion < wv8) or (GetSystemMetrics(SM_MAXIMUMTOUCHES) = 0)
or (GetSystemMetrics(SM_SYSTEMDOCKED) <> 0) then exit;
if GetAutoRotationState(ts) and (ord(ts) and (ord(AR_NOT_SUPPORTED) or
ord(AR_LAPTOP) or ord(AR_NOSENSOR)) <> 0) then exit;
r := PowerDeterminePlatformRoleEx(POWER_PLATFORM_ROLE_V2);
if r in [PlatformRoleMobile, PlatformRoleSlate] then
ist := not GetSystemMetrics(SM_CONVERTIBLESLATEMODE);
Result := ist;
{$endif}
end;
function TPLCSSMediaQueriesEnvironment.FeatureAnyHover: TPLStringArray;
begin
if UsePrinter and Assigned(Printer) then exit(TPLStringFuncs.NewArray(['none']));
if IsDeviceUsedAsATablet then exit(TPLStringFuncs.NewArray(['none']));
if GetSystemMetrics(SM_MOUSEPRESENT) <> 0 then
exit(TPLStringFuncs.NewArray(['hover']));
Result := TPLStringFuncs.NewArray(['none']);
end;
function TPLCSSMediaQueriesEnvironment.FeatureAnyPointer: TPLStringArray;
var
itdp: TPLBool;
begin
if UsePrinter and Assigned(Printer) then exit(TPLStringFuncs.NewArray(['none']));
if IsDeviceUsedAsATablet then exit(TPLStringFuncs.NewArray(['coarse']));
itdp := IsTouchDevicePresent;
if (GetSystemMetrics(SM_MOUSEPRESENT) = 0) and not itdp then
exit(TPLStringFuncs.NewArray(['none']));
Result := TPLStringFuncs.NewArray(['fine']);
if itdp then Result += TPLStringFuncs.NewArray(['coarse']);
end;
function TPLCSSMediaQueriesEnvironment.FeatureAspectRatio: TPLFloat;
begin
if UsePrinter and Assigned(Printer) then
Result := Printer.PageWidth / Printer.PageHeight
else
Result := Viewport.Width / Viewport.Height;
end;
function TPLCSSMediaQueriesEnvironment.FeatureColor: TPLInt;
var
dc: HDC;
hw: HWND = 0;
begin
if FeatureMonochrome > 0 then Result := 0
else begin
{$ifdef windows}
if UsePrinter and Assigned(Printer) then
hw := TWinPrinter(Printer).Handle;
{$endif}
dc := GetDC(hw);
Result := GetDeviceCaps(dc, BITSPIXEL);
ReleaseDC(hw, dc);
end;
end;
function TPLCSSMediaQueriesEnvironment.FeatureColorGamut: TPLString;
begin
Result := 'srgb';
end;
function TPLCSSMediaQueriesEnvironment.FeatureColorIndex: TPLUInt;
begin
if FeatureMonochrome > 0 then Result := 0
else begin
Result := QWord(2) << (FeatureColor - 1);
end;
end;
function TPLCSSMediaQueriesEnvironment.FeatureDeviceAspectRatio: TPLFloat;
begin
if UsePrinter and Assigned(Printer) then
Result := Printer.PageWidth / Printer.PageHeight
else
Result := Screen.width / Screen.height;
end;
function TPLCSSMediaQueriesEnvironment.FeatureDeviceHeight: TPLInt;
begin
if UsePrinter and Assigned(Printer) then
Result := Printer.PageHeight
else
Result := Screen.height;
end;
function TPLCSSMediaQueriesEnvironment.FeatureDeviceWidth: TPLInt;
begin
if UsePrinter and Assigned(Printer) then
Result := Printer.PageWidth
else
Result := Screen.width;
end;
function TPLCSSMediaQueriesEnvironment.FeatureDisplayMode: TPLString;
begin
if Assigned(Hook.Hook) then begin
if Hook.Hook.WindowState = wsFullScreen then
Result := 'fullscreen'
else case Hook.Display of
wdStandalone: Result := 'standalone';
wdMinimalUI: Result := 'minimal-ui';
wdBrowser: Result := 'browser';
end;
end else Result := 'standalone';
end;
function TPLCSSMediaQueriesEnvironment.FeatureGrid: TPLBool;
var
dc: HDC;
begin
if UsePrinter and Assigned(Printer) then exit(false);
dc := GetDC(0);
Result := (FeatureMonochrome > 0) and ((GetSystemMetrics(SM_SLOWMACHINE) <> 0)
or (GetDeviceCaps(dc, NUMFONTS) < 2));
ReleaseDC(0, dc);
end;
function TPLCSSMediaQueriesEnvironment.FeatureHeight: TPLInt;
begin
if UsePrinter and Assigned(Printer) then
Result := Printer.PageHeight
else
Result := Viewport.Height;
end;
function TPLCSSMediaQueriesEnvironment.FeatureHover: TPLBool;
begin
Result := 'hover' in FeatureAnyHover;
end;
function TPLCSSMediaQueriesEnvironment.FeatureMonochrome: TPLInt;
var
dc: HDC;
begin
if UsePrinter and Assigned(Printer) then begin
dc := GetDC(TWinPrinter(Printer).Handle);
if GetDeviceCaps(dc, BITSPIXEL) > 2 then
Result := GetDeviceCaps(dc, BITSPIXEL)
else
Result := 0;
ReleaseDC(TWinPrinter(Printer).Handle, dc);
end else begin
if Screen.colorDepth <= 2 then Result := Screen.pixelDepth
else Result := 0;
end;
end;
function TPLCSSMediaQueriesEnvironment.FeatureOrientation: TPLString;
begin
if UsePrinter and Assigned(Printer) then begin
case Printer.Orientation of
poLandscape, poReverseLandscape: Result := 'landscape';
poPortrait, poReversePortrait: Result := 'portrait';
end;
end else begin
if Viewport.Height >= Viewport.Width then Result := 'portrait'
else Result := 'landscape';
end;
end;
function TPLCSSMediaQueriesEnvironment.FeaturePointer: TPLString;
var
ap: TPLStringArray;
begin
ap := FeatureAnyPointer;
if 'fine' in ap then Result := 'fine' else
if 'coarse' in ap then Result := 'coarse' else
Result := 'none';
end;
function TPLCSSMediaQueriesEnvironment.FeaturePrefersColorScheme: TPLString;
begin
Result := PreferredColorScheme;
end;
function TPLCSSMediaQueriesEnvironment.FeaturePrefersReducedMotion: TPLString;
begin
if PreferredReducedMotion or (UsePrinter and Assigned(Printer)) then
Result := 'reduce'
else
Result := 'no-preference';
end;
function TPLCSSMediaQueriesEnvironment.FeatureResolution: TPLFloat;
begin
if UsePrinter and Assigned(Printer) then
Result := min(Printer.XDPI, Printer.YDPI)
else
Result := Screen.devicePPI;
end;
function TPLCSSMediaQueriesEnvironment.FeatureScan: TPLString;
begin
Result := 'progressive';
end;
function TPLCSSMediaQueriesEnvironment.FeatureUpdate: TPLString;
begin
if UsePrinter and Assigned(Printer) then
Result := 'none'
else if GetSystemMetrics(SM_SLOWMACHINE) <> 0 then
Result := 'slow'
else
Result := 'fast';
end;
function TPLCSSMediaQueriesEnvironment.FeatureWidth: TPLInt;
begin
if UsePrinter and Assigned(Printer) then
Result := Printer.PageWidth
else
Result := Viewport.Width;
end;
constructor TPLCSSMediaQueriesEnvironment.Create(AVWidth, AVHeight: TPLInt);
begin
Viewport.Width := AVWidth;
Viewport.Height := AVHeight;
PreferredColorScheme := 'light';
PreferredReducedMotion := false;
UsePrinter := false;
Hook := TPLDOMWindow.Create(nil);
DocumentBody := nil;
end;
{ TPLCSSMediaExpressionBase }
function TPLCSSMediaExpressionBase.IsCorrect: TPLBool;
begin
Result := not TPLString.IsNullOrEmpty(FFeature);
end;
function TPLCSSMediaExpressionBase.Clone: TPLCSSMediaExpressionBase;
begin
Result := TPLCSSMediaExpressionBase.Create;
end;
function TPLCSSMediaExpressionBase.Evaluate(
const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
begin
if not IsCorrect then exit(false);
Result := true;
// ...
end;
function TPLCSSMediaExpressionBase.AsString: TPLString;
begin
Result := '';
end;
{ TPLCSSMediaExpression }
constructor TPLCSSMediaExpression.Create(const AFeature: TPLString);
begin
inherited Create;
FFeature := AFeature.ToLower;
FValue := nil;
end;
constructor TPLCSSMediaExpression.Create(const AFeature: TPLString;
const AValue: TPLCSSPropertyValuePart);
begin
inherited Create;
FFeature := AFeature.ToLower;
FValue := AValue;
end;
destructor TPLCSSMediaExpression.Destroy;
begin
if HasValue then FreeAndNil(FValue);
inherited Destroy;
end;
function TPLCSSMediaExpression.IsCorrect: TPLBool;
begin
Result := inherited IsCorrect;
end;
function TPLCSSMediaExpression.HasValue: TPLBool;
begin
Result := Assigned(FValue);
end;
function TPLCSSMediaExpression.Clone: TPLCSSMediaExpressionBase;
begin
Result := TPLCSSMediaExpression.Create(FFeature, FValue);
end;
function TPLCSSMediaExpression.Evaluate(
const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
var
vf: TPLFloat;
begin
Result := inherited Evaluate(AEnvironment);
if not Result then exit;
Result := false;
case FFeature of
'any-hover': begin
if not HasValue then
Result := 'hover' in AEnvironment.FeatureAnyHover
else if FValue is TPLCSSPropertyValuePartStringOrIdentifier then
Result := TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value in AEnvironment.FeatureAnyHover;
end;
'any-pointer': begin
if not HasValue then
Result := not ('none' in AEnvironment.FeatureAnyPointer)
else if FValue is TPLCSSPropertyValuePartStringOrIdentifier then
Result := TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value in AEnvironment.FeatureAnyPointer;
end;
'aspect-ratio', 'min-aspect-ratio', 'max-aspect-ratio':
if HasValue and (FValue is TPLCSSPropertyValuePartFunction) and
(TPLCSSPropertyValuePartFunction(FValue).Arguments.Count = 2) and
(TPLCSSPropertyValuePartFunction(FValue).Arguments.First is TPLCSSPropertyValuePartNumber) and
(TPLCSSPropertyValuePartFunction(FValue).Arguments.Last is TPLCSSPropertyValuePartNumber) then begin
vf := TPLCSSPropertyValuePartNumber(TPLCSSPropertyValuePartFunction(FValue).Arguments.First).Value /
TPLCSSPropertyValuePartNumber(TPLCSSPropertyValuePartFunction(FValue).Arguments.Last).Value;
if FFeature.StartsWith('min') then Result := AEnvironment.FeatureAspectRatio >= vf
else if FFeature.StartsWith('max') then Result := AEnvironment.FeatureAspectRatio <= vf
else Result := AEnvironment.FeatureAspectRatio = vf;
end;
'color': begin
if not HasValue then
Result := AEnvironment.FeatureColor > 0
else if FValue is TPLCSSPropertyValuePartNumber then
Result := TPLCSSPropertyValuePartNumber(FValue).Value = AEnvironment.FeatureColor;
end;
'min-color', 'max-color': if HasValue and (FValue is TPLCSSPropertyValuePartNumber) then begin
if FFeature.StartsWith('min') then
Result := AEnvironment.FeatureColor >= TPLCSSPropertyValuePartNumber(FValue).Value
else
Result := AEnvironment.FeatureColor <= TPLCSSPropertyValuePartNumber(FValue).Value;
end;
'color-gamut': if HasValue and (FValue is TPLCSSPropertyValuePartStringOrIdentifier) then begin
Result := AEnvironment.FeatureColorGamut = TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value;
end;
'color-index': begin
if not HasValue then
Result := AEnvironment.FeatureColorIndex > 0
else if FValue is TPLCSSPropertyValuePartNumber then
Result := TPLCSSPropertyValuePartNumber(FValue).Value = AEnvironment.FeatureColorIndex;
end;
'min-color-index', 'max-color-index': if HasValue and (FValue is TPLCSSPropertyValuePartNumber) then begin
if FFeature.StartsWith('min') then
Result := AEnvironment.FeatureColorIndex >= TPLCSSPropertyValuePartNumber(FValue).Value
else
Result := AEnvironment.FeatureColorIndex <= TPLCSSPropertyValuePartNumber(FValue).Value;
end;
'device-aspect-ratio', 'min-device-aspect-ratio', 'max-device-aspect-ratio':
if HasValue and (FValue is TPLCSSPropertyValuePartFunction) and
(TPLCSSPropertyValuePartFunction(FValue).Arguments.Count = 2) and
(TPLCSSPropertyValuePartFunction(FValue).Arguments.First is TPLCSSPropertyValuePartNumber) and
(TPLCSSPropertyValuePartFunction(FValue).Arguments.Last is TPLCSSPropertyValuePartNumber) then begin
vf := TPLCSSPropertyValuePartNumber(TPLCSSPropertyValuePartFunction(FValue).Arguments.First).Value /
TPLCSSPropertyValuePartNumber(TPLCSSPropertyValuePartFunction(FValue).Arguments.Last).Value;
if FFeature.StartsWith('min') then Result := AEnvironment.FeatureDeviceAspectRatio >= vf
else if FFeature.StartsWith('max') then Result := AEnvironment.FeatureDeviceAspectRatio <= vf
else Result := AEnvironment.FeatureDeviceAspectRatio = vf;
end;
'device-height', 'min-device-height', 'max-device-height':
if HasValue and (FValue is TPLCSSPropertyValuePartDimension) then begin
vf := AutoLengthToPx(TPLCSSPropertyValuePartDimension(FValue).Value, TPLCSSPropertyValuePartDimension(FValue).&Unit, AEnvironment.DocumentBody, 'env:device-height');
if FFeature.StartsWith('min') then Result := AEnvironment.FeatureDeviceHeight >= vf
else if FFeature.StartsWith('max') then Result := AEnvironment.FeatureDeviceHeight <= vf
else Result := AEnvironment.FeatureDeviceHeight = vf;
end;
'device-width', 'min-device-width', 'max-device-width':
if HasValue and (FValue is TPLCSSPropertyValuePartDimension) then begin
vf := AutoLengthToPx(TPLCSSPropertyValuePartDimension(FValue).Value, TPLCSSPropertyValuePartDimension(FValue).&Unit, AEnvironment.DocumentBody, 'env:device-width');
if FFeature.StartsWith('min') then Result := AEnvironment.FeatureDeviceWidth >= vf
else if FFeature.StartsWith('max') then Result := AEnvironment.FeatureDeviceWidth <= vf
else Result := AEnvironment.FeatureDeviceWidth = vf;
end;
'height', 'min-height', 'max-height':
if HasValue and (FValue is TPLCSSPropertyValuePartDimension) then begin
vf := AutoLengthToPx(TPLCSSPropertyValuePartDimension(FValue).Value, TPLCSSPropertyValuePartDimension(FValue).&Unit, AEnvironment.DocumentBody, 'env:height');
if FFeature.StartsWith('min') then Result := AEnvironment.FeatureHeight >= vf
else if FFeature.StartsWith('max') then Result := AEnvironment.FeatureHeight <= vf
else Result := AEnvironment.FeatureHeight = vf;
end;
'width', 'min-width', 'max-width':
if HasValue and (FValue is TPLCSSPropertyValuePartDimension) then begin
vf := AutoLengthToPx(TPLCSSPropertyValuePartDimension(FValue).Value, TPLCSSPropertyValuePartDimension(FValue).&Unit, AEnvironment.DocumentBody, 'env:width');
if FFeature.StartsWith('min') then Result := AEnvironment.FeatureWidth >= vf
else if FFeature.StartsWith('max') then Result := AEnvironment.FeatureWidth <= vf
else Result := AEnvironment.FeatureWidth = vf;
end;
'display-mode': if HasValue and (FValue is TPLCSSPropertyValuePartStringOrIdentifier) then begin
Result := AEnvironment.FeatureDisplayMode = TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value;
end;
'grid': begin
if not HasValue then
Result := AEnvironment.FeatureGrid
else if FValue is TPLCSSPropertyValuePartNumber then
Result := BoolToStr(AEnvironment.FeatureGrid, '1', '0').ToExtended = TPLCSSPropertyValuePartNumber(FValue).Value;
end;
'hover': begin
if not HasValue then
Result := AEnvironment.FeatureHover
else if FValue is TPLCSSPropertyValuePartStringOrIdentifier then
Result := AEnvironment.FeatureHover and (TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value = 'hover');
end;
'monochrome', 'min-monochrome', 'max-monochrome': begin
if not HasValue and (FFeature = 'monochrome') then
Result := AEnvironment.FeatureMonochrome > 0
else if FValue is TPLCSSPropertyValuePartNumber then begin
vf := TPLCSSPropertyValuePartNumber(FValue).Value;
if FFeature.StartsWith('min') then Result := AEnvironment.FeatureMonochrome >= vf
else if FFeature.StartsWith('max') then Result := AEnvironment.FeatureMonochrome <= vf
else Result := AEnvironment.FeatureMonochrome = vf;
end;
end;
'orientation': if HasValue and (FValue is TPLCSSPropertyValuePartStringOrIdentifier) then begin
Result := AEnvironment.FeatureOrientation = TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value;
end;
'pointer': begin
if not HasValue then
Result := AEnvironment.FeaturePointer <> 'none'
else if FValue is TPLCSSPropertyValuePartStringOrIdentifier then
Result := AEnvironment.FeaturePointer = TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value;
end;
'prefers-color-scheme': if HasValue and (FValue is TPLCSSPropertyValuePartStringOrIdentifier) then begin
Result := AEnvironment.PreferredColorScheme = TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value;
end;
'prefers-reduced-motion': if HasValue and (FValue is TPLCSSPropertyValuePartStringOrIdentifier) then begin
Result := AEnvironment.PreferredReducedMotion = (TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value = 'reduce');
end;
'resolution', 'min-resolution', 'max-resolution':
if HasValue and (FValue is TPLCSSPropertyValuePartDimension) then begin
vf := TPLCSSPropertyValuePartDimension(FValue).Value;
case TPLCSSPropertyValuePartDimension(FValue).&Unit of
'dpi': ; // = vf
'dpcm': vf /= 2.54;
'dppx', 'x': vf /= 96;
else vf := 0;
end;
if FFeature.StartsWith('min') then Result := AEnvironment.FeatureResolution >= vf
else if FFeature.StartsWith('max') then Result := AEnvironment.FeatureResolution <= vf
else Result := AEnvironment.FeatureResolution = vf;
end;
'update': begin
if not HasValue then
Result := AEnvironment.FeatureUpdate <> 'none'
else if FValue is TPLCSSPropertyValuePartStringOrIdentifier then
Result := AEnvironment.FeatureUpdate = TPLCSSPropertyValuePartStringOrIdentifier(FValue).Value;
end;
end;
end;
function TPLCSSMediaExpression.AsString: TPLString;
begin
Result := '(' + FFeature;
if HasValue then
Result += ': ' + FValue.AsString;
Result += ')';
end;
{ TPLCSSMediaExpressionRange }
constructor TPLCSSMediaExpressionRange.Create(const AFeature: TPLString;
const AOperator: TPLCSSMediaExpressionRangeOperator;
const AValue: TPLCSSPropertyValuePart);
begin
Create(AFeature, AOperator, meroEqual, AValue, nil);
end;
constructor TPLCSSMediaExpressionRange.Create(const AFeature: TPLString;
const AOperator1, AOperator2: TPLCSSMediaExpressionRangeOperator;
const AValue1, AValue2: TPLCSSPropertyValuePart);
begin
inherited Create;
FFeature := AFeature;
FOperatorFirst := AOperator1;
FOperatorSecond := AOperator2;
FValueFirst := AValue1;
FValueSecond := AValue2;
end;
destructor TPLCSSMediaExpressionRange.Destroy;
begin
if Assigned(FValueFirst) then FreeAndNil(FValueFirst);
if Assigned(FValueSecond) then FreeAndNil(FValueSecond);
inherited Destroy;
end;
function TPLCSSMediaExpressionRange.IsCorrect: TPLBool;
begin
Result := inherited IsCorrect and (HasOneSide or HasTwoSides);
end;
function TPLCSSMediaExpressionRange.HasOneSide: TPLBool;
begin
Result := Assigned(FValueFirst) and not Assigned(FValueSecond);
end;
function TPLCSSMediaExpressionRange.HasTwoSides: TPLBool;
begin
Result := Assigned(FValueFirst) and Assigned(FValueSecond);
end;
function TPLCSSMediaExpressionRange.Clone: TPLCSSMediaExpressionBase;
begin
Result := TPLCSSMediaExpressionRange.Create(FFeature, FOperatorFirst,
FOperatorSecond, FValueFirst, FValueSecond);
end;
function TPLCSSMediaExpressionRange.Evaluate(
const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
var
vf1, vf2, vc: TPLFloat;
begin
Result := inherited Evaluate(AEnvironment);
if not Result then exit;
Result := false;
case FFeature of
'aspect-ratio', 'device-aspect-ratio': if (FValueFirst is TPLCSSPropertyValuePartFunction) and
(TPLCSSPropertyValuePartFunction(FValueFirst).Arguments.Count = 2) and
(TPLCSSPropertyValuePartFunction(FValueFirst).Arguments.First is TPLCSSPropertyValuePartNumber) and
(TPLCSSPropertyValuePartFunction(FValueFirst).Arguments.Last is TPLCSSPropertyValuePartNumber) then begin
if FFeature = 'aspect-ratio' then
vc := AEnvironment.FeatureAspectRatio
else
vc := AEnvironment.FeatureDeviceAspectRatio;
vf1 := TPLCSSPropertyValuePartNumber(TPLCSSPropertyValuePartFunction(FValueFirst).Arguments.First).Value /
TPLCSSPropertyValuePartNumber(TPLCSSPropertyValuePartFunction(FValueFirst).Arguments.Last).Value;
if HasTwoSides then begin
case FOperatorFirst of
meroEqual: Result := vf1 = vc;
meroGreater: Result := vf1 > vc;
meroGreaterEqual: Result := vf1 >= vc;
meroLess: Result := vf1 < vc;
meroLessEqual: Result := vf1 <= vc;
end;
end else begin
case FOperatorFirst of
meroEqual: Result := vf1 = vc;
meroGreater: Result := vf1 < vc;
meroGreaterEqual: Result := vf1 <= vc;
meroLess: Result := vf1 > vc;
meroLessEqual: Result := vf1 >= vc;
end;
end;
if Result and HasTwoSides and (FValueSecond is TPLCSSPropertyValuePartFunction) and
(TPLCSSPropertyValuePartFunction(FValueSecond).Arguments.Count = 2) and
(TPLCSSPropertyValuePartFunction(FValueSecond).Arguments.First is TPLCSSPropertyValuePartNumber) and
(TPLCSSPropertyValuePartFunction(FValueSecond).Arguments.Last is TPLCSSPropertyValuePartNumber) then begin
vf2 := TPLCSSPropertyValuePartNumber(TPLCSSPropertyValuePartFunction(FValueSecond).Arguments.First).Value /
TPLCSSPropertyValuePartNumber(TPLCSSPropertyValuePartFunction(FValueSecond).Arguments.Last).Value;
case FOperatorSecond of
meroEqual: Result := vf2 = vc;
meroGreater: Result := vf2 > vc;
meroGreaterEqual: Result := vf2 >= vc;
meroLess: Result := vf2 < vc;
meroLessEqual: Result := vf2 <= vc;
end;
end;
end;
'color', 'color-index', 'monochrome': if FValueFirst is TPLCSSPropertyValuePartNumber then begin
case FFeature of
'color': vc := AEnvironment.FeatureColor;
'color-index': vc := AEnvironment.FeatureColorIndex;
'monochrome': vc := AEnvironment.FeatureMonochrome;
end;
vf1 := TPLCSSPropertyValuePartNumber(FValueFirst).Value;
if HasTwoSides then begin
case FOperatorFirst of
meroEqual: Result := vf1 = vc;
meroGreater: Result := vf1 > vc;
meroGreaterEqual: Result := vf1 >= vc;
meroLess: Result := vf1 < vc;
meroLessEqual: Result := vf1 <= vc;
end;
end else begin
case FOperatorFirst of
meroEqual: Result := vf1 = vc;
meroGreater: Result := vf1 < vc;
meroGreaterEqual: Result := vf1 <= vc;
meroLess: Result := vf1 > vc;
meroLessEqual: Result := vf1 >= vc;
end;
end;
if Result and HasTwoSides and (FValueSecond is TPLCSSPropertyValuePartNumber) then begin
vf2 := TPLCSSPropertyValuePartNumber(FValueSecond).Value;
case FOperatorSecond of
meroEqual: Result := vf2 = vc;
meroGreater: Result := vf2 > vc;
meroGreaterEqual: Result := vf2 >= vc;
meroLess: Result := vf2 < vc;
meroLessEqual: Result := vf2 <= vc;
end;
end;
end;
'device-height', 'device-width', 'height', 'width', 'resolution':
if FValueFirst is TPLCSSPropertyValuePartDimension then begin
case FFeature of
'device-height': vc := AEnvironment.FeatureDeviceHeight;
'device-width': vc := AEnvironment.FeatureDeviceWidth;
'height': vc := AEnvironment.FeatureHeight;
'width': vc := AEnvironment.FeatureWidth;
'resolution': vc := AEnvironment.FeatureResolution;
end;
if FFeature = 'resolution' then begin
vf1 := TPLCSSPropertyValuePartDimension(FValueFirst).Value;
case TPLCSSPropertyValuePartDimension(FValueFirst).&Unit of
'dpi': ; // = vf1
'dpcm': vf1 /= 2.54;
'dppx', 'x': vf1 /= 96;
else vf1 := 0;
end;
end else begin
vf1 := AutoLengthToPx(TPLCSSPropertyValuePartDimension(FValueFirst).Value, TPLCSSPropertyValuePartDimension(FValueFirst).&Unit, AEnvironment.DocumentBody, 'env:' + FFeature);
end;
if HasTwoSides then begin
case FOperatorFirst of
meroEqual: Result := vf1 = vc;
meroGreater: Result := vf1 > vc;
meroGreaterEqual: Result := vf1 >= vc;
meroLess: Result := vf1 < vc;
meroLessEqual: Result := vf1 <= vc;
end;
end else begin
case FOperatorFirst of
meroEqual: Result := vf1 = vc;
meroGreater: Result := vf1 < vc;
meroGreaterEqual: Result := vf1 <= vc;
meroLess: Result := vf1 > vc;
meroLessEqual: Result := vf1 >= vc;
end;
end;
if Result and HasTwoSides and (FValueSecond is TPLCSSPropertyValuePartDimension) then begin
if FFeature = 'resolution' then begin
vf2 := TPLCSSPropertyValuePartDimension(FValueSecond).Value;
case TPLCSSPropertyValuePartDimension(FValueSecond).&Unit of
'dpi': ; // = vf2
'dpcm': vf2 /= 2.54;
'dppx', 'x': vf2 /= 96;
else vf2 := 0;
end;
end else begin
vf2 := AutoLengthToPx(TPLCSSPropertyValuePartDimension(FValueSecond).Value, TPLCSSPropertyValuePartDimension(FValueSecond).&Unit, AEnvironment.DocumentBody, 'env:' + FFeature);
end;
case FOperatorSecond of
meroEqual: Result := vf2 = vc;
meroGreater: Result := vf2 > vc;
meroGreaterEqual: Result := vf2 >= vc;
meroLess: Result := vf2 < vc;
meroLessEqual: Result := vf2 <= vc;
end;
end;
end;
end;
end;
function TPLCSSMediaExpressionRange.AsString: TPLString;
begin
Result := '(';
if HasOneSide then begin
Result += FFeature + ' ' + TPLString(FOperatorFirst) + ' ' + FValueFirst.AsString;
end else if HasTwoSides then begin
Result += FValueFirst.AsString + ' ' + TPLString(FOperatorFirst) + ' ' + FFeature +
' ' + TPLString(FOperatorSecond) + ' ' + FValueSecond.AsString;
end;
Result += ')';
end;
{ TPLCSSMediaQuery }
constructor TPLCSSMediaQuery.Create;
begin
inherited Create;
FExpressions := TPLCSSMediaExpressions.Create(true);
FQualifier := mqNone;
FMediaType := 'all';
end;
destructor TPLCSSMediaQuery.Destroy;
begin
FExpressions.Free;
inherited Destroy;
end;
function TPLCSSMediaQuery.Evaluate(
const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
var
e: TPLCSSMediaExpressionBase;
begin
if AEnvironment.UsePrinter then
Result := FMediaType in TPLStringFuncs.NewArray(['all', 'print'])
else Result := FMediaType in TPLStringFuncs.NewArray(['all', 'screen']);
if Result then for e in FExpressions do begin
Result := Result and e.Evaluate(AEnvironment);
if not Result then break;
end;
if FQualifier = mqNot then Result := not Result;
end;
function TPLCSSMediaQuery.AsString: TPLString;
var
e: TPLCSSMediaExpressionBase;
begin
Result := '';
if FQualifier <> mqNone then
case FQualifier of
mqNot: Result := 'not ';
mqOnly: Result := 'only ';
end;
Result += FMediaType;
if FExpressions.Empty then exit;
Result += ' and ';
for e in FExpressions do begin
Result += e.AsString;
if e <> FExpressions.Last then Result += ' and ';
end;
end;
{ TPLCSSMediaQueries }
function TPLCSSMediaQueries.Evaluate(
const AEnvironment: TPLCSSMediaQueriesEnvironment): TPLBool;
var
q: TPLCSSMediaQuery;
begin
Result := false;
for q in self do begin
Result := Result or q.Evaluate(AEnvironment);
if Result then break;
end;
end;
function TPLCSSMediaQueries.AsString: TPLString;
var
q: TPLCSSMediaQuery;
begin
Result := '';
for q in self do begin
Result += q.AsString;
if q <> Last then Result += ', ';
end;
Result := Result.Trim;
end;
{ TPLCSSMediaQueryParser }
class procedure TPLCSSMediaQueryParser.ParseMediaQueries(ASource: TPLString;
var AMediaQueries: TPLCSSMediaQueries);
label
abort_end, one_side2;
const
set_idm = ['A'..'Z', 'a'..'z', '_'];
set_id = set_idm + ['-'];
set_num = ['0'..'9'];
set_comp = ['<', '>', '='];
var
pos: SizeInt = 1;
q: TPLCSSMediaQuery = nil;
function IsEOF: TPLBool; inline;
begin
Result := pos > Length(ASource);
end;
function Current: TPLChar; inline;
begin
Result := ASource[pos];
end;
function Peek: TPLChar; inline;
begin
Result := ifthen(pos+1 > Length(ASource), #0, ASource[pos+1])[1];
end;
procedure ConsumeWhitespace;
begin
while not IsEOF and (Current in ''.WhitespacesArrayString) do Inc(pos);
end;
function GetIdentifier(out id: TPLString): TPLBool;
var
bpos: SizeInt;
begin
Result := true;
id := '';
bpos := pos;
if (Current in ['0'..'9']) or ((Current = '-') and (Peek in ['0'..'9'])) then
Result := false;
if not Result then exit;
while not IsEOF and Result do begin
if Current.IsWhiteSpace or (Current = ':') then break;
if not (Current in (set_id + set_num)) then
Result := false
else begin
id += Current;
Inc(pos);
end;
end;
if not Result then begin
id := '';
pos := bpos;
end;
end;
function GetValue(const stop_chars: TPLCharSet): TPLString;
begin
Result := '';
while not (IsEOF or (Current in stop_chars)) do begin
Result += Current;
Inc(pos);
end;
end;
var
idn, ft, v1, v2, ops: TPLString;
op1, op2: TPLCSSMediaExpressionRangeOperator;
part1, part2: TPLCSSPropertyValuePart;
vf: TPLFloat;
arr: TPLStringArray;
procedure Abort;
begin
if Assigned(q) then q.Free;
if Assigned(part1) then part1.Free;
if Assigned(part2) then part2.Free;
AMediaQueries.Clear;
end;
begin
ASource := ASource.Trim.ToLower.Replace('(', ' ').Replace(')', ' ') + ' ';
while not IsEOF do begin
ConsumeWhitespace;
q := TPLCSSMediaQuery.Create;
if GetIdentifier(idn) then begin
case idn of
'not': q.Qualifier := mqNot;
'only': q.Qualifier := mqOnly;
end;
if q.Qualifier <> mqNone then begin
ConsumeWhitespace;
GetIdentifier(idn);
end;
if idn in TPLStringFuncs.NewArray(['all', 'print', 'screen', 'tty', 'tv',
'projection', 'handheld', 'braille', 'embossed', 'aural', 'speech'])
then begin
q.MediaType := idn;
ConsumeWhitespace;
GetIdentifier(idn);
end;
end;
while not IsEOF do begin
if idn = '' then begin // range
ConsumeWhitespace;
v1 := GetValue(set_comp + [' ']);
ConsumeWhitespace;
if not (Current in set_comp) then goto abort_end;
ops := Current;
Inc(pos);
if Current in set_comp then begin
ops += Current;
Inc(pos);
end;
ConsumeWhitespace;
if not GetIdentifier(idn) then goto abort_end;
ft := idn;
ConsumeWhitespace;
if TryStrToFloat(v1, vf) then
part1 := TPLCSSPropertyValuePartNumber.Create(v1)
else begin
if v1.Exists('/') then begin
arr := v1.Split('/');
if Length(arr) <> 2 then goto abort_end;
arr[0] := arr[0].Trim;
arr[1] := arr[1].Trim;
vf := arr[1];
if vf = 0 then goto abort_end; // cannot divide by 0
part1 := TPLCSSPropertyValuePartFunction.Create('r(%s, %s)'.Format([arr[0], arr[1]])); // ratio function
end else if TPLCSSPropertyValuePartDimension.IsDimensionValue(v1) then
part1 := TPLCSSPropertyValuePartDimension.Create(v1)
else
part1 := TPLCSSPropertyValuePartStringOrIdentifier.Create(v1);
end;
if GetIdentifier(idn) then begin // only one side
case ops of // mirror
'>': op1 := meroLess;
'<': op1 := meroGreater;
'>=': op1 := meroLessEqual;
'<=': op1 := meroGreaterEqual;
else op1 := meroEqual;
end;
q.Expressions.Add(TPLCSSMediaExpressionRange.Create(ft, op1, part1));
part1 := nil;
part2 := nil;
continue;
end;
case ops of
'<': op1 := meroLess;
'>': op1 := meroGreater;
'<=': op1 := meroLessEqual;
'>=': op1 := meroGreaterEqual;
else op1 := meroEqual;
end;
ConsumeWhitespace;
if not (Current in set_comp) then goto abort_end;
ops := Current;
Inc(pos);
if Current in set_comp then begin
ops += Current;
Inc(pos);
end;
ConsumeWhitespace;
case ops of
'<': op2 := meroLess;
'>': op2 := meroGreater;
'<=': op2 := meroLessEqual;
'>=': op2 := meroGreaterEqual;
else op2 := meroEqual;
end;
v2 := GetValue(set_comp + [' ']);
ConsumeWhitespace;
if TryStrToFloat(v2, vf) then
part2 := TPLCSSPropertyValuePartNumber.Create(v2)
else begin
if v2.Exists('/') then begin
arr := v2.Split('/');
if Length(arr) <> 2 then goto abort_end;
arr[0] := arr[0].Trim;
arr[1] := arr[1].Trim;
vf := arr[1];
if vf = 0 then goto abort_end; // cannot divide by 0
part2 := TPLCSSPropertyValuePartFunction.Create('r(%s, %s)'.Format([arr[0], arr[1]])); // ratio function
end else if TPLCSSPropertyValuePartDimension.IsDimensionValue(v2) then
part2 := TPLCSSPropertyValuePartDimension.Create(v2)
else
part2 := TPLCSSPropertyValuePartStringOrIdentifier.Create(v2);
end;
q.Expressions.Add(TPLCSSMediaExpressionRange.Create(ft, op1, op2, part1, part2));
part1 := nil;
part2 := nil;
GetIdentifier(idn);
end else if idn <> 'and' then begin // normal or range?
if Current.IsWhiteSpace then begin // normal without value
ConsumeWhitespace;
if Current in set_comp then goto one_side2;
q.Expressions.Add(TPLCSSMediaExpression.Create(idn));
ConsumeWhitespace;
end else if Current = ':' then begin // normal with value
ConsumeWhitespace;
Inc(pos);
ConsumeWhitespace;
ft := idn;
v1 := GetValue(set_comp + [' ']);
if TryStrToFloat(v1, vf) then
part1 := TPLCSSPropertyValuePartNumber.Create(v1)
else begin
if v1.Exists('/') then begin
arr := v1.Split('/');
if Length(arr) <> 2 then goto abort_end;
arr[0] := arr[0].Trim;
arr[1] := arr[1].Trim;
vf := arr[1];
if vf = 0 then goto abort_end; // cannot divide by 0
part1 := TPLCSSPropertyValuePartFunction.Create('r(%s, %s)'.Format([arr[0], arr[1]])); // ratio function
end else if TPLCSSPropertyValuePartDimension.IsDimensionValue(v1) then
part1 := TPLCSSPropertyValuePartDimension.Create(v1)
else
part1 := TPLCSSPropertyValuePartStringOrIdentifier.Create(v1);
end;
q.Expressions.Add(TPLCSSMediaExpression.Create(ft, part1));
part1 := nil;
part2 := nil;
end else if Current in set_comp then begin // one-side range
ConsumeWhitespace;
one_side2:
ft := idn;
ops := Current;
Inc(pos);
if Current in set_comp then begin
ops += Current;
Inc(pos);
end;
ConsumeWhitespace;
case ops of
'<': op1 := meroLess;
'>': op1 := meroGreater;
'<=': op1 := meroLessEqual;
'>=': op1 := meroGreaterEqual;
else op1 := meroEqual;
end;
ConsumeWhitespace;
v1 := GetValue(set_comp + [' ']);
if TryStrToFloat(v1, vf) then
part1 := TPLCSSPropertyValuePartNumber.Create(v1)
else begin
if v1.Exists('/') then begin
arr := v1.Split('/');
if Length(arr) <> 2 then goto abort_end;
arr[0] := arr[0].Trim;
arr[1] := arr[1].Trim;
vf := arr[1];
if vf = 0 then goto abort_end; // cannot divide by 0
part1 := TPLCSSPropertyValuePartFunction.Create('r(%s, %s)'.Format([arr[0], arr[1]])); // ratio function
end else if TPLCSSPropertyValuePartDimension.IsDimensionValue(v1) then
part1 := TPLCSSPropertyValuePartDimension.Create(v1)
else
part1 := TPLCSSPropertyValuePartStringOrIdentifier.Create(v1);
end;
q.Expressions.Add(TPLCSSMediaExpressionRange.Create(ft, op1, part1));
part1 := nil;
part2 := nil;
end else goto abort_end;
end;
ConsumeWhitespace;
if (Current = ',') or (Current + Peek = 'or') then break;
GetIdentifier(idn);
end;
AMediaQueries.Add(q);
q := nil;
ConsumeWhitespace;
if Current = ',' then Inc(pos);
ConsumeWhitespace;
if Current + Peek = 'or' then Inc(pos, 2);
ConsumeWhitespace;
end;
exit;
abort_end:
Abort;
end;
initialization
Printer.SetPrinter('*'); // set default printer
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;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
const
NAME_C = 'Bill';
PLACE_C = 'Helsinki';
resourcestring
SHello = 'Hello World'; //loc This is a comment
SCharacters = 'Characters'; //loc MaxChars=20 This is characters comment
SPixels = 'Pixels'; //loc MaxPixels=100 This is pixels comment
SFormatNoComment = 'Hello %s, welcome to %s';
SFormatComment = 'Hello %s, welcome to %s'; //loc This is comment but no placeholder descriptions
SFormatPlaceholderComment = 'Hello %s, welcome to %s'; //loc 0: Name of the person, 1: Name of the place
SRegExComment = 'EXPRESSION_100'; //loc RegEx="[A-Z0-9_]*" This can only contains A to Z, numbers and underscore
SIgnore = 'Ignore this'; //noloc
begin
Label1.Caption := SHello;
Label2.Caption := SCharacters;
Label3.Caption := SPixels;
Label4.Caption := Format(SFormatNoComment, [NAME_C, PLACE_C]);
Label5.Caption := Format(SFormatComment, [NAME_C, PLACE_C]);
Label6.Caption := Format(SFormatPlaceholderComment, [NAME_C, PLACE_C]);
Label7.Caption := SRegExComment;
Label8.Caption := SIgnore;
end;
end.
|
unit ControllerObjectItem;
interface
uses ControllerObjectCommandList, ControllerDataTypes;
type
TControllerObjectItem = class
public
ObjectID: Pointer;
BaseObjectID: Pointer;
CommandList: TControllerObjectCommandList;
// constructors and destructors
constructor Create(_Object: Pointer);
destructor Destroy; override;
end;
implementation
constructor TControllerObjectItem.Create(_Object: Pointer);
begin
ObjectID := _Object;
BaseObjectID := nil;
CommandList := TControllerObjectCommandList.Create;
end;
destructor TControllerObjectItem.Destroy;
begin
CommandList.Free;
inherited Destroy;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.