text stringlengths 14 6.51M |
|---|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IPPeerClient, REST.Client,
Data.Bind.Components, Data.Bind.ObjectScope;
type
TForm1 = class(TForm)
Memo1: TMemo;
btnOk: TButton;
tEdit: TEdit;
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
Label1: TLabel;
Button1: TButton;
procedure btnOkClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure RESTRequest1HTTPProtocolError(Sender: TCustomRESTRequest);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnOkClick(Sender: TObject);
begin
if tEdit.Text = '' then
raise Exception.Create('Campo para pesquisa vazio')
else
begin
RESTRequest1.Params.AddUrlSegment('ORIGEM', tEdit.Text);
RESTRequest1.Execute;
Memo1.Lines.Clear;
if (RESTResponse1.JSONValue.GetValue<string>('status') = 'ERROR') or
(RESTResponse1.JSONValue.GetValue<string>('status') = '') then
begin
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('status'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('message'));
btnOk.Enabled := false;
tEdit.Enabled := false;
end
else
begin
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('nome'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('fantasia'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('cnpj'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('tipo'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('situacao'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('abertura'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('logradouro'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('numero'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('complemento'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('cep'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('bairro'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('municipio'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('uf'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('email'));
Memo1.Lines.Add(RESTResponse1.JSONValue.GetValue<string>('telefone'));
btnOk.Enabled := false;
tEdit.Enabled := false;
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Sleep(2000);
btnOk.Enabled := True;
tEdit.Text := '';
tEdit.Enabled:= True;
end;
procedure TForm1.RESTRequest1HTTPProtocolError(Sender: TCustomRESTRequest);
begin
tEdit.Text := '';
raise Exception.Create('ERRO na pesquisa'+#13+
'Verifique se existem pontos ou trašos no campo de pesquisa!');
end;
end.
|
unit ColisionCheck;
interface
uses ColisionCheckBase, BasicMathsTypes, BasicDataTypes;
{$INCLUDE source/Global_Conditionals.inc}
type
PColisionCheck = ^CColisionCheck;
CColisionCheck = class (CColisionCheckBase)
private
function IsVertexInsideOrOutside2DNone(const _VL1, _VL2, _V: TVector2f): byte;
function IsVertexInsideOrOutside2DV1(const _VL1, _VL2, _V: TVector2f): byte;
function IsVertexInsideOrOutside2DV2(const _VL1, _VL2, _V: TVector2f): byte;
function IsVertexInsideOrOutside2DEdge(const _VL1, _VL2, _V: TVector2f): byte;
public
function Are2DTrianglesColiding(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
function Are2DTrianglesColidingEdges(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
function Are2DTrianglesColidingEdgesQuick(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
function Are2DTrianglesOverlapping(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
function Are2DTrianglesOverlappingQuick(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
function Is2DTriangleColidingEdge(const _VA1, _VA2, _VA3, _VB1, _VB2: TVector2f): boolean;
function Is2DTriangleOverlappingEdge(const _VA1, _VA2, _VA3, _VB1, _VB2: TVector2f): boolean;
function Is2DPointInsideTriangle(const _V, _V1, _V2, _V3: TVector2f): boolean;
function Is2DTriangleColidingWithMesh(const _V1, _V2, _V3: TVector2f; const _Coords: TAVector2f; const _Faces: auint32; const _AllowedFaces: abool): boolean;
function Is2DTriangleColidingWithMeshMT(const _V1, _V2, _V3: TVector2f; const _Coords: TAVector2f; const _Faces: auint32; const _AllowedFaces: abool): boolean;
end;
TTriangleColidingMeshStruct = record
Tool: PColisionCheck;
V1, V2, V3: TVector2f;
Coords: TAVector2f;
Faces: auint32;
AllowedFaces: abool;
StartElem,FinalElem: integer;
Result: boolean;
end;
PTriangleColidingMeshStruct = ^TTriangleColidingMeshStruct;
implementation
uses GlobalVars, GenericThread;
function CColisionCheck.IsVertexInsideOrOutside2DNone(const _VL1, _VL2, _V: TVector2f): byte;
var
// DistVVL1, DistVVL2, DistVL1VL2, DetVVL1VL2: single;
VL1VL2: TVector2f;
DetVVL1VL2,DistVL1VL2,ProjVVL: single;
begin
// DistVVL1 := sqrt(((_V.U - _VL1.U) * (_V.U - _VL1.U)) + ((_V.V - _VL1.V) * (_V.V - _VL1.V)));
// DistVVL2 := sqrt(((_V.U - _VL2.U) * (_V.U - _VL2.U)) + ((_V.V - _VL2.V) * (_V.V - _VL2.V)));
// DistVL1VL2 := sqrt(((_VL1.U - _VL2.U) * (_VL1.U - _VL2.U)) + ((_VL1.V - _VL2.V) * (_VL1.V - _VL2.V)));
// determinant.
DetVVL1VL2 := Epsilon((_V.U * _VL1.V) + (_V.V * _VL2.U) + (_VL1.U * _VL2.V) - (_V.U * _VL2.V) - (_V.V * _VL1.U) - (_VL1.V * _VL2.U));
// if (DetVVL1VL2 > 0) or ((DetVVL1VL2 = 0) and ((Epsilon(DistVVL1 + DistVVL2 - DistVL1VL2) > 0))) then
// if (DetVVL1VL2 > 0) or ((DetVVL1VL2 = 0) and ((ProjVVL < 0) or (Epsilon(ProjVVL - 1) > 0))) or ((DetVVL1VL2 < 0) and ((ProjVVL < 0) or (Epsilon(ProjVVL - 1) > 0))) then
if DetVVL1VL2 >= 0 then
begin
if DetVVL1Vl2 = 0 then
begin
VL1VL2.U := (_VL2.U - _VL1.U);
VL1VL2.V := (_VL2.V - _VL1.V);
DistVL1VL2 := sqrt(((_VL1.U - _VL2.U) * (_VL1.U - _VL2.U)) + ((_VL1.V - _VL2.V) * (_VL1.V - _VL2.V)));
VL1VL2.U := VL1VL2.U / DistVL1VL2;
VL1VL2.V := VL1VL2.V / DistVL1VL2;
// Projection
ProjVVL := Epsilon((((_V.U - _VL1.U) * VL1VL2.U) + ((_V.V - _VL1.V) * VL1VL2.V)) / DistVL1VL2);
if ((ProjVVL >= 0) and (Epsilon(ProjVVL - 1) <= 0)) then
begin
Result := 33; // Hack to remove vertexes at the edges.
end
else
begin
Result := 1;
end;
end
else
begin
Result := 1;
end;
end
else
begin
Result := 0;
end;
end;
function CColisionCheck.IsVertexInsideOrOutside2DV1(const _VL1, _VL2, _V: TVector2f): byte;
var
// DistVVL1, DistVVL2, DistVL1VL2, DetVVL1VL2: single;
VL1VL2: TVector2f;
DetVVL1VL2,DistVL1VL2,ProjVVL: single;
begin
// DistVVL1 := sqrt(((_V.U - _VL1.U) * (_V.U - _VL1.U)) + ((_V.V - _VL1.V) * (_V.V - _VL1.V)));
// DistVVL2 := sqrt(((_V.U - _VL2.U) * (_V.U - _VL2.U)) + ((_V.V - _VL2.V) * (_V.V - _VL2.V)));
// determinant.
DetVVL1VL2 := Epsilon((_V.U * _VL1.V) + (_V.V * _VL2.U) + (_VL1.U * _VL2.V) - (_V.U * _VL2.V) - (_V.V * _VL1.U) - (_VL1.V * _VL2.U));
// if (DetVVL1VL2 > 0) or ((DetVVL1VL2 = 0) and ((Epsilon(DistVVL1 + DistVVL2 - DistVL1VL2) > 0) or (Epsilon(DistVVL1) = 0))) then
// if (DetVVL1VL2 > 0) or ((DetVVL1VL2 = 0) and ((ProjVVL <= 0) or (Epsilon(ProjVVL - 1) > 0))) or ((DetVVL1VL2 < 0) and ((ProjVVL < 0) or (Epsilon(ProjVVL - 1) > 0))) then
if DetVVL1VL2 >= 0 then
begin
if DetVVL1Vl2 = 0 then
begin
VL1VL2.U := (_VL2.U - _VL1.U);
VL1VL2.V := (_VL2.V - _VL1.V);
DistVL1VL2 := sqrt(((_VL1.U - _VL2.U) * (_VL1.U - _VL2.U)) + ((_VL1.V - _VL2.V) * (_VL1.V - _VL2.V)));
VL1VL2.U := VL1VL2.U / DistVL1VL2;
VL1VL2.V := VL1VL2.V / DistVL1VL2;
// Projection
ProjVVL := Epsilon((((_V.U - _VL1.U) * VL1VL2.U) + ((_V.V - _VL1.V) * VL1VL2.V)) / DistVL1VL2);
if ((ProjVVL > 0) and (Epsilon(ProjVVL - 1) <= 0)) then
begin
Result := 33; // Hack to remove vertexes at the edges except at VL1.
end
else
begin
Result := 1;
end;
end
else
begin
Result := 1;
end;
end
else
begin
Result := 0;
end;
end;
function CColisionCheck.IsVertexInsideOrOutside2DV2(const _VL1, _VL2, _V: TVector2f): byte;
var
// DistVVL1, DistVVL2, DistVL1VL2, DetVVL1VL2: single;
VL1VL2: TVector2f;
DetVVL1VL2,DistVL1VL2,ProjVVL: single;
begin
// DistVVL1 := sqrt(((_V.U - _VL1.U) * (_V.U - _VL1.U)) + ((_V.V - _VL1.V) * (_V.V - _VL1.V)));
// DistVVL2 := sqrt(((_V.U - _VL2.U) * (_V.U - _VL2.U)) + ((_V.V - _VL2.V) * (_V.V - _VL2.V)));
// determinant.
DetVVL1VL2 := Epsilon((_V.U * _VL1.V) + (_V.V * _VL2.U) + (_VL1.U * _VL2.V) - (_V.U * _VL2.V) - (_V.V * _VL1.U) - (_VL1.V * _VL2.U));
// if (DetVVL1VL2 > 0) or ((DetVVL1VL2 = 0) and ((Epsilon(DistVVL1 + DistVVL2 - DistVL1VL2) > 0) or (Epsilon(DistVVL2) = 0))) then
// if (DetVVL1VL2 > 0) or ((DetVVL1VL2 = 0) and ((ProjVVL < 0) or (Epsilon(ProjVVL - 1) >= 0))) or ((DetVVL1VL2 < 0) and ((ProjVVL < 0) or (Epsilon(ProjVVL - 1) > 0))) then
if DetVVL1VL2 >= 0 then
begin
if DetVVL1Vl2 = 0 then
begin
VL1VL2.U := (_VL2.U - _VL1.U);
VL1VL2.V := (_VL2.V - _VL1.V);
DistVL1VL2 := sqrt(((_VL1.U - _VL2.U) * (_VL1.U - _VL2.U)) + ((_VL1.V - _VL2.V) * (_VL1.V - _VL2.V)));
VL1VL2.U := VL1VL2.U / DistVL1VL2;
VL1VL2.V := VL1VL2.V / DistVL1VL2;
// Projection
ProjVVL := Epsilon((((_V.U - _VL1.U) * VL1VL2.U) + ((_V.V - _VL1.V) * VL1VL2.V)) / DistVL1VL2);
if ((ProjVVL >= 0) and (Epsilon(ProjVVL - 1) < 0)) then
begin
Result := 33; // Hack to remove vertexes at the edges except at VL2.
end
else
begin
Result := 1;
end;
end
else
begin
Result := 1;
end;
end
else
begin
Result := 0;
end;
end;
function CColisionCheck.IsVertexInsideOrOutside2DEdge(const _VL1, _VL2, _V: TVector2f): byte;
var
// DistVVL1, DistVVL2, DistVL1VL2, DetVVL1VL2,ProjVVL: single;
VL1VL2: TVector2f;
DetVVL1VL2,DistVL1VL2,ProjVVL: single;
begin
// DistVVL1 := sqrt(((_V.U - _VL1.U) * (_V.U - _VL1.U)) + ((_V.V - _VL1.V) * (_V.V - _VL1.V)));
// DistVVL2 := sqrt(((_V.U - _VL2.U) * (_V.U - _VL2.U)) + ((_V.V - _VL2.V) * (_V.V - _VL2.V)));
// determinant.
DetVVL1VL2 := Epsilon((_V.U * _VL1.V) + (_V.V * _VL2.U) + (_VL1.U * _VL2.V) - (_V.U * _VL2.V) - (_V.V * _VL1.U) - (_VL1.V * _VL2.U));
// if (DetVVL1VL2 > 0) or ((DetVVL1VL2 = 0) and ((ProjVVL <= 0) or (Epsilon(ProjVVL - 1) >= 0))) or ((DetVVL1VL2 < 0) and ((ProjVVL < 0) or (Epsilon(ProjVVL - 1) > 0))) then
if DetVVL1VL2 >= 0 then
begin
if DetVVL1Vl2 = 0 then
begin
VL1VL2.U := (_VL2.U - _VL1.U);
VL1VL2.V := (_VL2.V - _VL1.V);
DistVL1VL2 := sqrt(((_VL1.U - _VL2.U) * (_VL1.U - _VL2.U)) + ((_VL1.V - _VL2.V) * (_VL1.V - _VL2.V)));
VL1VL2.U := VL1VL2.U / DistVL1VL2;
VL1VL2.V := VL1VL2.V / DistVL1VL2;
// Projection
ProjVVL := Epsilon((((_V.U - _VL1.U) * VL1VL2.U) + ((_V.V - _VL1.V) * VL1VL2.V)) / DistVL1VL2);
if ((ProjVVL > 0) and (Epsilon(ProjVVL - 1) < 0)) then
begin
Result := 33; // Hack to remove vertexes at the edges except at VL1 and VL2.
end
else
begin
Result := 1;
end;
end
else
begin
Result := 1;
end;
end
else
begin
Result := 0;
end;
end;
{
function CColisionCheck.IsVertexInsideOrOutside2DEdge(const _VL1, _VL2, _V: TVector2f): byte;
var
DetVL1Vl2: single;
begin
// determinant.
DetVL1Vl2 := (_V.U * _VL1.V) + (_V.V * _VL2.U) + (_VL1.U * _VL2.V) - (_V.U * _VL2.V) - (_V.V * _VL1.U) - (_VL1.V * _VL2.U);
if Epsilon(DetVL1Vl2) <= 0 then
begin
Result := 1;
end
else
begin
Result := 0;
end;
end;
}
function CColisionCheck.Are2DTrianglesColiding(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
var
VertexConfig1,VertexConfig2,VertexConfig3: byte;
begin
Result := true; // assume true for optimization
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DEdge(_VA1, _VA2, _VB1) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3,_VB1)) or (4 * IsVertexInsideOrOutside2DEdge(_VA3, _VA1, _VB1));
if VertexConfig1 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DEdge(_VA1, _VA2, _VB2) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB2)) or (4 * IsVertexInsideOrOutside2DEdge(_VA3, _VA1, _VB2));
if VertexConfig2 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 3
VertexConfig3 := IsVertexInsideOrOutside2DEdge(_VA1, _VA2, _VB3) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB3)) or (4 * IsVertexInsideOrOutside2DEdge(_VA3, _VA1, _VB3));
if VertexConfig3 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the line segments
if (VertexConfig1 and VertexConfig2) = 0 then
begin
exit; // return true, the line segment crosses the triangle.
end;
if (VertexConfig2 and VertexConfig3) = 0 then
begin
exit; // return true, the line segment crosses the triangle.
end;
if (VertexConfig1 and VertexConfig3) = 0 then
begin
exit; // return true, the line segment crosses the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2 and VertexConfig3) = 0 then
begin
exit; // return true, the triangle contains the other triangle.
end;
Result := false; // return false. There is no colision between the two triangles.
end;
function CColisionCheck.Are2DTrianglesColidingEdges(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
var
VertexConfig1,VertexConfig2,VertexConfig3: byte;
begin
Result := true; // assume true for optimization
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DV2(_VA1, _VA2, _VB1) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3,_VB1)) or (4 * IsVertexInsideOrOutside2DV1(_VA3, _VA1, _VB1));
if (VertexConfig1 = 0) or (VertexConfig1 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DV2(_VA1, _VA2, _VB2) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB2)) or (4 * IsVertexInsideOrOutside2DV1(_VA3, _VA1, _VB2));
if (VertexConfig2 = 0) or (VertexConfig2 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 3
VertexConfig3 := IsVertexInsideOrOutside2DV2(_VA1, _VA2, _VB3) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB3)) or (4 * IsVertexInsideOrOutside2DV1(_VA3, _VA1, _VB3));
if (VertexConfig3 = 0) or (VertexConfig3 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2 and VertexConfig3) = 0 then
begin
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DNone(_VB1, _VB2, _VA1) or (2 * IsVertexInsideOrOutside2DNone(_VB2, _VB3,_VA1)) or (4 * IsVertexInsideOrOutside2DNone(_VB3, _VB1, _VA1));
if (VertexConfig1 = 0) or (VertexConfig1 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DEdge(_VB1, _VB2, _VA2) or (2 * IsVertexInsideOrOutside2DEdge(_VB2, _VB3, _VA2)) or (4 * IsVertexInsideOrOutside2DEdge(_VB3, _VB1, _VA2));
if (VertexConfig2 = 0) or (VertexConfig2 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 3
VertexConfig3 := IsVertexInsideOrOutside2DEdge(_VB1, _VB2, _VA3) or (2 * IsVertexInsideOrOutside2DEdge(_VB2, _VB3, _VA3)) or (4 * IsVertexInsideOrOutside2DEdge(_VB3, _VB1, _VA3));
if (VertexConfig3 = 0) or (VertexConfig3 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2 and VertexConfig3) = 0 then
begin
exit;
end;
end;
Result := false; // return false. There is no colision between the two triangles.
end;
function CColisionCheck.Are2DTrianglesColidingEdgesQuick(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
var
VertexConfig1,VertexConfig2,VertexConfig3: byte;
begin
Result := true; // assume true for optimization
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DV2(_VA1, _VA2, _VB1) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3,_VB1)) or (4 * IsVertexInsideOrOutside2DV1(_VA3, _VA1, _VB1));
if VertexConfig1 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DV2(_VA1, _VA2, _VB2) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB2)) or (4 * IsVertexInsideOrOutside2DV1(_VA3, _VA1, _VB2));
if VertexConfig2 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 3
VertexConfig3 := IsVertexInsideOrOutside2DV2(_VA1, _VA2, _VB3) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB3)) or (4 * IsVertexInsideOrOutside2DV1(_VA3, _VA1, _VB3));
if VertexConfig3 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2 and VertexConfig3) = 0 then
begin
exit; // return true, the triangle contains the other triangle.
end;
Result := false; // return false. There is no colision between the two triangles.
end;
function CColisionCheck.Are2DTrianglesOverlapping(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
var
VertexConfig1,VertexConfig2,VertexConfig3: byte;
begin
Result := true; // assume true for optimization
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DEdge(_VB1, _VB2, _VA1) or (2 * IsVertexInsideOrOutside2DEdge(_VB2, _VB3,_VA1)) or (4 * IsVertexInsideOrOutside2DEdge(_VB3, _VB1, _VA1));
if (VertexConfig1 = 0) or (VertexConfig1 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DEdge(_VB1, _VB2, _VA2) or (2 * IsVertexInsideOrOutside2DEdge(_VB2, _VB3, _VA2)) or (4 * IsVertexInsideOrOutside2DEdge(_VB3, _VB1, _VA2));
if (VertexConfig2 = 0) or (VertexConfig2 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 3
VertexConfig3 := IsVertexInsideOrOutside2DEdge(_VB1, _VB2, _VA3) or (2 * IsVertexInsideOrOutside2DEdge(_VB2, _VB3, _VA3)) or (4 * IsVertexInsideOrOutside2DEdge(_VB3, _VB1, _VA3));
if (VertexConfig3 = 0) or (VertexConfig3 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2 and VertexConfig3) = 0 then
begin
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DEdge(_VA1, _VA2, _VB1) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3,_VB1)) or (4 * IsVertexInsideOrOutside2DEdge(_VA3, _VA1, _VB1));
if VertexConfig1 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DEdge(_VA1, _VA2, _VB2) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB2)) or (4 * IsVertexInsideOrOutside2DEdge(_VA3, _VA1, _VB2));
if VertexConfig2 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 3
VertexConfig3 := IsVertexInsideOrOutside2DEdge(_VA1, _VA2, _VB3) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB3)) or (4 * IsVertexInsideOrOutside2DEdge(_VA3, _VA1, _VB3));
if VertexConfig3 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2 and VertexConfig3 and 7) = 0 then
begin
exit; // return true, the triangle contains the other triangle.
end;
end;
Result := false; // return false. There is no colision between the two triangles.
end;
function CColisionCheck.Are2DTrianglesOverlappingQuick(const _VA1, _VA2, _VA3, _VB1, _VB2, _VB3: TVector2f): boolean;
var
VertexConfig1,VertexConfig2,VertexConfig3: byte;
begin
Result := true; // assume true for optimization
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DEdge(_VB1, _VB2, _VA1) or (2 * IsVertexInsideOrOutside2DEdge(_VB2, _VB3,_VA1)) or (4 * IsVertexInsideOrOutside2DEdge(_VB3, _VB1, _VA1));
if VertexConfig1 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DEdge(_VB1, _VB2, _VA2) or (2 * IsVertexInsideOrOutside2DEdge(_VB2, _VB3, _VA2)) or (4 * IsVertexInsideOrOutside2DEdge(_VB3, _VB1, _VA2));
if VertexConfig2 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 3
VertexConfig3 := IsVertexInsideOrOutside2DEdge(_VB1, _VB2, _VA3) or (2 * IsVertexInsideOrOutside2DEdge(_VB2, _VB3, _VA3)) or (4 * IsVertexInsideOrOutside2DEdge(_VB3, _VB1, _VA3));
if VertexConfig3 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2 and VertexConfig3) = 0 then
begin
exit; // return true, the triangle contains the other triangle.
end;
Result := false; // return false. There is no colision between the two triangles.
end;
function CColisionCheck.Is2DTriangleColidingEdge(const _VA1, _VA2, _VA3, _VB1, _VB2: TVector2f): boolean;
var
VertexConfig1,VertexConfig2: byte;
begin
Result := true; // assume true for optimization
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DV2(_VA1, _VA2, _VB1) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3,_VB1)) or (4 * IsVertexInsideOrOutside2DV1(_VA3, _VA1, _VB1));
if (VertexConfig1 = 0) or (VertexConfig1 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DV2(_VA1, _VA2, _VB2) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB2)) or (4 * IsVertexInsideOrOutside2DV1(_VA3, _VA1, _VB2));
if (VertexConfig2 = 0) or (VertexConfig2 >= 16) then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2) = 0 then
begin
exit;
end;
Result := false; // return false. There is no colision between the two triangles.
end;
function CColisionCheck.Is2DTriangleOverlappingEdge(const _VA1, _VA2, _VA3, _VB1, _VB2: TVector2f): boolean;
var
VertexConfig1,VertexConfig2: byte;
begin
Result := true; // assume true for optimization
// Collect vertex configurations. 1 is outside and 0 is inside.
// Vertex 1
VertexConfig1 := IsVertexInsideOrOutside2DEdge(_VA1, _VA2, _VB1) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3,_VB1)) or (4 * IsVertexInsideOrOutside2DEdge(_VA3, _VA1, _VB1));
if VertexConfig1 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Vertex 2
VertexConfig2 := IsVertexInsideOrOutside2DEdge(_VA1, _VA2, _VB2) or (2 * IsVertexInsideOrOutside2DEdge(_VA2, _VA3, _VB2)) or (4 * IsVertexInsideOrOutside2DEdge(_VA3, _VA1, _VB2));
if VertexConfig2 = 0 then
begin
exit; // return true, the vertex is inside the triangle.
end;
// Now let's check the triangle, if it contains the other or not.
if (VertexConfig1 and VertexConfig2 and 7) = 0 then
begin
exit; // return true, the triangle contains the other triangle.
end;
Result := false; // return false. There is no colision between the two triangles.
end;
function CColisionCheck.Is2DPointInsideTriangle(const _V, _V1, _V2, _V3: TVector2f): boolean;
var
VertexConfig: byte;
begin
// Collect vertex configuration. 1 is outside and 0 is inside.
VertexConfig := IsVertexInsideOrOutside2DEdge(_V1, _V2, _V) or (2 * IsVertexInsideOrOutside2DEdge(_V2, _V3,_V)) or (4 * IsVertexInsideOrOutside2DEdge(_V3, _V1, _V));
Result := VertexConfig = 0;
end;
function CColisionCheck.Is2DTriangleColidingWithMesh(const _V1, _V2, _V3: TVector2f; const _Coords: TAVector2f; const _Faces: auint32; const _AllowedFaces: abool): boolean;
var
i, v: integer;
begin
// Let's check if this UV Position will hit another UV project face.
Result := true;
v := 0;
for i := Low(_AllowedFaces) to High(_AllowedFaces) do
begin
// If the face was projected in the UV domain.
if _AllowedFaces[i] then
begin
// Check if the candidate position is inside this triangle.
// If it is inside the triangle, then point is not validated. Exit.
if Are2DTrianglesColiding(_V1,_V2,_V3,_Coords[_Faces[v]],_Coords[_Faces[v+1]],_Coords[_Faces[v+2]]) then
begin
Result := false;
exit;
end;
end;
inc(v,3);
end;
end;
function ThreadIs2DTriangleColidingWithMesh(const _args: pointer): integer;
var
Data: TTriangleColidingMeshStruct;
i, v: integer;
begin
if _args <> nil then
begin
Data := PTriangleColidingMeshStruct(_args)^;
// Let's check if this UV Position will hit another UV project face.
Data.Result := false;
v := 0;
for i := Data.StartElem to Data.FinalElem do
begin
// If the face was projected in the UV domain.
if Data.AllowedFaces[i] = true then
begin
// Check if the candidate position is inside this triangle.
// If it is inside the triangle, then point is not validated. Exit.
if (Data.Tool)^.Are2DTrianglesColiding(Data.V1,Data.V2,Data.V3,Data.Coords[Data.Faces[v]],Data.Coords[Data.Faces[v+1]],Data.Coords[Data.Faces[v+2]]) then
begin
Data.Result := true;
exit;
end;
end;
inc(v,3);
end;
end;
end;
function CColisionCheck.Is2DTriangleColidingWithMeshMT(const _V1, _V2, _V3: TVector2f; const _Coords: TAVector2f; const _Faces: auint32; const _AllowedFaces: abool): boolean;
function CreatePackageForThreadCall(const _V1, _V2, _V3: TVector2f; const _Coords: TAVector2f; const _Faces: auint32; const _AllowedFaces: abool; _StartElem,_FinalElem: integer): TTriangleColidingMeshStruct;
begin
Result.Tool := Addr(self);
Result.V1 := _V1;
Result.V2 := _V2;
Result.V3 := _V3;
Result.Coords := _Coords;
Result.Faces := _Faces;
Result.AllowedFaces := _AllowedFaces;
Result.StartElem := _StartElem;
Result.FinalElem := _FinalElem;
end;
var
i, e, step, maxThreads: integer;
Packages: array of TTriangleColidingMeshStruct;
Threads: array of TGenericThread;
MyFunction : TGenericFunction;
begin
maxThreads := GlobalVars.SysInfo.PhysicalCore;
e := 0;
step := (High(_AllowedFaces) + 1) div maxThreads;
SetLength(Threads, maxThreads);
SetLength(Packages, maxThreads);
MyFunction := ThreadIs2DTriangleColidingWithMesh;
for i := 0 to (maxThreads - 2) do
begin
Packages[i] := CreatePackageForThreadCall(_V1, _V2, _V3, _Coords, _Faces, _AllowedFaces, e, e + step - 1);
Threads[i] := TGenericThread.Create(MyFunction,Addr(Packages[i]));
e := e + step;
end;
// Last thread has a special code.
i := maxThreads - 1;
Packages[i] := CreatePackageForThreadCall(_V1, _V2, _V3, _Coords, _Faces, _AllowedFaces, e, High(_AllowedFaces));
Threads[i] := TGenericThread.Create(MyFunction,Addr(Packages[i]));
for i := 0 to (maxThreads - 1) do
begin
Threads[i].WaitFor;
Threads[i].Free;
end;
Result := false;
for i := 0 to (maxThreads - 1) do
begin
Result := Result or Packages[i].Result;
end;
SetLength(Threads,0);
SetLength(Packages,0);
end;
end.
|
(*
Category: SWAG Title: NOVELL/LANTASTIC NETWORK ROUTINES
Original name: 0054.PAS
Description: AS/400 to ASCII converter
Author: TOBIAS SCHROEDEL
Date: 08-30-97 10:09
*)
{
This code if herewith given to the public domain and may be used for and in
any situation needed. It may help you to convert AS/400 data to ASCII char
set.
It is not yet the fastest as I use a Blockread with 1 Byte only, but you
can optimize it yourself.
I will not take any responsibilty in any case if your data is not accurate
after usage or something is destroyed. Therefore compile it yourself and
it is your code.
Toby Schroedel
}
Program AS400_to_ASCII;
Uses
Dos, Crt;
Const
AS400Table : Array[0..255] of Integer =
{Note : Char #10 should normally be set to #0, because it is unknown,
BUT as it is the LF command of an ASCII file it should transfer to #10
also. Please change, if needed !}
( 0, 1, 2, 3, 0, 9, 0,127, 0, 0, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 0, 0, 8, 0, 24, 25, 0, 0, 28, 29, 30, 31,
0, 0, 0, 0, 0, 10, 23, 27, 0, 0, 0, 0, 0, 5, 6, 7,
0, 0, 22, 0, 0, 0, 0, 4, 0, 0, 0, 0, 20, 21, 0, 26,
32, 32,131,132,133,160,166,134,135,164, 91, 46, 60, 40, 43,124,
38,130,136,137,138,161,140,139,141,225, 93, 36, 42, 41, 59,170,
45, 47, 0,142, 0, 0, 0,143,128,165,124, 44, 37, 95, 62, 63,
237,144, 0, 0, 0, 0, 0, 0, 0, 96, 58, 35, 64, 39, 61, 34,
237, 97, 98, 99,100,101,102,103,104,105,174,175,235, 0, 0,241,
248,106,107,108,109,110,111,112,113,114,166,167,145, 0,146, 0,
230,126,115,116,117,118,119,120,121,122,173,168, 0, 89, 0, 0,
94,156,157,250, 0, 21, 20,172,171, 0, 91, 93, 0, 0, 39, 0,
123, 65, 66, 67, 68, 69, 70, 71, 72, 73, 45,147,148,149,162,167,
125, 74, 75, 76, 77, 78, 79, 80, 81, 82, 0,150,129,151,163,152,
92,246, 83, 84, 85, 86, 87, 88, 89, 90,253, 0,153, 0, 0, 0,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0,150,154, 0, 0, 0);
Var
FIn, FOut : File;
KeyPress,
SIn, SOut : Char;
FSize,
Counter : LongInt;
ErrText : String;
Function Prozent(Ist, Gesamt : Real) : LongInt;
Begin;
If Gesamt > 0
Then Prozent:=Trunc(Ist / Gesamt *100)
Else Prozent := 0;
End;
Function FileExist(strn : String) : Boolean;
Var
FileInfo : SearchRec;
Begin;
FindFirst(Strn,AnyFile,FileInfo);
If DosError=0 then FileExist:=TRUE else FileExist:=FALSE;
end;
Function Convert_AS400_to_ASCII ( S : Char ) : Char;
Var
L : Integer;
{I : Byte;}
O : Char;
Begin;
L := Ord( S );
O := Chr( AS400Table[ L ] );
Convert_AS400_to_ASCII := O;
End;
Begin;
ClrScr;
WriteLn('AS/400 to ASCII file converter');
Writeln('- Freeware, no warranty, use at your own risk -');
Writeln;
ErrText := '';
If ParamCount <> 2 Then Begin;
ErrText := ErrText + 'Incorrect parameters.' + #13;
End Else Begin
If not FileExist( ParamStr( 1 )) Then ErrText := ErrText + 'Inputfile not found.' + #13;
If FileExist( ParamStr( 2 )) Then ErrText := ErrText + 'Outputfile already exists.' + #13;
End;
If ErrText <> '' Then Begin;
WriteLn('AS/400 to ASCII file converter');
WriteLn('AS4_ASCI <Infile> <Outfile>');
WriteLn( ErrText );
Halt;
End;
Counter := 0;
Assign( FIn , ParamStr( 1 ));
Assign( FOut, ParamStr( 2 ));
Reset( FIn, 1 );
ReWrite( FOut, 1 );
FSize := FileSize( FIn );
GotoXY(1,3);
Write('Conversion progress : ');
While not Eof(FIn) Do begin;
If KeyPressed Then Begin;
KeyPress := ReadKey;
If KeyPress = #27 Then Exit;
End;
Inc( Counter );
GotoXY( 23, 3 );
Write( Prozent( Counter, FSize ), '%');
BlockRead( FIn, SIn , 1);
SOut := Convert_AS400_to_ASCII( SIn );
BlockWrite( FOut, SOut, 1 );
End;
Close( FIn );
Close( FOut );
End.
|
(*==========================================================================;
*
* Copyright (C) 1995-1997 Microsoft Corporation. All Rights Reserved.
*
* File: d3dcaps.h
* Content: Direct3D capabilities include file
*
* DirectX 5 Delphi adaptation by Erik Unger
* (based on Blake Stone's DirectX 3 adaptation)
*
* Modyfied: 21.3.98
*
* Download: http://www.sbox.tu-graz.ac.at/home/ungerik/DelphiGraphics/
* E-Mail: h_unger@magnet.at
*
***************************************************************************)
unit D3DCaps;
{$MODE Delphi}
{$INCLUDE COMSWITCH.INC}
interface
uses
{$IFDEF D2COM}
OLE2,
{$ENDIF}
Windows,
D3DTypes,
DDraw;
(* Description of capabilities of transform *)
type
TD3DTransformCaps = packed record
dwSize: DWORD;
dwCaps: DWORD;
end;
const
D3DTRANSFORMCAPS_CLIP = $00000001; (* Will clip whilst transforming *)
(* Description of capabilities of lighting *)
type
TD3DLightingCaps = packed record
dwSize: DWORD;
dwCaps: DWORD; (* Lighting caps *)
dwLightingModel: DWORD; (* Lighting model - RGB or mono *)
dwNumLights: DWORD; (* Number of lights that can be handled *)
end;
const
D3DLIGHTINGMODEL_RGB = $00000001;
D3DLIGHTINGMODEL_MONO = $00000002;
D3DLIGHTCAPS_POINT = $00000001; (* Point lights supported *)
D3DLIGHTCAPS_SPOT = $00000002; (* Spot lights supported *)
D3DLIGHTCAPS_DIRECTIONAL = $00000004; (* Directional lights supported *)
D3DLIGHTCAPS_PARALLELPOINT = $00000008; (* Parallel point lights supported *)
D3DLIGHTCAPS_GLSPOT = $00000010; (* GL syle spot lights supported *)
(* Description of capabilities for each primitive type *)
type
TD3DPrimCaps = packed record
dwSize: DWORD;
dwMiscCaps: DWORD; (* Capability flags *)
dwRasterCaps: DWORD;
dwZCmpCaps: DWORD;
dwSrcBlendCaps: DWORD;
dwDestBlendCaps: DWORD;
dwAlphaCmpCaps: DWORD;
dwShadeCaps: DWORD;
dwTextureCaps: DWORD;
dwTextureFilterCaps: DWORD;
dwTextureBlendCaps: DWORD;
dwTextureAddressCaps: DWORD;
dwStippleWidth: DWORD; (* maximum width and height of *)
dwStippleHeight: DWORD; (* of supported stipple (up to 32x32) *)
end;
const
(* TD3DPrimCaps dwMiscCaps *)
D3DPMISCCAPS_MASKPLANES = $00000001;
D3DPMISCCAPS_MASKZ = $00000002;
D3DPMISCCAPS_LINEPATTERNREP = $00000004;
D3DPMISCCAPS_CONFORMANT = $00000008;
D3DPMISCCAPS_CULLNONE = $00000010;
D3DPMISCCAPS_CULLCW = $00000020;
D3DPMISCCAPS_CULLCCW = $00000040;
(* TD3DPrimCaps dwRasterCaps *)
D3DPRASTERCAPS_DITHER = $00000001;
D3DPRASTERCAPS_ROP2 = $00000002;
D3DPRASTERCAPS_XOR = $00000004;
D3DPRASTERCAPS_PAT = $00000008;
D3DPRASTERCAPS_ZTEST = $00000010;
D3DPRASTERCAPS_SUBPIXEL = $00000020;
D3DPRASTERCAPS_SUBPIXELX = $00000040;
D3DPRASTERCAPS_FOGVERTEX = $00000080;
D3DPRASTERCAPS_FOGTABLE = $00000100;
D3DPRASTERCAPS_STIPPLE = $00000200;
D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT = $00000400;
D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT = $00000800;
D3DPRASTERCAPS_ANTIALIASEDGES = $00001000;
D3DPRASTERCAPS_MIPMAPLODBIAS = $00002000;
D3DPRASTERCAPS_ZBIAS = $00004000;
D3DPRASTERCAPS_ZBUFFERLESSHSR = $00008000;
D3DPRASTERCAPS_FOGRANGE = $00010000;
D3DPRASTERCAPS_ANISOTROPY = $00020000;
(* TD3DPrimCaps dwZCmpCaps, dwAlphaCmpCaps *)
const
D3DPCMPCAPS_NEVER = $00000001;
D3DPCMPCAPS_LESS = $00000002;
D3DPCMPCAPS_EQUAL = $00000004;
D3DPCMPCAPS_LESSEQUAL = $00000008;
D3DPCMPCAPS_GREATER = $00000010;
D3DPCMPCAPS_NOTEQUAL = $00000020;
D3DPCMPCAPS_GREATEREQUAL = $00000040;
D3DPCMPCAPS_ALWAYS = $00000080;
(* TD3DPrimCaps dwSourceBlendCaps, dwDestBlendCaps *)
D3DPBLENDCAPS_ZERO = $00000001;
D3DPBLENDCAPS_ONE = $00000002;
D3DPBLENDCAPS_SRCCOLOR = $00000004;
D3DPBLENDCAPS_INVSRCCOLOR = $00000008;
D3DPBLENDCAPS_SRCALPHA = $00000010;
D3DPBLENDCAPS_INVSRCALPHA = $00000020;
D3DPBLENDCAPS_DESTALPHA = $00000040;
D3DPBLENDCAPS_INVDESTALPHA = $00000080;
D3DPBLENDCAPS_DESTCOLOR = $00000100;
D3DPBLENDCAPS_INVDESTCOLOR = $00000200;
D3DPBLENDCAPS_SRCALPHASAT = $00000400;
D3DPBLENDCAPS_BOTHSRCALPHA = $00000800;
D3DPBLENDCAPS_BOTHINVSRCALPHA = $00001000;
(* TD3DPrimCaps dwShadeCaps *)
D3DPSHADECAPS_COLORFLATMONO = $00000001;
D3DPSHADECAPS_COLORFLATRGB = $00000002;
D3DPSHADECAPS_COLORGOURAUDMONO = $00000004;
D3DPSHADECAPS_COLORGOURAUDRGB = $00000008;
D3DPSHADECAPS_COLORPHONGMONO = $00000010;
D3DPSHADECAPS_COLORPHONGRGB = $00000020;
D3DPSHADECAPS_SPECULARFLATMONO = $00000040;
D3DPSHADECAPS_SPECULARFLATRGB = $00000080;
D3DPSHADECAPS_SPECULARGOURAUDMONO = $00000100;
D3DPSHADECAPS_SPECULARGOURAUDRGB = $00000200;
D3DPSHADECAPS_SPECULARPHONGMONO = $00000400;
D3DPSHADECAPS_SPECULARPHONGRGB = $00000800;
D3DPSHADECAPS_ALPHAFLATBLEND = $00001000;
D3DPSHADECAPS_ALPHAFLATSTIPPLED = $00002000;
D3DPSHADECAPS_ALPHAGOURAUDBLEND = $00004000;
D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED = $00008000;
D3DPSHADECAPS_ALPHAPHONGBLEND = $00010000;
D3DPSHADECAPS_ALPHAPHONGSTIPPLED = $00020000;
D3DPSHADECAPS_FOGFLAT = $00040000;
D3DPSHADECAPS_FOGGOURAUD = $00080000;
D3DPSHADECAPS_FOGPHONG = $00100000;
(* TD3DPrimCaps dwTextureCaps *)
D3DPTEXTURECAPS_PERSPECTIVE = $00000001;
D3DPTEXTURECAPS_POW2 = $00000002;
D3DPTEXTURECAPS_ALPHA = $00000004;
D3DPTEXTURECAPS_TRANSPARENCY = $00000008;
D3DPTEXTURECAPS_BORDER = $00000010;
D3DPTEXTURECAPS_SQUAREONLY = $00000020;
(* TD3DPrimCaps dwTextureFilterCaps *)
D3DPTFILTERCAPS_NEAREST = $00000001;
D3DPTFILTERCAPS_LINEAR = $00000002;
D3DPTFILTERCAPS_MIPNEAREST = $00000004;
D3DPTFILTERCAPS_MIPLINEAR = $00000008;
D3DPTFILTERCAPS_LINEARMIPNEAREST = $00000010;
D3DPTFILTERCAPS_LINEARMIPLINEAR = $00000020;
(* TD3DPrimCaps dwTextureBlendCaps *)
D3DPTBLENDCAPS_DECAL = $00000001;
D3DPTBLENDCAPS_MODULATE = $00000002;
D3DPTBLENDCAPS_DECALALPHA = $00000004;
D3DPTBLENDCAPS_MODULATEALPHA = $00000008;
D3DPTBLENDCAPS_DECALMASK = $00000010;
D3DPTBLENDCAPS_MODULATEMASK = $00000020;
D3DPTBLENDCAPS_COPY = $00000040;
D3DPTBLENDCAPS_ADD = $00000080;
(* TD3DPrimCaps dwTextureAddressCaps *)
D3DPTADDRESSCAPS_WRAP = $00000001;
D3DPTADDRESSCAPS_MIRROR = $00000002;
D3DPTADDRESSCAPS_CLAMP = $00000004;
D3DPTADDRESSCAPS_BORDER = $00000008;
D3DPTADDRESSCAPS_INDEPENDENTUV = $00000010;
(*
* Description for a device.
* This is used to describe a device that is to be created or to query
* the current device.
*)
type
PD3DDeviceDesc = ^TD3DDeviceDesc;
TD3DDeviceDesc = packed record
dwSize: DWORD; (* Size of TD3DDeviceDesc structure *)
dwFlags: DWORD; (* Indicates which fields have valid data *)
dcmColorModel: TD3DColorModel; (* Color model of device *)
dwDevCaps: DWORD; (* Capabilities of device *)
dtcTransformCaps: TD3DTransformCaps; (* Capabilities of transform *)
bClipping: BOOL; (* Device can do 3D clipping *)
dlcLightingCaps: TD3DLightingCaps; (* Capabilities of lighting *)
dpcLineCaps: TD3DPrimCaps;
dpcTriCaps: TD3DPrimCaps;
dwDeviceRenderBitDepth: DWORD; (* One of DDBB_8, 16, etc.. *)
dwDeviceZBufferBitDepth: DWORD; (* One of DDBD_16, 32, etc.. *)
dwMaxBufferSize: DWORD; (* Maximum execute buffer size *)
dwMaxVertexCount: DWORD; (* Maximum vertex count *)
// *** New fields for DX5 *** //
// Width and height caps are 0 for legacy HALs.
dwMinTextureWidth, dwMinTextureHeight : DWORD;
dwMaxTextureWidth, dwMaxTextureHeight : DWORD;
dwMinStippleWidth, dwMaxStippleWidth : DWORD;
dwMinStippleHeight, dwMaxStippleHeight : DWORD;
end;
const
D3DDEVICEDESCSIZE = sizeof(TD3DDeviceDesc);
type
TD3DEnumDevicesCallback = function (const lpGuid: TGUID;
lpDeviceDescription: LPSTR; lpDeviceName: LPSTR;
const lpD3DHWDeviceDesc: TD3DDeviceDesc;
const lpD3DHELDeviceDesc: TD3DDeviceDesc;
lpUserArg: Pointer) : HResult; stdcall;
(* TD3DDeviceDesc dwFlags indicating valid fields *)
const
D3DDD_COLORMODEL = $00000001; (* dcmColorModel is valid *)
D3DDD_DEVCAPS = $00000002; (* dwDevCaps is valid *)
D3DDD_TRANSFORMCAPS = $00000004; (* dtcTransformCaps is valid *)
D3DDD_LIGHTINGCAPS = $00000008; (* dlcLightingCaps is valid *)
D3DDD_BCLIPPING = $00000010; (* bClipping is valid *)
D3DDD_LINECAPS = $00000020; (* dpcLineCaps is valid *)
D3DDD_TRICAPS = $00000040; (* dpcTriCaps is valid *)
D3DDD_DEVICERENDERBITDEPTH = $00000080; (* dwDeviceRenderBitDepth is valid *)
D3DDD_DEVICEZBUFFERBITDEPTH = $00000100; (* dwDeviceZBufferBitDepth is valid *)
D3DDD_MAXBUFFERSIZE = $00000200; (* dwMaxBufferSize is valid *)
D3DDD_MAXVERTEXCOUNT = $00000400; (* dwMaxVertexCount is valid *)
(* TD3DDeviceDesc dwDevCaps flags *)
D3DDEVCAPS_FLOATTLVERTEX = $00000001; (* Device accepts floating point *)
(* for post-transform vertex data *)
D3DDEVCAPS_SORTINCREASINGZ = $00000002; (* Device needs data sorted for increasing Z*)
D3DDEVCAPS_SORTDECREASINGZ = $00000004; (* Device needs data sorted for decreasing Z*)
D3DDEVCAPS_SORTEXACT = $00000008; (* Device needs data sorted exactly *)
D3DDEVCAPS_EXECUTESYSTEMMEMORY = $00000010; (* Device can use execute buffers from system memory *)
D3DDEVCAPS_EXECUTEVIDEOMEMORY = $00000020; (* Device can use execute buffers from video memory *)
D3DDEVCAPS_TLVERTEXSYSTEMMEMORY = $00000040; (* Device can use TL buffers from system memory *)
D3DDEVCAPS_TLVERTEXVIDEOMEMORY = $00000080; (* Device can use TL buffers from video memory *)
D3DDEVCAPS_TEXTURESYSTEMMEMORY = $00000100; (* Device can texture from system memory *)
D3DDEVCAPS_TEXTUREVIDEOMEMORY = $00000200; (* Device can texture from device memory *)
D3DDEVCAPS_DRAWPRIMTLVERTEX = $00000400; (* Device can draw TLVERTEX primitives *)
D3DDEVCAPS_CANRENDERAFTERFLIP = $00000800; (* Device can render without waiting for flip to complete *)
D3DDEVCAPS_TEXTURENONLOCALVIDMEM = $00001000; (* Device can texture from nonlocal video memory *)
D3DFDS_COLORMODEL = $00000001; (* Match color model *)
D3DFDS_GUID = $00000002; (* Match guid *)
D3DFDS_HARDWARE = $00000004; (* Match hardware/software *)
D3DFDS_TRIANGLES = $00000008; (* Match in triCaps *)
D3DFDS_LINES = $00000010; (* Match in lineCaps *)
D3DFDS_MISCCAPS = $00000020; (* Match primCaps.dwMiscCaps *)
D3DFDS_RASTERCAPS = $00000040; (* Match primCaps.dwRasterCaps *)
D3DFDS_ZCMPCAPS = $00000080; (* Match primCaps.dwZCmpCaps *)
D3DFDS_ALPHACMPCAPS = $00000100; (* Match primCaps.dwAlphaCmpCaps *)
D3DFDS_SRCBLENDCAPS = $00000200; (* Match primCaps.dwSourceBlendCaps *)
D3DFDS_DSTBLENDCAPS = $00000400; (* Match primCaps.dwDestBlendCaps *)
D3DFDS_SHADECAPS = $00000800; (* Match primCaps.dwShadeCaps *)
D3DFDS_TEXTURECAPS = $00001000; (* Match primCaps.dwTextureCaps *)
D3DFDS_TEXTUREFILTERCAPS = $00002000; (* Match primCaps.dwTextureFilterCaps *)
D3DFDS_TEXTUREBLENDCAPS = $00004000; (* Match primCaps.dwTextureBlendCaps *)
D3DFDS_TEXTUREADDRESSCAPS = $00008000; (* Match primCaps.dwTextureBlendCaps *)
(*
* FindDevice arguments
*)
type
TD3DFindDeviceSearch = packed record
dwSize: DWORD;
dwFlags: DWORD;
bHardware: BOOL;
dcmColorModel: TD3DColorModel;
guid: TGUID;
dwCaps: DWORD;
dpcPrimCaps: TD3DPrimCaps;
end;
TD3DFindDeviceResult = packed record
dwSize: DWORD;
guid: TGUID; (* guid which matched *)
ddHwDesc: TD3DDeviceDesc; (* hardware TD3DDeviceDesc *)
ddSwDesc: TD3DDeviceDesc; (* software TD3DDeviceDesc *)
end;
(*
* Description of execute buffer.
*)
TD3DExecuteBufferDesc = packed record
dwSize: DWORD; (* size of this structure *)
dwFlags: DWORD; (* flags indicating which fields are valid *)
dwCaps: DWORD; (* capabilities of execute buffer *)
dwBufferSize: DWORD; (* size of execute buffer data *)
lpData: Pointer; (* pointer to actual data *)
end;
(* D3DEXECUTEBUFFER dwFlags indicating valid fields *)
const
D3DDEB_BUFSIZE = $00000001; (* buffer size valid *)
D3DDEB_CAPS = $00000002; (* caps valid *)
D3DDEB_LPDATA = $00000004; (* lpData valid *)
(* D3DEXECUTEBUFFER dwCaps *)
D3DDEBCAPS_SYSTEMMEMORY = $00000001; (* buffer in system memory *)
D3DDEBCAPS_VIDEOMEMORY = $00000002; (* buffer in device memory *)
D3DDEBCAPS_MEM = (D3DDEBCAPS_SYSTEMMEMORY or D3DDEBCAPS_VIDEOMEMORY);
implementation
end.
|
unit OTFEUnified_frmSelectOTFESystem;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
OTFEUnified_U;
type
TfrmSelectOTFESystem = class(TForm)
Label1: TLabel;
cbOTFESystem: TComboBox;
pbOK: TButton;
pbCancel: TButton;
Label2: TLabel;
Label3: TLabel;
procedure pbOKClick(Sender: TObject);
procedure cbOTFESystemChange(Sender: TObject);
private
Selected: TOTFESystem;
public
procedure Add(system: TOTFESystem);
function GetSelected(): TOTFESystem;
end;
implementation
{$R *.DFM}
procedure TfrmSelectOTFESystem.Add(system: TOTFESystem);
begin
cbOTFESystem.Items.AddObject(OTFESDispNames[system], TObject(ord(system)));
cbOTFESystem.ItemIndex := 0;
end;
function TfrmSelectOTFESystem.GetSelected(): TOTFESystem;
begin
Result := Selected;
end;
procedure TfrmSelectOTFESystem.pbOKClick(Sender: TObject);
begin
Selected := TOTFESystem(cbOTFESystem.Items.Objects[cbOTFESystem.ItemIndex]);
ModalResult := mrOK;
end;
procedure TfrmSelectOTFESystem.cbOTFESystemChange(Sender: TObject);
begin
pbOK.Enabled := (cbOTFESystem.ItemIndex>=0);
end;
END.
|
unit appgui;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls, sorter;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
CheckBox1: TCheckBox;
Label1: TLabel;
OpenDialog1: TOpenDialog;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
RadioButton3: TRadioButton;
RadioGroup1: TRadioGroup;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure CheckBox1Change(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
public
end;
var
Form1: TForm1;
lst,lstrev:TStringList;
filechosen:boolean;
opt:TSorterOptions;
path, flagstring, readdata,tmp,line:string;
ch:char;
filestream:TFileStream;
i:integer;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
filechosen:=false;
while not OpenDialog1.Execute do;
if Sorter.sorter(lst,opt) then
begin
path:=OpenDialog1.FileName;
Label1.Caption:=path;
filechosen:=true;
end
else
Label1.Caption:='Error';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
//open file
//check settings
if CheckBox1.Checked then
opt.DelDuplicates:=DelAllDups
else
opt.DelDuplicates:=skip;
if RadioButton1.Checked then
opt.SortAction:=asc;
if RadioButton2.Checked then
opt.SortAction:=desc;
if RadioButton3.Checked then
opt.SortAction:=off;
case opt.SortAction of
asc:flagstring:='Sorting:asc';
desc:flagstring:='Sorting:desc';
off:flagstring:='Sorting:none';
end;
if opt.DelDuplicates=DelAllDups then
flagstring+=sLineBreak+'Delete all duplicates';
//start process
if not filechosen then
ShowMessage('Please select a file!')
else
if sorter.sorter(lst,opt) then
begin
ShowMessage('Done!'+sLineBreak+'file path: '+path+sLineBreak+flagstring);
filestream:=TFileStream.Create(path,fmOpenRead);
try
{SetLength(readdata,filestream.size);
for i:=1 to 5 do
begin
filestream.read(readdata[i],1);
end;
ShowMessage(readdata);}
lst:=TStringList.Create;
line:='';
lstrev:=TStringList.Create();
if opt.DelDuplicates=DelAllDups then
begin
{lstrev.Duplicates:=dupIgnore;
lst.Duplicates:=dupIgnore;}
end
else
begin
lstrev.Duplicates:=dupAccept;
lst.Duplicates:=dupAccept;
end;
while(filestream.Read(ch,1)=1) do
if (ch <> sLineBreak) then
line+=ch
else
begin
if ((lst.IndexOf(line)=-1) or (opt.DelDuplicates=skip)) then
lst.Add(line);
line:='';
end;
// получены все строки из файла
// ShowMessage(IntToStr(lst.Count)+lst[3]);
if not (opt.SortAction=off) then
lst.Sort;
if opt.SortAction=desc then
begin
for i:=0 to lst.Count-1 do
lstrev.Add(lst[lst.Count-1-i]);
lst:=lstrev
end;
filestream.Destroy;
FileCreate(path+'.new');
filestream:=TFileStream.Create(path+'.new',fmOpenWrite);
lst.SaveToStream(filestream);//writeerror
finally
filestream.free;
end;
end
else
ShowMessage('Error!')
end;
procedure TForm1.CheckBox1Change(Sender: TObject);
begin
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
filechosen:=false;
end;
end.
|
unit ScriptEdit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, SynEdit, SynHighlighterPas, Forms, Controls, StdCtrls,
Graphics, Dialogs, Menus, lazUTF8,
msgstr, scriptsfunc, usbhid;
type
{ TScriptEditForm }
TScriptEditForm = class(TForm)
MainMenu: TMainMenu;
MenuItemScetionName: TMenuItem;
MenuItemSaveAs: TMenuItem;
MenuItemSection: TMenuItem;
MenuItemRun: TMenuItem;
MenuItemFile: TMenuItem;
MenuItemOpen: TMenuItem;
MenuItemSave: TMenuItem;
OpenDialog: TOpenDialog;
ScriptEditLog: TMemo;
SaveDialog: TSaveDialog;
SynEdit: TSynEdit;
SynPasSyn: TSynPasSyn;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormShow(Sender: TObject);
procedure MenuItemOpenClick(Sender: TObject);
procedure MenuItemRunClick(Sender: TObject);
procedure MenuItemSaveAsClick(Sender: TObject);
procedure MenuItemSaveClick(Sender: TObject);
procedure MenuItemSectionClick(Sender: TObject);
procedure SectionItemMenuClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
procedure ScriptLogPrint(text: string);
var
ScriptEditForm: TScriptEditForm;
implementation
uses main;
var
CurrentSectionName: string;
{$R *.lfm}
{ TScriptEditForm }
procedure ScriptLogPrint(text: string);
begin
ScriptEditForm.ScriptEditLog.Lines.Add(text);
end;
procedure TScriptEditForm.SectionItemMenuClick(Sender: TObject);
begin
CurrentSectionName := TMenuItem(Sender).Caption;
MenuItemScetionName.Caption:= CurrentSectionName;
end;
procedure FillScriptSection(ScriptText: TStrings);
var
st, SectionName: string;
i: integer;
mi: TMenuItem;
begin
ScriptEditForm.MenuItemSection.Clear;
for i:= 0 to ScriptText.Count-1 do
begin
st := Trim(Upcase(ScriptText.Strings[i]));
if Copy(st, 1, 2) = '{$' then
begin
SectionName := Trim(Copy(st, 3, pos('}', st)-3));
if SectionName <> '' then
begin
mi := NewItem(SectionName, 0, false, true, @ScriptEditForm.SectionItemMenuClick, 0, '');
mi.RadioItem:= true;
mi.AutoCheck:= true;
ScriptEditForm.MenuItemSection.Add(mi);
end;
end;
end;
mi := NewItem('-', 0, false, true, NIL, 0, '');
ScriptEditForm.MenuItemSection.Add(mi);
end;
function SaveFile: boolean;
begin
Result := false;
with ScriptEditForm do
begin
if SaveDialog.FileName <> '' then
begin
SynEdit.Lines.SaveToFile(SaveDialog.FileName);
SynEdit.Modified:= false;
Result := true;
end
else
begin
SaveDialog.InitialDir:= GetCurrentDir+DirectorySeparator+ScriptsPath;
if SaveDialog.Execute then
begin
SynEdit.Lines.SaveToFile(SaveDialog.FileName);
SynEdit.Modified:= false;
Result := true;
end;
end;
end;
end;
procedure TScriptEditForm.FormShow(Sender: TObject);
var
ScriptFileName: string;
begin
ScriptFileName := ScriptsPath + CurrentICParam.Script;
SaveDialog.FileName:= '';
if FileExists(ScriptFileName) then
begin
SynEdit.Lines.LoadFromFile(ScriptFileName);
SaveDialog.FileName:= ScriptFileName;
FillScriptSection(SynEdit.Lines);
end;
end;
procedure TScriptEditForm.MenuItemOpenClick(Sender: TObject);
begin
OpenDialog.InitialDir:= GetCurrentDir+DirectorySeparator+ScriptsPath;
if OpenDialog.Execute then
begin
SynEdit.Lines.LoadFromFile(OpenDialog.FileName);
SaveDialog.FileName:= OpenDialog.FileName;
FillScriptSection(SynEdit.Lines);
end;
end;
procedure TScriptEditForm.MenuItemSaveAsClick(Sender: TObject);
begin
SaveDialog.InitialDir:= GetCurrentDir+DirectorySeparator+ScriptsPath;
if SaveDialog.Execute then
begin
SynEdit.Lines.SaveToFile(SaveDialog.FileName);
SynEdit.Modified:= false;
end;
end;
procedure TScriptEditForm.MenuItemSaveClick(Sender: TObject);
begin
SaveFile();
end;
procedure TScriptEditForm.MenuItemSectionClick(Sender: TObject);
begin
FillScriptSection(SynEdit.Lines);
end;
procedure TScriptEditForm.FormCloseQuery(Sender: TObject; var CanClose: boolean
);
begin
if SynEdit.Modified then
case QuestionDlg(STR_DLG_FILECHGD, STR_DLG_SAVEFILE, mtConfirmation, [mrYes, mrNo, mrCancel],0) of
mrYes: if not SaveFile() then CanClose := false;
mrCancel: CanClose := false;
end;
end;
procedure TScriptEditForm.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
SynEdit.Clear;
SynEdit.Modified:= false;
ScriptEditForm.MenuItemScetionName.Caption:= '';
end;
procedure TScriptEditForm.MenuItemRunClick(Sender: TObject);
var
ScriptText: TStrings;
begin
try
ScriptText := TStringList.Create;
if ParseScriptText(SynEdit.Lines, CurrentSectionName, ScriptText) then
begin
ScriptLogPrint(STR_SCRIPT_RUN_SECTION+CurrentSectionName);
RunScript(ScriptText);
end
else
if CurrentSectionName = '' then
ScriptLogPrint(STR_SCRIPT_SEL_SECTION+CurrentSectionName)
else ScriptLogPrint(STR_SCRIPT_NO_SECTION+CurrentSectionName);
finally
ScriptText.Free;
end;
end;
end.
|
//******************************************************************************
// Проект "Контракты"
// Справочник лог
// Чернявский А.Э. 2006г.
//******************************************************************************
unit cn_Log_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, dxBar, dxBarExtItems, ImgList, cxGraphics, cxContainer, cxEdit,
cxProgressBar, dxStatusBar, cxControls, IBase,
cn_DM_Log, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB,
cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxClasses, cxTextEdit,
cn_Common_Funcs, cnConsts, cn_Common_Types, cxCalendar;
type
TfrmLog = class(TForm)
BarManager: TdxBarManager;
AddButton: TdxBarLargeButton;
EditButton: TdxBarLargeButton;
DeleteButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
ExitButton: TdxBarLargeButton;
PopupImageList: TImageList;
LargeImages: TImageList;
DisabledLargeImages: TImageList;
StatusBar: TdxStatusBar;
Styles: TcxStyleRepository;
BackGround: TcxStyle;
FocusedRecord: TcxStyle;
Header: TcxStyle;
DesabledRecord: TcxStyle;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
DevExpress_Style: TcxGridTableViewStyleSheet;
Grid: TcxGrid;
GridDBView: TcxGridDBTableView;
GridLevel: TcxGridLevel;
SelectButton: TdxBarLargeButton;
USER_NAME: TcxGridDBColumn;
ACTION_NAME: TcxGridDBColumn;
TIMESTAMP_ACTION: TcxGridDBColumn;
procedure ExitButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
PLanguageIndex: byte;
DM:TDM_Log;
procedure FormIniLanguage;
public
res:Variant;
constructor Create(AParameter:TcnSimpleParamsEx);reintroduce;
end;
implementation
{$R *.dfm}
constructor TfrmLog.Create(AParameter:TcnSimpleParamsEx);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AParameter.Owner);
GridDBView.Items[0].DataBinding.ValueTypeClass := TcxStringValueType;
GridDBView.Items[1].DataBinding.ValueTypeClass := TcxStringValueType;
GridDBView.Items[2].DataBinding.ValueTypeClass := TcxStringValueType;
DM:=TDM_Log.Create(Self);
DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_ACTION_HISTORY_SELECT(' +
inttostr(AParameter.cnParamsToPakage.ID_DOG_ROOT) + ',' +
inttostr(AParameter.cnParamsToPakage.ID_DOG) + ',' +
inttostr(AParameter.cnParamsToPakage.ID_STUD) + ')' ;
DM.DB.Handle:=AParameter.DB_Handle;
DM.DataSet.Open;
GridDBView.DataController.DataSource := DM.DataSource;
FormIniLanguage();
Screen.Cursor:=crDefault;
end;
procedure TfrmLog.FormIniLanguage;
begin
PLanguageIndex:= cn_Common_Funcs.cnLanguageIndex();
//кэпшн формы
Caption:= cnConsts.cn_Log[PLanguageIndex];
//названия кнопок
AddButton.Caption := cnConsts.cn_InsertBtn_Caption[PLanguageIndex];
EditButton.Caption := cnConsts.cn_EditBtn_Caption[PLanguageIndex];
DeleteButton.Caption := cnConsts.cn_DeleteBtn_Caption[PLanguageIndex];
RefreshButton.Caption := cnConsts.cn_RefreshBtn_Caption[PLanguageIndex];
SelectButton.Caption := cnConsts.cn_SelectBtn_Caption[PLanguageIndex];
ExitButton.Caption := cnConsts.cn_ExitBtn_Caption[PLanguageIndex];
USER_NAME.Caption := cnConsts.cn_User[PLanguageIndex];
ACTION_NAME.Caption := cnConsts.cn_Action[PLanguageIndex];
TIMESTAMP_ACTION.Caption := cnConsts.cn_Stamp[PLanguageIndex];
//статусбар
StatusBar.Panels[0].Text:= cnConsts.cn_InsertBtn_ShortCut[PLanguageIndex] + cnConsts.cn_InsertBtn_Caption[PLanguageIndex];
StatusBar.Panels[1].Text:= cnConsts.cn_EditBtn_ShortCut[PLanguageIndex] + cnConsts.cn_EditBtn_Caption[PLanguageIndex];
StatusBar.Panels[2].Text:= cnConsts.cn_DeleteBtn_ShortCut[PLanguageIndex] + cnConsts.cn_DeleteBtn_Caption[PLanguageIndex];
StatusBar.Panels[3].Text:= cnConsts.cn_RefreshBtn_ShortCut[PLanguageIndex] + cnConsts.cn_RefreshBtn_Caption[PLanguageIndex];
StatusBar.Panels[4].Text:= cnConsts.cn_EnterBtn_ShortCut[PLanguageIndex] + cnConsts.cn_SelectBtn_Caption[PLanguageIndex];
StatusBar.Panels[5].Text:= cnConsts.cn_ExitBtn_ShortCut[PLanguageIndex] + cnConsts.cn_ExitBtn_Caption[PLanguageIndex];
end;
procedure TfrmLog.ExitButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmLog.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FormStyle = fsMDIChild then action:=caFree
else
DM.Free;
end;
procedure TfrmLog.FormShow(Sender: TObject);
begin
if FormStyle = fsMDIChild then SelectButton.Enabled:=false;
end;
end.
|
unit uMediaRepository;
interface
uses
Generics.Collections,
System.SysUtils,
Dmitry.CRC32,
Dmitry.Utils.System,
UnitDBDeclare,
uConstants,
uMemory,
uDBClasses,
uDBConnection,
uDBContext,
uDBEntities,
uCollectionEvents;
type
TMediaRepository = class(TInterfacedObject, IMediaRepository)
private
FContext: IDBContext;
public
constructor Create(Context: IDBContext);
destructor Destroy; override;
function GetIdByFileName(FileName: string): Integer;
function GetFileNameById(ID: Integer): string;
procedure SetFileNameById(ID: Integer; FileName: string);
procedure SetAccess(ID, Access: Integer);
procedure SetRotate(ID, Rotate: Integer);
procedure SetRating(ID, Rating: Integer);
procedure SetAttribute(ID, Attribute: Integer);
procedure DeleteFromCollection(FileName: string; ID: Integer);
procedure DeleteFromCollectionEx(IDs: TList<Integer>);
procedure PermanentlyDeleteFromCollectionEx(IDs: TList<Integer>);
procedure DeleteDirectoryFromCollection(DirectoryName: string);
function GetCount: Integer;
function GetMenuItemByID(ID: Integer): TMediaItem;
function GetMenuItemsByID(ID: Integer): TMediaItemCollection;
function GetMenuInfosByUniqId(UniqId: string): TMediaItemCollection;
procedure UpdateMediaInfosFromDB(Info: TMediaItemCollection);
function UpdateMediaFromDB(Media: TMediaItem; LoadThumbnail: Boolean): Boolean;
function GetTopImagesWithPersons(MinDate: TDateTime; MaxItems: Integer): TMediaItemCollection;
procedure IncMediaCounter(ID: Integer);
procedure UpdateLinks(ID: Integer; NewLinks: string);
procedure RefreshImagesCache;
end;
implementation
{ TMediaRepository }
constructor TMediaRepository.Create(Context: IDBContext);
begin
FContext := Context;
end;
destructor TMediaRepository.Destroy;
begin
FContext := nil;
inherited;
end;
procedure TMediaRepository.DeleteDirectoryFromCollection(DirectoryName: string);
var
UC: TUpdateCommand;
SC: TSelectCommand;
EventInfo: TEventValues;
MediaItem: TMediaItem;
begin
SC := FContext.CreateSelect(ImageTable);
try
SC.AddParameter(TAllParameter.Create);
SC.AddWhereParameter(TIntegerParameter.Create('FolderCRC', Integer(GetPathCRC(DirectoryName, False))));
SC.AddWhereParameter(TStringParameter.Create('FFileName', AnsiLowerCase(DirectoryName) + '%', paLike));
if SC.Execute > 0 then
begin
UC := FContext.CreateUpdate(ImageTable);
try
UC.AddParameter(TDateTimeParameter.Create('DateUpdated', Now));
UC.AddParameter(TIntegerParameter.Create('Attr', Db_attr_deleted));
UC.AddWhereParameter(TIntegerParameter.Create('FolderCRC', Integer(GetPathCRC(DirectoryName, False))));
UC.AddWhereParameter(TStringParameter.Create('FFileName', AnsiLowerCase(DirectoryName) + '%', paLike));
UC.Execute;
while not SC.DS.Eof do
begin
MediaItem := TMediaItem.CreateFromDS(SC.DS);
try
EventInfo.ID := MediaItem.ID;
CollectionEvents.DoIDEvent(nil, MediaItem.ID, [EventID_Param_Delete], EventInfo);
finally
F(MediaItem);
end;
SC.DS.Next;
end;
finally
F(UC);
end;
end;
finally
F(SC);
end;
end;
procedure TMediaRepository.DeleteFromCollection(FileName: string; ID: Integer);
var
UC: TUpdateCommand;
EventInfo: TEventValues;
begin
UC := FContext.CreateUpdate(ImageTable);
try
UC.AddParameter(TDateTimeParameter.Create('DateUpdated', Now));
UC.AddParameter(TIntegerParameter.Create('Attr', Db_attr_deleted));
UC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
UC.Execute;
EventInfo.ID := ID;
EventInfo.FileName := FileName;
CollectionEvents.DoIDEvent(nil, ID, [EventID_Param_Delete], EventInfo);
finally
F(UC);
end;
end;
procedure TMediaRepository.DeleteFromCollectionEx(IDs: TList<Integer>);
var
I: Integer;
UC: TUpdateCommand;
EventInfo: TEventValues;
begin
for I := 0 to IDs.Count - 1 do
begin
UC := FContext.CreateUpdate(ImageTable);
try
UC.AddParameter(TDateTimeParameter.Create('DateUpdated', Now));
UC.AddParameter(TIntegerParameter.Create('Attr', Db_attr_deleted));
UC.AddWhereParameter(TIntegerParameter.Create('ID', IDs[I]));
UC.Execute;
EventInfo.ID := IDs[I];
CollectionEvents.DoIDEvent(nil, IDs[I], [EventID_Param_Delete], EventInfo);
finally
F(UC);
end;
end;
end;
procedure TMediaRepository.PermanentlyDeleteFromCollectionEx(IDs: TList<Integer>);
var
I: Integer;
DC: TDeleteCommand;
EventInfo: TEventValues;
begin
for I := 0 to IDs.Count - 1 do
begin
DC := FContext.CreateDelete(ImageTable);
try
DC.AddWhereParameter(TIntegerParameter.Create('ID', IDs[I]));
DC.Execute;
EventInfo.ID := IDs[I];
CollectionEvents.DoIDEvent(nil, IDs[I], [EventID_Param_Delete], EventInfo);
finally
F(DC);
end;
end;
end;
function TMediaRepository.GetCount: Integer;
var
SC: TSelectCommand;
begin
Result := 0;
SC := FContext.CreateSelect(ImageTable);
try
SC.AddParameter(TCustomFieldParameter.Create('COUNT(*) AS ITEMS_COUNT'));
SC.AddWhereParameter(TCustomConditionParameter.Create(FormatEx('Attr <> {0}', [Db_attr_deleted])));
if SC.Execute > 0 then
Result := SC.DS.FieldByName('ITEMS_COUNT').AsInteger;
finally
F(SC);
end;
end;
function TMediaRepository.GetFileNameById(ID: Integer): string;
var
SC: TSelectCommand;
begin
Result := '';
SC := FContext.CreateSelect(ImageTable);
try
SC.AddParameter(TStringParameter.Create('FFileName'));
SC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
if SC.Execute > 0 then
Result := SC.DS.FieldByName('FFileName').AsString;
finally
F(SC);
end;
end;
function TMediaRepository.GetIdByFileName(FileName: string): Integer;
var
SC: TSelectCommand;
begin
Result := 0;
SC := FContext.CreateSelect(ImageTable);
try
SC.AddParameter(TIntegerParameter.Create('ID'));
SC.AddWhereParameter(TIntegerParameter.Create('FolderCRC', Integer(GetPathCRC(FileName, True))));
SC.AddWhereParameter(TStringParameter.Create('FFileName', AnsiLowerCase(FileName), paEquals));
if SC.Execute > 0 then
Result := SC.DS.FieldByName('ID').AsInteger;
finally
F(SC);
end;
end;
procedure TMediaRepository.SetAccess(ID, Access: Integer);
var
UC: TUpdateCommand;
EventInfo: TEventValues;
begin
UC := FContext.CreateUpdate(ImageTable);
try
UC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
UC.AddParameter(TIntegerParameter.Create('Access', Access));
UC.Execute;
EventInfo.ID := ID;
EventInfo.Access := Access;
CollectionEvents.DoIDEvent(nil, ID, [EventID_Param_Access], EventInfo);
finally
F(UC);
end;
end;
procedure TMediaRepository.SetAttribute(ID, Attribute: Integer);
var
UC: TUpdateCommand;
EventInfo: TEventValues;
begin
UC := FContext.CreateUpdate(ImageTable);
try
UC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
UC.AddParameter(TIntegerParameter.Create('Attr', Attribute));
UC.Execute;
EventInfo.ID := ID;
EventInfo.Attr := Attribute;
CollectionEvents.DoIDEvent(nil, ID, [EventID_Param_Attr], EventInfo);
finally
F(UC);
end;
end;
procedure TMediaRepository.SetFileNameById(ID: Integer; FileName: string);
var
UC: TUpdateCommand;
begin
UC := FContext.CreateUpdate(ImageTable);
try
UC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
UC.AddParameter(TIntegerParameter.Create('FolderCRC', GetPathCRC(FileName, True)));
UC.AddParameter(TStringParameter.Create('FFileName', AnsiLowerCase(FileName)));
UC.AddParameter(TStringParameter.Create('Name', ExtractFileName(FileName)));
UC.AddParameter(TIntegerParameter.Create('Attr', Db_attr_norm));
UC.Execute;
finally
F(UC);
end;
end;
procedure TMediaRepository.SetRating(ID, Rating: Integer);
var
UC: TUpdateCommand;
EventInfo: TEventValues;
begin
UC := FContext.CreateUpdate(ImageTable);
try
UC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
UC.AddParameter(TIntegerParameter.Create('Rating', Rating));
UC.Execute;
EventInfo.ID := ID;
EventInfo.Rating := Rating;
CollectionEvents.DoIDEvent(nil, ID, [EventID_Param_Rating], EventInfo);
finally
F(UC);
end;
end;
procedure TMediaRepository.SetRotate(ID, Rotate: Integer);
var
UC: TUpdateCommand;
EventInfo: TEventValues;
begin
UC := FContext.CreateUpdate(ImageTable);
try
UC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
UC.AddParameter(TIntegerParameter.Create('Rotated', Rotate));
UC.Execute;
EventInfo.ID := ID;
EventInfo.Rotation := Rotate;
CollectionEvents.DoIDEvent(nil, ID, [EventID_Param_Rotate], EventInfo);
finally
F(UC);
end;
end;
function TMediaRepository.GetMenuItemByID(ID: Integer): TMediaItem;
var
SC: TSelectCommand;
begin
Result := nil;
SC := FContext.CreateSelect(ImageTable);
try
SC.AddParameter(TAllParameter.Create);
SC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
if SC.Execute > 0 then
Result := TMediaItem.CreateFromDS(SC.DS);
finally
F(SC);
end;
end;
function TMediaRepository.GetMenuItemsByID(ID: Integer): TMediaItemCollection;
var
MediaItem: TMediaItem;
begin
Result := TMediaItemCollection.Create;
MediaItem := GetMenuItemByID(ID);
if MediaItem <> nil then
Result.Add(MediaItem);
end;
function TMediaRepository.GetTopImagesWithPersons(MinDate: TDateTime;
MaxItems: Integer): TMediaItemCollection;
var
SQL: string;
MediaItem: TMediaItem;
SC: TSelectCommand;
DFormatSettings: TFormatSettings;
begin
Result := TMediaItemCollection.Create;
SC := FContext.CreateSelect(ImageTable);
try
SQL := 'SELECT TOP {3} * FROM ' +
' (SELECT IM1.* from {0} AS IM1 ' +
' LEFT JOIN ' +
' (SELECT DISTINCT Im.ID, Im.Rating FROM {0} im ' +
' INNER JOIN {1} OM on Im.Id = OM.ImageId) AS IR on IR.ID = IM1.ID ' +
' WHERE DateToAdd > #{2}# ' +
' ORDER BY [IM1].[ID] ASC) AS Result ';
DFormatSettings := FormatSettings;
DFormatSettings.DateSeparator := '/';
SQL := FormatEx(SQL, [ImageTable, ObjectMappingTableName, FormatDateTime('dd/mm/yyyy', MinDate, DFormatSettings), MaxItems]);
if SC.ExecuteSQL(SQL, True) > 0 then
begin
while not SC.DS.Eof do
begin
MediaItem := TMediaItem.Create;
MediaItem.ReadFromDS(SC.DS);
Result.Add(MediaItem);
SC.DS.Next;
end;
end;
finally
F(SC);
end;
end;
procedure TMediaRepository.IncMediaCounter(ID: Integer);
var
UC: TUpdateCommand;
begin
UC := FContext.CreateUpdate(ImageTable, True);
try
UC.AddParameter(TCustomFieldParameter.Create('[ViewCount] = [ViewCount] + 1'));
UC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
UC.Execute;
finally
F(UC);
end;
end;
procedure TMediaRepository.RefreshImagesCache;
var
UC: TUpdateCommand;
begin
UC := FContext.CreateUpdate(ImageTable, True);
try
UC.AddParameter(TDateTimeParameter.Create('DateUpdated', EncodeDate(1900, 1, 1)));
UC.AddWhereParameter(TCustomConditionParameter.Create('1=1'));
UC.Execute;
finally
F(UC);
end;
end;
procedure TMediaRepository.UpdateLinks(ID: Integer; NewLinks: string);
var
UC: TUpdateCommand;
EventInfo: TEventValues;
begin
UC := FContext.CreateUpdate(ImageTable, True);
try
UC.AddParameter(TStringParameter.Create('Links', NewLinks));
UC.AddWhereParameter(TIntegerParameter.Create('ID', ID));
UC.Execute;
EventInfo.ID := ID;
EventInfo.Links := NewLinks;
CollectionEvents.DoIDEvent(nil, ID, [EventID_Param_Links], EventInfo);
finally
F(UC);
end;
end;
function TMediaRepository.GetMenuInfosByUniqId(UniqId: string): TMediaItemCollection;
var
SC: TSelectCommand;
MediaItem: TMediaItem;
begin
Result := TMediaItemCollection.Create;
SC := FContext.CreateSelect(ImageTable);
try
SC.AddParameter(TAllParameter.Create);
SC.AddWhereParameter(TIntegerParameter.Create('StrThCrc', StringCRC(UniqId)));
SC.AddWhereParameter(TStringParameter.Create('StrTh', UniqId));
if SC.Execute > 0 then
begin
while not SC.DS.Eof do
begin
MediaItem := TMediaItem.CreateFromDS(SC.DS);
Result.Add(MediaItem);
SC.DS.Next;
end;
Result.Position := 0;
end;
finally
F(SC);
end;
end;
procedure TMediaRepository.UpdateMediaInfosFromDB(Info: TMediaItemCollection);
var
I, J: Integer;
SC: TSelectCommand;
MediaItem: TMediaItem;
begin
for I := 0 to Info.Count - 1 do
begin
if not Info[I].InfoLoaded then
begin
SC := FContext.CreateSelect(ImageTable);
try
//todo: don't select images
SC.AddParameter(TAllParameter.Create);
SC.AddWhereParameter(TIntegerParameter.Create('FolderCRC', GetPathCRC(Info[I].FileName, True)));
if SC.Execute > 0 then
begin
while not SC.DS.Eof do
begin
MediaItem := TMediaItem.CreateFromDS(SC.DS);
for J := I to Info.Count - 1 do
begin
if AnsiLowerCase(Info[I].FileName) = MediaItem.FileName then
Info[I].Assign(MediaItem);
end;
SC.DS.Next;
end;
end;
finally
F(SC);
end;
end;
end;
end;
function TMediaRepository.UpdateMediaFromDB(Media: TMediaItem; LoadThumbnail: Boolean): Boolean;
var
SC: TSelectCommand;
begin
Result := False;
SC := FContext.CreateSelect(ImageTable);
try
if Media.ID > 0 then
SC.AddWhereParameter(TIntegerParameter.Create('ID', Media.ID))
else
begin
SC.AddWhereParameter(TIntegerParameter.Create('FolderCRC', GetPathCRC(Media.FileName, True)));
SC.AddWhereParameter(TStringParameter.Create('Name', ExtractFileName(Media.FileName)));
end;
SC.AddParameter(TAllParameter.Create());
if SC.Execute > 0 then
begin
Media.ReadFromDS(SC.DS);
if LoadThumbnail then
Media.LoadImageFromDS(SC.DS);
Media.Tag := EXPLORER_ITEM_IMAGE;
end;
finally
F(SC);
end;
end;
end.
|
unit gr_uMessage;
interface
uses Classes, SysUtils,Dialogs,Graphics,Forms,StdCtrls, gr_uCommonProc, Controls;
function grShowMessage(Title:String;Msg:String;DlgType:TMsgDlgType;Buttons:TMsgDlgButtons):Integer;
implementation
const OkBtnCaption :array [1..2] of string = ('Гаразд','Хорошо');
const CancelBtnCaption :array [1..2] of string = ('Відмінити','Отменить');
const YesBtnCaption :array [1..2] of string = ('Так','Да');
const NoBtnCaption :array [1..2] of string = ('Ні','Нет');
const AbortBtnCaption :array [1..2] of string = ('Прервати','Прервать');
const RetryBtnCaption :array [1..2] of string = ('Повторити','Повторить');
const IgnoreBtnCaption :array [1..2] of string = ('Продовжити','Продолжить');
const AllBtnCaption :array [1..2] of string = ('Для усіх','Для всех');
const HelpBtnCaption :array [1..2] of string = ('Допомога','Помощь');
const NoToAllBtnCaption :array [1..2] of string = ('Ні для усіх','Нет для всех');
const YesToAllBtnCaption :array [1..2] of string = ('Так для усіх','Да для всех');
function grShowMessage(Title:String;Msg:String;DlgType:TMsgDlgType;Buttons:TMsgDlgButtons):Integer;
var ViewMessageForm:TForm;
i:integer;
CurrentIndexLanguage:Byte;
begin
Result:=mrNone;
CurrentIndexLanguage := IndexLanguage;
if Pos(#13,Msg)=0 then Msg:=#13+Msg;
ViewMessageForm:=CreateMessageDialog(Msg,DlgType,Buttons);
with ViewMessageForm do
begin
for i:=0 to ComponentCount-1 do
if (Components[i].ClassType=TButton) then
begin
if UpperCase((Components[i] as TButton).Caption)='OK' then
(Components[i] as TButton).Caption := OkBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption)='CANCEL' then
(Components[i] as TButton).Caption := CancelBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption)='&YES' then
(Components[i] as TButton).Caption := YesBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption)='&NO' then
(Components[i] as TButton).Caption := NoBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption)='&ABORT' then
(Components[i] as TButton).Caption := AbortBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption)='&RETRY' then
(Components[i] as TButton).Caption := RetryBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption)='&IGNORE' then
(Components[i] as TButton).Caption := IgnoreBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption) = '&ALL' then
(Components[i] as TButton).Caption := AllBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption) = '&HELP' then
(Components[i] as TButton).Caption := HelpBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption) = 'N&O TO ALL' then
(Components[i] as TButton).Caption := NoToAllBtnCaption[CurrentIndexLanguage];
if UpperCase((Components[i] as TButton).Caption) = 'YES TO &ALL' then
(Components[i] as TButton).Caption := YesToAllBtnCaption[CurrentIndexLanguage];
end;
Caption:=Title;
Result:=ShowModal;
Free;
end;
end;
end.
|
unit CryptocurrencyDM;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, REST.Types, REST.Client, REST.Response.Adapter,
Data.Bind.Components, Data.Bind.ObjectScope, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client;
type
TCryptocurrencyData = class(TDataModule)
TmpExchangeMemTable: TFDMemTable;
ExchangeResponse: TRESTResponse;
ExchangeClient: TRESTClient;
ExchangeAdapter: TRESTResponseDataSetAdapter;
ExchangeRequest: TRESTRequest;
private
public
function GetOneDate(const key: string; dt: TDateTime; var btc, eth: double; var msg: string): boolean;
end;
var
CryptocurrencyData: TCryptocurrencyData;
implementation
uses Windows;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TCryptocurrencyData }
// For payed key, we can retrieve all history in one request
// For freeware key, wee should use a separate request for every date
function TCryptocurrencyData.GetOneDate(const key: string; dt: TDateTime;
var btc, eth: double; var msg: string): boolean;
var
url: string;
begin
url := 'http://api.coinlayer.com/api/'
+ FormatDateTime('yyyy-mm-dd', dt)
+ '?access_key='+key
+ '&symbols=BTC,ETH'
+ '';
ExchangeClient.BaseURL := url;
try
ExchangeRequest.Execute;
btc := CryptocurrencyData.TmpExchangeMemTable.FieldByName('BTC').AsFloat;
eth := CryptocurrencyData.TmpExchangeMemTable.FieldByName('ETH').AsFloat;
result := true;
except
on e: Exception do begin
result := false;
msg := e.Message;
end;
end;
end;
end.
|
{$B-,I-,Q-,R-,S-}
{$M 16384,0,655360}
{þ Kola.
En un cuarto hay M botellas rellenas con una bebida sumamente
popular y de buen gusto, llamada Kola. Cada una de las botellas est
marcada por uno de los n£meros 1, 2, 3, ... M, y no hay ning£n par de
botellas marcadas con el mismo n£mero.
Una cola (muy popular en nuestro pa¡s) consiste en N personas
sedientas que forman en la puerta de entrada al cuarto. Cada persona
tiene asignado un de n£mero 1, 2, 3, ... N, y de nuevo, ning£n par
de ellas tiene el mismo n£mero. Todos ellos esperan para beber Kola
de una de las botellas en el cuarto. Uno por uno, organizados por sus
n£meros (la persona que se le asign¢ el n£mero 1 es el primero en
entrar, el pr¢ximo es la persona que se le asign¢ el n£mero 2,
etc.), entran en el cuarto, beben un decilitro de Kola de una de las
botellas en el cuarto y entonces se marchan. No m s de una persona se
permite estar en el cuarto en cualquier momento. Hay dos tipos de
personas: malgastadoras y econ¢micas. Las personas malgastadoras
siempre beben de una de las botellas m s llenas. Los econ¢micos
siempre beben de una de las botellas menos llenas (por supuesto,
las botellas vac¡as son ignoradas). Es conocido cu nta Kola permanece
en cada botella despu‚s de que la £ltima persona dej¢ el cuarto.
Tarea
Usted necesita escribir un programa que determine qu‚ persona bebi¢
de cada botella.
Entrada
La primera l¡nea del fichero de entrada COLA.IN contiene tres enteros
N, M y K, 1 <= N <= 1000, 1 <= M <= 100, 1 <= K <= 20, el n£mero
de las personas en la cola, el n£mero de botellas en el cuarto y
cu ntos decilitros de Kola estaban inicialmente en cada
botella, respectivamente. Se asignan a las personas los n£meros del 1
al N y las botellas se marcan por n£meros del 1 al M como se
describi¢ anteriormente. La segunda l¡nea del fichero de entrada
contiene una sucesi¢n de caracteres 'R' y 'S' de longitud N. El
car cter de la posici¢n i describe a la persona i-esima: 'R' denota
a la persona malgastadora y 'S' denota a la persona econ¢mica. La
tercera (y £ltima l¡nea) del fichero de entrada contiene M enteros que
denotan los vol£menes (en decilitros) que quedaron de Kola en
las botellas correspondientes: el k-‚simo n£mero corresponde a la
botella k-‚sima. Los n£meros adyacentes son separados por un
espacio. Cada uno de esos M enteros son del conjunto (0, 1, 2... K).
Salida
La primera y £nica l¡nea del fichero de salida COLA.OUT debe
contener N enteros; el i-esimo n£mero es el n£mero de botella de la
persona i- esima que bebi¢ Kola. Dos n£meros adyacentes deben ser
separados por un espacio.
Ejemplos de Entrada y Salida:
Ejemplo # 1 Ejemplo # 2 Ejemplo # 3
ÚÄÄÄÄÄÄÄ¿ÚÄÄÄÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄ¿ÚÄÄÄÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄÄÄÄÄ¿ÚÄÄÄÄÄÄÄÄÄÄÄ¿
³COLA.IN³³ COLA.OUT ³ ³COLA.IN³³ COLA.OUT ³ ³ COLA.IN ³³ COLA.OUT ³
ÃÄÄÄÄÄÄÄ´ÃÄÄÄÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄ´ÃÄÄÄÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄÄÄÄÄ´ÃÄÄÄÄÄÄÄÄÄÄÄ´
³ 4 3 3 ³³ 2 2 2 3 ³ ³ 4 3 3 ³³ 2 2 3 2 ³ ³ 5 5 2 ³³ 3 3 5 1 5 ³
³ SSSS ³ÀÄÄÄÄÄÄÄÄÄÄÙ ³ SSRS ³ÀÄÄÄÄÄÄÄÄÄÄÙ ³ SSRRS ³ÀÄÄÄÄÄÄÄÄÄÄÄÙ
³ 3 0 2 ³ ³ 3 0 2 ³ ³ 1 2 0 2 0 ³
ÀÄÄÄÄÄÄÄÙ ÀÄÄÄÄÄÄÄÙ ÀÄÄÄÄÄÄÄÄÄÄÄÙ
Nota: Habr siempre una soluci¢n, no necesariamente £nica, para todos
los juegos de datos de prueba.
}
var
fe,fs : text;
n,m,k : longint;
res,bot,ide,r : array[1..1001] of longint;
per : array[1..1001] of char;
procedure open;
var
t : longint;
begin
assign(fe,'cola.in'); reset(fe);
assign(fs,'cola.out'); rewrite(fs);
readln(fe,n,m,k);
for t:=1 to n do read(fe,per[t]);
readln(fe);
for t:=1 to m do
begin
read(fe,bot[t]);
res[t]:=k;
end;
end;
function findmax : longint;
var
i,aux,best : longint;
begin
aux:=0;
for i:=1 to m do
if (res[i] > aux) then
begin
aux:=res[i];
best:=i;
end;
findmax:=best;
end;
function findmin : longint;
var
i,aux,best : longint;
begin
aux:=maxlongint;
for i:=1 to m do
if (res[i] < aux) and (res[i] > 0) then
begin
aux:=res[i];
best:=i;
end;
findmin:=best;
end;
procedure swap(var n1,n2 : longint);
var
t : longint;
begin
t:=n1;
n1:=n2;
n2:=t;
end;
procedure qsort(ini,fin : longint);
var
i,j,k : longint;
begin
i:=ini; j:=fin; k:=bot[(i+j) div 2];
repeat
while bot[i] < k do inc(i);
while bot[j] > k do dec(j);
if i<=j then
begin
swap(bot[i],bot[j]);
swap(ide[i],ide[j]);
inc(i); dec(j);
end;
until i>j;
if i < fin then qsort(i,fin);
if j > ini then qsort(ini,j);
end;
procedure work;
var
i,k : longint;
begin
for i:=1 to m do ide[i]:=i;
qsort(1,m);
for i:=1 to n do
begin
if per[i] = 'S' then
begin
k:=findmin;
dec(res[k]);
end
else
begin
k:=findmax;
dec(res[k]);
end;
r[i]:=ide[k];
end;
end;
procedure closer;
var
t : longint;
begin
for t:=1 to n do write(fs,r[t],' ');
close(fs);
end;
begin
open;
work;
closer;
end. |
unit URunner;
interface
uses ULogger, Windows, SysUtils;
procedure Run(const Feedback: TLogger; const LogChannel: TLogChannel;
const FileName, CurrDir: string; const Parameters: string;
const ExpectedExit: integer = 0);
implementation
uses ShellAPI;
procedure Run(const Feedback: TLogger; const LogChannel: TLogChannel; const FileName, CurrDir: string; const Parameters: string;
const ExpectedExit: integer = 0);
const
ReadBuffer = 2400;
var
Security : TSecurityAttributes;
ReadPipe,WritePipe : THandle;
start : TStartUpInfo;
ProcessInfo : TProcessInformation;
Buffer : TBytes;
BytesRead : DWord;
Apprunning : DWord;
ExitCode: DWORD;
CommandLine : string;
Avail: DWord;
PCurrDir: PWideChar;
LocalText: string;
PCommandLine: PChar;
PEnvironment: PChar;
begin
PEnvironment :=nil;
if CurrDir = '' then PCurrDir := nil else PCurrDir := PWideChar(CurrDir);
SetLength(Buffer, ReadBuffer + 1);
LocalText := '';
ZeroMemory(@Security, SizeOf(TSecurityAttributes));
ZeroMemory(@ProcessInfo, SizeOf(TProcessInformation));
Security.nlength := SizeOf(TSecurityAttributes) ;
Security.binherithandle := true;
Security.lpsecuritydescriptor := nil;
if not Createpipe (ReadPipe, WritePipe, @Security, 0) then raise Exception.Create('Error running ' + FileName);
try
FillChar(Start,Sizeof(Start),#0) ;
start.cb := SizeOf(start) ;
start.hStdOutput := WritePipe;
start.hStdError := WritePipe;
start.hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdinput;
start.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW;
start.wShowWindow := SW_HIDE;
CommandLine := '"' + FileName + '" ' + Parameters;
PCommandLine := PChar(CommandLine);
if not CreateProcess(nil,
PCommandLine,
@Security,
@Security,
true,
NORMAL_PRIORITY_CLASS or CREATE_UNICODE_ENVIRONMENT,
PEnvironment,
PCurrDir,
start,
ProcessInfo)
then raise Exception.Create('Error running ' + FileName);
try
Repeat
Apprunning := WaitForSingleObject(ProcessInfo.hProcess,100) ;
Repeat
PeekNamedPipe(ReadPipe, nil, 0, nil, @Avail, nil);
if Avail > 0 then
begin
BytesRead := 0;
ReadFile(ReadPipe, Buffer[0], ReadBuffer, BytesRead, nil) ;
LocalText := LocalText + TEncoding.ASCII.GetString(Buffer, 0, BytesRead);
end;
until (Avail = 0) ;
if Assigned(Feedback) then Feedback(LogChannel, LocalText);
LocalText:='';
until (Apprunning <> WAIT_TIMEOUT) ;
GetExitCodeProcess(ProcessInfo.hProcess, ExitCode);
if (integer(ExitCode) <> ExpectedExit) then raise Exception.Create('Error running: ' +FileName + ' Exit code: ' + IntToStr(ExitCode));
finally
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
end;
finally
CloseHandle(ReadPipe);
CloseHandle(WritePipe);
end;
end;
end.
|
unit unContaCorrenteController;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, unControllerBase, unModelBase, SQLDB;
type
{ TLoadBanco }
TLoadBanco = class(TInterfacedObject, IObserverCurrent, IObserverList)
private
FConnection: TSqlConnection;
FCurrent: string;
FList: TStringList;
FIdxSelected: integer;
procedure SetCurrent(AValue: string);
procedure SetIdxSelected(AValue: integer);
procedure SetList(AValue: TStringList);
procedure LoadList;
protected
procedure UpdateCurrent(ACurrent: TModelBase);
procedure UpdateList(AList: TList);
property Current: string read FCurrent write SetCurrent;
property List: TStringList read FList write SetList;
property IdxSelected: integer read FIdxSelected write SetIdxSelected;
public
constructor Create(AConnection: TSqlConnection);
end;
{ TContaCorrenteValidator }
TContaCorrenteValidator = class(TInterfacedObject, IModelValidator)
public
procedure Validate(AModel: TModelBase; out isValid: boolean;
out errors: TStringList);
end;
{ TContaCorrenteController }
TContaCorrenteController = class(TAbstractController)
private
FPointerCurrent: Pointer;
FFilterIdBanco: string;
FFilterNomeConta: string;
FFilterNumeroConta: string;
FLoadBanco: TLoadBanco;
function GetIndiceBanco: integer;
function GetListaBanco: TStringList;
function GetNomeBanco: string;
procedure SetFilterIdBanco(AValue: string);
procedure SetFilterNomeConta(AValue: string);
procedure SetFilterNumeroConta(AValue: string);
protected
function GetTemplateSelect: string; override;
function GetTableName: string; override;
function GetInsertFieldList: TStringList; override;
procedure SetInsertFieldValues(AModel: TModelBase; AQuery: TSQLQuery);
override;
procedure SetUpdateFieldValues(AModel: TModelBase; AQuery: TSQLQuery);
override;
procedure SetFilterParamsValues(AQuery: TSQLQuery); override;
function GetFilterExpression: string; override;
function GetValidator: IModelValidator; override;
function PopulateModel(AQuery: TSQLQuery): TModelBase; override;
public
property FilterIdBanco: string read FFilterIdBanco write SetFilterIdBanco;
property FilterNomeConta: string read FFilterNomeConta write SetFilterNomeConta;
property FilterNumeroConta: string read FFilterNumeroConta
write SetFilterNumeroConta;
property NomeBanco: string read GetNomeBanco;
property ListaBanco: TStringList read GetListaBanco;
property IndiceBanco:integer read GetIndiceBanco;
constructor Create(AConnection: TSQLConnection); override;
destructor Destroy; override;
end;
implementation
uses unContaCorrente;
const
FIELD_ID_BANCO = 'idBanco';
FIELD_NOME_CONTA = 'nomeConta';
FIELD_NUMERO = 'numero';
FIELD_DATA_ABERTURA = 'dataAbertura';
FIELD_OBSERVACAO = 'observacao';
FIELD_SALDO_INICIAL = 'saldoInicial';
{ TLoadBanco }
procedure TLoadBanco.SetCurrent(AValue: string);
begin
if FCurrent = AValue then
Exit;
FCurrent := AValue;
end;
procedure TLoadBanco.SetIdxSelected(AValue: integer);
begin
if FIdxSelected = AValue then
Exit;
FIdxSelected := AValue;
end;
procedure TLoadBanco.SetList(AValue: TStringList);
begin
if FList = AValue then
Exit;
FList := AValue;
end;
procedure TLoadBanco.LoadList;
var
query: TSQLQuery;
begin
if (Assigned(FList)) then
begin
exit;
end;
FList := TStringList.Create;
query := TSQLQuery.Create(nil);
try
query.SQLConnection := FConnection;
query.SQL.Text := 'SELECT CAST ( id as VARCHAR) as _id, nomeBanco FROM banco ORDER BY nomeBanco';
query.Open;
query.First;
while not query.EOF do
begin
FList.AddPair(query.FieldByName('nomeBanco').AsString, query.FieldByName('_id').AsString );
query.Next;
end;
finally
query.Free;
end;
end;
procedure TLoadBanco.UpdateCurrent(ACurrent: TModelBase);
var
pos: Integer;
begin
LoadList;
if ( not Assigned(ACurrent) ) then
begin
exit;
end;
with ACurrent as TContaCorrente do
begin
for pos := 0 to FList.Count -1 do
begin
if ( FList.ValueFromIndex[pos] = IdBanco ) then
begin
Current:= FList[pos];
IdxSelected:= pos;
Break;
end;
end;
end;
end;
procedure TLoadBanco.UpdateList(AList: TList);
begin
LoadList;
end;
constructor TLoadBanco.Create(AConnection: TSqlConnection);
begin
inherited Create;
FConnection := AConnection;
LoadList;
end;
{ TContaCorrenteValidator }
procedure TContaCorrenteValidator.Validate(AModel: TModelBase;
out isValid: boolean; out errors: TStringList);
begin
if (Assigned(errors)) then
begin
errors.Free;
end;
errors := TStringList.Create;
errors.Clear;
with AModel as TContaCorrente do
begin
if (IdBanco = string.Empty) then
begin
errors.Add('O banco da conta corrente é obrigatório.');
end;
if (NomeConta = string.Empty) then
begin
errors.Add('O nome da conta é obrigatório.');
end;
if (Numero = string.Empty) then
begin
errors.Add('O número da conta é obrigatório.');
end;
end;
isValid := errors.Count = 0;
end;
{ TContaCorrenteController }
procedure TContaCorrenteController.SetFilterIdBanco(AValue: string);
begin
if FFilterIdBanco = AValue then
Exit;
FFilterIdBanco := AValue;
end;
function TContaCorrenteController.GetNomeBanco: string;
begin
if ( ASsigned(FLoadBanco)) then
begin
Result := FLoadBanco.Current;
exit;
end;
result := string.Empty;
end;
function TContaCorrenteController.GetListaBanco: TStringList;
begin
Result := FLoadBanco.List;
end;
function TContaCorrenteController.GetIndiceBanco: integer;
begin
if ( ASsigned(FLoadBanco)) then
begin
Result := FLoadBanco.IdxSelected;
exit;
end;
result := -1;
end;
procedure TContaCorrenteController.SetFilterNomeConta(AValue: string);
begin
if FFilterNomeConta = AValue then
Exit;
FFilterNomeConta := AValue;
end;
procedure TContaCorrenteController.SetFilterNumeroConta(AValue: string);
begin
if FFilterNumeroConta = AValue then
Exit;
FFilterNumeroConta := AValue;
end;
function TContaCorrenteController.GetTemplateSelect: string;
begin
Result := 'SELECT cast(conta_corrente.id as varchar) as _id, cast(idBanco as varchar) as _idBanco, banco.nomeBanco , conta_corrente.* FROM %s INNER JOIN banco ON conta_corrente.idBanco = banco.id ';
end;
constructor TContaCorrenteController.Create(AConnection: TSQLConnection);
begin
inherited Create(AConnection);
FLoadBanco := TLoadBanco.Create(AConnection);
FPointerCurrent := AtachObserverCurrent(FLoadBanco);
end;
destructor TContaCorrenteController.Destroy;
begin
UnAtachObserverCurrent(FPointerCurrent);
inherited Destroy;
end;
function TContaCorrenteController.GetTableName: string;
begin
Result := 'conta_corrente';
end;
function TContaCorrenteController.GetInsertFieldList: TStringList;
begin
Result := TStringList.Create;
Result.Add(FIELD_ID_BANCO);
Result.Add(FIELD_NOME_CONTA);
Result.Add(FIELD_NUMERO);
Result.Add(FIELD_DATA_ABERTURA);
Result.Add(FIELD_OBSERVACAO);
Result.Add(FIELD_SALDO_INICIAL);
end;
procedure TContaCorrenteController.SetInsertFieldValues(AModel: TModelBase;
AQuery: TSQLQuery);
begin
with AModel as TContaCorrente do
begin
AQuery.ParamByName(FIELD_ID_BANCO).AsString := IdBanco;
AQuery.ParamByName(FIELD_NOME_CONTA).AsString := NomeConta;
AQuery.ParamByName(FIELD_NUMERO).AsString := Numero;
AQuery.ParamByName(FIELD_DATA_ABERTURA).AsDateTime := DataAbertura;
AQuery.ParamByName(FIELD_OBSERVACAO).AsString := Observacao;
AQuery.ParamByName(FIELD_SALDO_INICIAL).AsFloat := SaldoInicial;
end;
end;
procedure TContaCorrenteController.SetUpdateFieldValues(AModel: TModelBase;
AQuery: TSQLQuery);
begin
with AModel as TContaCorrente do
begin
AQuery.ParamByName(FIELD_ID_BANCO).AsString := IdBanco;
AQuery.ParamByName(FIELD_NOME_CONTA).AsString := NomeConta;
AQuery.ParamByName(FIELD_NUMERO).AsString := Numero;
AQuery.ParamByName(FIELD_DATA_ABERTURA).AsDateTime := DataAbertura;
AQuery.ParamByName(FIELD_OBSERVACAO).AsString := Observacao;
AQuery.ParamByName(FIELD_SALDO_INICIAL).AsFloat := SaldoInicial;
end;
end;
procedure TContaCorrenteController.SetFilterParamsValues(AQuery: TSQLQuery);
begin
if (FilterIdBanco <> string.Empty) then
begin
AQuery.ParamByName(FIELD_ID_BANCO).AsString := FilterIdBanco;
end;
if (FilterNomeConta <> string.Empty) then
begin
AQuery.ParamByName(FIELD_NOME_CONTA).AsString := '%'+FilterNomeConta +'%';
end;
if (FilterNumeroConta <> string.Empty) then
begin
AQuery.ParamByName(FIELD_NUMERO).AsString := FilterNumeroConta;
end;
end;
function TContaCorrenteController.GetFilterExpression: string;
begin
Result := 'WHERE 1 = 1 ';
if (FilterIdBanco <> string.Empty) then
begin
Result := Result + ' AND conta_corrente.' + FIELD_ID_BANCO + ' = :' + FIELD_ID_BANCO;
end;
if (FilterNomeConta <> string.Empty) then
begin
Result := Result + ' AND UPPER(conta_corrente.' + FIELD_NOME_CONTA + ') LIKE UPPER(:' +
FIELD_NOME_CONTA + ') ';
end;
if (FilterNumeroConta <> string.Empty) then
begin
Result := Result + ' AND conta_corrente.' + FIELD_NUMERO + ' = :' + FIELD_NUMERO;
end;
end;
function TContaCorrenteController.GetValidator: IModelValidator;
begin
Result := TContaCorrenteValidator.Create;
end;
function TContaCorrenteController.PopulateModel(AQuery: TSQLQuery): TModelBase;
begin
Result := TContaCorrente.Create;
with Result as TContaCorrente do
begin
IdBanco := AQuery.FieldByName('_idBanco').AsString;
NomeConta := AQuery.FieldByName(FIELD_NOME_CONTA).AsString;
Numero := AQuery.FieldByName(FIELD_NUMERO).AsString;
DataAbertura := AQuery.FieldByName(FIELD_DATA_ABERTURA).AsDateTime;
Observacao := AQuery.FieldByName(FIELD_OBSERVACAO).AsString;
SaldoInicial := AQuery.FieldByName(FIELD_SALDO_INICIAL).AsFloat;
NomeBanco:= AQuery.FieldByName('nomeBanco').AsString;
end;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Spec.BuildEntry;
interface
uses
JsonDataObjects,
Spring.Collections,
DPM.Core.Logging,
DPM.Core.Spec.Interfaces,
DPM.Core.Spec.Node;
type
TSpecCopyEntry = class(TSpecNode, ISpecCopyEntry)
private
FSource : string;
FFlatten : boolean;
protected
function GetSource : string;
function GetFlatten : boolean;
function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override;
function Clone : ISpecCopyEntry;
public
constructor CreateClone(const logger : ILogger; const source : string; const flatten : boolean); reintroduce;
public
constructor Create(const logger : ILogger); override;
end;
TSpecBuildEntry = class(TSpecNode, ISpecBuildEntry)
private
FBplOutputDir : string;
FConfig : string;
FLibOutputDir : string;
FId : string;
FProject : string;
FDesignOnly : boolean;
FBuildForDesign : boolean;
FCopyFiles : IList<ISpecCopyEntry>;
protected
function GetConfig : string;
function GetBplOutputDir : string;
function GetLibOutputDir : string;
function GetId : string;
function GetProject : string;
function GetDesignOnly : boolean;
function GetBuildForDesign : boolean;
function GetCopyFiles: IList<ISpecCopyEntry>;
procedure SetProject(const value : string);
procedure SetLibOutputDir(const value : string);
procedure SetBplOutputDir(const value : string);
procedure SetId(const value : string);
procedure SetDesignOnly(const value : boolean);
procedure SetBuildForDesign(const value : boolean);
function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override;
function Clone : ISpecBuildEntry;
public
constructor CreateClone(const logger : ILogger; const id, project, config, bpldir, libdir : string; const designOnly : boolean; const buildForDesign : boolean; const copyFiles : IList<ISpecCopyEntry>); reintroduce;
public
constructor Create(const logger : ILogger); override;
end;
implementation
{ TSpecBuildEntry }
function TSpecBuildEntry.Clone : ISpecBuildEntry;
begin
result := TSpecBuildEntry.CreateClone(logger, FId, FProject, FConfig, FBplOutputDir, FLibOutputDir, FDesignOnly, FBuildForDesign, FCopyFiles);
end;
constructor TSpecBuildEntry.Create(const logger : ILogger);
begin
inherited Create(logger);
FCopyFiles := TCollections.CreateList<ISpecCopyEntry>;
end;
constructor TSpecBuildEntry.CreateClone(const logger : ILogger; const id, project, config, bpldir, libdir : string; const designOnly : boolean; const buildForDesign : boolean; const copyFiles : IList<ISpecCopyEntry>);
var
copyEntry : ISpecCopyEntry;
begin
inherited Create(logger);
FId := id;
FProject := project;
FConfig := config;
FBplOutputDir := bpldir;
FLibOutputDir := libdir;
FDesignOnly := designOnly;
FBuildForDesign := buildForDesign;
FCopyFiles := TCollections.CreateList<ISpecCopyEntry>;
for copyEntry in copyFiles do
FCopyFiles.Add(copyEntry.Clone);
end;
function TSpecBuildEntry.GetLibOutputDir: string;
begin
result := FLibOutputDir;
end;
function TSpecBuildEntry.GetBplOutputDir : string;
begin
result := FBplOutputDir;
end;
function TSpecBuildEntry.GetBuildForDesign: boolean;
begin
result := FBuildForDesign;
end;
function TSpecBuildEntry.GetConfig : string;
begin
result := FConfig;
end;
function TSpecBuildEntry.GetCopyFiles: IList<ISpecCopyEntry>;
begin
result := FCopyFiles;
end;
function TSpecBuildEntry.GetDesignOnly: boolean;
begin
result := FDesignOnly;
end;
function TSpecBuildEntry.GetId : string;
begin
result := FId;
end;
function TSpecBuildEntry.GetProject : string;
begin
result := FProject;
end;
function TSpecBuildEntry.LoadFromJson(const jsonObject : TJsonObject) : Boolean;
var
copyFilesArray : TJsonArray;
begin
result := true;
FId := jsonObject.S['id'];
if FId = '' then
begin
Logger.Error('Build Entry is missing required [id] property.');
result := false;
end;
FProject := jsonObject.S['project'];
if FProject = '' then
begin
Logger.Error('Build Entry is missing required [project] property.');
result := false;
end;
FConfig := jsonObject.S['config'];
if FConfig = '' then
FConfig := 'Release';
FBplOutputDir := jsonObject.S['bplOutputDir'];
if FBplOutputDir = '' then
FBplOutputDir := 'bin';
FLibOutputDir := jsonObject.S['libOutputDir'];
if FLibOutputDir = '' then
FLibOutputDir := 'lib';
FDesignOnly := jsonObject.B['designOnly'];
FBuildForDesign := jsonObject.B['buildForDesign'];
if jsonObject.Contains('copyFiles') then
begin
copyFilesArray := jsonObject.A['copyFiles'];
LoadJsonCollection(copyFilesArray, TSpecCopyEntry,
procedure(const value : IInterface)
begin
FCopyFiles.Add(value as ISpecCopyEntry);
end);
end;
end;
procedure TSpecBuildEntry.SetLibOutputDir(const value: string);
begin
FLibOutputDir := value;
end;
procedure TSpecBuildEntry.SetBplOutputDir(const value : string);
begin
FBplOutputDir := value;
end;
procedure TSpecBuildEntry.SetBuildForDesign(const value: boolean);
begin
FBuildForDesign := value;
end;
procedure TSpecBuildEntry.SetDesignOnly(const value: boolean);
begin
FDesignOnly := value;
end;
procedure TSpecBuildEntry.SetId(const value : string);
begin
FId := value;
end;
procedure TSpecBuildEntry.SetProject(const value : string);
begin
FProject := value;
end;
{ TSpecCopyEntry }
function TSpecCopyEntry.Clone: ISpecCopyEntry;
begin
result := TSpecCopyEntry.CreateClone(Logger, FSource, FFlatten)
end;
constructor TSpecCopyEntry.Create(const logger: ILogger);
begin
inherited Create(logger);
end;
constructor TSpecCopyEntry.CreateClone(const logger: ILogger; const source: string; const flatten: boolean);
begin
inherited Create(logger);
FSource := source;
FFlatten := flatten;
end;
function TSpecCopyEntry.GetFlatten: boolean;
begin
result := FFlatten;
end;
function TSpecCopyEntry.GetSource: string;
begin
result := FSource;
end;
function TSpecCopyEntry.LoadFromJson(const jsonObject: TJsonObject): Boolean;
begin
result := true;
FSource := jsonObject.S['src'];
if FSource = '' then
begin
Logger.Error('Copy Entry is missing required [src] property.');
result := false;
end;
FFlatten := jsonObject.B['flatten'];
end;
end.
|
unit uDateUtils;
interface
uses
System.SysUtils,
System.DateUtils,
uTranslate;
function DateTimeStrEval(const DateTimeFormat: string; const DateTimeStr: string): TDateTime;
function FormatDateTimeShortDate(Date: TDateTime): string;
function MonthToString(Date: TDate; Scope: string): string; overload;
function MonthToString(Month: Integer): string; overload;
function WeekDayToString(Date: TDate): string;
implementation
const
MonthList: array[1..12] of string = ('january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december');
function MonthToString(Month: Integer): string;
begin
Result := TA(MonthList[Month], 'Month');
end;
function MonthToString(Date: TDate; Scope: string): string;
begin
Result := TA(MonthList[MonthOf(Date)], Scope);
end;
function WeekDayToString(Date: TDate): string;
const
MonthList: array[1..7] of string = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday');
begin
Result := TA(MonthList[DayOfTheWeek(Date)], 'Date');
end;
// =============================================================================
// Evaluate a date time string into a TDateTime obeying the
// rules of the specified DateTimeFormat string
// eg. DateTimeStrEval('dd-MMM-yyyy hh:nn','23-May-2002 12:34)
//
// NOTE : One assumption I have to make that DAYS,MONTHS,HOURS and
// MINUTES have a leading ZERO or SPACE (ie. are 2 chars long)
// and MILLISECONDS are 3 chars long (ZERO or SPACE padded)
//
// Supports DateTimeFormat Specifiers
//
// dd the day as a number with a leading zero or space (01-31).
// ddd the day as an abbreviation (Sun-Sat)
// dddd the day as a full name (Sunday-Saturday)
// mm the month as a number with a leading zero or space (01-12).
// mmm the month as an abbreviation (Jan-Dec)
// mmmm the month as a full name (January-December)
// yy the year as a two-digit number (00-99).
// yyyy the year as a four-digit number (0000-9999).
// hh the hour with a leading zero or space (00-23)
// nn the minute with a leading zero or space (00-59).
// ss the second with a leading zero or space (00-59).
// zzz the millisecond with a leading zero (000-999).
// ampm Specifies am or pm flag hours (0..12)
// ap Specifies a or p flag hours (0..12)
//
//
// Delphi 6 Specific in DateUtils can be translated to ....
//
// YearOf()
//
// function YearOf(const AValue: TDateTime): Word;
// var LMonth, LDay : word;
// begin
// DecodeDate(AValue,Result,LMonth,LDay);
// end;
//
// TryEncodeDateTime()
//
// function TryEncodeDateTime(const AYear,AMonth,ADay,AHour,AMinute,ASecond,
// AMilliSecond : word;
// out AValue : TDateTime): Boolean;
// var LTime : TDateTime;
// begin
// Result := TryEncodeDate(AYear, AMonth, ADay, AValue);
// if Result then begin
// Result := TryEncodeTime(AHour, AMinute, ASecond, AMilliSecond, LTime);
// if Result then
// AValue := AValue + LTime;
// end;
// end;
//
// =============================================================================
function DateTimeStrEval(const DateTimeFormat: string;
const DateTimeStr: string): TDateTime;
var
I, Ii, Iii: Integer;
Retvar: TDateTime;
Tmp, Fmt, Data, Mask, Spec: string;
Year, Month, Day, Hour, Minute, Second, MSec: Word;
AmPm: Integer;
begin
Year := 1;
Month := 1;
Day := 1;
Hour := 0;
Minute := 0;
Second := 0;
MSec := 0;
Fmt := UpperCase(DateTimeFormat);
Data := UpperCase(DateTimeStr);
I := 1;
Mask := '';
AmPm := 0;
while I < Length(Fmt) do
begin
if CharInSet(Fmt[I], ['A', 'P', 'D', 'M', 'Y', 'H', 'N', 'S', 'Z']) then
begin
// Start of a date specifier
Mask := Fmt[I];
Ii := I + 1;
// Keep going till not valid specifier
while True do
begin
if Ii > Length(Fmt) then
Break; // End of specifier string
Spec := Mask + Fmt[Ii];
if (Spec = 'DD') or (Spec = 'DDD') or (Spec = 'DDDD') or (Spec = 'MM')
or (Spec = 'MMM') or (Spec = 'MMMM') or (Spec = 'YY') or
(Spec = 'YYY') or (Spec = 'YYYY') or (Spec = 'HH') or (Spec = 'NN') or
(Spec = 'SS') or (Spec = 'ZZ') or (Spec = 'ZZZ') or (Spec = 'AP') or
(Spec = 'AM') or (Spec = 'AMP') or (Spec = 'AMPM') then
begin
Mask := Spec;
Inc(Ii);
end
else
begin
// End of or Invalid specifier
Break;
end;
end;
// Got a valid specifier ? - evaluate it from data string
if (Mask <> '') and (Length(Data) > 0) then
begin
// Day 1..31
if (Mask = 'DD') then
begin
Day := StrToIntDef(Trim(Copy(Data, 1, 2)), 0);
Delete(Data, 1, 2);
end;
// Day Sun..Sat (Just remove from data string)
if Mask = 'DDD' then
Delete(Data, 1, 3);
// Day Sunday..Saturday (Just remove from data string LEN)
if Mask = 'DDDD' then
begin
Tmp := Copy(Data, 1, 3);
for Iii := 1 to 7 do
begin
if Tmp = UpperCase(Copy(FormatSettings.LongDayNames[Iii],
1, 3)) then
begin
Delete(Data, 1, Length(FormatSettings.LongDayNames[Iii]));
Break;
end;
end;
end;
// Month 1..12
if (Mask = 'MM') then
begin
Month := StrToIntDef(Trim(Copy(Data, 1, 2)), 0);
Delete(Data, 1, 2);
end;
// Month Jan..Dec
if Mask = 'MMM' then
begin
Tmp := Copy(Data, 1, 3);
for Iii := 1 to 12 do
begin
if Tmp = UpperCase(Copy(FormatSettings.LongMonthNames[Iii],
1, 3)) then
begin
Month := Iii;
Delete(Data, 1, 3);
Break;
end;
end;
end;
// Month January..December
if Mask = 'MMMM' then
begin
Tmp := Copy(Data, 1, 3);
for Iii := 1 to 12 do
begin
if Tmp = UpperCase(Copy(FormatSettings.LongMonthNames[Iii],
1, 3)) then
begin
Month := Iii;
Delete(Data, 1, Length(FormatSettings.LongMonthNames[Iii]));
Break;
end;
end;
end;
// Year 2 Digit
if Mask = 'YY' then
begin
Year := StrToIntDef(Copy(Data, 1, 2), 0);
Delete(Data, 1, 2);
if Year < FormatSettings.TwoDigitYearCenturyWindow then
Year := (YearOf(Date) div 100) * 100 + Year
else
Year := (YearOf(Date) div 100 - 1) * 100 + Year;
end;
// Year 4 Digit
if Mask = 'YYYY' then
begin
Year := StrToIntDef(Copy(Data, 1, 4), 0);
Delete(Data, 1, 4);
end;
// Hours
if Mask = 'HH' then
begin
Hour := StrToIntDef(Trim(Copy(Data, 1, 2)), 0);
Delete(Data, 1, 2);
end;
// Minutes
if Mask = 'NN' then
begin
Minute := StrToIntDef(Trim(Copy(Data, 1, 2)), 0);
Delete(Data, 1, 2);
end;
// Seconds
if Mask = 'SS' then
begin
Second := StrToIntDef(Trim(Copy(Data, 1, 2)), 0);
Delete(Data, 1, 2);
end;
// Milliseconds
if (Mask = 'ZZ') or (Mask = 'ZZZ') then
begin
MSec := StrToIntDef(Trim(Copy(Data, 1, 3)), 0);
Delete(Data, 1, 3);
end;
// AmPm A or P flag
if (Mask = 'AP') then
begin
if Data[1] = 'A' then
AmPm := -1
else
AmPm := 1;
Delete(Data, 1, 1);
end;
// AmPm AM or PM flag
if (Mask = 'AM') or (Mask = 'AMP') or (Mask = 'AMPM') then
begin
if Copy(Data, 1, 2) = 'AM' then
AmPm := -1
else
AmPm := 1;
Delete(Data, 1, 2);
end;
Mask := '';
I := Ii;
end;
end else
begin
// Remove delimiter from data string
if Length(Data) > 1 then
Delete(Data, 1, 1);
Inc(I);
end;
end;
if AmPm = 1 then
Hour := Hour + 12;
if not TryEncodeDateTime(Year, Month, Day, Hour, Minute, Second, MSec,
Retvar) then
Retvar := 0.0;
Result := Retvar;
end;
function FormatDateTimeShortDate(Date: TDateTime): string;
begin
Result := FormatDateTime('ddddd', Date);
end;
end.
|
unit ListRes;
{$MODE Delphi}
interface
uses Values, Classes;
type
TCOGFile=class
Vals:TCOgValues;
Constructor Create;
Destructor Destroy;override;
Procedure Load(const fname:string);
Procedure LoadNoLocals(const fname:string);
Function GetCount:integer;
Function GetItem(i:integer):TCOGValue;
Property Count:integer read GetCount;
Property Items[i:integer]:TCOGValue read getItem;default;
Private
Procedure Clear;
Procedure LoadFile(const fname:string;locals:boolean);
end;
TPUPFile=class
Keys:TStringList;
Constructor Create;
Destructor Destroy;override;
Procedure Load(const fname:string);
end;
TSNDFile=class
wavs:TStringList;
Constructor Create;
Destructor Destroy;override;
Procedure Load(const fname:string);
end;
T3DOFile=class
mats:TStringList;
Constructor Create;
Destructor Destroy;override;
Procedure Load(const fname:string);
end;
TITEMSDATFile=class
cogs:TStringList;
Constructor Create;
Destructor Destroy;override;
Procedure Load(const fname:string);
end;
TMODELSDATFile=class
snds:TStringList;
a3dos:TSTringList;
Constructor Create;
Destructor Destroy;override;
Procedure Load(const fname:string);
end;
Function GetMatFromSPR(const fname:string):string;
Function GetMatFromPAR(const fname:string):string;
Procedure LoadJKLLists(const jklname:string;sl:TSTringList);
implementation
uses Files, FileOperations, misc_utils, SysUtils;
Constructor TCOGFile.Create;
begin
Vals:=TCOGValues.Create;
end;
Procedure TCOGFile.Clear;
var i:integer;
begin
For i:=0 to vals.count-1 do Vals[i].Free;
Vals.Clear;
end;
Destructor TCOGFile.Destroy;
begin
Clear;
vals.Free;
end;
Procedure TCOGFile.LoadNoLocals(const fname:string);
begin
LoadFile(fname,false);
end;
Procedure TCOGFile.Load(const fname:string);
begin
LoadFile(fname,true);
end;
Procedure TCOGFile.LoadFile(const fname:string;locals:boolean);
var t:TTextFile;s,w,w1:string;p,pe:integer;v:TCogValue;
begin
for p:=0 to Vals.Count-1 do Vals[p].Free;
Vals.clear;
try
t:=TTextFile.CreateRead(OpenGameFile(fname));
except
On Exception do exit;
end;
Try
Repeat
t.Readln(s);
GetWord(s,1,w);
until (t.eof) or (CompareText(w,'symbols')=0);
if not t.eof then
While not t.eof do
begin
t.Readln(s); RemoveComment(s);
p:=GetWord(s,1,w);
if CompareText(w,'end')=0 then break;
if w<>'' then
begin
v:=TCogValue.Create;
GetCOGVal(s,v);
if not locals then
begin
if (v.local) or (v.cog_type=ct_msg) then
begin
v.free;
continue;
end;
end;
Vals.Add(v);
end;
end;
finally
t.Fclose;
end;
end;
Function TCOGFile.GetCount:integer;
begin
Result:=Vals.Count;
end;
Function TCOGFile.GetItem(i:integer):TCOGValue;
begin
Result:=TCOgValue(Vals[i]);
end;
Constructor TPUPFile.Create;
begin
Keys:=TStringList.Create;
end;
Destructor TPUPFile.Destroy;
begin
Keys.Free;
end;
Procedure TPUPFile.Load(const fname:string);
var t:TTextFile;s,w:string;p:integer;
begin
Keys.Clear;
try
t:=TTextFile.CreateRead(OpenGameFile(fname));
except
On Exception do exit;
end;
Try
While not t.eof do
begin
t.Readln(s); RemoveComment(s);
p:=GetWord(s,1,w);
if w<>'' then
begin
GetWord(s,p,w);
if UpperCase(ExtractFileExt(w))='.KEY' then keys.Add(w);
end;
end;
finally
t.Fclose;
end;
end;
Constructor TSNDFile.Create;
begin
Wavs:=TStringList.Create;
end;
Destructor TSNDFile.Destroy;
begin
Wavs.Free;
end;
Procedure TSNDFile.Load(const fname:string);
var t:TTextFile;s,w:string;p:integer;
begin
Wavs.Clear;
try
t:=TTextFile.CreateRead(OpenGameFile(fname));
except
On Exception do exit;
end;
Try
While not t.eof do
begin
t.Readln(s); RemoveComment(s);
p:=GetWord(s,1,w);
if w<>'' then
begin
GetWord(s,p,w);
Wavs.Add(w);
end;
end;
finally
t.Fclose;
end;
end;
Function GetMatFromSPR(const fname:string):string;
var t:TTextFile;s,w:string;
begin
Result:='';
try
t:=TTextFile.CreateRead(OpenGameFile(fname));
except
On Exception do exit;
end;
Try
While not t.eof do
begin
t.Readln(s); RemoveComment(s);
GetWord(s,1,w);
if w<>'' then begin Result:=w; exit; end;
end;
finally
t.Fclose;
end;
end;
Function GetMatFromPAR(const fname:string):string;
var t:TTextFile;s,w:string;p:integer;
begin
Result:='';
try
t:=TTextFile.CreateRead(OpenGameFile(fname));
except
On Exception do exit;
end;
Try
While not t.eof do
begin
t.Readln(s); RemoveComment(s);
p:=GetWord(s,1,w);
if w='MATERIAL' then begin GetWord(s,p,Result); exit; end;
end;
finally
t.Fclose;
end;
end;
Constructor T3DOFile.Create;
begin
mats:=TStringList.Create;
end;
Destructor T3DOFile.Destroy;
begin
Mats.free;
end;
Procedure T3DOFile.Load(const fname:string);
var t:TTextFile;
s,w:string;
i,n,p,nm:integer;
begin
Mats.clear;
try
t:=TTextFile.CreateRead(OpenGameFile(fname));
except
On Exception do exit;
end;
try
Repeat
t.Readln(s);
p:=GetWord(s,1,w);
until (t.eof) or (w='MATERIALS');
if not t.eof then
begin
RemoveComment(s);
GetWord(s,p,w);
n:=StrToInt(w);
nm:=0;
While (nm<n) or t.eof do
begin
t.Readln(s);
RemoveComment(s);
p:=GetWord(s,1,w);
if w='' then continue;
GetWord(s,p,w);
mats.Add(w);
inc(nm);
end;
end;
finally
t.Fclose;
end;
end;
Constructor TITEMSDatFile.Create;
begin
cogs:=TStringList.Create;
end;
Destructor TITEMSDatFile.Destroy;
begin
cogs.free;
end;
Procedure TITEMSDatFile.Load(const fname:string);
var t:TTextFile;
s,w:string;
i,n,p:integer;
begin
Cogs.clear;
try
t:=TTextFile.CreateRead(OpenGameFile(fname));
except
On Exception do exit;
end;
try
While not t.eof do
begin
t.Readln(s);
RemoveComment(s);
p:=pos('cog=',s);
if p<>0 then
begin
GetWord(s,p+4,w);
if w<>'' then cogs.Add(w);
end;
end;
finally
t.Fclose;
end;
end;
Constructor TMODELSDatFile.Create;
begin
snds:=TStringList.Create;
a3dos:=TStringList.Create;
end;
Destructor TMODELSDatFile.Destroy;
begin
snds.free;
a3dos.Free;
end;
Procedure TMODELSDatFile.Load(const fname:string);
var t:TTextFile;
s,w:string;
i,n,p:integer;
begin
Snds.clear;
try
t:=TTextFile.CreateRead(OpenGameFile(fname));
except
On Exception do exit;
end;
try
While not t.eof do
begin
t.Readln(s);
RemoveComment(s);
p:=GetWord(s,1,w);
p:=GetWord(s,p,w);
if w<>'' then a3dos.Add(w);
p:=GetWord(s,p,w);
if w<>'' then snds.Add(w);
end;
finally
t.Fclose;
end;
end;
Procedure LoadJKLLists(const jklname:string;sl:TSTringList);
var
EndOfSection:boolean;
CurSection:string;
t:TTextFile;
s:string;
Procedure GetNextLine(var s:String);
var cmt_pos:word; {Position of #}
begin
s:='';
Repeat
if t.eof then begin EndOfSection:=true; exit; end;
t.Readln(s);
cmt_pos:=Pos('#',s);
if cmt_pos<>0 then SetLength(s,cmt_pos-1);
s:=UpperCase(Trim(s));
Until s<>'';
if s='END' then begin CurSection:=''; EndOfSection:=true; end;
if GetWordN(s,1)='SECTION:' then begin CurSection:=GetWordN(s,2); EndOfSection:=true; end;
end; {GetNextLine}
Procedure SkipToNextSection;
begin
While not EndOfSection do GetNextLine(s);
end;
Procedure LoadSounds;
begin
CurSection:='';
GetNextLine(s);
While (not EndOfSection) do
begin
GetNextLine(s);
sl.Add(s);
end;
end;
Procedure LoadListSec;
begin
CurSection:='';
GetNextLine(s);
While (not EndOfSection) do
begin
GetNextLine(s);
sl.Add(GetWordN(s,2));
end;
end;
begin {LoadJKLLists}
Try
t:=TTextFile.CreateRead(OpenFileRead(jklname,0));
Try
Repeat
While (CurSection='') and (not t.eof) do GetNextLine(s);
if t.eof then break;
EndOfSection:=false;
if CurSection='SOUNDS' then LoadSounds
else if CurSection='MATERIALS' then LoadListSec
else if CurSection='MODELS' then LoadListSec
else if CurSection='MATERIALS' then LoadListSec
else if CurSection='AICLASS' then LoadListSec
else if CurSection='SPRITES' then LoadListSec
else if CurSection='KEYFRAMES' then LoadListSec
else if CurSection='ANIMCLASS' then LoadListSec
else if CurSection='SOUNDCLASS' then LoadListSec
else if CurSection='COGSCRIPTS' then LoadListSec
else SkipToNextSection;
until t.eof;
Finally
t.Fclose;
end;
Except
on Exception do;
end;
end;
end.
|
unit SpPeople_Types;
interface
uses Controls;
type
TEditMode = (emNew, emModify, emView);
// Уже есть в SP_Lib.SpCommon
type
TItemInfo = record
IdMan: integer;
FIO: string;
Familia: string;
Imya: string;
Otchestvo: string;
Rus_familia: string;
Rus_Imya: string;
Rus_Otchestvo: string;
Birth_Date: TDateTime;
Tin: string;
Tn: integer;
end;
type
TPassRec = record
Familia: string;
Imya: string;
Otchestvo: string;
RusFamilia: string;
RusImya: string;
RusOtchestvo: string;
Seria: string;
Number: string;
IdPassType: Integer;
GrantDate: TDate; // Когда выдан
GrantedBy: string; // Кем выдан
ID_MAN: Integer; // Необходим для сверки ФИО и новых данных
UpdateFIO: Boolean; // Корректировать ли ФИО
ID_PAS_DATA: Int64; // Идентификатор паспорта
WithOutOtchestvo: Boolean; // Признак, с отчеством физлицо или без
end;
type
TDogRec = record
ID_DOG_BANKCARD: Int64;
ID_MAN: Integer;
TIN: string;
ID_TYPE_PAYMENT: Integer;
FULL_NAME_TYPE_PAYMENT: string;
NUM_LIC_ACCAUNT: string;
CONTROL_ID: string;
DATE_DOG: TDate;
DATE_BEG: TDate;
DATE_END: TDate;
NUM_DOG: string;
COMENT: string;
IS_DOG_CLOSE: Integer;
end;
type
TCardRec = record
ID_BANKCARD: Int64;
ID_DOG_BANKCARD: Int64;
NUM_CARD: string;
DATE_BEG: TDate;
DATE_END: TDate;
COMENT: string;
ID_TYPE_BANKCARD: Integer;
NAME_TYPE_BANKCARD: string;
IS_CARD_CLOSE: Integer;
end;
implementation
end.
|
unit uCharFunctions;
interface
function IsDigit(ch: char): boolean;
function IsUpper(ch: char): boolean;
function IsLower(ch: char): boolean;
function ToUpper(ch: char): char;
function ToLower(ch: char): char;
function ValidateQty(cKey:Char):Char;
function ValidateCurrency(cKey:Char):Char;
function ValidatePositiveCurrency(cKey:Char):Char;
function ValidateNumbers(cKey:Char):Char;
function ValidateFloats(cKey:Char):Char;
implementation
uses Windows;
function IsDigit(ch: char): boolean;
begin
Result := ch in ['0'..'9'];
end;
function IsUpper(ch: char): boolean;
begin
//To determine if the character is an uppercase letter.
Result := ch in ['A'..'Z'];
end;
function IsLower(ch: char): boolean;
begin
//To determine if the character is an lowercase letter.
Result := ch in ['a'..'z'];
end;
function ToUpper(ch: char): char;
begin
//Changes a character to an uppercase letter.
Result := chr(ord(ch) and $DF);
end;
function ToLower(ch: char): char;
begin
//Changes a character to a lowercase letter.
Result := chr(ord(ch) or $20);
end;
function ValidateNumbers(cKey:Char):Char;
begin
if not (cKey IN ['0'..'9',#8]) then
begin
Result:=#0;
MessageBeep($FFFFFFFF);
end
else
Result:=cKey;
end;
function ValidateFloats(cKey:Char):Char;
begin
if not (cKey IN ['0'..'9','.',#8]) then
begin
Result:=#0;
MessageBeep($FFFFFFFF);
end
else
Result:=cKey;
end;
function ValidatePositiveCurrency(cKey:Char):Char;
begin
if not (cKey IN ['0'..'9',',','.',#8]) then
begin
Result:=#0;
MessageBeep($FFFFFFFF);
end
else
Result:=cKey;
end;
function ValidateCurrency(cKey:Char):Char;
begin
if not (cKey IN ['0'..'9','-',',','.',#8]) then
begin
Result:=#0;
MessageBeep($FFFFFFFF);
end
else
Result:=cKey;
end;
function ValidateQty(cKey:Char):Char;
begin
if not (cKey IN ['0'..'9','-',#8]) then
begin
Result:=#0;
MessageBeep($FFFFFFFF);
end
else
Result:=cKey;
end;
end.
|
unit uModAgreement;
interface
uses
uModApp, uModRefPajak, uModTipePembayaran, uModCustomer, uModProdukJasa,
uModBank, uModOrganization, uModUnit;
type
TModAgreement = class(TModApp)
private
FAGR_DATE_END: TDatetime;
FAGR_DATE_INV: TDateTime;
FAGR_DATE_START: TDatetime;
FAGR_DESCRIPTION: string;
FAGR_INV_CNT: Integer;
FAGR_IS_BKP: Integer;
FAGR_IS_PPH23: Integer;
FAGR_IS_PPN: Integer;
FAGR_NO: string;
FAGR_PER_CNT: Integer;
FMODORGANIZATION: TModOrganization;
FMODPAJAK: TModRefPajak;
FMODTIPEBAYAR: TModTipePembayaran;
FMODUNIT: TModUnit;
published
property AGR_DATE_END: TDatetime read FAGR_DATE_END write FAGR_DATE_END;
property AGR_DATE_INV: TDateTime read FAGR_DATE_INV write FAGR_DATE_INV;
property AGR_DATE_START: TDatetime read FAGR_DATE_START write
FAGR_DATE_START;
property AGR_DESCRIPTION: string read FAGR_DESCRIPTION write
FAGR_DESCRIPTION;
property AGR_INV_CNT: Integer read FAGR_INV_CNT write FAGR_INV_CNT;
property AGR_IS_BKP: Integer read FAGR_IS_BKP write FAGR_IS_BKP;
property AGR_IS_PPH23: Integer read FAGR_IS_PPH23 write FAGR_IS_PPH23;
property AGR_IS_PPN: Integer read FAGR_IS_PPN write FAGR_IS_PPN;
property AGR_NO: string read FAGR_NO write FAGR_NO;
property AGR_PER_CNT: Integer read FAGR_PER_CNT write FAGR_PER_CNT;
property MODORGANIZATION: TModOrganization read FMODORGANIZATION write
FMODORGANIZATION;
property MODPAJAK: TModRefPajak read FMODPAJAK write FMODPAJAK;
property MODTIPEBAYAR: TModTipePembayaran read FMODTIPEBAYAR write
FMODTIPEBAYAR;
property MODUNIT: TModUnit read FMODUNIT write FMODUNIT;
end;
TModAgreementDetil = class(TModApp)
private
FAGRD_PRICE: Double;
FAGRD_PRICE_PPN: Double;
FAGRD_QTY: Double;
FAGRD_SUBTOTAL: Double;
FAGRD_TOTAL: Double;
FMODAGREEMENT: TModAgreement;
FMODPRODUKJASA: TModProdukJasa;
published
property AGRD_PRICE: Double read FAGRD_PRICE write FAGRD_PRICE;
property AGRD_PRICE_PPN: Double read FAGRD_PRICE_PPN write FAGRD_PRICE_PPN;
property AGRD_QTY: Double read FAGRD_QTY write FAGRD_QTY;
property AGRD_SUBTOTAL: Double read FAGRD_SUBTOTAL write FAGRD_SUBTOTAL;
property AGRD_TOTAL: Double read FAGRD_TOTAL write FAGRD_TOTAL;
property MODAGREEMENT: TModAgreement read FMODAGREEMENT write FMODAGREEMENT;
property MODPRODUKJASA: TModProdukJasa read FMODPRODUKJASA write
FMODPRODUKJASA;
end;
TModAgreementJadwal = class(TModApp)
private
FAGRJDWL_DESCRIPTION: string;
FAGRJDWL_DUE_DATE: Integer;
FAGRJDWL_NOINVOICE: string;
FAGRJDWL_TERM_NO: Integer;
FAGRJDWL_TRANSDATE: TDateTime;
FMODAGREEMENT: TModAgreement;
FMODORGANIZATION: TModOrganization;
published
property AGRJDWL_DESCRIPTION: string read FAGRJDWL_DESCRIPTION write
FAGRJDWL_DESCRIPTION;
property AGRJDWL_DUE_DATE: Integer read FAGRJDWL_DUE_DATE write
FAGRJDWL_DUE_DATE;
property AGRJDWL_NOINVOICE: string read FAGRJDWL_NOINVOICE write
FAGRJDWL_NOINVOICE;
property AGRJDWL_TERM_NO: Integer read FAGRJDWL_TERM_NO write
FAGRJDWL_TERM_NO;
property AGRJDWL_TRANSDATE: TDateTime read FAGRJDWL_TRANSDATE write
FAGRJDWL_TRANSDATE;
property MODAGREEMENT: TModAgreement read FMODAGREEMENT write FMODAGREEMENT;
property MODORGANIZATION: TModOrganization read FMODORGANIZATION write
FMODORGANIZATION;
end;
implementation
initialization
TModAgreement.RegisterRTTI;
TModAgreementDetil.RegisterRTTI;
TModAgreementJadwal.RegisterRTTI;
end.
|
unit GLDRepositoryForm;
interface
uses
Windows, SysUtils, Classes, Controls, Forms,
ComCtrls, StdCtrls, ExtCtrls, Menus, Buttons,
GL, GLDTypes, GLDConst, GLDClasses, GLDObjects,
GLDCamera, GLDMaterial, GLDRepository;
type
TGLDRepositoryForm = class(TForm)
P_ToolBar: TPanel;
P_Buttons: TPanel;
TV_Main: TTreeView;
BB_Ok: TBitBtn;
BB_Cancel: TBitBtn;
PM_Main: TPopupMenu;
MI_NewCamera: TMenuItem;
MI_NewMaterial: TMenuItem;
MI_NewObject: TMenuItem;
MI_Plane: TMenuItem;
MI_Disk: TMenuItem;
MI_Ring: TMenuItem;
MI_Box: TMenuItem;
MI_Pyramid: TMenuItem;
MI_Cylinder: TMenuItem;
MI_Cone: TMenuItem;
MI_Torus: TMenuItem;
MI_Sphere: TMenuItem;
MI_Tube: TMenuItem;
MI_NewModifier: TMenuItem;
MI_Bend: TMenuItem;
MI_Rotate: TMenuItem;
MI_RotateXYZ: TMenuItem;
MI_Scale: TMenuItem;
MI_Skew: TMenuItem;
MI_Taper: TMenuItem;
MI_Twist: TMenuItem;
MI_N1: TMenuItem;
MI_DeleteCameras: TMenuItem;
MI_DeleteMaterials: TMenuItem;
MI_DeleteObjects: TMenuItem;
MI_DeleteModifiers: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure MI_NewCameraClick(Sender: TObject);
procedure MI_NewMaterialClick(Sender: TObject);
procedure NewObject(Sender: TObject);
procedure NewModifier(Sender: TObject);
procedure MI_DeleteClick(Sender: TObject);
procedure TV_MainClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure PM_MainPopup(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FEditedRepository: TGLDRepository;
FCamerasNode: TTreeNode;
FMaterialsNode: TTreeNode;
FObjectsNode: TTreeNode;
FOnSelectComponent: TGLDSelectComponentMethod;
procedure SetEditedRepository(Value: TGLDRepository);
procedure ResetTree;
procedure EnableAndDisableControls;
procedure ChangeNames;
public
procedure SelectComponent(Instance: TPersistent);
property EditedRepository: TGLDRepository read FEditedRepository write SetEditedRepository;
property OnSelectComponent: TGLDSelectComponentMethod read FOnSelectComponent write FOnSelectComponent;
end;
function GLDGetRepositoryForm: TGLDRepositoryForm;
procedure GLDReleaseRepositoryForm;
implementation
{$R *.dfm}
uses dialogs,
GLDModify,
{$INCLUDE GLDObjects.inc};
var
vRepositoryForm: TGLDRepositoryForm = nil;
function GLDGetRepositoryForm: TGLDRepositoryForm;
begin
if not Assigned(vRepositoryForm) then
vRepositoryForm := TGLDRepositoryForm.Create(nil);
Result := vRepositoryForm;
end;
procedure GLDReleaseRepositoryForm;
begin
if Assigned(vRepositoryForm) then
vRepositoryForm.Free;
vRepositoryForm := nil;
end;
{$HINTS OFF}
procedure TGLDRepositoryForm.FormCreate(Sender: TObject);
begin
FEditedRepository := nil;
FCamerasNode := nil;
FMaterialsNode := nil;
FObjectsNode := nil;
FOnSelectComponent := nil;
end;
procedure TGLDRepositoryForm.EnableAndDisableControls;
begin
if Assigned(TV_Main.Selected) then
with TV_Main do
begin
MI_NewCamera.Enabled := False;
MI_NewMaterial.Enabled := False;
MI_NewObject.Enabled := False;
MI_NewModifier.Enabled := False;
MI_DeleteCameras.Enabled := False;
MI_DeleteMaterials.Enabled := False;
MI_DeleteObjects.Enabled := False;
MI_DeleteModifiers.Enabled := False;
if not Assigned(FEditedRepository) then Exit;
if Selected = FCamerasNode then
begin
MI_NewCamera.Enabled := True;
if FEditedRepository.Cameras.Count > 0 then
MI_DeleteCameras.Enabled := True;
end else
if Selected = FMaterialsNode then
begin
MI_NewMaterial.Enabled := True;
if FEditedRepository.Materials.Count > 0 then
MI_DeleteMaterials.Enabled := True;
end else
if Selected = FObjectsNode then
begin
MI_NewObject.Enabled := True;
if FEditedRepository.Objects.Count > 0 then
MI_DeleteObjects.Enabled := True;
end else
if Assigned(Selected.Data) and
(TObject(Selected.Data) is TGLDModifyList) then
begin
MI_NewModifier.Enabled := True;
if TGLDModifyList(Selected.Data).Count > 0 then
MI_DeleteModifiers.Enabled := True;
end;
end;
end;
procedure TGLDRepositoryForm.ChangeNames;
var
i: Integer;
begin
with FCamerasNode do
if Count > 0 then
for i := 0 to Count - 1 do
Item[i].Text := TGLDUserCamera(Item[i].Data).Name;
with FMaterialsNode do
if Count > 0 then
for i := 0 to Count - 1 do
Item[i].Text := TGLDMaterial(Item[i].Data).Name;
with FObjectsNode do
if Count > 0 then
for i := 0 to Count - 1 do
Item[i].Text := TGLDVisualObject(Item[i].Data).Name;
end;
procedure TGLDRepositoryForm.SetEditedRepository(Value: TGLDRepository);
var
i, j: GLuint;
TreeItem: TTreeNode;
TreeItem2: TTreeNode;
begin
FEditedRepository := Value;
if FEditedRepository = nil then
begin
TV_Main.Items.Clear;
Exit;
end;
ResetTree;
with FEditedRepository.Cameras do
if Count > 0 then
for i := 1 to Count do
begin
TV_Main.Items.AddChild(FCamerasNode, Cameras[i].Name);
FCamerasNode.Item[i - 1].Data := Pointer(Cameras[i]);
end;
with FEditedRepository.Materials do
if Count > 0 then
for i := 1 to Count do
begin
TV_Main.Items.AddChild(FMaterialsNode, Materials[i].Name);
FMaterialsNode.Item[i - 1].Data := Pointer(Materials[i]);
end;
with FEditedRepository.Objects do
if Count > 0 then
for i := 1 to Count do
begin
TV_Main.Items.AddChild(FObjectsNode, Objects[i].Name);
FObjectsNode.Item[i - 1].Data := Pointer(Objects[i]);
if Objects[i].IsEditableObject then
begin
TreeItem := TV_Main.Items.AddChild(FObjectsNode.Item[i - 1], GLD_MODIFIERS_STR);
TreeItem.Data := Pointer(TGLDEditableObject(Objects[i]).ModifyList);
if TGLDEditableObject(Objects[i]).ModifyList.Count > 0 then
for j := 1 to TGLDEditableObject(Objects[i]).ModifyList.Count do
begin
TreeItem2 := TV_Main.Items.AddChild(TreeItem, TGLDEditableObject(Objects[i]).ModifyList[j].RealName);
TreeItem2.Data := Pointer(TGLDEditableObject(Objects[i]).ModifyList[j]);
end;
end;
end;
end;
procedure TGLDRepositoryForm.ResetTree;
begin
with TV_Main.Items do
begin
Clear;
if Assigned(FEditedRepository) then
begin
FCamerasNode := Add(nil, GLD_CAMERAS_STR);
FCamerasNode.Data := Pointer(FEditedRepository.Cameras);
FMaterialsNode := Add(nil, GLD_MATERIALS_STR);
FMaterialsNode.Data := Pointer(FEditedRepository.Materials);
FObjectsNode := Add(nil, GLD_OBJECTS_STR);
FObjectsNode.Data := Pointer(FEditedRepository.Objects);
end;
end;
end;
procedure TGLDRepositoryForm.MI_NewCameraClick(Sender: TObject);
var
TreeItem: TTreeNode;
begin
if not Assigned(FEditedRepository) then Exit;
if FEditedRepository.Cameras.CreateNew > 0 then
if Assigned(FCamerasNode) then
begin
TreeItem := TV_Main.Items.AddChild(FCamerasNode,
FEditedRepository.Cameras.Last.Name);
TreeItem.Data := Pointer(FEditedRepository.Cameras.Last);
FCamerasNode.Expand(False);
end;
TreeItem := nil;
end;
procedure TGLDRepositoryForm.MI_NewMaterialClick(Sender: TObject);
var
TreeItem: TTreeNode;
begin
if not Assigned(FEditedRepository) then Exit;
if FEditedRepository.Materials.CreateNew > 0 then
if Assigned(FMaterialsNode) then
begin
TreeItem := TV_Main.Items.AddChild(FMaterialsNode,
FEditedRepository.Materials.Last.Name);
TreeItem.Data := Pointer(FEditedRepository.Materials.Last);
FMaterialsNode.Expand(False);
end;
TreeItem := nil;
end;
procedure TGLDRepositoryForm.NewObject(Sender: TObject);
var
TreeItem: TTreeNode;
Index: GLuint;
begin
if not Assigned(FEditedRepository) then Exit;
with FEditedRepository.Objects do
begin
Index := 0;
if Sender = MI_Plane then Index := CreateNew(TGLDPlane) else
if Sender = MI_Disk then Index := CreateNew(TGLDDisk) else
if Sender = MI_Ring then Index := CreateNew(TGLDRing) else
if Sender = MI_Box then Index := CreateNew(TGLDBox) else
if Sender = MI_Pyramid then Index := CreateNew(TGLDPyramid) else
if Sender = MI_Cylinder then Index := CreateNew(TGLDCylinder) else
if Sender = MI_Cone then Index := CreateNew(TGLDCone) else
if Sender = MI_Torus then Index := CreateNew(TGLDTorus) else
if Sender = MI_Sphere then Index := CreateNew(TGLDSphere) else
if Sender = MI_Tube then Index := CreateNew(TGLDTube);
if Index = 0 then Exit;
Last.OnChange := FEditedRepository.OnChange;
if Assigned(FObjectsNode) then
begin
TreeItem := TV_Main.Items.AddChild(FObjectsNode,
Last.Name);
TreeItem.Data := Pointer(Last);
TreeItem := TV_Main.Items.AddChild(TreeItem, GLD_MODIFIERS_STR);
TreeItem.Data := TGLDEditableObject(Last).ModifyList;
FObjectsNode.Expand(True);
end;
end;
TreeItem := nil;
end;
procedure TGLDRepositoryForm.NewModifier(Sender: TObject);
var
TreeItem: TTreeNode;
Index: GLuint;
begin
if not Assigned(FEditedRepository) then Exit;
if Assigned(TV_Main.Selected) and
Assigned(TV_Main.Selected.Data) and
(TObject(TV_Main.Selected.Data) is TGLDModifyList) then
with TGLDModifyList(TV_Main.Selected.Data) do
begin
Index := 0;
if Sender = MI_Bend then Index := CreateNew(TGLDBend) else
if Sender = MI_Rotate then Index := CreateNew(TGLDRotate) else
if Sender = MI_RotateXYZ then Index := CreateNew(TGLDRotateXYZ) else
if Sender = MI_Scale then Index := CreateNew(TGLDScale) else
if Sender = MI_Skew then Index := CreateNew(TGLDSkew) else
if Sender = MI_Taper then Index := CreateNew(TGLDTaper) else
if Sender = MI_Twist then Index := CreateNew(TGLDTwist);
if Index = 0 then Exit;
TreeItem := TV_Main.Items.AddChild(TV_Main.Selected, Last.RealName);
TreeItem.Data := Pointer(Last);
TV_Main.Selected.Expand(False);
end;
end;
procedure TGLDRepositoryForm.MI_DeleteClick(Sender: TObject);
begin
if not Assigned(FEditedRepository) then Exit;
with FEditedRepository do
if Sender = MI_DeleteCameras then
begin
Cameras.Clear;
FCamerasNode.DeleteChildren;
end else
if Sender = MI_DeleteMaterials then
begin
Materials.Clear;
FMaterialsNode.DeleteChildren;
end else
if Sender = MI_DeleteObjects then
begin
Objects.Clear;
FObjectsNode.DeleteChildren;
end else
if Sender = MI_DeleteModifiers then
begin
if Assigned(TV_Main.Selected) and
Assigned(TV_Main.Selected.Data) and
(TObject(TV_Main.Selected.Data) is TGLDModifyList) then
begin
TGLDModifyList(TV_Main.Selected.Data).Clear;
TV_Main.Selected.DeleteChildren;
end;
end;
end;
{$HINTS ON}
procedure TGLDRepositoryForm.TV_MainClick(Sender: TObject);
begin
EnableAndDisableControls;
if not Assigned(FEditedRepository) then Exit;
with TV_Main do
begin
if Assigned(Selected) then
begin
if Selected = FCamerasNode then
begin
SelectComponent(FEditedRepository.Cameras);
end else
if Selected = FMaterialsNode then
SelectComponent(FEditedRepository.Materials) else
if Selected = FObjectsNode then
SelectComponent(FEditedRepository.Objects) else
if Selected.Parent = FCamerasNode then
SelectComponent(TGLDCamera(Selected.Data)) else
if Selected.Parent = FMaterialsNode then
SelectComponent(TGLDMaterial(Selected.Data)) else
if Selected.Parent = FObjectsNode then
SelectComponent(TGLDVisualObject(Selected.Data)) else
if Assigned(Selected.Data) and
(TObject(Selected.Data) is TGLDModify) then
SelectComponent(TGLDModify(Selected.Data));
end;
end;
end;
procedure TGLDRepositoryForm.SelectComponent(Instance: TPersistent);
begin
if Assigned(FOnSelectComponent) then
FOnSelectComponent(Instance);
end;
procedure TGLDRepositoryForm.FormActivate(Sender: TObject);
begin
ChangeNames;
end;
procedure TGLDRepositoryForm.PM_MainPopup(Sender: TObject);
begin
EnableAndDisableControls;
end;
procedure TGLDRepositoryForm.FormDestroy(Sender: TObject);
begin
FOnSelectComponent := nil;
end;
initialization
finalization
GLDReleaseRepositoryForm;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Implements projected textures through a GLScene object.
}
unit VXS.ProjectedTextures;
interface
{$I VXScene.inc}
uses
System.Classes,
VXS.OpenGL,
VXS.XOpenGL,
VXS.VectorTypes,
VXS.Scene,
VXS.PersistentClasses,
VXS.Texture,
VXS.VectorGeometry,
VXS.RenderContextInfo,
VXS.State,
VXS.Context;
type
{ Possible styles of texture projection. Possible values:
ptsOriginal: Original projection method (first pass,
is default scene render, second pass is texture projection).
ptsInverse: Inverse projection method (first pass
is texture projection, sencond pass is regular scene render).
This method is useful if you want to simulate
lighting only through projected textures (the textures
of the scene are "masked" into the white areas of
the projection textures). }
TVXProjectedTexturesStyle = (ptsOriginal, ptsInverse);
TVXProjectedTextures = class;
{ A projected texture emmiter.
It's material property will be used as the projected texture.
Can be places anywhere in the scene. }
TVXTextureEmitter = class(TVXSceneObject)
private
FFOVy: single;
FAspect: single;
protected
{ Sets up the base texture matrix for this emitter
Should be called whenever a change on its properties is made.}
procedure SetupTexMatrix(var ARci: TVXRenderContextInfo);
public
constructor Create(AOwner: TComponent); override;
published
{ Indicates the field-of-view of the projection frustum.}
property FOVy: single read FFOVy write FFOVy;
{ x/y ratio. For no distortion, this should be set to
texture.width/texture.height.}
property Aspect: single read FAspect write FAspect;
end;
{ Specifies an item on the TVXTextureEmitters collection. }
TVXTextureEmitterItem = class(TCollectionItem)
private
FEmitter: TVXTextureEmitter;
protected
procedure SetEmitter(const val: TVXTextureEmitter);
procedure RemoveNotification(aComponent: TComponent);
function GetDisplayName: string; override;
public
constructor Create(ACollection: TCollection); override;
procedure Assign(Source: TPersistent); override;
published
property Emitter: TVXTextureEmitter read FEmitter write SetEmitter;
end;
{ Collection of TVXTextureEmitter. }
TVXTextureEmitters = class(TCollection)
private
FOwner: TVXProjectedTextures;
protected
function GetOwner: TPersistent; override;
function GetItems(index: Integer): TVXTextureEmitterItem;
procedure RemoveNotification(aComponent: TComponent);
public
procedure AddEmitter(texEmitter: TVXTextureEmitter);
property Items[index: Integer]: TVXTextureEmitterItem read GetItems; default;
end;
{ Projected Textures Manager.
Specifies active texture Emitters (whose texture will be projected)
and receivers (children of this object). }
TVXProjectedTextures = class(TVXImmaterialSceneObject)
private
FEmitters: TVXTextureEmitters;
FStyle: TVXProjectedTexturesStyle;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoRender(var ARci: TVXRenderContextInfo;
ARenderSelf, ARenderChildren: Boolean); override;
published
{ List of texture emitters. }
property Emitters: TVXTextureEmitters read FEmitters write FEmitters;
{ Indicates the style of the projected textures. }
property Style: TVXProjectedTexturesStyle read FStyle write FStyle;
end;
//==============================================================
implementation
//==============================================================
// ------------------
// ------------------ TVXTextureEmitter ------------------
// ------------------
constructor TVXTextureEmitter.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
FFOVy := 90;
FAspect := 1;
end;
procedure TVXTextureEmitter.SetupTexMatrix(var ARci: TVXRenderContextInfo);
const
cBaseMat: TMatrix =
(V:((X:0.5; Y:0; Z:0; W:0),
(X:0; Y:0.5; Z:0; W:0),
(X:0; Y:0; Z:1; W:0),
(X:0.5; Y:0.5; Z:0; W:1)));
var
PM: TMatrix;
begin
// Set the projector's "perspective" (i.e. the "spotlight cone"):.
PM := MatrixMultiply(CreatePerspectiveMatrix(FFOVy, FAspect, 0.1, 1), cBaseMat);
PM := MatrixMultiply(invAbsoluteMatrix, PM);
Arci.VXStates.SetTextureMatrix(PM);
end;
// ------------------
// ------------------ TVXTextureEmitterItem ------------------
// ------------------
constructor TVXTextureEmitterItem.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
end;
procedure TVXTextureEmitterItem.Assign(Source: TPersistent);
begin
if Source is TVXTextureEmitterItem then
begin
FEmitter := TVXTextureEmitterItem(Source).FEmitter;
TVXProjectedTextures(TVXTextureEmitters(Collection).GetOwner).StructureChanged;
end;
inherited;
end;
procedure TVXTextureEmitterItem.SetEmitter(const val: TVXTextureEmitter);
begin
if FEmitter <> val then
begin
FEmitter := val;
TVXProjectedTextures(TVXTextureEmitters(Collection).GetOwner).StructureChanged;
end;
end;
// RemoveNotification
//
procedure TVXTextureEmitterItem.RemoveNotification(aComponent: TComponent);
begin
if aComponent = FEmitter then
FEmitter := nil;
end;
// GetDisplayName
//
function TVXTextureEmitterItem.GetDisplayName: string;
begin
if Assigned(FEmitter) then
begin
Result := '[TexEmitter] ' + FEmitter.Name;
end
else
Result := 'nil';
end;
// ------------------
// ------------------ TVXTextureEmitters ------------------
// ------------------
// GetOwner
//
function TVXTextureEmitters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
// GetItems
//
function TVXTextureEmitters.GetItems(index: Integer): TVXTextureEmitterItem;
begin
Result := TVXTextureEmitterItem(inherited Items[index]);
end;
// RemoveNotification
//
procedure TVXTextureEmitters.RemoveNotification(aComponent: TComponent);
var
i: Integer;
begin
for i := 0 to Count - 1 do
Items[i].RemoveNotification(aComponent);
end;
// AddEmitter
//
procedure TVXTextureEmitters.AddEmitter(texEmitter: TVXTextureEmitter);
var
item: TVXTextureEmitterItem;
begin
item := TVXTextureEmitterItem(self.Add);
item.Emitter := texEmitter;
end;
// ------------------
// ------------------ TVXProjectedTextures ------------------
// ------------------
// Create
//
constructor TVXProjectedTextures.Create(AOwner: TComponent);
begin
inherited Create(aOWner);
FEmitters := TVXTextureEmitters.Create(TVXTextureEmitterItem);
FEmitters.FOwner := self;
end;
// Destroy
//
destructor TVXProjectedTextures.Destroy;
begin
FEmitters.Free;
inherited destroy;
end;
// DoRender
//
procedure TVXProjectedTextures.DoRender(var ARci: TVXRenderContextInfo;
ARenderSelf, ARenderChildren: boolean);
const
PS: array[0..3] of Single = (1, 0, 0, 0);
PT: array[0..3] of Single = (0, 1, 0, 0);
PR: array[0..3] of Single = (0, 0, 1, 0);
PQ: array[0..3] of Single = (0, 0, 0, 1);
var
i: integer;
emitter: TVXTextureEmitter;
begin
if not (ARenderSelf or ARenderChildren) then
Exit;
if (csDesigning in ComponentState) then
begin
inherited;
Exit;
end;
//First pass of original style: render regular scene
if Style = ptsOriginal then
self.RenderChildren(0, Count - 1, ARci);
//generate planes
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
glTexGenfv(GL_S, GL_EYE_PLANE, @PS);
glTexGenfv(GL_T, GL_EYE_PLANE, @PT);
glTexGenfv(GL_R, GL_EYE_PLANE, @PR);
glTexGenfv(GL_Q, GL_EYE_PLANE, @PQ);
//options
Arci.VXStates.Disable(stLighting);
Arci.VXStates.DepthFunc := cfLEqual;
Arci.VXStates.Enable(stBlend);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);
glEnable(GL_TEXTURE_GEN_R);
glEnable(GL_TEXTURE_GEN_Q);
//second pass (original) first pass (inverse): for each emiter,
//render projecting the texture summing all emitters
for i := 0 to Emitters.Count - 1 do
begin
emitter := Emitters[i].Emitter;
if not assigned(emitter) then
continue;
if not emitter.Visible then
continue;
emitter.Material.Apply(ARci);
ARci.VXStates.Enable(stBlend);
if Style = ptsOriginal then
begin
//on the original style, render blending the textures
if emitter.Material.Texture.TextureMode <> tmBlend then
ARci.VXStates.SetBlendFunc(bfDstColor, bfOne)
else
ARci.VXStates.SetBlendFunc(bfDstColor, bfZero);
end
else
begin
//on inverse style: the first texture projector should
//be a regular rendering (i.e. no blending). All others
//are "added" together creating an "illumination mask"
if i = 0 then
Arci.VXStates.SetBlendFunc(bfOne, bfZero)
else
ARci.VXStates.SetBlendFunc(bfOne, bfOne);
end;
//get this emitter's tex matrix
emitter.SetupTexMatrix(ARci);
repeat
ARci.ignoreMaterials := true;
Self.RenderChildren(0, Count - 1, ARci);
ARci.ignoreMaterials := false;
until not emitter.Material.UnApply(ARci);
end;
// LoseTexMatrix
ARci.VXStates.SetBlendFunc(bfOne, bfZero);
glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);
glDisable(GL_TEXTURE_GEN_R);
glDisable(GL_TEXTURE_GEN_Q);
glMatrixMode(GL_TEXTURE);
glLoadIdentity;
glMatrixMode(GL_MODELVIEW);
ARci.VXStates.DepthFunc := cfLEqual;
//second pass (inverse): render regular scene, blending it
//with the "mask"
if Style = ptsInverse then
begin
Arci.VXStates.Enable(stBlend);
ARci.VXStates.SetBlendFunc(bfDstColor, bfSrcColor);
//second pass: render everything, blending with what is
//already there
ARci.ignoreBlendingRequests := true;
self.RenderChildren(0, Count - 1, ARci);
ARci.ignoreBlendingRequests := false;
end;
end;
initialization
RegisterClasses([TVXTextureEmitter, TVXProjectedTextures]);
end.
|
unit InfoPagina;
{$mode delphi}
interface
uses
Classes, SysUtils;
type
//Estrazione informazioni dal topic
TInfoTopic = class
private
ttopic, tsubject, tnum_replies, tsc : String;
tvalido : Boolean;
public
constructor Create(NomeFile:String);
function Topic : String;
function Subject : String;
function NumReplies : String;
function SC : String;
function Valido : Boolean;
end;
//estrazione informazioni dal pannello
TPannello = class
const
Expression='.*?\.new">(.*?)</a>.*?">(In revisione|In traduzione|Rilasciata).*?<a href=.*?(center">|center"><a href="(.*?)".*?)<img alt="Upload.*?';
private
tSerie, tStatus, tUrl : TStringList;
tvalido : Boolean;
public
constructor Create(NomeFile:String);
function Count : Integer;
function Serie( index : Integer ) : String;
function Status( index : Integer ) : String;
function Url( index : Integer ) : String;
function Valido : Boolean;
end;
//estrazione informazioni dal modulo di invio
//resynch tramite pannello
TPannelloInvia = class
const
Expression = '<option value="(\d{1,6})">(.*?)</option>';
INVIA = 'INVIA';
MAX_FILE_SIZE = '300000';
private
tpost,
tnome_serie, tid_topic, tepisodio,
ttraduttori, trevisore, tresynch : String;
cartella_value, cartella_voce : TStringList;
tvalido : Boolean;
public
constructor Create(NomeFile:String);
function CartelleCount : Integer;
function CartellaValue( index : Integer) : String;
function CartellaVoce( index : Integer) : String;
function Post : String;
function Serie : String;
function Topic : String;
function Episodio : String;
function Traduttori : String;
function Revisore : String;
function Resynch : String;
function Valido : Boolean;
end;
//estraziione informazioni dalla pagina risultante
//dell'invio tramite pannello per verificare
//l'avvenuto invio
TPannelloPost = class
const
Expression = 'Invio resynch<span style="color:.*?;"> (.*?)</span>';
private
tvalido: Boolean;
public
constructor Create(NomeFile:String);
function Valido : Boolean;
end;
implementation
uses Dialogs, UtilitaExtra, RegExpr;
constructor TInfoTopic.Create(NomeFile:String);
var
TxtFile : TextFile;
buffer : string;
begin
tvalido := False;
if FileExists(NomeFile) then
begin
AssignFile(TxtFile, NomeFile);
Reset(TxtFile) ;
while not EOF(TxtFile) do
begin
ReadLn(TxtFile, buffer);
if ttopic = '' then
ttopic:=LeggiDato(buffer,'hidden" name="topic" value="','" />')
else if tsubject = '' then
tsubject:=LeggiDato(buffer,'hidden" name="subject" value="','" />')
else if tnum_replies = '' then
tnum_replies:=LeggiDato(buffer,'hidden" name="num_replies" value="','" />')
else if tsc = '' then
tsc:=LeggiDato(buffer,'hidden" name="sc" value="','" />')
end;
CloseFile(TxtFile);
tvalido:=True;
end;
end;
function TInfoTopic.Topic : String;
begin
Result := ttopic;
end;
function TInfoTopic.Subject : String;
begin
Result := tsubject;
end;
function TInfoTopic.NumReplies : String;
begin
Result := tnum_replies;
end;
function TInfoTopic.SC : String;
begin
Result := tsc;
end;
function TInfoTopic.Valido : Boolean;
begin
Result := tvalido;
end;
//------------------------------------------------
constructor TPannello.Create(NomeFile:String);
var
TxtFile : TextFile;
buffer : string;
Reg:TRegExpr;
begin
tSerie := TStringList.Create;
tStatus := TStringList.Create;
tUrl := TStringList.Create;
Reg := TregExpr.Create;
tvalido := false;
if FileExists(NomeFile) then
begin
Reg.Expression:=Expression;
AssignFile(TxtFile, NomeFile);
Reset(TxtFile) ;
while not EOF(TxtFile) do
begin
ReadLn(TxtFile, buffer);
if Reg.Exec(buffer) then
repeat
tSerie.Add(StringReplace(Reg.Match[1],' ',' ',[rfReplaceAll]));
tStatus.Add(Reg.Match[2]);
if Reg.SubExprMatchCount > 3
then tUrl.Add(Reg.Match[4])
else tUrl.Add('');
until not Reg.ExecNext;
end;
CloseFile(TxtFile);
tvalido:=True;
end;
Reg.Free;
end;
function TPannello.Count : Integer;
begin
Result := tSerie.Count;
end;
function TPannello.Serie( index : Integer ) : String;
begin
Result := '';
if index < Count then
Result := tSerie.Strings[index];
end;
function TPannello.Status( index : Integer ) : String;
begin
Result := '';
if index < Count then
Result := tStatus.Strings[index];
end;
function TPannello.Url( index : Integer ) : String;
begin
Result := '';
if index < Count then
Result := tUrl.Strings[index];
end;
function TPannello.Valido : Boolean;
begin
Result := tvalido;
end;
//------------------------------------------------
constructor TPannelloInvia.Create(NomeFile:String);
var
TxtFile : TextFile;
buffer : string;
Reg : TRegExpr;
begin
tvalido:=False;
cartella_value := TStringList.Create;
cartella_voce := TStringList.Create;
Reg := TregExpr.Create;
if FileExists(NomeFile) then
begin
Reg.Expression:=Expression;
AssignFile(TxtFile, NomeFile);
Reset(TxtFile) ;
while not EOF(TxtFile) do
begin
ReadLn(TxtFile, buffer);
if tpost = '' then
tpost:=LeggiDato(buffer,'multipart/form-data" action="/','" method="post">')
else if tnome_serie = '' then
begin
tnome_serie:=LeggiDato(buffer,'name="nome_serie" value="','" size="50"');
tid_topic:=LeggiDato(buffer,'name="id_topic" value="','"></td></tr><tr><td >Episodio');
tepisodio:=LeggiDato(buffer,'name="episodio" value="','" size="50"></td>');
ttraduttori:=LeggiDato(buffer,'name="traduttori" value="','" size="80"');
trevisore:=LeggiDato(buffer,'name="revisore" value="','" size="30"');
tresynch:=LeggiDato(buffer,'name="resynch" size="70" value="','"></td></tr><tr><td >Sottotitoli');
end
else if Reg.Exec(buffer) then
repeat
cartella_value.Add(Reg.Match[1]);
cartella_voce.Add(Reg.Match[2]);
tvalido:=True;
until not Reg.ExecNext;
end;
end;
CloseFile(TxtFile);
end;
function TPannelloInvia.CartelleCount : Integer;
begin
Result := cartella_value.Count;
end;
function TPannelloInvia.CartellaValue( index : Integer ) : String;
begin
Result := '';
if index < CartelleCount then
Result := cartella_value.Strings[index];
end;
function TPannelloInvia.CartellaVoce( index : Integer ) : String;
begin
Result := '';
if index < CartelleCount then
Result := cartella_voce.Strings[index];
end;
function TPannelloInvia.Serie : String;
begin
Result := tnome_serie;
end;
function TPannelloInvia.Post : String;
begin
Result := tpost;
end;
function TPannelloInvia.Topic : String;
begin
Result := tid_topic;
end;
function TPannelloInvia.Episodio : String;
begin
Result := tepisodio;
end;
function TPannelloInvia.Traduttori : String;
begin
Result := ttraduttori;
end;
function TPannelloInvia.Revisore : String;
begin
Result := trevisore;
end;
function TPannelloInvia.Resynch : String;
begin
Result := tresynch;
end;
function TPannelloInvia.Valido : Boolean;
begin
Result := tvalido;
end;
//------------------------------------------------
constructor TPannelloPost.Create(NomeFile:String);
var
TxtFile : TextFile;
buffer : string;
Reg : TRegExpr;
begin
tvalido:=False;
Reg := TregExpr.Create;
if FileExists(NomeFile) then
begin
Reg.Expression:=Expression;
AssignFile(TxtFile, NomeFile);
Reset(TxtFile) ;
while not EOF(TxtFile) do
begin
ReadLn(TxtFile, buffer);
if Reg.Exec(buffer) then
if Reg.Match[1] = 'ESEGUITO' then
begin
tvalido := True;
Break;
end
else ShowMessage(Reg.Match[1]);
end;
end;
CloseFile(TxtFile);
end;
function TPannelloPost.Valido : Boolean;
begin
Result := tvalido;
end;
end.
|
unit UHistory;
interface
type
THistoryCell = packed record
code: Integer;
date: TDateTime;
score: Integer;
snakeLength: Integer;
end;
THistoryArray = array of THistoryCell;
procedure addHistoryItem(cell: THistoryCell); overload;
procedure clearHistory();
function returnHistory():THistoryArray;
function toHistoryCell(score: Integer; snakeLength: Integer):THistoryCell;
implementation
uses
DateUtils, SysUtils;
type
THistoryList = ^THistoryListElem;
THistoryListElem = record
cell: THistoryCell;
next: THistoryList;
end;
var
list: THistoryList;
lastCode: Integer = 0;
function isEmpty(list: THistoryList):Boolean;
begin
result := list^.next = nil;
end;
procedure insert(list: THistoryList; cell: THistoryCell);
var
temp: THistoryList;
begin
while not isEmpty(list) and (list^.next^.cell.score > cell.score) do
list := list^.next;
new(temp);
temp^.cell := cell;
temp^.next := list^.next;
list^.next := temp;
end;
procedure delete(list: THistoryList);
var
temp: THistoryList;
begin
temp := list^.next;
list^.next := temp^.next;
dispose(temp);
end;
procedure clearList(list: THistoryList);
begin
while not isEmpty(list) do
delete(list);
end;
procedure createList(var list: THistoryList);
begin
new(list);
list^.next := nil;
end;
procedure destroyList(var list: THistoryList);
begin
clearList(list);
dispose(list);
list := nil;
end;
function isEmptyList():Boolean;
begin
result := isEmpty(list);
end;
procedure addHistoryItem(cell: THistoryCell);
begin
if cell.code = -1 then
begin
inc(lastCode);
cell.code := lastCode;
end
else
if lastCode < cell.code then
lastCode := cell.code;
insert(list, cell);
end;
procedure clearHistory();
begin
clearList(list);
end;
function returnHistory():THistoryArray;
var
temp: THistoryList;
begin
temp := list;
SetLength(result, 0);
while not isEmpty(temp) do
begin
SetLength(result, length(result) + 1);
result[length(result) - 1] := temp^.next^.cell;
temp := temp^.next;
end;
end;
function toHistoryCell(score: Integer; snakeLength: Integer):THistoryCell;
begin
result.code := -1;
result.date := Now;
result.score := score;
result.snakeLength := snakeLength;
end;
initialization
createList(list);
finalization
destroyList(list);
end.
|
unit Chapter05._06_Solution1;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
AI.ListNode;
// 19. Remove Nth Node From End of List
// https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
//
// 使用双指针, 对链表只遍历了一遍
// 时间复杂度: O(n)
// 空间复杂度: O(1)
type
TSolution = class(TObject)
public
function removeNthFromEnd(head: TListNode; n: integer): TListNode;
end;
procedure Main;
implementation
procedure Main;
var
head: TListNode;
begin
head := TListNode.Create([1, 2, 3, 4, 5]);
with TSolution.Create do
begin
head := removeNthFromEnd(head, 1);
WriteLn(head.ToString);
Free;
end;
head.CLearAndFree;
end;
{ TSolution }
function TSolution.removeNthFromEnd(head: TListNode; n: integer): TListNode;
var
l, r, dummyHead, del: TListNode;
i: integer;
begin
dummyHead := TListNode.Create(0);
dummyHead.Next := head;
l := dummyHead;
r := dummyHead;
for i := 0 to n do
r := r.Next;
while r <> nil do
begin
l := l.Next;
r := r.Next;
end;
del := l.Next;
l.Next := del.Next;
FreeAndNil(del);
Result := dummyHead.Next;
dummyHead.Free;
end;
end.
|
unit FProgress;
(*====================================================================
Universal progress window - used when resorting window with found items
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages, ExtCtrls,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, {Gauges,} StdCtrls,
UTypes, ATGauge;
type
{ TFormProgress }
TFormProgress = class(TForm)
ButtonStop: TButton;
Gauge1: TGauge;
procedure ButtonStopClick(Sender: TObject);
private
{ Private declarations }
public
StopIt : boolean;
procedure ResetAndShow (Title: ShortString);
procedure SetProgress(Percent: Integer);
procedure DefaultHandler(var Message); override;
end;
var
FormProgress: TFormProgress;
implementation
uses FSettings;
{$R *.dfm}
//-----------------------------------------------------------------------------
procedure TFormProgress.ResetAndShow (Title: ShortString);
begin
Gauge1.Progress := 0;
Caption := Title;
StopIt := false;
Show;
end;
//-----------------------------------------------------------------------------
procedure TFormProgress.SetProgress(Percent: Integer);
begin
if Percent > Gauge1.Progress then
begin
Gauge1.Progress := Percent;
Application.ProcessMessages;
end;
end;
//-----------------------------------------------------------------------------
procedure TFormProgress.ButtonStopClick(Sender: TObject);
begin
StopIt := true;
end;
//-----------------------------------------------------------------------------
// Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay
// to the top window, so we must have this handler in all forms.
procedure TFormProgress.DefaultHandler(var Message);
begin
with TMessage(Message) do
if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and
g_CommonOptions.bDisableCdAutorun
then
Result := 1
else
inherited DefaultHandler(Message)
end;
//-----------------------------------------------------------------------------
end.
|
unit define_datasrc;
interface
uses
define_dealitem;
type
TDealDataSource = (
src_unknown,
src_all,
src_ctp,
src_offical,
src_tongdaxin,
src_tonghuasun,
src_dazhihui,
src_sina,
src_163,
src_qq,
src_xq
);
const
DataSrc_All = 1;
DataSrc_CTP = 11;
DataSrc_Standard = 12; // 来至官方 证券交易所
DataSrc_TongDaXin = 21; // 通达信
DataSrc_TongHuaSun = 22; // 同花顺
DataSrc_DaZhiHui = 23; // 大智慧
DataSrc_Sina = 31;
DataSrc_163 = 32;
DataSrc_QQ = 33;
DataSrc_XQ = 34; // 雪球
function GetDataSrcCode(ADataSrc: integer): AnsiString;
function GetStockCode_163(AStockItem: PRT_DealItem): AnsiString;
function GetStockCode_Sina(AStockItem: PRT_DealItem): AnsiString;
function GetStockCode_QQ(AStockItem: PRT_DealItem): AnsiString;
function GetDealDataSource(ASourceCode: integer): TDealDataSource;
function GetDealDataSourceCode(ASource: TDealDataSource): integer;
implementation
function GetDealDataSource(ASourceCode: integer): TDealDataSource;
begin
Result := src_unknown;
case ASourceCode of
DataSrc_All: Result := src_all;
DataSrc_CTP: Result := src_ctp;
DataSrc_Standard: Result := src_offical;
DataSrc_tongdaxin: Result := src_tongdaxin;
DataSrc_tonghuasun: Result := src_tonghuasun;
DataSrc_dazhihui: Result := src_dazhihui;
DataSrc_Sina: Result := src_sina;
DataSrc_163: Result := src_163;
DataSrc_QQ: Result := src_qq;
DataSrc_XQ: Result := src_xq;
end;
end;
function GetDealDataSourceCode(ASource: TDealDataSource): integer;
begin
Result := 0;
case ASource of
src_all: Result := DataSrc_All;
src_ctp: Result := DataSrc_Ctp;
src_offical: Result := DataSrc_Standard;
src_tongdaxin: Result := DataSrc_tongdaxin;
src_tonghuasun: Result := DataSrc_tonghuasun;
src_dazhihui: Result := DataSrc_dazhihui;
src_sina: Result := DataSrc_sina;
src_163: Result := DataSrc_163;
src_qq: Result := DataSrc_qq;
src_xq: Result := DataSrc_xq;
end;
end;
function GetDataSrcCode(ADataSrc: integer): AnsiString;
begin
Result := '';
case ADataSrc of
DataSrc_CTP : Result := 'ctp';
DataSrc_Standard : Result := 'gov'; // official 来至官方 证券交易所
DataSrc_Sina : Result := 'sina';
DataSrc_163 : Result := '163';
DataSrc_QQ : Result := 'qq';
DataSrc_XQ : Result := 'xq'; // 雪球
DataSrc_TongDaXin : Result := 'tdx'; // 通达信
DataSrc_TongHuaSun : Result := 'ths'; // 同花顺
DataSrc_DaZhiHui : Result := 'dzh'; // 大智慧
end;
end;
function GetStockCode_163(AStockItem: PRT_DealItem): AnsiString;
begin
if AStockItem.sCode[1] = '6' then
begin
Result := '0' + AStockItem.sCode;
end else
begin
Result := '1' + AStockItem.sCode;
end;
end;
function GetStockCode_Sina(AStockItem: PRT_DealItem): AnsiString;
begin
if AStockItem.sCode[1] = '6' then
begin
Result := 'sh' + AStockItem.sCode;
end else
begin
Result := 'sz' + AStockItem.sCode;
end;
end;
function GetStockCode_QQ(AStockItem: PRT_DealItem): AnsiString;
begin
Result := GetStockCode_Sina(AStockItem);
end;
end.
|
program HowToMoveASprite;
uses
SwinGame, sgTypes;
procedure Main();
var
ball: Sprite;
begin
OpenGraphicsWindow('Move a Sprite', 150, 150);
LoadBitmapNamed('ball', 'ball_small.png');
ball := CreateSprite(BitmapNamed('ball'));
SpriteSetX(ball, 60);
SpriteSetY(ball, 0);
SpriteSetDx(ball, 0);
SpriteSetDy(ball, 0.05);
repeat
ClearScreen(ColorWhite);
if SpriteOffscreen(ball) then
begin
SpriteSetX(ball, 60);
SpriteSetY(ball, -30);
end;
DrawSprite(ball);
UpdateSprite(ball);
RefreshScreen();
ProcessEvents();
until WindowCloseRequested();
FreeSprite(ball);
ReleaseAllResources();
end;
begin
Main();
end. |
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright � 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.AboutForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls;
type
TDPMAboutForm = class(TForm)
Image1 : TImage;
Label1 : TLabel;
Label2 : TLabel;
Label3 : TLabel;
githubLinkLabel : TLinkLabel;
Label4 : TLabel;
lblVersion: TLabel;
procedure githubLinkLabelLinkClick(Sender : TObject; const Link : string; LinkType : TSysLinkType);
private
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner : TComponent);override;
end;
var
DPMAboutForm : TDPMAboutForm;
implementation
uses
Winapi.ShellAPI,
ToolsApi,
DPM.Core.Utils.System;
{$I DPMIDE.inc}
{$R *.dfm}
constructor TDPMAboutForm.Create(AOwner: TComponent);
begin
inherited;
{$IFDEF STYLEELEMENTS}
StyleElements := [seFont, seClient, seBorder];
{$ENDIF}
{$IFDEF THEMESERVICES}
(BorlandIDEServices as IOTAIDEThemingServices).ApplyTheme(Self);
{$ENDIF}
lblVersion.Caption := lblVersion.Caption + TSystemUtils.GetVersionString;
end;
procedure TDPMAboutForm.githubLinkLabelLinkClick(Sender : TObject; const Link : string; LinkType : TSysLinkType);
begin
ShellExecute(0, 'Open', PChar(Link), nil, nil, SW_SHOWNORMAL);
end;
end.
|
program FiveCollCatalog(input, output);
const
MaxBooksInCatalog = 25;
choiceListBooks = 1;
choiceAddBook = 2;
choiceEndOfWork = 3;
charBook = 'B';
charJournal = 'J';
charAvailable = 'A';
charLoan = 'L';
charReserved = 'R';
CatalogFileName = 'catalog.dat';
type
AuthorType = packed array[1..60] of char;
TitleType = packed array[1..80] of char;
StatusType = (available, loan, reserved);
BookKinds = (theBook, theJournal);
PublisherType = packed array[1..40]of char;
LibraryType = packed array[1..12]of char;
PlaceType = record
Library : LibraryType;
CallNumber : packed array[1..16]of char;
end;
YearType = packed array[1..4]of char;
IssueType = packed array[1..4]of char;
VolumeType = packed array[1..4]of char;
BookType = record
Author : AuthorType;
Title : TitleType;
Place : PlaceType;
Status : StatusType;
case Kind : BookKinds of
theBook : (
Publisher : PublisherType;
YearOfPubl : YearType);
theJournal : (
TitleOfJourn : TitleType;
YearOfIssue : YearType;
Volume : VolumeType;
Issue : IssueType);
end;
CatalogType = array[1..MaxBooksInCatalog]of BookType;
var
DataFile : text;
NumBooksInCatalog : integer;
Catalog : CatalogType;
choice : integer;
{ ******* UpCase }
{ Capitalizes the argument }
function UpCase(ch : char) : char;
begin
if (ch >= 'a') and (ch <= 'z')
then ch := chr(ord(ch) - ord('a') + ord('A'));
UpCase := ch;
end; { UpCase }
{******** ReadAllBooks }
{ Opens the data file, and reads all book records from it }
{ one-by-one until the end of file is reached, or limit of }
{ catalog. }
procedure ReadAllBooks(var data : text; var numOfBooks : integer;
var books : CatalogType);
{ ******* ReadTheRecord }
{ Read one book record from data file }
procedure ReadTheRecord(var data : text; var book : BookType);
var
bookKind, status : char;
begin
readln(data, book.Author);
readln(data, book.Title);
readln(data, bookKind);
if bookKind = charBook
then begin
book.Kind := theBook;
readln(data, book.Publisher);
readln(data, book.YearOfPubl);
end
else begin
book.Kind := theJournal;
readln(data, book.TitleOfJourn);
readln(data, book.YearOfIssue);
readln(data, book.Volume);
readln(data, book.Issue);
end;
readln(data, book.Place.Library);
readln(data, book.Place.CallNumber);
readln(data, status);
case status of
charAvailable : book.Status := available;
charLoan : book.Status := loan;
charReserved : book.Status := reserved;
end;
end; { ReadTheRecord }
begin { procedure ReadAllBooks }
open(data, CatalogFileName, OLD);
reset(data);
numOfBooks := 0;
while (not eof(data)) and (numOfBooks < MaxBooksInCatalog) do begin
ReadTheRecord(data, books[numOfBooks+1]);
numOfBooks := numOfBooks + 1;
readln(data);
end;
end; { ReadAllBooks }
{ ******* WriteAllBooks }
{ Rewinds the file to the beginning, and writes all }
{ book records into file one-by-one. Then closes }
{ the file. }
procedure WriteAllBooks(var data : text; numOfBooks : integer;
books : CatalogType);
var
i : integer;
{ ******* WriteTheRecord }
{ Writes one book record from catalog array into }
{ the data file. }
procedure WriteTheRecord(var data : text; book : BookType);
begin
writeln(data, book.Author);
writeln(data, book.Title);
if book.Kind = theBook
then begin
writeln(data, charBook);
writeln(data, book.Publisher);
writeln(data, book.YearOfPubl);
end
else begin
writeln(data, charJournal);
writeln(data, book.TitleOfJourn);
writeln(data, book.YearOfIssue);
writeln(data, book.Volume);
writeln(data, book.Issue);
end;
writeln(data, book.Place.Library);
writeln(data, book.Place.CallNumber);
case book.Status of
available : writeln(data, charAvailable);
loan : writeln(data, charLoan);
reserved : writeln(data, charReserved);
end;
end; { WriteTheRecord }
begin { procedure WriteAllBooks }
rewrite(data);
for i := 1 to numOfBooks do begin
WriteTheRecord(data, books[i]);
writeln(data);
end;
close(data);
end; { WriteAllBooks }
{ ******* GetUserChoice }
{ Prompts the user about the action that he/she }
{ wishes to perform. Accept only "1", "2", or "3" }
function GetUserChoice : integer;
var
choiceChar : char;
choiceInt : integer;
begin
repeat
writeln('1. List All Items');
writeln('2. Add an Item');
writeln('3. Quit.');
writeln;
readln(choiceChar);
choiceInt := ord(choiceChar)-ord('1')+1;
until (choiceInt >= choiceListBooks) and (choiceInt <= choiceEndOfWork);
GetUserChoice := choiceInt;
end; { GetUserChoice }
{ ******* ListAllBooks }
{ Lists all book records on the screen one-by-one, }
{ and prompts the user about changes of book status. }
procedure ListAllBooks(numOfBooks : integer; var books : CatalogType);
var
i : integer;
quit : boolean;
choice : char;
{ ******* ListABook }
{ Prints one book record on the screen }
procedure ListABook(book : BookType);
begin
writeln;
writeln('****************************************************************');
writeln;
writeln('Author: ', book.Author);
writeln('Title: ', book.Title);
writeln;
if book.Kind = theBook
then begin
writeln('Published by ', book.Publisher, ' at ', book.YearOfPubl);
writeln;
end
else begin
writeln('It is the artical in ', book.TitleOfJourn);
writeln('Vol. ', book.Volume, ', no. ', book.Issue, ' in ',
book.YearOfIssue);
writeln;
end;
write ('Library: ', book.Place.Library);
writeln(' Call Number: ', book.Place.CallNumber);
writeln;
write ('Status:');
case book.Status of
available : writeln('It''s available now!');
loan : writeln('I''m sorry. It''s loaned.');
reserved : writeln('It''s reserved.');
end;
writeln('****************************************************************');
end; { ListABook }
begin { procedure ListAllBooks }
i := 0;
quit := FALSE;
while not quit and (i < numOfBooks) do begin
i := i+1;
repeat
ListABook(books[i]);
writeln;
write('Change the status of book (',charAvailable);
writeln('=available,',charLoan,'=loan,',charReserved,'=reserved)');
writeln('Type S to stop listing, anything else to continue.');
readln(choice);
choice := UpCase(choice);
case choice of
charAvailable : books[i].Status := available;
charLoan : books[i].Status := loan;
charReserved : books[i].Status := reserved;
'S' : quit := TRUE;
end;
until not (choice in [charAvailable, charLoan, charReserved]);
end;
end; { ListAllBooks }
{ ******* AddTheBook }
{ This procedure is called when the user chooses }
{ "2" from main menu. It queries the user about adding the }
{ book or paper into catalog. It prompts step-by-step }
{ for all book record parameters. }
procedure AddTheBook(var numOfBooks : integer; var books : CatalogType);
{ ******* GetBookKind }
{ Asks about the kind of inputed information, }
{ whether it is a book, or journal paper. }
{ Accept only "B',"b',"j",&"J" answers. }
function GetBookKind : BookKinds;
var
choice : char;
begin
choice := chr(0);
repeat
write('Is it a book or paper in journal (B=book,J=journal)?');
readln(choice);
choice := UpCase(choice);
until (choice = charBook) or (choice = charJournal);
if choice = charBook
then GetBookKind := theBook
else GetBookKind := theJournal;
end; { GetBookKind }
{ ******* GetLibraryName }
{ Prompts the user for the library name, }
function GetLibraryName : LibraryType;
const
MaxLibrNum = 8;
var
choice : char;
i : integer;
names : array[1..8]of LibraryType VALUE [1:'UMASS/MAIN';
2:'UMASS/PSC';
3:'UMASS/MUSC';
4:'UMASS/BIOL';
5:'AC';
6:'SC';
7:'HAMP';
8:'MHC'];
begin
repeat
writeln('You have to choose one of this libraries');
for i := 1 to MaxLibrNum do
writeln(i:2,'. ',names[i]);
write('Choose the Library Name:');
readln(choice);
i := ord(choice) - ord('1') + 1;
until (i >= 1) and (i <= MaxLibrNum);
GetLibraryName := names[i];
end; { GetLibraryName }
begin { procedure AddTheBook }
if numOfBooks >= MaxBooksInCatalog
then writeln('Sorry. No book can be added.')
else begin
numOfBooks := numOfBooks + 1;
write('Input the Author name: '); readln(books[numOfBooks].Author);
write('Input the Title : '); readln(books[numOfBooks].Title);
writeln;
books[numOfBooks].Kind := GetBookKind;
writeln;
if books[numOfBooks].Kind = theBook
then begin
write('Input the Publisher of the book: ');
readln(books[numOfBooks].Publisher);
write('Input the year of publishing: ');
readln(books[numOfBooks].YearOfPubl);
end
else begin
write('Input the Journal''s title: ');
readln(books[numOfBooks].TitleOfJourn);
write('Input the year of issue: ');
readln(books[numOfBooks].YearOfIssue);
write('Input the volume number: ');
readln(books[numOfBooks].Volume);
write('Input the issue number: ');
readln(books[numOfBooks].Issue);
end;
writeln;
books[numOfBooks].Place.Library := GetLibraryName;
write('Input the Call Number: ');
readln(books[numOfBooks].Place.CallNumber);
books[numOfBooks].Status := available;
end;
end; { AddTheBook }
begin { program }
ReadAllBooks(DataFile, NumBooksInCatalog, Catalog);
repeat
choice := GetUserChoice;
case choice of
choiceListBooks : ListAllBooks(NumBooksInCatalog, Catalog);
choiceAddBook : AddTheBook(NumBooksInCatalog, Catalog);
end;
until choice = choiceEndOfWork;
WriteAllBooks(DataFile, NumBooksInCatalog, Catalog);
end. { program }
|
//**************************************************************
// *
// SecurityManager * *
// For Delphi 5, 6, 7, 2005, 2006 *
// Freeware Component *
// by *
// Per Linds Larsen *
// per.lindsoe@larsen.dk *
// *
// Contributions: *
// Eran Bodankin (bsalsa) bsalsa@bsalsa.com *
// - D2005 update *
// *
// Updated versions: *
// http://www.bsalsa.com *
//**************************************************************
{*******************************************************************************}
{LICENSE:
THIS SOFTWARE IS PROVIDED TO YOU "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED INCLUDING BUT NOT LIMITED TO THE APPLIED
WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
YOU ASSUME THE ENTIRE RISK AS TO THE ACCURACY AND THE USE OF THE SOFTWARE
AND ALL OTHER RISK ARISING OUT OF THE USE OR PERFORMANCE OF THIS SOFTWARE
AND DOCUMENTATION. [YOUR NAME] DOES NOT WARRANT THAT THE SOFTWARE IS ERROR-FREE
OR WILL OPERATE WITHOUT INTERRUPTION. THE SOFTWARE IS NOT DESIGNED, INTENDED
OR LICENSED FOR USE IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE CONTROLS,
INCLUDING WITHOUT LIMITATION, THE DESIGN, CONSTRUCTION, MAINTENANCE OR
OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS,
AIR TRAFFIC CONTROL, AND LIFE SUPPORT OR WEAPONS SYSTEMS. VSOFT SPECIFICALLY
DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR SUCH PURPOSE.
You may use, change or modify the component under 4 conditions:
1. In your website, add a link to "http://www.bsalsa.com"
2. In your application, add credits to "Embedded Web Browser"
3. Mail me (bsalsa@bsalsa.com) any code change in the unit
for the benefit of the other users.
4. Please consider donation in our web site!
{*******************************************************************************}
//$Id: SecurityManager.pas,v 1.7 2007/01/29 11:01:29 bsalsa Exp $
unit SecurityManager;
interface
uses
Activex, UrlMon, Windows, SysUtils, Classes, IEConst;
const
DefaultActions: array[0..24] of DWORD = (
$00001001, $00001004, $00001200, $00001201, $00001400, $00001402,
$00001405, $00001406, $00001407, $00001601, $00001604, $00001605,
$00001606, $00001607, $00001800, $00001802, $00001803, $00001804,
$00001805, $00001A00, $00001A02, $00001A03, $00001A04, $00001C00,
$00001E05);
type
TJavaPolicyOption = (Prohibited, High, Medium, Low, Custom);
TAllowDisAllowPolicyOption = (Allow, Disallow);
const
JavaPolicyValues: array[0..4] of Cardinal =
(URLPOLICY_JAVA_PROHIBIT,
URLPOLICY_JAVA_HIGH,
URLPOLICY_JAVA_MEDIUM,
URLPOLICY_JAVA_LOW,
URLPOLICY_JAVA_CUSTOM);
AllowDisallowValues: array[0..1] of Cardinal = (URLPOLICY_ALLOW, URLPOLICY_DISALLOW);
type
TActiveXOptions = TAllowDisAllowPolicyOption;
TJavaPermissionsOptions = TJavaPolicyOption;
TScriptOptions = TAllowDisallowPolicyOption;
TSubmitFormsOptions = TAllowDisallowPolicyOption;
TCrossDomainDataOptions = TAllowDisallowPolicyOption;
TUrlPolicyOptions = class(TPersistent)
private
FActiveX: TActiveXOptions;
FCrossDomainData: TCrossDomainDataOptions;
FJavaPermissions: TJavaPermissionsOptions;
FSubmitForms: TSubmitFormsOptions;
FScriptOptions: TScriptOptions;
published
property ActiveX: TActiveXOptions read FActiveX write FActiveX;
property CrossDomainData: TCrossDomainDataOptions read FCrossDomainData write FCrossDomainData;
property SubmitForms: TSubmitFormsOptions read FSubmitForms write FSubmitForms;
property JavaPermissions: TJavaPermissionsOptions read FJavaPermissions write FJavaPermissions;
property Scripts: TScriptOptions read FScriptOptions write FScriptOptions;
end;
TSetSecuritySiteEvent = function(Site: IInternetSecurityMgrSite): HResult of object;
TGetSecuritySiteEvent = function(out Site: IInternetSecurityMgrSite): HResult of object;
TMapUrlToZoneEvent = function(pwszUrl: LPCWSTR; out dwZone: DWORD;
dwFlags: DWORD): HResult of object;
TGetSecurityIdEvent = function(pwszUrl: LPCWSTR; pbSecurityId: Pointer;
var cbSecurityId: DWORD; dwReserved: DWORD): HResult of object;
TProcessUrlActionEvent = function(pwszUrl: LPCWSTR; dwAction: DWORD;
pPolicy: Pointer; cbPolicy: DWORD; pContext: Pointer; cbContext: DWORD;
dwFlags, dwReserved: DWORD): HResult of object;
TQueryCustomPolicyEvent = function(pwszUrl: LPCWSTR; const guidKey: TGUID;
out pPolicy: Pointer; out cbPolicy: DWORD; pContext: Pointer; cbContext: DWORD;
dwReserved: DWORD): HResult of object;
TSetZoneMappingEvent = function(dwZone: DWORD; lpszPattern: LPCWSTR;
dwFlags: DWORD): HResult of object;
TGetZoneMappingsEvent = function(dwZone: DWORD; out enumString: IEnumString;
dwFlags: DWORD): HResult of object;
TSecurityManager = class(TComponent, IInternetSecurityManager)
private
{ Private declarations }
FSetSecuritySite: TSetSecuritySiteEvent;
FGetSecuritySite: TGetSecuritySiteEvent;
FMapUrlToZone: TMapUrlToZoneEvent;
FGetSecurityID: TGetSecurityIDEvent;
FProcessUrlAction: TProcessUrlActionEvent;
FQueryCustomPolicy: TQueryCustomPolicyEvent;
FSetZoneMapping: TSetZoneMappingEvent;
FGetZoneMappings: TGetZoneMappingsEvent;
FUrlPolicyOptions: TUrlPolicyOptions;
protected
{ Protected declarations }
public
{ Public declarations }
function QueryInterface(const IID: TGUID; out Obj): HResult; override;
function SetSecuritySite(Site: IInternetSecurityMgrSite): HResult; stdcall;
function GetSecuritySite(out Site: IInternetSecurityMgrSite): HResult; stdcall;
function MapUrlToZone(pwszUrl: LPCWSTR; out dwZone: DWORD;
dwFlags: DWORD): HResult; stdcall;
function GetSecurityId(pwszUrl: LPCWSTR; pbSecurityId: Pointer;
var cbSecurityId: DWORD; dwReserved: DWORD): HResult; stdcall;
function ProcessUrlAction(pwszUrl: LPCWSTR; dwAction: DWORD;
pPolicy: Pointer; cbPolicy: DWORD; pContext: Pointer; cbContext: DWORD;
dwFlags, dwReserved: DWORD): HResult; stdcall;
function QueryCustomPolicy(pwszUrl: LPCWSTR; const guidKey: TGUID;
out pPolicy: Pointer; out cbPolicy: DWORD; pContext: Pointer; cbContext: DWORD;
dwReserved: DWORD): HResult; stdcall;
function SetZoneMapping(dwZone: DWORD; lpszPattern: LPCWSTR;
dwFlags: DWORD): HResult; stdcall;
function GetZoneMappings(dwZone: DWORD; out enumString: IEnumString;
dwFlags: DWORD): HResult; stdcall;
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property OnSetSecuritySite: TSetSecuritySiteEvent read FSetSecuritySite write FSetSecuritySite;
property OnGetSecuritySite: TGetSecuritySiteEvent read FGetSecuritySite write FGetSecuritySite;
property OnMapUrlToZone: TMapUrlToZoneEvent read FMapUrlToZone write FMapUrlToZone;
property OnGetSecurityID: TGetSecurityIDEvent read FGetSecurityID write FGetSecurityID;
property OnProcessUrlAction: TProcessUrlActionEvent read FProcessUrlAction write FProcessUrlAction;
property OnQueryCustomPolicy: TQueryCustomPolicyEvent read FQueryCustomPolicy write FQueryCustomPolicy;
property OnSetZoneMapping: TSetZoneMappingEvent read FSetZoneMapping write FSetZoneMapping;
property OnGetZoneMappings: TGetZoneMappingsEvent read FGetZoneMappings write FGetZoneMappings;
property UrlPolicy: TUrlPolicyOptions read FUrlPolicyOptions write FUrlPolicyOptions;
end;
function DisplayAction(UrlAction: DWORD): string;
function DisplayPolicy(UrlAction, UrlPolicy: DWORD): string;
implementation
// Helper/debug function
function DisplayPolicy(UrlAction, UrlPolicy: DWORD): string;
begin
case UrlPolicy of
URLPOLICY_ALLOW: result := 'URLPOLICY_ALLOW';
URLPOLICY_DISALLOW: result := 'URLPOLICY_DISALLOW';
URLPOLICY_QUERY: result := 'URLPOLICY_QUERY';
URLPOLICY_ACTIVEX_CHECK_LIST: result := 'URLPOLICY_ACTIVEX_CHECK_LIST';
URLPOLICY_MASK_PERMISSIONS: result := 'URLPOLICY_MASK_PERMISSIONS';
URLPOLICY_LOG_ON_DISALLOW: result := 'URLPOLICY_LOG_ON_DISALLOW';
URLPOLICY_LOG_ON_ALLOW: result := 'URLPOLICY_LOG_ON_ALLOW';
URLPOLICY_NOTIFY_ON_DISALLOW: result := 'URLPOLICY_NOTIFY_ON_DISALLOW';
URLPOLICY_NOTIFY_ON_ALLOW: result := 'URLPOLICY_NOTIFY_ON_ALLOW';
end;
if UrlAction = URLACTION_CREDENTIALS_USE then
begin
if UrlPolicy = URLPOLICY_CREDENTIALS_ANONYMOUS_ONLY then
result := 'URLPOLICY_CREDENTIALS_ANONYMOUS_ONLY'
else
if UrlPolicy = URLPOLICY_CREDENTIALS_CONDITIONAL_PROMPT then
result := 'URLPOLICY_CREDENTIALS_CONDITIONAL_PROMPT'
else
if UrlPolicy = URLPOLICY_CREDENTIALS_MUST_PROMPT_USER then
result := 'URLPOLICY_CREDENTIALS_MUST_PROMPT_USER'
else
if UrlPolicy = URLPOLICY_CREDENTIALS_SILENT_LOGON_OK then
result := 'URLPOLICY_CREDENTIALS_SILENT_LOGON_OK';
end
else
if UrlAction = URLACTION_CHANNEL_SOFTDIST_PERMISSIONS then
begin
if UrlPolicy = URLPOLICY_CHANNEL_SOFTDIST_AUTOINSTALL then
result := 'URLPOLICY_CHANNEL_SOFTDIST_AUTOINSTALL'
else
if UrlPolicy = URLPOLICY_CHANNEL_SOFTDIST_PRECACHE then
result := 'URLPOLICY_CHANNEL_SOFTDIST_PRECACHE'
else
if UrlPolicy = URLPOLICY_CHANNEL_SOFTDIST_PROHIBIT then
result := 'URLPOLICY_CHANNEL_SOFTDIST_PROHIBIT'
else
end
else
if UrlAction = URLACTION_JAVA_PERMISSIONS then
begin
if UrlPolicy = URLPOLICY_JAVA_CUSTOM then
result := 'URLPOLICY_JAVA_CUSTOM'
else
if UrlPolicy = URLPOLICY_JAVA_MEDIUM then
result := 'URLPOLICY_JAVA_MEDIUM'
else
if UrlPolicy = URLPOLICY_JAVA_LOW then
result := 'URLPOLICY_JAVA_LOW'
else
if UrlPolicy = URLPOLICY_JAVA_HIGH then
result := 'URLPOLICY_JAVA_HIGH'
else
if UrlPolicy = URLPOLICY_JAVA_PROHIBIT then
result := 'URLPOLICY_JAVA_PROHIBIT';
end;
end;
// Helper/debug function
function DisplayAction(UrlAction: DWORD): string;
begin
case
UrlAction of
URLACTION_DOWNLOAD_SIGNED_ACTIVEX: result := 'URLACTION_DOWNLOAD_SIGNED_ACTIVEX';
URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX: result := 'URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX';
URLACTION_ACTIVEX_RUN: result := 'URLACTION_ACTIVEX_RUN';
URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY: result := 'URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY';
URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY: result := 'URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY';
URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY: result := 'URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY';
URLACTION_SCRIPT_OVERRIDE_SAFETY: result := 'URLACTION_SCRIPT_OVERRIDE_SAFETY';
URLACTION_ACTIVEX_CONFIRM_NOOBJECTSAFETY: result := 'URLACTION_ACTIVEX_CONFIRM_NOOBJECTSAFETY';
URLACTION_ACTIVEX_TREATASUNTRUSTED: result := 'URLACTION_ACTIVEX_TREATASUNTRUSTED';
URLACTION_CROSS_DOMAIN_DATA: result := 'URLACTION_CROSS_DOMAIN_DATA';
URLACTION_HTML_SUBFRAME_NAVIGATE: result := 'URLACTION_HTML_SUBFRAME_NAVIGATE';
URLACTION_HTML_USERDATA_SAVE: result := 'URLACTION_HTML_USERDATA_SAVE';
URLACTION_COOKIES: result := 'URLACTION_COOKIES';
URLACTION_COOKIES_SESSION: result := 'URLACTION_COOKIES_SESSION';
URLACTION_SCRIPT_PASTE: result := 'URLACTION_SCRIPT_PASTE';
URLACTION_SCRIPT_RUN: result := 'URLACTION_SCRIPT_RUN';
URLACTION_SCRIPT_JAVA_USE: result := 'URLACTION_SCRIPT_JAVA_USE';
URLACTION_SCRIPT_SAFE_ACTIVEX: result := 'URLACTION_SCRIPT_SAFE_ACTIVEX';
URLACTION_HTML_SUBMIT_FORMS: result := 'URLACTION_HTML_SUBMIT_FORMS';
URLACTION_HTML_SUBMIT_FORMS_FROM: result := 'URLACTION_HTML_SUBMIT_FORMS_FROM';
URLACTION_HTML_SUBMIT_FORMS_TO: result := 'URLACTION_HTML_SUBMIT_FORMS_TO';
URLACTION_HTML_FONT_DOWNLOAD: result := 'URLACTION_HTML_FONT_DOWNLOAD';
URLACTION_HTML_JAVA_RUN: result := 'URLACTION_HTML_JAVA_RUN';
URLACTION_SHELL_INSTALL_DTITEMS: result := 'URLACTION_SHELL_INSTALL_DTITEMS';
URLACTION_SHELL_MOVE_OR_COPY: result := 'URLACTION_SHELL_MOVE_OR_COPY';
URLACTION_SHELL_FILE_DOWNLOAD: result := 'URLACTION_SHELL_FILE_DOWNLOAD';
URLACTION_SHELL_VERB: result := 'URLACTION_SHELL_VERB';
URLACTION_SHELL_WEBVIEW_VERB: result := 'URLACTION_SHELL_WEBVIEW_VERB';
URLACTION_CREDENTIALS_USE: result := 'URLACTION_CREDENTIALS_USE';
URLACTION_CLIENT_CERT_PROMPT: result := 'URLACTION_CLIENT_CERT_PROMPT';
URLACTION_AUTHENTICATE_CLIENT: result := 'URLACTION_AU:TICATE_CLIENT';
URLACTION_JAVA_PERMISSIONS: result := 'URLACTION_JAVA_PERMISSIONS';
URLACTION_INFODELIVERY_NO_ADDING_CHANNELS: result := 'URLACTION_INFODELIVERY_NO_ADDING_CHANNELS';
URLACTION_INFODELIVERY_NO_EDITING_CHANNELS: result := 'URLACTION_INFODELIVERY_NO_EDITING_CHANNELS';
URLACTION_INFODELIVERY_NO_REMOVING_CHANNELS: result := 'URLACTION_INFODELIVERY_NO_REMOVING_CHANNELS';
URLACTION_INFODELIVERY_NO_ADDING_SUBSCRIPTIONS: result := 'URLACTION_INFODELIVERY_NO_ADDING_SUBSCRIPTIONS';
URLACTION_INFODELIVERY_NO_EDITING_SUBSCRIPTIONS: result := 'URLACTION_INFODELIVERY_NO_EDITING_SUBSCRIPTIONS';
URLACTION_INFODELIVERY_NO_REMOVING_SUBSCRIPTIONS: result := 'URLACTION_INFODELIVERY_NO_REMOVING_SUBSCRIPTIONS';
URLACTION_INFODELIVERY_NO_CHANNEL_LOGGING: result := 'URLACTION_INFODELIVERY_NO_CHANNEL_LOGGING';
URLACTION_CHANNEL_SOFTDIST_PERMISSIONS: result := 'URLACTION_CHANNEL_SOFTDIST_PERMISSIONS';
end;
end;
{ TSecurityManager }
constructor TSecurityManager.Create(Owner: TComponent);
begin
inherited;
FUrlPolicyOptions := TUrlPolicyOptions.Create;
end;
destructor TSecurityManager.Destroy;
begin
FUrlPolicyOptions.Free;
inherited;
end;
function TSecurityManager.GetSecurityId(pwszUrl: LPCWSTR;
pbSecurityId: Pointer; var cbSecurityId: DWORD;
dwReserved: DWORD): HResult;
begin
if Assigned(FGetSecurityID) then
Result := FGetSecurityID(pwszUrl, pbSecurityID, cbSecurityID, dwReserved)
else
Result := INET_E_DEFAULT_ACTION;
end;
function TSecurityManager.GetSecuritySite(
out Site: IInternetSecurityMgrSite): HResult;
begin
if Assigned(FGetSecuritySite) then
Result := FGetSecuritySite(site)
else
Result := INET_E_DEFAULT_ACTION;
end;
function TSecurityManager.GetZoneMappings(dwZone: DWORD;
out enumString: IEnumString; dwFlags: DWORD): HResult;
begin
if Assigned(FGetZoneMappings) then
result := FGetZoneMappings(dwZone, enumString, dwFlags)
else
Result := INET_E_DEFAULT_ACTION;
end;
function TSecurityManager.MapUrlToZone(pwszUrl: LPCWSTR; out dwZone: DWORD;
dwFlags: DWORD): HResult;
begin
if Assigned(FMapUrlToZone) then
Result := FMapUrlToZone(pwszUrl, dwZone, dwFlags)
else
Result := INET_E_DEFAULT_ACTION;
end;
function TSecurityManager.ProcessUrlAction(pwszUrl: LPCWSTR;
dwAction: DWORD; pPolicy: Pointer; cbPolicy: DWORD; pContext: Pointer;
cbContext, dwFlags, dwReserved: DWORD): HResult;
var
dwPolicy: DWORD;
begin
if Assigned(FProcessUrlAction) then
Result := FProcessUrlAction(pwszUrl, dwAction, pPolicy, cbPolicy, pContext, cbContext, dwFlags, dwReserved)
else
begin
Result := S_FALSE;
dwPolicy := URLPOLICY_ALLOW;
if (dwAction <= URLACTION_ACTIVEX_MAX) and (dwAction >= URLACTION_ACTIVEX_MIN)
then
dwPolicy := AllowDisallowValues[Ord(FUrlPolicyOptions.FActiveX)]
else
if ((dwAction <= URLACTION_JAVA_MAX) and (dwAction >= URLACTION_JAVA_MIN)) or
(dwAction = URLACTION_HTML_JAVA_RUN) then
dwPolicy := JavaPolicyValues[Ord(FUrlPolicyOptions.FJavaPermissions)]
else
if ((dwAction = URLACTION_HTML_SUBMIT_FORMS_TO) or (dwAction = URLACTION_HTML_SUBMIT_FORMS_FROM)) then
dwPolicy := AllowDisallowValues[Ord(FUrlPolicyOptions.FSubmitforms)]
else
if (dwAction = URLACTION_CROSS_DOMAIN_DATA) then
dwPolicy := AllowDisallowValues[Ord(FUrlPolicyOptions.FCrossDomainData)]
else
if (dwAction <= URLACTION_SCRIPT_MAX) and (dwAction >= URLACTION_SCRIPT_MIN) then
dwPolicy := AllowDisallowValues[Ord(FUrlPolicyOptions.FScriptOptions)]
else
Result := INET_E_DEFAULT_ACTION;
if (Result = S_FALSE) and (cbPolicy >= SizeOf(DWORD)) then
begin
Dword(ppolicy^) := dwpolicy;
Result := S_OK;
end;
end;
end;
function TSecurityManager.QueryCustomPolicy(pwszUrl: LPCWSTR;
const guidKey: TGUID; out pPolicy: Pointer; out cbPolicy: DWORD;
pContext: Pointer; cbContext, dwReserved: DWORD): HResult;
begin
if Assigned(FQueryCustomPolicy) then
Result := FQueryCustomPolicy(pwszUrl, guidKey, pPolicy, cbPolicy, pContext, cbContext, dwReserved)
else
Result := INET_E_DEFAULT_ACTION;
end;
function TSecurityManager.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
result := inherited Queryinterface(iid, obj);
end;
function TSecurityManager.SetSecuritySite(
Site: IInternetSecurityMgrSite): HResult;
begin
if Assigned(FSetSecuritySite) then
Result := FSetSecuritySite(site)
else
Result := INET_E_DEFAULT_ACTION;
end;
function TSecurityManager.SetZoneMapping(dwZone: DWORD;
lpszPattern: LPCWSTR; dwFlags: DWORD): HResult;
begin
if Assigned(FSetZoneMapping) then
Result := FSetZoneMapping(dwZone, lpszPattern, dwFlags)
else
Result := INET_E_DEFAULT_ACTION;
end;
end.
|
unit uSpDismissionView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxControls, cxGridCustomView, cxGrid,
StdCtrls, Buttons, ExtCtrls, ActnList, FIBDataSet, pFIBDataSet,
cxClasses, FIBDatabase, pFIBDatabase, uActionControl;
type
TfmSpDismissionView = class(TForm)
LocalDatabase: TpFIBDatabase;
LocalReadTransaction: TpFIBTransaction;
LocalWriteTransaction: TpFIBTransaction;
StyleRepository: TcxStyleRepository;
stBackground: TcxStyle;
stContent: TcxStyle;
stContentEven: TcxStyle;
stContentOdd: TcxStyle;
stFilterBox: TcxStyle;
stFooter: TcxStyle;
stGroup: TcxStyle;
stGroupByBox: TcxStyle;
stHeader: TcxStyle;
stInactive: TcxStyle;
stIncSearch: TcxStyle;
stIndicator: TcxStyle;
stPreview: TcxStyle;
stSelection: TcxStyle;
stHotTrack: TcxStyle;
qizzStyle: TcxGridTableViewStyleSheet;
ResultQuery: TpFIBDataSet;
WorkQuery: TpFIBDataSet;
DataSource: TDataSource;
KeyList: TActionList;
OkAction: TAction;
CancelAction: TAction;
AddAction: TAction;
ModifyAction: TAction;
DeleteAction: TAction;
FindPanel: TPanel;
SearchLabel: TLabel;
Label1: TLabel;
SearchNextButton: TSpeedButton;
SearchEdit: TEdit;
OrderGrid: TcxGrid;
OrderGridDBTableView1: TcxGridDBTableView;
OrderGridDBTableView1DBColumn3: TcxGridDBColumn;
OrderGridDBTableView1DBColumn1: TcxGridDBColumn;
OrderGridLevel1: TcxGridLevel;
ResultQueryID_DISMISSION: TFIBIntegerField;
ResultQueryNAME_DISMISSION: TFIBStringField;
ResultQueryKZOT_ST: TFIBStringField;
ActionControl: TqFActionControl;
Panel3: TPanel;
AddItemButton: TSpeedButton;
ModifyItemButton: TSpeedButton;
DeleteItemButton: TSpeedButton;
InfoButton: TSpeedButton;
CancelButton: TSpeedButton;
SelectButton: TSpeedButton;
RefreshButton: TSpeedButton;
RefreshAction: TAction;
CloneAction: TAction;
InfoAction: TAction;
CloneButton: TSpeedButton;
procedure SearchEditChange(Sender: TObject);
procedure SearchNextButtonClick(Sender: TObject);
procedure CancelActionExecute(Sender: TObject);
procedure OkActionExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmSpDismissionView: TfmSpDismissionView;
implementation
{$R *.dfm}
procedure TfmSpDismissionView.SearchEditChange(Sender: TObject);
begin
try
ResultQuery.ExtLocate('NAME_DISMISSION', '%'+SearchEdit.Text+'%', [eloCaseInsensitive, eloWildCards]);
except
end;
end;
procedure TfmSpDismissionView.SearchNextButtonClick(Sender: TObject);
begin
ResultQuery.ExtLocateNext('NAME_DISMISSION', '%'+SearchEdit.Text+'%', [eloCaseInsensitive, eloWildCards]);
end;
procedure TfmSpDismissionView.CancelActionExecute(Sender: TObject);
begin
ModalResult := mrCancel;
if FormStyle = fsMDIChild then
Close;
end;
procedure TfmSpDismissionView.OkActionExecute(Sender: TObject);
begin
if SearchEdit.Focused then SearchNextButtonClick(Sender);
ModalResult := mrOk;
end;
procedure TfmSpDismissionView.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if FormStyle = fsMDIChild then
Action := caFree;
end;
end.
|
unit TurboDocumentHost;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls,
dxDockControl, dxDockPanel,
TurboPhpDocument, Design;
type
TTurboDocumentHostForm = class(TForm)
dxDockingManager1: TdxDockingManager;
DesignDock: TdxDockPanel;
dxDockSite1: TdxDockSite;
dxLayoutDockSite1: TdxLayoutDockSite;
PhpDock: TdxDockPanel;
JavaScriptDock: TdxDockPanel;
PreviewDock: TdxDockPanel;
DebugDock: TdxDockPanel;
dxTabContainerDockSite2: TdxTabContainerDockSite;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FDocument: TTurboPhpDocument;
protected
procedure DesignChange(inSender: TObject);
procedure SetDocument(const Value: TTurboPhpDocument);
public
{ Public declarations }
procedure ActivateDesign;
procedure DeactivateDesign;
procedure LoadDockConfig;
procedure SaveDockConfig;
property Document: TTurboPhpDocument read FDocument write SetDocument;
end;
var
TurboDocumentHostForm: TTurboDocumentHostForm;
implementation
uses
LrUtils, Globals, DesignHost, PhpEdit, JavaScriptEdit, DockingUtils,
Documents;
const
cDockConfig = 'turbodock.cfg';
{$R *.dfm}
procedure TTurboDocumentHostForm.FormCreate(Sender: TObject);
begin
AddForm(DesignHostForm, TDesignHostForm, DesignDock);
AddForm(JavaScriptEditForm, TJavaScriptEditForm, JavaScriptDock);
AddForm(PhpEditForm, TPhpEditForm, PhpDock);
end;
procedure TTurboDocumentHostForm.FormDestroy(Sender: TObject);
begin
//
end;
procedure TTurboDocumentHostForm.LoadDockConfig;
begin
LoadDockLayout(dxDockingManager1, ConfigHome + cDockConfig);
end;
procedure TTurboDocumentHostForm.SaveDockConfig;
begin
SaveDockLayout(dxDockingManager1, ConfigHome + cDockConfig);
end;
procedure TTurboDocumentHostForm.SetDocument(
const Value: TTurboPhpDocument);
begin
FDocument := Value;
if Document <> nil then
begin
DesignHostForm.DesignForm := Document.DesignForm;
Document.DesignForm.OnChange := DesignChange;
BringToFront;
end
else
DesignHostForm.DesignForm := nil;
end;
procedure TTurboDocumentHostForm.ActivateDesign;
begin
DesignHostForm.ActivateDesign;
end;
procedure TTurboDocumentHostForm.DeactivateDesign;
begin
DesignHostForm.DeactivateDesign;
end;
procedure TTurboDocumentHostForm.DesignChange(inSender: TObject);
begin
if (Document <> nil) and not Document.Modified then
begin
Document.Modified := true;
DocumentsForm.UpdateDocumentTabs;
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20160510 - 150223
////////////////////////////////////////////////////////////////////////////////
unit android.drm.DrmStore_ConstraintsColumns;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JDrmStore_ConstraintsColumns = interface;
JDrmStore_ConstraintsColumnsClass = interface(JObjectClass)
['{819812F4-97E6-47A4-B969-6A6C2B155388}']
function _GetEXTENDED_METADATA : JString; cdecl; // A: $19
function _GetLICENSE_AVAILABLE_TIME : JString; cdecl; // A: $19
function _GetLICENSE_EXPIRY_TIME : JString; cdecl; // A: $19
function _GetLICENSE_START_TIME : JString; cdecl; // A: $19
function _GetMAX_REPEAT_COUNT : JString; cdecl; // A: $19
function _GetREMAINING_REPEAT_COUNT : JString; cdecl; // A: $19
property EXTENDED_METADATA : JString read _GetEXTENDED_METADATA; // Ljava/lang/String; A: $19
property LICENSE_AVAILABLE_TIME : JString read _GetLICENSE_AVAILABLE_TIME; // Ljava/lang/String; A: $19
property LICENSE_EXPIRY_TIME : JString read _GetLICENSE_EXPIRY_TIME; // Ljava/lang/String; A: $19
property LICENSE_START_TIME : JString read _GetLICENSE_START_TIME; // Ljava/lang/String; A: $19
property MAX_REPEAT_COUNT : JString read _GetMAX_REPEAT_COUNT; // Ljava/lang/String; A: $19
property REMAINING_REPEAT_COUNT : JString read _GetREMAINING_REPEAT_COUNT; // Ljava/lang/String; A: $19
end;
[JavaSignature('android/drm/DrmStore_ConstraintsColumns')]
JDrmStore_ConstraintsColumns = interface(JObject)
['{3B5F2D79-FDCA-421E-8274-9EA1299251A6}']
end;
TJDrmStore_ConstraintsColumns = class(TJavaGenericImport<JDrmStore_ConstraintsColumnsClass, JDrmStore_ConstraintsColumns>)
end;
const
TJDrmStore_ConstraintsColumnsEXTENDED_METADATA = 'extended_metadata';
TJDrmStore_ConstraintsColumnsLICENSE_AVAILABLE_TIME = 'license_available_time';
TJDrmStore_ConstraintsColumnsLICENSE_EXPIRY_TIME = 'license_expiry_time';
TJDrmStore_ConstraintsColumnsLICENSE_START_TIME = 'license_start_time';
TJDrmStore_ConstraintsColumnsMAX_REPEAT_COUNT = 'max_repeat_count';
TJDrmStore_ConstraintsColumnsREMAINING_REPEAT_COUNT = 'remaining_repeat_count';
implementation
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Nurbs surfaces vector file loading.
}
unit VXS.FileNurbs;
interface
uses
System.Classes,
System.SysUtils,
VXS.VectorFileObjects,
VXS.VectorGeometry,
VXS.VectorLists,
VXS.ApplicationFileIO,
VXS.ParametricSurfaces,
VXS.Utils;
type
TVXNurbsVectorFile = class(TVXVectorFile)
public
class function Capabilities: TVXDataFileCapabilities; override;
procedure LoadFromStream(stream: TStream); override;
end;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------
// ------------------ TVXNurbsVectorFile ------------------
// ------------------
class function TVXNurbsVectorFile.Capabilities: TVXDataFileCapabilities;
begin
Result := [dfcRead];
end;
procedure TVXNurbsVectorFile.LoadFromStream(stream: TStream);
function CleanupLine(const line: String): String;
var
p: Integer;
begin
p := Pos('#', line);
if p > 0 then
Result := LowerCase(Trim(Copy(line, 1, p - 1)))
else
Result := LowerCase(Trim(line));
end;
function ReadSingleArray(sl: TStrings; idx: Integer;
list: TSingleList): Integer;
var
k: Integer;
buf: String;
vals: TStringList;
begin
vals := TStringList.Create;
try
while idx < sl.Count do
begin
buf := CleanupLine(sl[idx]);
if buf = ']' then
Break;
vals.CommaText := buf;
for k := 0 to vals.Count - 1 do
if vals[k] <> '' then
list.Add(VXS.Utils.StrToFloatDef(vals[k], 0));
Inc(idx);
end;
Result := idx;
finally
vals.Free;
end;
end;
function ReadVectorArray(sl: TStrings; idx: Integer;
list: TAffineVectorList): Integer;
var
buf: String;
vals: TStringList;
begin
vals := TStringList.Create;
try
while idx < sl.Count do
begin
buf := CleanupLine(sl[idx]);
if buf = ']' then
Break;
vals.CommaText := buf;
if vals.Count >= 3 then
list.Add(VXS.Utils.StrToFloatDef(vals[0], 0),
VXS.Utils.StrToFloatDef(vals[1], 0),
VXS.Utils.StrToFloatDef(vals[2], 0));
Inc(idx);
end;
Result := idx;
finally
vals.Free;
end;
end;
var
sl, buf: TStringList;
ss: TStringStream;
i, j: Integer;
surface: TMOParametricSurface;
invert: Boolean;
invControlPoints: TAffineVectorList;
begin
ss := TStringStream.Create('');
sl := TStringList.Create;
buf := TStringList.Create;
surface := TMOParametricSurface.CreateOwned(Owner.MeshObjects);
with surface do
begin
Name := 'Nurbs' + IntToStr(Owner.IndexOf(surface));
Basis := psbBSpline;
Renderer := psrOpenVX;
AutoKnots := False;
end;
invert := False;
try
ss.CopyFrom(stream, stream.Size - stream.Position);
sl.Text := ss.DataString;
i := 0;
while i < sl.Count do
begin
buf.CommaText := CleanupLine(sl[i]);
if buf.Count > 1 then
begin
if buf[0] = 'uorder' then
surface.OrderU := StrToIntDef(buf[1], 2)
else if buf[0] = 'vorder' then
surface.OrderV := StrToIntDef(buf[1], 2)
else if buf[0] = 'uknot' then
i := ReadSingleArray(sl, i + 1, surface.KnotsU)
else if buf[0] = 'vknot' then
i := ReadSingleArray(sl, i + 1, surface.KnotsV)
else if buf[0] = 'weight' then
i := ReadSingleArray(sl, i + 1, surface.Weights)
else if buf[0] = 'udimension' then
surface.CountU := StrToIntDef(buf[1], 0)
else if buf[0] = 'vdimension' then
surface.CountV := StrToIntDef(buf[1], 0)
else if buf[0] = 'controlpoint' then
i := ReadVectorArray(sl, i + 1, surface.ControlPoints)
else if buf[0] = 'ccw' then
invert := (buf[1] = 'false');
end;
Inc(i);
end;
if invert then
begin
invControlPoints := TAffineVectorList.Create;
for i := surface.CountV - 1 downto 0 do
for j := 0 to surface.CountU - 1 do
invControlPoints.Add(surface.ControlPoints[i * surface.CountU + j]);
surface.ControlPoints.Assign(invControlPoints);
invControlPoints.Free;
end;
finally
buf.Free;
sl.Free;
ss.Free;
end;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterVectorFileFormat('nurbs', 'Nurbs model files', TVXNurbsVectorFile);
end.
|
unit IconsLib;
{$I NoRTTI.inc}
interface
uses
Windows, System.SysUtils, System.Classes, Graphics, System.ImageList, Vcl.ImgList,
Vcl.BaseImageCollection, Vcl.ImageCollection, Controls, CommCtrl,
{$IFDEF HFS_GIF_IMAGES}
Vcl.Imaging.gifimg,
{$ELSE ~HFS_GIF_IMAGES}
Vcl.Imaging.gifimg,
Vcl.Imaging.pngImage,
{$ENDIF HFS_GIF_IMAGES}
Vcl.VirtualImageList
;
type
TIconsDM = class(TDataModule)
ImgCollection: TImageCollection;
images: TVirtualImageList;
constructor Create(AOwner: TComponent); override;
private
{ Private declarations }
public
{ Public declarations }
systemimages: Timagelist; // system icons
end;
function idx_img2ico(i:integer):integer;
function idx_ico2img(i:integer):integer;
{$IFDEF HFS_GIF_IMAGES}
function stringToGif(s: RawByteString; gif: TgifImage=NIL): TgifImage;
function gif2str(gif:TgifImage): RawByteString;
{$ELSE ~HFS_GIF_IMAGES}
function stringToPNG(const s: RawByteString; png: TpngImage=NIL): TpngImage;
function png2str(png: TPngImage): RawByteString;
{$ENDIF HFS_GIF_IMAGES}
function bmp2str(bmp: Tbitmap): RawByteString;
function pic2str(idx: integer; imgSize: Integer): RawByteString;
function str2pic(const s: RawByteString; imgSize: Integer): integer;
function strGif2pic(const gs: RawByteString; imgSize: Integer): integer;
function getImageIndexForFile(fn:string):integer;
function stringPNG2BMP(const s: RawByteString): TBitmap;
const
ICONMENU_NEW = 1;
ICON_UNIT = 31;
ICON_ROOT = 1;
ICON_LINK = 4;
ICON_FILE = 37;
ICON_FOLDER = 6;
ICON_REAL_FOLDER = 19;
ICON_LOCK = 12;
ICON_EASY = 29;
ICON_EXPERT = 35;
USER_ICON_MASKS_OFS = 10000;
var
IconsDM: TIconsDM;
startingImagesCount: integer;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
uses
AnsiClasses, ansiStrings, WinApi.ShellAPI,
RnQCrypt,
srvVars;
const
ImageSizeSmall = 16;
ImageSizeBig = 32;
var
imagescacheSm: array of RawByteString;
imagescacheBg: array of RawByteString;
sysidx2index: array of record sysidx, idx:integer; end; // maps system imagelist icons to internal imagelist
function Shell_GetImageLists(var hl,hs:Thandle):boolean; stdcall; external 'shell32.dll' index 71;
function getSystemimages():TImageList;
var
hl, hs: Thandle;
begin
result := NIL;
if not Shell_GetImageLists(hl,hs) then exit;
result := Timagelist.Create(NIL);
Result.ColorDepth := cd32Bit;
result.ShareImages := TRUE;
result.handle := hs;
end; // loadSystemimages
constructor TIconsDM.Create(AOwner: TComponent);
begin
Inherited Create(AOwner);
systemimages := getSystemimages();
images.Masked := false;
images.ColorDepth := cd32bit;
end;
function idx_img2ico(i: integer): integer;
begin
if (i < startingImagesCount) or (i >= USER_ICON_MASKS_OFS) then
result := i
else
result := i-startingImagesCount+USER_ICON_MASKS_OFS
end;
function idx_ico2img(i: integer): integer;
begin
if i < USER_ICON_MASKS_OFS then
result := i
else
result := i-USER_ICON_MASKS_OFS+startingImagesCount
end;
{$IFDEF HFS_GIF_IMAGES}
function stringToGif(s: RawByteString; gif: TgifImage=NIL):TgifImage;
var
ss: TAnsiStringStream;
begin
ss := TAnsiStringStream.create(s);
try
if gif = NIL then
gif := TGIFImage.Create();
gif.loadFromStream(ss);
result := gif;
finally ss.free end;
end; // stringToGif
function gif2str(gif: TgifImage): RawByteString;
var
stream: Tbytesstream;
begin
stream:=Tbytesstream.create();
gif.SaveToStream(stream);
setLength(result, stream.size);
move(stream.bytes[0], result[1], stream.size);
stream.free;
end; // gif2str
function bmp2str(bmp: Tbitmap): RawByteString;
var
gif: TGIFImage;
begin
gif:=TGIFImage.Create();
try
gif.ColorReduction:=rmQuantize;
gif.Assign(bmp);
result:=gif2str(gif);
finally gif.free;
end;
end; // bmp2str
function pic2str(idx:integer): RawByteString;
var
ico: Ticon;
gif: TgifImage;
begin
result:='';
if idx < 0 then exit;
idx:=idx_ico2img(idx);
if length(imagescache) <= idx then
setlength(imagescache, idx+1);
result:=imagescache[idx];
if result > '' then exit;
ico:=Ticon.Create;
gif:=TGifImage.Create;
try
IconsDM.images.getIcon(idx, ico);
gif.Assign(ico);
result:=gif2str(gif);
imagescache[idx]:=result;
finally
gif.Free;
ico.free;
end;
end; // pic2str
function str2pic(s: RawByteString):integer;
var
gif: TGIFImage;
begin
for result:=0 to IconsDM.images.count-1 do
if pic2str(result) = s then
exit;
// in case the pic was not found, it automatically adds it to the pool
gif := stringToGif(s);
try
result := IconsDM.images.addMasked(gif.bitmap, gif.Bitmap.TransparentColor);
etags.values['icon.'+intToStr(result)] := MD5PassHS(s);
finally
gif.free
end;
end; // str2pic
{$ELSE ~HFS_GIF_IMAGES}
function stringToPNG(const s: RawByteString; png: TpngImage=NIL): TpngImage;
var
ss: TAnsiStringStream;
begin
ss := TAnsiStringStream.create(s);
try
if png = NIL then
png := TPNGImage.Create();
png.loadFromStream(ss);
result := png;
finally ss.free end;
end; // stringToPNG
function gif2png(const s: RawByteString): RawByteString;
var
gif: TgifImage;
ss: TAnsiStringStream;
bmp: TBitmap;
begin
Result := '';
ss := TAnsiStringStream.create(s);
try
gif := TGIFImage.Create();
bmp := TBitmap.Create;
gif.loadFromStream(ss);
Result := bmp2str(bmp);
finally
ss.free;
gif.Free;
end;
end; // Gif2PNG
function png2str(png: TpngImage): RawByteString;
var
stream: Tbytesstream;
begin
stream := Tbytesstream.create();
png.SaveToStream(stream);
setLength(result, stream.size);
move(stream.bytes[0], result[1], stream.size);
stream.free;
end; // png2str
function bmp2str(bmp: Tbitmap): RawByteString;
const
PixelsQuad = MaxInt div SizeOf(TRGBQuad) - 1;
type
TRGBAArray = Array [0..PixelsQuad - 1] of TRGBQuad;
PRGBAArray = ^TRGBAArray;
var
png: TPNGImage;
RowInOut: PRGBAArray;
RowAlpha: PByteArray;
begin
png := TPNGImage.Create();
try
// png.ColorReduction:=rmQuantize;
png.Assign(bmp);
if bmp.PixelFormat = pf32bit then
begin
PNG.CreateAlpha;
for var Y:=0 to Bmp.Height - 1 do
begin
RowInOut := Bmp.ScanLine[Y];
RowAlpha := PNG.AlphaScanline[Y];
for var X:=0 to Bmp.Width - 1 do
RowAlpha[X] := RowInOut[X].rgbReserved;
end;
end;
result:=png2str(png);
finally png.free;
end;
end; // bmp2str
function pic2str(idx:integer; imgSize: Integer): RawByteString;
var
bmp: TBitmap;
begin
result := '';
if idx < 0 then
exit;
idx := idx_ico2img(idx);
if length(imagescacheSm) <= idx then
begin
setlength(imagescacheSm, idx+1);
setlength(imagescacheBg, idx+1);
end;
if imgSize = ImageSizeSmall then
result := imagescacheSm[idx]
else
if imgSize = ImageSizeBig then
result := imagescacheBg[idx];
if result > '' then
exit;
bmp := nil;
try
bmp := IconsDM.ImgCollection.GetBitmap(idx, imgSize, imgSize);
if Assigned(bmp) then
begin
result := bmp2str(bmp);
if imgSize = ImageSizeSmall then
imagescacheSm[idx] := Result
else
if imgSize = ImageSizeBig then
imagescacheBg[idx] := Result;
end;
finally
if Assigned(bmp) then
bmp.Free;
end;
end; // pic2str
function str2pic(const s: RawByteString; imgSize: Integer):integer;
var
png: TPNGImage;
str: TAnsiStringStream;
i: Integer;
begin
for result:=0 to IconsDM.images.count-1 do
if pic2str(result, imgSize) = s then
exit;
// in case the pic was not found, it automatically adds it to the pool
png := stringToPNG(s);
try
str := TAnsiStringStream.Create(s);
i := IconsDM.images.count;
IconsDM.imgCollection.Add(IntToStr(i), str);
str.free;
IconsDM.images.Add(IntToStr(i), i);
Result := i;
etags.values['icon.'+intToStr(result)] := MD5PassHS(s);
finally
png.free
end;
end; // str2pic
function strGif2pic(const gs: RawByteString; imgSize: Integer):integer;
var
ps: RawByteString;
begin
ps := gif2png(gs);
Result := str2pic(ps, imgSize);
end; // str2pic
{$ENDIF HFS_GIF_IMAGES}
function stringPNG2BMP(const s: RawByteString): TBitmap;
var
ss: TAnsiStringStream;
png: TPNGImage;
begin
Result := NIL;
if s = '' then
Exit(NIL);
ss := TAnsiStringStream.create(s);
png := TPngImage.Create;
try
png.LoadFromStream(ss);
finally
ss.free;
end;
if png.Height > 0 then
begin
result := TBitmap.Create;
png.AssignTo(Result);
end;
end;
procedure ClearAlpha(B: TBitmap);
type
PRGBA = ^TRGBA;
TRGBA = packed record
case Cardinal of
0: (Color: Cardinal);
2: (HiWord, LoWord: Word);
3: (B, G, R, A: Byte);
end;
PRGBAArray = ^TRGBAArray;
TRGBAArray = array[0..0] of TRGBA;
var
I: Integer;
p: Pointer;
begin
{
p := B.Scanline[B.Height - 1];
if p <> NIL then
for I := 0 to B.Width * B.Height - 1 do
PRGBAArray(P)[I].A := 1;
}
for var j := 0 to b.Height -1 do
begin
p := B.Scanline[j];
if p <> NIL then
for i := 0 to B.Width - 1 do
begin
PRGBAArray(P)[I].A := 5;
PRGBAArray(P)[I].r := 222;
// PRGBAArray(P)[I].b := 9;
end;
end;
end;
function getImageIndexForFile(fn:string):integer;
var
newIdx, n: integer;
shfi: TShFileInfo;
sR16, sR32: RawByteString;
bmp: TBitmap;
str: TAnsiStringStream;
// iconX, iconY: Integer;
begin
ZeroMemory(@shfi, SizeOf(TShFileInfo));
// documentation reports shGetFileInfo() to be working with relative paths too,
// but it does not actually work without the expandFileName()
shGetFileInfo( pchar(expandFileName(fn)), 0, shfi, SizeOf(shfi), SHGFI_SYSICONINDEX);
if shfi.iIcon = 0 then
begin
result:=ICON_FILE;
exit;
end;
// as reported by official docs
if shfi.hIcon <> 0 then
destroyIcon(shfi.hIcon);
sR16 := '';
sR32 := '';
// have we already met this sysidx before?
for var i:=0 to length(sysidx2index)-1 do
if sysidx2index[i].sysidx = shfi.iIcon then
begin
result:=sysidx2index[i].idx;
exit;
end;
// found not, let's check deeper: byte comparison.
// we first add the ico to the list, so we can use pic2str()
// 16x16
bmp := TBitmap.Create;
try
bmp.PixelFormat := pf32bit;
bmp.SetSize(ImageSizeSmall, ImageSizeSmall);
ImageList_DrawEx(IconsDM.systemimages.Handle, shfi.iIcon, bmp.Canvas.Handle, 0, 0, ImageSizeSmall, ImageSizeSmall, CLR_NONE, CLR_NONE, ILD_SCALE or ILD_PRESERVEALPHA);
sR16 := bmp2str(bmp);
finally
bmp.Free;
end;
// 32x32
bmp := TBitmap.Create;
try
bmp.PixelFormat := pf32bit;
bmp.SetSize(ImageSizeBig, ImageSizeBig);
ImageList_DrawEx(IconsDM.systemimages.Handle, shfi.iIcon, bmp.Canvas.Handle, 0, 0, ImageSizeBig, ImageSizeBig, CLR_NONE, CLR_NONE, ILD_SCALE or ILD_PRESERVEALPHA);
sR32 := bmp2str(bmp);
// saveFileA(IntToStr(i) + '.png', sR);
// bmp.saveToStream(str);
finally
bmp.Free;
end;
if (sR16 > '') or (sR32 > '') then
begin
newIdx := IconsDM.imgCollection.count;
if sR16 > '' then
begin
str := TAnsiStringStream.Create(sR16);
IconsDM.imgCollection.add(IntToStr(newIdx), str);
str.free;
end;
if sR32 > '' then
begin
str := TAnsiStringStream.Create(sR32);
IconsDM.imgCollection.add(IntToStr(newIdx), str);
str.free;
end;
IconsDM.images.Add(IntToStr(newIdx), newIdx);
// sR:=pic2str(i);
etags.values['icon.'+intToStr(newIdx)] := MD5PassHS(sR16);
end
else
newIdx := -1;
// i:=mainfrm.images.addIcon(ico);
// now we can search if the icon was already there, by byte comparison
n:=0;
if newIdx >= 0 then
while n < length(sysidx2index) do
begin
if pic2str(sysidx2index[n].idx, ImageSizeSmall) = sR16 then
begin // found, delete the duplicate
IconsDM.imgCollection.delete(newIdx);
IconsDM.images.Delete(IntToStr(newIdx));
setlength(imagescacheSm, newIdx);
setlength(imagescacheBg, newIdx);
newIdx := sysidx2index[n].idx;
break;
end;
inc(n);
end;
if (newIdx >= length(imagescacheSm)) then
begin
setLength(imagescacheSm, newIdx+1);
setLength(imagescacheBg, newIdx+1);
end;
if (newIdx>=0) and (imagescacheSm[newIdx] = '') then
imagescacheSm[newIdx] := sR16;
if (newIdx>=0) and (imagescacheBg[newIdx] = '') then
imagescacheBg[newIdx] := sR32;
n:=length(sysidx2index);
setlength(sysidx2index, n+1);
sysidx2index[n].sysidx:=shfi.iIcon;
sysidx2index[n].idx:= newIdx;
result:= newIdx;
end; // getImageIndexForFile
end.
|
unit sgDriverGraphics;
//=============================================================================
// sgDriverGraphics.pas
//=============================================================================
//
// The Graphics driver is responsible for acting as the interface between driver
// code and swingame code. Swingame code uses the graphics driver to access the
// current active driver.
//
// Changing this driver will probably cause graphics drivers to break.
//
// Notes:
// - Pascal PChar is equivalent to a C-type string
// - Pascal Word is equivalent to a Uint16
// - Pascal LongWord is equivalent to a Uint32
// - Pascal SmallInt is equivalent to Sint16
//
//=============================================================================
interface
uses sgTypes, sgBackendTypes, sgDriverSDL2Types;
function RGBAColor(r, g, b, a: Byte) : Color;
procedure ColorComponents(c : Color; var r, g, b, a : Byte);
function GetPixel (src: psg_drawing_surface; x, y: Single) : Color;
procedure FillTriangle(clr: Color; x1, y1, x2, y2, x3, y3: Single; const opts : DrawingOptions);
procedure DrawTriangle(clr: Color; x1, y1, x2, y2, x3, y3: Single; const opts : DrawingOptions);
procedure FillCircle(clr: Color; xc, yc, radius: Single; const opts : DrawingOptions);
procedure DrawCircle(clr: Color; xc, yc, radius: Single; const opts : DrawingOptions);
procedure FillEllipse (clr: Color; x, y, width, height: Single; const opts : DrawingOptions);
procedure DrawEllipse (clr: Color; x, y, width, height: Single; const opts : DrawingOptions);
procedure FillRectangle (clr : Color; rect : Rectangle; const opts : DrawingOptions);
procedure DrawRectangle (clr : Color; rect : Rectangle; const opts : DrawingOptions);
procedure DrawLine(clr : Color; x1, y1, x2, y2 : Single; const opts : DrawingOptions);
procedure DrawPixel(clr : Color; x, y : Single; const opts: DrawingOptions);
procedure DrawQuad(clr : Color; const q: Quad; const opts: DrawingOptions); overload;
procedure FillQuad(clr : Color; const q: Quad; const opts: DrawingOptions); overload;
procedure SetClipRectangle(dest : psg_drawing_surface; rect : Rectangle);
procedure ResetClip(dest : psg_drawing_surface);
function OpenWindow(const caption : String; screenWidth, screenHeight : LongInt): WindowPtr;
procedure CloseWindow(var wind: WindowPtr);
procedure ResizeWindow(wind: WindowPtr; newWidth, newHeight : LongInt);
procedure RefreshWindow(window : WindowPtr);
procedure SetVideoModeFullScreen(wind: WindowPtr);
procedure SetVideoModeNoFrame(wind: WindowPtr);
function AvailableResolutions(): ResolutionArray;
implementation
uses sgShared, sgGeometry;
function RGBAColor(r, g, b, a: Byte) : Color;
begin
//TODO: standardise and remove from drivers
result := a shl 24 or r shl 16 or g shl 8 or b ;
end;
procedure ColorComponents(c : Color; var r, g, b, a : Byte);
begin
//TODO: standardise and remove from drivers
a := c and $FF000000 shr 24;
r := c and $00FF0000 shr 16;
g := c and $0000FF00 shr 8;
b := c and $000000FF;
end;
function GetPixel (src: psg_drawing_surface; x, y: Single) : Color;
var
clr: sg_color;
begin
clr := _sg_functions^.graphics.read_pixel(src, Round(x), Round(y));
result := RGBAColor(Round(clr.r * 255), Round(clr.g * 255), Round(clr.b * 255), Round(clr.a * 255));
end;
procedure FillTriangle(clr: Color; x1, y1, x2, y2, x3, y3: Single; const opts : DrawingOptions);
var
pts: array [0..6] of Single;
begin
XYFromOpts(opts, x1, y1);
XYFromOpts(opts, x2, y2);
XYFromOpts(opts, x3, y3);
pts[0] := x1;
pts[1] := y1;
pts[2] := x2;
pts[3] := y2;
pts[4] := x3;
pts[5] := y3;
_sg_functions^.graphics.fill_triangle(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 6);
end;
procedure DrawTriangle(clr: Color; x1, y1, x2, y2, x3, y3: Single; const opts : DrawingOptions);
var
pts: array [0..6] of Single;
begin
XYFromOpts(opts, x1, y1);
XYFromOpts(opts, x2, y2);
XYFromOpts(opts, x3, y3);
pts[0] := x1;
pts[1] := y1;
pts[2] := x2;
pts[3] := y2;
pts[4] := x3;
pts[5] := y3;
_sg_functions^.graphics.draw_triangle(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 6);
end;
procedure FillCircle(clr: Color; xc, yc, radius: Single; const opts : DrawingOptions);
var
pts: array [0..3] of Single;
begin
XYFromOpts(opts, xc, yc);
pts[0] := xc;
pts[1] := yc;
pts[2] := radius;
_sg_functions^.graphics.fill_circle(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 3);
end;
procedure DrawCircle(clr: Color; xc, yc, radius: Single; const opts : DrawingOptions);
var
pts: array [0..3] of Single;
begin
XYFromOpts(opts, xc, yc);
pts[0] := xc;
pts[1] := yc;
pts[2] := radius;
_sg_functions^.graphics.draw_circle(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 3);
end;
procedure FillEllipse (clr: Color; x, y, width, height: Single; const opts : DrawingOptions);
var
pts: array [0..4] of Single;
begin
pts[0] := x;
pts[1] := y;
pts[2] := width;
pts[3] := height;
XYFromOpts(opts, pts[0], pts[1]);
_sg_functions^.graphics.fill_ellipse(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 4);
end;
procedure DrawEllipse (clr: Color; x, y, width, height: Single; const opts : DrawingOptions);
var
pts: array [0..4] of Single;
begin
pts[0] := x;
pts[1] := y;
pts[2] := width;
pts[3] := height;
XYFromOpts(opts, pts[0], pts[1]);
_sg_functions^.graphics.draw_ellipse(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 4);
end;
procedure DrawQuad(clr : Color; const q: Quad; const opts: DrawingOptions); overload;
var
pts: array [0..7] of Single;
i: Integer;
begin
for i := 0 to 3 do
begin
pts[i * 2] := q.points[i].x;
pts[i * 2 + 1] := q.points[i].y;
XYFromOpts(opts, pts[i * 2], pts[i * 2 + 1]);
end;
_sg_functions^.graphics.draw_rect(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 8);
end;
procedure FillQuad(clr : Color; const q: Quad; const opts: DrawingOptions); overload;
var
pts: array [0..7] of Single;
i: Integer;
begin
for i := 0 to 3 do
begin
pts[i * 2] := q.points[i].x;
pts[i * 2 + 1] := q.points[i].y;
XYFromOpts(opts, pts[i * 2], pts[i * 2 + 1]);
end;
_sg_functions^.graphics.fill_rect(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 8);
end;
procedure FillRectangle (clr : Color; rect : Rectangle; const opts : DrawingOptions);
var
pts: array [0..4] of Single;
begin
pts[0] := rect.x;
pts[1] := rect.y;
pts[2] := rect.width;
pts[3] := rect.height;
XYFromOpts(opts, pts[0], pts[1]);
_sg_functions^.graphics.fill_aabb_rect(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 4);
end;
procedure DrawRectangle (clr : Color; rect : Rectangle; const opts : DrawingOptions);
var
pts: array [0..4] of Single;
begin
pts[0] := rect.x;
pts[1] := rect.y;
pts[2] := rect.width;
pts[3] := rect.height;
XYFromOpts(opts, pts[0], pts[1]);
_sg_functions^.graphics.draw_aabb_rect(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 4);
end;
procedure DrawLine(clr : Color; x1, y1, x2, y2 : Single; const opts : DrawingOptions);
var
pts: array [0..5] of Single;
begin
pts[0] := x1;
pts[1] := y1;
pts[2] := x2;
pts[3] := y2;
pts[4] := opts.lineWidth;
XYFromOpts(opts, pts[0], pts[1]);
XYFromOpts(opts, pts[2], pts[3]);
_sg_functions^.graphics.draw_line(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 5);
end;
procedure DrawPixel(clr : Color; x, y : Single; const opts: DrawingOptions);
var
pts: array [0..2] of Single;
begin
pts[0] := x;
pts[1] := y;
XYFromOpts(opts, pts[0], pts[1]);
_sg_functions^.graphics.draw_pixel(ToSurfacePtr(opts.dest), _ToSGColor(clr), @pts[0], 2);
end;
procedure SetClipRectangle(dest : psg_drawing_surface; rect : Rectangle);
var
pts: array [0..4] of Single;
begin
pts[0] := rect.x;
pts[1] := rect.y;
pts[2] := rect.width;
pts[3] := rect.height;
_sg_functions^.graphics.set_clip_rect(dest, @pts[0], 4);
end;
procedure ResetClip(dest : psg_drawing_surface);
begin
_sg_functions^.graphics.clear_clip_rect(dest);
end;
procedure SetVideoModeFullScreen(wind: WindowPtr);
var
val: Longint = 0;
begin
wind^.fullscreen := not wind^.fullscreen;
if wind^.fullscreen then val := -1;
_sg_functions^.graphics.show_fullscreen(@wind^.image.surface, val);
end;
procedure SetVideoModeNoFrame(wind: WindowPtr);
var
val: Longint = 0;
begin
wind^.border := not wind^.border;
if wind^.border then val := -1;
_sg_functions^.graphics.show_border(@wind^.image.surface, val);
end;
function OpenWindow(const caption : String; screenWidth, screenHeight : LongInt): WindowPtr;
var
clr: sg_color;
begin
New(result);
result^.id := WINDOW_PTR;
result^.caption := caption;
result^.image.surface := _sg_functions^.graphics.open_window(PChar(caption), screenWidth, screenHeight);
SetLength(result^.image.clipStack, 0);
_sg_functions^.input.window_position(@result^.image.surface, @result^.x, @result^.y);
result^.open := true;
result^.fullscreen := false;
result^.border := true;
result^.eventData.close_requested := 0;
result^.eventData.has_focus := 0;
result^.eventData.mouse_over := 0;
result^.eventData.shown := -1;
result^.screenRect := RectangleFrom(0,0,screenWidth, screenHeight);
result^.tempString := '';
result^.maxStringLen := 0;
result^.textBitmap := nil;
result^.cursorBitmap := nil;
result^.font := nil;
result^.foreColor := RGBAColor(0, 0, 0, 255);
result^.backgroundColor := RGBAColor(255, 255, 255, 255);
result^.area := RectangleFrom(0,0,0,0);
result^.readingString := false;
result^.textCancelled := false;
clr := _ToSGColor(RGBAColor(255,255,255,255));
_sg_functions^.graphics.clear_drawing_surface(@result^.image.surface, clr);
clr := _ToSGColor(RGBAColor(128,128,128,255));
_sg_functions^.text.draw_text( @result^.image.surface, nil, screenWidth div 2 - 60, screenHeight div 2, 'Getting ready to make a Splash!', clr);
RefreshWindow(result);
end;
procedure CloseWindow(var wind: WindowPtr);
begin
_sg_functions^.graphics.close_drawing_surface(@wind^.image.surface);
wind^.id := NONE_PTR;
Dispose(wind);
wind := nil;
end;
procedure ResizeWindow(wind: WindowPtr; newWidth, newHeight : LongInt);
begin
_sg_functions^.graphics.resize(@wind^.image.surface, newWidth, newHeight);
wind^.screenRect := RectangleFrom(0, 0, newWidth, newHeight);
end;
procedure RefreshWindow(window : WindowPtr);
begin
_sg_functions^.graphics.refresh_window(@window^.image.surface);
end;
function AvailableResolutions(): ResolutionArray;
var
sysData: ^sg_system_data;
begin
sysData := _sg_functions^.read_system_data();
SetLength(result, 0);
if sysData^.num_displays > 0 then
begin
// Just read display 0
// TODO: think about how to handle multiple displays
// TODO: add in other possible modes
// TODO: check why refresh reate is always 0
SetLength(result, 1);
result[0].width := sysData^.displays^.width;
result[0].height := sysData^.displays^.height;
result[0].format := sysData^.displays^.format;
result[0].refreshRate := sysData^.displays^.refresh_rate;
end;
end;
end.
|
unit addInterlocutorForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Ani, FMX.Layouts, FMX.Gestures,
FMX.StdCtrls, FMX.Controls.Presentation, FMX.Graphics, FMX.Media,
Data.Bind.Components, Data.Bind.ObjectScope, REST.Client,
REST.Authenticator.Simple, FMX.ExtCtrls, FMX.ListView.Types,
FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView,
System.Math.Vectors, FMX.Controls3D, FMX.Objects3D, FMX.MultiView,
FMX.TabControl, FMX.Edit, FMX.Objects, FMX.ScrollBox, FMX.Memo,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, XMLIntf, XMLDoc;
type
TForm2 = class(TForm)
StyleBook1: TStyleBook;
ToolbarHolder: TLayout;
ToolbarPopup: TPopup;
ToolbarPopupAnimation: TFloatAnimation;
ToolBar1: TToolBar;
ToolbarApplyButton: TButton;
ToolbarCloseButton: TButton;
ToolbarAddButton: TButton;
Label10: TLabel;
addIntelocutorEdit: TEdit;
addIntelocutorBtn: TButton;
Rectangle1: TRectangle;
Rectangle15: TRectangle;
procedure addIntelocutorBtnClick(Sender: TObject);
private
FGestureOrigin: TPointF;
FGestureInProgress: Boolean;
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.fmx}
uses MainForm;
procedure TForm2.addIntelocutorBtnClick(Sender: TObject);
var Doc: IXMLDocument;
begin
Doc := TXMLDocument.Create(nil);
Doc.Active := True;
with Doc do
begin
with AddChild ('Data') do
begin
ChildValues ['Event'] := 'AddInterlocutor';
ChildValues ['Token'] := Form1.myUser.Token;
with AddChild ('Interlocutor') do
begin
ChildValues ['Email'] := addIntelocutorEdit.Text;
end;
end;
end;
Form1.TCP.Socket.WriteLn(Doc.XML[0]);
end;
end.
|
unit EST0002P.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, PesquisaBase.View, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Silver, cxControls, cxContainer,
cxEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator,
cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxClasses, cxTextEdit, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
dxGDIPlusClasses, Vcl.ExtCtrls, cxLabel, Vcl.StdCtrls, cxButtons, Base.View.Interf,
TESTORCAMENTO.Entidade.Model, ormbr.container.DataSet.interfaces,
ormbr.container.fdmemtable, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinMetropolisDark, dxSkinVisualStudio2013Dark, dxSkinBlack, dxSkinSilver;
type
TFEST0002PView = class(TFPesquisaView, IBasePesquisaView)
FdDadosCODIGO: TStringField;
FdDadosIDORCAMENTO: TIntegerField;
FdDadosDESCRICAO: TStringField;
FdDadosDATA_CADASTRO: TDateTimeField;
VwDadosIDORCAMENTO: TcxGridDBColumn;
VwDadosDESCRICAO: TcxGridDBColumn;
VwDadosDATA_CADASTRO: TcxGridDBColumn;
BtExportar: TcxButton;
BtEnviar: TcxButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtNovoClick(Sender: TObject);
procedure BtAlterarClick(Sender: TObject);
procedure BtConsultarClick(Sender: TObject);
procedure BtExcluirClick(Sender: TObject);
procedure BtDuplicarClick(Sender: TObject);
procedure BtExportarClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
FContainer: IContainerDataSet<TTESTORCAMENTO>;
procedure listarRegistros;
public
{ Public declarations }
class function New: IBasePesquisaView;
function incluirRegistro: IBasePesquisaView;
function alterarRegistro: IBasePesquisaView;
function consultarRegistro: IBasePesquisaView;
function excluirRegistro: IBasePesquisaView;
function duplicarRegistro: IBasePesquisaView;
procedure &executar;
end;
var
FEST0002PView: TFEST0002PView;
implementation
{$R *.dfm}
uses FacadeView, Tipos.Controller.Interf, FacadeController;
{ TFEST0002PView }
function TFEST0002PView.alterarRegistro: IBasePesquisaView;
begin
inherited;
Result := Self;
TFacadeView.New
.ModulosFacadeView
.EstoqueFactoryView
.exibirTelaCadastro(tcOrcamento)
.operacao(FOperacao)
.registroSelecionado(FdDadosCODIGO.AsString)
.executar;
end;
procedure TFEST0002PView.BtAlterarClick(Sender: TObject);
begin
inherited;
alterarRegistro;
listarRegistros;
end;
procedure TFEST0002PView.BtConsultarClick(Sender: TObject);
begin
inherited;
consultarRegistro;
listarRegistros;
end;
procedure TFEST0002PView.BtDuplicarClick(Sender: TObject);
begin
inherited;
duplicarRegistro;
listarRegistros;
end;
procedure TFEST0002PView.BtExcluirClick(Sender: TObject);
begin
inherited;
excluirRegistro;
listarRegistros;
end;
procedure TFEST0002PView.BtExportarClick(Sender: TObject);
begin
inherited;
TFacadeController.New
.modulosFacadeController
.estoqueFactoryController
.exportarOrcamento
.codigoOrcamento(FdDadosCODIGO.AsString)
.carregarItens
.exportar;
end;
procedure TFEST0002PView.BtNovoClick(Sender: TObject);
begin
inherited;
incluirRegistro;
listarRegistros;
end;
function TFEST0002PView.consultarRegistro: IBasePesquisaView;
begin
inherited;
Result := Self;
TFacadeView.New
.ModulosFacadeView
.EstoqueFactoryView
.exibirTelaCadastro(tcOrcamento)
.operacao(FOperacao)
.registroSelecionado(FdDadosCODIGO.AsString)
.executar;
end;
function TFEST0002PView.duplicarRegistro: IBasePesquisaView;
begin
inherited;
Result := Self;
TFacadeView.New
.ModulosFacadeView
.EstoqueFactoryView
.exibirTelaCadastro(tcOrcamento)
.operacao(FOperacao)
.registroSelecionado(FdDadosCODIGO.AsString)
.executar;
end;
function TFEST0002PView.excluirRegistro: IBasePesquisaView;
begin
inherited;
Result := Self;
TFacadeView.New
.ModulosFacadeView
.EstoqueFactoryView
.exibirTelaCadastro(tcOrcamento)
.operacao(FOperacao)
.registroSelecionado(FdDadosCODIGO.AsString)
.executar;
end;
procedure TFEST0002PView.executar;
begin
Show;
end;
procedure TFEST0002PView.FormCreate(Sender: TObject);
begin
inherited;
FContainer := TContainerFDMemTable<TTESTORCAMENTO>.Create(FConexao, FdDados);
end;
procedure TFEST0002PView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
inherited;
case Key of
VK_F5:
begin
incluirRegistro;
listarRegistros;
end;
VK_F6:
begin
alterarRegistro;
listarRegistros;
end;
VK_F7:
begin
consultarRegistro;
listarRegistros;
end;
VK_F8:
begin
excluirRegistro;
listarRegistros;
end;
VK_F9:
begin
duplicarRegistro;
listarRegistros;
end;
end;
end;
procedure TFEST0002PView.FormShow(Sender: TObject);
begin
inherited;
FCampoOrdem := 'DATA_CADASTRO desc';
listarRegistros;
end;
function TFEST0002PView.incluirRegistro: IBasePesquisaView;
begin
inherited;
Result := Self;
TFacadeView.New
.ModulosFacadeView
.EstoqueFactoryView
.exibirTelaCadastro(tcOrcamento)
.operacao(FOperacao)
.executar;
end;
procedure TFEST0002PView.listarRegistros;
begin
FContainer.OpenWhere('', FCampoOrdem);
controlaBotoesAtivos;
end;
class function TFEST0002PView.New: IBasePesquisaView;
begin
Result := Self.Create(nil);
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: SVGInterfaces
Author: PyScripter
Purpose: Inteface-based access to Svg parsing and drawing
History:
-----------------------------------------------------------------------------}
unit SVGInterfaces;
interface
Uses
Winapi.Windows,
System.Types,
System.UITypes,
System.SysUtils,
System.Classes;
const
SVG_INHERIT_COLOR = TColors.SysDefault;
SVG_NONE_COLOR = TColors.SysNone;
type
// Abstraction of an SVG document
ISVG = interface
['{70F71B0C-95FA-4D2D-84F6-481BD871B20B}']
// property access methods
function GetWidth: Single;
function GetHeight: Single;
function GetOpacity: Single;
procedure SetOpacity(const Opacity: Single);
function GetGrayScale: Boolean;
procedure SetGrayScale(const IsGrayScale: Boolean);
function GetFixedColor: TColor;
procedure SetFixedColor(const Color: TColor);
function GetSource: string;
procedure SetSource(const ASource: string);
// procedures and functions
function IsEmpty: Boolean;
procedure Clear;
procedure SaveToStream(Stream: TStream);
procedure SaveToFile(const FileName: string);
procedure LoadFromStream(Stream: TStream);
procedure LoadFromFile(const FileName: string);
procedure PaintTo(DC: HDC; R: TRectF; KeepAspectRatio: Boolean = True);
// properties
property Width: Single read GetWidth;
property Height: Single read GetHeight;
property Opacity: Single read GetOpacity write SetOpacity;
property GrayScale: Boolean read GetGrayScale write SetGrayScale;
property FixedColor: TColor read GetFixedColor write SetFixedColor;
property Source: string read GetSource write SetSource;
end;
// Factory type
ISVGFactory = interface
['{D81A7410-F0DB-457E-BA9D-480A335A1337}']
// Factory method
function NewSvg: ISVG;
end;
function GlobalSVGFactory: ISVGFactory;
procedure SetGlobalSVGFactory(const SVGFactory : ISVGFactory);
implementation
//{$INCLUDE SVGIconImageList.inc}
Uses
PasSVGFactory;
Var
FGlobalSVGFactory: ISVGFactory;
function GlobalSVGFactory: ISVGFactory;
begin
if not Assigned(FGlobalSVGFactory) then
begin
FGlobalSVGFactory := GetPasSVGFactory;
end;
Result := FGlobalSVGFactory;
end;
procedure SetGlobalSVGFactory(const SVGFactory : ISVGFactory);
begin
FGlobalSVGFactory := SVGFactory;
end;
end.
|
unit MainFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TMainForm = class(TForm)
btnHash: TButton;
edtHash: TEdit;
memSrc: TMemo;
pnlBottom: TPanel;
rbMD4: TRadioButton;
rbMD5: TRadioButton;
rbSHA1: TRadioButton;
rbSHA256: TRadioButton;
rbSHA512: TRadioButton;
procedure btnHashClick(Sender: TObject);
private
function HashData(const AData: TBytes): string;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
OpenSSL.Core, OpenSSL.HashUtils;
{ TMainForm }
procedure TMainForm.btnHashClick(Sender: TObject);
var
D: TBytes;
begin
D := TEncoding.Default.GetBytes(memSrc.Text);
edtHash.Text := HashData(D);
end;
function TMainForm.HashData(const AData: TBytes): string;
var
R: TBytes;
begin
if rbMD4.Checked then
R := TMD4.Execute(AData)
else if rbMD5.Checked then
R := TMD5.Execute(AData)
else if rbSHA1.Checked then
R := TSHA1.Execute(AData)
else if rbSHA256.Checked then
R := TSHA256.Execute(AData)
else if rbSHA512.Checked then
R := TSHA512.Execute(AData)
else begin
R := nil;
Assert(False);
end;
Result := BytesToHex(R);
end;
end.
|
unit uSelfDeleteAction;
interface
uses
System.SysUtils,
System.Classes,
Winapi.Windows,
uMemory,
uActions,
uShellUtils,
uInstallUtils;
const
InstallRemoveSelfPoints = 512 * 1024;
type
TSelfDeleteActions = class(TInstallAction)
public
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
implementation
{ TSelfDeleteActions }
function TSelfDeleteActions.CalculateTotalPoints: Int64;
begin
Result := InstallRemoveSelfPoints;
end;
procedure TSelfDeleteActions.Execute(Callback: TActionCallback);
var
Terminate: Boolean;
ExeCommandsName: string;
MS: TMemoryStream;
FS: TFileStream;
Pi: TProcessInformation;
Si: TStartupInfo;
begin
inherited;
ExeCommandsName := GetTempFileName;
MS := TMemoryStream.Create;
try
GetRCDATAResourceStream('COMMANDS', MS);
MS.Seek(0, soFromBeginning);
FS := TFileStream.Create(ExeCommandsName, fmCreate);
try
FS.CopyFrom(MS, MS.Size);
finally
F(FS);
end;
finally
F(MS);
end;
FillChar(Pi, SizeOf(Pi), #0);
FillChar(Si, SizeOf(Si), #0);
Si.cb := SizeOf(Si);
CreateProcess(nil, PChar(Format('"%s" /delete "%s" /wait 100000 /pid %d /withdirectory', [ExeCommandsName, ParamStr(0), GetCurrentProcessId])),
nil, nil, FALSE, NORMAL_PRIORITY_CLASS, nil, nil, Si, Pi);
MoveFileEx(PChar(ExeCommandsName), nil, MOVEFILE_DELAY_UNTIL_REBOOT);
Callback(Self, InstallRemoveSelfPoints, InstallRemoveSelfPoints, Terminate);
end;
end.
|
unit Level_1_1.Entities;
interface
type
TSpawnFlag = (sfCopyPosition);
TSpawnFlags = set of TSpawnFlag;
TBehaviorFlag = (bfIgnoreCollision, bfCameraFollows, bfCameraCenters, bfAlwaysUpdate);
TBehaviorFlags = set of TBehaviorFlag;
TEntity = record
Active: Integer;
X: Single;
Y: Single;
Input: Boolean;
Team: Integer;
Live: Integer;
LiveTime: Integer;
Sprite: Integer;
Frames: Integer;
Orientation: Integer;
NoDirection: Boolean;
Vel_X: Single;
Vel_Y: Single;
BounceX: Single;
BounceY: Single;
Gravity: Single;
LeftBlocked: Integer;
RightBlocked: Integer;
UpBlocked: Integer;
DownBlocked: Integer;
InAirTimer: Integer;
bbWidth: Integer;
bbHeight: Integer;
DamageLeft: Integer;
DamageRight: Integer;
DamageTop: Integer;
DamageBottom: Integer;
VulnerableLeft: Integer;
VulnerableRight: Integer;
VulnerableTop: Integer;
VulnerableBottom: Integer;
ReplaceOnDead: Integer;
ReplaceOnTimeOut: Integer;
SpawnFlags: TSpawnFlags;
BehaviorFlags: TBehaviorFlags;
LastCollider: Integer;
LastColliderTime: Integer;
end;
const
CFirstEntity = 0;
CLastEntity = 112;
CGameOverScreen = CLastEntity;
var
GEntity: array[CFirstEntity..CLastEntity] of TEntity =
(
//Dummy enemie the StartScreen collides with and kills it
(
Active: 1;
X: 3256;
Y: 400;
Live: 1;
Sprite: 0;
bbWidth: 64;
bbHeight: 8;
DamageBottom: 1;
VulnerableBottom: 1;
),
//StartScreen which is replaced by Mario on death
(
Active: 1;
X: 3256;
Y: 420;
Input: True;
Team: 1;
Live: 1;
Sprite: 11;
Frames: 1;
NoDirection: True;
Gravity: 1;
bbWidth: 8;
bbHeight: 8;
DamageTop: 1;
VulnerableTop: 1;
ReplaceOnDead: 1;
BehaviorFlags: [bfCameraCenters];
),
(
X: 40;
Y: 208;
{$i Mario.ent}
),
//First Blockgroup
// ?
//
//
//
// ? #?#?#
//
//
//
////////////////////
(
Active: 1;
X: 264;
Y: 160;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 264;
Y: 160;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 328;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 344;
Y: 160;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 344;
Y: 160;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 360;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 376;
Y: 160;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 376;
Y: 160;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 392;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 360;
Y: 96;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 360;
Y: 96;
{$i CoinBlock.ent}
),
//Endof first Blockgroup
//Second Blockgroup
// ######## ###?
//
//
//
//#?# #
//
//
//
//////////////////////////
(
Active: 1;
X: 1240;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 1256;
Y: 160;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 1256;
Y: 160;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 1272;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 1288;
Y: 96;
{$i Block.ent}
),
//
(
Active: 1;
X: 1304;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1320;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1336;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1352;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1368;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1384;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1400;
Y: 96;
{$i Block.ent}
),
//
(
Active: 1;
X: 1464;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1480;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1496;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1512;
Y: 96;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 1512;
Y: 96;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 1512;
Y: 160;
{$i Block.ent}
),
//end of second BlockGroup
//third Blockgroud
// ?
//
//
//
//## ? ? ?
//
//
//
//////////////////////////
(
Active: 1;
X: 1608;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 1624;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 1704;
Y: 160;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 1704;
Y: 160;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 1752;
Y: 160;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 1752;
Y: 160;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 1752;
Y: 96;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 1752;
Y: 96;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 1800;
Y: 160;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 1800;
Y: 160;
{$i CoinBlock.ent}
),
//end of third blockgroup
//fourth blockgroup
// ### #??#
//
//
//
//# ##
//
//
//
//////////////////////////
(
Active: 1;
X: 1896;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 1944;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1960;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 1976;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 2056;
Y: 96;
{$i Block.ent}
),
(
Active: 1;
X: 2072;
Y: 96;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 2072;
Y: 96;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 2088;
Y: 96;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 2088;
Y: 96;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 2072;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 2088;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 2104;
Y: 96;
{$i Block.ent}
),
//end of fourth blockgroup
//fifth blockgroup
//
//
//
//
//##?#
//
//
//
//////////////////////////
(
Active: 1;
X: 2696;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 2712;
Y: 160;
{$i Block.ent}
),
(
Active: 1;
X: 2728;
Y: 160;
{$i ItemBlockEmpty.ent}
),
(
Active: 1;
X: 2728;
Y: 160;
{$i CoinBlock.ent}
),
(
Active: 1;
X: 2744;
Y: 160;
{$i Block.ent}
),
//end of fifth blockgroup
//enemies of first blockgroup
(
Active: 1;
X: 360;
Y: 208;
{$i Gumba.ent}
),
//enemies in first pipe section
(
Active: 1;
X: 680;
Y: 208;
{$i Gumba.ent}
),
//enemies in second pipe section
(
Active: 1;
X: 824;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 856;
Y: 208;
{$i Gumba.ent}
),
//enemies of second blockgroup
(
Active: 1;
X: 1288;
Y: 80;
{$i Gumba.ent}
),
(
Active: 1;
X: 1320;
Y: 80;
{$i Gumba.ent}
),
(
Active: 1;
X: 1560;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 1592;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 1752;
Y: 204;
{$i Koopa.ent}
),
//enemies of fourth blockgroup
(
Active: 1;
X: 1896;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 1928;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 2008;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 2040;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 2088;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 2120;
Y: 208;
{$i Gumba.ent}
),
//enemies of fifth blockgroup
(
Active: 1;
X: 2808;
Y: 208;
{$i Gumba.ent}
),
(
Active: 1;
X: 2840;
Y: 208;
{$i Gumba.ent}
),
//FinishBlock
//Invisible and put on the ground so it triggers when Mario walks over
(
Active: 1;
X: 3272;
Y: 217;
Live: 1;
Sprite: 13;
bbWidth: 4;
bbHeight: 4;
VulnerableLeft: 1;
VulnerableRight: 1;
VulnerableTop: 1;
VulnerableBottom: 1;
ReplaceOnDead: 1;
BehaviorFlags: [bfIgnoreCollision];
),
//FinishScreen
(
Live: 1;
Sprite: 12;
Frames: 1;
SpawnFlags: [sfCopyPosition];
BehaviorFlags: [bfIgnoreCollision, bfCameraCenters];
),
//GameOverScreen
(
Live: 1;
Sprite: 10;
Frames: 1;
BehaviorFlags: [bfIgnoreCollision, bfCameraCenters, bfAlwaysUpdate];
)
);
implementation
end.
|
unit trl_ilog;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
ILog = interface
['{5F619DCC-AC09-4617-B9F5-7789E36FA39C}']
procedure DebugLn(const s: string = ''); overload;
procedure DebugLn(const S: String; Args: array of const); overload;
procedure DebugLnEnter(const s: string = ''); overload;
procedure DebugLnEnter(s: string; Args: array of const); overload;
procedure DebugLnExit(const s: string = ''); overload;
procedure DebugLnExit(s: string; Args: array of const); overload;
end;
implementation
end.
|
PROGRAM wildcard;
uses Crt, Timer;
VAR
comps : LONGINT;
(* Compares two char
Returns true if chars equal *)
FUNCTION EQ(c1,c2 : CHAR) : BOOLEAN;
BEGIN
comps := comps + 1;
IF c1 = '?' THEN EQ := TRUE
ELSE EQ := c1 = c2;
END;
(* Check for a char in a string
recursive
Returns true if char is in the string *)
FUNCTION Matching(p : CHAR; s : STRING; VAR i : INTEGER) : Boolean;
BEGIN
IF s <> '' THEN
BEGIN
i := i + 1;
IF EQ(p, s[1]) THEN Matching := TRUE
ELSE Matching := Matching(p, Copy(s,2,Length(s)), i);
END
ELSE
Matching := FALSE;
END;
(* BruteForce Left To Right One Loop
with recursive matching *)
Procedure BruteForceLR1L(s,p : STRING; Var pos1, pos2 : INTEGER);
VAR
sLen, pLen, i, j, iterations, qcount : INTEGER;
found : Boolean;
BEGIN
sLen := Length(s);
pLen := Length(p);
iterations := 0;
qcount := 0;
i := 1;
j := 1;
REPEAT
IF p[j] = '?' THEN BEGIN
i := i + 1;
j := j + 1;
qcount := qcount + 1;
END
ELSE IF p[j] = '*' THEN BEGIN
WHILE (j < pLen) AND ((p[j] = '*') OR (p[j] = '?')) DO
BEGIN
IF p[j] = '*' THEN j := j + 1
ELSE IF p[j] = '?' THEN BEGIN
i := i + 1;
j := j + 1;
qcount := qcount + 1;
END;
END;
IF p[j] = '*' THEN
BEGIN
iterations := sLen - i;
i := sLen + 1;
j := pLen + 1;
END
ELSE BEGIN
IF NOT Matching(p[j], Copy(s,i,sLen), iterations) THEN
BEGIN
i := sLen + 1;
break;
END
ELSE
BEGIN
i := i + iterations;
j := j + 1;
END;
END;
END
ELSE IF EQ(s[i], p[j]) THEN BEGIN
i := i + 1;
j := j + 1;
qcount := qcount + 1;
END
ELSE BEGIN
i := i -j + 1 + 1;
j := 1;
END;
UNTIl (i > sLen) OR (j > pLen);
IF (iterations <> 0) AND (j > pLen) THEN BEGIN
pos1 := i - iterations - qcount;
pos2 := i - 1;
END
ELSE IF j > pLen THEN
BEGIN
pos1 := i - pLen;
pos2 := i - 1;
END
ELSE
BEGIN
pos1 := 0;
pos2 := 0;
END;
END;
(* BruteForce Left To Right One Loop
iterative matching*)
Procedure BruteForceLR1LIt(s,p : STRING; Var pos1, pos2 : INTEGER);
VAR
sLen, pLen, i, j, iterations, qcount : INTEGER;
found : Boolean;
BEGIN
sLen := Length(s);
pLen := Length(p);
iterations := 0;
qcount := 0;
i := 1;
j := 1;
REPEAT
IF p[j] = '?' THEN BEGIN
i := i + 1;
j := j + 1;
qcount := qcount + 1;
END
ELSE IF p[j] = '*' THEN BEGIN
WHILE (j < pLen) AND ((p[j] = '*') OR (p[j] = '?')) DO
BEGIN
IF p[j] = '*' THEN j := j + 1
ELSE IF p[j] = '?' THEN BEGIN
i := i + 1;
j := j + 1;
qcount := qcount + 1;
END;
END;
IF p[j] = '*' THEN
BEGIN
iterations := sLen - i;
i := sLen + 1;
j := pLen + 1;
END
ELSE BEGIN
WHILE (NOT EQ(s[i], p[j])) AND (i < sLen) DO BEGIN
i := i + 1;
iterations := iterations + 1;
END;
IF i = sLen THEN i := sLen + 1;
END;
END
ELSE IF EQ(s[i], p[j]) THEN BEGIN
i := i + 1;
j := j + 1;
qcount := qcount + 1;
END
ELSE BEGIN
i := i -j + 1 + 1;
j := 1;
END;
UNTIl (i > sLen) OR (j > pLen);
IF (iterations <> 0) AND (j > pLen) THEN BEGIN
pos1 := i - iterations - qcount;
pos2 := i - 1;
END
ELSE IF j > pLen THEN
BEGIN
pos1 := i - pLen;
pos2 := i - 1;
END
ELSE
BEGIN
pos1 := 0;
pos2 := 0;
END;
END;
(*Highlighting Text with green*
Prints out normal if conditions not met *)
PROCEDURE HighlightPart(s: STRING; fromPos, toPos: Integer);
VAR
i : Integer;
BEGIN
IF (fromPos <> 0) AND (toPos >= fromPos) THEN BEGIN
Write(' ');
FOR i := 1 TO Length(s) DO BEGIN
IF (i >= fromPos) AND (i <= toPos) THEN BEGIN
TextColor(Green);
Write(s[i]);
END
ELSE BEGIN
TextColor(LightGray);
Write(s[i]);
END;
END;
TextBackground(Black);
TextColor(LightGray);
END ELSE
Write(' ', s);
WriteLn;
END;
VAR
s,p : String;
pos1, pos2 : INTEGER;
BEGIN
s := 'aabbccddeeffgaaaeghhaXeasdflkasdfl';
p := 'a*e';
pos1 := 0;
pos2 := 0;
(* recursive *)
comps := 0;
BruteForceLR1L(s,p,pos1,pos2);
writeln('BruteForceLR1L:', #13#10, ' pos: from ', pos1, ' - ', pos2, #13#10, ' comps: ', comps);
WriteLn(' ', p);
HighlightPart(s,pos1,pos2);
p := 'b**e';
comps := 0;
BruteForceLR1L(s,p,pos1,pos2);
writeln('BruteForceLR1L:', #13#10, ' pos: from ', pos1, ' - ', pos2, #13#10, ' comps: ', comps);
WriteLn(' ', p);
HighlightPart(s,pos1,pos2);
p := 'X**z';
comps := 0;
BruteForceLR1L(s,p,pos1,pos2);
writeln('BruteForceLR1L:', #13#10, ' pos: from ', pos1, ' - ', pos2, #13#10, ' comps: ', comps);
WriteLn(' ', p);
HighlightPart(s,pos1,pos2);
p := 'b*?e';
comps := 0;
BruteForceLR1L(s,p,pos1,pos2);
writeln('BruteForceLR1L:', #13#10, ' pos: from ', pos1, ' - ', pos2, #13#10, ' comps: ', comps);
WriteLn(' ', p);
HighlightPart(s,pos1,pos2);
p := '??e';
comps := 0;
BruteForceLR1L(s,p,pos1,pos2);
writeln('BruteForceLR1L:', #13#10, ' pos: from ', pos1, ' - ', pos2, #13#10, ' comps: ', comps);
WriteLn(' ', p);
HighlightPart(s,pos1,pos2);
WriteLn('elapsed time: ', ElapsedTime, #13#10);
p := '?*?a';
comps := 0;
BruteForceLR1L(s,p,pos1,pos2);
writeln('BruteForceLR1L:', #13#10, ' pos: from ', pos1, ' - ', pos2, #13#10, ' comps: ', comps);
WriteLn(' ', p);
HighlightPart(s,pos1,pos2);
WriteLn('elapsed time: ', ElapsedTime, #13#10);
END. |
program hvl2wav;
(*
Project : HVL2WAV v1.2
Detail : FPC Port based on HVL2WAV v1.2 for Win32 and AmigaOS4
URL : http://www.petergordon.org.uk/files/hvl2wav12.zip
*)
{$H+}
Uses
sysutils,
replay; // unit replay, based on hvl replayer library 1.8
Var
max_frames : uint32 = 10 * 60 * 50;
framelen : uint32;
mix_freq : uint32 = 44100;
subsong : uint32 = 0;
smplen : uint32 = 0;
stereosep : uint32 = 0;
autogain : longbool = FALSE;
use_songend : longbool = TRUE;
filename : pchar = Nil;
outname : pchar = Nil;
wavname : packed array [0..pred(1020)] of char;
tmpname : packed array [0..pred(1024)] of char;
mixbuf : pint8 = Nil;
ht : Phvl_tune = Nil;
outf : longint;
tempf : longint;
procedure write32(f: THandle; n: uint32);
begin
{$IFDEF ENDIAN_BIG}
FileWrite(f, SwapEndian(n), SizeOf(n));
{$ELSE}
FileWrite(f, n, SizeOf(n));
{$ENDIF}
end;
procedure write16(f: THandle; n: uint16);
begin
{$IFDEF ENDIAN_BIG}
FileWrite(f, SwapEndian(n), SizeOf(n));
{$ELSE}
FileWrite(f, n, SizeOf(n));
{$ENDIF}
end;
function Main(argc: longint; argv: ppchar): longint;
var
i, j : LongInt;
l : int32;
frm : uint32;
{$IFDEF ENDIAN_BIG}
k : int8;
{$ENDIF}
begin
for i := 1 to pred(argc) do
begin
if (argv[i][0] = '-') then
begin
case ( argv[i][1] ) of
't' :
begin
max_frames := StrToInt( argv[i][2] ) * 50;
j := 2;
while( ( argv[i][j] >= '0' ) and ( argv[i][j] <= '9' ) ) do inc(j);
if ( argv[i][j] = ':' ) then
begin
max_frames := max_frames * 60;
max_frames := max_frames + (StrToInt( argv[i][j+1] )*50);
end;
if ( max_frames = 0 ) then
begin
WriteLn( 'Invalid timeout' );
exit( 0 );
end;
use_songend := FALSE;
end;
'f' :
begin
mix_freq := StrToInt( argv[i][2] );
if( ( mix_freq < 8000 ) or ( mix_freq > 48000 ) ) then
begin
WriteLn( 'Frequency should be between 8000 and 48000' );
exit( 0 )
end;
end;
's' :
begin
subsong := StrToInt( argv[i][2] );
end;
'a' :
begin
autogain := TRUE;
end;
'o' :
begin
outname := @argv[i][2];
if ( outname[0] = #0 ) then
begin
WriteLn( 'Invalid output name' );
exit( 0 );
end;
end;
'x' :
begin
stereosep := StrToInt( argv[i][2] );
if( stereosep > 4 ) then stereosep := 4;
end;
end; // case
end
else
begin
if filename = nil then filename := argv[i];
end;
end;
if ( filename = nil ) then
begin
WriteLn( 'HVL2WAV 1.2, replayer v1.8' );
WriteLn( 'By Xeron/IRIS (pete@petergordon.org.uk)' );
WriteLn;
WriteLn( 'Usage: hvl2wav [options] <filename>' );
WriteLn;
WriteLn( 'Options:' );
WriteLn( ' -ofile Output to "file"' );
WriteLn( ' -tm:ss Timeout after m minutes and ss seconds' );
WriteLn( ' (overrides songend detection, defaults to 10:00' );
WriteLn( ' -fn Set frequency, where n is 8000 to 48000' );
WriteLn( ' -sn Use subsong n' );
WriteLn( ' -a Calculate optimal gain before converting' );
WriteLn( ' -xn Set stereo seperation (ahx only, no effect on HVL files)' );
WriteLn( ' 0 = 0% (Mono)' );
WriteLn( ' 1 = 25%' );
WriteLn( ' 2 = 50%' );
WriteLn( ' 3 = 75%' );
WriteLn( ' 4 = 100% (Paula)' );
exit ( 0 );
end;
framelen := (mix_freq*2*2) div 50; // framelen = 3528 bytes
mixbuf := GetMem( framelen );
if ( mixbuf = nil ) then
begin
WriteLn( 'Out of memory :-(' );
exit( 0 );
end;
hvl_InitReplayer;
ht := hvl_LoadTune( filename, mix_freq, stereosep );
if ( ht = nil ) then
begin
FreeMem( mixbuf );
WriteLn(Format( 'Unable to open "%s"', [filename] ));
exit( 0 );
end;
if ( not hvl_InitSubsong( ht, subsong ) ) then
begin
hvl_FreeTune( ht );
FreeMem( mixbuf );
WriteLn( Format( 'Unable to initialise subsong %d', [subsong] ));
exit( 0 );
end;
if ( autogain ) then
begin
WriteLn( 'Calculating optimal gain...' );
l := hvl_FindLoudest( ht, max_frames, use_songend );
if ( l > 0 )
then l := 3276700 div l
else l := 100;
if ( l > 200 ) then l := 200;
ht^.ht_mixgain := (l * 256) div 100;
hvl_InitSubsong( ht, subsong );
ht^.ht_SongEndReached := 0;
end;
writeln( 'Converting tune...' );
if ( outname <> nil ) then
begin
strlcopy( wavname, outname, 1020 );
end
else
begin
if ( ( strlen( filename ) > 4 ) and
( ( strlcomp( filename, 'hvl.', 4 ) = 0 ) or
( strlcomp( filename, 'ahx.', 4 ) = 0 ) ) )
then strlcopy( wavname, @filename[4], 1020 )
else strlcopy( wavname, filename, 1020 );
if ( ( strlen( wavname ) > 4 ) and
( ( strcomp( @wavname[strlen(wavname)-4], '.hvl' ) = 0 ) or
( strcomp( @wavname[strlen(wavname)-4], '.ahx' ) = 0 ) ) )
then wavname[strlen(wavname)-4] := #0;
strcat( wavname, '.wav' );
end;
strcopy( tmpname, wavname );
strcat ( tmpname, '.tmp' );
tempf := FileCreate( tmpname, fmOpenReadWrite);
if ( tempf = -1 ) then
begin
hvl_FreeTune( ht );
FreeMem( mixbuf );
WriteLn(Format( 'Unable to open "%s" for output', [tmpname] ));
exit( 0 );
end;
frm := 0;
smplen := 0;
while ( frm < max_frames ) do
begin
if ( ( use_songend ) and ( ht^.ht_SongEndReached <> 0) )
then break;
hvl_DecodeFrame( ht, mixbuf, @mixbuf[2], 4 );
{$IFDEF ENDIAN_BIG}
// The replayer generates audio samples in the same
// endian mode as the CPU. So on big endian systems
// we have to swap it all to stupid endian for the
// WAV format.
i := 0;
while ( i < framelen ) do
begin
k := mixbuf[i];
mixbuf[i] := mixbuf[i+1];
mixbuf[i+1] := k;
i := i + 2;
end;
{$ENDIF}
filewrite( tempf, mixbuf^, framelen );
smplen := smplen + framelen;
frm := frm + 1;
end;
FileClose( tempf );
outf := filecreate( wavname, fmOpenReadWrite );
if ( outf = -1 ) then
begin
hvl_FreeTune( ht );
FreeMem( mixbuf );
//unlink( tmpname );
WriteLn( Format('Unable to open "%s" for output', [wavname] ));
exit( 0 );
end;
tempf := FileOpen( tmpname, fmOpenRead );
if ( tempf = -1 ) then
begin
FileClose( outf );
//unlink( wavname );
//unlink( tmpname );
hvl_FreeTune( ht );
FreeMem( mixbuf );
WriteLn( Format( 'Unable to open "%s" for input', [tmpname] ));
exit( 0 );
end;
FileWrite( outf, 'RIFF', 4 );
write32 ( outf, smplen+36 );
FileWrite( outf, 'WAVE', 4 );
FileWrite( outf, 'fmt ', 4 );
write32 ( outf, 16 );
write16 ( outf, 1 );
write16 ( outf, 2 );
write32 ( outf, mix_freq );
write32 ( outf, mix_freq*4 );
write16 ( outf, 4 );
write16 ( outf, 16 );
FileWrite( outf, 'data', 4 );
write32 ( outf, smplen );
i := 0;
while ( i < smplen ) do
begin
FileRead ( tempf, mixbuf^, framelen);
FileWrite( outf, mixbuf^, framelen);
i := i + framelen;
end;
FileClose( outf );
FileClose( tempf );
//unlink( tmpname );
hvl_FreeTune( ht );
FreeMem( mixbuf );
WriteLn( 'ALL DONE!' );
exit( 0 );
end;
begin
ExitCode := Main(argc, argv);
end.
|
unit ClassPedido;
interface
uses System.Generics.Collections, ClassConexao, Data.DB;
type
TPedido = Class
public type
TItensPedido = Class
private
FVlrTotal : Double;
FNumPedido : Integer;
FItem : Integer;
FQuantidade : Double;
FVlrUnit : Double;
FCodProduto : Integer;
procedure SetCodProduto(const Value: Integer);
procedure SetItem(const Value: Integer);
procedure SetNumPedido(const Value: Integer);
procedure SetQuantidade(const Value: Double);
procedure SetVlrTotal(const Value: Double);
procedure SetVlrUnit(const Value: Double);
public
property Item : Integer read FItem write SetItem;
property NumPedido : Integer read FNumPedido write SetNumPedido;
property CodProduto : Integer read FCodProduto write SetCodProduto;
property Quantidade : Double read FQuantidade write SetQuantidade;
property VlrUnit : Double read FVlrUnit write SetVlrUnit;
property VlrTotal : Double read FVlrTotal write SetVlrTotal;
End;
private
FVlrTotal : Double;
FCodCliente : Integer;
FListaItens : TObjectList<TItensPedido>;
FNumPedido : Integer;
FDtEmissao : TDateTime;
Conexao : TConexao;
FMsgErro : String;
procedure SetCodCliente(const Value: Integer);
procedure SetDtEmissao(const Value: TDateTime);
procedure SetVlrTotal(const Value: Double);
procedure SetMsgErro(const Value: String);
function RetNumPedido: Integer;
function ValidaExiste(pPedido: Integer): Boolean;
public
constructor Create;
destructor Destroy; override;
function GravarPedido: Boolean;
function CarregaPedido(pPedido: Integer): Boolean;
property NumPedido : Integer read FNumPedido write FNumPedido;
property DtEmissao : TDateTime read FDtEmissao write SetDtEmissao;
property CodCliente : Integer read FCodCliente write SetCodCliente;
property VlrTotal : Double read FVlrTotal write SetVlrTotal;
property ListaItens : TObjectList<TItensPedido> read FListaItens write FListaItens;
property MsgErro : String read FMsgErro write SetMsgErro;
End;
implementation
uses
System.SysUtils;
{ TPedido.TItensPedido }
procedure TPedido.TItensPedido.SetCodProduto(const Value: Integer);
begin
FCodProduto := Value;
end;
procedure TPedido.TItensPedido.SetItem(const Value: Integer);
begin
FItem := Value;
end;
procedure TPedido.TItensPedido.SetNumPedido(const Value: Integer);
begin
FNumPedido := Value;
end;
procedure TPedido.TItensPedido.SetQuantidade(const Value: Double);
begin
FQuantidade := Value;
end;
procedure TPedido.TItensPedido.SetVlrTotal(const Value: Double);
begin
FVlrTotal := Value;
end;
procedure TPedido.TItensPedido.SetVlrUnit(const Value: Double);
begin
FVlrUnit := Value;
end;
{ TPedido }
constructor TPedido.Create;
begin
FListaItens := TObjectList<TItensPedido>.Create;
Conexao := TConexao.Create;
FNumPedido := RetNumPedido;
end;
destructor TPedido.Destroy;
begin
Conexao.Free;
FreeAndNil(FListaItens);
inherited;
end;
function TPedido.ValidaExiste(pPedido: Integer): Boolean;
var
cSQL: String;
bConectado: Boolean;
begin
Result := False;
bConectado := Conexao.Conectado;
if not bConectado then begin
bConectado := Conexao.Conectar(FMsgErro);
if FMsgErro <> '' then begin
Result := False;
Exit;
end;
end;
if bConectado then begin
cSQL := 'SELECT * ' +
'FROM PEDIDO ' +
'WHERE NUM_PEDIDO = :PNUM_PEDIDO ';
Conexao.PreparaQuery(cSQL);
Conexao.PassaParametro('PNUM_PEDIDO', pPedido, ftInteger);
Conexao.AbreQuery(FMsgErro);
if FMsgErro <> '' then begin
Result := False;
Exit;
end;
Result := not Conexao.Query.IsEmpty;
end;
end;
function TPedido.GravarPedido: Boolean;
var
cSQL,
cSQLItem: String;
bConectado,
bExistePedido: Boolean;
nI: Integer;
begin
Result := True;
bConectado := Conexao.Conectado;
if not bConectado then begin
bConectado := Conexao.Conectar(FMsgErro);
if FMsgErro <> '' then begin
Result := False;
Exit;
end;
end;
if bConectado then begin
bExistePedido := ValidaExiste(FNumPedido);
if bExistePedido then begin
cSQL := 'UPDATE PEDIDO SET DT_EMISSAO = :PDT_EMISSAO, ' +
' COD_CLI = :PCOD_CLI, ' +
' VLR_TOTAL = :PVLR_TOTAL ' +
'WHERE NUM_PEDIDO = :PNUM_PEDIDO ';
end else begin
cSQL := 'INSERT INTO PEDIDO( DT_EMISSAO, COD_CLI, VLR_TOTAL) '+
' VALUES(:PDT_EMISSAO, :PCOD_CLI, :PVLR_TOTAL) ';
end;
Conexao.PreparaQuery(cSQL);
Conexao.PassaParametro('PDT_EMISSAO', FDtEmissao , ftDate);
Conexao.PassaParametro('PCOD_CLI' , FCodCliente , ftInteger);
Conexao.PassaParametro('PVLR_TOTAL' , FVlrTotal , ftFloat);
if bExistePedido then begin
Conexao.PassaParametro('PNUM_PEDIDO', FNumPedido , ftInteger);
end;
Conexao.ExecutaQuery(FMsgErro);
if FMsgErro <> '' then begin
Result := False;
Exit;
end;
if bExistePedido then begin
cSQLItem := 'DELETE FROM ITENS_PEDIDO WHERE NUM_PEDIDO = :PNUM_PEDIDO';
Conexao.PreparaQuery(cSQLItem);
Conexao.PassaParametro('PNUM_PEDIDO', FNumPedido , ftInteger);
Conexao.ExecutaQuery(FMsgErro);
if FMsgErro <> '' then begin
Result := False;
Exit;
end;
end;
cSQLItem := 'INSERT INTO ITENS_PEDIDO( NUM_PEDIDO, ITEM, COD_PROD, QUANTIDADE, VLR_UNIT, VLR_TOTAL) '+
' VALUES(:PNUM_PEDIDO, :PITEM, :PCOD_PROD, :PQUANTIDADE, :PVLR_UNIT, :PVLR_TOTAL) ';
for nI := 0 to ListaItens.Count - 1 do begin
Conexao.PreparaQuery(cSQLItem);
Conexao.PassaParametro('PNUM_PEDIDO', ListaItens[nI].NumPedido);
Conexao.PassaParametro('PITEM' , ListaItens[nI].Item);
Conexao.PassaParametro('PCOD_PROD' , ListaItens[nI].CodProduto);
Conexao.PassaParametro('PQUANTIDADE', ListaItens[nI].Quantidade);
Conexao.PassaParametro('PVLR_UNIT' , ListaItens[nI].VlrUnit);
Conexao.PassaParametro('PVLR_TOTAL' , ListaItens[nI].VlrTotal);
Conexao.ExecutaQuery(FMsgErro);
if FMsgErro <> '' then begin
Result := False;
Exit;
end;
End;
end;
end;
function TPedido.CarregaPedido(pPedido: Integer): Boolean;
var
cSQL: String;
bConectado: Boolean;
nI: Integer;
begin
Result := False;
bConectado := Conexao.Conectado;
if not bConectado then begin
bConectado := Conexao.Conectar(FMsgErro);
if FMsgErro <> '' then begin
Exit;
end;
end;
if bConectado then begin
cSQL := 'SELECT NUM_PEDIDO, DT_EMISSAO, COD_CLI, VLR_TOTAL '+
'FROM PEDIDO WHERE NUM_PEDIDO = :PNUM_PEDIDO ';
Conexao.PreparaQuery(cSQL);
Conexao.PassaParametro('PNUM_PEDIDO', pPedido , ftInteger);
Conexao.AbreQuery(FMsgErro);
if FMsgErro <> '' then begin
Exit;
end;
if not Conexao.Query.IsEmpty then begin
FNumPedido := Conexao.Query.FieldByName('NUM_PEDIDO').AsInteger;
FDtEmissao := Conexao.Query.FieldByName('DT_EMISSAO').AsDateTime;
FCodCliente := Conexao.Query.FieldByName('COD_CLI').AsInteger;
FVlrTotal := Conexao.Query.FieldByName('VLR_TOTAL').AsFloat;
Result := True;
end;
cSQL := 'SELECT NUM_PEDIDO, ITEM, COD_PROD, QUANTIDADE, VLR_UNIT, VLR_TOTAL '+
'FROM ITENS_PEDIDO WHERE NUM_PEDIDO = :PNUM_PEDIDO '+
'ORDER BY ITEM ';
Conexao.PreparaQuery(cSQL);
Conexao.PassaParametro('PNUM_PEDIDO', pPedido , ftInteger);
Conexao.AbreQuery(FMsgErro);
if FMsgErro <> '' then begin
Exit;
end;
while not Conexao.Query.Eof do begin
ListaItens.Add(TPedido.TItensPedido.Create);
nI := ListaItens.Count - 1;
ListaItens[nI].Item := Conexao.Query.FieldByName('NUM_PEDIDO').AsInteger;
ListaItens[nI].NumPedido := Conexao.Query.FieldByName('ITEM').AsInteger;
ListaItens[nI].CodProduto := Conexao.Query.FieldByName('COD_PROD').AsInteger;
ListaItens[nI].Quantidade := Conexao.Query.FieldByName('QUANTIDADE').AsFloat;
ListaItens[nI].VlrUnit := Conexao.Query.FieldByName('VLR_UNIT').AsFloat;
ListaItens[nI].VlrTotal := Conexao.Query.FieldByName('VLR_TOTAL').AsFloat;
Conexao.Query.Next;
end;
end;
end;
function TPedido.RetNumPedido: Integer;
var
cSQL: String;
bConectado: Boolean;
begin
Result := 0;
bConectado := Conexao.Conectado;
if not bConectado then begin
bConectado := Conexao.Conectar(FMsgErro);
if FMsgErro <> '' then begin
Exit;
end;
end;
if bConectado then begin
cSQL := 'SELECT COALESCE(MAX(NUM_PEDIDO),0) + 1 NUM_PEDIDO FROM PEDIDO ';
Conexao.PreparaQuery(cSQL);
Conexao.AbreQuery(FMsgErro);
if FMsgErro <> '' then begin
Exit;
end;
if not Conexao.Query.IsEmpty then begin
Result := Conexao.Query.FieldByName('NUM_PEDIDO').AsInteger;
end;
end;
end;
procedure TPedido.SetCodCliente(const Value: Integer);
begin
FCodCliente := Value;
end;
procedure TPedido.SetDtEmissao(const Value: TDateTime);
begin
FDtEmissao := Value;
end;
procedure TPedido.SetMsgErro(const Value: String);
begin
FMsgErro := Value;
end;
procedure TPedido.SetVlrTotal(const Value: Double);
begin
FVlrTotal := Value;
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmNotebook
Purpose : A replacement for Borlands Notebook component.
Date : 11-20-02
Author : Ryan J. Mills
Version : 1.92
Notes :
================================================================================}
unit rmNotebook2;
interface
{$I CompilerDefines.INC}
{$D+}
uses Windows, rmTabs3x, Messages, Forms, Classes, Controls, Graphics, ImgList, sysutils;
type
TrmCustomNotebookControl = class;
TrmNotebookPage = class;
TrmNotebookPageEvent = procedure(ASheet : TrmNotebookPage) of object;
TrmNotebookQueryPageEvent = procedure(ASheet : TrmNotebookPage; var CanClose : Boolean) of object;
TrmNotebookPage = class(TCustomControl)
private
FNotebookControl : TrmCustomNotebookControl;
FImageIndex : Integer;
FOnQueryClosePage: TrmNotebookQueryPageEvent;
FOnDestroy : TrmNotebookPageEvent;
fData: integer;
procedure SetImageIndex(Value : Integer);
function GetPageOrderIndex : Integer;
procedure SetNotebookControl(ANotebookControl : TrmCustomNotebookControl);
procedure SetPageOrderIndex(Value : Integer);
protected
procedure CreateParams(var Params : TCreateParams); override;
procedure ReadState(Reader : TReader); override;
procedure WMErase(var Message : TMessage); message WM_ERASEBKGND;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
procedure CMParentColorChanged(var Message: TMessage); message CM_PARENTCOLORCHANGED;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Paint; override;
property NotebookControl : TrmCustomNotebookControl read FNotebookControl write SetNotebookControl;
published
property Color;
property Caption;
property Data : integer read fData write fData;
property Font;
property Enabled;
property Hint;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible default true;
property ParentFont;
property ParentColor;
property ImageIndex : Integer read FImageIndex write SetImageIndex;
property PageOrderIndex : Integer read GetPageOrderIndex write SetPageOrderIndex stored False;
property OnEnter;
property OnExit;
property OnResize;
property OnDestroy : TrmNotebookPageEvent read FOnDestroy write FOnDestroy;
property OnQueryClosePage : TrmNotebookQueryPageEvent read FOnQueryClosePage write FOnQueryClosePage;
end;
TPageChangingEvent = procedure(Sender: TObject; NewPageIndex : integer; var AllowChange: Boolean) of object;
TrmCustomNotebookControl = class(TCustomControl)
private
FPages : TList;
FImages : TCustomImageList;
FActivePage : TrmNotebookPage;
FImageChangeLink : TChangeLink;
FBorderStyle: TBorderStyle;
FPageChanged : TNotifyEvent;
FPageChanging : TPageChangingEvent;
function GetPage(Index : Integer) : TrmNotebookPage;
function GetPageCount : Integer;
procedure SetImages(Value : TCustomImageList);
procedure ImageListChange(Sender : TObject);
procedure CMDialogKey(var Message : TCMDialogKey); message CM_DIALOGKEY;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMBorderChanged(var Message: TMessage); message CM_BORDERCHANGED;
procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED;
function GetActivePageIndex: integer;
procedure SetBorderStyle(Value: TBorderStyle);
protected
procedure GetChildren(Proc : TGetChildProc; Root : TComponent); override;
procedure SetChildOrder(Child : TComponent; Order : Integer); override;
procedure ShowControl(AControl : TControl); override;
procedure WMErase(var Message : TMessage); message WM_ERASEBKGND;
procedure CreateParams(var Params: TCreateParams); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure InsertPage(Page : TrmNotebookPage); virtual;
procedure RemovePage(Page : TrmNotebookPage); virtual;
procedure SetActivePage(Page : TrmNotebookPage); virtual;
procedure SetActivePageIndex(PageIndex:integer); virtual;
procedure DoPageChanged; virtual;
function DoPageChanging(NewPageIndex:integer):boolean; virtual;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsNone;
property Images : TCustomImageList read FImages write SetImages;
property ActivePageIndex : integer read GetActivePageIndex write SetActivePageIndex stored false;
property OnPageChanging : TPageChangingEvent read fPageChanging write fPageChanging;
property OnPageChanged : TNotifyEvent read fPageChanged write fPageChanged;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Paint; override;
function NewPage:TrmNoteBookPage;
function FindNextPage(CurPage : TrmNotebookPage; GoForward : Boolean) : TrmNotebookPage;
procedure SelectNextPage(GoForward : Boolean);
property PageCount : Integer read GetPageCount;
property Pages[Index : Integer] : TrmNotebookPage read GetPage;
published
property ActivePage : TrmNotebookPage read FActivePage write SetActivePage;
end;
TrmTabbedNoteBookControl = class(TrmCustomNotebookControl)
private
fTabs : TrmTabSet;
fchanging : boolean;
procedure DoTabChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
function GetTabsVisible: boolean;
procedure SetTabsVisible(const Value: boolean);
procedure RebuildTabs;
function GetTabBackgroundcolor: TColor;
function GetTabDitherBackground: Boolean;
function GetTabSelectedColor: TColor;
function GetTabType: TTabType;
function GetTabUnselectedColor: TColor;
procedure setTabBackgroundColor(const Value: TColor);
procedure SetTabDitherBackground(const Value: Boolean);
procedure SetTabSelectedColor(const Value: TColor);
procedure SetTabType(const Value: TTabType);
procedure SetTabUnselectedColor(const Value: TColor);
protected
procedure InsertPage(Page : TrmNotebookPage); override;
procedure RemovePage(Page : TrmNotebookPage); override;
procedure DoPageChanged; override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
published
property Align;
property Color;
property Font;
property OnResize;
property BorderStyle;
property ActivePageIndex;
property OnPageChanging;
property OnPageChanged;
property Images;
property TabSelectedColor: TColor read GetTabSelectedColor write SetTabSelectedColor;
property TabUnselectedColor: TColor read GetTabUnselectedColor write SetTabUnselectedColor;
property TabDitherBackground: Boolean read GetTabDitherBackground write SetTabDitherBackground;
property TabBackgroundColor : TColor read GetTabBackgroundcolor write setTabBackgroundColor;
property TabType : TTabType read GetTabType write SetTabType;
property TabsVisible:boolean read GetTabsVisible write SetTabsVisible;
end;
TrmNoteBookControl = class(TrmCustomNoteBookControl)
published
property Align;
property Color;
property Font;
property OnResize;
property BorderStyle;
property ActivePageIndex;
property OnPageChanging;
property OnPageChanged;
property Images;
end;
implementation
uses rmLibrary;
const
SNotebookIndexError = 'Sheet index Error';
{ TrmNotebookPage }
constructor TrmNotebookPage.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csAcceptsControls] - [csDesignInteractive];
Visible := True;
Caption := '';
FImageIndex := -1;
align := alClient;
end;
procedure TrmNotebookPage.SetImageIndex(Value : Integer);
begin
FImageIndex := Value;
// PaintButton;
end;
destructor TrmNotebookPage.Destroy;
begin
if Assigned(FOnDestroy) then
FOnDestroy(Self);
inherited Destroy;
end;
function TrmNotebookPage.GetPageOrderIndex : Integer;
begin
if FNotebookControl <> nil then
Result := FNotebookControl.FPages.IndexOf(Self)
else
Result := -1;
end;
procedure TrmNotebookPage.CreateParams(var Params : TCreateParams);
begin
inherited CreateParams(Params);
with Params.WindowClass do
style := style and not (CS_HREDRAW or CS_VREDRAW);
end;
procedure TrmNotebookPage.ReadState(Reader : TReader);
begin
inherited ReadState(Reader);
if Reader.Parent is TrmCustomNotebookControl then
NotebookControl := TrmCustomNotebookControl(Reader.Parent);
end;
procedure TrmNotebookPage.SetNotebookControl(ANotebookControl : TrmCustomNotebookControl);
begin
if FNotebookControl <> ANotebookControl then
begin
if FNotebookControl <> nil then
FNotebookControl.RemovePage(Self);
Parent := ANotebookControl;
if ANotebookControl <> nil then
ANotebookControl.InsertPage(Self);
end;
end;
procedure TrmNotebookPage.SetPageOrderIndex(Value : Integer);
var
MaxPageIndex : Integer;
begin
if FNotebookControl <> nil then
begin
MaxPageIndex := FNotebookControl.FPages.Count - 1;
if Value > MaxPageIndex then
raise EListError.CreateFmt(SNotebookIndexError, [Value, MaxPageIndex]);
FNotebookControl.FPages.Move(PageOrderIndex, Value);
end;
end;
procedure TrmNotebookPage.Paint;
begin
if not (csDestroying in ComponentState) and (Assigned(FNotebookControl)) then
begin
if ParentColor then
Canvas.Brush.Color := FNotebookControl.Color
else
Canvas.Brush.Color := Color;
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(Rect(0, 0, Width, Height));
end;
if csDesigning in ComponentState then
with Canvas do
begin
Pen.Style := psDash;
Brush.Style := bsClear;
Rectangle(0, 0, Width, Height);
end;
end;
procedure TrmNotebookPage.WMErase(var Message: TMessage);
begin
Message.Result := 1;
end;
procedure TrmNotebookPage.CMColorChanged(var Message: TMessage);
begin
Inherited;
Invalidate;
end;
procedure TrmNotebookPage.CMParentColorChanged(var Message: TMessage);
begin
inherited;
if ParentColor then
Invalidate;
end;
{ TrmCustomNotebookControl }
constructor TrmCustomNotebookControl.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csOpaque];
width := 250;
height := 250;
Caption := '';
FBorderStyle := bsNone;
FPages := TList.Create;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
end;
destructor TrmCustomNotebookControl.Destroy;
var
I : Integer;
begin
for I := FPages.Count - 1 downto 0 do
TrmNotebookPage(FPages[I]).Free;
FPages.Free;
FImageChangeLink.Free;
inherited Destroy;
end;
procedure TrmCustomNotebookControl.ImageListChange(Sender : TObject);
begin
Invalidate;
end;
function TrmCustomNotebookControl.FindNextPage(CurPage : TrmNotebookPage; GoForward : Boolean) : TrmNotebookPage;
var
I, StartIndex : Integer;
begin
Result := nil;
if FPages.Count <> 0 then
begin
StartIndex := FPages.IndexOf(CurPage);
if StartIndex = -1 then
begin
if GoForward then
begin
StartIndex := FPages.Count - 1;
for I := StartIndex downto 0 do
begin
if TrmNotebookPage(FPages[I]).Visible then
begin
StartIndex := I;
Break;
end;
end;
end
else
begin
StartIndex := 0;
for I := 0 to FPages.Count - 1 do
begin
if TrmNotebookPage(FPages[I]).Visible then
begin
StartIndex := I;
Break;
end;
end;
end;
end;
if GoForward then
begin
Inc(StartIndex);
if StartIndex = FPages.Count then
StartIndex := 0;
for I := StartIndex to FPages.Count - 1 do
begin
if TrmNotebookPage(FPages[I]).Visible then
begin
StartIndex := I;
Break;
end;
end;
end
else
begin
if StartIndex = 0 then
StartIndex := FPages.Count;
Dec(StartIndex);
for I := StartIndex downto 0 do
begin
if TrmNotebookPage(FPages[I]).Visible then
begin
StartIndex := I;
Break;
end;
end;
end;
Result := FPages[StartIndex];
end;
end;
procedure TrmCustomNotebookControl.GetChildren(Proc : TGetChildProc; Root : TComponent);
var
I : Integer;
begin
for I := 0 to FPages.Count - 1 do
Proc(TComponent(FPages[I]));
end;
function TrmCustomNotebookControl.GetPage(Index : Integer) : TrmNotebookPage;
begin
Result := FPages[Index];
end;
function TrmCustomNotebookControl.GetPageCount : Integer;
begin
Result := FPages.Count;
end;
procedure TrmCustomNotebookControl.InsertPage(Page : TrmNotebookPage);
begin
FPages.Add(Page);
Page.FNotebookControl := Self;
Page.FreeNotification(self);
end;
procedure TrmCustomNotebookControl.RemovePage(Page : TrmNotebookPage);
var
wPage : TrmNotebookPage;
begin
if FActivePage = Page then
begin
wPage := FindNextPage(FActivePage, True);
if wPage = Page then
FActivePage := nil
else
FActivePage := wPage;
end;
FPages.Remove(Page);
Page.FNotebookControl := nil;
if not (csDestroying in ComponentState) then
Invalidate;
end;
procedure TrmCustomNotebookControl.SelectNextPage(GoForward : Boolean);
begin
SetActivePage(FindNextPage(ActivePage, GoForward));
end;
procedure TrmCustomNotebookControl.SetActivePage(Page : TrmNotebookPage);
var
woldPage : TrmNotebookPage;
wPageChanged : boolean;
begin
wPageChanged := false;
if not (csDestroying in ComponentState) then
begin
if (assigned(Page) and (Page.NotebookControl = Self)) or (Page = nil) then
begin
if assigned(fActivePage) then
begin
if fActivePage <> Page then
begin
wOldPage := fActivePage;
fActivePage := Page;
if csdesigning in componentstate then
begin
fActivePage.BringToFront;
wOldPage.SendToBack;
end
else
begin
fActivePage.Show;
fActivePage.BringToFront;
wOldPage.SendToBack;
wOldPage.Hide;
end;
try
fActivePage.SelectFirst;
except
//do nothing...
end;
wPageChanged := true;
end;
end
else
begin
fActivePage := Page;
fActivePage.Show;
if csdesigning in componentstate then
fActivePage.BringToFront;
try
fActivePage.SelectFirst;
except
//do nothing...
end;
wPageChanged := true;
end;
end;
end;
if wPageChanged then
DoPageChanged;
end;
procedure TrmCustomNotebookControl.SetChildOrder(Child : TComponent; Order : Integer);
begin
TrmNotebookPage(Child).PageOrderIndex := Order;
end;
procedure TrmCustomNotebookControl.ShowControl(AControl : TControl);
begin
if (AControl is TrmNotebookPage) and (TrmNotebookPage(AControl).NotebookControl = Self) then
SetActivePage(TrmNotebookPage(AControl));
inherited ShowControl(AControl);
end;
procedure TrmCustomNotebookControl.CMDialogKey(var Message : TCMDialogKey);
begin
if (Message.CharCode = VK_TAB) and (GetKeyState(VK_CONTROL) < 0) then
begin
SelectNextPage(GetKeyState(VK_SHIFT) >= 0);
Message.Result := 1;
end
else
inherited;
end;
procedure TrmCustomNotebookControl.SetImages(Value : TCustomImageList);
begin
if Images <> nil then
Images.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if Images <> nil then
begin
Images.RegisterChanges(FImageChangeLink);
Images.FreeNotification(Self);
end;
Invalidate;
end;
procedure TrmCustomNotebookControl.Paint;
var
wRect : TRect;
begin
wRect := ClientRect;
Canvas.Brush.Color := color;
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(wRect);
if assigned(FActivePage) then
fActivePage.Invalidate;
end;
procedure TrmCustomNotebookControl.WMErase(var Message: TMessage);
begin
Message.Result := 1;
end;
procedure TrmCustomNotebookControl.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
begin
if AComponent = Images then
Images := nil;
if (AComponent is TrmNotebookPage) and (TrmNotebookPage(AComponent).NotebookControl = self) then
RemovePage(TrmNotebookPage(AComponent));
end;
end;
procedure TrmCustomNotebookControl.CreateParams(var Params: TCreateParams);
const
BorderStyles: array[TBorderStyle] of DWORD = (0, WS_BORDER);
begin
inherited CreateParams(Params);
with Params do
begin
Style := Style or BorderStyles[FBorderStyle];
if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then
begin
Style := Style and not WS_BORDER;
ExStyle := ExStyle or WS_EX_CLIENTEDGE;
end;
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW);
end;
end;
procedure TrmCustomNotebookControl.CMColorChanged(var Message: TMessage);
begin
Inherited;
Invalidate;
end;
procedure TrmCustomNotebookControl.CMFontChanged(var Message: TMessage);
begin
Inherited;
Invalidate;
end;
procedure TrmCustomNotebookControl.CMBorderChanged(var Message: TMessage);
begin
inherited;
Invalidate;
end;
procedure TrmCustomNotebookControl.CMCtl3DChanged(var Message: TMessage);
begin
if NewStyleControls and (FBorderStyle = bsSingle) then RecreateWnd;
inherited;
end;
procedure TrmCustomNotebookControl.SetActivePageIndex(PageIndex: integer);
begin
SetActivePage(TrmNotebookPage(fPages[PageIndex]));
end;
procedure TrmCustomNotebookControl.SetBorderStyle(Value: TBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
RecreateWnd;
end;
end;
function TrmCustomNotebookControl.GetActivePageIndex: integer;
begin
if assigned(factivepage) then
result := FPages.IndexOf(FActivePage)
else
result := -1;
end;
function TrmCustomNotebookControl.NewPage: TrmNoteBookPage;
var
wPage : TrmNotebookPage;
begin
wPage := TrmNotebookPage.Create(nil);
wPage.NotebookControl := self;
ActivePage := wPage;
result := wPage;
end;
procedure TrmCustomNotebookControl.DoPageChanged;
begin
if not (csDestroying in ComponentState) and Assigned(FPageChanged) then
FPageChanged(self);
end;
function TrmCustomNotebookControl.DoPageChanging(NewPageIndex:integer): boolean;
var
wResult : boolean;
begin
wResult := true;
if Assigned(fPageChanging) then
FPageChanging(Self, NewPageIndex, wResult);
result := wResult;
end;
{ TrmTabbedNoteBookControl }
constructor TrmTabbedNoteBookControl.Create(AOwner: TComponent);
begin
inherited;
fTabs := TrmTabSet.Create(self);
fTabs.parent := self;
fTabs.Align := alBottom;
fTabs.OnChange := DoTabChange;
fchanging := false;
end;
destructor TrmTabbedNoteBookControl.Destroy;
begin
fTabs.Free;
inherited;
end;
function TrmTabbedNoteBookControl.GetTabsVisible: boolean;
begin
result := fTabs.Visible;
end;
procedure TrmTabbedNoteBookControl.SetTabsVisible(const Value: boolean);
begin
fTabs.Visible := value;
end;
procedure TrmTabbedNoteBookControl.RebuildTabs;
var
loop : integer;
begin
if (csdestroying in componentstate) then
exit;
fTabs.Tabs.BeginUpdate;
try
fTabs.Tabs.Clear;
if fPages.count > 0 then
begin
for loop := 0 to fPages.Count-1 do
fTabs.Tabs.Add(TrmNotebookPage(fPages[loop]).Caption);
fTabs.TabIndex := ActivePageIndex;
end;
finally
fTabs.Tabs.EndUpdate;
end;
end;
procedure TrmTabbedNoteBookControl.DoPageChanged;
begin
inherited;
fTabs.TabIndex := ActivePageIndex;
end;
procedure TrmTabbedNoteBookControl.InsertPage(Page: TrmNotebookPage);
begin
inherited;
RebuildTabs;
end;
procedure TrmTabbedNoteBookControl.RemovePage(Page: TrmNotebookPage);
begin
inherited;
RebuildTabs;
end;
function TrmTabbedNoteBookControl.GetTabBackgroundcolor: TColor;
begin
result := fTabs.BackgroundColor;
end;
function TrmTabbedNoteBookControl.GetTabDitherBackground: Boolean;
begin
result := fTabs.DitherBackground;
end;
function TrmTabbedNoteBookControl.GetTabSelectedColor: TColor;
begin
result := fTabs.SelectedColor;
end;
function TrmTabbedNoteBookControl.GetTabType: TTabType;
begin
result := fTabs.TabType;
end;
function TrmTabbedNoteBookControl.GetTabUnselectedColor: TColor;
begin
result := fTabs.UnselectedColor;
end;
procedure TrmTabbedNoteBookControl.setTabBackgroundColor(
const Value: TColor);
begin
fTabs.BackgroundColor := value;
end;
procedure TrmTabbedNoteBookControl.SetTabDitherBackground(
const Value: Boolean);
begin
fTabs.DitherBackground := Value;
end;
procedure TrmTabbedNoteBookControl.SetTabSelectedColor(
const Value: TColor);
begin
fTabs.SelectedColor := Value;
end;
procedure TrmTabbedNoteBookControl.SetTabType(const Value: TTabType);
begin
fTabs.TabType := Value;
end;
procedure TrmTabbedNoteBookControl.SetTabUnselectedColor(
const Value: TColor);
begin
fTabs.UnselectedColor := Value;
end;
procedure TrmTabbedNoteBookControl.DoTabChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
begin
if fChanging then
exit;
fChanging := true;
try
AllowChange := DoPageChanging(newtab);
if AllowChange then
ActivePageIndex := newTab;
finally
fchanging := false;
end;
end;
end.
|
unit uFrmQuickBooks;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParent, siComp, StdCtrls, ExtCtrls, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, ComCtrls, Buttons, Mask,
DateBox, cxContainer, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, DBClient, Menus,
uDMQuickBooks, uDMImportExport, ADODB, Provider;
type
TFrmQuickBooks = class(TFrmParent)
Panel1: TPanel;
Label9: TLabel;
lbVersion: TLabel;
imgPeachtree: TImage;
Shape8: TShape;
lbSelection: TLabel;
pnlMenu: TPanel;
lbInvoices: TLabel;
lbCustomer: TLabel;
imgInvoices: TImage;
imgSelect2: TImage;
Shape6: TShape;
imgExit: TImage;
lbExit: TLabel;
lbMRVersion: TLabel;
pgOption: TPageControl;
tsCustomer: TTabSheet;
tsSale: TTabSheet;
pnlFilter: TPanel;
Label13: TLabel;
lbFrom: TLabel;
Label5: TLabel;
cbxStore: TcxLookupComboBox;
dtStart: TDateBox;
dtEnd: TDateBox;
btnSearch: TBitBtn;
btnUpdate: TBitBtn;
cdsInvoice: TClientDataSet;
cdsInvoiceMarked: TBooleanField;
cdsInvoiceInvoiceCode: TStringField;
cdsInvoiceInvoiceDate: TDateTimeField;
cdsInvoiceTotalInvoice: TBCDField;
cdsInvoiceCustomer: TStringField;
cdsInvoiceIDInvoice: TIntegerField;
cdsInvoiceMediaID: TIntegerField;
cdsInvoiceFirstName: TStringField;
cdsInvoiceLastName: TStringField;
cdsInvoiceIDPreSale: TIntegerField;
cdsInvoiceCanceled: TBooleanField;
cdsInvoiceSubTotal: TBCDField;
cdsInvoiceTax: TBCDField;
cdsInvoiceLayaway: TBooleanField;
cdsInvoiceAditionalExpenses: TBCDField;
cdsInvoiceSaleCode: TStringField;
cdsInvoiceAccInvoiceNumber: TStringField;
cdsInvoiceAccGLMainAccount: TStringField;
cdsInvoiceAccSalesTaxCode: TStringField;
cdsInvoiceAccCashAccount: TStringField;
cdsInvoiceAccCustomerID: TStringField;
dsInvoice: TDataSource;
grdSales: TcxGrid;
grdSalesDBTableView: TcxGridDBTableView;
grdSalesLevel: TcxGridLevel;
popSelection: TPopupMenu;
Selectall1: TMenuItem;
UnSelectAll1: TMenuItem;
imgConfig: TImage;
lbConfig: TLabel;
cdsCategory: TClientDataSet;
imgItems: TImage;
lbItems: TLabel;
tsItems: TTabSheet;
cxgrdCustomer: TcxGrid;
cxgrdDBCustomer: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
pnlComple: TPanel;
lbResult: TLabel;
btnComplete: TButton;
pbExportSales: TProgressBar;
cxgrdCategory: TcxGrid;
cxGridDBTableView2: TcxGridDBTableView;
cxGridLevel2: TcxGridLevel;
dsCategory: TDataSource;
cdsCategoryIDCategory: TIntegerField;
cdsCategoryCategory: TStringField;
cxGridDBTableView2IDCategory: TcxGridDBColumn;
cxGridDBTableView2Category: TcxGridDBColumn;
Panel2: TPanel;
btnSearchCustomer: TBitBtn;
cdsEntity: TClientDataSet;
dsEntity: TDataSource;
cdsEntityIDPessoa: TIntegerField;
cdsEntityIDTipoPessoa: TIntegerField;
cdsEntityPath: TStringField;
cdsEntityPessoa: TStringField;
cdsEntityTelefone: TStringField;
cdsEntityCellular: TStringField;
cdsEntityFax: TStringField;
cdsEntityCode: TIntegerField;
cdsEntitySystem: TBooleanField;
cdsEntityDesativado: TIntegerField;
cdsEntityHidden: TIntegerField;
cdsEntityCountry: TStringField;
cdsEntityStateName: TStringField;
cdsEntityState: TStringField;
cdsEntityAddress: TStringField;
cdsEntityCity: TStringField;
cdsEntityZip: TStringField;
cdsEntityEmail: TStringField;
cdsEntityContact: TStringField;
cdsEntityFederalID: TStringField;
cdsEntitySalesTax: TStringField;
cdsEntityDriverLicense: TStringField;
cdsEntityJobDoc: TStringField;
cdsEntityUserCode: TStringField;
cdsEntitySocialSecurity: TStringField;
cdsEntitySCDate: TDateTimeField;
cdsEntitySCGov: TStringField;
cdsEntityLastName: TStringField;
cdsEntityFirstName: TStringField;
cdsEntityCPF: TStringField;
cdsEntityCGC: TStringField;
cdsEntityCustomerCard: TStringField;
cdsEntityNeighborwood: TStringField;
cdsEntityPhoneAreaCode: TStringField;
cdsEntityCellAreaCode: TStringField;
cdsEntityNascimento: TDateTimeField;
cxgrdDBCustomerPessoa: TcxGridDBColumn;
cxgrdDBCustomerTelefone: TcxGridDBColumn;
cxgrdDBCustomerState: TcxGridDBColumn;
cxgrdDBCustomerAddress: TcxGridDBColumn;
cxgrdDBCustomerCity: TcxGridDBColumn;
cxgrdDBCustomerZip: TcxGridDBColumn;
cxgrdDBCustomerEmail: TcxGridDBColumn;
cxgrdDBCustomerContact: TcxGridDBColumn;
cxgrdDBCustomerPhoneAreaCode: TcxGridDBColumn;
Label1: TLabel;
edtCustomerName: TEdit;
cdsInvoiceTelefone: TStringField;
cdsInvoiceCountry: TStringField;
cdsInvoiceState: TStringField;
cdsInvoiceAddress: TStringField;
cdsInvoiceCity: TStringField;
cdsInvoiceZip: TStringField;
cdsInvoiceEmail: TStringField;
cdsInvoiceContact: TStringField;
cdsInvoicePhoneAreaCode: TStringField;
cdsInvoiceFax: TStringField;
cdsSaleItem: TClientDataSet;
cdsSaleItemModelID: TIntegerField;
cdsSaleItemCaseQty: TBCDField;
cdsSaleItemModel: TStringField;
cdsSaleItemDescription: TStringField;
cdsSaleItemCategory: TStringField;
cdsSaleItemSuggRetail: TBCDField;
cdsSaleItemQty: TBCDField;
cdsSaleItemExchangeInvoice: TIntegerField;
cdsSaleItemSalePrice: TBCDField;
cdsSaleItemCostPrice: TBCDField;
cdsSaleItemDiscount: TBCDField;
cdsSaleItemItemTotalSold: TBCDField;
cdsSaleItemIDUser: TIntegerField;
cdsSaleItemIDComission: TIntegerField;
cdsSaleItemIDInventoryMov: TIntegerField;
cdsSaleItemTax: TBCDField;
cdsSaleItemNotVerifyQty: TBooleanField;
cdsSaleItemIDDepartment: TIntegerField;
cdsSaleItemRequestCustomer: TBooleanField;
cdsSaleItemPuppyTracker: TBooleanField;
cdsSaleItemPromo: TBooleanField;
cdsSaleItemSellingPrice: TBCDField;
cdsSaleItemIDMovParent: TIntegerField;
cdsSalePayment: TClientDataSet;
cdsSalePaymentIDLancamento: TIntegerField;
cdsSalePaymentValorNominal: TBCDField;
cdsSalePaymentMeioPag: TStringField;
cdsSalePaymentTipo: TIntegerField;
cdsSalePaymentDataLancamento: TDateTimeField;
imgTimeClock: TImage;
lbTimeClock: TLabel;
tsTimeClock: TTabSheet;
Panel3: TPanel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
cxTimeStore: TcxLookupComboBox;
dtTimeStart: TDateBox;
dtTimeEnd: TDateBox;
btnTimeSearch: TBitBtn;
grdTimeClock: TcxGrid;
cxGridDBTimeClock: TcxGridDBTableView;
cxGridLevel3: TcxGridLevel;
cdsTimeClock: TClientDataSet;
dsTimeClock: TDataSource;
cdsTimeClockEnterDate: TDateTimeField;
cdsTimeClockExitDate: TDateTimeField;
cdsTimeClockWorkedHour: TDateTimeField;
cdsTimeClockWorkHourPay: TIntegerField;
cdsTimeClockWorkMunitPay: TBCDField;
cdsTimeClockPessoa: TStringField;
cdsTimeClockIDUser: TIntegerField;
cdsTimeClockStore: TStringField;
cxGridDBTimeClockPessoa: TcxGridDBColumn;
cxGridDBTimeClockStore: TcxGridDBColumn;
cxGridDBTimeClockEnterDate: TcxGridDBColumn;
cxGridDBTimeClockExitDate: TcxGridDBColumn;
cxGridDBTimeClockWorkedHour: TcxGridDBColumn;
cxGridDBTimeClockWorkHourPay: TcxGridDBColumn;
cxGridDBTimeClockWorkMunitPay: TcxGridDBColumn;
cxGridDBTimeClockIDUser: TcxGridDBColumn;
cdsTimeClockMarked: TBooleanField;
cxGridDBTimeClockMarked: TcxGridDBColumn;
btnMarkTime: TBitBtn;
cdsImportTime: TClientDataSet;
StringField1: TStringField;
DateTimeField1: TDateTimeField;
cdsImportTimeWorkedHour: TDateTimeField;
cdsQBCashRegMov: TClientDataSet;
dsQBCashRegMov: TDataSource;
cdsQBCashRegMovMarked: TBooleanField;
cdsQBCashRegMovIDCashRegMov: TIntegerField;
cdsQBCashRegMovOpenTime: TDateTimeField;
cdsQBCashRegMovTotalCash: TBCDField;
cdsQBCashRegMovGrandTotal: TCurrencyField;
grdSalesDBTableViewMarked: TcxGridDBColumn;
grdSalesDBTableViewTransNum: TcxGridDBColumn;
grdSalesDBTableViewOpenTime: TcxGridDBColumn;
grdSalesDBTableViewGrandTotal: TcxGridDBColumn;
cdsQBPayments: TClientDataSet;
cdsQBPaymentsIDMeioPag: TIntegerField;
cdsQBPaymentsMeioPag: TStringField;
cdsQBPaymentsAmount: TBCDField;
cdsQBCashRegMovCashRegister: TStringField;
grdSalesDBTableViewCashRegister: TcxGridDBColumn;
cdsQBCashRegMovTotalCheck: TBCDField;
cdsQBCashRegMovIDStore: TIntegerField;
cdsQBCashRegMovTransDate: TDateTimeField;
cdsQBCashRegMovTransNum: TStringField;
grdSalesDBTableViewTransDate: TcxGridDBColumn;
cdsQBCashRegItem: TClientDataSet;
cdsQBCashRegItemIDGroup: TIntegerField;
cdsQBCashRegItemCategory: TStringField;
cdsQBCashRegItemItemTotalSold: TBCDField;
cdsQBCashRegItemTax: TBCDField;
cdsQBCashRegMovTotalTax: TCurrencyField;
cdsQBCashRegMovTotalPetty: TBCDField;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lbExitClick(Sender: TObject);
procedure cdsInvoiceBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure btnSearchClick(Sender: TObject);
procedure Selectall1Click(Sender: TObject);
procedure UnSelectAll1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lbConfigClick(Sender: TObject);
procedure btnCompleteClick(Sender: TObject);
procedure cdsEntityBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure btnSearchCustomerClick(Sender: TObject);
procedure btnUpdateClick(Sender: TObject);
procedure cdsSalePaymentBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure cdsTimeClockBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure btnTimeSearchClick(Sender: TObject);
procedure cdsSaleItemBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure cdsQBCashRegMovBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure cdsQBPaymentsBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure cdsQBCashRegItemBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
private
FDMQuickBooks : TDMQuickBooks;
iCurrenctInvoice, iCurrenctIDPreSale, iCurrentIDCashRegMov : Integer;
function QuickBooksConnect : Boolean;
procedure ShowPanel(iOption: Integer);
procedure LoadValues;
procedure CreateItems;
procedure CreateCustomers;
procedure CreateSales;
procedure CreateRevMov;
procedure CreateTimeClock;
procedure OpenItems;
procedure CloseItems;
procedure OpenCustomer;
procedure CloseCustomer;
procedure OpenCashRegMov;
procedure CloseCashRegMov;
procedure GetTotalPayment(var APositive, ANegative : Currency);
procedure InsertTestMemoCredit;
public
function Start : Boolean;
end;
implementation
uses uMRSQLParam, uDateTimeFunctions, uFrmQuickBooksConfig, DateUtils,
uParamFunctions, ibqitem, uNumericfunctions;
{$R *.dfm}
{ TFrmQuickBooks }
function TFrmQuickBooks.Start: Boolean;
begin
Result := False;
if QuickBooksConnect then
begin
LoadValues;
ShowModal;
Result := True;
end;
end;
procedure TFrmQuickBooks.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
CloseItems;
CloseCustomer;
CloseCashRegMov;
FreeAndNil(FDMQuickBooks);
DMImportExport.CloseStore;
DMImportExport.ImportConn.Connected := False;
end;
procedure TFrmQuickBooks.lbExitClick(Sender: TObject);
begin
inherited;
ShowPanel(TLabel(Sender).Tag);
end;
procedure TFrmQuickBooks.ShowPanel(iOption: Integer);
begin
case iOption of
0 : Close;
1 : begin
pgOption.ActivePage := tsSale;
lbSelection.Caption := tsSale.Caption;
end;
2 : begin
pgOption.ActivePage := tsCustomer;
lbSelection.Caption := tsCustomer.Caption;
end;
3 : begin
OpenItems;
pgOption.ActivePage := tsItems;
lbSelection.Caption := tsItems.Caption;
end;
4 : begin
pgOption.ActivePage := tsTimeClock;
lbSelection.Caption := tsTimeClock.Caption;
end;
end;
end;
procedure TFrmQuickBooks.cdsInvoiceBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
inherited;
try
Param := TMRSQLParam.Create;
Param.AddKey('IDInvoice');
Param.KeyByName('IDInvoice').AsInteger := 0;
Param.KeyByName('IDInvoice').Condition := tcDifferent;
Param.AddKey('InvoiceDate');
Param.KeyByName('InvoiceDate').AsString := MyFormatDate(Trunc(dtStart.Date));
Param.KeyByName('InvoiceDate').Condition := tcGreaterThanEqual;
Param.KeyByName('InvoiceDate').Field := 'InvoiceDate';
Param.AddKey('InvoiceDate1');
Param.KeyByName('InvoiceDate1').AsString := MyFormatDate(Trunc(dtEnd.Date+1));
Param.KeyByName('InvoiceDate1').Condition := tcLessThan;
Param.KeyByName('InvoiceDate1').Field := 'InvoiceDate';
if cbxStore.EditValue > 0 then
begin
Param.AddKey('IDStore');
Param.KeyByName('IDStore').AsInteger := cbxStore.EditValue;
Param.KeyByName('IDStore').Condition := tcEquals;
Param.KeyByName('IDStore').Field := 'I.IDStore';
end;
OwnerData := Param.ParamString;
finally
FreeAndNil(Param);
end;
end;
procedure TFrmQuickBooks.btnSearchClick(Sender: TObject);
begin
inherited;
try
Screen.Cursor := crHourGlass;
CloseCashRegMov;
OpenCashRegMov;
grdSalesDBTableView.DataController.Groups.FullExpand;
{
with cdsInvoice do
begin
if Active then
Close;
Open;
end;
}
finally
Screen.Cursor := crDefault;
end;
end;
procedure TFrmQuickBooks.LoadValues;
begin
//dtStart.Date := InicioMes(Now);
//dtEnd.Date := FimMes(Now);
dtStart.Date := Trunc(Now);
dtEnd.Date := Trunc(Now);
dtTimeStart.Date := Trunc(InicioMes(Now));
dtTimeEnd.Date := Trunc(FimMes(Now));
grdSalesDBTableView.OptionsView.GroupByBox := False;
ShowPanel(1);
DMImportExport.ImportConn.Connected := True;
DMImportExport.OpenStore;
if DMImportExport.GetAppProperty('QuickBooks', 'SalesAcc') = '' then
lbConfigClick(Self);
end;
procedure TFrmQuickBooks.Selectall1Click(Sender: TObject);
var
cds : TClientDataSet;
begin
inherited;
if pgOption.ActivePage = tsSale then
begin
//cds := cdsInvoice;
cds := cdsQBCashRegMov;
end else if pgOption.ActivePage = tsTimeClock then
begin
cds := cdsTimeClock;
end;
with cds do
if Active then
try
DisableControls;
First;
while not EOF do
begin
if not FieldByName('Marked').AsBoolean then
begin
Edit;
FieldByName('Marked').AsBoolean := True;
Post;
end;
Next;
end;
finally
EnableControls;
end;
end;
procedure TFrmQuickBooks.UnSelectAll1Click(Sender: TObject);
var
cds : TClientDataSet;
begin
inherited;
if pgOption.ActivePage = tsSale then
begin
//cds := cdsInvoice;
cds := cdsQBCashRegMov;
end else if pgOption.ActivePage = tsTimeClock then
begin
cds := cdsTimeClock;
end;
with cds do
if Active then
try
DisableControls;
First;
while not EOF do
begin
if FieldByName('Marked').AsBoolean then
begin
Edit;
FieldByName('Marked').AsBoolean := False;
Post;
end;
Next;
end;
finally
EnableControls;
end;
end;
function TFrmQuickBooks.QuickBooksConnect: Boolean;
begin
with FDMQuickBooks do
begin
ConnectionMode := CON_TYPE_DONT_CARE;
ApplicationName := 'MainRetail';
CompanyFile := '';
Result := Connect;
end;
end;
procedure TFrmQuickBooks.FormCreate(Sender: TObject);
begin
inherited;
FDMQuickBooks := TDMQuickBooks.Create(Self);
end;
procedure TFrmQuickBooks.lbConfigClick(Sender: TObject);
begin
inherited;
with TFrmQuickBooksConfig.Create(Self) do
Start;
end;
procedure TFrmQuickBooks.CreateItems;
var
QBItem : TQBItem;
begin
QBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
try
Screen.Cursor := crHourGlass;
QBItem.SetConnectionStr(FDMQuickBooks.GetConnectionString);
QBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'SalesAcc');
pbExportSales.Visible := True;
Application.ProcessMessages;
OpenItems;
with cdsCategory do
begin
DisableControls;
First;
pbExportSales.Position := 0;
pbExportSales.Max := RecordCount;
while not EOF do
begin
QBItem.ItemName := Copy(FieldByName('Category').AsString, 0, 30);
QBItem.Desc := FieldByName('Category').AsString;
QBItem.SalesTaxCode := '';
QBItem.Price := 0;
QBItem.AddItem;
pbExportSales.Position := pbExportSales.Position + 1;
Application.ProcessMessages;
Next;
end;
First;
EnableControls;
end;
finally
pbExportSales.Visible := False;
FreeAndNil(QBItem);
Screen.Cursor := crDefault;
end;
end;
procedure TFrmQuickBooks.CloseItems;
begin
with cdsCategory do
if Active then
Close;
end;
procedure TFrmQuickBooks.OpenItems;
begin
with cdsCategory do
if not Active then
Open;
end;
procedure TFrmQuickBooks.btnCompleteClick(Sender: TObject);
begin
inherited;
try
btnComplete.Enabled := False;
if pgOption.ActivePage = tsItems then
begin
CreateItems;
end else if pgOption.ActivePage = tsCustomer then
begin
CreateCustomers;
end else if pgOption.ActivePage = tsSale then
begin
//CreateSales;
CreateRevMov;
end else if pgOption.ActivePage = tsTimeClock then
begin
CreateTimeClock;
end;
finally
btnComplete.Enabled := True;
end;
end;
procedure TFrmQuickBooks.cdsEntityBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
inherited;
try
Param := TMRSQLParam.Create;
Param.AddKey('P.Pessoa');
Param.KeyByName('P.Pessoa').AsString := edtCustomerName.Text;
Param.KeyByName('P.Pessoa').Condition := tcLikeStartWith;
OwnerData := Param.ParamString;
finally
FreeAndNil(Param);
end;
end;
procedure TFrmQuickBooks.btnSearchCustomerClick(Sender: TObject);
begin
inherited;
try
Screen.Cursor := crHourGlass;
CloseCustomer;
OpenCustomer;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TFrmQuickBooks.CreateTimeClock;
var
QBTimeClock : TQBTimeClock;
fDateTime : TDateTime;
begin
QBTimeClock := TQBTimeClock.Create(FDMQuickBooks.GetConnectionString);
try
Screen.Cursor := crHourGlass;
QBTimeClock.SetConnectionStr(FDMQuickBooks.GetConnectionString);
pbExportSales.Visible := True;
lbResult.Visible := False;
with cdsTimeClock do
begin
DisableControls;
First;
pbExportSales.Position := 0;
pbExportSales.Max := RecordCount;
Application.ProcessMessages;
try
cdsImportTime.CreateDataSet;
while not EOF do
begin
if FieldByName('Marked').AsBoolean then
begin
if not cdsImportTime.Locate('EnterDate', FormatDateTime('mm/dd/yyyy', FieldByName('EnterDate').AsDateTime), []) then
begin
cdsImportTime.Append;
fDateTime := Trunc(FieldByName('EnterDate').AsDateTime);
cdsImportTime.FieldByName('EnterDate').AsString := FormatDateTime('mm/dd/yyyy', fDateTime);
cdsImportTime.FieldByName('Pessoa').AsString := 'EMP_' + FieldByName('Pessoa').AsString;
cdsImportTime.FieldByName('WorkedHour').AsDateTime := FDMQuickBooks.AddHoursToDate(fDateTime, FormatDateTime('hh:mm', (FieldByName('WorkedHour').AsDatetime)));
end
else
begin
cdsImportTime.Edit;
cdsImportTime.FieldByName('WorkedHour').AsDateTime := FDMQuickBooks.AddHoursToDate(cdsImportTime.FieldByName('WorkedHour').AsDateTime, FormatDateTime('hh:mm', FieldByName('WorkedHour').AsDateTime));
end;
cdsImportTime.Post;
end;
pbExportSales.Position := pbExportSales.Position + 1;
Application.ProcessMessages;
Next;
end;
cdsImportTime.First;
pbExportSales.Position := 0;
pbExportSales.Max := cdsImportTime.RecordCount;
Application.ProcessMessages;
while not cdsImportTime.EOF do
begin
QBTimeClock.Employee := cdsImportTime.FieldByName('Pessoa').AsString;
QBTimeClock.TransDate := FormatDateTime('mm/dd/yyyy', cdsImportTime.FieldByName('EnterDate').AsDateTime);
QBTimeClock.Duration := FormatDateTime('hh:mm', cdsImportTime.FieldByName('WorkedHour').AsDateTime);
QBTimeClock.AddTimeClock;
pbExportSales.Position := pbExportSales.Position + 1;
Application.ProcessMessages;
cdsImportTime.Next;
end;
finally
cdsImportTime.Close;
end;
First;
EnableControls;
lbResult.Caption := IntToStr(pbExportSales.Max) + ' timeclock(s) exported to QuickBooks.';
lbResult.Visible := True;
end;
finally
pbExportSales.Visible := False;
FreeAndNil(QBTimeClock);
Screen.Cursor := crDefault;
end;
end;
procedure TFrmQuickBooks.CreateCustomers;
var
QBCustomer : TQBCustomer;
begin
QBCustomer := TQBCustomer.Create(FDMQuickBooks.GetConnectionString);
try
Screen.Cursor := crHourGlass;
QBCustomer.SetConnectionStr(FDMQuickBooks.GetConnectionString);
pbExportSales.Visible := True;
with cdsEntity do
begin
DisableControls;
First;
pbExportSales.Position := 0;
pbExportSales.Max := RecordCount;
Application.ProcessMessages;
while not EOF do
begin
QBCustomer.CustomerName := FieldByName('Pessoa').AsString;
QBCustomer.Address := FieldByName('Address').AsString;
QBCustomer.City := FieldByName('City').AsString;
QBCustomer.State := FieldByName('State').AsString;
QBCustomer.Zip := FieldByName('Zip').AsString;
QBCustomer.ContactName := FieldByName('Contact').AsString;
QBCustomer.Country := FieldByName('Country').AsString;
QBCustomer.Phone := FieldByName('PhoneAreaCode').AsString + ' ' + FieldByName('Telefone').AsString;
QBCustomer.Fax := FieldByName('Fax').AsString;
QBCustomer.Email := FieldByName('Email').AsString;
QBCustomer.AddCustomer;
pbExportSales.Position := pbExportSales.Position + 1;
Application.ProcessMessages;
Next;
end;
First;
EnableControls;
end;
finally
pbExportSales.Visible := False;
FreeAndNil(QBCustomer);
Screen.Cursor := crDefault;
end;
end;
procedure TFrmQuickBooks.CloseCustomer;
begin
with cdsEntity do
if Active then
Close;
end;
procedure TFrmQuickBooks.OpenCustomer;
begin
with cdsEntity do
if not Active then
Open;
end;
procedure TFrmQuickBooks.btnUpdateClick(Sender: TObject);
var
P : TPoint;
begin
inherited;
GetCursorPos(P);
popSelection.Popup(P.X, P.Y);
end;
procedure TFrmQuickBooks.CreateSales;
var
iSalesImported : Integer;
FQBInvoice : TQBInvoice;
FQBItem : TQBItem;
FQBPayment : TQBPayment;
FAccount : String;
begin
{
lbResult.Visible := False;
with cdsInvoice do
if not Active then
ShowMessage('No sale to export')
else
try
DisableControls;
lbResult.Visible := False;
pbExportSales.Visible := True;
Application.ProcessMessages;
Screen.Cursor := crHourGlass;
First;
pbExportSales.Position := 0;
pbExportSales.Max := RecordCount;
iSalesImported := 0;
FQBInvoice := TQBInvoice.Create(FDMQuickBooks.GetConnectionString);
try
while not EOF do
begin
if FieldByName('Marked').AsBoolean then
begin
if FieldByName('Customer').AsString <> '' then
FQBInvoice.CustomerName := FieldByName('Customer').AsString
else
FQBInvoice.CustomerName := 'None';
FQBInvoice.City := FieldByName('City').AsString;
FQBInvoice.Country := FieldByName('Country').AsString;
FQBInvoice.Address := FieldByName('Address').AsString;
FQBInvoice.ContactName := FieldByName('Contact').AsString;
FQBInvoice.Phone := FieldByName('PhoneAreaCode').AsString + ' ' +FieldByName('Telefone').AsString;
FQBInvoice.Fax := FieldByName('Fax').AsString;
FQBInvoice.Email := FieldByName('Email').AsString;
FQBInvoice.Zip := FieldByName('Zip').AsString;
FQBInvoice.State := FieldByName('State').AsString;
FQBInvoice.TransactionDate := FormatDateTime('mm/dd/yyyy', FieldByName('InvoiceDate').AsDateTime);
FQBInvoice.RefNumber := FieldByName('AccInvoiceNumber').AsString;
iCurrenctInvoice := FieldByName('IDInvoice').AsInteger;
iCurrenctIDPreSale := FieldByName('IDPreSale').AsInteger;
if (FieldByName('TotalInvoice').AsCurrency > 0) then
FAccount := DMImportExport.GetAppProperty('QuickBooks', 'SalesAcc')
else
FAccount := DMImportExport.GetAppProperty('QuickBooks', 'RefoundAcc');
try
cdsSaleItem.Open;
cdsSaleItem.First;
while not cdsSaleItem.EOF do
begin
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := Copy(cdsSaleItem.FieldByName('Category').AsString, 0, 30);
FQBItem.Desc := cdsSaleItem.FieldByName('Category').AsString;
FQBItem.Price := ABS(cdsSaleItem.FieldByName('ItemTotalSold').AsCurrency);
FQBItem.Qty := ABS(cdsSaleItem.FieldByName('Qty').AsFloat);
FQBItem.Account := FAccount;
FQBInvoice.SaleItems.Add(FQBItem);
cdsSaleItem.Next;
end;
//Criar um produto chamado Tax, pois o invoice esta ficand com diferenca
if (not cdsSaleItem.IsEmpty) and (FieldByName('Tax').AsCurrency <> 0) then
begin
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := 'Sale Tax';
FQBItem.Desc := 'Sale Tax';
FQBItem.Price := ABS(FieldByName('Tax').AsCurrency);
FQBItem.Account := FAccount;
FQBItem.Qty := 1;
FQBInvoice.SaleItems.Add(FQBItem);
end;
finally
cdsSaleItem.Close;
end;
try
cdsSalePayment.Open;
cdsSalePayment.First;
while not cdsSalePayment.EOF do
begin
FQBPayment := TQBPayment.Create(FDMQuickBooks.GetConnectionString);
FQBPayment.PaymentMethod := cdsSalePayment.FieldByName('MeioPag').AsString;
FQBPayment.TransactionDate := FormatDateTime('mm/dd/yyyy', cdsSalePayment.FieldByName('DataLancamento').AsDateTime);
FQBPayment.Amount := ABS(cdsSalePayment.FieldByName('ValorNominal').AsCurrency);
FQBPayment.DefaulPayment := DMImportExport.GetAppProperty('QuickBooks', 'PaymentMethod');
FQBPayment.CustomerName := FQBInvoice.CustomerName;
FQBPayment.RefNumber := FQBInvoice.RefNumber;
FQBInvoice.Payments.Add(FQBPayment);
cdsSalePayment.Next;
end;
finally
cdsSalePayment.Close;
end;
FQBInvoice.Add;
inc(iSalesImported);
end;
pbExportSales.Position := pbExportSales.Position + 1;
Application.ProcessMessages;
Next;
end;
finally
FreeAndNil(FQBInvoice);
end;
lbResult.Caption := IntToStr(iSalesImported) + ' transaction(s) exported to QuickBooks.';
lbResult.Visible := True;
finally
Screen.Cursor := crDefault;
pbExportSales.Visible := False;
Application.ProcessMessages;
EnableControls;
end;
}
end;
procedure TFrmQuickBooks.cdsSalePaymentBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
inherited;
try
Param := TMRSQLParam.Create;
Param.AddKey('L.IDPreSale');
Param.KeyByName('L.IDPreSale').AsInteger := iCurrenctIDPreSale;
Param.KeyByName('L.IDPreSale').Condition := tcEquals;
OwnerData := Param.ParamString;
finally
FreeAndNil(Param);
end;
end;
procedure TFrmQuickBooks.cdsTimeClockBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
inherited;
try
Param := TMRSQLParam.Create;
Param.AddKey('P.Desativado');
Param.KeyByName('P.Desativado').AsInteger := 0;
Param.KeyByName('P.Desativado').Condition := tcEquals;
Param.AddKey('EnterDate');
Param.KeyByName('EnterDate').AsString := MyFormatDate(Trunc(dtTimeStart.Date));
Param.KeyByName('EnterDate').Condition := tcGreaterThanEqual;
Param.KeyByName('EnterDate').Field := 'TC.EnterDate';
Param.AddKey('EnterDate1');
Param.KeyByName('EnterDate1').AsString := MyFormatDate(Trunc(dtTimeEnd.Date+1));
Param.KeyByName('EnterDate1').Condition := tcLessThan;
Param.KeyByName('EnterDate1').Field := 'TC.EnterDate';
Param.AddKey('ExitDate');
Param.KeyByName('ExitDate').AsString := '';
Param.KeyByName('ExitDate').Condition := tcDifferent;
Param.KeyByName('ExitDate').Field := 'TC.ExitDate';
if cxTimeStore.EditValue > 0 then
begin
Param.AddKey('IDStore');
Param.KeyByName('IDStore').AsInteger := cxTimeStore.EditValue;
Param.KeyByName('IDStore').Condition := tcEquals;
Param.KeyByName('IDStore').Field := 'TC.IDStore';
end;
OwnerData := Param.ParamString;
finally
FreeAndNil(Param);
end;
end;
procedure TFrmQuickBooks.btnTimeSearchClick(Sender: TObject);
begin
inherited;
try
Screen.Cursor := crHourGlass;
with cdsTimeClock do
begin
if Active then
Close;
Open;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TFrmQuickBooks.cdsSaleItemBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
inherited;
try
Param := TMRSQLParam.Create;
Param.AddKey('IM.DocumentID');
Param.KeyByName('IM.DocumentID').AsInteger := iCurrenctInvoice;
Param.KeyByName('IM.DocumentID').Condition := tcEquals;
OwnerData := Param.ParamString;
finally
FreeAndNil(Param);
end;
end;
procedure TFrmQuickBooks.cdsQBCashRegMovBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
inherited;
try
Param := TMRSQLParam.Create;
Param.AddKey('CRMDate');
Param.KeyByName('CRMDate').AsString := MyFormatDate(Trunc(dtStart.Date));
Param.KeyByName('CRMDate').Condition := tcGreaterThanEqual;
Param.KeyByName('CRMDate').Field := 'CRM.OpenTime';
Param.AddKey('CRMDate1');
Param.KeyByName('CRMDate1').AsString := MyFormatDate(Trunc(dtEnd.Date+1));
Param.KeyByName('CRMDate1').Condition := tcLessThan;
Param.KeyByName('CRMDate1').Field := 'CRM.OpenTime';
if cbxStore.EditValue > 0 then
begin
Param.AddKey('IDStore');
Param.KeyByName('IDStore').AsInteger := cbxStore.EditValue;
Param.KeyByName('IDStore').Condition := tcEquals;
Param.KeyByName('IDStore').Field := 'I.IDStore';
end;
OwnerData := Param.ParamString;
finally
FreeAndNil(Param);
end;
end;
procedure TFrmQuickBooks.CloseCashRegMov;
begin
with cdsQBCashRegMov do
if Active then
Close;
end;
procedure TFrmQuickBooks.OpenCashRegMov;
begin
with cdsQBCashRegMov do
if not Active then
Open;
end;
procedure TFrmQuickBooks.CreateRevMov;
var
iSalesImported : Integer;
FQBSales : TQBSales;
FQBCreditMemo : TQBCreditMemo;
FQBItem : TQBItem;
FQBPayment : TQBPayment;
FAccount, sColumn : String;
cPositivePayment, cNegativePayment : Currency;
FTransDate : TDateTime;
begin
lbResult.Visible := False;
with cdsQBCashRegMov do
if not Active then
ShowMessage('No sale to export')
else
try
DisableControls;
lbResult.Visible := False;
pbExportSales.Visible := True;
Application.ProcessMessages;
Screen.Cursor := crHourGlass;
First;
pbExportSales.Position := 0;
pbExportSales.Max := RecordCount;
iSalesImported := 0;
sColumn := DMImportExport.GetAppProperty('QuickBooks', 'PaymentColumns');
while not EOF do
begin
if FieldByName('Marked').AsBoolean then
begin
//Sales Header
if (FQBSales = nil) then
begin
FQBSales := TQBSales.Create(FDMQuickBooks.GetConnectionString);
FQBSales.CustomerName := 'MRSale';
FQBSales.TransactionDate := FormatDateTime('mm/dd/yyyy', FieldByName('OpenTime').AsDateTime);
FQBSales.RefNumber := 'MR' + FieldByName('TransNum').AsString;
end;
iCurrentIDCashRegMov := FieldByName('IDCashRegMov').AsInteger;
GetTotalPayment(cPositivePayment, cNegativePayment);
//Credit Memo Header
if (cNegativePayment <> 0) and (FQBCreditMemo = nil) then
begin
FQBCreditMemo := TQBCreditMemo.Create(FDMQuickBooks.GetConnectionString);
FQBCreditMemo.CustomerName := 'MRSale';
FQBCreditMemo.TransactionDate := FormatDateTime('mm/dd/yyyy', FieldByName('OpenTime').AsDateTime);
FQBCreditMemo.RefNumber := 'CM' + FieldByName('TransNum').AsString;
end;
//Items
try
cdsQBCashRegItem.Open;
cdsQBCashRegItem.First;
if FQBSales <> nil then
begin
while not cdsQBCashRegItem.EOF do
begin
FQBSales.AppendPayment(cdsQBCashRegItem.FieldByName('Category').AsString,
DMImportExport.GetAppProperty('QuickBooks', 'SalesAcc'),
MyRound(cdsQBCashRegItem.FieldByName('ItemTotalSold').AsCurrency, 2),
1, itNonInventory);
cdsQBCashRegItem.Next;
end;
FQBSales.AppendPayment('SalesTax',
DMImportExport.GetAppProperty('QuickBooks', 'SalesAcc'),
FieldByName('TotalTax').AsCurrency, 1, itNonInventory);
if FieldByName('TotalPetty').AsCurrency <> 0 then
FQBSales.AppendPayment('PettyCash',
DMImportExport.GetAppProperty('QuickBooks', 'SalesAcc'),
(FieldByName('TotalPetty').AsCurrency * -1), 1, itNonInventory);
end;
finally
cdsQBCashRegItem.Close;
end;
//Item Payments
try
//Cash Payment
if FieldByName('TotalCash').AsCurrency > 0 then
begin
if FQBSales <> nil then
FQBSales.AppendPayment(ParseParam(sColumn, 'Cash'),
DMImportExport.GetAppProperty('QuickBooks', 'PaymentMethod'),
(FieldByName('TotalCash').AsCurrency * -1),
1, itPayment);
end;
//Check Payment
if FieldByName('TotalCheck').AsCurrency > 0 then
begin
if FQBSales <> nil then
FQBSales.AppendPayment(ParseParam(sColumn, 'Check'),
DMImportExport.GetAppProperty('QuickBooks', 'PaymentMethod'),
(FieldByName('TotalCheck').AsCurrency * -1),
1, itPayment);
end;
cdsQBPayments.First;
while not cdsQBPayments.EOF do
begin
if (cdsQBPayments.FieldByName('Amount').AsCurrency > 0) then
begin
if FQBSales <> nil then
FQBSales.AppendPayment(ParseParam(sColumn, cdsQBPayments.FieldByName('MeioPag').AsString),
DMImportExport.GetAppProperty('QuickBooks', 'PaymentMethod'),
(cdsQBPayments.FieldByName('Amount').AsCurrency * -1),
1, itPayment);
end
else if (cdsQBPayments.FieldByName('Amount').AsCurrency < 0) then
begin
//Add a positive product to zero the invoice
if (FQBCreditMemo <> nil) then
begin
FQBCreditMemo.AppendCreditMemo('MRItemAdjust',
DMImportExport.GetAppProperty('QuickBooks', 'RefoundAcc'),
ABS(cdsQBPayments.FieldByName('Amount').AsCurrency),
1, itNonInventory);
FQBCreditMemo.AppendCreditMemo(ParseParam(sColumn, cdsQBPayments.FieldByName('MeioPag').AsString),
DMImportExport.GetAppProperty('QuickBooks', 'RefoundAcc'),
cdsQBPayments.FieldByName('Amount').AsCurrency,
1, itPayment);
end;
end;
cdsQBPayments.Next;
end;
finally
cdsQBPayments.Close;
end;
end;
pbExportSales.Position := pbExportSales.Position + 1;
Application.ProcessMessages;
FTransDate := FieldByName('TransDate').AsDateTime;
Next;
if cdsQBCashRegMov.EOF or (FTransDate <> FieldByName('TransDate').AsDateTime) then
begin
if (FQBSales <> nil) then
begin
FQBSales.CreateItemAdjust('MRItemAdjust', DMImportExport.GetAppProperty('QuickBooks', 'SalesAcc'));
FQBSales.Add;
FreeAndNil(FQBSales);
inc(iSalesImported);
end;
if (FQBCreditMemo <> nil) then
begin
FQBCreditMemo.Add;
FreeAndNil(FQBCreditMemo);
end;
end;
end;
lbResult.Caption := IntToStr(iSalesImported) + ' transaction(s) exported to QuickBooks.';
lbResult.Visible := True;
finally
Screen.Cursor := crDefault;
pbExportSales.Visible := False;
Application.ProcessMessages;
EnableControls;
end;
{
if FieldByName('Marked').AsBoolean then
begin
FQBSales := TQBSales.Create(FDMQuickBooks.GetConnectionString);
try
FQBSales.CustomerName := 'MRSale';
FQBSales.TransactionDate := FormatDateTime('mm/dd/yyyy', FieldByName('OpenTime').AsDateTime);
FQBSales.RefNumber := 'MR' + FieldByName('IDCashRegMov').AsString;
iCurrentIDCashRegMov := FieldByName('IDCashRegMov').AsInteger;
GetTotalPayment(cPositivePayment, cNegativePayment);
if (cNegativePayment <> 0) then
begin
FQBCreditMemo := TQBCreditMemo.Create(FDMQuickBooks.GetConnectionString);
FQBCreditMemo.CustomerName := 'MRSale';
FQBCreditMemo.TransactionDate := FormatDateTime('mm/dd/yyyy', FieldByName('OpenTime').AsDateTime);
FQBCreditMemo.RefNumber := 'CM' + FieldByName('IDCashRegMov').AsString;
end;
//Item
if cPositivePayment <> 0 then
begin
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := 'MRProduct';
FQBItem.Desc := 'MRProduct';
FQBItem.Price := cPositivePayment;
FQBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'SalesAcc');
FQBItem.Qty := 1;
FQBSales.SaleItems.Add(FQBItem);
end;
//Payments
try
//Cash Payment
if FieldByName('TotalCash').AsCurrency > 0 then
begin
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := 'Cash';
FQBItem.Desc := 'Cash';
FQBItem.Price := FieldByName('TotalCash').AsCurrency * -1;
FQBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'PaymentMethod');
FQBItem.Qty := 1;
FQBItem.ItemType := itPayment;
FQBSales.SaleItems.Add(FQBItem);
end;
//Check Payment
if FieldByName('TotalCheck').AsCurrency > 0 then
begin
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := 'Check';
FQBItem.Desc := 'Check';
FQBItem.Price := FieldByName('TotalCheck').AsCurrency * -1;
FQBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'PaymentMethod');
FQBItem.Qty := 1;
FQBItem.ItemType := itPayment;
FQBSales.SaleItems.Add(FQBItem);
end;
cdsQBPayments.First;
while not cdsQBPayments.EOF do
begin
if (cdsQBPayments.FieldByName('Amount').AsCurrency > 0) then
begin
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := ParseParam(sColumn, cdsQBPayments.FieldByName('MeioPag').AsString);
FQBItem.Desc := ParseParam(sColumn, cdsQBPayments.FieldByName('MeioPag').AsString);
FQBItem.Price := cdsQBPayments.FieldByName('Amount').AsCurrency * -1;
FQBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'PaymentMethod');
FQBItem.Qty := 1;
FQBItem.ItemType := itPayment;
FQBSales.SaleItems.Add(FQBItem);
end
else if (cdsQBPayments.FieldByName('Amount').AsCurrency < 0) then
begin
//Add a positive product to zero the invoice
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := 'MRProduct';
FQBItem.Desc := 'MRProduct';
FQBItem.Price := ABS(cdsQBPayments.FieldByName('Amount').AsCurrency);
FQBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'RefoundAcc');
FQBItem.Qty := 1;
if (FQBCreditMemo <> nil) then
FQBCreditMemo.SaleItems.Add(FQBItem);
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := ParseParam(sColumn, cdsQBPayments.FieldByName('MeioPag').AsString);
FQBItem.Desc := ParseParam(sColumn, cdsQBPayments.FieldByName('MeioPag').AsString);
FQBItem.Price := cdsQBPayments.FieldByName('Amount').AsCurrency;
FQBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'RefoundAcc');
FQBItem.Qty := 1;
if (FQBCreditMemo <> nil) then
FQBCreditMemo.SaleItems.Add(FQBItem);
end;
cdsQBPayments.Next;
end;
finally
cdsQBPayments.Close;
end;
FQBSales.Add;
if (FQBCreditMemo <> nil) then
FQBCreditMemo.Add;
inc(iSalesImported);
finally
FreeAndNil(FQBSales);
if (FQBCreditMemo <> nil) then
FreeAndNil(FQBCreditMemo);
end;
end;
}
end;
procedure TFrmQuickBooks.cdsQBPaymentsBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
inherited;
try
Param := TMRSQLParam.Create;
Param.AddKey('L.IDCashRegMov');
Param.KeyByName('L.IDCashRegMov').AsInteger := iCurrentIDCashRegMov;
Param.KeyByName('L.IDCashRegMov').Condition := tcEquals;
OwnerData := Param.ParamString;
finally
FreeAndNil(Param);
end;
end;
procedure TFrmQuickBooks.GetTotalPayment(var APositive, ANegative : Currency);
begin
APositive := 0;
ANegative := 0;
if cdsQBCashRegMov.FieldByName('TotalCash').AsCurrency > 0 then
APositive := cdsQBCashRegMov.FieldByName('TotalCash').AsCurrency
else
ANegative := cdsQBCashRegMov.FieldByName('TotalCash').AsCurrency;
if cdsQBCashRegMov.FieldByName('TotalCheck').AsCurrency > 0 then
APositive := APositive + cdsQBCashRegMov.FieldByName('TotalCheck').AsCurrency
else
ANegative := ANegative + cdsQBCashRegMov.FieldByName('TotalCheck').AsCurrency;
cdsQBPayments.Open;
cdsQBPayments.First;
while not cdsQBPayments.EOF do
begin
if cdsQBPayments.FieldByName('Amount').AsCurrency > 0 then
APositive := APositive + cdsQBPayments.FieldByName('Amount').AsCurrency
else
ANegative := ANegative - ABS(cdsQBPayments.FieldByName('Amount').AsCurrency);
cdsQBPayments.Next;
end;
end;
procedure TFrmQuickBooks.InsertTestMemoCredit;
var
FQBCreditMemo : TQBCreditMemo;
FQBItem : TQBItem;
begin
{
FQBCreditMemo := TQBCreditMemo.Create(FDMQuickBooks.GetConnectionString);
try
FQBCreditMemo.CustomerName := 'MRSale';
FQBCreditMemo.TransactionDate := FormatDateTime('mm/dd/yyyy', Now);
FQBCreditMemo.RefNumber := 'XXX001';
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := 'MRProduct';
FQBItem.Desc := 'MRProduct';
FQBItem.Price := ABS(-5);
FQBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'RefoundAcc');
FQBItem.Qty := 1;
FQBCreditMemo.SaleItems.Add(FQBItem);
FQBItem := TQBItem.Create(FDMQuickBooks.GetConnectionString);
FQBItem.ItemName := 'Visa';
FQBItem.Desc := 'Visa';
FQBItem.Price := -5;
FQBItem.Account := DMImportExport.GetAppProperty('QuickBooks', 'RefoundAcc');
FQBItem.Qty := 1;
FQBCreditMemo.SaleItems.Add(FQBItem);
FQBCreditMemo.Add;
finally
FreeAndNil(FQBCreditMemo);
end;
}
end;
procedure TFrmQuickBooks.cdsQBCashRegItemBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
inherited;
try
Param := TMRSQLParam.Create;
Param.AddKey('I.CashRegMovID');
Param.KeyByName('I.CashRegMovID').AsInteger := iCurrentIDCashRegMov;
Param.KeyByName('I.CashRegMovID').Condition := tcEquals;
OwnerData := Param.ParamString;
finally
FreeAndNil(Param);
end;
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Edit, FMX.Controls.Presentation, IPPeerClient, IPPeerServer,
System.Tether.Manager, System.Tether.AppProfile;
type
TMainForm = class(TForm)
ToolBar1: TToolBar;
edtResult: TEdit;
lblTitle: TLabel;
TetheringManager1: TTetheringManager;
TetheringAppProfile1: TTetheringAppProfile;
ClearEditButton1: TClearEditButton;
StyleBook1: TStyleBook;
butExit: TButton;
procedure TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
procedure ClearEditButton1Click(Sender: TObject);
procedure butExitClick(Sender: TObject);
private
{ Private declarations }
procedure SetClipboard(s: string);
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
{$R *.Macintosh.fmx MACOS}
{$R *.Windows.fmx MSWINDOWS}
uses FMX.Platform;
procedure TMainForm.butExitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TMainForm.ClearEditButton1Click(Sender: TObject);
begin
edtResult.Text := '';
SetClipboard(edtResult.Text);
end;
procedure TMainForm.SetClipboard(s: string);
var
Svc: IFMXClipboardService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, Svc) then
Svc.SetClipboard(s);
end;
procedure TMainForm.TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
begin
if AResource.Hint = 'Barcode' then
begin
edtResult.Text := AResource.Value.AsString;
SetClipboard(edtResult.Text);
end;
end;
end.
|
unit unBanco;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, unModelBase;
type
{ TBanco }
TBanco = class(TModelBase)
private
FCodigoBanco: integer;
FNomeBanco: string;
procedure SetCodigoBanco(AValue: integer);
procedure SetNomeBanco(AValue: string);
public
property CodigoBanco: integer read FCodigoBanco write SetCodigoBanco;
property NomeBanco: string read FNomeBanco write SetNomeBanco;
end;
implementation
{ TBanco }
procedure TBanco.SetCodigoBanco(AValue: integer);
begin
if FCodigoBanco=AValue then Exit;
FCodigoBanco:=AValue;
end;
procedure TBanco.SetNomeBanco(AValue: string);
begin
if FNomeBanco=AValue then Exit;
FNomeBanco:=AValue;
end;
end.
|
unit DSA.Sorts.SelectionSort;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.Comparer,
DSA.Utils;
type
{ TSelectionSort }
generic TSelectionSort<T> = class
private
type
TArr_T = specialize TArray<T>;
ICmp_T = specialize IDSA_Comparer<T>;
public
class procedure Sort(var arr: TArr_T; cmp: ICmp_T);
end;
procedure Main;
implementation
type
{ TStudent }
TStudent = class
type
{ TComparer }
TComparer = class(TInterfacedObject, specialize IDSA_Comparer<TStudent>)
public
constructor Default;
function Compare(const Left, Right: TStudent): integer;
end;
var
Name: string;
Score: integer;
constructor Create(newName: string; newScore: integer);
function ToString: string; override;
end;
TSelectionSort_int = specialize TSelectionSort<integer>;
TSelectionSort_TStudent = specialize TSelectionSort<TStudent>;
TArr_student = specialize TArray<TStudent>;
procedure Main;
var
arr: TArray_int;
n: integer;
SortTestHelper: TSortTestHelper_int;
studentArr: TArr_student;
i: integer;
ts: TSelectionSort_int;
begin
n := 10000;
ts := TSelectionSort_int.Create;
SortTestHelper := TSortTestHelper_int.Create;
arr := SortTestHelper.GenerateRandomArray(n, n);
SortTestHelper.TestSort('SelectionSort', arr, @ts.Sort);
SetLength(studentArr, 4);
studentArr := [TStudent.Create('D', 90), TStudent.Create('C', 100),
TStudent.Create('B', 95), TStudent.Create('A', 95)];
TSelectionSort_TStudent.Sort(studentArr, TStudent.TComparer.Default);
for i := 0 to Length(studentArr) - 1 do
Writeln(studentArr[i].ToString);
ts.Free;
end;
{ TStudent.TComparer }
constructor TStudent.TComparer.Default;
begin
inherited Create;
end;
function TStudent.TComparer.Compare(const Left, Right: TStudent): integer;
var
bool: integer;
begin
if Left.Score = Right.Score then
bool := 0
else if Left.Score < Right.Score then
bool := -1
else
bool := 1;
Result := bool;
end;
constructor TStudent.Create(newName: string; newScore: integer);
begin
Name := newName;
Score := newScore;
end;
function TStudent.ToString: string;
var
sb: TStringBuilder;
begin
sb := TStringBuilder.Create;
sb.Append('Student: ').Append(Name).Append(' ').Append(Score);
Result := sb.ToString;
end;
{ TSelectionSort }
class procedure TSelectionSort.Sort(var arr: TArr_T; cmp: ICmp_T);
procedure __swap(var a, b: T);
var
tmp: T;
begin
tmp := a;
a := b;
b := tmp;
end;
var
i, j: integer;
minIndex: integer;
begin
for i := 0 to Length(arr) - 1 do
begin
minIndex := i;
for j := i to Length(arr) - 1 do
begin
if cmp.Compare(arr[minIndex], arr[j]) > 0 then
minIndex := j;
end;
__swap(arr[i], arr[minIndex]);
end;
end;
end.
|
unit uDlgSelectObjectsForDocs;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBASE_SelectForm, Menus, cxLookAndFeelPainters, StdCtrls,
cxButtons, ExtCtrls, cxClasses, dxRibbon, cxControls, uFrameBaseGrid,
uFrameObjectsByProps, cxSplitter, uFrameObjectList, uFrameObjectReestr,
dxBar, ActnList, DB, ADODB, Grids, DBGrids;
type
TIdItem = class(TCollectionItem)
private
FValue: integer;
FViewID: variant;
FStatusID: variant;
FOrgFrom: variant;
FOrgTo: variant;
public
property Value: integer read FValue write FValue;
property ViewID: variant read FViewID write FViewID;
property StatusID: variant read FStatusID write FStatusID;
property OrgFrom: variant read FOrgFrom write FOrgFrom;
property OrgTo: variant read FOrgTo write FOrgTo;
end;
TIdCollection = class(TCollection)
private
function GetItems(Index: integer): TIdItem;
public
property Items[Index: integer]: TIdItem read GetItems; default;
function Add(id: integer; AViewID: variant; AStatusID: variant; AOrgFrom: variant; AOrgTo: variant): TIdItem;
function Exists(id: integer): boolean;
procedure Delete(id: integer);
function IdIndex(id: integer): integer;
end;
TdlgSelectObjectsForDocs = class(TBASE_SelectForm)
cxSplitter: TcxSplitter;
FrameObjectsByProps: TFrameObjectsByProps;
BarManagerRecordsAction: TdxBarManager;
BarRecordsAction: TdxBar;
bbAddRecord: TdxBarButton;
bbDeleteDecord: TdxBarButton;
RecordsActionDeleteBar: TdxBar;
alRecordsAction: TActionList;
actAddRecord: TAction;
actRemoveRecord: TAction;
pnlCaption: TPanel;
qryView: TADOQuery;
dsView: TDataSource;
dsStatus: TDataSource;
qryStatus: TADOQuery;
FrameObjectReestr: TFrameObjectReestr;
dsOrg: TDataSource;
qryOrg: TADOQuery;
procedure actAddRecordExecute(Sender: TObject);
procedure actRemoveRecordExecute(Sender: TObject);
procedure actRemoveRecordUpdate(Sender: TObject);
procedure actAddRecordUpdate(Sender: TObject);
procedure FrameObjectsByPropsspObjectListAfterPost(DataSet: TDataSet);
procedure btnOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FViewIDDef: variant;
FStatusIDDef: variant;
{ Private declarations }
protected
procedure AddObjectById(ObjectID: integer);
public
SelectedIDs: TIdCollection;
property ViewIDDef: variant read FViewIDDef write FViewIDDef;
property StatusIDDef: variant read FStatusIDDef write FStatusIDDef;
procedure ApplyParamsAfterOpen; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
dlgSelectObjects: TdlgSelectObjectsForDocs;
implementation
uses cxGridCustomView, cxGridDBDataDefinitions, cxGridDBBandedTableView,
uMain, uCommonUtils, uUserBook, cxtCustomDataSourceM, cxTableViewCds, cxDBLookupComboBox, cxGridCustomTableView;
{$R *.dfm}
{ TIdCollection }
function TIdCollection.Add(id: integer; AViewID: variant; AStatusID: variant; AOrgFrom: variant; AOrgTo: variant): TIdItem;
begin
result:=TIdItem(inherited Add);
result.Value:=id;
result.FViewID:=AViewID;
result.FStatusID:=AStatusID;
result.OrgFrom:=AOrgFrom;
result.OrgTo:=AOrgTo;
end;
procedure TIdCollection.Delete(id: integer);
begin
inherited Delete(IdIndex(id));
end;
function TIdCollection.Exists(id: integer): boolean;
begin
result:=IdIndex(id)<>-1
end;
function TIdCollection.GetItems(Index: integer): TIdItem;
begin
result:=TIdItem(inherited Items[Index]);
end;
function TIdCollection.IdIndex(id: integer): integer;
var
i: integer;
begin
result:=-1;
for i:=0 to Count-1 do
if Items[i].Value=id then begin
result:=i;
exit;
end;
end;
{ TdlgSelectObjectsForDocs }
constructor TdlgSelectObjectsForDocs.Create(AOwner: TComponent);
begin
inherited;
self.FrameObjectsByProps.OpenEmptyData;
SelectedIDs:=TIdCollection.Create(TIdItem);
qryView.Open;
qryStatus.Open;
qryOrg.Open;
end;
procedure TdlgSelectObjectsForDocs.actAddRecordExecute(Sender: TObject);
var
id, i: integer;
ac: TControl;
gv: TcxCustomGridView;
f: TField;
ds: TDataSet;
sr: TViewSelectedRecords;
// csr: TCashViewSelectedRecords;
dsc: TcxtCustomDataSourceM;
begin
inherited;
id:=-1;
sr:=nil;
// csr:=nil;
if self.FrameObjectReestr.NavBar.ActiveGroupIndex=1 then begin
ac:=ActiveControl;
{ if Assigned(ac) and (ac is TcxGridSite) then begin
gv:=(ac as TcxGridSite).GridView;
ds:=(gv.DataController as TcxGridDBDataController).DataSource.DataSet;
f:=ds.Fields.FindField('вк_Свойства');
if Assigned(f) then
sr:=TViewSelectedRecords.Create(gv as TcxGridDBBandedTableView, 'вк_Свойства');
end;}
//переход на Андрюху
if Assigned(ac) and (ac is TcxGridSite) then begin
gv:=(ac as TcxGridSite).GridView;
dsc:=(gv.DataController as TcxGridDataControllerCds).CashDataSource;
if Assigned(dsc.FindField('вк_Свойства')) then
sr:=TViewSelectedRecords.Create(gv as TcxGridBandedTableViewCds, 'вк_Свойства');
end;
end;
if (FrameObjectReestr.NavBar.ActiveGroupIndex=0) and Assigned(FrameObjectReestr.FrameByProps) then begin
dsc:=FrameObjectReestr.FrameByProps.DataSourceCash;
if dsc.Active then
sr:=TViewSelectedRecords.Create(FrameObjectReestr.FrameByProps.ViewCds);
// csr:=TCashViewSelectedRecords.Create(FrameObjectReestr.FrameByProps.ViewCds);
{ ds:=FrameObjectReestr.FrameByProps.spObjectList;
if ds.Active then
sr:=TViewSelectedRecords.Create(FrameObjectReestr.FrameByProps.View);}
end;
if Assigned(sr) then begin
for i:=0 to sr.Count-1 do
AddObjectById(sr.Items[i].PrimaryKeyValue);
sr.Free;
end;
{ if Assigned(csr) then begin
for i:=0 to csr.Count-1 do
AddObjectById(csr.Items[i].PrimaryKeyValue);
csr.Free;
end;}
end;
procedure TdlgSelectObjectsForDocs.AddObjectById(ObjectID: integer);
var
qry: TAdoQuery;
i: integer;
begin
if SelectedIDs.Exists(ObjectID) then
raise Exception.Create('Данный объект уже в списке для добавления');
qry:=CreateQuery('[sp_Учетная единица_получить] @код_Учетная_единица = '+IntToStr(ObjectID));
try
qry.Open;
with FrameObjectsByProps do begin
if not spObjectList.Active then
spObjectList.Open;
spObjectList.Insert;
spObjectList['IntValue']:=ObjectID;
spObjectList['ForADOInsertCol']:=false;
spObjectList['Учетная единица.Реeстровый номер']:=qry['Учетная единица.Реeстровый номер'];
spObjectList['Учетная единица.Балансовая стоимость']:=qry['Учетная единица.Балансовая стоимость'];
spObjectList['Учетная единица.Дата ввода в эксплуатацию']:=qry['Учетная единица.Дата ввода в эксплуатацию'];
spObjectList['Учетная единица.Входящий износ']:=qry['Учетная единица.Входящий износ'];
spObjectList['ОКОФ.ОКОФ']:=qry['ОКОФ.ОКОФ'];
spObjectList['Учетная единица.Входящая остаточная стоимость']:=qry['Учетная единица.Входящая остаточная стоимость'];
spObjectList['Адрес.Район']:=qry['Адрес.Район'];
spObjectList['Адрес.Населенный пункт']:=qry['Адрес.Населенный пункт'];
spObjectList['Адрес.Тип']:=qry['Адрес.Тип'];
spObjectList['Адрес.Улица']:=qry['Адрес.Улица'];
spObjectList['Адрес.№ дома']:=qry['Адрес.№ дома'];
spObjectList['Адрес.Корпус']:=qry['Адрес.Корпус'];
spObjectList['Адрес.Литер']:=qry['Адрес.Литер'];
spObjectList['Адрес.№ квартиры']:=qry['Адрес.№ квартиры'];
spObjectList['Учетная единица.Тип объекта']:=qry['Учетная единица.Тип объекта'];
spObjectList['Учетная единица.Вид пользования имуществом']:=ViewIDDef;
spObjectList['Учетная единица.Статус объекта']:=StatusIDDef;
spObjectList.Post;
SelectedIDs.Add(ObjectID, ViewIDDef, StatusIDDef, null, null);
end;
finally
qry.Free;
end;
end;
destructor TdlgSelectObjectsForDocs.Destroy;
begin
SelectedIDs.Free;
inherited;
end;
procedure TdlgSelectObjectsForDocs.actRemoveRecordExecute(Sender: TObject);
var
id: integer;
begin
if MessageBox(Handle, 'Удалить объект из списка добавляемых?', 'Удаление', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL)=IDNO then exit;
id:=FrameObjectsByProps.spObjectList['IntValue'];
FrameObjectsByProps.spObjectList.Delete;
SelectedIDs.Delete(id);
end;
procedure TdlgSelectObjectsForDocs.actRemoveRecordUpdate(Sender: TObject);
begin
inherited;
with FrameObjectsByProps.spObjectList do
(Sender as TAction).Enabled:=Active and (RecordCount>0);
end;
procedure TdlgSelectObjectsForDocs.actAddRecordUpdate(Sender: TObject);
var
id, fri: integer;
ac: TControl;
gv: TcxCustomGridView;
f: TField;
ds: TDataSet;
dsc: TcxtCustomDataSourceM;
begin
inherited;
id:=-1;
if self.FrameObjectReestr.NavBar.ActiveGroupIndex=1 then begin
ac:=ActiveControl;
{ if Assigned(ac) and (ac is TcxGridSite) then begin
gv:=(ac as TcxGridSite).GridView;
ds:=(gv.DataController as TcxGridDBDataController).DataSource.DataSet;
f:=ds.Fields.FindField('вк_Свойства');
if Assigned(f) then
id:=f.Value;
end;}
//переход на Андрюху
if Assigned(ac) and (ac is TcxGridSite) then begin
gv:=(ac as TcxGridSite).GridView;
if (gv.DataController is TcxGridDataControllerCds) then begin
dsc:=(gv.DataController as TcxGridDataControllerCds).CashDataSource;
fri:=(gv.DataController as TcxGridDataControllerCds).FocusedRecordIndex;
id:=dsc.Values[fri, dsc.FieldByName('вк_Свойства').Index];
end;
end;
end;
if (FrameObjectReestr.NavBar.ActiveGroupIndex=0) and Assigned(FrameObjectReestr.FrameByProps) then begin
dsc:=FrameObjectReestr.FrameByProps.DataSourceCash;
if dsc.Active and (FrameObjectReestr.FrameByProps.ViewCds.DataController.FilteredRecordCount>0) then
id:=nz(dsc.Values[FrameObjectReestr.FrameByProps.ViewCds.DataController.FocusedRecordIndex, 0], -1);
{ ds:=FrameObjectReestr.FrameByProps.spObjectList;
if ds.Active and (FrameObjectReestr.FrameByProps.View.DataController.RowCount>0) then
id:=self.FrameObjectReestr.FrameByProps.spObjectList['Учетная единица.код_Учетная единица'];}
end;
(Sender as TAction).Enabled:=id<>-1;
// (Sender as TAction).Enabled:=true;
end;
procedure TdlgSelectObjectsForDocs.ApplyParamsAfterOpen;
begin
inherited;
StatusIDDef:=Params['Статус объекта по-умолчанию'].Value;
ViewIDDef:=Params['Вид пользования по-умолчанию'].Value;
end;
procedure TdlgSelectObjectsForDocs.FrameObjectsByPropsspObjectListAfterPost(
DataSet: TDataSet);
var
i: integer;
begin
inherited;
i:=SelectedIDs.IdIndex(DataSet.Fields[0].Value);
if i=-1 then exit;
SelectedIDs[i].ViewID:=DataSet['Вид пользования имуществом'];
SelectedIDs[i].StatusID:=DataSet['Правовой статус'];
SelectedIDs[i].OrgFrom:=DataSet['Принято от'];
SelectedIDs[i].OrgTo:=DataSet['Закреплено за'];
end;
procedure TdlgSelectObjectsForDocs.btnOKClick(Sender: TObject);
begin
if FrameObjectsByProps.spObjectList.State=dsEdit then
FrameObjectsByProps.spObjectList.Post;
inherited;
end;
procedure TdlgSelectObjectsForDocs.FormShow(Sender: TObject);
begin
inherited;
FrameObjectsByProps.spObjectList.Close;
FrameObjectsByProps.spObjectList.CursorLocation:=clUseClient;
FrameObjectsByProps.spObjectList.LockType:=ltBatchOptimistic;
FrameObjectsByProps.spObjectList.AfterOpen:=nil;
FrameObjectsByProps.DataSourceCash.DataSet:=nil;
FrameObjectsByProps.spObjectList.Open;
FrameObjectsByProps.GridLevel.GridView:=FrameObjectsByProps.View;
//Delphi оочень плохо с фреймами работает - пришлось в рантайме назнаяать поля, иначе слетают свойства
with FrameObjectsByProps.ViewColumn25 do begin
DataBinding.FieldName:='Правовой статус';
Caption:='Правовой статус';
Position.ColIndex:=1;
PropertiesClass:=TcxLookupComboBoxProperties;
(Properties as TcxLookupComboBoxProperties).ListSource:=dsStatus;
(Properties as TcxLookupComboBoxProperties).ListFieldNames:='Наименование';
(Properties as TcxLookupComboBoxProperties).KeyFieldNames:='код_статус объекта';
Options.Editing:=true;
Options.ShowEditButtons:=isebAlways;
end;
with FrameObjectsByProps.ViewColumn24 do begin
DataBinding.FieldName:='Принято от';
Caption:='Принято от';
Position.ColIndex:=2;
PropertiesClass:=TcxLookupComboBoxProperties;
(Properties as TcxLookupComboBoxProperties).ListSource:=dsOrg;
(Properties as TcxLookupComboBoxProperties).ListFieldNames:='Сокр. наим. орг-ции';
(Properties as TcxLookupComboBoxProperties).KeyFieldNames:='код_Субъекты учета';
Options.Editing:=true;
Options.ShowEditButtons:=isebAlways;
end;
with FrameObjectsByProps.ViewColumn5 do begin
DataBinding.FieldName:='Закреплено за';
Caption:='Закреплено за';
Position.ColIndex:=3;
PropertiesClass:=TcxLookupComboBoxProperties;
(Properties as TcxLookupComboBoxProperties).ListSource:=dsOrg;
(Properties as TcxLookupComboBoxProperties).ListFieldNames:='Сокр. наим. орг-ции';
(Properties as TcxLookupComboBoxProperties).KeyFieldNames:='код_Субъекты учета';
Options.Editing:=true;
Options.ShowEditButtons:=isebAlways;
end;
with FrameObjectsByProps.ViewDBBandedColumn18 do begin
DataBinding.FieldName:='Вид пользования имуществом';
Caption:='Вид пользования';
Position.ColIndex:=4;
PropertiesClass:=TcxLookupComboBoxProperties;
(Properties as TcxLookupComboBoxProperties).ListSource:=dsView;
(Properties as TcxLookupComboBoxProperties).ListFieldNames:='Наименование';
(Properties as TcxLookupComboBoxProperties).KeyFieldNames:='код_Вид пользования имуществом';
Options.Editing:=true;
Options.ShowEditButtons:=isebAlways;
end;
end;
end.
|
unit Unit_Filters_Consts;
interface
resourcestring
YesBtn_Caption = 'Прийняти';
CancelBtn_Caption = 'Відмінити';
PeriodLabel_Caption = 'Період відбору даних:';
FilterKodSetup_Caption = 'Фільтр по періоду';
Error_Caption = 'Помилка';
MonthesList_Text = 'Січень'+#13+'Лютий'+#13+'Березень'+#13+
'Квітень'+#13+'Травень'+#13+'Червень'+#13+
'Липень'+#13+'Серпень'+#13+'Вересень'+#13+
'Жовтень'+#13+'Листопад'+#13+'Грудень';
implementation
end.
|
unit ZPeoplePrivControl;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel,
cxControls, cxGroupBox, StdCtrls, cxButtons,
PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase,
ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr,
cxSpinEdit, FIBQuery, pFIBQuery, pFIBStoredProc, Unit_ZGlobal_Consts,
ActnList, zProc, zMessages;
type
TFZPeoplePrivControl = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxOptions: TcxGroupBox;
EditDateEnd: TcxDateEdit;
EditDateBeg: TcxDateEdit;
DateBegLabel: TcxLabel;
DateEndLabel: TcxLabel;
LabelAmountPriv: TcxLabel;
DataBase: TpFIBDatabase;
DSet: TpFIBDataSet;
DefaultTransaction: TpFIBTransaction;
DSource: TDataSource;
BoxMan: TcxGroupBox;
EditMan: TcxButtonEdit;
LabelMan: TcxLabel;
WriteTransaction: TpFIBTransaction;
StoredProc: TpFIBStoredProc;
BoxPriv: TcxGroupBox;
LabelPrivilege: TcxLabel;
EditPrivilege: TcxButtonEdit;
SpinEditPrivAmount: TcxSpinEdit;
Actions: TActionList;
Action1: TAction;
procedure CancelBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditPrivilegePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormCreate(Sender: TObject);
procedure Action1Execute(Sender: TObject);
private
PId_man:LongWord;
PId_Priv:Integer;
PParameter:TZPeoplePrivParameters;
PResault:Variant;
PLanguageIndex:Byte;
public
constructor Create(AOwner:TComponent;ComeDB:TISC_DB_HANDLE;AParameter:TZPeoplePrivParameters);reintroduce;
property Resault:Variant read PResault;
end;
function View_FZPeoplePrivControl(AOwner:TComponent;DB:TISC_DB_HANDLE;AParameter:TZPeoplePrivParameters):Variant; stdcall;
exports View_FZPeoplePrivControl;
implementation
uses VarConv;
{$R *.dfm}
function View_FZPeoplePrivControl(AOwner : TComponent;DB:TISC_DB_HANDLE;AParameter:TZPeoplePrivParameters):Variant; stdcall;
var ViewForm:TFZPeoplePrivControl;
Res:variant;
begin
ViewForm := TFZPeoplePrivControl.Create(AOwner,DB,AParameter);
if ViewForm.ModalResult=mrNone then
ViewForm.ShowModal;
If AParameter.ControlFormStyle=zcfsInsert then
begin
Res:=VarArrayCreate([0,1],varVariant);
Res[1]:=ViewForm.Resault;
end
else
Res:=VarArrayCreate([0,0],varVariant);
res[0]:=ViewForm.ModalResult;
ViewForm.Free;
View_FZPeoplePrivControl:=Res;
end;
constructor TFZPeoplePrivControl.Create(AOwner: TComponent;ComeDB:TISC_DB_HANDLE;AParameter:TZPeoplePrivParameters);
begin
inherited Create(AOwner);
PParameter:=AParameter;
PLanguageIndex:=LanguageIndex;
//******************************************************************************
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
LabelMan.Caption := LabelMan_Caption[PLanguageIndex];
LabelPrivilege.Caption := LabelPrivilege_Caption[PLanguageIndex];
LabelAmountPriv.Caption := LabelExpense_Caption[PLanguageIndex];
DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex];
DateEndLabel.Caption := LabelDateEnd_Caption[PLanguageIndex];
//******************************************************************************
self.EditDateEnd.Date := date;
self.EditDateBeg.Date := date;
//******************************************************************************
case AParameter.TypeId of
zppctIdPeoplePriv: DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_PEOPLE_PRIV_SELECTONE('+IntToStr(AParameter.ID)+',2)';
zppctIdPeople: DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_PEOPLE_PRIV_SELECTONE('+IntToStr(AParameter.ID)+',1)';
end;
IF AParameter.TypeId<>zppctNULL then
begin
DataBase.Handle:=ComeDB;
DSet.Open;
if DSet.FieldValues['FIO']<>NULL then
begin
PId_man := DSet.FieldValues['ID_PEOPLE'];
EditMan.Text := varTostr(DSet.FieldValues['FIO']);
end;
if DSet.FieldValues['NAME_PRIV']<>NULL then
begin
PId_Priv := DSet.FieldValues['ID_PRIV'];
EditPrivilege.Text := VarToStr(DSet.FieldValues['NAME_PRIV']);
end;
if DSet.FieldValues['EXPENSE']<>NULL then SpinEditPrivAmount.Value := DSet.FieldValues['EXPENSE'];
if DSet.FieldValues['MIN_AMOUNT_PRIV']<>NULL then
SpinEditPrivAmount.Properties.MinValue := DSet.FieldValues['MIN_AMOUNT_PRIV'];
if DSet.FieldValues['MAX_AMOUNT_PRIV']<>NULL then
SpinEditPrivAmount.Properties.MaxValue := DSet.FieldValues['MAX_AMOUNT_PRIV'];
if DSet.FieldValues['DATE_BEG']<>NULL then
EditDateBeg.Date := VarToDateTime(DSet.FieldValues['DATE_BEG']);
if DSet.FieldValues['DATE_END']<>NULL then
EditDateEnd.Date := VarToDateTime(DSet.FieldValues['DATE_END']);
if DSet.FieldValues['PRIV_DBEG']<>NULL then
begin
EditDateBeg.Properties.MinDate := VarToDateTime(DSet.FieldValues['PRIV_DBEG']);
EditDateEnd.Properties.MinDate := VarToDateTime(DSet.FieldValues['PRIV_DBEG']);
end;
if DSet.FieldValues['PRIV_DEND']<>NULL then
begin
EditDateBeg.Properties.MaxDate := VarToDateTime(DSet.FieldValues['PRIV_DEND']);
EditDateEnd.Properties.MaxDate := VarToDateTime(DSet.FieldValues['PRIV_DEND']);
end;
if (DSet.FieldValues['MIN_AMOUNT_PRIV']<>NULL) and
(DSet.FieldValues['MAX_AMOUNT_PRIV']=DSet.FieldValues['MIN_AMOUNT_PRIV']) then
begin
SpinEditPrivAmount.Value := DSet.FieldValues['MIN_AMOUNT_PRIV'];
SpinEditPrivAmount.Properties.ReadOnly := True;
end;
if (DSet.FieldValues['PRIV_DBEG']<>NULL) and
(DSet.FieldValues['PRIV_DEND']=DSet.FieldValues['PRIV_DBEG']) then
begin
EditDateEnd.Date := VarToDateTime(DSet.FieldValues['PRIV_DEND']);
EditDateEnd.Properties.ReadOnly := True;
EditDateBeg.Date := VarToDateTime(DSet.FieldValues['PRIV_DBEG']);
EditDateBeg.Properties.ReadOnly := True;
end;
case AParameter.ControlFormStyle of
zcfsInsert:
begin
BoxMan.Enabled := False;
Caption := ZPeoplePrivCtrl_Caption_Insert[PLanguageIndex];
end;
zcfsUpdate:
begin
BoxMan.Enabled := False;
BoxOptions.Enabled := True;
Caption := ZPeoplePrivCtrl_Caption_Update[PLanguageIndex];
end;
zcfsShowDetails:
begin
BoxOptions.Enabled := False;
BoxMan.Enabled := False;
BoxPriv.Enabled := False;
YesBtn.Visible := False;
CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex];
Caption := ZPeoplePrivCtrl_Caption_Detail[PLanguageIndex];
end;
end;
end;
end;
procedure TFZPeoplePrivControl.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFZPeoplePrivControl.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if DefaultTransaction.Active then DefaultTransaction.Commit;
end;
procedure TFZPeoplePrivControl.EditManPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Man:Variant;
begin
Man:=LoadPeopleModal(self,DataBase.Handle);
if VarArrayDimCount(Man)> 0 then
if Man[0]<>NULL then
begin
EditMan.Text := Man[1]+' '+Man[2]+' '+Man[3];
PId_Man := Man[0];
end;
end;
procedure TFZPeoplePrivControl.EditPrivilegePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Privilege:Variant;
begin
Privilege:=LoadPrivileges(self,DataBase.Handle,zfsModal);
if VarArrayDimCount(Privilege)> 0 then
if Privilege[0]<>NULL then
begin
EditPrivilege.Text := Privilege[1];
PId_Priv := Privilege[0];
{ ShowMessage(VarToStr(Privilege[0])+#13+
VarToStr(Privilege[1])+#13+
VarToStr(Privilege[2])+#13+
VarToStr(Privilege[3])+#13+
VarToStr(Privilege[4])+#13+
VarToStr(Privilege[5]));}
if Privilege[2]=Privilege[3] then
begin
SpinEditPrivAmount.Value := Privilege[2];
SpinEditPrivAmount.Properties.ReadOnly := True;
end
else
begin
SpinEditPrivAmount.Properties.MaxValue := Privilege[3];
SpinEditPrivAmount.Value := Privilege[2];
SpinEditPrivAmount.Properties.MinValue := Privilege[2];
SpinEditPrivAmount.Properties.ReadOnly := False;
end;
if Privilege[4]=Privilege[5] then
begin
EditDateEnd.Date := VarToDateTime(Privilege[4]);
EditDateBeg.Date := VarToDateTime(Privilege[4]);
EditDateEnd.Properties.ReadOnly := True;
EditDateBeg.Properties.ReadOnly := True;
end
else
begin
EditDateEnd.Properties.MaxDate := VarToDateTime(Privilege[5]);
EditDateEnd.Properties.MinDate := VarToDateTime(Privilege[4]);
EditDateBeg.Properties.MaxDate := VarToDateTime(Privilege[5]);
EditDateBeg.Properties.MinDate := VarToDateTime(Privilege[4]);
EditDateEnd.Properties.ReadOnly := False;
EditDateBeg.Properties.ReadOnly := False;
end;
BoxOptions.Enabled := True;
end;
end;
procedure TFZPeoplePrivControl.FormCreate(Sender: TObject);
begin
if PParameter.ControlFormStyle=zcfsDelete then
begin
if ZShowMessage(ZPeoplePrivCtrl_Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_PEOPLE_PRIV_D';
StoredProc.Prepare;
StoredProc.ParamByName('ID_PEOPLE_PRIV').AsInteger := PParameter.ID;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end
else
ModalResult:=mrCancel;
Exit;
end;
end;
procedure TFZPeoplePrivControl.Action1Execute(Sender: TObject);
begin
If EditMan.Text = '' then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ManInput_ErrorText[PLanguageIndex],mtWarning,[mbOK]);
if BoxMan.Enabled then EditMan.SetFocus;
Exit;
end;
If EditPrivilege.Text = '' then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputPrivilege_Error_Text[PLanguageIndex],mtWarning,[mbOK]);
if BoxPriv.Enabled then EditPrivilege.SetFocus;
Exit;
end;
If (SpinEditPrivAmount.Text = '') or (SpinEditPrivAmount.Value=0) then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputExpense_Error_Text[PLanguageIndex],mtWarning,[mbOK]);
if BoxOptions.Enabled then SpinEditPrivAmount.SetFocus;
Exit;
end;
if EditDateEnd.Date < EditDateBeg.Date then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputTerms_ErrorText[PLanguageIndex],mtWarning,[mbOK]);
if BoxPriv.Enabled then EditDateBeg.SetFocus;
Exit;
end;
case PParameter.ControlFormStyle of
zcfsInsert:
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_PEOPLE_PRIV_I';
StoredProc.Prepare;
StoredProc.ParamByName('ID_PEOPLE').AsInteger := PId_man;
StoredProc.ParamByName('ID_PRIV').AsInteger := PId_Priv;
StoredProc.ParamByName('DATE_BEG').AsDate := EditDateBeg.Date;
StoredProc.ParamByName('DATE_END').AsDate := EditDateEnd.Date;
StoredProc.ParamByName('EXPENSE').AsInteger := SpinEditPrivAmount.Value;
StoredProc.ExecProc;
PResault := StoredProc.ParamByName('ID_PEOPLE_PRIV').AsInteger;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end;
zcfsUpdate:
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_PEOPLE_PRIV_U';
StoredProc.Prepare;
StoredProc.ParamByName('ID_PEOPLE_PRIV').AsInteger := PParameter.ID;
StoredProc.ParamByName('ID_PEOPLE').AsInteger := PId_man;
StoredProc.ParamByName('ID_PRIV').AsInteger := PId_Priv;
StoredProc.ParamByName('DATE_BEG').AsDate := EditDateBeg.Date;
StoredProc.ParamByName('DATE_END').AsDate := EditDateEnd.Date;
StoredProc.ParamByName('EXPENSE').AsInteger := SpinEditPrivAmount.Value;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end;
end;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Logger.Provider.Console
Description : Log Console Provider
Author : Kike Pérez
Version : 1.22
Created : 12/10/2017
Modified : 24/04/2020
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
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 Quick.Logger.Provider.Console;
{$i QuickLib.inc}
interface
uses
Classes,
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
SysUtils,
Quick.Commons,
Quick.Console,
Quick.Logger;
type
{$IFDEF DELPHIXE7_UP}
TEventTypeColors = array of TConsoleColor;
{$ELSE}
TEventTypeColors = array[0..11] of TConsoleColor;
{$ENDIF}
const
//Reference for TEventType = (etHeader, etInfo, etSuccess, etWarning, etError, etCritical, etException, etDebug, etTrace, etDone, etCustom1, etCustom2);
{$IFDEF DELPHIXE7_UP}
DEF_EVENTTYPECOLORS : TEventTypeColors = [ccLightGray {etHeader},
ccWhite {etInfo},
ccLightGreen {etSuccess},
ccYellow {etWarning},
ccLightRed {etError},
ccYellow {etCritical},
ccRed {etException},
ccLightCyan {etDebug},
ccLightMagenta {etTrace},
ccGreen {etDone},
ccCyan {etCustom1},
ccCyan {etCustom2}
];
{$ELSE}
DEF_EVENTTYPECOLORS : TEventTypeColors = (ccLightGray {etHeader},
ccWhite {etInfo},
ccLightGreen {etSuccess},
ccYellow {etWarning},
ccLightRed {etError},
ccYellow {etCritical},
ccRed {etException},
ccLightCyan {etDebug},
ccLightMagenta {etTrace},
ccGreen {etDone},
ccCyan {etCustom1},
ccCyan {etCustom2}
);
{$ENDIF}
CR = #13;
type
TLogConsoleProvider = class (TLogProviderBase)
private
fShowEventColors : Boolean;
fShowTimeStamp : Boolean;
fEventTypeColors : TEventTypeColors;
fShowEventTypes : Boolean;
fUnderlineHeaderEventType : Boolean;
function GetEventTypeColor(cEventType : TEventType) : TConsoleColor;
procedure SetEventTypeColor(cEventType: TEventType; cValue : TConsoleColor);
public
constructor Create; override;
destructor Destroy; override;
property ShowEventColors : Boolean read fShowEventColors write fShowEventColors;
property ShowTimeStamp : Boolean read fShowTimeStamp write fShowTimeStamp;
property ShowEventType : Boolean read fShowEventTypes write fShowEventTypes;
property UnderlineHeaderEventType : Boolean read fUnderlineHeaderEventType write fUnderlineHeaderEventType;
property EventTypeColor[cEventType : TEventType] : TConsoleColor read GetEventTypeColor write SetEventTypeColor;
procedure Init; override;
procedure Restart; override;
procedure WriteLog(cLogItem : TLogItem); override;
end;
var
GlobalLogConsoleProvider : TLogConsoleProvider;
implementation
constructor TLogConsoleProvider.Create;
begin
inherited;
LogLevel := LOG_ALL;
fShowEventTypes := False;
fShowEventColors := True;
fShowTimeStamp := False;
fUnderlineHeaderEventType := False;
fEventTypeColors := DEF_EVENTTYPECOLORS;
end;
destructor TLogConsoleProvider.Destroy;
begin
inherited;
end;
function TLogConsoleProvider.GetEventTypeColor(cEventType: TEventType): TConsoleColor;
begin
Result := fEventTypeColors[Integer(cEventType)];
end;
procedure TLogConsoleProvider.SetEventTypeColor(cEventType: TEventType; cValue : TConsoleColor);
begin
fEventTypeColors[Integer(cEventType)] := cValue;
end;
procedure TLogConsoleProvider.Init;
begin
{$IFDEF MSWINDOWS}
//not enable if console not available
if GetStdHandle(STD_OUTPUT_HANDLE) = 0 then
begin
Enabled := False;
Exit;
end;
{$ENDIF}
inherited;
end;
procedure TLogConsoleProvider.Restart;
begin
Stop;
Init;
end;
procedure TLogConsoleProvider.WriteLog(cLogItem : TLogItem);
begin
if CustomMsgOutput then
begin
Writeln(LogItemToFormat(cLogItem){$IFDEF LINUX}+CR{$ENDIF});
Exit;
end;
if fShowEventColors then
begin
//changes color for event
if cLogItem.EventType = etCritical then TextBackground(ccRed)
else TextColor(EventTypeColor[cLogItem.EventType]);
{case cLogItem.EventType of
etHeader : TextColor(ccLightGray);
etInfo : TextColor(ccWhite);
etSuccess : TextColor(ccLightGreen);
etWarning : TextColor(ccYellow);
etError : TextColor(ccLightRed);
etCritical : begin TextColor(ccYellow); TextBackground(ccRed); end;
etException : TextColor(ccRed);
etDebug : TextColor(ccLightCyan);
etTrace : TextColor(ccLightMagenta);
else TextColor(ccWhite);
end;}
if cLogItem.EventType = etHeader then
begin
Writeln(cLogItem.Msg{$IFDEF LINUX}+CR{$ENDIF});
if fUnderlineHeaderEventType then Writeln(FillStr('-',cLogItem.Msg.Length));
end
else
begin
//if fShowTimeStamp then Writeln(Format('%s %s',[DateTimeToStr(cLogItem.EventDate,FormatSettings),cLogItem.Msg{$IFDEF LINUX}+CR{$ENDIF}]))
// else Writeln(cLogItem.Msg{$IFDEF LINUX}+CR{$ENDIF});
writeln(LogItemToLine(cLogItem,fShowTimeStamp,fShowEventTypes){$IFDEF LINUX}+CR{$ENDIF});
end;
ResetColors;
end
else
begin
TextColor(ccWhite);
if fShowTimeStamp then Writeln(Format('%s [%s] %s',[DateTimeToStr(cLogItem.EventDate,FormatSettings),EventTypeName[cLogItem.EventType],cLogItem.Msg{$IFDEF LINUX}+CR{$ENDIF}]))
else Writeln(Format('[%s] %s',[EventTypeName[cLogItem.EventType],cLogItem.Msg{$IFDEF LINUX}+CR{$ENDIF}]));
if cLogItem.EventType = etHeader then Writeln(FillStr('-',cLogItem.Msg.Length));
end;
end;
initialization
GlobalLogConsoleProvider := TLogConsoleProvider.Create;
finalization
if Assigned(GlobalLogConsoleProvider) and (GlobalLogConsoleProvider.RefCount = 0) then GlobalLogConsoleProvider.Free;
end.
|
unit OrcamentoOperacaoDuplicar.Controller;
interface
uses Orcamento.Controller.interf, Orcamento.Model.interf,
OrcamentoItens.Model.interf, TESTORCAMENTOITENS.Entidade.Model,
Generics.Collections, TESTORCAMENTO.Entidade.Model,
OrcamentoFornecedores.Model.interf, TESTORCAMENTOFORNECEDORES.Entidade.Model;
type
TOrcamentoOperacaoDuplicarController = class(TInterfacedObject,
IOrcamentoOperacaoDuplicarController)
private
FOrcamentoModel: IOrcamentoModel;
FOrcamentoItensModel: IOrcamentoItensModel;
FOrcamentoFornecedoresModel: IOrcamentoFornecedoresModel;
FDescricao: string;
FListaItens: TList<TOrcamentoItens>;
FListaFornecedores: TList<TOrcamentoFornecedores>;
procedure gravaCapaOrcamento;
procedure gravaItensOrcamento;
procedure gravaFornecedoresOrcamento;
public
constructor Create;
destructor Destroy; override;
class function New: IOrcamentoOperacaoDuplicarController;
function orcamentoModel(AValue: IOrcamentoModel)
: IOrcamentoOperacaoDuplicarController;
function orcamentoItensModel(AValue: IOrcamentoItensModel)
: IOrcamentoOperacaoDuplicarController;
function orcamentoFornecedoresModel(AValue: IOrcamentoFornecedoresModel)
: IOrcamentoOperacaoDuplicarController;
function descricao(AValue: string): IOrcamentoOperacaoDuplicarController;
function itens(AValue: TList<TOrcamentoItens>)
: IOrcamentoOperacaoDuplicarController;
function fornecedores(AValue: TList<TOrcamentoFornecedores>)
: IOrcamentoOperacaoDuplicarController;
procedure finalizar;
end;
implementation
{ TOrcamentoOperacaoDuplicarController }
constructor TOrcamentoOperacaoDuplicarController.Create;
begin
end;
function TOrcamentoOperacaoDuplicarController.descricao(AValue: string)
: IOrcamentoOperacaoDuplicarController;
begin
Result := Self;
FDescricao := AValue;
end;
destructor TOrcamentoOperacaoDuplicarController.Destroy;
begin
inherited;
end;
procedure TOrcamentoOperacaoDuplicarController.finalizar;
begin
{1} gravaCapaOrcamento;
{2} gravaItensOrcamento;
{3} gravaFornecedoresOrcamento;
end;
function TOrcamentoOperacaoDuplicarController.fornecedores(
AValue: TList<TOrcamentoFornecedores>): IOrcamentoOperacaoDuplicarController;
begin
Result := Self;
FListaFornecedores := AValue;
end;
procedure TOrcamentoOperacaoDuplicarController.gravaCapaOrcamento;
begin
FOrcamentoModel.Entidade(TTESTORCAMENTO.Create);
FOrcamentoModel.Entidade.descricao := FDescricao;
FOrcamentoModel.DAO.Insert(FOrcamentoModel.Entidade);
end;
procedure TOrcamentoOperacaoDuplicarController.gravaFornecedoresOrcamento;
var I: Integer;
begin
for I := 0 to pred(FListaFornecedores.Count) do
begin
FOrcamentoFornecedoresModel.Entidade(TTESTORCAMENTOFORNECEDORES.Create);
FOrcamentoFornecedoresModel.Entidade.IDORCAMENTO := FOrcamentoModel.Entidade.CODIGO;
FOrcamentoFornecedoresModel.Entidade.IDFORNECEDOR := FListaFornecedores.Items[I].CODIGO;
FOrcamentoFornecedoresModel.DAO.Insert(FOrcamentoFornecedoresModel.Entidade);
end;
end;
procedure TOrcamentoOperacaoDuplicarController.gravaItensOrcamento;
var I: Integer;
begin
for I := 0 to pred(FListaItens.Count) do
begin
FOrcamentoItensModel.Entidade(TTESTORCAMENTOITENS.Create);
FOrcamentoItensModel.Entidade.IDORCAMENTO := FOrcamentoModel.Entidade.CODIGO;
FOrcamentoItensModel.Entidade.IDPRODUTO := FListaItens.Items[I].CODIGO;
FOrcamentoItensModel.Entidade.QTDE := FListaItens.Items[I].QTDE;
FOrcamentoItensModel.DAO.Insert(FOrcamentoItensModel.Entidade);
end;
end;
function TOrcamentoOperacaoDuplicarController.itens
(AValue: TList<TOrcamentoItens>): IOrcamentoOperacaoDuplicarController;
begin
Result := Self;
FListaItens := AValue;
end;
class function TOrcamentoOperacaoDuplicarController.New
: IOrcamentoOperacaoDuplicarController;
begin
Result := Self.Create;
end;
function TOrcamentoOperacaoDuplicarController.orcamentoFornecedoresModel
(AValue: IOrcamentoFornecedoresModel): IOrcamentoOperacaoDuplicarController;
begin
Result := self;
FOrcamentoFornecedoresModel := AValue;
end;
function TOrcamentoOperacaoDuplicarController.orcamentoItensModel
(AValue: IOrcamentoItensModel): IOrcamentoOperacaoDuplicarController;
begin
Result := Self;
FOrcamentoItensModel := AValue;
end;
function TOrcamentoOperacaoDuplicarController.orcamentoModel
(AValue: IOrcamentoModel): IOrcamentoOperacaoDuplicarController;
begin
Result := Self;
FOrcamentoModel := AValue;
end;
end.
|
unit uGOM;
interface
uses
System.Types,
System.Classes,
System.SysUtils,
uRWLock,
uMemory;
type
TManagerObjects = class(TObject)
private
FObjects: TList;
FSync: IReadWriteSync;
public
constructor Create;
destructor Destroy; override;
procedure AddObj(Obj: TObject);
procedure RemoveObj(Obj: TObject);
function IsObj(Obj: TObject): Boolean;
function Count: Integer;
end;
function GOM: TManagerObjects;
implementation
var
GOMObj: TManagerObjects = nil;
function GOM: TManagerObjects;
begin
if GOMObj = nil then
GOMObj := TManagerObjects.Create;
Result := GOMObj;
end;
{ TManagerObjects }
procedure TManagerObjects.AddObj(Obj: TObject);
begin
FSync.BeginWrite;
try
if FObjects.IndexOf(Obj) > -1 then
Exit;
if Obj = nil then
raise Exception.Create('Obj is null!');
FObjects.Add(Obj);
finally
FSync.EndWrite;
end;
end;
constructor TManagerObjects.Create;
begin
FSync := CreateRWLock;
FObjects := TList.Create;
end;
destructor TManagerObjects.Destroy;
begin
F(FObjects);
FSync := nil;
inherited;
end;
function TManagerObjects.IsObj(Obj: TObject): Boolean;
begin
FSync.BeginRead;
try
Result := FObjects.IndexOf(Obj) > -1;
finally
FSync.EndRead;
end;
end;
function TManagerObjects.Count: Integer;
begin
Result := FObjects.Count;
end;
procedure TManagerObjects.RemoveObj(Obj: TObject);
begin
FSync.BeginWrite;
try
FObjects.Remove(Obj);
finally
FSync.EndWrite;
end;
end;
initialization
finalization
F(GOMObj);
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.2 2004.05.20 11:38:10 AM czhower
IdStreamVCL
}
{
Rev 1.1 2004.02.03 3:15:54 PM czhower
Updates to move to System.
}
{
Rev 1.0 2004.02.03 2:36:04 PM czhower
Move
}
unit IdResourceStrings;
interface
resourcestring
//IIdTextEncoding
RSInvalidSourceArray = 'ソース配列が無効です';
RSInvalidDestinationArray = 'ターゲット配列が無効です';
RSCharIndexOutOfBounds = '文字インデックスが範囲外です (%d)';
RSInvalidCharCount = 'カウントが無効です (%d)';
RSInvalidDestinationIndex = 'ターゲット インデックスが無効です (%d)';
RSInvalidCodePage = 'コードページが無効です (%d)';
RSInvalidCharSet = '文字セット (%s) が無効です';
RSInvalidCharSetConv = '文字セット変換が無効です (%s <-> %s)';
RSInvalidCharSetConvWithFlags = '文字セット変換が無効です (%s <-> %s、%s)';
//IdSys
RSFailedTimeZoneInfo = 'タイム ゾーン情報を取得できませんでした。';
// Winsock
RSWinsockCallError = 'Winsock2 ライブラリ関数 %s への呼び出しでエラーが発生しました';
RSWinsockLoadError = 'Winsock2 ライブラリ (%s) の読み込み中にエラーが発生しました';
{CH RSWinsockInitializationError = 'Winsock Initialization Error.'; }
// Status
RSStatusResolving = 'ホスト名 %s を解決しています。';
RSStatusConnecting = '%s に接続しています。';
RSStatusConnected = '接続しました。';
RSStatusDisconnecting = '接続解除しています。';
RSStatusDisconnected = '接続解除されました。';
RSStatusText = '%s';
// Stack
RSStackError = 'Socket エラー # %d'#13#10'%s';
RSStackEINTR = 'システム コールが割り込まれました。';
RSStackEBADF = 'ファイル番号が不正です。';
RSStackEACCES = 'アクセスが拒否されました。';
RSStackEFAULT = 'バッファ フォルトが発生しました。';
RSStackEINVAL = '引数が無効です。';
RSStackEMFILE = '開いているファイルが多すぎます。';
RSStackEWOULDBLOCK = '操作はブロックされます。';
RSStackEINPROGRESS = '操作を現在実行中です。';
RSStackEALREADY = '操作は既に実行中です。';
RSStackENOTSOCK = 'ソケット以外のものに対するソケット操作です。';
RSStackEDESTADDRREQ = '送信先アドレスが必要です。';
RSStackEMSGSIZE = 'メッセージが長すぎます。';
RSStackEPROTOTYPE = 'ソケットのプロトコルの種類が正しくありません。';
RSStackENOPROTOOPT = 'プロトコル オプションが不正です。';
RSStackEPROTONOSUPPORT = 'プロトコルがサポートされていません。';
RSStackESOCKTNOSUPPORT = 'ソケット タイプがサポートされていません。';
RSStackEOPNOTSUPP = 'ソケットで操作がサポートされていません。';
RSStackEPFNOSUPPORT = 'プロトコル ファミリがサポートされていません。';
RSStackEAFNOSUPPORT = 'アドレス ファミリがプロトコル ファミリでサポートされていません。';
RSStackEADDRINUSE = 'アドレスは既に使われています。';
RSStackEADDRNOTAVAIL = '要求されたアドレスを割り当てることができません。';
RSStackENETDOWN = 'ネットワークが停止しています。';
RSStackENETUNREACH = 'ネットワークに到達できません。';
RSStackENETRESET = 'ネットワークが接続を切断またはリセットしました。';
RSStackECONNABORTED = 'ソフトウェアが原因で接続が途中で中止されました。';
RSStackECONNRESET = 'ピアにより接続がリセットされました。';
RSStackENOBUFS = '使用できるバッファ領域がありません。';
RSStackEISCONN = 'ソケットは既に接続されています。';
RSStackENOTCONN = 'ソケットが接続されていません。';
RSStackESHUTDOWN = 'ソケットが閉じた後に送信や受信をすることはできません。';
RSStackETOOMANYREFS = '参照が多すぎます。継ぎ合わせることができません。';
RSStackETIMEDOUT = '接続がタイムアウトしました。';
RSStackECONNREFUSED = '接続が拒否されました。';
RSStackELOOP = 'シンボリック リンクのレベルが多すぎます。';
RSStackENAMETOOLONG = 'ファイル名が長すぎます。';
RSStackEHOSTDOWN = 'ホストが停止しています。';
RSStackEHOSTUNREACH = 'ホストへのルートが存在しません。';
RSStackENOTEMPTY = 'ディレクトリが空ではありません';
RSStackHOST_NOT_FOUND = 'ホストが見つかりません。';
RSStackClassUndefined = 'スタック クラスは未定義です。';
RSStackAlreadyCreated = 'スタックが既に作成されています。';
// Other
RSAntiFreezeOnlyOne = 'アプリケーションあたり 1 つの TIdAntiFreeze のみ存在できます。';
RSCannotSetIPVersionWhenConnected = '接続時に IPVersion を変更できません';
RSCannotBindRange = 'ポート範囲 (%d - %d) にバインドできません';
RSConnectionClosedGracefully = '接続が正常に閉じられました。';
RSCorruptServicesFile = '%s が壊れています。';
RSCouldNotBindSocket = 'ソケットをバインドできませんでした。アドレスとポートは既に使われています。';
RSInvalidPortRange = 'ポート範囲 (%d - %d) が無効です';
RSInvalidServiceName = '%s は有効なサービスではありません。';
RSIPv6Unavailable = 'IPv6 は利用できません';
RSInvalidIPv6Address = '%s は有効な IPv6 アドレスではありません';
RSIPVersionUnsupported = '要求した IP バージョン/アドレス ファミリはサポートされていません。';
RSNotAllBytesSent = '送信できなかったバイトがあります。';
RSPackageSizeTooBig = 'パッケージ サイズが大きすぎます。';
RSSetSizeExceeded = 'セットのサイズを超えています。';
RSNoEncodingSpecified = 'エンコーディングが指定されていません。';
{CH RSStreamNotEnoughBytes = 'Not enough bytes read from stream.'; }
RSEndOfStream = 'ストリームの終わり: クラス %s (位置 %d)';
//DNS Resolution error messages
RSMaliciousPtrRecord = '悪意のある PTR レコードです';
implementation
end.
|
{$I-,Q-,R-,S-}
{Problema 7: Tiempo Lechero [Jeffrey Wang, 2007]
Bessie es una vaca muy trabajadora. De hecho, ella est tan enfocada
en maximizar su productividad que ella decide planificar sus
siguientes N (1 <= N <= 1,000,000) horas (convenientemente rotuladas
0..N-1) de tal manera que ella produzca tanta leche como sea posible.
El Granjero Juan tiene una lista de M (1 <= M <= 1,000) intervalos
posiblemente sobrelapados en los cuales ‚l est disponible para
orde¤o. Cada intervalo i tiene una hora inicial (0 <= hora_inicial_i <
N), y hora de finalizaci¢n (hora_incial_i < hora_final_i <= N), y una
eficiencia correspondiente (1 <= eficiencia_i <= 1,000,000) la cual
indica cu ntos galones de leche ‚l puede obtener de Bessie en ese
intervalo. El Granejro Juan comienza y termina a orde¤ar al comienzo
de la hora inicial y al final de la hora final, respectivamente.
Cuando es orde¤ada, Bessie debe ser orde¤ada durante un intervalo
completo.
Sin embargo, a£n Bessie tiene sus limitaciones. Despu‚s de ser
orde¤ada durante cualquier intervalo, ella debe descansar R (1 <= R <=
N) horas antes de comenzar a ser orde¤ada nuevamente. Dada la lista de
intervalos del Granjero Juan, determine la m xima cantidad de leche
que Bessie puede producir en las N horas.
NOMBRE DEL PROBLEMA: milkprod
FORMATO DE ENTRADA:
* L¡nea 1: Tres enteros separados por espacios: N, M, y R.
* L¡neas 2..M+1: La l¡nea i+1 describe el intervalo i‚simo de GJ con
tres enteros separados por espacios: hora_inicial_i,
hora_final_i, y eficiencia_i
ENTRADA EJEMPLO (archivo milkprod.in):
12 4 2
1 2 8
10 12 19
3 6 24
7 10 31
DETALLES DE LA ENTRADA:
Bessie quiere planificar las siguientes 12 horas; el Granjero Juan
tiene 4 intervalos no sobrelapados en los cuales ‚l puede orde¤arla;
Bessie debe descansar 2 horas despu‚s de cada orde¤ada. El primer
intervalo va de la hora 1 a la hora 2, el segundo de la hora 10 a la
hora 12, el tercero de la hora 3 a la hora 6, y el cuarto de la hora 7
a la hora 10. El Granjero Juan puede obtener 8, 19, 24, y 31 galones
de leche, respectivamente, de Bessie en esos intervalos.
FORMATO DE SALIDA:
* L¡nea 1: El m ximo n£mero de galones de leche que Bessie puede
producir en las N horas
SALIDA EJEMPLO (archivo milkprod.out):
43
DETALLES DE LA SALIDA:
Si Bessie usa el primer intervalo, ella no puede usar el tercero
debido a que necesita 2 horas de descanso. Si usa el segundo, ella no
puede usar el cuarto. Finalmente, si ella usa el tercero, ella no
puede usar el cuarto. La mejor situaci¢n es elegir los intervalos
segundo y tercero, produciendo 43 galones de leche.
}
const
max = 1001;
var
fe,fs : text;
n,m,r,sol : longint;
tab : array[0..max,1..3] of longint;
best : array[0..max] of longint;
procedure open;
var
i : longint;
begin
assign(fe,'milkprod.in'); reset(fe);
assign(fs,'milkprod.out'); rewrite(fs);
readln(fe,n,m,r);
for i:=1 to m do
readln(fe,tab[i,1],tab[i,2],tab[i,3]);
close(fe);
end;
procedure qsort(ini,fin,p : longint);
var
i,j,k : longint;
begin
i:=ini; j:=fin; k:=tab[(i+j) div 2,p];
repeat
while tab[i,p] < k do inc(i);
while tab[j,p] > k do dec(j);
if i<=j then
begin
tab[0]:=tab[i]; tab[i]:=tab[j]; tab[j]:=tab[0];
inc(i); dec(j);
end;
until i>j;
if i<fin then qsort(i,fin,p);
if j>ini then qsort(ini,j,p);
end;
procedure work;
var
i,j,act : longint;
begin
qsort(1,m,2); { A lo mejor se puede eliminar un qsort }
qsort(1,m,1); { no probe, pero asi da en tiempo }
sol:=0;
for i:=m downto 1 do
begin
act:=0; best[i]:=tab[i,3];
for j:=i+1 to m do
begin
if (tab[i,2]+r <= tab[j,1]) and (best[j] > act) then
act:=best[j];
end;
best[i]:=best[i] + act;
if best[i] > sol then sol:=best[i];
end;
writeln(fs,sol);
close(fs);
end;
begin
open;
work;
end. |
{..............................................................................}
{ Summary Layers information based on the current PCB layer stack }
{ of the pcb document. }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Function ConvertDielectricTypeTOString (DT : TDielectricType): String;
Begin
Result := 'Unknown Type';
Case DT Of
eNoDielectric : Result := 'No Dielectric';
eCore : Result := 'Core';
ePrePreg : Result := 'PrePreg';
eSurfaceMaterial : Result := 'Surface Material';
End;
End;
{..............................................................................}
{..............................................................................}
Function GetLayerInfo(BoardHandle : IPCB_Board; LayerObject : IPCB_LayerObject) : String;
Begin
Result := Layer2String(LayerObject.LayerID) + ', ' + LayerObject.Name + ', ' +
'Copper' + ', ' + FloatToStr(LayerObject.CopperThickness / 10000) + ', ';
If LayerObject.Dielectric.DielectricType <> eNoDielectric Then
Begin
Result := Result + ConvertDielectricTypeTOString(LayerObject.Dielectric.DielectricType) + ', ' +
LayerObject.Dielectric.DielectricMaterial + ', ' + FloatToStr(LayerObject.Dielectric.DielectricHeight / 10000) + ', ' +
FloatToStr(LayerObject.Dielectric.DielectricConstant);
End;
End;
{..............................................................................}
{..............................................................................}
Procedure FetchLayersInformation;
Var
BoardHandle : IPCB_Board;
LayerIterator : IPCB_LayerObjectIterator;
Filename : String;
ReportDocument : IServerDocument;
StringList : TStringList;
Begin
BoardHandle := PCBServer.GetCurrentPCBBoard;
If BoardHandle = Nil Then
Begin
ShowError('Current document is not PCB document');
Exit;
End;
StringList := TStringList.Create;
StringList.Add('Layer, Name, Material, Cu Thickness, Dielectric Material, type, constant, height');
LayerIterator := BoardHandle.ElectricalLayerIterator;
While LayerIterator.Next Do
StringList.Add(GetLayerInfo(BoardHandle, LayerIterator.LayerObject));
FileName := ChangeFileExt(BoardHandle.FileName, '') + '_LayerRpt.cvs';
StringList.SaveToFile(Filename);
StringList.Free;
ReportDocument := Client.OpenDocument('Text', FileName);
If ReportDocument <> Nil Then
Client.ShowDocument(ReportDocument);
End;
{..............................................................................}
{..............................................................................}
|
unit dbfunc;
interface
uses
Classes, SysUtils, IBX.IBDatabase, IBX.IBQuery, Variants;
type
{ TValueItem - вспомогательный класс, является буфером для значения
одной ячеки из таблицы, хранит значение одного элемента}
TValueItem = class(TCollectionItem) // элемент коллекции
private
fValue: variant;
public
constructor Create(ACollection: TCollection); override;
property Value: variant read fValue write fValue;
end;
{ TValues }
TValues = class(TCollection)
private
function GetItem(Index: integer): TValueItem;
public
constructor Create;
function Add: TValueItem;
property Items[Index: integer]: TValueItem read GetItem; default;
end;
{ TResultItem }
TResultItem = class(TCollectionItem)
private
fValues: TValues;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
function ValueByName(const aField: string): variant;
function ValueStrByName(const aField: string): string;
property Values: TValues read fValues;
end;
{ TResultTable }
TResultTable = class(TCollection)
private
fFieldNames: TStrings;
function GetItem(Index: integer): TResultItem;
public
constructor Create;
destructor Destroy; override;
function Add: TResultItem;
procedure ReadData(aQuery: TIBQuery);
property FieldNames: TStrings read fFieldNames;
property Items[Index: integer]: TResultItem read GetItem; default;
end;
function ExecSQL(aDB: TIBDatabase; aTrans: TIBTransaction; const aStr: string; const Args: array of variant): boolean;
function OpenSQL(aDB: TIBDatabase; aTrans: TIBTransaction; const aStr: string; const Args: array of variant): TResultTable;
procedure SetSQL(aQuery: TIBQuery; const aStr: string; const Args: array of variant);
implementation
function ExecSQL(aDB: TIBDatabase; aTrans: TIBTransaction; const aStr: string; const Args: array of variant): boolean;
var
Query: TIBQuery;
i: integer;
begin
Query := TIBQuery.Create(nil);
Result := True;
try
try
with Query do
begin
DataBase:=aDB;
if aTrans.Active then
aTrans.Active:=false;
aTrans.StartTransaction;
SQL.Text:=aStr;
Prepare;
for i:=low(Args) to high(Args) do
Params[i].Value:=Args[i];
ExecSQL;
aTrans.Commit;
Close;
end;
except
aTrans.Rollback;
Result:=false;
end;
finally
aTrans.Active:=false;
Query.Free;
end;
end;
function OpenSQL(aDB: TIBDatabase; aTrans: TIBTransaction; const aStr: string; const Args: array of variant): TResultTable;
var
Query: TIBQuery;
i: integer;
begin
Query := TIBQuery.Create(nil);
Result := TResultTable.Create;
try
try
with Query do
begin
DataBase:=aDB;
if aTrans.Active then
aTrans.Active:=false;
aTrans.StartTransaction;
SQL.Text:=aStr;
Prepare;
for i:=low(Args) to high(Args) do
Params[i].Value:=Args[i];
Open;
Result.ReadData(Query);
aTrans.Commit;
Close;
end;
except
aTrans.Rollback;
end;
finally
aTrans.Active:=false;
Query.Free;
end;
end;
procedure SetSQL(aQuery: TIBQuery; const aStr: string; const Args: array of variant);
var
i: integer;
begin
with aQuery do
begin
SQL.Text:=aStr;
Prepare;
for i:=low(Args) to high(Args) do
Params[i].Value:=Args[i];
end;
end;
{ TValueItem }
constructor TValueItem.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
fValue:=varempty;
end;
{ TValues }
function TValues.GetItem(Index: integer): TValueItem;
begin
Result:=TValueItem(inherited GetItem(Index));
end;
constructor TValues.Create;
begin
inherited Create(TValueItem);
end;
function TValues.Add: TValueItem;
begin
Result:=TValueItem(inherited Add);
end;
{ TResultTable }
function TResultTable.GetItem(Index: integer): TResultItem;
begin
Result:=TResultItem(inherited GetItem(Index));
end;
constructor TResultTable.Create;
begin
inherited Create(TResultItem);
fFieldNames:=TStringList.Create;
end;
destructor TResultTable.Destroy;
begin
fFieldNames.Free;
inherited Destroy;
end;
function TResultTable.Add: TResultItem;
begin
Result:=TResultItem(inherited Add);
end;
procedure TResultTable.ReadData(aQuery: TIBQuery);
var
i: integer;
begin
Clear;
with aQuery do
begin
for i:=0 to FieldDefs.Count-1 do
fFieldNames.Add(FieldDefs[i].Name);
First;
while not Eof do
with Add do
begin
for i:=0 to fFieldNames.Count-1 do
Values.Add.Value:=FieldByName(fFieldNames[i]).Value;
Next;
end;
end;
end;
{ TResultItem }
constructor TResultItem.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
fValues:=TValues.Create;
end;
destructor TResultItem.Destroy;
begin
fValues.Free;
inherited Destroy;
end;
function TResultItem.ValueByName(const aField: string): variant;
var
i: integer;
begin
Result:=varempty;
with (Collection as TResultTable) do
for i:=0 to fFieldNames.Count-1 do
if UpperCase(fFieldNames[i])=UpperCase(aField) then
begin
Result:=fValues[i].Value;
Break;
end;
end;
function TResultItem.ValueStrByName(const aField: string): string;
var
i: integer;
begin
Result:='';
with (Collection as TResultTable) do
for i:=0 to fFieldNames.Count-1 do
if UpperCase(fFieldNames[i])=UpperCase(aField) then
begin
if not VarIsEmpty(fValues[i].Value) and not VarIsNull(fValues[i].Value) then
Result:=string(fValues[i].Value);
Break;
end;
end;
end.
|
unit ShiftOpTest;
interface
uses
DUnitX.TestFramework,
uIntXLibTypes,
uIntX;
type
[TestFixture]
TShiftOpTest = class(TObject)
public
[Test]
procedure Zero();
[Test]
procedure SimpleAndNeg();
[Test]
procedure Complex();
[Test]
procedure BigShift();
[Test]
procedure MassiveShift();
end;
implementation
[Test]
procedure TShiftOpTest.Zero();
var
int1: TIntX;
begin
int1 := TIntX.Create(0);
Assert.IsTrue(int1 shl 100 = 0);
Assert.IsTrue(int1 shr 100 = 0);
end;
[Test]
procedure TShiftOpTest.SimpleAndNeg();
var
temp: TIntXLibUInt32Array;
int1: TIntX;
begin
SetLength(temp, 2);
temp[0] := 0;
temp[1] := 8;
int1 := TIntX.Create(8);
Assert.IsTrue((int1 shl 0 = int1 shr 0) and (int1 shl 0 = 8));
Assert.IsTrue((int1 shl 32 = int1 shr - 32) and
(int1 shl 32 = TIntX.Create(temp, False)));
end;
[Test]
procedure TShiftOpTest.Complex();
var
int1: TIntX;
begin
int1 := TIntX.Create('$0080808080808080');
Assert.IsTrue((int1 shl 4).ToString(16) = '808080808080800');
Assert.IsTrue(int1 shr 36 = $80808);
end;
[Test]
procedure TShiftOpTest.BigShift();
var
int1: TIntX;
begin
int1 := 8;
Assert.IsTrue(int1 shr 777 = 0);
end;
[Test]
procedure TShiftOpTest.MassiveShift();
var
n: TIntX;
i: Integer;
begin
for i := 1 to Pred(2000) do
begin
n := i;
n := n shl i;
n := n shr i;
Assert.IsTrue(TIntX.Create(i).Equals(n));
end;
end;
initialization
TDUnitX.RegisterTestFixture(TShiftOpTest);
end.
|
unit uIntralot_extrator_de_resultados;
{
Autor : Fábio Moura de Oliveira
Data : 06/12/2015.
Esta unit, extrai os resultados do site da intralot, que ficam na url abaixo:
www.intralot/newsite/resultados
Há dois tipos de consulta, por data de jogo e por número do jogo, como funciona:
O jogador escolhe o jogo, as opções são:
* Todos os jogos;
* Keno Minas
* Minas 5
* Multiplix
* LotoMinas
* Totolot.
Após escolher o jogo o usuário seleciona se quer por data do jogo ou se por número do jogo.
Após isto, clica no botão 'BUSCAR'.
Quando o usuário clica no botão é gerado uma solicitação GET, como é sabido, solicitações
GET, o conteúdo do formulário é enviado na url, no formato propriedade=valor.
Haverá na url duas formas de enviar a consulta, para a consulta por data de jogo e
por número de jogo.
Por data de jogo, segue-se nomenclatura.
www.intralot.com.br/newsite/resultados/?
Após a url acima, haverá os parâmetros abaixo:
'jogo=', após o símbolo haverá o nome do jogo, cada jogo há um nome diferente
do que está na caixa de combinação, segue-se, para o jogo:
'Todos os jogos', será 'todos';
'Minas 5', será 'minas-5';
'Keno Minas', será 'keno-minas';
'Multiplix', será 'multplix';
'Loto Minas', será 'loto-minas';
'Totolot', será 'totolot'.
Os valores 'todos', 'minas-5', 'keno-minas', 'multplix', 'lotominas' e
'totolot', são todos valores do campo 'value' do tag 'select'.
Em seguida, o tipo da busca, se for por data, o string de consulta será:
&busca=data
Entretanto, se for por concurso, será:
&busca=numero
Em seguida, haverá a string de consulta:
&range=
Em seguida, vem o intervalo que escolhermos, se a busca foi por data,
por exemplo, se o usuário selecionou o intervalo: 01/12/2015 a 06/12/2015,
ficará assim:
01122015-06122015,
observe que, se o dia ou mês for menor que 10, devemos acrescentar sempre um
zero a esquerda, ou seja, dia e mês, sempre tem que haver dois algarismos.
Entretanto, se a busca foi por número do jogo, então, por exemplo,
se o usuário selecionou o jogo número 1 (um) a 1000, então deve-se colocado
a informação na url desta forma:
1-1000
Em seguida, ao enviarmos a url codificada novamente para o servidor, estaremos
simulando uma consulta.
Se esta consulta, retorna mais de uma página, conseguiremos detectar isto
dentro do conteúdo html, pois há um tag denominado: '<div class="pagination"
que guarda algumas páginas, as 8 primeiras e em seguida, a última das páginas.
Na url, cada página é identificada pelo string: &page=xxx, onde xxx, indica o número
da página, a url que enviamos será a página 1, ela não terá o string: '&page=1',
entretanto, as demais páginas terão.
Pode-se observar, no conteúdo html, que o link para a próxima página
está localizado dentro do tag: '<div class="pagination".
Dentro do tag, terá até 8 páginas seguintes, e terá um link para a última página.
Então, o que nosso extrator de resultados, fará na tag '<div class="pagination":
Percorrerá todos os links que está somente na primeira página, e como na primeira
página é identificada a última página, não precisaremos nas próximas páginas
analisar o que está entre '<div class="pagination".
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uHtml_Analisador, strUtils;
type
{ Tfb_Intralot_Resultados }
Tfb_Intralot_Resultados = class
lista_de_resultados: TStrings;
// Indica se cabeçalho já foi inserido.
cabecalho_existe : boolean;
strErro: string;
function extrair_por_numero_do_jogo(strJogo: string;
iJogo_Inicial: integer; iJogo_Final: integer): boolean;
function extrair_por_data_do_jogo(strJogo: string; iData_Inicial: string;
iData_Final: string): boolean;
public
function extrair(var resultado_dos_jogos: TSTrings; tokens_html: TStrings
): boolean;
property ultimo_erro: string read strErro;
private
function Gravar_Cabecalho(strJogo: string): boolean;
function intervalo_valido_das_bolas(jogo_tipo: string; bola_numero: integer
): boolean;
function jogo_valido(var strJogo: string): boolean;
function Tag_Abre_e_Fecha(tokens_html: TStrings; strIdentificador_Tag: string;
uIndice_Inicio: integer; uIndice_Fim: integer; out uIndice_Tag: integer
): boolean;
function Validar_Data_Hora(strData_Hora: string; var strData: string;
var strHora: string): boolean;
function Validar_Hora(strData_Hora: string): boolean;
function Validar_Jogo(strJogo: string): boolean;
end;
implementation
{ Tfb_Intralot_Resultados }
// Esta função valida se o jogo está correto.
function Tfb_Intralot_Resultados.Validar_Jogo(strJogo: string): boolean;
begin
strJogo := LowerCase(strJogo);
case strJogo of
'todos':
Result := True;
'keno-minas':
Result := True;
'minas-5':
Result := True;
'multplix':
Result := True;
'loto-minas':
Result := True;
'totolot':
Result := True;
else
Result := False;
end;
end;
{
A função abaixo
}
function Tfb_Intralot_Resultados.extrair_por_numero_do_jogo(strJogo: string;
iJogo_Inicial: integer; iJogo_Final: integer): boolean;
var
strUrl_do_Jogo: string;
begin
if not Validar_Jogo(strJogo) then
begin
strErro := 'Jogo inválido.';
Exit(False);
end;
// Vamos criar a url do jogo:
strUrl_do_Jogo := 'http://www.intralot.com.br/newsite/resultados?';
strUrl_do_Jogo := strUrl_do_Jogo + Format(
'jogo=%s&busca=numero&range=%d-%d', [strJogo, iJogo_Inicial, iJogo_Final]);
end;
function Tfb_Intralot_Resultados.extrair_por_data_do_jogo(strJogo: string;
iData_Inicial: string; iData_Final: string): boolean;
begin
end;
{
Esta função grava o cabeçalho, que vai na primeira linha do arquivo:
Este programa grava o resultado dos arquivos em formato csv.
Na primeira linha, o nome dos cabeçalhos são separados por ';', pois é um formato csv.
JOGO_TIPO: O nome do jogo.
CONCURSO: O número do concurso.
DATA SORTEIO: A data do sorteio.
BOLA1: A primeira bola sorteada do jogo.
}
function Tfb_Intralot_Resultados.Gravar_Cabecalho(strJogo: string): boolean;
var
strCabecalho: String;
iA: Integer;
begin
strCabecalho := 'JOGO_TIPO;CONCURSO;DATA SORTEIO';
case UpperCase(strJogo) of
'INTRALOT_MINAS_5': for iA := 1 to 5 do strCabecalho := strCabecalho + format(';BOLA%d', [iA]);
'INTRALOT_LOTO_MINAS': for iA := 1 to 6 do strCabecalho := strCabecalho + format(';BOLA%d', [iA]);
'INTRALOT_KENO_MINAS': for iA := 1 to 20 do strCabecalho := strCabecalho + format(';BOLA%d', [iA]);
'INTRALOT_MULTIPLIX' :
begin
strErro := 'Jogo ainda não implementado.';
Exit(False);
end;
'INTRALOT_TOTOLOT':
begin
strErro := 'Jogo INTRALOT_TOTOLOT não será implementado, pois os números não são ' +
' escolhidos pelo usuário e sim pelo sistema.';
Exit(False);
end;
else begin
strErro := 'Jogo ' + strJogo + ' inexistente.';
Exit(False);
end;
end;
lista_de_resultados.Add(strCabecalho);
end;
// O método 'extrair' é a função núcleo do extrator de resultados, é onde os tags
// html são analisados sintaticamente e se válidos o resultado de um ou mais jogos
// são retornados.
// Os tokens já foram separados, aqui, simplesmente, os tokens são validados
// sintaticamente conforme descrito no site da intralot.
function Tfb_Intralot_Resultados.extrair(var resultado_dos_jogos: TSTrings;tokens_html: TStrings): boolean;
var
uTotal_de_Tokens: Integer;
uIndice: Integer;
uTag_Div_Fechamento_Indice: Integer;
jogo_resultado: TStrings;
strJogo: String;
tag_fim_result_item: integer;
concurso_data_hora: String;
iEspaco_Posicao: SizeInt;
numero_do_concurso: String;
tag_fim_class_bolas: Integer;
uBola_Numero: Integer;
strData_Hora: String;
strData: string;
strHora: string;
pedra_preciosa_simbolo: String;
strTexto_Resultado: String;
iA: Integer;
begin
uTotal_de_Tokens := tokens_html.Count - 1;
// O jogo sempre fica entre o tag <div class="resultados" </div>
// Então, devemos localizar onde está este token.
jogo_resultado := TStrings(TStringList.Create);
if Assigned(lista_de_resultados) then begin
FreeAndNil(lista_de_resultados);
end;
lista_de_Resultados := TStrings(TStringList.Create);
if not Assigned(lista_de_resultados) then
begin
strErro := 'Não foi possível criar lista de resultados.';
Exit(False);
end;
cabecalho_existe := false;
// Vamos localizar o primeiro token que começa com '<div'
uIndice := tokens_html.IndexOf('<div');
// O loop abaixo tem a finalidade de localizar dentro do conteúdo html
// a palavra formada pelos tokens html: <div class = "resultados >"
// Estes tokens indica o início do resultados dos jogos da site da intralot.
while uIndice <= uTotal_de_Tokens do
begin
// Se os próximos quatros campos é igual a '<div', 'class', '=' e '"resultados"',
// encontramos o início.
if (tokens_html.Strings[uIndice + 0] = '<div') and
(tokens_html.Strings[uIndice + 1] = 'class') and
(tokens_html.Strings[uIndice + 2] = '=') and
(tokens_html.Strings[uIndice + 3] = '"resultados"') and
(tokens_html.Strings[uIndice + 4] = '>') then
begin
// Se encontrarmos o início, devemos apontar após o tag: '>'
Inc(uIndice, 5);
break;
end;
// Vamos percorrer um token por vez, até encontrar o token inicial.
Inc(uIndice, 1);
end;
// Se uIndice é maior que 'uTotal_de_Tokens', quer dizer, que não foi encontrado
// Nenhum tokens de início de resultado.
if uIndice > uTotal_de_Tokens then
begin
strErro := Format('Os tokens não foram localizados: ' +
QuotedStr('%s') + QuotedStr('%s') + QuotedStr('%s') +
QuotedStr('%s'), ['<div', 'class', '=', '"resultados"']);
Exit(False);
end;
// Dentro de '<div class="resultados"' haverá vários jogos, para termos
// certeza até onde iremos iremos percorrer até encontrar o tag de fechamento
// correspondente.
// Vamos localizar o tag '</div>' que corresponde ao tag <div class = "resultados">
// Como assim, estamos apontando após '<div' devemos fazer uIndice, apontar para
// a posição de '<div'
uTag_Div_Fechamento_Indice := 0;
// Se não encontrado o tag de fechamento, sair então.
// O índice inicial é igual a -5, pois devemos começar do token '<div'
if not tag_abre_e_fecha(tokens_html, 'div', uIndice - 5, tokens_html.Count -1, uTag_Div_Fechamento_Indice) then
begin
strErro := 'Tag de fechamento ''</div>'' não encontrado, que corresponderia ' +
'ao tag de início: ''<div class="resultados"''';
Exit(false);
end;
// Aqui, uIndice após após o token '>', de
// Se o intervalo inicial e final não existe, o servidor retorna uma mensagem no formato abaixo:
// <div class="item_busca">Nenhum resultado encontrado!</div>'
// Então devemos verificar isto antes, pois se não há nenhum jogo, informar com um erro.
if (tokens_html[uIndice + 0] = '<div') and
(tokens_html[uIndice + 1] = 'class') and
(tokens_html[uIndice + 2] = '=') and
(tokens_html[uIndice + 3] = '"item_busca"') and
(tokens_html[uIndice + 4] = '>') and
(tokens_html[uIndice + 5] = 'Nenhum resultado encontrado!') and
(tokens_html[uIndice + 6] = '</div>') then
begin
strErro := 'Nem resultado encontrado para o intervalo de jogo solicitado!!!';
Exit(False);
end;
// O próximo tag que segue é:
// <div class = "item_busca" >
// Resultado do sorteio
// <strong>Keno Minas</strong>
// de número
// <strong>999999</strong>
// <div
// Aqui, uIndice deve apontar para o tag '<div'
// Sempre, iremos verificar se há alguns do tokens e retornar o erro.
if not ((tokens_html[uIndice + 0] = '<div') and
(tokens_html[uIndice + 1] = 'class') and
(tokens_html[uIndice + 2] = '=') and
(tokens_html[uIndice + 3] = '"item_busca"') and
(tokens_html[uIndice + 4] = '>') and
(tokens_html[uIndice + 5] = 'Resultado do sorteio') and
(tokens_html[uIndice + 6] = '<strong>') and
// O campo na posição uIndice + 7, refere ao jogo, iremos verificar
// depois, pois este campo é variável.
(tokens_html[uIndice + 8] = '</strong>') and
(tokens_html[uIndice + 9] = 'de número') and
(tokens_html[uIndice + 10] = '<strong>') and
// O campo na posição uIndice + 11, refere-se ao número do sorteio do jogo.
// Este campo é variável, será verificado posteriormente.
(tokens_html[uIndice + 12] = '</strong>') and
(tokens_html[uIndice + 13] = '</div>')) then
begin
// TODO: Verificar uIndice + 9 = Saiu no arquivo outros caracteres.
strErro := 'Erro, após o tag de fechamento do tag ''<div class="resultados">''' +
'Era esperado os campos do tag: ''<div class="item_busca">''';
Exit(False);
end;
// O campo na posição 'uIndice + 7', indica o nome do jogo.
strJogo := tokens_html[uIndice + 7];
if not jogo_valido(strJogo) then
Exit(False);
if not gravar_cabecalho(strJogo) then
Exit(False);
// Em seguida, cada informação do jogo, fica entre os tags: '<div class="result-item">' e '</div>'
// Pode haver mais de um jogo, então haverá mais de um tag conforme descrito acima.
// Vamos fazer uIndice apontar para o token '<div'.
Inc(uIndice, 14);
while uIndice < uTag_Div_Fechamento_Indice do
begin
// Vamos verificar se os tags começam com '<div class="result-item">'
if not((tokens_html[uIndice] = '<div') and
(tokens_html[uIndice + 1] = 'class') and
(tokens_html[uIndice + 2] = '=') and
(tokens_html[uIndice + 3] = '"result-item"') and
(tokens_html[uIndice + 4] = '>')) then
begin
strErro := 'Era esperado os tags: ''<div class="result_item" >''';
Exit(False);
end;
// Se chegamos aqui, quer dizer que o tag inicial existe, devemos encontrar
// o tag de fechamento.
// Se o acharmos, devemos ir para o próximo tag dentro deste tag.
tag_fim_result_item := 0;
if not tag_abre_e_fecha(tokens_html, 'div', uIndice, uTag_Div_Fechamento_Indice, tag_fim_result_item) then
begin
strErro := 'Tag div correspondente de fechamento para o tag inicial: ' +
'''<div class="result_item" >'' não localizado.';
Exit(False);
end;
// Aponta para o ínicio do tag: '<span'
Inc(uIndice, 5);
// Verifica se o próximo tag é:
if not ((tokens_html[uIndice] = '<span') and
(tokens_html[uIndice + 1] = 'class') and
(tokens_html[uIndice + 2] = '=') and
(tokens_html[uIndice + 3] = '"num_id"') and
(tokens_html[uIndice + 4] = '>') and
// Na posição uIndice + 5, fica a informação
// do número do concurso, data, e hora, iremos analisar depois.
(tokens_html[uIndice + 6] = '</span>')) then
begin
strErro := Format('Erro, índice: %d, era esperado os tokens: ' +
'''<span class = "num_id">'' .. ''</span>''.', [uIndice]);
Exit(False);
end;
// O token na posição uIndice + 5, contém a informação do
// número do concurso, data e hora, iremos pegar somente
// o número do concurso e a data, a hora não é necessária, ainda.
// Então, iremos verificar cada campo.
concurso_data_hora := LowerCase(tokens_html[uIndice + 5]);
// Se não começa, retorna falso e not inverte para true.
if not AnsiStartsStr('número: ', concurso_data_hora) then
begin
strErro := 'Erro, índice: ' + IntToStr(uIndice + 5) + ', era o token ' +
'começando com ''Número: ''';
Exit(False);
end;
// Vamos pegar o número do concurso.
concurso_data_hora := AnsiMidStr(concurso_data_hora, Length('número: ') + 1,
Length(concurso_data_hora));
concurso_data_hora := Trim(concurso_data_hora);
// Após vem o número do concurso, devemos procurar um espaço após.
iEspaco_Posicao := AnsiPos(' ', concurso_data_hora);
if iEspaco_Posicao = 0 then
begin
strErro := 'Erro, índice ' + IntToStr(uIndice + 5) + ', número de concurso inválido.';
Exit(False);
end;
numero_do_concurso := AnsiLeftStr(concurso_data_hora, iEspaco_Posicao -1);
numero_do_concurso := Trim(numero_do_concurso);
try
StrToInt(numero_do_concurso);
except
on exc:Exception do
begin
strErro := 'Erro, índice: ' + IntTostr(uIndice + 5) + exc.Message;
Exit(False);
end;
end;
// Vamos adicionar o nome do jogo:
jogo_resultado.Add(strJogo);
// Vamos adicionar o número do concurso;
jogo_resultado.Add(numero_do_concurso);
// Deleta o número do concurso no string 'concurso_data_hora'.
Delete(concurso_data_hora, 1, iEspaco_Posicao);
concurso_data_hora := Trim(concurso_data_hora);
// Vamos verificar se começa com a palavra 'Data:'
// Observe que estamos comparando em minúsculo, pois, convertermos
// assim a variável concurso_data_hora em minúscula.
if not AnsiStartsStr('data:', concurso_data_hora) then
begin
strErro := 'Erro, índice ' + IntToStr(uIndice + 5) + ', era esperado a palavra ' +
'''Data:'' após o número do concurso do jogo.';
Exit(False);
end;
// A data e hora deve ser separada por um espaço em branco.
strData_Hora := AnsiMidStr(concurso_data_hora, 6, Length(concurso_data_hora));
// Vamos verificar se a data é válida.
if not Validar_Data_Hora(strData_Hora, strData, strHora) then
begin
strErro := 'Data inválida.';
Exit(False);
end;
// Temos a data e hora, guardar esta informação
jogo_resultado.Add(strData);
// Vamos apontar para o próximo token
Inc(uIndice, 7);
if not((tokens_html[uIndice] = '<div') and
(tokens_html[uIndice + 1] = 'class') and
(tokens_html[uIndice + 2] = '=') and
(tokens_html[uIndice + 3] = '"bolas"') and
(tokens_html[uIndice + 4] = '>')) then
begin
strErro := Format('Erro, índice: %d, era esperado os tags: ' +
'''<div class = "bolas" >''.', [uIndice]);
Exit(False);
end;
// Vamos localizar o tag de fechamento, referente ao tag '<div class = "bolas">'
tag_fim_class_bolas := 0;
if not tag_abre_e_fecha(tokens_html, 'div', uIndice, tag_fim_result_item, tag_fim_class_bolas) then
begin
strErro := Format('Erro, índice: %d, tag de fechamento correspondente' +
' a ''<div class="bolas">'' não localizado.', [uIndice]);
Exit(False);
end;
// No loop abaixo, iremos percorrer até chegar ao token de índice tag_fim_class_bolas
// Para cada número sorteado, há os tokens abaixo, onde 99, sempre um número qualquer.
// <span class = "bolao" >
// <p>99</p>
// </span>
// Vamos apontar para o primeiro token, que é '<span'.
Inc(uIndice, 5);
while uIndice < tag_fim_class_bolas do
begin
// Entre os tags '<div class="bolas">' and '</div>', há duas formas:
// Jogo que é diferente de 'Multiplix', tem os tags seguintes:
// <span class = "bolao" >
// <p>999</p>
// </span>
// E no caso do multiplix, além do formato cima para os números das bolas,
// o jogo tem mais uma tag conforme layout abaixo:
// <div class = "pedra bolao" >
// <span class="esmeralda_int" title="Esmeralda"> </span>
// <span class="name">Esmeralda</span>
// </div>
// Conforme contéudo html, esta forma deve ser a última dentro do tag
// <div class="bolas">
if strJogo = 'INTRALOT_MULTIPLIX' then begin
// Quando a último tag estiver no final, no caso, do jogo multiplix
// será informado, o tipo da pedra, rubi, esmeralda e assim por diante.
// Neste caso, haverá 22 tokens, o primeiro token começa em 0 e o último
// termina em 21, então após este estaremos depois do fim do tag, ou seja
// estaremos no tag de fechamento da tag '<div class = "bolas">
if uIndice + 22 = tag_fim_class_bolas then
begin
if not (
(tokens_html[uIndice + 0] = '<div') and
(tokens_html[uIndice + 1] = 'class') and
(tokens_html[uIndice + 2] = '=') and
(tokens_html[uIndice + 3] = 'pedra bolao') and
(tokens_html[uIndice + 4] = '>') and
(tokens_html[uIndice + 5] = '<span') and
(tokens_html[uIndice + 6] = 'class') and
(tokens_html[uIndice + 7] = '=') and
// O ítem da posição uIndice + 8 varia, será analisado posteriormente.
(tokens_html[uIndice + 9] = 'title') and
(tokens_html[uIndice + 10] = '=') and
// O ítem da posição uIndice + 11 varia, será analisado posteriormente.
(tokens_html[uIndice + 12] = '>') and
(tokens_html[uIndice + 13] = '</span>') and
(tokens_html[uIndice + 14] = '<span') and
(tokens_html[uIndice + 15] = 'class') and
(tokens_html[uIndice + 16] = '=') and
(tokens_html[uIndice + 17] = '"name"') and
(tokens_html[uIndice + 18] = '>') and
// O ítem da posição uIndice + 19 varia, será analisado posteriormente.
// Este será o valor que será guardado.
(tokens_html[uIndice + 20] = '</span>') and
(tokens_html[uIndice + 21] = '</div>')) then
begin
strErro := 'Erro, índice ' + IntToStr(uIndice) + ' no layout para ' +
'definir quais dos símbolos utilizar: ' + #13#10 +
'Rubi, Esmeralda, Diamante ou Topazio.';
Exit(false);
end;
// Verifica se existe um dos símbolos.
pedra_preciosa_simbolo := Trim(LowerCase(tokens_html[uIndice+19]));
if (pedra_preciosa_simbolo <> 'rubi') and (pedra_preciosa_simbolo <> 'esmeralda') and
(pedra_preciosa_simbolo <> 'diamante') and (pedra_preciosa_simbolo <> 'topazio') then
begin
strErro := 'Era esperado um dos símbolos: Rubi, Esmeralda, Diamante ou Topazio.';
Exit(False);
end;
// Adiciona símbolo localizado.
jogo_resultado.Add(pedra_preciosa_simbolo);
end;
end;
if not((tokens_html[uIndice] = '<span') and (tokens_html[uIndice + 1] = 'class') and
(tokens_html[uIndice + 2] = '=') and (tokens_html[uIndice + 3] = '"bolao"') and
(tokens_html[uIndice + 4] = '>') and (tokens_html[uIndice + 5] = '<p>') and
// O token na posição uIndice + 6 representa o número da bola.
(tokens_html[uIndice + 7] = '</p>') and (tokens_html[uIndice + 8] = '</span>')) then
begin
strErro := Format('Erro, índice %s, era esperado os tokens: ' + #13#10 +
'<span class="bolao">' + #13#10 +
'<p>999</p>' + #13#10 +
'</span>' + #13#10 +
'onde 999, representa um número qualquer.', [uIndice]);
Exit(False);
end;
try
uBola_Numero := StrToInt(tokens_html[uIndice + 6]);
except
On exc: Exception do
begin
strErro := 'Erro, índice: ' + IntToStr(uIndice + 6) + exc.Message;
Exit(False);
end;
end;
jogo_resultado.Add(IntToStr(uBola_Numero));
Inc(uIndice, 9);
end;
// Acabamos de processar todas as bolas do jogo, guardar na variável de instância
// da classe.
strTexto_Resultado := jogo_resultado[0];
for iA := 1 to jogo_resultado.Count - 1 do begin
strTexto_Resultado := strTexto_Resultado + ';' + jogo_resultado[iA];
end;
// Guarda a lista de resultados do jogo.
lista_de_resultados.Add(strTexto_Resultado);
// Apagar lista temporária.
jogo_resultado.Clear;
// Até aqui, uIndice aponta para a mesma posição de tag_fim_class_bolas
// tag_fim_class_bolas corresponde ao tag de fechamento do tag de abertura
// <div class="bolas">
uIndice := tag_fim_class_bolas + 1;
// Agora, após incrementarmos, apontará para '</div>' da tag
// <div class="bolao">
// Também devemos incrementar para apontar após '</div>'.
Inc(uIndice, 1);
end;
if not Assigned (resultado_dos_jogos) then
resultado_dos_jogos := TStrings(TStringList.Create);
resultado_dos_jogos.Clear;
resultado_dos_jogos.AddStrings(lista_de_resultados);
lista_de_resultados.Clear;
FreeAndNil(lista_de_resultados);
Exit(True);
end;
function Tfb_Intralot_Resultados.intervalo_valido_das_bolas(jogo_tipo: string; bola_numero: integer): boolean;
begin
case LowerCase(jogo_tipo) of
'intralot_minas_5': Result := (bola_numero >= 1) and (bola_numero <= 34);
'intralot_loto_minas': Result := (bola_numero >= 1) and (bola_numero <= 38);
'intralot_keno_minas': Result := (bola_numero >= 1) and (bola_numero <= 80);
end;
end;
// Cada jogo no contéudo html tem uma representação ao visualizar o html no navegador.
// Entretanto, ao gravar no banco deve estar conforme o layout no banco de dados.
// Por exemplo, o jogo 'Keno Minas', tem a representação: 'INTRALOT_KENO_MINAS'
function TFb_Intralot_Resultados.jogo_valido(var strJogo: string): boolean;
begin
case LowerCase(strJogo) of
'keno minas': strJogo := 'INTRALOT_KENO_MINAS';
'loto minas': strJogo := 'INTRALOT_LOTO_MINAS';
'multplix' : strJogo := 'INTRALOT_MULTIPLIX';
'totolot' : strJogo := 'INTRALOT_TOTOLOT';
'minas 5' : strJogo := 'INTRALOT_MINAS_5';
else
begin
strErro := 'Jogo inválido: ' + strJogo;
Exit(False);
end;
end;
Exit(True);
end;
{
Esta função verificar se um tag de abertura, tem seu tag respectivo de fechamento.
Por exemplo, se analisarmos o tag '<div>', devemos localizar o tag '</div>',
A função funciona assim:
Um variável é atribuído o valor 1, pois temos um tag, por exemplo, '<div>'
Ao percorrermos a lista de tokens, ao encontrarmos o tag de abertura:
'<div>' ou '<div' seguido de '>', incrementaremos tal variável em 1.
Ao encontrarmos o tag de fechamento decrementaremos tal variável em 1.
Se durante percorrermos sequencialmente a lista de tokens, a variável torna-se zero, quer dizer
que o tag de fechamento correspondente foi localizado. Devemos retornar da
função com o valor 'True' e Indicar na variável uIndice_Tag, a posição baseada
em zero, do tag de fechamento.
Os parâmetros são:
tokens_html: O token a analisar.
strIdentificador_Tag: O identificador do tag a localizar.
uIndice_Inicio: O índice em tokens_html, em que a pesquisa começará.
uIndice_Fim: O índice final em tokens_html, baseado em zero, em que a pesquisa terminará.
uIndice_Tag: O índice em tokens_html, que o tag de fechamento correspondente foi localizado.
}
function Tfb_Intralot_Resultados.Tag_Abre_e_Fecha(tokens_html: TStrings; strIdentificador_Tag: string;
uIndice_Inicio: integer; uIndice_Fim: integer; out uIndice_Tag: integer): boolean;
var
iA: integer;
uTokens_Quantidade: integer;
iTag_Div_Qt: integer;
begin
// Vamos validar a informação entrada pelo usuário nos campos:
// uIndice_Inicio e uIndice_Fim.
if uIndice_Fim < uIndice_Inicio then begin
strErro := 'Índice final menor que índice inicial.';
Exit(False);
end;
if uIndice_Inicio < 0 then begin
strErro := 'Índice inicial menor que zero.';
Exit(False);
end;
// uIndice_Fim é baseado em zero, então deve ser menor que count -1.
if uIndice_Fim > tokens_html.Count then begin
strErro := 'Índice final maior que quantidade de ítens em tokens_html.';
Exit(False);
end;
// iA, apontará para a posição que começaremos a escanear,
// que corresponde a uIndice_Inicio;
iA := uIndice_Inicio;
uTokens_Quantidade := uIndice_Fim;
// Deve haver um balanceamento entre todos os tags html
// Neste caso, estamos verificando somente o tag '<div'
iTag_Div_Qt := 0;
while iA <= uTokens_Quantidade do
begin
if tokens_html.Strings[iA] = '<div' then
begin
// Quando em html, encontramos um tag, iniciando, por exemplo
// '<div', isto quer dizer, que entre '<div' e '>', há propriedades
// na forma propriedade=valor, então devemos localizar o token
// '>', mas entre o token '<div' e '>', não pode haver token
// nestes formatos: '<teste', '</teste>' e '<teste>'
Inc(iA);
while iA <= uTokens_Quantidade do
begin
// Temos que utilizar esta condição primeiro
// Senão, quando entrar na condição abaixo dará um erro
// pois, na segunda condição abaixo, estamos verificando
// as extremidades esquerda e direita do string a procura
// do caractere '<', e se o token for um único caractere,
// a condição será satisfeita.
if tokens_html.Strings[iA] = '>' then
begin
Inc(iTag_Div_Qt);
Break;
end;
if (AnsiStartsStr('<', tokens_html.Strings[iA]) = True) or
(AnsiEndsStr('>', tokens_html.Strings[iA]) = True) or
((AnsiStartsStr('<', tokens_html.Strings[iA]) = True) and
(AnsiEndsStr('>', tokens_html.Strings[iA]) = True)) then
begin
strErro := 'Propriedade do tag ''<div'' inválida ' +
'provavelmente, faltou o caractere ' +
'antes da propriedade.';
Exit(False);
end;
Inc(iA);
end;
end;
if tokens_html.Strings[iA] = '<div>' then
begin
Inc(iTag_Div_qt);
end;
if tokens_html.Strings[iA] = '</div>' then
begin
Dec(iTag_Div_Qt);
end;
// Se igual a zero, quer dizer, que encontramos nosso nosso
// tag de fechamento.
if iTag_Div_Qt = 0 then
begin
uIndice_Tag := iA;
Exit(true);
end;
// Ao sair do loop, iA, sempre apontará para o tag de fechamento,
// pois, se 'iTag_Div_Qt' é igual a zero, não haverá incremento
// da variável iA.
Inc(iA);
end;
if iTag_Div_Qt <> 0 then
Result := false;
end;
function Tfb_Intralot_Resultados.Validar_Hora(strData_Hora: string): boolean;
var
hora_campo: Integer;
iDois_Pontos: SizeInt;
strHora: String;
begin
if strData_Hora = '' then
begin
strErro := 'Formato de tempo inválido, nenhum tempo fornecido.';
Exit(False);
end;
end;
// Validar o campo data e hora e se informação estiver válida, retorna data e hora
// nas variáveis strData e strHora, respectivamente.
// strData_Hora deve estar neste formato: DD/MM/YYYY HH:NN
//
function TFB_Intralot_Resultados.Validar_Data_Hora(strData_Hora: string; var strData: string;
var strHora: string): boolean;
var
iVirgula: SizeInt;
iDia: Integer;
iMes: Integer;
iAno: Integer;
bAno_Bissexto: Boolean;
begin
if strData_Hora = '' then
begin
strErro := 'Data inválida.';
end;
// O valor para a propriedade 'data' deve está formato conforme abaixo:
// 31/10/2015 20:00
// Os números das datas, dia e mês, sempre formatados com dois dígitos.
// Vamos analisar cada caractere.
// Primeiro, iremos verificar se são só números válidos e a barra.
iVirgula := pos('/', strData_Hora);
if iVirgula <= 1 then begin
strErro := 'Formato de data e hora inválido: ''/'' ausente.';
Exit(false);
end;
try
iDia := StrToInt(AnsiLeftStr(strData_Hora, iVirgula - 1));
// Vamos apontar o string após a barra depois do dia.
strData_Hora := AnsiMidStr(strData_Hora, iVirgula + 1, Length(strData_Hora));
iVirgula := pos('/', strData_Hora);
if iVirgula <= 1 then begin
strErro := 'Formato de data e hora inválido: ''/'' ausente.';
Exit(false);
end;
iMes := StrToInt(AnsiLeftStr(strData_Hora, iVirgula - 1));
// Vamos apontar o string após a barra depois do mês.
strData_Hora := AnsiMidStr(strData_Hora, iVirgula + 1, Length(strData_Hora));
iVirgula := pos(' ', strData_Hora);
if iVirgula <= 1 then begin
strErro := 'Formato de data e hora inválido: '','' ausente.';
Exit(false);
end;
iAno := StrToInt(AnsiLeftStr(strData_Hora, iVirgula - 1));
// Vamos apontar o string para depois do espaço.
strData_Hora := AnsiMidSTr(strData_Hora, iVirgula + 1, Length(strData_Hora));
// Se está fora da faixa é inválido.
if (iDia in [1..31]) = false then begin
strErro := 'Formato de Data inválido: ' +
'Dia não está no intervalo de 1 a 31.';
Exit(false);
end;
// Vamos verificar se a data é válida.
// Os meses que terminam com 30 são:
// Abril, Junho, Setembro, Novembro
// Se o dia for 31, e o mês for abril, junho, setembro ou novembro.
// o formato de data está inválido.
if (iDia = 31) and (iMes in [2, 4, 6, 9, 11]) then begin
strErro := 'Formato de data invalido: ' + #10#13 +
'O último dia do mês de Abril, Junho, Setembro e ' + #10#13 +
'Novembro, é 30, entretanto, o dia fornecido é 31.';
Exit(False);
end;
// Se o mês é fevereiro e o dia é maior que 29, indicar um erro.
if (iDia > 29) and (iMes = 2) then begin
strErro := 'Formato de data inválido: Mês de fevereiro termina em 28, ' +
'ou 29, se bissexto, entretanto, o dia fornecido é maior que ' +
'29.';
Exit(false);
end;
// Vamos verificar, se o ano não for bissexto e o mês de fevereiro é 29
// está errado, então.
bAno_Bissexto := false;
if ((iAno mod 4 = 0) and (iAno mod 100 <> 1)) or
(iAno mod 400 = 0) then begin
bAno_Bissexto := true;
end;
if (iDia = 29) and (bAno_Bissexto = false) and (iMes = 2) then begin
strErro := 'Formato de data inválido: Dia é igual a ''29'' de ''fevereiro''' +
' mas ano não é bissexto.';
Exit(False);
end;
except
// Se strToInt dar uma exceção indicando que o string não é um número
// devemos retornar falso.
On exc: Exception do begin
strErro := exc.Message;
Exit(false);
end;
end;
// Vamos retornar as informações nas variáveis strData, strHora
strData := Format('%d/%d/%d', [iDia, iMes, iAno]);
strHora := '';
Result:= true;
end;
end.
|
{algo triangle_entier
// BUT avoir un triangle d'entier
// ENTRE un triangle de 1 a 9
// SORTIE le triangle affiché de 1 a 9
CONST
intmax=9
tabint = tableau [1..intmax,1..intmax] d'entier
procedure inint (Var tab1:tabint;Var cpt:entier)
Var
i,j:Entier
debut
cpt:=0
pour i de intmax a 1 pas de -1 faire
pour j de 1 a intmax faire
si i>=j alors
tab1[i,j]<-cpt // le cpt fais plus 1 au entier pour chaque ligne
ECRIRE (tab1[i,j]) le tab s'affiche dans le if pour n'avoir que un triangle
fin si
fin pour
fin pour
cpt<-cpt+1 // c'est la que les entiers vont monté le pas
fin
Var
tab2:tableau[1..intmax,1..intmax] d'entier;
i,j,cpt:integer;
Debut
clrscr;
inint(tab2,cpt); // Appel de la seconde procedure avec le tableau et le cpt
Readln;
fin.}
program triangle_entier;
uses crt;
CONST
intmax=10;
type
tabint = array [1..intmax,1..intmax] of integer;
//nom de la procédure
Procedure inint(VAR tab1:tabint; VAR cpt:integer);
VAR
i,j:integer;
begin
cpt:=0;
For i:=intmax downto 1 do
begin
For j:=1 to intmax do
begin
If i>=j then
begin
tab1[i,j]:=cpt; // le cpt va être chargé de change chaque entier en fct de la ligne
Write(tab1[i,j]); //affichage du tab pour forme le triangle
end;
end;
cpt:=cpt+1;
Writeln;
end;
end;
Var
tab2:Array[1..intmax,1..intmax] of integer;
i,j,cpt:integer;
begin
clrscr;
inint(tab2,cpt); // Appel de la seconde procedure
Readln;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
unit FInfo;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.StdCtrls,
FMX.TabControl,
FMX.Layouts,
FMX.ListBox,
FMX.Memo,
FMX.ScrollBox,
FMX.Controls.Presentation,
VXS.Scene,
VXS.Context;
type
TInfoForm = class(TForm)
TabControl: TTabControl;
TabItemVXScene: TTabItem;
TabItemInformation: TTabItem;
TabItemExtensions: TTabItem;
TabItemContributors: TTabItem;
TabItemAbout: TTabItem;
ButtonClose: TButton;
ImageControl1: TImageControl;
ScrollBoxInfo: TScrollBox;
LabelCommon: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
CopyLabel: TLabel;
AccLabel: TLabel;
StereoLabel: TLabel;
DoubleLabel: TLabel;
VersionLabel: TLabel;
RendererLabel: TLabel;
VendorLabel: TLabel;
LabelDepths: TLabel;
Label9: TLabel;
ColorLabel: TLabel;
Label11: TLabel;
DepthLabel: TLabel;
Label13: TLabel;
StencilLabel: TLabel;
Label15: TLabel;
AccumLabel: TLabel;
Label17: TLabel;
AuxLabel: TLabel;
Label19: TLabel;
SubLabel: TLabel;
Label21: TLabel;
OverlayLabel: TLabel;
ListBoxExtensions: TListBox;
Label23: TLabel;
UnderlayLabel: TLabel;
LabelMaxValues: TLabel;
Label8: TLabel;
ViewLabel: TLabel;
Label26: TLabel;
ModelLabel: TLabel;
Label28: TLabel;
ListLabel: TLabel;
LightLabel: TLabel;
Label31: TLabel;
EvalLabel: TLabel;
Label33: TLabel;
ClipLabel: TLabel;
Label35: TLabel;
Label36: TLabel;
Label37: TLabel;
NameLabel: TLabel;
Label39: TLabel;
PixelLabel: TLabel;
ProjLabel: TLabel;
TexSizeLabel: TLabel;
Label43: TLabel;
TexStackLabel: TLabel;
Label45: TLabel;
TexUnitsLabel: TLabel;
Label47: TLabel;
MemoContributors: TMemo;
MemoAbout: TMemo;
LabelOfficial: TLabel;
WebSiteLbl: TLabel;
LabelDevelopment: TLabel;
DevSiteLbl: TLabel;
Label10: TLabel;
VersionLbl: TLabel;
procedure ButtonCloseClick(Sender: TObject);
procedure WebSiteLblClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ListBoxExtensionsDblClick(Sender: TObject);
protected
procedure LoadContributors;
function GetSceneVersion: string;
public
procedure GetInfoFrom(aSceneBuffer: TVXSceneBuffer);
end;
var
InfoForm: TInfoForm;
//=======================================================================
implementation
//=======================================================================
{$R *.fmx}
procedure ShowInfoForm(aSceneBuffer: TVXSceneBuffer; Modal: boolean);
var
infoForm: TInfoForm;
begin
infoForm := TInfoForm.Create(nil);
try
infoForm.GetInfoFrom(aSceneBuffer);
with infoForm do
if Modal then
ShowModal
else
Show;
except
infoForm.Free;
raise;
end;
end;
//---------------------------------------
{ TInfoForm }
//---------------------------------------
procedure TInfoForm.FormCreate(Sender: TObject);
begin
TabControl.ActiveTab := TabItemVXScene;
end;
procedure TInfoForm.FormShow(Sender: TObject);
begin
TabControl.ActiveTab := TabItemVXScene;
end;
procedure TInfoForm.GetInfoFrom(aSceneBuffer: TVXSceneBuffer);
{ TODO -cIncompatibility : Need to replace TPixelFormatDescriptor and HDC }
///const
///DRIVER_MASK = PFD_GENERIC_FORMAT or PFD_GENERIC_ACCELERATED;
var
///pfd: TPixelFormatDescriptor;
pixelFormat: Integer;
///dc: HDC; /// HDC - in Winapi.Windows should be replaced with...
i: Integer;
ExtStr: String;
procedure IntLimitToLabel(const aLabel: TLabel; const aLimit: TLimitType);
begin
aLabel.Text := IntToStr(aSceneBuffer.LimitOf[aLimit]);
end;
begin
Caption := Caption + ' (current context in ' +
(aSceneBuffer.Owner as TComponent).Name + ')';
aSceneBuffer.RenderingContext.Activate;
try
with aSceneBuffer do
begin
// common properties
VendorLabel.Text := String(glGetString(GL_VENDOR));
RendererLabel.Text := String(glGetString(GL_RENDERER));
(*
dc := wglGetCurrentDC();
pixelFormat := GetPixelFormat(dc);
DescribePixelFormat(dc, pixelFormat, SizeOf(pfd), pfd);
// figure out the driver type
if (DRIVER_MASK and pfd.dwFlags) = 0 then
AccLabel.Text := 'Installable Client Driver'
else if (DRIVER_MASK and pfd.dwFlags) = DRIVER_MASK then
AccLabel.Text := 'Mini-Client Driver'
else if (DRIVER_MASK and pfd.dwFlags) = PFD_GENERIC_FORMAT then
AccLabel.Text := 'Generic Software Driver';
*)
VersionLabel.Text := String(glGetString(GL_VERSION));
ExtStr := String(glGetString(GL_EXTENSIONS));
ListBoxExtensions.Clear;
while Length(ExtStr) > 0 do
begin
i := Pos(' ', ExtStr);
if i = 0 then
i := 255;
ListBoxExtensions.Items.Add(Copy(ExtStr, 1, i - 1));
Delete(ExtStr, 1, i);
end;
if LimitOf[limDoubleBuffer] = GL_TRUE then
DoubleLabel.Text := 'yes'
else
DoubleLabel.Text := 'no';
if LimitOf[limStereo] = GL_TRUE then
StereoLabel.Text := 'yes'
else
StereoLabel.Text := 'no';
// Include WGL extensions
(*
if WGL_ARB_extensions_string then
begin
ExtStr := String(wglGetExtensionsStringARB(dc));
while Length(ExtStr) > 0 do
begin
i := Pos(' ', ExtStr);
if i = 0 then
i := 255;
ListBoxExtensions.Items.Add(Copy(ExtStr, 1, i - 1));
Delete(ExtStr, 1, i);
end;
end;
// Some extra info about the double buffer mode
if (pfd.dwFlags and PFD_DOUBLEBUFFER) = PFD_DOUBLEBUFFER then
begin
CopyLabel.Text := '';
if (pfd.dwFlags and PFD_SWAP_EXCHANGE) > 0 then
CopyLabel.Text := 'exchange';
if (pfd.dwFlags and PFD_SWAP_COPY) > 0 then
begin
if Length(CopyLabel.Text) > 0 then
CopyLabel.Text := CopyLabel.Text + ', ';
CopyLabel.Text := CopyLabel.Text + 'copy';
end;
if Length(CopyLabel.Text) = 0 then
CopyLabel.Text := 'no info available';
end
else
begin
CopyLabel.Text := 'n/a';
end;
// buffer and pixel depths
ColorLabel.Text :=
Format('red: %d, green: %d, blue: %d, alpha: %d bits',
[LimitOf[limRedBits], LimitOf[limGreenBits], LimitOf[limBlueBits],
LimitOf[limAlphaBits]]);
DepthLabel.Text := Format('%d bits', [LimitOf[limDepthBits]]);
StencilLabel.Text := Format('%d bits', [LimitOf[limStencilBits]]);
AccumLabel.Text :=
Format('red: %d, green: %d, blue: %d, alpha: %d bits',
[LimitOf[limAccumRedBits], LimitOf[limAccumGreenBits],
LimitOf[limAccumBlueBits], LimitOf[limAccumAlphaBits]]);
IntLimitToLabel(AuxLabel, limAuxBuffers);
IntLimitToLabel(SubLabel, limSubpixelBits);
OverlayLabel.Text := IntToStr(pfd.bReserved and 7);
UnderlayLabel.Text := IntToStr(pfd.bReserved shr 3);
*)
// Maximum values
IntLimitToLabel(ClipLabel, limClipPlanes);
IntLimitToLabel(EvalLabel, limEvalOrder);
IntLimitToLabel(LightLabel, limLights);
IntLimitToLabel(ListLabel, limListNesting);
IntLimitToLabel(ModelLabel, limModelViewStack);
IntLimitToLabel(ViewLabel, limViewportDims);
IntLimitToLabel(NameLabel, limNameStack);
IntLimitToLabel(PixelLabel, limPixelMapTable);
IntLimitToLabel(ProjLabel, limProjectionStack);
IntLimitToLabel(TexSizeLabel, limTextureSize);
IntLimitToLabel(TexStackLabel, limTextureStack);
IntLimitToLabel(TexUnitsLabel, limNbTextureUnits);
end;
VersionLbl.Text := GetSceneVersion;
finally
aSceneBuffer.RenderingContext.Deactivate;
end;
end;
procedure TInfoForm.ButtonCloseClick(Sender: TObject);
begin
Close;
end;
procedure TInfoForm.FormKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
/// if Key = #27 then
Close;
end;
procedure TInfoForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Release;
end;
// -------------------------------------------------------------------
procedure TInfoForm.ListBoxExtensionsDblClick(Sender: TObject);
var
p: Integer;
url, buf: String;
begin
with ListBoxExtensions do
begin
if ItemIndex < 0 then
Exit;
url := Items[ItemIndex];
end;
p := Pos('_', url);
buf := Copy(url, 1, p - 1);
url := Copy(url, p + 1, 255);
if (buf <> 'GL') and (buf <> 'WGL') and (buf <> 'GLX') then
Exit;
p := Pos('_', url);
buf := Copy(url, 1, p - 1);
url := 'http://www.opengl.org/registry/specs/' + buf + '/' +
Copy(url, p + 1, 255) + '.txt';
{ TODO -cIncompatibility : Find substitution to ShellExecute(0, 'open', PChar(Url), nil, nil, SW_SHOW); }
///ShowHTMLUrl(url);
end;
// -------------------------------------------------------------------
procedure TInfoForm.LoadContributors;
// var
// ContributorsFileName: string;
begin
// In the future, will be loaded from a file
{ ContributorsFileName:=
// 'Contributors.txt';
if FileExistsUTF8(ContributorsFileName) then
MemoContributors.Lines.LoadFromFile(UTF8ToSys(ContributorsFileName))
else
MemoContributors.Lines.Text:='Cannot find contributors list.';
MemoContributors.Lines.Add( ContributorsFileName) }
end;
// -------------------------------------------------------------------
function TInfoForm.GetSceneVersion: string;
var
FExePath, FVXSceneRevision: string;
begin
FVXSceneRevision := Copy(VXScene_REVISION, 12, 4);
FExePath := ExtractFilePath(ParamStr(0));
if FileExists(FExePath + 'VXSceneRevision') then
try
with TStringList.Create do
try
LoadFromFile(FExePath + 'VXSceneRevision');
if (Count >= 1) and (trim(Strings[0]) <> '') then
FVXSceneRevision:= trim(Strings[0]);
finally
Free;
end;
except
end;
Result := Format(VXScene_VERSION, [FVXSceneRevision]);
end;
// -------------------------------------------------------------------
procedure TInfoForm.WebSiteLblClick(Sender: TObject);
begin
/// ShellExecute(0, 'open', PChar(Url), nil, nil, SW_SHOW);
/// ShowHTMLUrl(WebSiteLbl.Text);
end;
// ------------------------------------------------------------------------------
initialization
// ------------------------------------------------------------------------------
RegisterInfoForm(ShowInfoForm);
end.
|
unit Utils.Collector;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, DateUtils, IniFiles,
JsonDataObjects,
Ils.Logger, Ils.Utils,
UMemStream,
CINIFilesData;
type
//------------------------------------------------------------------------------
//!
//------------------------------------------------------------------------------
TCollectorParams = record
DumpFolder: string;
KafkaBootstrap: string;
KafkaTopic: string;
PortNumber: Integer;
end;
function LoadCollectorParams(
out RParams: TCollectorParams
): Boolean;
procedure DumpAnswer(
const AOutputData: TMyMemStream;
const AIMEI: string
);
procedure DumpDevice(
const AInputData: TMyMemStream;
const AIMEI: string
);
procedure JSON2File(
const AJSON: TJsonObject;
const APath: string
);
//------------------------------------------------------------------------------
implementation
function LoadCollectorParams(
out RParams: TCollectorParams
): Boolean;
var
INIFile: TIniFile;
//------------------------------------------------------------------------------
begin
Result := False;
try
INIFile := TIniFile.Create(ChangeFileExt(ParamStr(0), CIniDefExtDotted));
except
on Ex: Exception do
begin
ToLog('Ошибка открытия INI-файла:'#13#10 + Ex.Message);
Exit;
end;
end;
try
GLogLevel := INIFile.ReadInteger(CIniMainParamsSection, 'LogLevel', 0);
ToLog(Format('Уровень лога => "%d"', [GLogLevel]));
RParams.PortNumber := INIFile.ReadInteger(CIniMainParamsSection, 'Port', 0);
ToLog(Format('Порт прослушивания => "%d"', [RParams.PortNumber]));
RParams.DumpFolder := INIFile.ReadString(CIniMainParamsSection, 'DumpFolder', '');
if (RParams.DumpFolder = '') then
RParams.DumpFolder := ExtractFilePath(ParamStr(0)) + 'Data\'
else
RParams.DumpFolder := IncludeTrailingPathDelimiter(RParams.DumpFolder);
ForceDirectories(RParams.DumpFolder);
ToLog(Format('Папка сброса файлов данных => "%s"', [RParams.DumpFolder]));
RParams.KafkaBootstrap := INIFile.ReadString(CIniKafkaSection, 'bootstrap', '');
ToLog(Format('Kafka bootstrap => "%s"', [RParams.KafkaBootstrap]));
RParams.KafkaTopic := INIFile.ReadString(CIniKafkaSection, 'topic', '');
ToLog(Format('Kafka topic => "%s"', [RParams.KafkaTopic]));
except
on Ex: Exception do
begin
ToLog('Ошибка чтения параметров из INI-файла:'#13#10 + Ex.Message);
INIFile.Free();
Exit;
end;
end;
INIFile.Free();
Result := True;
end;
procedure DumpAnswer(
const AOutputData: TMyMemStream;
const AIMEI: string
);
var
LogData: TBytes;
LogLength: Integer;
//------------------------------------------------------------------------------
begin
AOutputData.UnreadReaded();
LogLength := AOutputData.Remaining;
if (LogLength = 0) then
Exit;
SetLength(LogData, LogLength);
AOutputData.ReadData(LogLength, @LogData[0]);
ToLog(LogDataHex('Ответ прибору с IMEI "' + AIMEI + '"', @LogData[0], LogLength));
AOutputData.UnreadReaded();
end;
procedure DumpDevice(
const AInputData: TMyMemStream;
const AIMEI: string
);
var
LogData: TBytes;
LogLength: Integer;
//------------------------------------------------------------------------------
begin
AInputData.UnreadReaded();
LogLength := AInputData.Remaining;
if (LogLength = 0) then
Exit;
SetLength(LogData, LogLength);
AInputData.ReadData(LogLength, @LogData[0]);
ToLog(LogDataHex('Данные прибора с IMEI "' + AIMEI + '"', @LogData[0], LogLength));
AInputData.UnreadReaded();
end;
procedure JSON2File(
const AJSON: TJsonObject;
const APath: string
);
var
NowTime: TDateTime;
FilePath: string;
//------------------------------------------------------------------------------
begin
NowTime := Now();
repeat
FilePath := APath + FormatDateTime('yyyymmdd"_"hhnnss"_"zzz".json"', NowTime);
if not FileExists(FilePath) then
begin
AJSON.SaveToFile(FilePath, False);
Break;
end;
NowTime := IncMilliSecond(NowTime, 10);
until False;
end;
end.
|
(*
* FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*)
unit ufrmFPGImages;
interface
uses
LCLIntf, LCLType, SysUtils, Classes, Graphics, Controls, Forms,
Buttons, ComCtrls, StdCtrls, uFPG, ExtCtrls, uinifile, Dialogs,
uFrmMessageBox, uLanguage,umainmap, uMAPGraphic, uFrmPalette;
type
{ TfrmFPGImages }
TfrmFPGImages = class(TForm)
bbAceptChanges: TBitBtn;
bbCancelChanges: TBitBtn;
bmodify: TButton;
tAddControlPoints: TTimer;
ColorDialog: TColorDialog;
OpenDialog: TOpenDialog;
PageControl1: TPageControl;
tsProperties: TTabSheet;
Panel2: TPanel;
lb_heigth: TLabel;
lb_width: TLabel;
lbWidth: TLabel;
lbHeight: TLabel;
lb_ctrl_points: TLabel;
lbNumCP: TLabel;
Panel1: TPanel;
imIcon: TImage;
gbCode: TGroupBox;
edCode: TEdit;
gbFName: TGroupBox;
edFName: TEdit;
gbName: TGroupBox;
edName: TEdit;
tsControlPoints: TTabSheet;
lvControlPoints: TListView;
GroupBox5: TGroupBox;
edCoordX: TEdit;
GroupBox6: TGroupBox;
edCoordY: TEdit;
sbDelete: TSpeedButton;
sbEdit: TSpeedButton;
sbAdd: TSpeedButton;
sbSetCenter: TSpeedButton;
sbImageSelect: TSpeedButton;
sbViewControlPoints: TSpeedButton;
sbChangeColor: TSpeedButton;
sbRemoveAll: TSpeedButton;
sbLoadCP: TSpeedButton;
pHook: TPanel;
rbTL: TRadioButton;
rbTM: TRadioButton;
rbTR: TRadioButton;
rbML: TRadioButton;
rbMM: TRadioButton;
rbMR: TRadioButton;
rbDL: TRadioButton;
rbDM: TRadioButton;
rbDR: TRadioButton;
sbSetControlPoint: TSpeedButton;
sbAddPoint: TSpeedButton;
sbPutCenter: TSpeedButton;
procedure bmodifyClick(Sender: TObject);
procedure edCodeKeyPress(Sender: TObject; var Key: Char);
procedure edCodeExit(Sender: TObject);
procedure bbAceptChangesClick(Sender: TObject);
procedure edCoordXExit(Sender: TObject);
procedure edCoordYExit(Sender: TObject);
procedure sbAddClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lvControlPointsDblClick(Sender: TObject);
procedure sbEditClick(Sender: TObject);
procedure sbDeleteClick(Sender: TObject);
procedure sbImageSelectClick(Sender: TObject);
procedure tAddControlPointsTimer(Sender: TObject);
procedure sbViewControlPointsClick(Sender: TObject);
procedure sbRemoveAllClick(Sender: TObject);
procedure sbChangeColorClick(Sender: TObject);
procedure sbSetCenterClick(Sender: TObject);
procedure sbLoadCPClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure sbAddPointClick(Sender: TObject);
procedure sbPutCenterClick(Sender: TObject);
procedure edCodeEnter(Sender: TObject);
procedure edFNameEnter(Sender: TObject);
procedure edFNameExit(Sender: TObject);
procedure edNameEnter(Sender: TObject);
procedure edNameExit(Sender: TObject);
procedure edCoordXEnter(Sender: TObject);
procedure edCoordYEnter(Sender: TObject);
private
{ Private declarations }
_lng_str : string;
procedure _set_lng;
public
{ Public declarations }
fpg_index : word;
myUpdate : boolean;
fpg: TFpg;
procedure getRBPoint(bmp: TBitmap; var x, y: Longint);
end;
var
frmFPGImages: TfrmFPGImages;
implementation
uses ufrmView;
{$R *.lfm}
procedure TfrmFPGImages._set_lng;
begin
if _lng_str = inifile_language then Exit;
_lng_str := inifile_language;
(*
lvControlPoints.Columns[0].Caption := LNG_PROPERTIES_;
sbDelete.Hint := LNG_NUMBER;
sbEdit.Hint := LNG_ADD_CONTROL_POINT;
sbAdd.Hint := LNG_DELETE_CONTROL_POINT;
*)
end;
procedure TfrmFPGImages.edCodeKeyPress(Sender: TObject; var Key: Char);
begin
case key of
'0' .. '9', chr(8): begin end;
else
key := chr(13);
end;
end;
procedure TfrmFPGImages.bmodifyClick(Sender: TObject);
begin
frmMapEditor.MenuItem2.Visible:=false;
frmMapEditor.MenuItem3.Visible:=false;
frmMapEditor.MenuItem4.Caption:= LNG_EXPORT;
fpg.images[fpg_index].bPalette:=fpg.Palette;
fpg.images[fpg_index].Gamuts:=fpg.Gamuts;
frmMapEditor.imageSource:=fpg.images[fpg_index];
frmMapEditor.scrlbxImage.Color:=panel1.Color;
frmMapEditor.cbBackground.ButtonColor:=panel1.Color;
frmMapEditor.ShowModal;
imIcon.Picture.Assign(fpg.images[fpg_index]);
fpg.Palette:=fpg.images[fpg_index].bPalette;
fpg.Gamuts:=fpg.images[fpg_index].Gamuts;
end;
procedure TfrmFPGImages.edCodeExit(Sender: TObject);
begin
edCode.Color := clMedGray;
if StrToInt(edCode.Text) <> Fpg.images[fpg_index].code then
if Fpg.CodeExists(StrToInt(edCode.Text)) then
begin
feMessageBox(LNG_ERROR, LNG_EXIST_CODE, 0, 0);
edCode.SetFocus;
Exit;
end;
end;
procedure TfrmFPGImages.bbAceptChangesClick(Sender: TObject);
var
j : word;
begin
// Fpg.images[fpg_index].Assign(imIcon.Picture.Bitmap);
if StrToInt(edCode.Text) <> Fpg.images[fpg_index].code then
if Fpg.CodeExists(StrToInt(edCode.Text)) then
begin
feMessageBox(LNG_ERROR, LNG_EXIST_CODE, 0, 0);
edCode.SetFocus;
Exit;
end;
Fpg.update := true;
if StrToInt(edCode.Text) < 10 then
edCode.Text := '00' + edCode.Text
else if StrToInt(edCode.Text) < 100 then
edCode.Text := '0' + edCode.Text;
Fpg.images[fpg_index].code := StrToInt(edCode.Text);
Fpg.images[fpg_index].fpname:=edFName.Text;
Fpg.images[fpg_index].name:=edName.Text;
Fpg.images[fpg_index].CPointsCount := lvControlPoints.Items.Count;
if lvControlPoints.Items.Count > 0 then
for j := 0 to lvControlPoints.Items.Count - 1 do
begin
Fpg.images[fpg_index].cpoints[j * 2] :=
StrToInt(lvControlPoints.Items.Item[j].SubItems.Strings[0]);
Fpg.images[fpg_index].cpoints[(j * 2) + 1] :=
StrToInt(lvControlPoints.Items.Item[j].SubItems.Strings[1]);
end;
frmFPGImages.ModalResult := mrYes;
end;
procedure TfrmFPGImages.edCoordXExit(Sender: TObject);
begin
edCoordX.Color := clMedGray;
if Length(edCoordX.Text) = 0 then
Exit;
end;
procedure TfrmFPGImages.edCoordYExit(Sender: TObject);
begin
edCoordY.Color := clMedGray;
if Length(edCoordY.Text) = 0 then
Exit;
end;
procedure TfrmFPGImages.sbAddClick(Sender: TObject);
var
list_add : TListItem;
begin
if Length(edCoordX.Text) = 0 then
begin
feMessageBox( LNG_WARNING, LNG_INSERT_COORD + ' X.', 0, 0);
edCoordX.SetFocus;
Exit;
end;
if Length(edCoordY.Text) = 0 then
begin
feMessageBox( LNG_WARNING, LNG_INSERT_COORD + ' Y.', 0, 0);
edCoordY.SetFocus;
Exit;
end;
if myUpdate then
begin
list_add := lvControlPoints.Selected;
myUpdate := false;
list_add.SubItems.Strings[0] := edCoordX.Text;
list_add.SubItems.Strings[1] := edCoordY.Text;
edCoordX.Color := clMedGray;
edCoordY.Color := clMedGray;
sbDelete.Enabled := true;
end
else
begin
list_add := lvControlPoints.Items.Add;
if (lvControlPoints.Items.Count - 1) < 10 then
list_add.Caption := '00' + IntToStr(lvControlPoints.Items.Count - 1)
else if (lvControlPoints.Items.Count - 1) < 100 then
list_add.Caption := '0' + IntToStr(lvControlPoints.Items.Count - 1)
else
list_add.Caption := IntToStr(lvControlPoints.Items.Count - 1);
list_add.SubItems.Add( edCoordX.Text );
list_add.SubItems.Add( edCoordY.Text );
end;
end;
procedure TfrmFPGImages.FormShow(Sender: TObject);
var
i, j :word;
list_add : TListItem;
begin
lbWidth.Caption := IntToStr(Fpg.images[fpg_index].width);
lbHeight.Caption := IntToStr(Fpg.images[fpg_index].height);
lbNumCP.Caption := IntToStr(Fpg.images[fpg_index].CPointsCount);
imIcon.Picture.Assign( Fpg.images[fpg_index]);;
edCode.Text := IntToStr(Fpg.images[fpg_index].code);
edFName.Text := Fpg.images[fpg_index].fpname;
edName.Text := Fpg.images[fpg_index].name;
lvControlPoints.Items.Clear;
if Fpg.images[fpg_index].CPointsCount >= 1 then
for j := 0 to Fpg.images[fpg_index].CPointsCount - 1 do
begin
list_add := frmFPGImages.lvControlPoints.Items.Add;
if j < 10 then
list_add.Caption := '00' + IntToStr(j)
else if j < 100 then
list_add.Caption := '0' + IntToStr(j)
else
list_add.Caption := IntToStr(j);
list_add.SubItems.Add( IntToStr(Fpg.images[fpg_index].cpoints[j * 2]));
list_add.SubItems.Add( IntToStr(Fpg.images[fpg_index].cpoints[(j * 2) + 1]));
end;
myUpdate := false;
edCoordX.Color := clMedGray;
edCoordY.Color := clMedGray;
sbDelete.Enabled := true;
for i := 2 to 17 do
for j := 2 to 17 do
sbChangecolor.Glyph.Canvas.Pixels[i,j] := inifile_color_points;
end;
procedure TfrmFPGImages.lvControlPointsDblClick(Sender: TObject);
begin
if lvControlPoints.SelCount <> 1 then
Exit;
if not myUpdate then
begin
edCoordX.Text := lvControlPoints.Selected.SubItems.Strings[0];
edCoordY.Text := lvControlPoints.Selected.SubItems.Strings[1];
edCoordX.Color := clTeal;
edCoordY.Color := clTeal;
sbDelete.Enabled := false;
end
else
begin
edCoordX.Color := clMedGray;
edCoordY.Color := clMedGray;
sbDelete.Enabled := true;
end;
myUpdate := not myUpdate;
end;
procedure TfrmFPGImages.sbEditClick(Sender: TObject);
begin
if lvControlPoints.SelCount <> 1 then
Exit;
lvControlPointsDblClick(Sender);
end;
procedure TfrmFPGImages.sbDeleteClick(Sender: TObject);
var
i : word;
begin
if lvControlPoints.SelCount <> 1 then
Exit;
lvControlPoints.Items.Delete(lvControlPoints.Selected.Index);
if lvControlPoints.Items.Count <= 0 then
Exit;
for i := 0 to lvControlPoints.Items.Count - 1 do
if i < 10 then
lvControlPoints.Items.Item[i].Caption := '00' + IntToStr(i)
else if i < 100 then
lvControlPoints.Items.Item[i].Caption := '0' + IntToStr(i)
else
lvControlPoints.Items.Item[i].Caption := IntToStr(i);
end;
procedure TfrmFPGImages.sbImageSelectClick(Sender: TObject);
var
i : integer;
pointX, pointY : integer;
begin
frmView.control_points := true;
frmView.FPG := true;
frmView.Image.Picture.Assign(Fpg.images[fpg_index]);;
for i := 0 to lvControlPoints.Items.Count - 1 do
begin
pointX := StrToInt(lvControlPoints.Items.Item[i].SubItems[0]);
pointY := StrToInt(lvControlPoints.Items.Item[i].SubItems[1]);
if( (pointX >= 0) and (pointX < frmView.Image.Picture.Bitmap.width) and
(pointY >= 0) and (pointY < frmView.Image.Picture.Bitmap.height) ) then
begin
frmView.paintCross(frmView.Image.Picture.Bitmap,pointX,pointY,inifile_color_points);
end;
end;
frmView.Show;
tAddControlPoints.Enabled := true;
end;
procedure TfrmFPGImages.tAddControlPointsTimer(Sender: TObject);
begin
tAddControlPoints.Enabled := frmView.control_points;
if( frmView.point_active ) then
begin
edCoordX.Text := IntToStr( frmView.pointX );
edCoordY.Text := IntToStr( frmView.pointY );
sbAddClick( Sender );
frmView.point_active := false;
end;
end;
procedure TfrmFPGImages.sbViewControlPointsClick(Sender: TObject);
var
i : integer;
pointX, pointY : integer;
begin
frmView.FPG := true;
//frmView.Image1.Picture.Bitmap.Width := graph_width;
//frmView.Image1.Picture.Bitmap.Height:= graph_height;
frmView.Image.Picture.assign (Fpg.images[fpg_index]);
for i := 0 to lvControlPoints.Items.Count - 1 do
begin
pointX := StrToInt(lvControlPoints.Items.Item[i].SubItems[0]);
pointY := StrToInt(lvControlPoints.Items.Item[i].SubItems[1]);
if( (pointX >= 0) and (pointX < frmView.Image.Picture.Bitmap.width) and
(pointY >= 0) and (pointY < frmView.Image.Picture.Bitmap.height) ) then
begin
frmView.paintCross(frmView.Image.Picture.Bitmap,pointX,pointY,inifile_color_points);
end;
end;
frmView.Show;
end;
procedure TfrmFPGImages.sbRemoveAllClick(Sender: TObject);
begin
if lvControlPoints.Items.Count > 0 then
begin
if( feMessageBox(LNG_WARNING, LNG_SURE_DELETE_ALLPOINTS, 4, 2) = mrYes )then
lvControlPoints.Items.Clear;
end;
end;
procedure TfrmFPGImages.sbChangeColorClick(Sender: TObject);
var
i, j: word;
begin
if ColorDialog.Execute then
begin
inifile_color_points := ColorDialog.Color;
for i := 2 to 17 do
for j := 2 to 17 do
sbChangecolor.Glyph.Canvas.Pixels[i,j] := inifile_color_points;
write_inifile;
end;
end;
procedure TfrmFPGImages.sbSetCenterClick(Sender: TObject);
var
list_add : TListItem;
x, y : LongInt;
begin
x := (Fpg.images[fpg_index].Width div 2) - 1;
y := (Fpg.images[fpg_index].Height div 2) - 1;
if lvControlPoints.Items.Count > 0 then
begin
list_add := lvControlPoints.Items.Item[0];
list_add.SubItems.Strings[0] := IntToStr( x );
list_add.SubItems.Strings[1] := IntToStr( y );
end
else
begin
list_add := lvControlPoints.Items.Add;
lvControlPoints.Items.Item[0].Caption := '000';
list_add.SubItems.Add( IntToStr( x ) );
list_add.SubItems.Add( IntToStr( y ) );
end;
end;
procedure TfrmFPGImages.sbLoadCPClick(Sender: TObject);
var
f : TextFile;
strin : string;
n_points, x, y, i : integer;
list_add : TListItem;
begin
if OpenDialog.Execute then
begin
try
AssignFile(f, OpenDialog.FileName);
Reset(f);
except
feMessageBox( LNG_ERROR, LNG_NOT_OPEN_FILE, 0, 0 );
Exit;
end;
ReadLn(f, strin);
if AnsiPos('CTRL-PTS',strin) <= 0 then
begin
CloseFile(f);
Exit;
end;
ReadLn(f, n_points);
for i := 0 to n_points - 1 do
begin
Read(f, x); ReadLn(f, y);
list_add := lvControlPoints.Items.Add;
if i < 10 then
list_add.Caption := '00' + IntToStr(i)
else if i < 100 then
list_add.Caption := '0' + IntToStr(i)
else
list_add.Caption := IntToStr(i);
list_add.SubItems.Add( IntToStr(x) );
list_add.SubItems.Add( IntToStr(y) );
end;
CloseFile(f);
end;
end;
procedure TfrmFPGImages.FormActivate(Sender: TObject);
begin
_set_lng;
rbMM.Checked := true
end;
procedure TfrmFPGImages.getRBPoint(bmp: TBitmap; var x, y: Longint);
begin
x := 0;
y := 0;
if rbTM.Checked or rbMM.Checked or rbDM.Checked then
x := (bmp.Width div 2) - 1;
if rbTR.Checked or rbMR.Checked or rbDR.Checked then
x := bmp.Width - 1;
if rbML.Checked or rbMM.Checked or rbMR.Checked then
y := (bmp.Height div 2) - 1;
if rbDL.Checked or rbDM.Checked or rbDR.Checked then
y := bmp.Height - 1;
end;
procedure TfrmFPGImages.sbAddPointClick(Sender: TObject);
var
x, y : LongInt;
begin
getRBPoint(TBitmap(Fpg.images[fpg_index]), x, y);
edCoordX.Text := IntToStr( x );
edCoordY.Text := IntToStr( y );
sbAddClick( Sender );
end;
procedure TfrmFPGImages.sbPutCenterClick(Sender: TObject);
var
list_add : TListItem;
x, y : LongInt;
begin
getRBPoint(TBitmap(Fpg.images[fpg_index]), x, y);
if lvControlPoints.Items.Count > 0 then
begin
list_add := lvControlPoints.Items.Item[0];
list_add.SubItems.Strings[0] := IntToStr( x );
list_add.SubItems.Strings[1] := IntToStr( y );
end
else
begin
list_add := lvControlPoints.Items.Add;
lvControlPoints.Items.Item[0].Caption := '000';
list_add.SubItems.Add( IntToStr( x ) );
list_add.SubItems.Add( IntToStr( y ) );
end;
end;
procedure TfrmFPGImages.edCodeEnter(Sender: TObject);
begin
edCode.Color := clWhite;
end;
procedure TfrmFPGImages.edFNameEnter(Sender: TObject);
begin
edFName.Color := clWhite;
end;
procedure TfrmFPGImages.edFNameExit(Sender: TObject);
begin
edFName.Color := clMedGray;
end;
procedure TfrmFPGImages.edNameEnter(Sender: TObject);
begin
edName.Color := clWhite;
end;
procedure TfrmFPGImages.edNameExit(Sender: TObject);
begin
edName.Color := clMedGray;
end;
procedure TfrmFPGImages.edCoordXEnter(Sender: TObject);
begin
edCoordX.Color := clWhite;
end;
procedure TfrmFPGImages.edCoordYEnter(Sender: TObject);
begin
edCoordY.Color := clWhite;
end;
end.
|
//**********************************************************
// Developed by TheUnkownOnes.net
//
// for more information look at www.TheUnknownOnes.net
//**********************************************************
unit uConsoleTools;
interface
uses
Classes,
Controls,
Windows,
WideStrings,
WideStrUtils,
SysUtils,
StrUtils;
type
TConsoleColor = (ccForegroundBlue = FOREGROUND_BLUE,
ccForegroundGreen = FOREGROUND_GREEN,
ccForegroundRed = FOREGROUND_RED,
ccForegroundIntensive = FOREGROUND_INTENSITY,
ccBackgroundBlue = BACKGROUND_BLUE,
ccBackgroundGreen = BACKGROUND_GREEN,
ccBackgroundRed = BACKGROUND_RED,
ccBackgroundIntensive = BACKGROUND_INTENSITY);
TConsoleColors = set of TConsoleColor;
TConsoleProcessWatcher = class;
TConsoleOutputProc = procedure(const AText: string) of object;
TCustomConsoleProcess = class(TComponent)
private
FOnStdOutEvent: TConsoleOutputProc;
FOnStdErrEvent: TConsoleOutputProc;
protected
FWatcher: TConsoleProcessWatcher;
FPipeInputWrite,
FPipeOutputRead,
FPipeErrorRead,
FPipeInputRead,
FPipeOutputWrite,
FPipeErrorWrite: THandle;
FChars: TPoint;
FShowWindow: Boolean;
FFullScreen: Boolean;
FCommandLine: WideString;
FColor: TConsoleColors;
FWindowPos: TRect;
FWindowTitle: WideString;
FProcessInformation: TProcessInformation;
FSecAttr: TSecurityAttributes;
FRunning: Boolean;
FCurrentDir: WideString;
FExitCode: Cardinal;
FHookIO: Boolean;
procedure SetChars(const Value: TPoint);
procedure SetColor(const Value: TConsoleColors);
procedure SetCommandLine(const Value: WideString);
procedure SetFullScreen(const Value: Boolean);
procedure SetShowWindow(const Value: Boolean);
procedure SetWindowPos(const Value: TRect);
procedure SetWindowTitle(const Value: WideString);
procedure SetCurrentDir(const Value: WideString);
procedure SetHookIO(const Value: Boolean);
procedure CheckRunningAndRaiseExceptionIf;
procedure CreatePipes(var AStartupInfos: _STARTUPINFOW);
procedure FreePipe(var APipe: THandle);
procedure OnProcessExit(ACode: Cardinal);
procedure DoStdOut(const AText: string);
procedure DoStdErr(const AText: string);
published
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute(): Boolean;
procedure Input(AData: string);
procedure KillProcess(ACode: Cardinal);
property CommandLine: WideString read FCommandLine write SetCommandLine;
property WindowTitle: WideString read FWindowTitle write SetWindowTitle;
property ShowWindow: Boolean read FShowWindow write SetShowWindow default true;
property WindowRect: TRect read FWindowPos write SetWindowPos;
property Chars: TPoint read FChars write SetChars;
property Color: TConsoleColors read FColor write SetColor;
property FullScreen: Boolean read FFullScreen write SetFullScreen default false;
property CurrentDir: WideString read FCurrentDir write SetCurrentDir;
property HookIO: Boolean read FHookIO write SetHookIO default false;
property OnStdOut: TConsoleOutputProc read FOnStdOutEvent write FOnStdOutEvent;
property OnStdErr: TConsoleOutputProc read FOnStdErrEvent write FOnStdErrEvent;
property ProcessInformation: TProcessInformation read FProcessInformation;
property SecurityAttributes: TSecurityAttributes read FSecAttr write FSecAttr;
property Running: Boolean read FRunning;
property ExitCode: Cardinal read FExitCode;
end;
TConsoleProcess = class(TCustomConsoleProcess)
published
property CommandLine;
property WindowTitle;
property ShowWindow;
property WindowRect;
property Chars;
property FullScreen;
property CurrentDir;
property HookIO;
property OnStdOut;
property OnStdErr;
end;
TConsoleProcessWatcher = class(TThread)
private
FProcess: TCustomConsoleProcess;
FExitCode: Cardinal;
FWideStringBuffer: WideString;
procedure DoProcessExit;
procedure DoStdOut;
procedure DoStdErr;
function ProcessRunning: Boolean;
function PipeHasData(APipe: THandle): Boolean;
function ReadPipe(APipe: THandle): string;
protected
procedure Execute; override;
public
constructor Create(AProcesse: TCustomConsoleProcess); reintroduce;
end;
EProcessRunning = class(Exception)
public
constructor Create();
end;
function GetConsoleColorValue(const AConsoleColors: TConsoleColors): Cardinal;
var
Default_Security_Attributes: TSecurityAttributes;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('TUO', [TConsoleProcess]);
end;
function GetConsoleColorValue(const AConsoleColors: TConsoleColors): Cardinal;
var
Buffer: Cardinal;
Color: TConsoleColor;
begin
Buffer := 0;
for Color in AConsoleColors do
Buffer := Buffer or Cardinal(Color);
Result := Buffer;
end;
{ TCustomConsoleProcess }
procedure TCustomConsoleProcess.CheckRunningAndRaiseExceptionIf;
begin
if FRunning then
raise EProcessRunning.Create;
end;
constructor TCustomConsoleProcess.Create(AOwner: TComponent);
begin
inherited;
FSecAttr := Default_Security_Attributes;
FShowWindow := true;
FWindowPos.TopLeft := Point(0, 0);
FWindowPos.BottomRight := Point(320, 100);
FChars.X := 80;
FChars.Y := 25;
FColor := [ccBackgroundBlue,
ccBackgroundGreen,
ccBackgroundRed,
ccBackgroundIntensive]; //black on white (best for eyes :) )
FCommandLine := EmptyStr;
FCurrentDir := EmptyStr;
FHookIO := false;
FPipeInputWrite := 0;
FPipeOutputRead := 0;
FPipeErrorRead := 0;
FPipeInputRead := 0;
FPipeOutputWrite := 0;
FPipeErrorWrite := 0;
end;
procedure TCustomConsoleProcess.CreatePipes(var AStartupInfos: _STARTUPINFOW);
begin
AStartupInfos.dwFlags := AStartupInfos.dwFlags or STARTF_USESTDHANDLES;
CreatePipe(FPipeInputRead, FPipeInputWrite, @FSecAttr, 0);
CreatePipe(FPipeOutputRead, FPipeOutputWrite, @FSecAttr, 0);
CreatePipe(FPipeErrorRead, FPipeErrorWrite, @FSecAttr, 0);
AStartupInfos.hStdInput := FPipeInputRead;
AStartupInfos.hStdOutput := FPipeOutputWrite;
AStartupInfos.hStdError := FPipeErrorWrite;
end;
destructor TCustomConsoleProcess.Destroy;
begin
inherited;
end;
function TCustomConsoleProcess.Execute: Boolean;
var
SA: _STARTUPINFOW;
CreationFlags: Cardinal;
begin
CheckRunningAndRaiseExceptionIf;
FRunning := false;
FExitCode := 0;
FillMemory(@FProcessInformation, SizeOf(TProcessInformation), 0);
FillMemory(@Sa, SizeOf(TStartupInfo), 0);
Sa.cb := SizeOf(TStartupInfo);
Sa.lpTitle := PWideChar(FWindowTitle);
Sa.dwX := FWindowPos.Left;
Sa.dwY := FWindowPos.Top;
Sa.dwXSize := FWindowPos.Right - FWindowPos.Left;
Sa.dwYSize := FWindowPos.Bottom - FWindowPos.Top;
Sa.dwXCountChars := FChars.X;
Sa.dwYCountChars := FChars.Y;
Sa.dwFillAttribute := GetConsoleColorValue(FColor);
if FShowWindow then
Sa.wShowWindow := 1
else
Sa.wShowWindow := 0;
if FFullScreen then
Sa.dwFlags := STARTF_RUNFULLSCREEN
else
Sa.dwFlags := 0;
Sa.dwFlags := Sa.dwFlags or
STARTF_USESHOWWINDOW or
STARTF_USESIZE or
STARTF_USEPOSITION or
STARTF_USECOUNTCHARS or
STARTF_USEFILLATTRIBUTE;
if Trim(FCurrentDir) = EmptyStr then
FCurrentDir := ExtractFileDir(FCommandLine);
CreationFlags := 0;
if FHookIO then
begin
CreationFlags := CreationFlags or CREATE_NEW_CONSOLE;
CreatePipes(Sa);
end;
Result := CreateProcessW(nil,
PWideChar(FCommandLine),
@FSecAttr,
@FSecAttr,
True,
CreationFlags,
nil,
PWideChar(FCurrentDir),
Sa,
FProcessInformation);
FRunning := Result;
if not Result then
RaiseLastOSError
else
begin
FWatcher := TConsoleProcessWatcher.Create(Self);
FreePipe(FPipeInputRead);
FreePipe(FPipeOutputWrite);
FreePipe(FPipeErrorWrite);
end;
end;
procedure TCustomConsoleProcess.KillProcess(ACode: Cardinal);
begin
if Running then
TerminateProcess(FProcessInformation.hProcess, ACode);
end;
procedure TCustomConsoleProcess.FreePipe(var APipe: THandle);
begin
if APipe > 0 then
begin
CloseHandle(APipe);
APipe := 0;
end;
end;
procedure TCustomConsoleProcess.Input(AData: string);
var
Written: Cardinal;
begin
if FRunning and FHookIO then
begin
WriteFile(FPipeInputWrite, AData[1], Length(AData), Written, nil);
//FlushFileBuffers(FPipeInputWrite);
end;
end;
procedure TCustomConsoleProcess.OnProcessExit(ACode: Cardinal);
begin
FRunning := false;
FExitCode := ACode;
FWatcher := nil;
FreePipe(FPipeInputWrite);
FreePipe(FPipeOutputRead);
FreePipe(FPipeErrorRead);
end;
procedure TCustomConsoleProcess.DoStdErr(const AText: string);
begin
if Assigned(FOnStdErrEvent) then
FOnStdErrEvent(AText);
end;
procedure TCustomConsoleProcess.DoStdOut(const AText: string);
begin
if Assigned(FOnStdOutEvent) then
FOnStdOutEvent(AText);
end;
procedure TCustomConsoleProcess.SetChars(const Value: TPoint);
begin
CheckRunningAndRaiseExceptionIf;
FChars := Value;
end;
procedure TCustomConsoleProcess.SetColor(const Value: TConsoleColors);
begin
CheckRunningAndRaiseExceptionIf;
FColor := Value;
end;
procedure TCustomConsoleProcess.SetCommandLine(const Value: WideString);
begin
CheckRunningAndRaiseExceptionIf;
FCommandLine := Value;
end;
procedure TCustomConsoleProcess.SetCurrentDir(const Value: WideString);
begin
CheckRunningAndRaiseExceptionIf;
FCurrentDir := Value;
end;
procedure TCustomConsoleProcess.SetFullScreen(const Value: Boolean);
begin
CheckRunningAndRaiseExceptionIf;
FFullScreen := Value;
end;
procedure TCustomConsoleProcess.SetHookIO(const Value: Boolean);
begin
CheckRunningAndRaiseExceptionIf;
FHookIO := Value;
end;
procedure TCustomConsoleProcess.SetShowWindow(const Value: Boolean);
begin
CheckRunningAndRaiseExceptionIf;
FShowWindow := Value;
end;
procedure TCustomConsoleProcess.SetWindowPos(const Value: TRect);
begin
CheckRunningAndRaiseExceptionIf;
FWindowPos := Value;
end;
procedure TCustomConsoleProcess.SetWindowTitle(const Value: WideString);
begin
CheckRunningAndRaiseExceptionIf;
FWindowTitle := Value;
end;
{ TConsoleProcessWatcher }
constructor TConsoleProcessWatcher.Create(AProcesse: TCustomConsoleProcess);
begin
Assert(Assigned(AProcesse), 'Please supply a valid ConsoleProcess');
FProcess := AProcesse;
FreeOnTerminate := true;
inherited Create(false);
end;
procedure TConsoleProcessWatcher.DoProcessExit;
begin
FProcess.OnProcessExit(FExitCode);
end;
procedure TConsoleProcessWatcher.DoStdErr;
begin
FProcess.DoStdErr(FWideStringBuffer);
end;
procedure TConsoleProcessWatcher.DoStdOut;
begin
FProcess.DoStdOut(FWideStringBuffer);
end;
procedure TConsoleProcessWatcher.Execute;
var
GoHome: Boolean;
begin
GoHome := false;
while not (Suspended or Terminated or GoHome) do
begin
if PipeHasData(FProcess.FPipeOutputRead) then
begin
FWideStringBuffer := ReadPipe(FProcess.FPipeOutputRead);
Synchronize(DoStdOut);
FWideStringBuffer := EmptyStr;
end;
if PipeHasData(FProcess.FPipeErrorRead) then
begin
FWideStringBuffer := ReadPipe(FProcess.FPipeErrorRead);
Synchronize(DoStdErr);
FWideStringBuffer := EmptyStr;
end;
if not ProcessRunning then
begin
GetExitCodeProcess(FProcess.ProcessInformation.hProcess, FExitCode);
Synchronize(DoProcessExit);
GoHome := true;
end;
end;
end;
function TConsoleProcessWatcher.PipeHasData(APipe: THandle): Boolean;
var
BytesAvailable: Cardinal;
begin
Result := PeekNamedPipe(APipe, nil, 0, nil, @BytesAvailable, nil) and (BytesAvailable > 0);
end;
function TConsoleProcessWatcher.ProcessRunning: Boolean;
begin
Result := WaitForSingleObject(FProcess.ProcessInformation.hProcess, 50) <> WAIT_OBJECT_0;
end;
function TConsoleProcessWatcher.ReadPipe(APipe: THandle): string;
var
BytesAvailable,
BytesRead: Cardinal;
begin
Result := EmptyStr;
if PeekNamedPipe(APipe, nil, 0, nil, @BytesAvailable, nil) and
(BytesAvailable > 0) then
begin
SetLength(Result, BytesAvailable * Sizeof(Result[1]));
ReadFile(APipe, Result[1], BytesAvailable, BytesRead, nil);
end;
end;
{ EProcessRunning }
constructor EProcessRunning.Create;
begin
inherited Create('The process is still running');
end;
initialization
Default_Security_Attributes.nLength := SizeOf(TSecurityAttributes);
Default_Security_Attributes.bInheritHandle := true;
end.
|
unit SysMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ComCtrls, StdCtrls, cxButtons, ExtCtrls,
Ibase, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet,
cxRadioGroup, cxDBEdit, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxButtonEdit, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxDBData, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid,
ToolWin, ImgList,pfibStoredProc, cxCheckBox, cxGridBandedTableView,
cxGridDBBandedTableView, Placemnt, cxDropDownEdit, cxCalendar;
type
TfrmSysOptions = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
cxButton2: TcxButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
WorkDatabase: TpFIBDatabase;
DefOptionDataSet: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
DefOptionDataSource: TDataSource;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
cxGrid1DBTableView1DBColumn1: TcxGridDBColumn;
cxGrid1DBTableView1DBColumn2: TcxGridDBColumn;
SysUchDataSet: TpFIBDataSet;
SysUchDataSource: TDataSource;
SmallImages: TImageList;
cxGrid1DBTableView1DBColumn3: TcxGridDBColumn;
SysInfoDataSet: TpFIBDataSet;
SysInfoDataSource: TDataSource;
Label5: TLabel;
cxDBTextEdit3: TcxDBTextEdit;
Label6: TLabel;
cxDBTextEdit4: TcxDBTextEdit;
Label7: TLabel;
cxDBTextEdit5: TcxDBTextEdit;
cxDBCheckBox1: TcxDBCheckBox;
Label8: TLabel;
cxDBTextEdit6: TcxDBTextEdit;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
cxDBTextEdit7: TcxDBTextEdit;
TabSheet4: TTabSheet;
cxGrid2: TcxGrid;
cxGridDBTableView1: TcxGridDBTableView;
cxGridDBColumn2: TcxGridDBColumn;
cxGridDBColumn3: TcxGridDBColumn;
cxGridLevel1: TcxGridLevel;
cxGridDBTableView1DBColumn1: TcxGridDBColumn;
ToolBar2: TToolBar;
RegUchDataSet: TpFIBDataSet;
RegUchDataSource: TDataSource;
ToolBar3: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
cxGrid1DBTableView1DBColumn5: TcxGridDBColumn;
cxGridDBTableView1DBColumn2: TcxGridDBColumn;
cxStyle2: TcxStyle;
cxGrid1DBTableView1DBColumn4: TcxGridDBColumn;
cxGrid1DBTableView1DBColumn6: TcxGridDBColumn;
TabSheet5: TTabSheet;
cxGrid3: TcxGrid;
cxGridDBTableView2: TcxGridDBTableView;
cxGridDBColumn4: TcxGridDBColumn;
cxGridDBColumn6: TcxGridDBColumn;
cxGridLevel2: TcxGridLevel;
ToolBar1: TToolBar;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
DocsTypeDataSet: TpFIBDataSet;
DocsTypeDataSource: TDataSource;
cxGridDBTableView2DBColumn1: TcxGridDBColumn;
TabSheet6: TTabSheet;
PageControl2: TPageControl;
TabSheet7: TTabSheet;
GroupBox1: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
CheckConfDefaultBu: TRadioGroup;
cxDBButtonEdit1: TcxDBButtonEdit;
cxDBTextEdit1: TcxDBTextEdit;
cxDBTextEdit2: TcxDBTextEdit;
TabSheet8: TTabSheet;
GroupBox2: TGroupBox;
Label4: TLabel;
cxDBButtonEdit4: TcxDBButtonEdit;
CheckConfDefaultKV: TRadioGroup;
TabSheet9: TTabSheet;
CheckKekv: TcxCheckBox;
CHECK_FOND_PLUS_GROUP: TcxCheckBox;
CheckKernelBlock: TcxCheckBox;
CHECK_SPIS_BY_SM_RZ_ST: TcxCheckBox;
ToolBar4: TToolBar;
ToolButton10: TToolButton;
ToolButton11: TToolButton;
ToolButton12: TToolButton;
cxGrid4: TcxGrid;
cxGrid2DBBandedTableView1: TcxGridDBBandedTableView;
cxGrid2DBBandedTableView1DBBandedColumn1: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn2: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn3: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn4: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn5: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn6: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn7: TcxGridDBBandedColumn;
cxGridLevel3: TcxGridLevel;
cxGrid2DBBandedTableView1DBBandedColumn8: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn9: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn10: TcxGridDBBandedColumn;
cxGrid2DBBandedTableView1DBBandedColumn11: TcxGridDBBandedColumn;
TemplateDataSet: TpFIBDataSet;
TemplateDataSource: TDataSource;
Panel3: TPanel;
cxDBCheckBox2: TcxDBCheckBox;
MAIN_BUHG_FIO: TcxTextEdit;
Label12: TLabel;
Label13: TLabel;
RECTOR_FIO: TcxTextEdit;
cxButton1: TcxButton;
FormStorage1: TFormStorage;
TabSheet10: TTabSheet;
cxButtonEdit1: TcxButtonEdit;
Label18: TLabel;
LinksDataSet: TpFIBDataSet;
LinksDataSource: TDataSource;
PageControl3: TPageControl;
TabSheet11: TTabSheet;
Label16: TLabel;
EdOnlyInCredit: TcxTextEdit;
Label17: TLabel;
EdOnlyInDb: TcxTextEdit;
Label14: TLabel;
EDMainSchNDS: TcxTextEdit;
Label15: TLabel;
EDStNeedNDS: TcxTextEdit;
Label19: TLabel;
cxButton3: TcxButton;
cxButton4: TcxButton;
cxGrid5: TcxGrid;
cxGridDBTableView3: TcxGridDBTableView;
cxGridDBColumn1: TcxGridDBColumn;
cxGridLevel4: TcxGridLevel;
TabSheet12: TTabSheet;
Label20: TLabel;
cxButton5: TcxButton;
cxButton6: TcxButton;
cxGrid6: TcxGrid;
cxGridDBTableView4: TcxGridDBTableView;
cxGridDBColumn7: TcxGridDBColumn;
cxGridLevel5: TcxGridLevel;
cxGridDBTableView4DBColumn1: TcxGridDBColumn;
SchFilterDataSet: TpFIBDataSet;
SchFilterDataSource: TDataSource;
DateForSprav: TcxDateEdit;
Label21: TLabel;
KERNELL_CHECK_SM_PLUS_KEKV: TcxCheckBox;
KERNELL_USE_HISTORY: TcxCheckBox;
CHECK_CLOSING_IN_BUDGETS: TcxCheckBox;
TabSheet13: TTabSheet;
FINANCE_NUM_PROP: TcxTextEdit;
Label22: TLabel;
ToolButton13: TToolButton;
ToolButton14: TToolButton;
Label23: TLabel;
cxDBTextEdit8: TcxDBTextEdit;
cxGridDBTableView1DBColumn3: TcxGridDBColumn;
Label24: TLabel;
CLOSE_FINANCE_RESULTS_DOX: TcxTextEdit;
Label25: TLabel;
CLOSE_FINANCE_RESULTS_RASX: TcxTextEdit;
Label26: TLabel;
CLOSE_FINANCE_RESULTS: TcxTextEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ToolButton1Click(Sender: TObject);
procedure cxDBButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxDBButtonEdit4PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxButton2Click(Sender: TObject);
procedure ToolButton2Click(Sender: TObject);
procedure ToolButton4Click(Sender: TObject);
procedure ToolButton5Click(Sender: TObject);
procedure ToolButton3Click(Sender: TObject);
procedure ToolButton9Click(Sender: TObject);
procedure ToolButton6Click(Sender: TObject);
procedure ToolButton7Click(Sender: TObject);
procedure ToolButton8Click(Sender: TObject);
procedure CheckKernelBlockPropertiesChange(Sender: TObject);
procedure CheckConfDefaultBuClick(Sender: TObject);
procedure CheckConfDefaultKVClick(Sender: TObject);
procedure CheckKekvPropertiesChange(Sender: TObject);
procedure CHECK_FOND_PLUS_GROUPPropertiesChange(Sender: TObject);
procedure CHECK_SPIS_BY_SM_RZ_STPropertiesChange(Sender: TObject);
procedure ToolButton10Click(Sender: TObject);
procedure ToolButton11Click(Sender: TObject);
procedure ToolButton12Click(Sender: TObject);
procedure cxButton1Click(Sender: TObject);
procedure cxButton3Click(Sender: TObject);
procedure cxButton4Click(Sender: TObject);
procedure cxButton5Click(Sender: TObject);
procedure cxButton6Click(Sender: TObject);
procedure ToolButton13Click(Sender: TObject);
private
public
constructor Create(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE);reintroduce;
procedure SetBuConfigure;
procedure SetKVConfigure;
end;
procedure GetSysOptions(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE);stdcall;
exports GetSysOptions;
implementation
uses GlobalSPR, UEditRegUch, BaseTypes,
UEditFormUch, UEditTypeDoc, UEditTemplate;
{$R *.dfm}
{ TfrmSysOptions }
procedure GetSysOptions(AOwner:TComponent;DB_HANDLE:TISC_DB_HANDLE);
var f:Boolean;
i:Integer;
begin
f:=true;
for i:=0 to Application.MainForm.MDIChildCount-1 do
begin
if (Application.MainForm.MDIChildren[i] is TfrmSysOptions)
then begin
Application.MainForm.MDIChildren[i].BringToFront;
f:=false;
end;
end;
if f then TfrmSysOptions.Create(AOwner,DB_HANDLE);
end;
constructor TfrmSysOptions.Create(AOwner: TComponent;DB_HANDLE: TISC_DB_HANDLE);
begin
inherited Create(AOwner);
WorkDatabase.Handle:=DB_HANDLE;
DefOptionDataSet.Open;
if (DefOptionDataSet.FieldByName('USE_DEFAULT_VALUES').AsBoolean)
then begin
CheckConfDefaultBu.ItemIndex:=0;
SetBuConfigure;
end;
if (DefOptionDataSet.FieldByName('USE_DEFAULT_KEKV').AsBoolean)
then begin
CheckConfDefaultKV.ItemIndex:=0;
SetKVConfigure;
end;
if (DefOptionDataSet.FieldByName('KERNELL_IS_BLOCK').AsBoolean)
then CheckKernelBlock.Checked:=true
else CheckKernelBlock.Checked:=false;
if (DefOptionDataSet.FieldByName('KERNELL_CHECK_KEKV').AsBoolean)
then CheckKekv.Checked:=true
else CheckKekv.Checked:=false;
if (DefOptionDataSet.FieldByName('CHECK_FOND_PLUS_GROUP').AsBoolean)
then CHECK_FOND_PLUS_GROUP.Checked:=true
else CHECK_FOND_PLUS_GROUP.Checked:=false;
if (DefOptionDataSet.FieldByName('CHECK_SPIS_BY_SM_RZ_ST').AsBoolean)
then CHECK_SPIS_BY_SM_RZ_ST.Checked:=true
else CHECK_SPIS_BY_SM_RZ_ST.Checked:=false;
if (DefOptionDataSet.FieldByName('MAIN_BUHG_FIO').Value<>null)
then MAIN_BUHG_FIO.Text:=DefOptionDataSet.FieldByName('MAIN_BUHG_FIO').AsString
else MAIN_BUHG_FIO.Text:='';
if (DefOptionDataSet.FieldByName('RECTOR_FIO').Value<>null)
then RECTOR_FIO.Text:=DefOptionDataSet.FieldByName('RECTOR_FIO').AsString
else RECTOR_FIO.Text:='';
if (DefOptionDataSet.FieldByName('NDS_NUM_PROP').Value<>null)
then EDMainSchNDS.Text:=DefOptionDataSet.FieldByName('NDS_NUM_PROP').AsString
else EDMainSchNDS.Text:='0';
if (DefOptionDataSet.FieldByName('ST_NDS_NUM_PROP').Value<>null)
then EDStNeedNDS.Text:=DefOptionDataSet.FieldByName('ST_NDS_NUM_PROP').AsString
else EDStNeedNDS.Text:='0';
if (DefOptionDataSet.FieldByName('SALDO_ONLY_IN_KR').Value<>null)
then EdOnlyInCredit.Text:=DefOptionDataSet.FieldByName('SALDO_ONLY_IN_KR').AsString
else EdOnlyInCredit.Text:='0';
if (DefOptionDataSet.FieldByName('SALDO_ONLY_IN_DB').Value<>null)
then EdOnlyInDb.Text:=DefOptionDataSet.FieldByName('SALDO_ONLY_IN_DB').AsString
else EdOnlyInDb.Text:='0';
if (DefOptionDataSet.FieldByName('KERNELL_CHECK_SM_PLUS_KEKV').Value<>null)
then KERNELL_CHECK_SM_PLUS_KEKV.Checked:=Boolean(DefOptionDataSet.FieldByName('KERNELL_CHECK_SM_PLUS_KEKV').AsInteger)
else KERNELL_CHECK_SM_PLUS_KEKV.Checked:=false;
if (DefOptionDataSet.FieldByName('KERNELL_USE_HISTORY').Value<>null)
then KERNELL_USE_HISTORY.Checked:=Boolean(DefOptionDataSet.FieldByName('KERNELL_USE_HISTORY').AsInteger)
else KERNELL_USE_HISTORY.Checked:=false;
if (DefOptionDataSet.FieldByName('CHECK_CLOSING_IN_BUDGETS').Value<>null)
then CHECK_CLOSING_IN_BUDGETS.Checked:=Boolean(DefOptionDataSet.FieldByName('CHECK_CLOSING_IN_BUDGETS').AsInteger)
else CHECK_CLOSING_IN_BUDGETS.Checked:=false;
if (DefOptionDataSet.FieldByName('FINANCE_NUM_PROP').Value<>null)
then FINANCE_NUM_PROP.Text:=DefOptionDataSet.FieldByName('FINANCE_NUM_PROP').AsString
else FINANCE_NUM_PROP.Text:='';
if (DefOptionDataSet.FieldByName('CLOSE_FINANCE_RESULTS').Value<>null)
then CLOSE_FINANCE_RESULTS.Text:=DefOptionDataSet.FieldByName('CLOSE_FINANCE_RESULTS').AsString
else CLOSE_FINANCE_RESULTS.Text:='';
if (DefOptionDataSet.FieldByName('CLOSE_FINANCE_RESULTS_RASX').Value<>null)
then CLOSE_FINANCE_RESULTS_RASX.Text:=DefOptionDataSet.FieldByName('CLOSE_FINANCE_RESULTS_RASX').AsString
else CLOSE_FINANCE_RESULTS_RASX.Text:='';
if (DefOptionDataSet.FieldByName('CLOSE_FINANCE_RESULTS_DOX').Value<>null)
then CLOSE_FINANCE_RESULTS_DOX.Text:=DefOptionDataSet.FieldByName('CLOSE_FINANCE_RESULTS_DOX').AsString
else CLOSE_FINANCE_RESULTS_DOX.Text:='';
DateForSprav.Date:=Date;
SchFilterDataSet.SelectSQL.Text:='SELECT * FROM MBOOK_SCH_Z_SELECT';
SysUchDataSet.Open;
SysInfoDataSet.SelectSQL.Text:=' select * from PUB_SYS_DATA_SELECT ';
SysInfoDataSet.Open;
RegUchDataSet.Open;
DocsTypeDataSet.Open;
TemplateDataSet.open;
LinksDataSet.open;
SchFilterDataSet.Open;
PageControl1.ActivePageIndex:=0;
end;
procedure TfrmSysOptions.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TfrmSysOptions.ToolButton1Click(Sender: TObject);
var UpdateStateSP:TpfibStoredProc;
id:Integer;
frmEditFormUch: TfrmEditFormUch;
begin
frmEditFormUch:=TfrmEditFormUch.Create(self);
frmEditFormUch.WorkGroup.ItemIndex :=SysUchDataSet.FieldByName('IS_WORKING').AsInteger;
frmEditFormUch.CheckMenGroup.ItemIndex:=SysUchDataSet.FieldByName('CHECK_ID_MEN').AsInteger;
frmEditFormUch.CheckDogGroup.ItemIndex:=SysUchDataSet.FieldByName('CHECK_DOG').AsInteger;
if frmEditFormUch.ShowModal=mrYes
then begin
UpdateStateSP:=TpfibStoredProc.Create(self);
UpdateStateSP.Database:=WorkDatabase;
UpdateStateSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdateStateSP.StoredProcName:='PUB_SP_SYSTEM_UPDATE';
UpdateStateSP.Prepare;
id :=SysUchDataSet.FieldByName('ID_SYSTEM').AsInteger;
UpdateStateSP.ParamByName('ID_SYSTEM').Value := SysUchDataSet.FieldByName('ID_SYSTEM').Value;
UpdateStateSP.ParamByName('IS_WORKING').Value := frmEditFormUch.WorkGroup.ItemIndex;
UpdateStateSP.ParamByName('CHECK_ID_MEN').Value := frmEditFormUch.CheckMenGroup.ItemIndex;
UpdateStateSP.ParamByName('CHECK_DOG').Value := frmEditFormUch.CheckDogGroup.ItemIndex;
UpdateStateSP.ExecProc;
WriteTransaction.Commit;
UpdateStateSP.Free;
SysUchDataSet.CloseOpen(true);
SysUchDataSet.Locate('ID_SYSTEM',id,[]);
end;
end;
procedure TfrmSysOptions.cxDBButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var id:Variant;
UpdProc:TpFibStoredProc;
begin
id:=GlobalSPR.GetSmets(self,WorkDatabase.Handle,SysInfoDataSet.FieldByName('MAIN_BOOK_DATE').AsDateTime,psmRazdSt);
if VarArrayDimCount(id)>0
then begin
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE';
UpdProc.Prepare;
UpdProc.ParamByName('USE_DEFAULT_VALUES').AsInteger:=1;
UpdProc.ParamByName('DEFAULT_SMETA').Value :=id[0];
UpdProc.ParamByName('DEFAULT_RAZD').Value :=id[1];
UpdProc.ParamByName('DEFAULT_ST').Value :=id[2];
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end;
end;
procedure TfrmSysOptions.cxDBButtonEdit4PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var id:Variant;
UpdProc:TpFibStoredProc;
begin
id:=GlobalSpr.GetKEKVSpr(self,WorkDatabase.Handle,fsNormal,SysInfoDataSet.FieldByName('MAIN_BOOK_DATE').AsDateTime,DEFAULT_ROOT_ID);
if VarArrayDimCount(id)>0
then begin
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE_KV';
UpdProc.Prepare;
UpdProc.ParamByName('USE_DEFAULT_KEKV').AsInteger:=1;
UpdProc.ParamByName('DEFAULT_KEKV').Value :=id[0][0];
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end;
end;
procedure TfrmSysOptions.cxButton2Click(Sender: TObject);
var GlobalConstsSP:TpFibStoredProc;
begin
GlobalConstsSP:=TpFibStoredProc.Create(self);
GlobalConstsSP.Database:=WorkDatabase;
GlobalConstsSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
GlobalConstsSP.StoredProcName:='MBOOK_INI_GCONST_UPDATE';
GlobalConstsSP.Prepare;
GlobalConstsSP.ParamByName('MAIN_BUHG_FIO').Value :=MAIN_BUHG_FIO.Text;
GlobalConstsSP.ParamByName('RECTOR_FIO').Value :=RECTOR_FIO.Text;
GlobalConstsSP.ParamByName('NDS_NUM_PROP').Value :=EDMainSchNDS.Text;
GlobalConstsSP.ParamByName('ST_NDS_NUM_PROP').Value :=EDStNeedNDS.Text;
GlobalConstsSP.ParamByName('SALDO_ONLY_IN_KR').Value:=EdOnlyInCredit.Text;
GlobalConstsSP.ParamByName('SALDO_ONLY_IN_DB').Value:=EdOnlyInDb.Text;
GlobalConstsSP.ParamByName('KERNELL_CHECK_SM_PLUS_KEKV').Value:=Integer(KERNELL_CHECK_SM_PLUS_KEKV.Checked);
GlobalConstsSP.ParamByName('KERNELL_USE_HISTORY').Value :=Integer(KERNELL_USE_HISTORY.Checked);
GlobalConstsSP.ParamByName('CHECK_CLOSING_IN_BUDGETS').Value :=Integer(CHECK_CLOSING_IN_BUDGETS.Checked);
GlobalConstsSP.ParamByName('FINANCE_NUM_PROP').Value :=FINANCE_NUM_PROP.Text;
GlobalConstsSP.ParamByName('CLOSE_FINANCE_RESULTS').Value :=CLOSE_FINANCE_RESULTS.Text;
GlobalConstsSP.ParamByName('CLOSE_FINANCE_RESULTS_DOX').Value :=CLOSE_FINANCE_RESULTS_DOX.Text;
GlobalConstsSP.ParamByName('CLOSE_FINANCE_RESULTS_RASX').Value:=CLOSE_FINANCE_RESULTS_RASX.Text;
GlobalConstsSP.ExecProc;
WriteTransaction.Commit;
GlobalConstsSP.Free;
Close;
end;
procedure TfrmSysOptions.ToolButton2Click(Sender: TObject);
var T:TfrmEditReg;
InsertStoredProc:TpFibStoredProc;
Id_reg:Integer;
begin
T:=TfrmEditReg.Create(self);
T.N_PP.Text:=IntToStr(RegUchDataSet.RecordCount+1);
if T.ShowModal=mrYes
then begin
InsertStoredProc:=TpFibStoredProc.Create(self);
InsertStoredProc.Database:=WorkDatabase;
InsertStoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertStoredProc.StoredProcName:='PUB_SP_REG_UCH_INSERT';
InsertStoredProc.Prepare;
InsertStoredProc.ParamByName('REG_TITLE').Value:=T.Edit1.Text;
InsertStoredProc.ParamByName('REG_SHORT').Value:=T.Edit2.Text;
InsertStoredProc.ParamByName('ID_FORM_UCH').Value:=T.DBLookupComboBox1.KeyValue;
InsertStoredProc.ParamByName('REG_KOD').Value:=T.Edit3.Text;
InsertStoredProc.ParamByName('N_PP').Value:=T.N_PP.Text;
try
InsertStoredProc.ExecProc;
except on E:Exception do
begin
ShowMessage('Помилка при роботі з регістрами обліку. Зверніться до адміністратора!');
end;
end;
Id_reg:=InsertStoredProc.ParamByName('ID_REG').AsInteger;
WriteTransaction.Commit;
InsertStoredProc.Free;
cxGrid1.BeginUpdate;
RegUchDataSet.CloseOpen(true);
RegUchDataSet.Locate('ID_REG',id_reg,[]);
cxGrid1.EndUpdate;
end;
T.Free;
end;
procedure TfrmSysOptions.ToolButton4Click(Sender: TObject);
var T:TfrmEditReg;
InsertStoredProc:TpFibStoredProc;
Id_reg:Integer;
begin
if (RegUchDataSet.RecordCount>0)
then begin
T:=TfrmEditReg.Create(self);
T.Edit1.Text:=RegUchDataSet.FieldByName('REG_TITLE').AsString;
T.Edit2.Text:=RegUchDataSet.FieldByName('REG_SHORT').AsString;
T.Edit3.Text:=RegUchDataSet.FieldByName('REG_KOD').AsString;
T.N_PP.Text :=RegUchDataSet.FieldByName('N_PP').AsString;
T.DBLookupComboBox1.KeyValue:=RegUchDataSet.FieldByName('ID_FORM_UCH').AsInteger;
if T.ShowModal=mrYes
then begin
InsertStoredProc:=TpFibStoredProc.Create(self);
InsertStoredProc.Database:=WorkDatabase;
InsertStoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertStoredProc.StoredProcName:='PUB_SP_REG_UCH_UPDATE';
InsertStoredProc.Prepare;
id_reg:=RegUchDataSet.FieldByName('ID_REG').AsInteger;
InsertStoredProc.ParamByName('ID_REG').Value:=RegUchDataSet.FieldByName('ID_REG').AsInteger;
InsertStoredProc.ParamByName('REG_TITLE').Value:=T.Edit1.Text;
InsertStoredProc.ParamByName('REG_SHORT').Value:=T.Edit2.Text;
InsertStoredProc.ParamByName('REG_KOD').Value:=T.Edit3.Text;
InsertStoredProc.ParamByName('ID_FORM_UCH').Value:=T.DBLookupComboBox1.KeyValue;
InsertStoredProc.ParamByName('N_PP').Value:=T.N_PP.Text;
try
InsertStoredProc.ExecProc;
except on E:Exception do
begin
ShowMessage('Помилка при роботі з регістрами обліку. Зверніться до адміністратора!');
end;
end;
WriteTransaction.Commit;
InsertStoredProc.Free;
cxGrid1.BeginUpdate;
RegUchDataSet.CloseOpen(true);
RegUchDataSet.Locate('ID_REG',id_reg,[]);
cxGrid1.EndUpdate;
end;
T.Free;
end;
end;
procedure TfrmSysOptions.ToolButton5Click(Sender: TObject);
begin
RegUchDataSet.CloseOpen(true);
SysUchDataSet.CloseOpen(true);
end;
procedure TfrmSysOptions.ToolButton3Click(Sender: TObject);
var InsertStoredProc:TpFibStoredProc;
begin
if (RegUchDataSet.RecordCount>0)
then begin
if BaseTypes.agMessageDlg('Увага!','Ви хочете видалити регістр обліку?',mtWarning,[mbYes,mbNo])=mrYes
then begin
InsertStoredProc:=TpFibStoredProc.Create(self);
InsertStoredProc.Database:=WorkDatabase;
InsertStoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertStoredProc.StoredProcName:='PUB_SP_REG_UCH_DELETE';
InsertStoredProc.Prepare;
InsertStoredProc.ParamByName('ID_REG').Value:=RegUchDataSet.FieldByName('ID_REG').AsInteger;
InsertStoredProc.ExecProc;
WriteTransaction.Commit;
InsertStoredProc.Free;
RegUchDataSet.CacheDelete;
end;
end;
end;
procedure TfrmSysOptions.ToolButton9Click(Sender: TObject);
var id:integer;
begin
Id:=-1;
cxGrid3.BeginUpdate;
if DocsTypeDataSet.RecordCount>0 then id:=DocsTypeDataSet.FieldByName('ID_TYPE_DOC').Value;
DocsTypeDataSet.CloseOpen(true);
DocsTypeDataSet.Locate('ID_TYPE_DOC',Id,[]);
cxGrid3.EndUpdate;
end;
procedure TfrmSysOptions.ToolButton6Click(Sender: TObject);
var T:TfrmEditDocType;
InsertSp:TpFibStoredProc;
NewId:Integer;
begin
T:=TfrmEditDocType.Create(self);
if T.ShowModal=mrYes
then begin
InsertSp:=TpFibStoredProc.Create(nil);
InsertSp.database:=WorkDatabase;
InsertSp.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertSp.StoredProcName:='PUB_INI_TYPE_DOC_INSERT';
InsertSp.Prepare;
InsertSp.ParamByName('TYPE_DOC_TITLE').Value:=T.cxTextEdit1.Text;
InsertSp.ParamByName('TYPE_DOC_SHORT').Value:=T.cxTextEdit2.Text;
InsertSp.ParamByName('ID_FORM_KOD').Value :=T.SysLookUp.EditValue;
InsertSp.ParamByName('ID_REG_UCH').Value :=T.RegLookUp.EditValue;
InsertSp.ExecProc;
NewId:=InsertSp.ParamByName('ID_TYPE_DOC').Value;
WriteTransaction.Commit;
cxGrid3.BeginUpdate;
DocsTypeDataSet.CloseOpen(true);
DocsTypeDataSet.Locate('ID_TYPE_DOC',NewId,[]);
cxGrid3.BeginUpdate;
end;
T.Free;
end;
procedure TfrmSysOptions.ToolButton7Click(Sender: TObject);
var DeleteSp:TpFibStoredProc;
begin
if (DocsTypeDataSet.RecordCount>0)
then begin
if BaseTypes.agMessageDlg('Увага!','Ви хочете видалити тип документу?',mtWarning,[mbYes,mbNo])=mrYes
then begin
DeleteSp:=TpFibStoredProc.Create(nil);
DeleteSp.database:=WorkDatabase;
DeleteSp.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
DeleteSp.StoredProcName:='PUB_INI_TYPE_DOC_DELETE';
DeleteSp.Prepare;
DeleteSp.ParamByName('ID_TYPE_DOC').Value:=DocsTypeDataSet.FieldByName('ID_TYPE_DOC').Value;
DeleteSp.ExecProc;
WriteTransaction.Commit;
DocsTypeDataSet.CloseOpen(true);
end;
end;
end;
procedure TfrmSysOptions.ToolButton8Click(Sender: TObject);
var T:TfrmEditDocType;
UpdateSp:TpFibStoredProc;
NewId:Integer;
begin
if DocsTypedataSet.RecordCount>0
then begin
T:=TfrmEditDocType.Create(self);
T.cxTextEdit1.Text:=DocsTypeDataSet.FieldByName('TYPE_DOC_TITLE').AsString;
T.cxTextEdit2.Text:=DocsTypeDataSet.FieldByName('TYPE_DOC_SHORT').AsString;
T.SysLookUp.EditValue:=DocsTypeDataSet.FieldByName('ID_FORM_KOD').Value;
T.RegLookUp.EditValue:=DocsTypeDataSet.FieldByName('ID_REG_UCH').Value;
if T.ShowModal=mrYes
then begin
UpdateSp:=TpFibStoredProc.Create(nil);
UpdateSp.database:=WorkDatabase;
UpdateSp.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdateSp.StoredProcName:='PUB_INI_TYPE_DOC_UPDATE';
UpdateSp.Prepare;
NewId:=DocsTypeDataSet.FieldByName('ID_TYPE_DOC').Value;
UpdateSp.ParamByName('ID_TYPE_DOC').Value:=DocsTypeDataSet.FieldByName('ID_TYPE_DOC').Value;
UpdateSp.ParamByName('TYPE_DOC_TITLE').Value:=T.cxTextEdit1.Text;
UpdateSp.ParamByName('TYPE_DOC_SHORT').Value:=T.cxTextEdit2.Text;
UpdateSp.ParamByName('ID_FORM_KOD').Value :=T.SysLookUp.EditValue;
UpdateSp.ParamByName('ID_REG_UCH').Value :=T.RegLookUp.EditValue;
UpdateSp.ExecProc;
WriteTransaction.Commit;
cxGrid3.BeginUpdate;
DocsTypeDataSet.CloseOpen(true);
DocsTypeDataSet.Locate('ID_TYPE_DOC',NewId,[]);
cxGrid3.EndUpdate;
end;
T.Free;
end;
end;
procedure TfrmSysOptions.CheckKernelBlockPropertiesChange(Sender: TObject);
var UpdProc:TpFibStoredProc;
begin
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE_EX';
UpdProc.Prepare;
UpdProc.ParamByName('KERNELL_IS_BLOCK').AsInteger :=Integer(CheckKernelBlock.Checked);
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end;
procedure TfrmSysOptions.SetBuConfigure;
var UpdProc:TpFibStoredProc;
begin
if (CheckConfDefaultBu.ItemIndex=0)
then begin
cxDBButtonEdit1.Enabled:=true;
cxDBTextEdit1.Enabled:=true;
cxDBTextEdit2.Enabled:=true;
Label1.Enabled:=true;
Label2.Enabled:=true;
Label3.Enabled:=true;
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE';
UpdProc.Prepare;
UpdProc.ParamByName('USE_DEFAULT_VALUES').AsInteger:=1;
UpdProc.ParamByName('DEFAULT_SMETA').Value :=DefOptionDataSet.FieldByName('DEFAULT_SMETA').Value;
UpdProc.ParamByName('DEFAULT_RAZD').Value :=DefOptionDataSet.FieldByName('DEFAULT_RAZD').Value;
UpdProc.ParamByName('DEFAULT_ST').Value :=DefOptionDataSet.FieldByName('DEFAULT_ST').Value;
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end
else begin
cxDBButtonEdit1.Enabled:=false;
cxDBTextEdit1.Enabled:=false;
cxDBTextEdit2.Enabled:=false;
Label1.Enabled:=false;
Label2.Enabled:=false;
Label3.Enabled:=false;
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE';
UpdProc.Prepare;
UpdProc.ParamByName('USE_DEFAULT_VALUES').AsInteger:=0;
UpdProc.ParamByName('DEFAULT_SMETA').Value :=DefOptionDataSet.FieldByName('DEFAULT_SMETA').Value;
UpdProc.ParamByName('DEFAULT_RAZD').Value :=DefOptionDataSet.FieldByName('DEFAULT_RAZD').Value;
UpdProc.ParamByName('DEFAULT_ST').Value :=DefOptionDataSet.FieldByName('DEFAULT_ST').Value;
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end;
end;
procedure TfrmSysOptions.CheckConfDefaultBuClick(Sender: TObject);
begin
SetBuConfigure;
end;
procedure TfrmSysOptions.CheckConfDefaultKVClick(Sender: TObject);
begin
SetKVConfigure;
end;
procedure TfrmSysOptions.SetKVConfigure;
var UpdProc:TpFibStoredProc;
begin
if (CheckConfDefaultKV.ItemIndex=0)
then begin
cxDBButtonEdit4.Enabled:=true;
Label4.Enabled:=true;
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE_KV';
UpdProc.Prepare;
UpdProc.ParamByName('USE_DEFAULT_KEKV').AsInteger:=1;
UpdProc.ParamByName('DEFAULT_KEKV').Value :=DefOptionDataSet.FieldByName('DEFAULT_KEKV').Value;
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end
else begin
cxDBButtonEdit4.Enabled:=false;
Label4.Enabled:=false;
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE_KV';
UpdProc.Prepare;
UpdProc.ParamByName('USE_DEFAULT_KEKV').AsInteger:=0;
UpdProc.ParamByName('DEFAULT_KEKV').Value :=DefOptionDataSet.FieldByName('DEFAULT_KEKV').Value;
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end;
end;
procedure TfrmSysOptions.CheckKekvPropertiesChange(Sender: TObject);
var UpdProc:TpFibStoredProc;
begin
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE_EX2';
UpdProc.Prepare;
UpdProc.ParamByName('KERNELL_CHECK_KEKV').AsInteger :=Integer(CheckKekv.Checked);
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end;
procedure TfrmSysOptions.CHECK_FOND_PLUS_GROUPPropertiesChange(
Sender: TObject);
var UpdProc:TpFibStoredProc;
begin
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE_EX3';
UpdProc.Prepare;
UpdProc.ParamByName('CHECK_FOND_PLUS_GROUP').AsInteger :=Integer(CHECK_FOND_PLUS_GROUP.Checked);
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end;
procedure TfrmSysOptions.CHECK_SPIS_BY_SM_RZ_STPropertiesChange(
Sender: TObject);
var UpdProc:TpFibStoredProc;
begin
UpdProc:=TpFibStoredProc.Create(self);
UpdProc.Database:=WorkDatabase;
UpdProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
UpdProc.StoredProcName:='MBOOK_INI_DATA_UPDATE_EX4';
UpdProc.Prepare;
UpdProc.ParamByName('CHECK_SPIS_BY_SM_RZ_ST').AsInteger :=Integer(CHECK_SPIS_BY_SM_RZ_ST.Checked);
UpdProc.ExecProc;
WriteTransaction.Commit;
DefOptionDataSet.CloseOpen(true);
end;
procedure TfrmSysOptions.ToolButton11Click(Sender: TObject);
var InsertSP:TpFibStoredProc;
begin
if (TemplateDataSet.RecordCount>0)
then begin
if agMessageDlg('Увага!','Ви хочете видалити шаблон?',mtWarning,[mbYes,mbNo])=mrYes
then begin
InsertSP:=TpFibStoredProc.Create(self);
InsertSP.Database:=WorkDatabase;
InsertSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertSP.StoredProcName:='BU_SPRAV_TEMPLATE_DELETE';
InsertSP.Prepare;
InsertSP.ParamByName('ID_TEMPLATE').Value :=TemplateDataSet.FieldByName('ID_TEMPLATE').Value;
InsertSP.ExecProc;
WriteTransaction.Commit;
TemplateDataSet.CloseOpen(true);
end;
end;
end;
procedure TfrmSysOptions.ToolButton10Click(Sender: TObject);
var T:TfrmEditTemplate;
InsertSP:TpFibStoredProc;
NewId:Integer;
begin
T:=TfrmEditTemplate.Create(self);
if T.ShowModal=mrYes
then begin
InsertSP:=TpFibStoredProc.Create(self);
InsertSP.Database:=WorkDatabase;
InsertSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertSP.StoredProcName:='BU_SPRAV_TEMPLATE_INSERT';
InsertSP.Prepare;
InsertSP.ParamByName('DB_ID_SCH').asInt64 :=T.DB_ID_SCH;
InsertSP.ParamByName('DB_ID_SCH').asInt64 :=T.DB_ID_SCH;
InsertSP.ParamByName('DB_ID_SM').asInt64 :=T.DB_ID_SM;
InsertSP.ParamByName('DB_ID_RZ').asInt64 :=T.DB_ID_RZ;
InsertSP.ParamByName('DB_ID_ST').asInt64 :=T.DB_ID_ST;
InsertSP.ParamByName('KR_ID_SM').asInt64 :=T.KR_ID_SM;
InsertSP.ParamByName('KR_ID_RZ').asInt64 :=T.KR_ID_RZ;
InsertSP.ParamByName('KR_ID_ST').asInt64 :=T.KR_ID_ST;
InsertSP.ParamByName('KR_ID_KEKV').AsInt64 :=T.KR_ID_KEKV;
InsertSP.ParamByName('DB_ID_KEKV').AsInt64 :=T.DB_ID_KEKV;
InsertSP.ParamByName('CR_BY_DT').AsInt64 :=Integer(T.CR_BY_DT.checked);
InsertSP.ParamByName('TEMPLATE_TITLE').Value:=T.TemplateTitle.Text;
InsertSP.ExecProc;
NewId:=InsertSP.ParamByName('ID_TEMPLATE').value;
WriteTransaction.Commit;
TemplateDataSet.CloseOpen(true);
TemplateDataSet.Locate('ID_TEMPLATE',NewId,[]);
end;
T.Free;
end;
procedure TfrmSysOptions.ToolButton12Click(Sender: TObject);
var T:TfrmEditTemplate;
InsertSP:TpFibStoredProc;
NewId:Integer;
begin
T:=TfrmEditTemplate.Create(self);
if TemplateDataSet.FieldByName('TEMPLATE_TITLE').Value<>null
then T.TemplateTitle.Text:=TemplateDataSet.FieldByName('TEMPLATE_TITLE').AsString;
if TemplateDataSet.FieldByName('CR_BY_DT').Value<>null
then T.CR_BY_DT.checked:=TemplateDataSet.FieldByName('CR_BY_DT').AsBoolean;
if TemplateDataSet.FieldByName('DB_ID_SM').Value<>null
then T.DB_ID_SM:=StrToInt64(TemplateDataSet.FieldByName('DB_ID_SM').AsString);
if TemplateDataSet.FieldByName('DB_ID_RZ').Value<>null
then T.DB_ID_RZ:=StrToInt64(TemplateDataSet.FieldByName('DB_ID_RZ').AsString);
if TemplateDataSet.FieldByName('DB_ID_ST').Value<>null
then T.DB_ID_ST:=StrToInt64(TemplateDataSet.FieldByName('DB_ID_ST').AsString);
if TemplateDataSet.FieldByName('KR_ID_SM').Value<>null
then T.KR_ID_SM:=StrToInt64(TemplateDataSet.FieldByName('KR_ID_SM').AsString);
if TemplateDataSet.FieldByName('KR_ID_RZ').Value<>null
then T.KR_ID_RZ:=StrToInt64(TemplateDataSet.FieldByName('KR_ID_RZ').AsString);
if TemplateDataSet.FieldByName('KR_ID_ST').value<>null
then T.KR_ID_ST:=StrToInt64(TemplateDataSet.FieldByName('KR_ID_ST').AsString);
if TemplateDataSet.FieldByName('DB_ID_SCH').Value<>null
then T.DB_ID_SCH:=StrToInt64(TemplateDataSet.FieldByName('DB_ID_SCH').AsString);
if TemplateDataSet.FieldByName('KR_ID_SCH').Value<>null
then T.KR_ID_SCH:=StrToInt64(TemplateDataSet.FieldByName('KR_ID_SCH').AsString);
if TemplateDataSet.FieldByName('DB_ID_KEKV').value<>null
then T.DB_ID_KEKV:=StrToInt64(TemplateDataSet.FieldByName('DB_ID_KEKV').AsString);
if TemplateDataSet.FieldByName('KR_ID_KEKV').value<>null
then T.KR_ID_KEKV:=StrToInt64(TemplateDataSet.FieldByName('KR_ID_KEKV').AsString);
if TemplateDataSet.FieldByName('DB_SM').value<>null
then T.DB_SM.Text:=TemplateDataSet.FieldByName('DB_SM').AsString;
if TemplateDataSet.FieldByName('DB_RZ').value<>null
then T.DB_RZ.Text:=TemplateDataSet.FieldByName('DB_RZ').AsString;
if TemplateDataSet.FieldByName('DB_ST').value<>null
then T.DB_ST.Text:=TemplateDataSet.FieldByName('DB_ST').AsString;
if TemplateDataSet.FieldByName('KR_SM').Value<>null
then T.KR_SM.Text:=TemplateDataSet.FieldByName('KR_SM').AsString;
if TemplateDataSet.FieldByName('KR_RZ').Value<>null
then T.KR_RZ.Text:=TemplateDataSet.FieldByName('KR_RZ').AsString;
if TemplateDataSet.FieldByName('KR_ST').Value<>null
then T.KR_ST.Text:=TemplateDataSet.FieldByName('KR_ST').AsString;
if TemplateDataSet.FieldByName('DB_SCH').value<>null
then T.DB_SCH.Text:=TemplateDataSet.FieldByName('DB_SCH').AsString;
if TemplateDataSet.FieldByName('KR_SCH').Value<>null
then T.KR_SCH.Text:=TemplateDataSet.FieldByName('KR_SCH').AsString;
if TemplateDataSet.FieldByName('DB_KEKV').Value<>null
then T.DB_KEKV.Text:=TemplateDataSet.FieldByName('DB_KEKV').AsString;
if TemplateDataSet.FieldByName('KR_KEKV').Value<>null
then T.KR_KEKV.Text:=TemplateDataSet.FieldByName('KR_KEKV').AsString;
if T.ShowModal=mrYes
then begin
InsertSP:=TpFibStoredProc.Create(self);
InsertSP.Database:=WorkDatabase;
InsertSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertSP.StoredProcName:='BU_SPRAV_TEMPLATE_UPDATE';
InsertSP.Prepare;
NewId:=TemplateDataSet.FieldByName('ID_TEMPLATE').Value;
InsertSP.ParamByName('ID_TEMPLATE').Value :=TemplateDataSet.FieldByName('ID_TEMPLATE').Value;
InsertSP.ParamByName('DB_ID_SM').AsInt64 :=T.DB_ID_SM;
InsertSP.ParamByName('DB_ID_RZ').AsInt64 :=T.DB_ID_RZ;
InsertSP.ParamByName('DB_ID_ST').AsInt64 :=T.DB_ID_ST;
InsertSP.ParamByName('KR_ID_SM').AsInt64 :=T.KR_ID_SM;
InsertSP.ParamByName('KR_ID_RZ').AsInt64 :=T.KR_ID_RZ;
InsertSP.ParamByName('KR_ID_ST').AsInt64 :=T.KR_ID_ST;
InsertSP.ParamByName('KR_ID_KEKV').AsInt64 :=T.KR_ID_KEKV;
InsertSP.ParamByName('DB_ID_KEKV').AsInt64 :=T.DB_ID_KEKV;
InsertSP.ParamByName('TEMPLATE_TITLE').Value:=T.TemplateTitle.Text;
InsertSP.ParamByName('DB_ID_SCH').asInt64 :=T.DB_ID_SCH;
InsertSP.ParamByName('KR_ID_SCH').asInt64 :=T.KR_ID_SCH;
InsertSP.ParamByName('CR_BY_DT').AsInt64 :=Integer(T.CR_BY_DT.checked);
InsertSP.ExecProc;
WriteTransaction.Commit;
TemplateDataSet.CloseOpen(true);
TemplateDataSet.Locate('ID_TEMPLATE',NewId,[]);
end;
T.Free;
end;
procedure TfrmSysOptions.cxButton1Click(Sender: TObject);
begin
close;
end;
procedure TfrmSysOptions.cxButton3Click(Sender: TObject);
var InsertSP:TpFibStoredProc;
num_prop:Integer;
begin
num_prop:=StrToInt(InputBox('Конфігурація системи.','Треба ввести номер властивості.','0'));
if not LinksDataSet.Locate('NUM_PROP',num_prop,[])
then begin
InsertSP:=TpFibStoredProc.Create(self);
InsertSP.Database:=WorkDatabase;
InsertSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertSP.StoredProcName:='MBOOK_LINKS_PROP_INSERT';
InsertSP.Prepare;
InsertSP.ParamByName('NUM_PROP').Value:=num_prop;
InsertSP.ExecProc;
WriteTransaction.Commit;
LinksDataSet.CloseOpen(true);
LinksDataSet.Locate('NUM_PROP',num_prop,[]);
InsertSP.Free;
end;
end;
procedure TfrmSysOptions.cxButton4Click(Sender: TObject);
var DeleteSP:TpFibStoredProc;
begin
if (LinksDataSet.RecordCount>0)
then begin
DeleteSP:=TpFibStoredProc.Create(self);
DeleteSP.Database:=WorkDatabase;
DeleteSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
DeleteSP.StoredProcName:='MBOOK_LINKS_PROP_DELETE';
DeleteSP.Prepare;
DeleteSP.ParamByName('NUM_PROP').Value:=LinksDataSet.FieldByName('NUM_PROP').Value;
DeleteSP.ExecProc;
WriteTransaction.Commit;
LinksDataSet.CacheDelete;
DeleteSP.Free;
end;
end;
procedure TfrmSysOptions.cxButton5Click(Sender: TObject);
var InsertSP:TpFibStoredProc;
Res:Variant;
id_sch:int64;
begin
Res:=GlobalSpr.GetSch(self,
WorkDatabase.handle,
fsNormal,
DateForSprav.Date,
DEFAULT_ROOT_ID,0,0);
If (varArrayDimCount(Res)>0)
then begin
id_sch:=RES[0][0];
if not SchFilterDataSet.Locate('ID_SCH',id_sch,[])
then begin
InsertSP:=TpFibStoredProc.Create(self);
InsertSP.Database:=WorkDatabase;
InsertSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
InsertSP.StoredProcName:='MBOOK_SCH_Z_INSERT';
InsertSP.Prepare;
InsertSP.ParamByName('ID_SCH').AsInt64 :=id_sch;
InsertSP.ParamByName('DATE_ADD').Value :=DateForSprav.Date;
InsertSP.ExecProc;
WriteTransaction.Commit;
SchFilterDataSet.CloseOpen(true);
SchFilterDataSet.Locate('ID_SCH',ID_SCH,[]);
InsertSP.Free;
end;
end;
end;
procedure TfrmSysOptions.cxButton6Click(Sender: TObject);
var DeleteSP:TpFibStoredProc;
begin
if (SchFilterDataSet.RecordCount>0)
then begin
DeleteSP:=TpFibStoredProc.Create(self);
DeleteSP.Database:=WorkDatabase;
DeleteSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
DeleteSP.StoredProcName:='MBOOK_SCH_Z_DELETE';
DeleteSP.Prepare;
DeleteSP.ParamByName('ID_SCH').Value:=StrToInt64(SchFilterDataSet.FieldByName('ID_SCH').AsString);
DeleteSP.ExecProc;
WriteTransaction.Commit;
SchFilterDataSet.CacheDelete;
DeleteSP.Free;
end;
end;
procedure TfrmSysOptions.ToolButton13Click(Sender: TObject);
var i:Integer;
begin
ToolButton13.Down:= not ToolButton13.Down;
for i:=0 to cxGridDBTableView2.ColumnCount-1 do cxGridDBTableView2.Columns[i].Options.Filtering:=ToolButton13.Down;
end;
end.
|
unit CCJSO_BlackListControl;
{*****************************************************
* © PgkSoft 10.03.2016
* Журнал интернет заказов
* Реализация действий по управлению черным списком
*****************************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
UCCenterJournalNetZkz, ExtCtrls, Util, ComCtrls, ToolWin, ActnList,
StdCtrls, uActionCore, UtilsBase;
type
TfrmCCJSO_BlackListControl = class(TForm)
pnlTop: TPanel;
pnlTop_Order: TPanel;
pnlTop_Client: TPanel;
actionList: TActionList;
aBlackList_Open: TAction;
aFrmClose: TAction;
aBlackList_Close: TAction;
aBlackList_NnknownMode: TAction;
pnlControl: TPanel;
pnlControl_Tool: TPanel;
tollBar: TToolBar;
tlbtnExec: TToolButton;
tlbtnClose: TToolButton;
pnlControl_Show: TPanel;
lblNote: TLabel;
edNote: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aBlackList_OpenExecute(Sender: TObject);
procedure aBlackList_CloseExecute(Sender: TObject);
procedure aFrmCloseExecute(Sender: TObject);
procedure edNoteChange(Sender: TObject);
private
{ Private declarations }
ISignActive : integer;
Mode : smallint;
RecSession : TUserSession;
RecHeaderItem : TJSO_OrderHeaderItem;
FOnAction: TBlackListEvent;
FActionResult: TActionResult;
procedure ShowGets;
public
{ Public declarations }
procedure SetRecHeaderItem(Parm : TJSO_OrderHeaderItem);
procedure SetRecSession(Parm : TUserSession);
procedure SetMode(Parm : smallint);
function ShowDialog(OnAction: TBlackListEvent): TActionResult;
end;
const
cBlackListMode_Open = 0;
cBlackListMode_close = 1;
var
frmCCJSO_BlackListControl: TfrmCCJSO_BlackListControl;
implementation
uses
CCJSO_DM;
{$R *.dfm}
procedure TfrmCCJSO_BlackListControl.FormCreate(Sender: TObject);
begin
{ Инициализация }
ISignActive := 0;
Mode := -1;
end;
procedure TfrmCCJSO_BlackListControl.FormActivate(Sender: TObject);
var
SCaption : string;
begin
if ISignActive = 0 then begin
edNote.Text := '';
{ Иконка формы и заголовок }
if Mode = cBlackListMode_Open then begin
FCCenterJournalNetZkz.imgMain.GetIcon(346,self.Icon);
self.Caption := 'Добавить в черный список';
tlbtnExec.Action := aBlackList_Open;
end else if Mode = cBlackListMode_Close then begin
FCCenterJournalNetZkz.imgMain.GetIcon(347,self.Icon);
self.Caption := 'Убрать из черного списка';
tlbtnExec.Action := aBlackList_Close;
end else begin
FCCenterJournalNetZkz.imgMain.GetIcon(345,self.Icon);
self.Caption := '!!! Не определен режим работы';
tlbtnExec.Action := aBlackList_NnknownMode;
end;
{ Подгоняем под размер панель управления }
pnlControl_Tool.Width := tlbtnExec.Width + tlbtnClose.Width + 3;
{ Отображаем реквизиты заказа }
SCaption := '№ ' + RecHeaderItem.SorderID;
pnlTop_Order.Caption := SCaption; pnlTop_Order.Width := TextPixWidth(SCaption, pnlTop_Order.Font) + 20;
SCaption := RecHeaderItem.orderShipName + '; ' + RecHeaderItem.orderPhone;
pnlTop_Client.Caption := SCaption;
{ Форма активна }
ISignActive := 1;
ShowGets;
end;
end;
procedure TfrmCCJSO_BlackListControl.SetRecHeaderItem(Parm : TJSO_OrderHeaderItem); begin RecHeaderItem := Parm; end;
procedure TfrmCCJSO_BlackListControl.SetRecSession(Parm : TUserSession); begin RecSession := Parm; end;
procedure TfrmCCJSO_BlackListControl.SetMode(Parm : smallint); begin Mode := Parm; end;
procedure TfrmCCJSO_BlackListControl.ShowGets;
begin
if ISignActive = 1 then begin
{ Доступ к управлению }
if length(edNote.Text) = 0 then begin
aBlackList_Open.Enabled := false;
aBlackList_Close.Enabled := false;
edNote.Color := clYellow;
end else begin
aBlackList_Open.Enabled := true;
aBlackList_Close.Enabled := true;
edNote.Color := clWindow;
end;
end;
end;
procedure TfrmCCJSO_BlackListControl.aBlackList_OpenExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
if MessageDLG('Подтвердите выполнение действия.',mtConfirmation,[mbYes,mbNo],0) = mrNo then exit;
if Assigned(FOnAction) then
begin
TActionCore.Clear_ActionResult(FActionResult);
try
FOnAction(RecHeaderItem.orderID, RecSession.CurrentUser, edNote.Text, blIns, FActionResult);
if FActionResult.IErr <> 0 then
ShowError(FActionResult.ExecMsg)
else
ModalResult := mrOk;
except
on E: Exception do
begin
FActionResult.IErr := cDefError;
FActionResult.ExecMsg := TrimRight(E.Message + ' ' + FActionResult.ExecMsg);
ShowError(FActionResult.ExecMsg);
end;
end;
end else
begin
DM_CCJSO.BlackListInsert(RecSession.CurrentUser,RecHeaderItem.orderID,edNote.Text,IErr,SErr);
if IErr = 0 then self.Close;
end;
end;
procedure TfrmCCJSO_BlackListControl.aBlackList_CloseExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
if MessageDLG('Подтвердите выполнение действия.',mtConfirmation,[mbYes,mbNo],0) = mrNo then exit;
if Assigned(FOnAction) then
begin
TActionCore.Clear_ActionResult(FActionResult);
try
FOnAction(RecHeaderItem.orderID, RecSession.CurrentUser, edNote.Text, blClose, FActionResult);
if FActionResult.IErr <> 0 then
ShowError(FActionResult.ExecMsg)
else
ModalResult := mrOk;
except
on E: Exception do
begin
FActionResult.IErr := cDefError;
FActionResult.ExecMsg := TrimRight(E.Message + ' ' + FActionResult.ExecMsg);
ShowError(FActionResult.ExecMsg);
end;
end;
end else
begin
DM_CCJSO.BlackListClose(RecSession.CurrentUser,RecHeaderItem.orderID,edNote.Text,IErr,SErr);
if IErr = 0 then self.Close;
end;
end;
procedure TfrmCCJSO_BlackListControl.aFrmCloseExecute(Sender: TObject);
begin
self.Close;
end;
procedure TfrmCCJSO_BlackListControl.edNoteChange(Sender: TObject);
begin
ShowGets;
end;
function TfrmCCJSO_BlackListControl.ShowDialog(OnAction: TBlackListEvent): TActionResult;
begin
FOnAction := OnAction;
ShowModal;
Result.IErr := FActionResult.IErr;
Result.ExecMsg := FActionResult.ExecMsg;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit BulletTest;
interface
uses
Box2D.Dynamics, Test;
type
TBulletTest = class(TTest)
protected
m_body: b2BodyWrapper;
m_bullet: b2BodyWrapper;
m_x: Float32;
public
constructor Create;
class function CreateTest: TTest; static;
procedure Launch;
procedure Step(settings: PSettings); override;
end;
implementation
uses
System.Math,
Box2D.Common, Box2D.Collision, DebugDraw;
constructor TBulletTest.Create;
var
bd: b2BodyDef;
body: b2BodyWrapper;
edge: b2EdgeShapeWrapper;
shape: b2PolygonShapeWrapper;
box: b2PolygonShapeWrapper;
begin
inherited Create;
bd := b2BodyDef.Create;
bd.position.&Set(0.0, 0.0);
body := m_world.CreateBody(@bd);
edge := b2EdgeShapeWrapper.Create;
edge.&Set(b2Vec2.Create(-10.0, 0.0), b2Vec2.Create(10.0, 0.0));
body.CreateFixture(edge, 0.0);
shape := b2PolygonShapeWrapper.Create;
shape.SetAsBox(0.2, 1.0, b2Vec2.Create(0.5, 1.0), 0.0);
body.CreateFixture(shape, 0.0);
bd := b2BodyDef.Create;
bd.&type := b2_dynamicBody;
bd.position.&Set(0.0, 4.0);
box := b2PolygonShapeWrapper.Create;
box.SetAsBox(2.0, 0.1);
m_body := m_world.CreateBody(@bd);
m_body.CreateFixture(box, 1.0);
box.SetAsBox(0.25, 0.25);
//m_x := RandomFloat(-1.0, 1.0);
m_x := 0.20352793;
bd.position.&Set(m_x, 10.0);
bd.bullet := true;
m_bullet := m_world.CreateBody(@bd);
m_bullet.CreateFixture(box, 100.0);
m_bullet.SetLinearVelocity(b2Vec2.Create(0.0, -50.0));
end;
class function TBulletTest.CreateTest: TTest;
begin
Result := TBulletTest.Create;
end;
procedure TBulletTest.Launch;
begin
m_body.SetTransform(b2Vec2.Create(0.0, 4.0), 0.0);
//m_body.SetLinearVelocity(b2Vec2_zero);
m_body.SetLinearVelocity(b2Vec2.Create(0.0, 0.0));
m_body.SetAngularVelocity(0.0);
m_x := RandomFloat(-1.0, 1.0);
m_bullet.SetTransform(b2Vec2.Create(m_x, 10.0), 0.0);
m_bullet.SetLinearVelocity(b2Vec2.Create(0.0, -50.0));
m_bullet.SetAngularVelocity(0.0);
// extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
// extern int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters;
// extern int32 b2_toiRootIters, b2_toiMaxRootIters;
// TODO : uncomment when external variables are accessible
// b2_gjkCalls := 0;
// b2_gjkIters := 0;
// b2_gjkMaxIters := 0;
//
// b2_toiCalls := 0;
// b2_toiIters := 0;
// b2_toiMaxIters := 0;
// b2_toiRootIters := 0;
// b2_toiMaxRootIters := 0;
end;
procedure TBulletTest.Step(settings: PSettings);
begin
inherited Step(settings);
// extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
// extern int32 b2_toiCalls, b2_toiIters;
// extern int32 b2_toiRootIters, b2_toiMaxRootIters;
// TODO : uncomment when external variables are accessible
// if (b2_gjkCalls > 0) then
// begin
// g_debugDraw.DrawString(5, m_textLine, 'gjk calls = %d, ave gjk iters = %3.1f, max gjk iters = %d',
// [b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxIters]);
// m_textLine := m_textLine + DRAW_STRING_NEW_LINE;
// end;
//
// if (b2_toiCalls > 0) then
// begin
// g_debugDraw.DrawString(5, m_textLine, 'toi calls = %d, ave toi iters = %3.1f, max toi iters = %d',
// [b2_toiCalls, b2_toiIters / float32(b2_toiCalls), b2_toiMaxRootIters]);
// m_textLine := m_textLine + DRAW_STRING_NEW_LINE;
//
// g_debugDraw.DrawString(5, m_textLine, 'ave toi root iters = %3.1f, max toi root iters = %d',
// [b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters]);
// m_textLine := m_textLine + DRAW_STRING_NEW_LINE;
// end;
if (m_stepCount mod 60) = 0 then
begin
Launch;
end;
end;
initialization
RegisterTest(TestEntry.Create('BulletTest', @TBulletTest.CreateTest));
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Packaging.Archive.Writer;
interface
uses
System.Classes,
System.Zip,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Packaging.Archive;
type
TPackageArchiveWriter = class(TInterfacedObject, IPackageArchiveWriter)
private
FFileName : string;
FZipFile : TZipFile;
FLastError : string;
FBasePath : string;
FVersion : TPackageVersion;
FLogger : ILogger;
protected
function AddFile(const filePath : string) : Boolean; overload;
function AddFile(const fileName : string; const archiveFileName : string) : boolean; overload;
function AddFiles(const files : System.TArray < System.string > ) : Boolean;
function AddIcon(const filePath : string) : boolean;
function WriteMetaDataFile(const stream : TStream) : Boolean; overload;
function WriteMetaDataFile(const fileName : string) : boolean; overload;
function Exists : Boolean;
function GetArchiveName : string;
function GetArchivePath : string;
function GetLastErrorString : string;
function IsArchive : Boolean;
function Open(const fileName : string) : Boolean;
procedure Close;
procedure SetBasePath(const path : string);
function GetPackageVersion : TPackageVersion;
public
constructor Create(const logger : ILogger); overload;
destructor Destroy; override;
end;
implementation
uses
DPM.Core.Constants,
System.SysUtils,
System.IOUtils;
{ TPackageArchiveWriter }
function TPackageArchiveWriter.AddFile(const filePath : string) : Boolean;
var
archiveFileName : string;
begin
archiveFileName := ExtractRelativePath(FBasePath, filePath);
FZipFile.Add(filePath, archiveFileName);
result := true;
end;
function TPackageArchiveWriter.AddFile(const fileName, archiveFileName : string) : boolean;
begin
try
FZipFile.Add(fileName, archiveFileName);
result := true;
except
on e : Exception do
raise Exception.Create('Error adding file [' + fileName + '] to package : ' + e.Message);
end;
end;
function TPackageArchiveWriter.AddFiles(const files : System.TArray < System.string > ) : Boolean;
var
f : string;
begin
for f in files do
begin
if not AddFile(f) then
Exit(false);
end;
result := true;
end;
function TPackageArchiveWriter.AddIcon(const filePath : string) : boolean;
var
iconBytes : TBytes;
begin
try
iconBytes := TFile.ReadAllBytes(filePath);
if ExtractFileExt(filePath) = '.svg' then
FZipFile.Add(iconBytes, cIconFileSVG)
else
FZipFile.Add(iconBytes, cIconFilePNG);
except
on e : Exception do
raise Exception.Create('Error adding icon [' + filePath + '] to package : ' + e.Message);
end;
result := true;
end;
procedure TPackageArchiveWriter.Close;
begin
if FZipFile <> nil then
begin
FZipFile.Close;
FreeAndNil(FZipFile);
end;
end;
constructor TPackageArchiveWriter.Create(const logger : ILogger);
begin
inherited Create;
FLogger := logger;
end;
destructor TPackageArchiveWriter.Destroy;
begin
if FZipFile <> nil then
FZipFile.Free;
inherited;
end;
function TPackageArchiveWriter.Exists : Boolean;
begin
result := (FZipFile <> nil) or TFile.Exists(FFileName);
end;
function TPackageArchiveWriter.GetArchiveName : string;
begin
result := TPath.GetFileName(FFileName);
end;
function TPackageArchiveWriter.GetArchivePath : string;
begin
// if FFileStream <> nil then
// result := 'c:\'
// else
result := TPath.GetDirectoryName(FFileName);
end;
function TPackageArchiveWriter.GetLastErrorString : string;
begin
result := FLastError;
end;
function TPackageArchiveWriter.GetPackageVersion : TPackageVersion;
begin
result := FVersion;
end;
function TPackageArchiveWriter.IsArchive : Boolean;
begin
result := true;
end;
function TPackageArchiveWriter.Open(const fileName : string) : Boolean;
begin
FFileName := fileName;
FVersion := TPackageVersion.Empty;
result := false;
if FZipFile <> nil then
exit(true); //already open;
FZipFile := TZipFile.Create;
try
FZipFile.Open(FFileName, TZipMode.zmWrite);
result := true;
except
on e : Exception do
begin
FreeAndNil(FZipFile);
FLogger.Error('Error opening package file : ' + e.Message);
FLastError := e.ToString;
end;
end;
end;
procedure TPackageArchiveWriter.SetBasePath(const path : string);
begin
FBasePath := path;
end;
function TPackageArchiveWriter.WriteMetaDataFile(const fileName : string) : boolean;
begin
FZipFile.Add(fileName, cPackageMetaFile);
result := true;
end;
function TPackageArchiveWriter.WriteMetaDataFile(const stream : TStream) : Boolean;
begin
FZipFile.Add(stream, cPackageMetaFile);
result := true;
end;
end.
|
(*
Category: SWAG Title: OOP/TURBO VISION ROUTINES
Original name: 0026.PAS
Description: Efficient Turbo Vision
Author: BRIAN RICHARDSON
Date: 11-02-93 16:45
*)
{
From: BRIAN RICHARDSON
Subj: Efficient Tv2
---------------------------------------------------------------------------
On 10-08-93 FRANK DERKS wrote to ALL...
Hello All,
for those who have read my other message (Efficient TV, Thu 07). Maybe
some of you can expand on the following idea. How do I create a
'dynamic' pick list box: a box that is displayed only when I have
Or maybe more simple : what I'm after is a sort of inputline-object
which can be cycled through a number of predefined values. }
uses objects, app, dialogs, drivers;
type
PRoomInputLine = ^TRoomInputLine;
TRoomInputLine = object(TInputLine)
StatusList : PStringCollection;
Index : integer;
constructor Init(var Bounds: TRect; AMaxLen: integer;
AStatusList : PStringCollection);
procedure HandleEvent(var Event : TEvent); virtual;
procedure Up; virtual;
procedure Down; virtual;
end;
PRoomDialog = ^TRoomDialog;
TRoomDialog = object(TDialog)
constructor Init(List : PStringCollection);
end;
constructor TRoomInputLine.Init(var Bounds : TRect; AMaxLen: Integer;
AStatusList : PStringCollection);
begin
inherited Init(Bounds, AMaxLen);
StatusList := AStatusList;
Index := 0;
SetData(PString(StatusList^.At(Index))^);
end;
procedure TRoomInputLine.Up;
begin
Index := (Index + 1) Mod StatusList^.Count;
SetData(PString(StatusList^.At(Index))^);
end;
procedure TRoomInputLine.Down;
begin
if Index = 0 then Index := (StatusList^.Count - 1) else
Dec(Index);
SetData(PString(StatusList^.At(Index))^);
end;
procedure TRoomInputLine.HandleEvent(var Event: TEvent);
begin
if (Event.What = evKeyDown) then begin
case Event.KeyCode of
kbUp : Up;
kbDown : Down;
else
inherited HandleEvent(Event);
end; end else
inherited HandleEvent(Event);
end;
constructor TRoomDialog.Init(List : PStringCollection);
var R: TRect;
begin
R.Assign(20, 5, 60, 20);
inherited Init(R, '');
R.Assign(15, 7, 25, 8);
Insert(New(PRoomInputLine, Init(R, 20, List)));
R.Assign(15, 9, 25, 10);
Insert(New(PRoomInputLine, Init(R, 20, List)));
end;
var
RoomApp : TApplication;
List : PStringCollection;
begin
RoomApp.Init;
List := New(PStringCollection, Init(3, 1));
with List^ do begin
Insert(NewStr('Vacant')); Insert(NewStr('Occupied'));
Insert(NewStr('Cleaning'));
end;
Application^.ExecuteDialog(New(PRoomDialog, Init(List)), nil);
Dispose(List, Done);
RoomApp.Done;
end.
|
unit CargoDAO;
interface
uses
DBXCommon, SqlExpr, BaseDAO, Cargo;
type
TCargoDAO = class(TBaseDAO)
public
function List: TDBXReader;
function Insert(Cargo: TCargo): Boolean;
function Update(Cargo: TCargo): Boolean;
function Delete(Cargo: TCargo): Boolean;
function FindById(Id: Integer): TCargo;
end;
implementation
uses uSCPrincipal, StringUtils;
{ TClienteDAO }
function TCargoDAO.List: TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT * FROM CARGOS';
Result := FComm.ExecuteQuery;
end;
function TCargoDAO.Insert(Cargo: TCargo): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'INSERT INTO CARGOS (DESCRICAO) VALUES (:DESCRICAO)';
//
query.ParamByName('DESCRICAO').AsString := Cargo.Descricao;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TCargoDAO.Update(Cargo: TCargo): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'UPDATE CARGOS SET DESCRICAO = :DESCRICAO '+
'WHERE ID = :ID';
//
query.ParamByName('DESCRICAO').AsString := Cargo.Descricao;
query.ParamByName('ID').AsInteger := Cargo.Id;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TCargoDAO.Delete(Cargo: TCargo): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'DELETE FROM CARGOS WHERE ID = :ID';
//
query.ParamByName('ID').AsInteger := Cargo.Id;
//
try
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TCargoDAO.FindById(Id: Integer): TCargo;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
//
query.SQL.Text := 'SELECT * FROM CARGOS WHERE ID = :ID';
//
query.ParamByName('ID').AsInteger := Id;
//
query.Open;
//
Result := TCargo.Create(query.FieldByName('ID').AsInteger,
query.FieldByName('DESCRICAO').AsString);
finally
query.Free;
end;
end;
end.
|
//******************************************************************************
// Проект "Контракты"
// Справочник специальностей
// Чернявский А.Э. 2006г.
// последние изменения Перчак А.Л. 29/10/2008
//******************************************************************************
unit cn_sp_SpecUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, dxBar, dxBarExtItems, ImgList, cxGraphics, cxContainer, cxEdit,
cxProgressBar, dxStatusBar, cxControls, IBase,
cn_DM_Spec, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB,
cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxClasses, cxTextEdit,
cn_Common_Funcs, cnConsts, cn_sp_SpecUnit_AE, cn_Common_Messages,
cnConsts_Messages, ActnList, Placemnt, cxCheckBox, cn_Common_Types;
type
TfrmSpSpec = class(TForm)
BarManager: TdxBarManager;
AddButton: TdxBarLargeButton;
EditButton: TdxBarLargeButton;
DeleteButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
ExitButton: TdxBarLargeButton;
PopupImageList: TImageList;
LargeImages: TImageList;
DisabledLargeImages: TImageList;
StatusBar: TdxStatusBar;
Styles: TcxStyleRepository;
BackGround: TcxStyle;
FocusedRecord: TcxStyle;
Header: TcxStyle;
DesabledRecord: TcxStyle;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
DevExpress_Style: TcxGridTableViewStyleSheet;
Grid: TcxGrid;
GridDBView: TcxGridDBTableView;
GridLevel: TcxGridLevel;
Name_Colmn: TcxGridDBColumn;
CODE_SPEC_Colmn: TcxGridDBColumn;
SelectButton: TdxBarLargeButton;
id_spec_clmn: TcxGridDBColumn;
Search_BarEdit: TdxBarEdit;
Contracts_ActionList: TActionList;
FilterAction: TAction;
GridDBViewDBColumn1: TcxGridDBColumn;
full_name_col: TcxGridDBColumn;
CnFormStorage: TFormStorage;
deleted_Column: TcxGridDBColumn;
procedure ExitButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SelectButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure GridDBViewDblClick(Sender: TObject);
procedure FilterActionExecute(Sender: TObject);
procedure Search_BarEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GridDBViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
PLanguageIndex: byte;
DM:TDM_Spec;
procedure FormIniLanguage;
public
res:Variant;
Is_admin:Boolean;
constructor Create(AParameter:TcnSimpleParams);reintroduce;
end;
implementation
{$R *.dfm}
constructor TfrmSpSpec.Create(AParameter:TcnSimpleParams);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AParameter.Owner);
DM:=TDM_Spec.Create(Self);
DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_SP_SPEC_SELECT';
If AParameter.Formstyle = fsNormal then
Begin
DM.DataSet.SQLs.SelectSQL.add('where is_deleted=0');
deleted_Column.Visible := False;
end;
DM.DB.Handle:=AParameter.DB_Handle;
DM.DataSet.Open;
DM.DataSet.FetchAll;
GridDBView.DataController.DataSource := DM.DataSource;
FormIniLanguage();
Self.Is_admin:=AParameter.is_admin;
Screen.Cursor:=crDefault;
CnFormStorage.RestoreFormPlacement;
end;
procedure TfrmSpSpec.FormIniLanguage;
begin
PLanguageIndex:= cn_Common_Funcs.cnLanguageIndex();
//кэпшн формы
Caption:= cnConsts.cn_Main_SpSpec[PLanguageIndex];
//названия кнопок
AddButton.Caption := cnConsts.cn_InsertBtn_Caption[PLanguageIndex];
EditButton.Caption := cnConsts.cn_EditBtn_Caption[PLanguageIndex];
DeleteButton.Caption := cnConsts.cn_DeleteBtn_Caption[PLanguageIndex];
RefreshButton.Caption := cnConsts.cn_RefreshBtn_Caption[PLanguageIndex];
SelectButton.Caption := cnConsts.cn_SelectBtn_Caption[PLanguageIndex];
ExitButton.Caption := cnConsts.cn_ExitBtn_Caption[PLanguageIndex];
Search_BarEdit.Caption := cnConsts.cn_SearchBtn_Caption[PLanguageIndex];
//статусбар
StatusBar.Panels[0].Text:= cnConsts.cn_InsertBtn_ShortCut[PLanguageIndex] + cnConsts.cn_InsertBtn_Caption[PLanguageIndex];
StatusBar.Panels[1].Text:= cnConsts.cn_EditBtn_ShortCut[PLanguageIndex] + cnConsts.cn_EditBtn_Caption[PLanguageIndex];
StatusBar.Panels[2].Text:= cnConsts.cn_DeleteBtn_ShortCut[PLanguageIndex] + cnConsts.cn_DeleteBtn_Caption[PLanguageIndex];
StatusBar.Panels[3].Text:= cnConsts.cn_RefreshBtn_ShortCut[PLanguageIndex] + cnConsts.cn_RefreshBtn_Caption[PLanguageIndex];
StatusBar.Panels[4].Text:= cnConsts.cn_EnterBtn_ShortCut[PLanguageIndex] + cnConsts.cn_SelectBtn_Caption[PLanguageIndex];
StatusBar.Panels[5].Text:= cnConsts.cn_ExitBtn_ShortCut[PLanguageIndex] + cnConsts.cn_ExitBtn_Caption[PLanguageIndex];
Name_Colmn.Caption := cnConsts.cn_Name_Column[PLanguageIndex];
CODE_SPEC_Colmn.Caption := cnConsts.cn_roles_Kod[PLanguageIndex];
end;
procedure TfrmSpSpec.ExitButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmSpSpec.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
CnFormStorage.SaveFormPlacement;
if FormStyle = fsMDIChild then action:=caFree
else
DM.Free;
end;
procedure TfrmSpSpec.SelectButtonClick(Sender: TObject);
var
RecMultiSelected, i: integer;
begin
if GridDBView.datacontroller.recordcount = 0 then exit;
if GridDBView.OptionsSelection.MultiSelect=true then
begin
RecMultiSelected:= GridDBView.DataController.GetSelectedCount;
res:=VarArrayCreate([0,RecMultiSelected-1],varVariant);
for i:=0 to GridDBView.DataController.GetSelectedCount-1 do
begin
res[i]:=VarArrayOf([
GridDBView.Controller.SelectedRecords[i].Values[0], // id_spec
GridDBView.Controller.SelectedRecords[i].Values[1], // code
GridDBView.Controller.SelectedRecords[i].Values[2], // name
GridDBView.Controller.SelectedRecords[i].Values[3], // shortname,
GridDBView.Controller.SelectedRecords[i].Values[4] // fullname
]);
end;
end;
ModalResult:=mrOk;
end;
procedure TfrmSpSpec.FormShow(Sender: TObject);
begin
if FormStyle = fsMDIChild then
begin
SelectButton.Visible:=ivNever;
GridDBView.OptionsSelection.MultiSelect:= False;
end;
end;
procedure TfrmSpSpec.AddButtonClick(Sender: TObject);
var
ViewForm : TfrmSpec_AE;
New_id_Locator : int64;
begin
if not Is_Admin then
if CheckPermission('/ROOT/Contracts/Cn_Sp','Edit') <> 0
then
begin
messagebox(handle,
pchar(cnConsts_Messages.cn_NotHaveRights[PLanguageIndex]
+#13+ cnConsts_Messages.cn_GoToAdmin[PLanguageIndex]),
pchar(cnConsts_Messages.cn_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
ViewForm:= TfrmSpec_AE.Create(Self, PLanguageIndex);
ViewForm.Caption := cnConsts.cn_InsertBtn_Caption[PLanguageIndex];
ViewForm.cxcheckDelete.Enabled:=False;
if ViewForm.ShowModal = mrOk then
begin
with DM.StProc do
try
Transaction.StartTransaction;
StoredProcName := 'CN_SP_SPEC_INSERT';
Prepare;
ParamByName('NAME').AsString := ViewForm.NameStage_Edit.Text;
ParamByName('CODE_SPEC').AsString := ViewForm.cnCode_Edit.Text;
ParamByName('SHORT_NAME').AsString := ViewForm.ShortName_Edit.Text;
ParamByName('FULL_NAME').AsString := ViewForm.FullName_Edit.Text;
ExecProc;
New_id_Locator:=ParamByName('ID_SPEC').AsInt64;
Transaction.Commit;
except
on E:Exception do
begin
cnShowMessage('Error',e.Message,mtError,[mbOK]);
Transaction.Rollback;
end;
end;
DM.DataSet.CloseOpen(True);
DM.DataSet.Locate('ID_SPEC',New_id_Locator,[] );
end;
end;
procedure TfrmSpSpec.RefreshButtonClick(Sender: TObject);
var
id_Locator : Int64;
begin
Screen.Cursor := crHourGlass;
id_Locator := DM.DataSet['ID_SPEC'];
DM.DataSet.CloseOpen(True);
DM.DataSet.Locate('ID_SPEC', id_Locator ,[] );
Screen.Cursor := crDefault;
end;
procedure TfrmSpSpec.EditButtonClick(Sender: TObject);
var
ViewForm : TfrmSpec_AE;
id_Locator : Int64;
begin
if not Is_Admin then
if CheckPermission('/ROOT/Contracts/Cn_Sp','Edit') <> 0 then
begin
messagebox(handle,
pchar(cnConsts_Messages.cn_NotHaveRights[PLanguageIndex]
+#13+ cnConsts_Messages.cn_GoToAdmin[PLanguageIndex]),
pchar(cnConsts_Messages.cn_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
if GridDBView.DataController.RecordCount = 0 then exit;
ViewForm:= TfrmSpec_AE.Create(Self, PLanguageIndex);
ViewForm.Caption := cnConsts.cn_EditBtn_Caption[PLanguageIndex];
if DM.DataSet['NAME']<>null
then ViewForm.NameStage_Edit.Text:= DM.DataSet['NAME'];
if DM.DataSet['CODE_SPEC'] <> null
then ViewForm.cnCode_Edit.Text:= DM.DataSet['CODE_SPEC'];
if DM.DataSet['SHORT_NAME'] <> null
then ViewForm.ShortName_Edit.Text:= DM.DataSet['SHORT_NAME'];
if DM.DataSet['FULL_NAME'] <> null
then ViewForm.FullName_Edit.Text:= DM.DataSet['FULL_NAME'];
if DM.DataSet['is_deleted'] = 1
then ViewForm.cxCheckDelete.Checked:= true;
if ViewForm.ShowModal = mrOk then
begin
id_Locator:= DM.DataSet['ID_SPEC'];
with DM.StProc do
try
Transaction.StartTransaction;
StoredProcName := 'CN_SP_SPEC_UPDATE';
Prepare;
ParamByName('ID_SPEC').AsInt64 := DM.DataSet['ID_SPEC'];
ParamByName('NAME').AsString := ViewForm.NameStage_Edit.Text;
ParamByName('CODE_SPEC').AsString := ViewForm.cnCode_Edit.Text;
ParamByName('SHORT_NAME').AsString := ViewForm.ShortName_Edit.Text;
ParamByName('FULL_NAME').AsString := ViewForm.FullName_Edit.Text;
if ViewForm.cxCheckDelete.Checked
then ParamByName('IS_DELETED').Value := 1
else ParamByName('IS_DELETED').Value := 0;
ExecProc;
Transaction.Commit;
except
on E:Exception do
begin
cnShowMessage('Error',e.Message,mtError,[mbOK]);
Transaction.Rollback;
end;
end;
DM.DataSet.CloseOpen(True);
DM.DataSet.Locate('ID_SPEC', id_Locator ,[] );
Grid.SetFocus;
end;
end;
procedure TfrmSpSpec.DeleteButtonClick(Sender: TObject);
var
i: byte;
begin
if not Is_Admin then
if CheckPermission('/ROOT/Contracts/Cn_Sp','Edit') <> 0
then
begin
messagebox(handle,
pchar(cnConsts_Messages.cn_NotHaveRights[PLanguageIndex]
+#13+ cnConsts_Messages.cn_GoToAdmin[PLanguageIndex]),
pchar(cnConsts_Messages.cn_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
if GridDBView.DataController.RecordCount = 0 then exit;
i:= cn_Common_Messages.cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_warning_Delete[PLanguageIndex], mtConfirmation, [mbYes, mbNo]);
if ((i = 7) or (i= 2)) then exit
else
begin
with DM.StProc do
try
Transaction.StartTransaction;
StoredProcName := 'CN_SP_SPEC_DELETE';
Prepare;
ParamByName('ID_SPEC').AsInt64 := DM.DataSet['ID_SPEC'];
ExecProc;
Transaction.Commit;
except
on E:Exception do
begin
cnShowMessage('Error',e.Message,mtError,[mbOK]);
Transaction.Rollback;
end;
end;
DM.DataSet.CloseOpen(True);
end;
end;
procedure TfrmSpSpec.GridDBViewDblClick(Sender: TObject);
begin
if FormStyle = fsMDIChild then EditButtonClick(Sender)
else
SelectButtonClick(Sender);
end;
procedure TfrmSpSpec.FilterActionExecute(Sender: TObject);
begin
Search_BarEdit.Setfocus;
end;
procedure TfrmSpSpec.Search_BarEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_return then
begin
DM.DataSet.Close;
DM.DataSet.SelectSQL.Clear;
DM.DataSet.SQLs.SelectSQL.Text := 'select * from CN_SP_SPEC_SEARCH(' + ''''+Search_BarEdit.Text +''''+ ')';
DM.DataSet.Open;
end;
end;
procedure TfrmSpSpec.GridDBViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = vk_delete then DeleteButtonClick(Sender);
end;
end.
|
unit houghTransform;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,math,unit_localizationAux;
const
HoughRho=125;
HoughTheta=90;
rsRho=0.04;
rsTheta=1;
type
TXY = record
x,y:double;
rho,theta:double;
idTheta,idRho:integer;
val:integer;
end;
{ THough }
THough = class
private
procedure FillAtheta;
procedure FillRho;
procedure CreateHoughMatrices;
procedure ClearH;
function GetOccuranceGrid(r, theta:integer): integer;
procedure incOccurance(r, theta: integer);
procedure SetOccuranceGrid(r, theta,val: integer);
procedure decOccurance(r, theta: integer);
public
lowPassHoughRho:TLowPassFilter;
lowPassHoughTheta:TLowPassCompass;
H:array [1..2*HoughRho,1..2*HoughTheta] of integer;
Mtheta:array [1..2*HoughTheta] of double;
MRho:array [1..2*HoughRho] of double;
thetaMax,RhoMax:integer;
resolTheta,resolRho:double;
constructor Create;
procedure HoughTransform(points:TPointList);
function GetHoughMax:TXY;
end;
implementation
uses unit_Localization;
{ THough }
procedure THough.FillAtheta;
var i:integer;
begin
for i:=1 to thetaMax do
Mtheta[i]:=degtorad(((i-1)-(thetaMax div 2))*resolTheta);
end;
procedure THough.FillRho;
var i:integer;
begin
for i:=1 to RhoMax do
MRho[i]:=((i-1)-(RhoMax div 2))*resolRho;
end;
procedure THough.ClearH;
begin
FillChar(H,SizeOf(H),0);
end;
procedure THough.CreateHoughMatrices;
begin
thetaMax:=round(2/resolTheta*90);
RhoMax:=round(2/resolRho*5);
FillAtheta;
FillRho;
ClearH;
end;
constructor THough.Create;
begin
lowPassHoughRho:=TLowPassFilter.Create(0.5,0.04,0);
lowPassHoughTheta:=TLowPassCompass.Create(0.5,0.04,0);
resolTheta:=rsTheta;
resolRho:=rsRho;
CreateHoughMatrices;
end;
function THough.GetOccuranceGrid(r, theta: integer): integer;
begin
result:=H[r,theta];
end;
procedure THough.incOccurance(r, theta: integer);
begin
H[r,theta]:=H[r,theta]+1;
end;
procedure THough.SetOccuranceGrid(r, theta, val: integer);
begin
H[r,theta]:=val;
end;
procedure THough.decOccurance(r, theta: integer);
begin
H[r,theta]:=H[r,theta]+1;
end;
procedure THough.HoughTransform(points: TPointList);
var x,y,ang,r:double;
angTheta,i:integer;
begin
ClearH;
for i:=0 to points.PCount do begin
x:=points.PList[i].x;
y:=points.PList[i].y;
for angTheta:=1 to thetaMax do begin
ang:=Mtheta[angTheta];
r:=(x*cos(ang)+y*sin(ang))/resolRho;
if ((round(r+0.5+(RhoMax div 2))>=1) and (round(r+(RhoMax div 2))<=RhoMax))then
incOccurance(round(r+0.5+(RhoMax div 2)),angTheta);
end;
end;
end;
function THough.GetHoughMax: TXY;
var r,angTheta:integer;
xy:TXY;
begin
xy.val:=-1;
for r:=1 to RhoMax do begin
for angTheta:=1 to thetaMax do begin
if H[r,angTheta]>xy.val then begin
xy.val:=H[r,angTheta];
xy.idRho:=r;
xy.idTheta:=angTheta;
xy.rho:=MRho[r];
xy.theta:=Mtheta[angTheta];
end;
end;
end;
Result:=xy;
end;
end.
|
// -------------------------------------------------------------
// Este programa mostra a definição de um tipo de dados bem
// complexo. Esse tipo de dados é utilizado para definição e uso
// de uma variável de exemplo. :~
// -------------------------------------------------------------
Program ExemploPzim ;
TYPE TIPO_ABSURDO = array[1..4] of record
campo1: integer;
campo2: array[1..4] of array [1..2,1..3] of string[11];
campo3 : record
novo_campo : integer;
end;
end;
VAR absurdo : array[1..4,1..5] of TIPO_ABSURDO;
Begin
absurdo[1,2][3].campo2[1,2][3] := 'Pascal ZIM!';
writeln('A variavel absurdo guarda o valor: ***', absurdo[1,2,3].campo2[1][2][3],'***');
writeln('=>Posicao 1 :***', absurdo[1][2][3].campo2[1][2,3][1],'***');
writeln('=>Posicao 2 :***', absurdo[1,2][3].campo2[1][2,3][2],'***');
writeln('=>Posicao 3 :***', absurdo[1][2,3].campo2[1][2,3][3],'***');
writeln('=>Posicao 4 :***', absurdo[1,2,3].campo2[1][2,3][4],'***');
writeln('=>Posicao 5 :***', absurdo[1][2][3].campo2[1][2][3][5],'***');
writeln('=>Posicao 6 :***', absurdo[1][2][3].campo2[1,2][3][6],'***');
writeln('=>Posicao 7 :***', absurdo[1,2][3].campo2[1][2,3][7],'***');
writeln('=>Posicao 8 :***', absurdo[1][2,3].campo2[1][2][3,8],'***');
writeln('=>Posicao 9 :***', absurdo[1,2,3].campo2[1,2,3][9],'***');
writeln('=>Posicao 10 :***', absurdo[1][2][3].campo2[1][2,3,10],'***');
writeln('=>Posicao 11 :***', absurdo[1,2,3].campo2[1,2,3,11],'***');
readkey;
End.
|
unit uPacktAndroidServiceDM;
interface
uses
System.SysUtils,
System.Classes,
System.Android.Service,
AndroidApi.JNI.GraphicsContentViewText,
Androidapi.JNI.Os, System.Notification, System.Threading,
System.DateUtils;
type
TDM = class(TAndroidService)
NotificationCenter1: TNotificationCenter;
function AndroidServiceStartCommand(const Sender: TObject;
const Intent: JIntent; Flags, StartId: Integer): Integer;
private
{ Private declarations }
public
{ Public declarations }
T : ITask;
procedure LaunchNotification(Name, Title, Body : String);
end;
var
DM: TDM;
implementation
uses Androidapi.JNI.App;
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
function TDM.AndroidServiceStartCommand(const Sender: TObject;
const Intent: JIntent; Flags, StartId: Integer): Integer;
begin
Result := TJService.JavaClass.START_STICKY;
T := TTask.Run( procedure
begin
while True do
sleep(10);
LaunchNotification('Packt Delphi Book', 'Delphi Rocks',
'This is Chapter 3!');
exit;
end
)
end;
procedure TDM.LaunchNotification(Name, Title, Body: String);
var
Notify : TNotification;
begin
Notify := NotificationCenter1.CreateNotification;
Try
Notify.Name := Name;
Notify.Title := Title;
Notify.AlertBody := Body;
Notify.FireDate := IncSecond(Now,1);
NotificationCenter1.ScheduleNotification(Notify);
Finally
Notify.Free;
End;
end;
end.
|
{
Copyright (c) 2016, Vencejo Software
Distributed under the terms of the Modified BSD License
The full license is distributed with this software
}
unit ooConfig.Intf;
interface
uses
ooEntity.Intf;
type
IConfigSection = interface(IEntity)
['{37CB5072-49D6-4EC1-AACF-70AA572C03A2}']
function Name: String;
function Description: String;
end;
IConfig = interface
['{18547F4D-59DF-4B56-9CF4-772F9B47D7E2}']
function LoadSection(const ConfigSection: IConfigSection): Boolean;
function SaveSection(const ConfigSection: IConfigSection): Boolean;
end;
implementation
end.
|
PROGRAM assignment1 (input, output, client_file, command_file) ;
CONST
Name_length = 20 ;
Phone_num_length = 8 ;
Number_of_interests = 10 ;
Max_interest_degree = 9 ;
Max_clients = 50 ;
Command_size = 20 ;
TYPE
Interest_range = 0..Max_interest_degree ;
Sex_type = (female, male) ;
Boolean = (false, true) ;
Client_type =
RECORD
name : PACKED ARRAY[1..Name_length] OF char ;
phone_num : PACKED ARRAY[1..Phone_num_length] OF char ;
interest_degree : ARRAY[1..Number_of_interests] OF Interest_range ;
match_index : 0..Max_clients ;
END ;
VAR
command : PACKED ARRAY[1..Command_size] OF char ;
client_file : text ;
command_file: text ;
quit_flag : Boolean ;
client_list : ARRAY[female..male, 1..Max_clients] OF Client_type ;
num_clients : ARRAY[female..male] OF integer ;
FUNCTION char_to_Sex_type (client_sex : char) : Sex_type ;
(* Function to convert a 'char' variable holding 'm','M','f','F' to an
appropriate 'Sex_type' variable *)
BEGIN
IF ((client_sex = 'm') OR (client_sex = 'M')) THEN
char_to_Sex_type := male
ELSE
char_to_Sex_type := female ;
END ;
FUNCTION other_sex (sex : Sex_type) : Sex_type ;
(* Function that returns the opposite sex of the given input sex *)
BEGIN
IF (sex = male) THEN
other_sex := female
ELSE
other_sex := male ;
END ;
PROCEDURE print_list ;
(* Procedure to execute PRINTLIST command *)
VAR
k : Sex_type ;
i, j: integer ;
BEGIN
writeln ('Num_clients = ', num_clients[male] + num_clients[female]) ;
FOR k := female TO male DO
BEGIN
FOR i := 1 TO num_clients[k] DO
BEGIN
WITH client_list[k, i] DO
BEGIN
write (name, phone_num) ;
FOR j := 1 TO Number_of_interests DO
write (interest_degree[j]:2) ;
writeln ('M = ', match_index) ;
END ;
END ;
END ;
END ;
PROCEDURE read_clients_file ;
(* Procedure to initialize the client_list record array with data from the
CLIENTS.DAT file *)
VAR
client_sex : char ;
num_records : integer ;
sex : Sex_type ;
i, j : integer ;
BEGIN
num_clients[female] := 0 ;
num_clients[male] := 0 ;
open (client_file, 'CLIENTS.DAT', old) ;
reset (client_file) ;
readln (client_file, num_records) ;
FOR i := 1 to num_records DO
BEGIN
readln (client_file, client_sex) ;
sex := char_to_Sex_type (client_sex) ;
num_clients[sex] := num_clients[sex] + 1 ;
WITH client_list[sex, num_clients[sex]] DO
BEGIN
readln (client_file, name) ;
readln (client_file, phone_num) ;
FOR j := 1 TO Number_of_interests DO
readln (client_file, interest_degree[j]) ;
readln (client_file, match_index) ;
END ;
END ;
close (client_file) ;
END ;
PROCEDURE new_clients(VAR error_flag : Boolean) ;
(* Procedure to execute command NEWCLIENTS : Returns error_flag=true if
no space left in the client_list array *)
VAR
search_index : integer ;
num_interests_matched : integer ;
client_sex : char ;
matched : Boolean ;
sex : Sex_type ;
opp_sex : Sex_type ;
i : integer ;
BEGIN
search_index := 1 ;
matched := false ;
writeln ('NEWCLIENT :') ;
readln (command_file, client_sex) ;
sex := char_to_Sex_type (client_sex) ;
IF (num_clients[sex] = Max_clients) THEN
error_flag := true
ELSE
BEGIN (* If space available in the client list *)
num_clients[sex] := num_clients[sex] + 1 ;
WITH client_list[sex, num_clients[sex]] DO
BEGIN (* Read in cliet data *)
readln (command_file, name) ;
readln (command_file, phone_num) ;
FOR i := 1 TO Number_of_interests DO
readln (command_file, interest_degree[i]) ;
match_index := 0 ;
END ;
opp_sex := other_sex(sex) ;
while ((search_index <= num_clients[opp_sex]) AND (matched = false))DO
BEGIN
(* While there are some more clients of the opposite sex who have not been
checked AND current client has not been matched DO *)
num_interests_matched := 0 ;
FOR i := 1 TO Number_of_interests DO
BEGIN
WITH client_list[opp_sex, search_index] DO
BEGIN
IF ((client_list[sex, num_clients[sex]].interest_degree[i]> 4) AND (interest_degree[i] > 4)) THEN
num_interests_matched := num_interests_matched + 1 ;
END ;
END ;
IF ((num_interests_matched >= 6) AND (client_list[opp_sex, search_index].match_index = 0)) THEN
matched := true
ELSE
search_index := search_index + 1 ;
END ;
IF (matched = true) THEN
BEGIN
client_list[sex, num_clients[sex]].match_index := search_index ;
client_list[opp_sex, search_index].match_index := num_clients[sex] ;
writeln ('Client Match :') ;
writeln ('Names : ', client_list[sex, num_clients[sex]].name, ' & ', client_list[opp_sex, search_index].name ) ;
writeln ('Phone numbers : ', client_list[sex, num_clients[sex]].phone_num, ' & ', client_list[opp_sex, search_index].phone_num) ;
END
ELSE
writeln ('No match for client ', client_list[sex, num_clients[sex]].name) ;
error_flag := false ;
END;
writeln ;
END ;
PROCEDURE unmatch ;
(* Procedure to execute command UNMATCH *)
VAR
i : integer ;
client_name : PACKED ARRAY[1..Name_length] OF char ;
sex : Sex_type ;
found : Boolean ;
BEGIN
found := false ;
writeln ('UNMATCH :') ;
readln (command_file, client_name) ;
FOR sex := female TO male DO
BEGIN
FOR i := 1 to num_clients[sex] DO
BEGIN
WITH client_list[sex, i] DO
BEGIN
IF (client_name = name) THEN
BEGIN
IF (match_index <> 0) THEN
BEGIN
writeln ('Clients ', name, ' & ', client_list[other_sex(sex), match_index].name, 'are unmatched.') ;
client_list[other_sex(sex), match_index].match_index := 0 ;
match_index := 0 ;
END
ELSE
writeln ('No match for client ', name) ;
found := true ;
END ;
END ;
END ;
END ;
IF (found = false) THEN
writeln ('Client ', client_name, 'is not in database.') ;
writeln ;
END ;
PROCEDURE print_match ;
(* Procedure to execute command PRINTMATCH *)
VAR
i : integer ;
BEGIN
writeln ('PRINTMATCH :') ;
FOR i := 1 TO num_clients[female] DO
BEGIN
WITH client_list[female, i] DO
BEGIN
IF (match_index <> 0) THEN
BEGIN
write ('Matched pair : ') ;
writeln (name, ' & ', client_list[male, match_index].name) ;
END ;
END ;
END ;
writeln ;
END ;
PROCEDURE print_free ;
(* Procedure to excute command PRINTFREE *)
VAR
sex : Sex_type ;
i : integer ;
BEGIN
writeln ('PRINTFREE :') ;
FOR sex := female TO male DO
BEGIN
FOR i := 1 TO num_clients[sex] DO
BEGIN
WITH client_list[sex, i] DO
BEGIN
IF (match_index = 0) THEN
BEGIN
writeln ('Free person :') ;
writeln ('NAME : ', name, ' SEX : ', sex, ' Phone Number : ', phone_num ) ;
END ;
END ;
END ;
END ;
writeln ;
END ;
BEGIN
quit_flag := false ;
read_clients_file ;
open (command_file, 'datecoms.dat', old) ;
reset (command_file) ;
WHILE (quit_flag = false) DO
BEGIN
readln (command_file, command) ;
IF (command = 'NEWCLIENT') THEN
BEGIN
new_clients (quit_flag) ;
IF (quit_flag = true) THEN
writeln ('Error! Too many clients. Exiting program.') ;
END
ELSE IF (command = 'UNMATCH') THEN
unmatch
ELSE IF (command = 'PRINTMATCH') THEN
print_match
ELSE IF (command = 'PRINTFREE') THEN
print_free
ELSE IF (command = 'QUIT') THEN
quit_flag := true ;
END ;
writeln ('QUIT') ;
close (command_file) ;
END.
|
unit OrcamentoFornecedores.Model.Interf;
interface
uses ormbr.container.objectset.interfaces,
TESTORCAMENTOFORNECEDORES.Entidade.Model;
type
IOrcamentoFornecedoresModel = interface
['{7A41E40E-E3EE-4097-9DF9-F82F7BC7470A}']
function Entidade(AValue: TTESTORCAMENTOFORNECEDORES)
: IOrcamentoFornecedoresModel; overload;
function Entidade: TTESTORCAMENTOFORNECEDORES; overload;
function DAO: IContainerObjectSet<TTESTORCAMENTOFORNECEDORES>;
end;
implementation
end.
|
unit uFIBCommonDBErrors;
interface
resourcestring
E_FIBCommonDB_DBIsNil = 'FIBDatabase is nil!';
E_FIBCommonDB_AlreadyStarted = 'TFIBDBTransaction.Start: already started!';
E_FIBCommonDB_CommitNotInTran = 'TFIBDBTransaction.Commit: not in transaction!';
E_FIBCommonDB_RollbackNotInTran = 'TFIBDBTransaction.Rollback: not in transaction!';
E_FIBCommonDB_NewSQLNotpFIBDataSet = 'TFIBDBTransaction.NewSQL: not TpFIBDataSet!';
E_FIBCommonDB_NewSQLNotMine = 'TFIBDBTransaction.NewSQL: supported dataset is not mine!';
implementation
end.
|
unit ZipIni;
interface
uses
SysUtils,ZipForge,IniFiles,Registry,Windows,Classes;
var
GlobZip:TZipForge;
GlobIni:TIniFile;
Procedure ZipIniCreateBase (BaseName:string);
Function ZipIniReadString (BaseName,FileName,Section,Ident,Default:string):string;
Function ZipIniReadInteger (BaseName,FileName,Section,Ident:string;Default:Integer):Integer;
Procedure ZipIniWriteString (BaseName,FileName,Section,Ident,Value:string);
Procedure ZipIniWriteInteger (BaseName,FileName,Section,Ident:string;Value:integer);
Procedure ZipIniReadSection (BaseName,FileName,Section: string;var list:TStringList);
implementation
Procedure ZipIniCreateBase (BaseName:string);
Begin
GlobZip:=TZIpForge.Create(nil);
GlobZip.FileName :=basename;
GlobZip.OpenArchive (fmCreate);
GlobZip.CloseArchive;
GlobZip.Free;
End;
Function ZipIniReadString (BaseName,FileName,Section,Ident,Default:string):string;
var
tmp:string;
begin
try
tmp:=GetTmpDir;
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(tmp);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenRead);
GlobZip.ExtractFiles (FileName);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni:=TIniFile.Create(tmp+FileName);
Result:=GlobIni.ReadString (Section,ident,default);
GlobIni.Free;
DeleteFile (pchar(tmp+FileName));
except
on e: exception do result:=Default;
end;
end;
Function ZipIniReadInteger (BaseName,FileName,Section,Ident:string;Default:Integer):integer;
var
tmp:string;
begin
try
tmp:=GetTmpDir;
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(Tmp);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenRead);
GlobZip.ExtractFiles (FileName);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni:=TIniFile.Create(Tmp+FileName);
Result:=GlobIni.ReadInteger (Section,ident,default);
GlobIni.Free;
DeleteFile (pchar(tmp+FileName));
except
on e: exception do result:=Default;
end;
end;
Procedure ZipIniWriteString (BaseName,FileName,Section,Ident,Value:string);
begin
try
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(GetTmpDir);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenReadWrite);
GlobZip.ExtractFiles (FileName);
GlobIni:=TIniFile.Create(GetTmpDir+FileName);
GlobIni.WriteString (Section,ident,Value);
GlobZip.MoveFiles (FileName);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni.Free;
except
end;
End;
Procedure ZipIniWriteInteger (BaseName,FileName,Section,Ident:string;Value:integer);
begin
try
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(GetTmpDir);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenReadWrite);
GlobZip.ExtractFiles (FileName);
GlobIni:=TIniFile.Create(GetTmpDir+FileName);
GlobIni.WriteInteger(Section,ident,Value);
GlobZip.MoveFiles (FileName);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni.Free;
except
end;
End;
Procedure ZipIniReadSection (BaseName,FileName,Section: string;var list:TStringList);
var
tmp:string;
begin
try
tmp:=GetTmpDir;
GlobZip:=TZIpForge.Create(nil);
GlobZip.BaseDir :=excludetrailingbackslash(Tmp);
GlobZip.FileName:=BaseName;
GlobZip.OpenArchive (fmOpenRead);
GlobZip.ExtractFiles (FileName);
GlobIni:=TIniFile.Create(Tmp+FileName);
GlobIni.ReadSection (Section,list);
GlobZip.CloseArchive;
GlobZip.Free;
GlobIni.Free;
DeleteFile (pchar(tmp+FileName));
except
end;
End;
end.
|
namespace RemObjects.Elements.EUnit;
interface
uses
Sugar;
type
Assert = public partial static class {$IF NOUGAT}mapped to Object{$ENDIF}
public
method AreEqual(Actual, Expected : Double; Message: String := nil);
method AreEqual(Actual, Expected, Precision : Double; Message: String := nil);
method AreNotEqual(Actual, Expected: Double; Message: String := nil);
method AreNotEqual(Actual, Expected, Precision: Double; Message: String := nil);
method Greater(Actual, Expected: Double; Message: String := nil);
method GreaterOrEquals(Actual, Expected: Double; Message: String := nil);
method Less(Actual, Expected: Double; Message: String := nil);
method LessOrEquals(Actual, Expected: Double; Message: String := nil);
method IsNaN(Actual: Double; Message: String := nil);
method IsNotNaN(Actual: Double; Message: String := nil);
method IsInfinity(Actual: Double; Message: String := nil);
method IsNotInfinity(Actual: Double; Message: String := nil);
end;
implementation
class method Assert.AreEqual(Actual: Double; Expected: Double; Message: String := nil);
begin
FailIfNot(Actual = Expected, Convert.ToString(Actual), Convert.ToString(Expected), coalesce(Message, AssertMessages.NotEqual));
end;
class method Assert.AreEqual(Actual: Double; Expected: Double; Precision: Double; Message: String := nil);
begin
if Consts.IsInfinity(Expected) or Consts.IsNaN(Expected) or Consts.IsNaN(Actual) then
AreEqual(Actual, Expected, Message)
else
FailIfNot(Math.Abs(Expected - Actual) <= Precision, Convert.ToString(Actual), Convert.ToString(Expected), coalesce(Message, AssertMessages.NotEqual));
end;
class method Assert.AreNotEqual(Actual: Double; Expected: Double; Message: String := nil);
begin
FailIfNot(Actual <> Expected, Convert.ToString(Actual), Convert.ToString(Expected), coalesce(Message, AssertMessages.Equal));
end;
class method Assert.AreNotEqual(Actual: Double; Expected: Double; Precision: Double; Message: String := nil);
begin
if Consts.IsInfinity(Expected) or Consts.IsNaN(Expected) or Consts.IsNaN(Actual) then
AreNotEqual(Actual, Expected, Message)
else
FailIfNot(Math.Abs(Expected - Actual) > Precision, Convert.ToString(Actual), Convert.ToString(Expected), coalesce(Message, AssertMessages.Equal));
end;
class method Assert.Greater(Actual: Double; Expected: Double; Message: String := nil);
begin
FailIfNot(Actual > Expected, Convert.ToString(Actual), Convert.ToString(Expected), coalesce(Message, AssertMessages.GreaterExpected));
end;
class method Assert.GreaterOrEquals(Actual: Double; Expected: Double; Message: String := nil);
begin
FailIfNot(Actual >= Expected, Convert.ToString(Actual), Convert.ToString(Expected), coalesce(Message, AssertMessages.GreaterOrEqualExpected));
end;
class method Assert.Less(Actual: Double; Expected: Double; Message: String := nil);
begin
FailIfNot(Actual < Expected, Convert.ToString(Actual), Convert.ToString(Expected), coalesce(Message, AssertMessages.LessExpected));
end;
class method Assert.LessOrEquals(Actual: Double; Expected: Double; Message: String := nil);
begin
FailIfNot(Actual <= Expected, Convert.ToString(Actual), Convert.ToString(Expected), coalesce(Message, AssertMessages.LessOrEqualExpected));
end;
class method Assert.IsNaN(Actual: Double; Message: String := nil);
begin
FailIfNot(Consts.IsNaN(Actual), Convert.ToString(Actual), Convert.ToString(Consts.NaN), coalesce(Message, AssertMessages.ValueIsNotNaN));
end;
class method Assert.IsNotNaN(Actual: Double; Message: String := nil);
begin
FailIf(Consts.IsNaN(Actual), Convert.ToString(Actual), Convert.ToString(Consts.NaN), coalesce(Message, AssertMessages.ValueIsNaN));
end;
class method Assert.IsInfinity(Actual: Double; Message: String := nil);
begin
FailIfNot(Consts.IsInfinity(Actual), Convert.ToString(Actual), Convert.ToString(Consts.PositiveInfinity), coalesce(Message, AssertMessages.ValueIsNotInf));
end;
class method Assert.IsNotInfinity(Actual: Double; Message: String := nil);
begin
FailIf(Consts.IsInfinity(Actual), Convert.ToString(Actual), Convert.ToString(Consts.PositiveInfinity), coalesce(Message, AssertMessages.ValueIsInf));
end;
end. |
unit BasicFunctions;
interface
uses BasicMathsTypes,SysUtils, Classes, Math, Windows, Graphics, ShellAPI;
// String related
function WriteStringToStream(const _String: string; var _Stream : TStream): boolean;
function ReadStringFromStream(var _Stream: TStream): string;
function CopyString(const _String : string): string;
function GetBool(_Value : integer): boolean; overload;
function GetBool(_Value : string): boolean; overload;
function GetStringID(_ID : integer): string;
// Graphics related (OpenGL engine)
function GetPow2Size(Size : Cardinal) : Cardinal;
function SetVectorI(x, y, z : integer) : TVector3i;
function CopyVector(const _vector : TVector3f): TVector3f;
function SetVector4f(x, y, z, w : single) : TVector4f;
Function TVector3fToTColor(Vector3f : TVector3f) : TColor;
Function TColorToTVector3f(Color : TColor) : TVector3f;
function Subtract3i(_V1,_V2: TVector3i): TVector3i;
function RGBA(r, g, b, a: Byte): COLORREF;
function CopyVector4f(_V: TVector4f): TVector4f;
// Numeric related
function epsilon(_value: single): single;
function absCeil(_value: single): single;
// Filename related
function GetFileNameWithNoExt(const _Filename: string): string;
// Program related
function RunAProgram (const theProgram, itsParameters, defaultDirectory : string): integer;
function RunProgram (const theProgram, itsParameters, defaultDirectory : string): TShellExecuteInfo;
function GetParamStr: String;
// Bitmap related
procedure ResizeBitmap(var Bitmap: TBitmap; Width, Height: Integer; Background: TColor);
implementation
// String related
function WriteStringToStream(const _String: string; var _Stream : TStream): boolean;
var
MyChar : integer;
Zero : char;
begin
Result := false;
Zero := #0;
try
for MyChar := 1 to Length(_String) do
begin
_Stream.WriteBuffer(_String[MyChar],sizeof(char));
end;
_Stream.WriteBuffer(Zero,sizeof(Char));
except
exit;
end;
Result := true;
end;
function ReadStringFromStream(var _Stream: TStream): string;
var
MyChar : char;
begin
Result := '';
try
_Stream.ReadBuffer(MyChar,sizeof(Char));
while MyChar <> #0 do
begin
Result := Result + MyChar;
_Stream.ReadBuffer(MyChar,sizeof(Char));
end;
except
exit;
end;
end;
function CopyString(const _String: string): string;
begin
Result := copy(_String,1,Length(_String));
end;
function GetBool(_Value : integer): boolean;
begin
if _Value <> 0 then
Result := true
else
Result := false;
end;
function GetBool(_Value : string): boolean;
begin
if CompareText(_Value,'true') = 0 then
Result := true
else
Result := false;
end;
function GetStringID(_ID : integer): string;
begin
if _ID < 10000 then
begin
if (_ID > 999) then
Result := IntToStr(_ID)
else if (_ID > 99) then
Result := '0' + IntToStr(_ID)
else if (_ID > 9) then
Result := '00' + IntToStr(_ID)
else
Result := '000' + IntToStr(_ID);
end;
end;
// Graphics related (OpenGL engine)
function GetPow2Size(Size : Cardinal) : Cardinal;
begin
Result := 1;
while (Result < Size) and (Result < 4096) do
Result := Result shl 1;
if Result > 4096 then
Result := 4096;
end;
function SetVectorI(x, y, z : integer) : TVector3i;
begin
result.x := x;
result.y := y;
result.z := z;
end;
function CopyVector(const _vector : TVector3f): TVector3f;
begin
result.x := _vector.x;
result.y := _vector.y;
result.z := _vector.z;
end;
function SetVector4f(x, y, z, w : single) : TVector4f;
begin
result.x := x;
result.y := y;
result.z := z;
result.W := w;
end;
Function TVector3fToTColor(Vector3f : TVector3f) : TColor;
begin
Result := RGB(trunc(Vector3f.X*255),trunc(Vector3f.Y*255),trunc(Vector3f.Z*255));
end;
Function TColorToTVector3f(Color : TColor) : TVector3f;
begin
Result.X := GetRValue(Color) / 255;
Result.Y := GetGValue(Color) / 255;
Result.Z := GetBValue(Color) / 255;
end;
function Subtract3i(_V1,_V2: TVector3i): TVector3i;
begin
Result.X := _V1.X - _V2.X;
Result.Y := _V1.Y - _V2.Y;
Result.Z := _V1.Z - _V2.Z;
end;
function CopyVector4f(_V: TVector4f): TVector4f;
begin
Result.X := _V.X;
Result.Y := _V.Y;
Result.Z := _V.Z;
Result.W := _V.W;
end;
function RGBA(r, g, b, a: Byte): COLORREF;
begin
Result := (r or (g shl 8) or (b shl 16) or (a shl 24));
end;
// Numeric related
function epsilon(_value: single): single;
begin
if abs(_value) < 0.0001 then
begin
Result := 0;
end
else
begin
Result := _value;
end;
end;
function absCeil(_value: single): single;
begin
if _value < 0 then
begin
Result := ceil(abs(_value)) * -1;
end
else
begin
Result := ceil(_value);
end;
end;
// Filename related
function GetFileNameWithNoExt(const _Filename: string): string;
var
i: integer;
begin
i := Length(_Filename);
while _Filename[i] <> '.' do
begin
dec(i);
end;
if i > 0 then
begin
Result := copy(_Filename,1,i-1);
end
else
begin
Result := copy(_Filename,1,Length(_Filename));
end;
end;
// Program related.
function RunAProgram (const theProgram, itsParameters, defaultDirectory : string): integer;
var
msg : string;
begin
Result := ShellExecute(0, 'open', pChar(theProgram), pChar(itsParameters), pChar(defaultDirectory), sw_ShowNormal);
if Result <= 32 then
begin
case Result of
0,
se_err_OOM : msg := 'Out of memory/resources';
error_File_Not_Found : msg := 'File "' + theProgram + '" not found';
error_Path_Not_Found : msg := 'Path not found';
error_Bad_Format : msg := 'Damaged or invalid exe';
se_err_AccessDenied : msg := 'Access denied';
se_err_NoAssoc,
se_err_AssocIncomplete : msg := 'Filename association invalid';
se_err_DDEBusy,
se_err_DDEFail,
se_err_DDETimeOut : msg := 'DDE error';
se_err_Share : msg := 'Sharing violation';
else msg := 'no text';
end; // of case
raise Exception.Create ('ShellExecute error #' + IntToStr(Result) + ': ' + msg);
end;
end;
function RunProgram (const theProgram, itsParameters, defaultDirectory : string): TShellExecuteInfo;
var
msg : string;
begin
Result.cbSize := sizeof(TShellExecuteInfo);
Result.lpFile := pChar(theProgram);
Result.lpParameters := pChar(itsParameters);
Result.lpDirectory := pChar(defaultDirectory);
Result.nShow := sw_ShowNormal;
Result.fMask := SEE_MASK_NOCLOSEPROCESS;
Result.Wnd := 0;
Result.lpVerb := 'open';
if not ShellExecuteEx(@Result) then
begin
if Result.hInstApp <= 32 then
begin
case Result.hInstApp of
0,
se_err_OOM : msg := 'Out of memory/resources';
error_File_Not_Found : msg := 'File "' + theProgram + '" not found';
error_Path_Not_Found : msg := 'Path not found';
error_Bad_Format : msg := 'Damaged or invalid exe';
se_err_AccessDenied : msg := 'Access denied';
se_err_NoAssoc,
se_err_AssocIncomplete : msg := 'Filename association invalid';
se_err_DDEBusy,
se_err_DDEFail,
se_err_DDETimeOut : msg := 'DDE error';
se_err_Share : msg := 'Sharing violation';
else msg := 'no text';
end; // of case
raise Exception.Create ('ShellExecute error #' + IntToStr(Result.hInstApp) + ': ' + msg);
end;
end;
end;
function GetParamStr: String;
var
x : integer;
begin
Result := '';
for x := 1 to ParamCount do
if Result <> '' then
Result := Result + ' ' +ParamStr(x)
else
Result := ParamStr(x);
end;
// Bitmap related
procedure ResizeBitmap(var Bitmap: TBitmap; Width, Height: Integer; Background: TColor);
var
R: TRect;
B: TBitmap;
X, Y: Integer;
begin
if assigned(Bitmap) then
begin
B:= TBitmap.Create;
try
if Bitmap.Width > Bitmap.Height then
begin
R.Right:= Width;
R.Bottom:= ((Width * Bitmap.Height) div Bitmap.Width);
X:= 0;
Y:= (Height div 2) - (R.Bottom div 2);
end
else
begin
R.Right:= ((Height * Bitmap.Width) div Bitmap.Height);
R.Bottom:= Height;
X:= (Width div 2) - (R.Right div 2);
Y:= 0;
end;
R.Left:= 0;
R.Top:= 0;
B.PixelFormat:= Bitmap.PixelFormat;
B.Width:= Width;
B.Height:= Height;
B.Canvas.Brush.Color:= Background;
B.Canvas.FillRect(B.Canvas.ClipRect);
B.Canvas.StretchDraw(R, Bitmap);
Bitmap.Width:= Width;
Bitmap.Height:= Height;
Bitmap.Canvas.Brush.Color:= Background;
Bitmap.Canvas.FillRect(Bitmap.Canvas.ClipRect);
Bitmap.Canvas.Draw(X, Y, B);
finally
B.Free;
end;
end;
end;
end.
|
unit DelphiDevDataSetTools;
interface
uses Classes, DB, IdGlobal;
{procedure CopyDataSet:
Copies data from dataset ASourceDataSet to dataset ADestDataSet.
Excludes fields defined in string AExcludeFields. The field names should be
comma seperated}
procedure CopyDataSet(ASourceDataSet, ADestDataSet: TDataSet;
AExcludedFields: String = '');
{procedure CopyRecord:
Copies the current record from dataset ASourceDataSet to dataset ADestDataSet.
Excludes fields defined in string AExcludeFields. The field names should be
comma seperated}
procedure CopyRecord(ASourceDataSet, ADestDataSet: TDataSet;
AExcludedFields: String = '');
{function FieldHasValue
Returns True if the field of ADataSet specified in AFieldName has the same
value in all dataset rows}
function FieldHasValue(ADataSet: TDataSet; AFieldName: String;
AFieldValue: Variant): Boolean;
{procedure CopyValueToDataSet
Copies AFieldValue to all the rows of ADataSet at field AFieldName}
procedure CopyValueToDataSet(ADataSet: TDataSet; AFieldName: String; AFieldValue: Variant);
function CheckFldIfEmpty(ADataSet: TDataSet; AFieldName: String): Boolean;
implementation
procedure CopyDataSet(ASourceDataSet, ADestDataSet: TDataSet;
AExcludedFields: String = '');
var
Fld: TField;
i: Integer;
ExcludedFieldsStrList: TStringList;
bmrk: TBookmark;
begin
if not Assigned(ASourceDataSet) or not ASourceDataSet.Active then exit;
if not Assigned(ADestDataSet) or not ADestDataSet.Active then exit;
ExcludedFieldsStrList := TStringList.Create;
ExcludedFieldsStrList.CommaText := AExcludedFields;
try
with ASourceDataSet do begin
bmrk := GetBookmark;
DisableControls;
try
First;
while not eof do begin
ADestDataSet.Last;
ADestDataSet.Append;
for i := 0 to FieldCount - 1 do begin
if ExcludedFieldsStrList.IndexOf(Fields[i].FieldName) > 0 then begin
Fld := ADestDataSet.FindField(Fields[i].FieldName);
if Assigned(Fld) then
Fld.AsVariant := Fields[i].AsVariant;
end;
end;
Next;
end;
finally
GotoBookmark(bmrk);
EnableControls;
FreeAndNil(bmrk);
end;
end;
finally
ExcludedFieldsStrList.Free;
end;
end;
procedure CopyRecord(ASourceDataSet, ADestDataSet: TDataSet;
AExcludedFields: String = '');
var
Fld: TField;
i: Integer;
ExcludedFieldsStrList: TStringList;
begin
if not Assigned(ASourceDataSet) or not ASourceDataSet.Active then exit;
if not Assigned(ADestDataSet) or not ADestDataSet.Active then exit;
ExcludedFieldsStrList := TStringList.Create;
ExcludedFieldsStrList.CommaText := AExcludedFields;
try
for i := 0 to ASourceDataSet.FieldCount - 1 do begin
if ExcludedFieldsStrList.IndexOf(ASourceDataSet.Fields[i].FieldName) > 0 then begin
Fld := ADestDataSet.FindField(ASourceDataSet.Fields[i].FieldName);
if Assigned(Fld) then
Fld.AsVariant := ASourceDataSet.Fields[i].AsVariant;
end;
end;
finally
ExcludedFieldsStrList.Free;
end;
end;
function FieldHasValue(ADataSet: TDataSet; AFieldName: String;
AFieldValue: Variant): Boolean;
var
Fld: TField;
bmrk: TBookmark;
begin
Result := False;
if not Assigned(ADataSet) or not ADataSet.Active then Exit;
Fld := ADataSet.FindField(AFieldName);
if not Assigned(Fld) then Exit;
with ADataSet do begin
bmrk := GetBookmark;
Result := True;
try
DisableControls;
First;
while not eof do begin
if Fld.AsVariant <> AFieldValue then begin
Result := False;
Exit;
end;
Next;
end;
finally
GotoBookmark(bmrk);
EnableControls;
FreeAndNil(bmrk);
end;
end;
end;
procedure CopyValueToDataSet(ADataSet: TDataSet; AFieldName: String;
AFieldValue: Variant);
var
Fld: TField;
begin
if not Assigned(ADataSet) or not ADataSet.Active then Exit;
Fld := ADataSet.FindField(AFieldName);
if not Assigned(Fld) then Exit;
with ADataSet do begin
First;
while not eof do begin
Edit;
Fld.AsVariant := AFieldValue;
Next;
end;
end;
end;
function CheckFldIfEmpty(ADataSet: TDataSet; AFieldName: String): Boolean;
var
Fld: TField;
begin
Result := False;
if not Assigned(ADataSet) or not ADataSet.Active then Exit;
Fld := ADataSet.FindField(AFieldName);
if not Assigned(Fld) then Exit;
with ADataSet do begin
try
Result := True;
DisableControls;
First;
while not eof do begin
if not Fld.IsNull then begin
Result := False;
exit;
end;
Next;
end;
finally
EnableControls;
end;
end;
end;
end.
|
{===============================================================================
Projeto Sintegra
****************
Biblioteca de Componente para geração do arquivo Sintegra
Site: http://www.sultan.welter.pro.br
Direitos Autorais Reservados (c) 2004 Régys Borges da Silveira
Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la sob
os termos da Licença Pública Geral Menor do GNU conforme publicada pela Free
Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) qualquer
versão posterior.
Esta biblioteca é distribuído na expectativa de que seja útil, porém, SEM
NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU
ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor do
GNU para mais detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto com
esta biblioteca; se não, escreva para a Free Software Foundation, Inc., no
endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
================================================================================
Contato:
Autor...: Régys Borges da Silveira
Email...: regyssilveira@hotmail.com
================================================================================
Colaboração:
Marcelo Welter <marcelo@welter.pro.br>
===============================================================================}
unit Funcoes;
interface
uses
SysUtils, Controls, Classes, Sintegra;
function LFIll(aString: string; aCaracter: Char; aTamanho: integer): string;
function RFill(aString: string; aCaracter: Char; aTamanho: integer): string;
function StrToNumero(aValor: string; aDecimais: Integer): Extended;
function RetornarCodPosse(TipoPosse: TTipoPosse): string;
function RetornarFinalidade(aFinalidade: TCodFinalidade): string;
function RetornarModDocumento(aTipoDocumento: TModDocumento): string;
function RetornarNatureza(aNaturezaOper: TCodIdentificaOper): string;
function RetornarSitNotafiscal(aSituacao: TSitNotaFiscal): string;
function RetornarTipoEmitente(aTipoEmitente: TTipoEmitente): string;
function RetornarTipoFrete(aTipoFrete: TModalidadeFrete): string;
function VerificarCEP(cCep, cEstado: string): Boolean;
function VerificarCFOP(aCFOP: string): Boolean;
function VerificarCPF_CNPJ(aCNPJ_CPF: string): Boolean;
function VerificarCST(aCST: string): Boolean;
function VerificarInscEstadual(aInscricao, aTipo: string): Boolean;
function VerificarSitTributaria(aSitTributaria: string): Boolean;
function VerificarUF(aUF: string): Boolean;
function VerificarSerieNF(aSerie: string): Boolean;
implementation
{
********** Preenche com caracteres a direita ***********************************
}
function RFill(aString: string; aCaracter: Char; aTamanho: integer): string;
var
Dado: string;
begin
if Length(aString) > aTamanho then
Dado := Copy(aString, 0, aTamanho)
else
Dado := aString;
Result := Dado + StringOfChar(aCaracter, aTamanho - length(Dado));
end;
{
********** Preenche com caracteres a esquerda **********************************
}
function LFIll(aString: string; aCaracter: Char; aTamanho: integer): string;
var
Dado: string;
begin
if Length(aString) > aTamanho then
Dado := Copy(aString, 0, aTamanho)
else
Dado := aString;
Result := StringOfChar(aCaracter, aTamanho - length(Dado)) + Dado;
end;
{
********** Retorna o codigo na natureza da operação ****************************
}
function RetornarNatureza(aNaturezaOper: TCodIdentificaOper): string;
begin
case aNaturezaOper of
opeInterestSubTributaria: Result := '1';
opeInterestaduais: Result := '2';
opeTotal: Result := '3';
end;
end;
{
********** Retorna o codigo da finalidade **************************************
}
function RetornarFinalidade(aFinalidade: TCodFinalidade): string;
begin
case aFinalidade of
finNormal: Result := '1';
finRetificacaoTotal: Result := '2';
finRetificacaoAditiva: Result := '3';
finDesfazimento: Result := '5';
end;
end;
{
********** Retorna o Modelo do documento pra o registro 60 *********************
}
function RetornarModDocumento(aTipoDocumento: TModDocumento): string;
begin
case aTipoDocumento of
modMaqRegistradora: Result := '2B';
modPDV: Result := '2C';
modECF: Result := '2D';
end;
end;
{
********** Retorna o tipo do emitente ******************************************
}
function RetornarTipoEmitente(aTipoEmitente: TTipoEmitente): string;
begin
case aTipoEmitente of
tpeProprio: Result := 'P';
tpeTerceiros: Result := 'T';
end;
end;
{
********** Retorna a situação da nota fiscal ***********************************
}
function RetornarSitNotafiscal(aSituacao: TSitNotaFiscal): string;
begin
case aSituacao of
nfNormal: Result := 'N';
nfCancelado: Result := 'S';
nfExtNormal: Result := 'E';
nfExtCancelado: Result := 'X';
end;
end;
{
********** Retorna a modalidade do frete ***************************************
}
function RetornarTipoFrete(aTipoFrete: TModalidadeFrete): string;
begin
case aTipoFrete of
frCIF: Result := '1';
frFOB: Result := '2';
frOUTRO: Result := '0';
end;
end;
{
********** Verifica se a UF digitada e valida **********************************
}
function VerificarUF(aUF: string): Boolean;
const
ListaUF: array[0..26] of string = (
'AC', 'AL', 'AM', 'AP', 'BA', 'CE', 'DF',
'ES', 'GO', 'MA', 'MG', 'MS', 'MT', 'PA',
'PB', 'PE', 'PI', 'PR', 'RJ', 'RN', 'RO',
'RR', 'RS', 'SC', 'SE', 'SP', 'TO');
var
i: integer;
Encontrado: Boolean;
begin
i := 0;
Encontrado := False;
while (not (Encontrado)) and (i <= 26) do
begin
Encontrado := ListaUF[i] = aUF;
inc(i);
end;
Result := Encontrado;
end;
{
********** Verifica se o CEP e valido ******************************************
}
function VerificarCEP(cCep: string; cEstado: string): Boolean;
var
cCEP1: Integer;
begin
cCEP1 := StrToInt(copy(cCep, 1, 3));
if Length(trim(cCep)) > 0 then
begin
if Length(trim(copy(cCep, 6, 3))) < 3 then
Result := False
else if (cEstado = 'SP') and (cCEP1 >= 10) and (cCEP1 <= 199) then
Result := True
else if (cEstado = 'RJ') and (cCEP1 >= 200) and (cCEP1 <= 289) then
Result := True
else if (cEstado = 'ES') and (cCEP1 >= 290) and (cCEP1 <= 299) then
Result := True
else if (cEstado = 'MG') and (cCEP1 >= 300) and (cCEP1 <= 399) then
Result := True
else if (cEstado = 'BA') and (cCEP1 >= 400) and (cCEP1 <= 489) then
Result := True
else if (cEstado = 'SE') and (cCEP1 >= 490) and (cCEP1 <= 499) then
Result := True
else if (cEstado = 'PE') and (cCEP1 >= 500) and (cCEP1 <= 569) then
Result := True
else if (cEstado = 'AL') and (cCEP1 >= 570) and (cCEP1 <= 579) then
Result := True
else if (cEstado = 'PB') and (cCEP1 >= 580) and (cCEP1 <= 589) then
Result := True
else if (cEstado = 'RN') and (cCEP1 >= 590) and (cCEP1 <= 599) then
Result := True
else if (cEstado = 'CE') and (cCEP1 >= 600) and (cCEP1 <= 639) then
Result := True
else if (cEstado = 'PI') and (cCEP1 >= 640) and (cCEP1 <= 649) then
Result := True
else if (cEstado = 'MA') and (cCEP1 >= 650) and (cCEP1 <= 659) then
Result := True
else if (cEstado = 'PA') and (cCEP1 >= 660) and (cCEP1 <= 688) then
Result := True
else if (cEstado = 'AM') and ((cCEP1 >= 690) and (cCEP1 <= 692) or (cCEP1 >= 694) and (cCEP1 <= 698)) then
Result := True
else if (cEstado = 'AP') and (cCEP1 = 689) then
Result := True
else if (cEstado = 'RR') and (cCEP1 = 693) then
Result := True
else if (cEstado = 'AC') and (cCEP1 = 699) then
Result := True
else if ((cEstado = 'DF') or (cEstado = 'GO')) and (cCEP1 >= 700) and (cCEP1 <= 769) then
Result := True
else if (cEstado = 'TO') and (cCEP1 >= 770) and (cCEP1 <= 779) then
Result := True
else if (cEstado = 'MT') and (cCEP1 >= 780) and (cCEP1 <= 788) then
Result := True
else if (cEstado = 'MS') and (cCEP1 >= 790) and (cCEP1 <= 799) then
Result := True
else if (cEstado = 'RO') and (cCEP1 = 789) then
Result := True
else if (cEstado = 'PR') and (cCEP1 >= 800) and (cCEP1 <= 879) then
Result := True
else if (cEstado = 'SC') and (cCEP1 >= 880) and (cCEP1 <= 899) then
Result := True
else if (cEstado = 'RS') and (cCEP1 >= 900) and (cCEP1 <= 999) then
Result := True
else
Result := False
end
else
Result := True;
end;
{
********** Valida a inscrição estadual *****************************************
}
function VerificarInscEstadual(aInscricao, aTipo: string): Boolean;
var
Contador: ShortInt;
Casos: ShortInt;
Digitos: ShortInt;
Tabela_1: string;
Tabela_2: string;
Tabela_3: string;
Base_1: string;
Base_2: string;
Base_3: string;
Valor_1: ShortInt;
Soma_1: Integer;
Soma_2: Integer;
Erro_1: ShortInt;
Erro_2: ShortInt;
Erro_3: ShortInt;
Posicao_1: string;
Posicao_2: string;
Tabela: string;
Rotina: string;
Modulo: ShortInt;
Peso: string;
Digito: ShortInt;
Resultado: string;
Retorno: Boolean;
begin
try
Tabela_1 := ' ';
Tabela_2 := ' ';
Tabela_3 := ' ';
if aTipo = 'AC' then
Tabela_1 := '1.09.0.E.11.01. . . . 01NNNNNNX.14.00';
if aTipo = 'AC' then
Tabela_2 := '2.13.0.E.11.02.E.11.01. 01NNNNNNNNNXY.13.14';
if aTipo = 'AL' then
Tabela_1 := '1.09.0.0.11.01. . . . 24BNNNNNX.14.00';
if aTipo = 'AP' then
Tabela_1 := '1.09.0.1.11.01. . . . 03NNNNNNX.14.00';
if aTipo = 'AP' then
Tabela_2 := '2.09.1.1.11.01. . . . 03NNNNNNX.14.00';
if aTipo = 'AP' then
Tabela_3 := '3.09.0.E.11.01. . . . 03NNNNNNX.14.00';
if aTipo = 'AM' then
Tabela_1 := '1.09.0.E.11.01. . . . 0CNNNNNNX.14.00';
if aTipo = 'BA' then
Tabela_1 := '1.08.0.E.10.02.E.10.03. NNNNNNYX.14.13';
if aTipo = 'BA' then
Tabela_2 := '2.08.0.E.11.02.E.11.03. NNNNNNYX.14.13';
if aTipo = 'CE' then
Tabela_1 := '1.09.0.E.11.01. . . . 0NNNNNNNX.14.13';
if aTipo = 'DF' then
Tabela_1 := '1.13.0.E.11.02.E.11.01. 07DNNNNNNNNXY.13.14';
if aTipo = 'ES' then
Tabela_1 := '1.09.0.E.11.01. . . . 0ENNNNNNX.14.00';
if aTipo = 'GO' then
Tabela_1 := '1.09.1.E.11.01. . . . 1FNNNNNNX.14.00';
if aTipo = 'GO' then
Tabela_2 := '2.09.0.E.11.01. . . . 1FNNNNNNX.14.00';
if aTipo = 'MA' then
Tabela_1 := '1.09.0.E.11.01. . . . 12NNNNNNX.14.00';
if aTipo = 'MT' then
Tabela_1 := '1.11.0.E.11.01. . . . NNNNNNNNNNX.14.00';
if aTipo = 'MS' then
Tabela_1 := '1.09.0.E.11.01. . . . 28NNNNNNX.14.00';
if aTipo = 'MG' then
Tabela_1 := '1.13.0.2.10.10.E.11.11. NNNNNNNNNNNXY.13.14';
if aTipo = 'PA' then
Tabela_1 := '1.09.0.E.11.01. . . . 15NNNNNNX.14.00';
if aTipo = 'PB' then
Tabela_1 := '1.09.0.E.11.01. . . . 16NNNNNNX.14.00';
if aTipo = 'PR' then
Tabela_1 := '1.10.0.E.11.09.E.11.08. NNNNNNNNXY.13.14';
if aTipo = 'PE' then
Tabela_1 := '1.14.1.E.11.07. . . .18ANNNNNNNNNNX.14.00';
if aTipo = 'PI' then
Tabela_1 := '1.09.0.E.11.01. . . . 19NNNNNNX.14.00';
if aTipo = 'RJ' then
Tabela_1 := '1.08.0.E.11.08. . . . GNNNNNNX.14.00';
if aTipo = 'RN' then
Tabela_1 := '1.09.0.0.11.01. . . . 20HNNNNNX.14.00';
if aTipo = 'RS' then
Tabela_1 := '1.10.0.E.11.01. . . . INNNNNNNNX.14.00';
if aTipo = 'RO' then
Tabela_1 := '1.09.1.E.11.04. . . . ANNNNNNNX.14.00';
if aTipo = 'RO' then
Tabela_2 := '2.14.0.E.11.01. . . .NNNNNNNNNNNNNX.14.00';
if aTipo = 'RR' then
Tabela_1 := '1.09.0.D.09.05. . . . 24NNNNNNX.14.00';
if aTipo = 'SC' then
Tabela_1 := '1.09.0.E.11.01. . . . NNNNNNNNX.14.00';
if aTipo = 'SP' then
Tabela_1 := '1.12.0.D.11.12.D.11.13. NNNNNNNNXNNY.11.14';
if aTipo = 'SP' then
Tabela_2 := '2.12.0.D.11.12. . . . NNNNNNNNXNNN.11.00';
if aTipo = 'SE' then
Tabela_1 := '1.09.0.E.11.01. . . . NNNNNNNNX.14.00';
if aTipo = 'TO' then
Tabela_1 := '1.11.0.E.11.06. . . . 29JKNNNNNNX.14.00';
if aTipo = 'CNPJ' then
Tabela_1 := '1.14.0.E.11.21.E.11.22.NNNNNNNNNNNNXY.13.14';
if aTipo = 'CPF' then
Tabela_1 := '1.11.0.E.11.31.E.11.32. NNNNNNNNNXY.13.14';
{ Deixa somente os numeros }
Base_1 := '';
for Contador := 1 to 30 do
if Pos(Copy(aInscricao, Contador, 1), '0123456789') <> 0 then
Base_1 := Base_1 + Copy(aInscricao, Contador, 1);
{ Repete 3x - 1 para cada caso possivel }
Casos := 0;
Erro_1 := 0;
Erro_2 := 0;
Erro_3 := 0;
while Casos < 3 do
begin
Casos := Casos + 1;
if Casos = 1 then
Tabela := Tabela_1;
if Casos = 2 then
Erro_1 := Erro_3;
if Casos = 2 then
Tabela := Tabela_2;
if Casos = 3 then
Erro_2 := Erro_3;
if Casos = 3 then
Tabela := Tabela_3;
Erro_3 := 0;
if Copy(Tabela, 1, 1) <> ' ' then
begin
{ Verifica o Tamanho }
if Length(Trim(Base_1)) <> (StrToInt(Copy(Tabela, 3, 2))) then
Erro_3 := 1;
if Erro_3 = 0 then
begin
{ Ajusta o Tamanho }
Base_2 := Copy(' ' + Base_1, Length(' ' + Base_1) - 13, 14);
{ Compara com valores possivel para cada uma da 14 posições }
Contador := 0;
while (Contador < 14) and (Erro_3 = 0) do
begin
Contador := Contador + 1;
Posicao_1 := Copy(Copy(Tabela, 24, 14), Contador, 1);
Posicao_2 := Copy(Base_2, Contador, 1);
if (Posicao_1 = ' ') and (Posicao_2 <> ' ') then
Erro_3 := 1;
if (Posicao_1 = 'N') and (Pos(Posicao_2, '0123456789') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'A') and (Pos(Posicao_2, '123456789') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'B') and (Pos(Posicao_2, '03578') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'C') and (Pos(Posicao_2, '47') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'D') and (Pos(Posicao_2, '34') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'E') and (Pos(Posicao_2, '08') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'F') and (Pos(Posicao_2, '015') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'G') and (Pos(Posicao_2, '1789') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'H') and (Pos(Posicao_2, '0123') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'I') and (Pos(Posicao_2, '01234') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'J') and (Pos(Posicao_2, '09') = 0) then
Erro_3 := 1;
if (Posicao_1 = 'K') and (Pos(Posicao_2, '1239') = 0) then
Erro_3 := 1;
if (Posicao_1 <> Posicao_2) and (Pos(Posicao_1, '0123456789') > 0) then
Erro_3 := 1;
end;
{ Calcula os Digitos }
Rotina := ' ';
Digitos := 000;
Digito := 000;
while (Digitos < 2) and (Erro_3 = 0) do
begin
Digitos := Digitos + 1;
{ Carrega peso }
Peso := Copy(Tabela, 5 + (Digitos * 8), 2);
if Peso <> ' ' then
begin
Rotina := Copy(Tabela, 0 + (Digitos * 8), 1);
Modulo := StrToInt(Copy(Tabela, 2 + (Digitos * 8), 2));
if Peso = '01' then
Peso := '06.05.04.03.02.09.08.07.06.05.04.03.02.00';
if Peso = '02' then
Peso := '05.04.03.02.09.08.07.06.05.04.03.02.00.00';
if Peso = '03' then
Peso := '06.05.04.03.02.09.08.07.06.05.04.03.00.02';
if Peso = '04' then
Peso := '00.00.00.00.00.00.00.00.06.05.04.03.02.00';
if Peso = '05' then
Peso := '00.00.00.00.00.01.02.03.04.05.06.07.08.00';
if Peso = '06' then
Peso := '00.00.00.09.08.00.00.07.06.05.04.03.02.00';
if Peso = '07' then
Peso := '05.04.03.02.01.09.08.07.06.05.04.03.02.00';
if Peso = '08' then
Peso := '08.07.06.05.04.03.02.07.06.05.04.03.02.00';
if Peso = '09' then
Peso := '07.06.05.04.03.02.07.06.05.04.03.02.00.00';
if Peso = '10' then
Peso := '00.01.02.01.01.02.01.02.01.02.01.02.00.00';
if Peso = '11' then
Peso := '00.03.02.11.10.09.08.07.06.05.04.03.02.00';
if Peso = '12' then
Peso := '00.00.01.03.04.05.06.07.08.10.00.00.00.00';
if Peso = '13' then
Peso := '00.00.03.02.10.09.08.07.06.05.04.03.02.00';
if Peso = '21' then
Peso := '05.04.03.02.09.08.07.06.05.04.03.02.00.00';
if Peso = '22' then
Peso := '06.05.04.03.02.09.08.07.06.05.04.03.02.00';
if Peso = '31' then
Peso := '00.00.00.10.09.08.07.06.05.04.03.02.00.00';
if Peso = '32' then
Peso := '00.00.00.11.10.09.08.07.06.05.04.03.02.00';
{ Multiplica }
Base_3 := Copy(('0000000000000000' + Trim(Base_2)), Length(('0000000000000000' + Trim(Base_2))) - 13, 14);
Soma_1 := 0;
Soma_2 := 0;
for Contador := 1 to 14 do
begin
Valor_1 := (StrToInt(Copy(Base_3, Contador, 01)) * StrToInt(Copy(Peso, Contador * 3 - 2, 2)));
Soma_1 := Soma_1 + Valor_1;
if Valor_1 > 9 then
Valor_1 := Valor_1 - 9;
Soma_2 := Soma_2 + Valor_1;
end;
{ Ajusta valor da soma }
if Pos(Rotina, 'A2') > 0 then
Soma_1 := Soma_2;
if Pos(Rotina, 'B0') > 0 then
Soma_1 := Soma_1 * 10;
if Pos(Rotina, 'C1') > 0 then
Soma_1 := Soma_1 + (5 + 4 * StrToInt(Copy(Tabela, 6, 1)));
{ Calcula o Digito }
if Pos(Rotina, 'D0') > 0 then
Digito := Soma_1 mod Modulo;
if Pos(Rotina, 'E12') > 0 then
Digito := Modulo - (Soma_1 mod Modulo);
if Digito < 10 then
Resultado := IntToStr(Digito);
if Digito = 10 then
Resultado := '0';
if Digito = 11 then
Resultado := Copy(Tabela, 6, 1);
{ Verifica o Digito }
if (Copy(Base_2, StrToInt(Copy(Tabela, 36 + (Digitos * 3), 2)), 1) <> Resultado) then
Erro_3 := 1;
end;
end;
end;
end;
end;
{ Retorna o resultado da Verificação }
Retorno := FALSE;
if (Trim(Tabela_1) <> '') and (ERRO_1 = 0) then
Retorno := TRUE;
if (Trim(Tabela_2) <> '') and (ERRO_2 = 0) then
Retorno := TRUE;
if (Trim(Tabela_3) <> '') and (ERRO_3 = 0) then
Retorno := TRUE;
if Trim(aInscricao) = 'ISENTO' then
Retorno := TRUE;
Result := Retorno;
except
Result := False;
end;
end;
{
********** Verifica se o CPF/CNPJ e Valido *************************************
}
function VerificarCPF_CNPJ(aCNPJ_CPF: string): Boolean;
var
iD1, iD2, i: integer;
sNumero, sDigitado, sCalculado: string;
begin
{ Limpa a String deixando so os numeros }
sNumero := '';
for i := 0 to Length(aCNPJ_CPF) do
if aCNPJ_CPF[i] in ['0'..'9'] then
sNumero := sNumero + aCNPJ_CPF[i];
{ Efetua os calculos para a validacao }
case Length(sNumero) of
11: { CPF }
begin
{ Calculo do primeiro digito }
iD1 := 11 - (
(
(StrToInt(sNumero[9]) * 2) +
(StrToInt(sNumero[8]) * 3) +
(StrToInt(sNumero[7]) * 4) +
(StrToInt(sNumero[6]) * 5) +
(StrToInt(sNumero[5]) * 6) +
(StrToInt(sNumero[4]) * 7) +
(StrToInt(sNumero[3]) * 8) +
(StrToInt(sNumero[2]) * 9) +
(StrToInt(sNumero[1]) * 10)
) mod 11);
if iD1 >= 10 then
iD1 := 0;
{ Calculo do Segundo Digito }
iD2 := 11 - (
(
(iD1 * 2) +
(StrToInt(sNumero[9]) * 3) +
(StrToInt(sNumero[8]) * 4) +
(StrToInt(sNumero[7]) * 5) +
(StrToInt(sNumero[6]) * 6) +
(StrToInt(sNumero[5]) * 7) +
(StrToInt(sNumero[4]) * 8) +
(StrToInt(sNumero[3]) * 9) +
(StrToInt(sNumero[2]) * 10) +
(StrToInt(sNumero[1]) * 11)
) mod 11);
if iD2 >= 10 then
iD2 := 0;
sCalculado := IntToStr(iD1) + IntToStr(iD2);
sDigitado := sNumero[10] + sNumero[11];
Result := sCalculado = sDigitado;
end;
14: { CNPJ }
begin
{ Calculo do primeiro digito }
iD1 := 11 - (
(
(StrToInt(sNumero[12]) * 2) +
(StrToInt(sNumero[11]) * 3) +
(StrToInt(sNumero[10]) * 4) +
(StrToInt(sNumero[9]) * 5) +
(StrToInt(sNumero[8]) * 6) +
(StrToInt(sNumero[7]) * 7) +
(StrToInt(sNumero[6]) * 8) +
(StrToInt(sNumero[5]) * 9) +
(StrToInt(sNumero[4]) * 2) +
(StrToInt(sNumero[3]) * 3) +
(StrToInt(sNumero[2]) * 4) +
(StrToInt(sNumero[1]) * 5)
) mod 11);
if iD1 >= 10 then
iD1 := 0;
{ Calculo do Segundo Digito }
iD2 := 11 - (
(
(iD1 * 2) +
(StrToInt(sNumero[12]) * 3) +
(StrToInt(sNumero[11]) * 4) +
(StrToInt(sNumero[10]) * 5) +
(StrToInt(sNumero[9]) * 6) +
(StrToInt(sNumero[8]) * 7) +
(StrToInt(sNumero[7]) * 8) +
(StrToInt(sNumero[6]) * 9) +
(StrToInt(sNumero[5]) * 2) +
(StrToInt(sNumero[4]) * 3) +
(StrToInt(sNumero[3]) * 4) +
(StrToInt(sNumero[2]) * 5) +
(StrToInt(sNumero[1]) * 6)
) mod 11);
if iD2 >= 10 then
iD2 := 0;
sCalculado := IntToStr(iD1) + IntToStr(iD2);
sDigitado := sNumero[13] + sNumero[14];
Result := sCalculado = sDigitado;
end;
else
Result := False;
end;
end;
{
********** Passa uma string para numero ****************************************
}
function StrToNumero(aValor: string; aDecimais: Integer): Extended;
var
i, iInicio, iFim: Integer;
str: string;
begin
str := '0';
if Trim(aValor) <> '' then
begin
for i := 0 to Length(aValor) do
if aValor[i] in ['0'..'9', '-'] then
str := str + avalor[i];
if (Trim(str) <> '') and (Trim(str) <> '-') then
begin
iInicio := Length(str) - aDecimais;
iFim := Length(str);
str := copy(str, 0, iInicio) + DecimalSeparator + Copy(str, iInicio + 1, iFim);
end;
end;
Result := StrTofloat(str);
end;
{
********** Verifica se a Serie da NF e válida **********************************
}
function VerificarSerieNF(aSerie: string): Boolean;
var
Serie: string;
begin
if Length(aSerie) > 3 then
Result := False
else
begin
Serie := LFill(aSerie, ' ', 3);
Result := (Serie[1] in [' ', 'B', 'C', 'E', 'U']) and
(Serie[2] in [' ', 'U', '1'..'9']) and
(Serie[3] in [' ', '1'..'9']) and
(Serie <> 'UU');
end;
end;
{
********** Verifica se a Situação Tributária e válida **************************
}
function VerificarSitTributaria(aSitTributaria: string): Boolean;
var
aAliquota: Currency;
aValida: Boolean;
begin
aAliquota := StrToNumero(aSitTributaria, 2);
if aAliquota = 0 then
begin
if aSitTributaria = 'F' then
aValida := True
else if aSitTributaria = 'I' then
aValida := True
else if aSitTributaria = 'N' then
aValida := True
else if aSitTributaria = 'CANC' then
aValida := True
else if aSitTributaria = 'DESC' then
aValida := True
else if aSitTributaria = 'ISS' then
aValida := True
else
aValida := False;
end
else
aValida := True;
Result := aValida;
end;
{
********** Verifica se o CFOP e válido *****************************************
}
function VerificarCFOP(aCFOP: string): Boolean;
const
ListaCFOP: array[0..522] of string = (
'1101', '1102', '1111', '1113', '1116', '1117', '1118', '1120', '1121', '1122', '1124', '1125', '1126', '1151', '1152', '1153', '1154', '1201',
'1202', '1203', '1204', '1205', '1206', '1207', '1208', '1209', '1251', '1252', '1253', '1254', '1255', '1256', '1257', '1301', '1302', '1303',
'1304', '1305', '1306', '1351', '1352', '1353', '1354', '1355', '1356', '1401', '1403', '1406', '1407', '1408', '1409', '1410', '1411', '1414',
'1415', '1451', '1452', '1501', '1503', '1504', '1551', '1552', '1553', '1554', '1555', '1556', '1557', '1601', '1602', '1603', '1604', '1650',
'1651', '1652', '1653', '1658', '1659', '1660', '1661', '1662', '1663', '1664', '1901', '1902', '1903', '1904', '1905', '1906', '1907', '1908',
'1909', '1910', '1911', '1912', '1913', '1914', '1915', '1916', '1917', '1918', '1919', '1920', '1921', '1922', '1923', '1924', '1925', '1926',
'1949', '2101', '2102', '2111', '2113', '2116', '2117', '2118', '2120', '2121', '2122', '2124', '2125', '2126', '2151', '2152', '2153', '2154',
'2201', '2202', '2203', '2204', '2205', '2206', '2207', '2208', '2209', '2251', '2252', '2253', '2254', '2255', '2256', '2257', '2301', '2302',
'2303', '2304', '2305', '2306', '2351', '2352', '2353', '2354', '2355', '2356', '2401', '2403', '2406', '2407', '2408', '2409', '2410', '2411',
'2414', '2415', '2501', '2503', '2504', '2551', '2552', '2553', '2554', '2555', '2556', '2557', '2603', '2651', '2652', '2653', '2658', '2659',
'2660', '2661', '2662', '2663', '2664', '2901', '2902', '2903', '2904', '2905', '2906', '2907', '2908', '2909', '2910', '2911', '2912', '2913',
'2914', '2915', '2916', '2917', '2918', '2919', '2920', '2921', '2922', '2923', '2924', '2925', '2949', '3101', '3102', '3126', '3127', '3201',
'3202', '3205', '3206', '3207', '3211', '3251', '3301', '3351', '3352', '3353', '3354', '3355', '3356', '3503', '3551', '3553', '3556', '3650',
'3651', '3652', '3653', '3930', '3949', '5101', '5102', '5103', '5104', '5105', '5106', '5109', '5110', '5111', '5112', '5113', '5114', '5115',
'5116', '5117', '5118', '5119', '5120', '5122', '5123', '5124', '5125', '5151', '5152', '5153', '5155', '5156', '5201', '5202', '5205', '5206',
'5207', '5208', '5209', '5210', '5251', '5252', '5253', '5254', '5255', '5256', '5257', '5258', '5301', '5302', '5303', '5304', '5305', '5306',
'5307', '5351', '5352', '5353', '5354', '5355', '5356', '5357', '5401', '5402', '5403', '5405', '5408', '5409', '5410', '5411', '5412', '5413',
'5414', '5415', '5451', '5501', '5502', '5503', '5551', '5552', '5553', '5554', '5555', '5556', '5557', '5601', '5602', '5603', '5650', '5651',
'5652', '5653', '5654', '5655', '5656', '5657', '5658', '5659', '5660', '5661', '5662', '5663', '5664', '5665', '5666', '5901', '5902', '5903',
'5904', '5905', '5906', '5907', '5908', '5909', '5910', '5911', '5912', '5913', '5914', '5915', '5916', '5917', '5918', '5919', '5920', '5921',
'5922', '5923', '5924', '5925', '5926', '5927', '5928', '5929', '5931', '5932', '5949', '6101', '6102', '6103', '6104', '6105', '6106', '6107',
'6108', '6109', '6110', '6111', '6112', '6113', '6114', '6115', '6116', '6117', '6118', '6119', '6120', '6122', '6123', '6124', '6125', '6151',
'6152', '6153', '6155', '6156', '6201', '6202', '6205', '6206', '6207', '6208', '6209', '6210', '6251', '6252', '6253', '6254', '6255', '6256',
'6257', '6258', '6301', '6302', '6303', '6304', '6305', '6306', '6307', '6351', '6352', '6353', '6354', '6355', '6356', '6357', '6401', '6402',
'6403', '6404', '6408', '6409', '6410', '6411', '6412', '6413', '6414', '6415', '6501', '6502', '6503', '6551', '6552', '6553', '6554', '6555',
'6556', '6557', '6603', '6650', '6651', '6652', '6653', '6654', '6655', '6656', '6657', '6658', '6659', '6660', '6661', '6662', '6663', '6664',
'6665', '6666', '6901', '6902', '6903', '6904', '6905', '6906', '6907', '6908', '6909', '6910', '6911', '6912', '6913', '6914', '6915', '6916',
'6917', '6918', '6919', '6920', '6921', '6922', '6923', '6924', '6925', '6929', '6931', '6932', '6949', '7101', '7102', '7105', '7106', '7127',
'7201', '7202', '7205', '7206', '7207', '7210', '7211', '7251', '7301', '7358', '7501', '7551', '7553', '7556', '7650', '7651', '7654', '7930',
'7949');
var
i: Integer;
Encontrado: Boolean;
begin
i := 0;
Encontrado := False;
while (not (Encontrado)) and (i <= 522) do
begin
Encontrado := ListaCFOP[i] = aCFOP;
inc(i);
end;
Result := Encontrado;
end;
{
********** Verifica se o Código de Situação Tributária esta correto ************
}
function VerificarCST(aCST: string): Boolean;
const
ListaCST: array[0..32] of string = (
'000', '010', '020', '030', '040', '041', '050', '051',
'060', '070', '090', '100', '110', '120', '130', '140',
'141', '150', '151', '160', '170', '190', '200', '210',
'220', '230', '240', '241', '250', '251', '260', '270',
'290');
var
i: integer;
Encontrado: Boolean;
begin
i := 0;
Encontrado := False;
while (not (Encontrado)) and (i <= 32) do
begin
Encontrado := ListaCST[i] = aCST;
inc(i);
end;
Result := Encontrado;
end;
{
********** Retorna o codigo do tipo de posse para a mercadoria no inventario ***
}
function RetornarCodPosse(TipoPosse: TTipoPosse): string;
begin
case TipoPosse of
tpo1: Result := '1';
tpo2: Result := '2';
tpo3: Result := '3';
end;
end;
end.
|
unit J_level;
{$MODE Delphi}
{This unit defines the classes for JK
level}
interface
uses Classes, Files, Tools, SysUtils, misc_utils,
GlobalVars, Geometry, FileOperations, Values, U_3dos;
Const
SF_Floor=1;
FF_Transluent=2;
SF_3DO=1 shl 31;
SFF_IMPASSABLE=4;
SFF_SKY=512;
SFF_SKY1=1024;
SFF_DOUBLERES=$10;
SFF_HALFRES=$20;
SFF_EIGHTHRES=$40;
SFF_FLIP=$80000000;
LF_NoBlock=1;
TX_DFLT=0;
TX_KEEP=1;
TF_NOEASY = $1000; // Object will not appear in "EASY" mode
TF_NOMEDIUM = $2000; // Object will not appear in "MEDIUM" mode
TF_NOHARD = $4000; // Object will not appear in "HARD" mode
TF_NOMULTI = $8000; // Object will not appear in Multiplyer modes
AF_BlockLight=$80000000;
type
TJKLevel=class;
TJKSector=class;
TJKSurface=class;
TJKVertex=class(TVertex)
Sector:TJKSector; {Owning sector}
Procedure Assign(v:TJKVertex);
end;
TJedLight=class
ID:integer; {Unique ID. Used in Undo}
X,Y,Z:double;
mark:integer;
Intensity:double;
Range:double;
layer:integer;
flags:longint;
R,G,B:Single;
rgbintensity:single;
rgbrange:double;
Constructor Create;
Procedure Assign(l:TJedLight);
end;
TJedLights=class(TList)
Function GetItem(n:integer):TJedLight;
Procedure SetItem(n:integer;v:TJedLight);
Property Items[n:integer]:TJedLight read GetItem write SetItem; default;
end;
TJKVertices=class(TVertices)
Function GetItem(n:integer):TJKVertex;
Procedure SetItem(n:integer;v:TJKVertex);
Property Items[n:integer]:TJKVertex read GetItem write SetItem; default;
end;
TJKLine=class
v1,v2:TJKVertex;
end;
TSectors=class(TList)
Function GetItem(n:integer):TJKSector;
Procedure SetItem(n:integer;v:TJKSector);
Property Items[n:integer]:TJKSector read GetItem write SetItem; default;
end;
TThing=class
ID:integer; {Unique ID. Used in Undo}
level:TJKLevel;
num:integer;
Sec:TJKSector;
name:String;
X,Y,Z:double;
PCH,YAW,ROL:Double;
vals:TTPLValues;
layer:integer;
a3DO:T3DO;
bbox:TThingBox;
Constructor Create;
Destructor Destroy;override;
Procedure Assign(thing:TThing);
Function AddValue(const name,s:string):TTplValue;
Function InsertValue(n:integer;const name,s:string):TTPlValue;
Function NextFrame(n:integer):integer;
Function PrevFrame(n:integer):integer;
Function Nframes:Integer;
end;
TJKThing=TThing;
TThings=class(TList)
Function GetItem(n:integer):TThing;
Procedure SetItem(n:integer;v:TThing);
Property Items[n:integer]:TThing read GetItem write SetItem; default;
end;
TJKSurface=class(TPolygon)
Adjoin:TJKSurface;
AdjoinFlags:Longint;
Material:String;
SurfFlags,FaceFlags:Longint;
sector:TJKSector;
geo,light,tex:integer;
extraLight:double;
mark,D3DID:integer;
num:integer;
nadj,nmat:integer;
uscale,vscale:single;
{ ucosa,usina:double;}
Function GetVXs:TJKVertices;
Procedure SetVXs(vxs:TJKVertices);
Property Vertices:TJKVertices read GetVXs write SetVXs;
Constructor Create(owner:TJKSector);
procedure Assign(surf:TJKSurface);
Procedure NewRecalcAll;
Procedure RecalcAll;
Procedure CheckIfFloor;
Function GetRefVector(var v:TVector):boolean;
end;
TSurfaces=class(TPolygons)
Function GetItem(n:integer):TJKSurface;
Procedure SetItem(n:integer;v:TJKSurface);
Property Items[n:integer]:TJKSurface read GetItem write SetItem; default;
end;
TJKSector=class{(TPolygons)}
ID:integer; {Unique ID. Used in Undo}
num:integer;
Flags:longint;
Ambient:double;
extra:double;
ColorMap:String;
Tint:TVector;
Sound:string;
snd_vol:double;
level:TJKLevel;
surfaces:TSurfaces;
vertices:TJKVertices;
layer:integer;
mark:integer;
Procedure Assign(sec:TJKSector);
Constructor Create(owner:TJKLevel);
Destructor Destroy;override;
Function NewVertex:TJKVertex;
Function NewSurface:TJKSurface;
Procedure Renumber;
Function FindVX(x,y,z:double):integer;
Function AddVertex(x,y,z:double):TJKVertex;
end;
TCOG=class
name:string;
vals:TCOGValues;
Constructor Create;
Destructor Destroy;override;
Procedure GetValues;
end;
TCOGs=class(TList)
Function GetItem(n:integer):TCOG;
Procedure SetItem(n:integer;v:TCOG);
Property Items[n:integer]:TCOG read GetItem write SetItem; default;
end;
TJKLHeader=record
version:Longint;
Gravity, CeilingSkyZ,
HorDistance,HorPixelsPerRev:float;
HorSkyOffs:array[1..2] of float;
CeilingSkyOffs:array[1..2] of float;
MipMapDist:array[1..4] of float;
LODDist:array[1..4] of float;
PerspDist, GouraudDist:float;
end;
TJKLevel=class
header:TJKLHeader;
mots:boolean;
sectors:TSectors;
Cogs:TCOGs;
Things:TThings;
Lights:TJedLights;
Layers:TStringList;
h3donodes:THNodes;
masterCMP:String;
ppunit:double;
lvisstring:string; {layer visibility string - in form 0101}
CurID:Integer;
Constructor Create;
Destructor Destroy;override;
Procedure Clear;
Procedure LoadFromJKL(F:TFileName);
Procedure JKLPostLoad;
Procedure LoadFromJed(F:TFileName);
Procedure SaveToJKL(F:TFileName);
Procedure SaveToJed(F:TFileName);
Procedure ImportLEV(F:TFileName;scfactor:double;txhow:integer);
Procedure ImportAsc(F:TFileName);
Procedure SetDefaultHeader;
Procedure RenumSecs;
Procedure RenumThings;
Function getNewID:integer;
Function NewSector:TJKSector;
Function NewThing:TJKThing;
Function NewLight:TJedLight;
Function New3DONode:THNode;
Function GetThingByID(id:integer):Integer;
Function GetSectorByID(id:integer):Integer;
Function GetLightByID(id:integer):Integer;
Function GetNodeByID(id:integer):Integer;
{for resolving references}
Function GetSectorN(n:integer):TJKSector;
Function GetSurfaceN(n:integer):TJKSurface;
Function GetThingN(n:integer):TJKthing;
Function GetGlobalSFN(sc,sf:integer):Integer;
Function GetLayerName(n:integer):String;
Function AddLayer(const name:string):integer;
Procedure AddMissingLayers;
Function GetMasterCMP:string;
end;
Var
level:TJKLevel;
Function SFtoInt(sc,sf:integer):integer;
Function EDtoInt(sc,sf,ed:integer):integer;
Function VXToInt(sc,vx:integer):integer;
Function FRToInt(th,fr:integer):integer;
Function GetsfSC(scsf:integer):integer;
Function GetsfSF(scsf:integer):integer;
Function GetedSC(scsfed:integer):integer;
Function GetedSF(scsfed:integer):integer;
Function GetedED(scsfed:integer):integer;
Function GetvxSC(scvx:integer):integer;
Function GetvxVX(scvx:integer):integer;
Function GetfrTH(thfr:integer):integer;
Function GetfrFR(thfr:integer):integer;
implementation
uses ProgressDialog, lev_utils, u_templates, Cog_utils, ListRes, U_CogForm,
U_Options;
{Lights}
Constructor TJedLight.Create;
begin
Range:=2;
Intensity:=10;
R:=1; g:=1; b:=1;
RGBIntensity:=10;
end;
Procedure TJedLight.Assign(l:TJedLight);
begin
intensity:=l.intensity;
range:=l.range;
r:=l.r;
g:=l.g;
b:=l.g;
RGBIntensity:=l.RGBIntensity;
layer:=l.Layer;
end;
Function TJedLights.GetItem(n:integer):TJedLight;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Light Index is out of bounds: %d',[n]);
Result:=TJedLight(List[n]);
end;
Procedure TJedLights.SetItem(n:integer;v:TJedLight);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Light Index is out of bounds: %d',[n]);
List[n]:=v;
end;
{Vertices}
Procedure TJKVertex.Assign(v:TJKVertex);
begin
x:=v.x;
y:=v.y;
z:=v.z;
end;
Function TJKVertices.GetItem(n:integer):TJKVertex;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Vertex Index is out of bounds: %d',[n]);
Result:=TJKVertex(List[n]);
end;
Procedure TJKVertices.SetItem(n:integer;v:TJKVertex);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Vertex Index is out of bounds: %d',[n]);
List[n]:=v;
end;
Constructor TThing.Create;
begin
Vals:=TTPLValues.Create;
name:='walkplayer';
end;
Destructor TThing.Destroy;
var i:integer;
begin
For i:=0 to vals.Count-1 do vals[i].free;
vals.free;
end;
Function TThing.InsertValue(n:integer;const name,s:string):TTPlValue;
var v:TTplValue;
begin
v:=TTPLValue.Create;
v.Name:=name;
v.vtype:=GetTPLVType(v.name);
v.atype:=GetTPLType(v.name);
v.Val(s);
Vals.Insert(n,v);
result:=v;
end;
Function TThing.AddValue(const name,s:string):TTplValue;
begin
Result:=InsertValue(Vals.count,name,s);
end;
Function TThing.Nframes:Integer;
var i:integer;
begin
Result:=0;
for i:=0 to vals.count-1 do
if CompareText(Vals[i].name,'frame')=0 then Inc(Result);
end;
Function TThing.PrevFrame(n:integer):integer;
var v:TTplValue;
begin
result:=-1;
dec(n);
while n>=0 do
begin
if CompareText(vals[n].name,'frame')=0 then
begin
result:=n;
exit;
end;
dec(n);
end;
end;
Function TThing.NextFrame(n:integer):integer;
var v:TTplValue;
begin
result:=-1;
inc(n);
while n<Vals.count do
begin
if CompareText(vals[n].name,'frame')=0 then
begin
result:=n;
exit;
end;
inc(n);
end;
end;
Procedure TThing.Assign;
var i:Integer;
v:TTPLvalue;
begin
name:=thing.name;
X:=thing.X;
Y:=thing.Y;
Z:=thing.Z;
PCH:=thing.PCH;
YAW:=thing.YAW;
ROL:=thing.ROL;
for i:=0 to Thing.Vals.Count-1 do
begin
v:=TTplvalue.Create;
v.Assign(Thing.Vals[i]);
vals.Add(v);
end;
layer:=thing.layer;
end;
{TCog methods}
Constructor TCog.Create;
begin
Vals:=TCOGValues.Create;
end;
Destructor TCog.Destroy;
begin
Vals.Free;
end;
Procedure TCog.GetValues;
begin
end;
Function TCOGs.GetItem(n:integer):TCOG;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('COG Index is out of bounds: %d',[n]);
Result:=TCOG(List[n]);
end;
Procedure TCOGs.SetItem(n:integer;v:TCog);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('COG Index is out of bounds: %d',[n]);
List[n]:=v;
end;
Function TSectors.GetItem(n:integer):TJKSector;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Sector Index is out of bounds: %d',[n]);
Result:=TJKSector(List[n]);
end;
Procedure TSectors.SetItem(n:integer;v:TJKSector);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Sector Index is out of bounds: %d',[n]);
List[n]:=v;
end;
Function TThings.GetItem(n:integer):TThing;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Thing Index is out of bounds: %d',[n]);
Result:=TThing(List[n]);
end;
Procedure TThings.SetItem(n:integer;v:TThing);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Thing Index is out of bounds: %d',[n]);
List[n]:=v;
end;
Function TSurfaces.GetItem(n:integer):TJKSurface;
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Surface Index is out of bounds: %d',[n]);
Result:=TJKSurface(List[n]);
end;
Procedure TSurfaces.SetItem(n:integer;v:TJKSurface);
begin
if (n<0) or (n>=count) then raise EListError.CreateFmt('Surface Index is out of bounds: %d',[n]);
List[n]:=v;
end;
{TJKSurface Methods}
Constructor TJKSurface.Create;
begin
Inherited Create;
sector:=owner;
AdjoinFlags:=7;
Material:='dflt.mat';
SurfFlags:=4;
FaceFlags:=4;
geo:=4;
light:=3;
tex:=1;
uscale:=1;
vscale:=1;
end;
Procedure TJKSurface.CheckIfFloor;
var cosa:double;
begin
cosa:=Smult(normal.dx,normal.dy,normal.dz,0,0,1);
if (cosa<=1) and (cosa>cos(Pi/4)) then SurfFlags:=SurfFlags or SF_Floor
else SurfFlags:=SurfFlags and (-1 xor SF_Floor);
end;
Function TJKSurface.GetRefVector(var v:TVector):boolean;
var v1,v2:TJKVertex;
begin
result:=false;
if vertices.count<2 then exit;
v1:=vertices[0];
v2:=vertices[1];
SetVec(v,v2.x-v1.x,v2.y-v1.y,v2.z-v1.z);
Result:=Normalize(v);
end;
Function TJKSurface.GetVXs:TJKVertices;
begin
Result:=TJKVertices(Tpolygon(self).Vertices);
end;
Procedure TJKSurface.SetVXs(vxs:TJKVertices);
begin
Tpolygon(self).Vertices:=vxs;
end;
procedure TJKSurface.Assign(surf:TJKSurface);
begin
if surf.AdjoinFlags<>0 then AdjoinFlags:=surf.AdjoinFlags;
if surf.Material<>'' then Material:=surf.Material;
if surf.SurfFlags<>0 then SurfFlags:=surf.SurfFlags;
if surf.FaceFlags<>0 then FaceFlags:=surf.FaceFlags;
if surf.geo<>0 then geo:=surf.geo;
light:=surf.light;
tex:=surf.tex;
extraLight:=surf.extraLight;
uscale:=surf.uscale;
vscale:=surf.vscale;
end;
Procedure TJKSurface.NewRecalcAll;
begin
Recalc;
CalcUV(Self,0);
CheckIfFloor;
end;
Procedure TJKSurface.RecalcAll;
var un,vn:tvector;
begin
Recalc;
CalcUVNormals(self,un,vn);
ArrangeTexture(self,0,un,vn);
end;
{TJKSector Methods}
Constructor TJKSector.Create;
begin
Surfaces:=TSurfaces.Create;
vertices:=TJKVertices.Create;
Surfaces.VXList:=Vertices;
Level:=owner;
ColorMap:='dflt.cmp';
Ambient:=5;
end;
Destructor TJKSector.Destroy;
var i:integer;
begin
for i:=0 to Surfaces.count-1 do Surfaces[i].free;
surfaces.free;
for i:=0 to vertices.count-1 do vertices[i].free;
vertices.free;
end;
Function TJKSector.NewVertex:TJKVertex;
begin
Result:=TJKVertex.Create;
Result.Sector:=self;
result.num:=Vertices.Add(Result)-1;
end;
Function TJKSector.NewSurface:TJKSurface;
begin
Result:=TJKSurface.Create(self);
end;
Procedure TJKSector.Renumber;
var i:integer;
begin
for i:=0 to vertices.count-1 do vertices[i].num:=i;
for i:=0 to surfaces.count-1 do surfaces[i].num:=i;
end;
Function TJKSector.FindVX(x,y,z:double):integer;
var v:TJKvertex;
i:integer;
begin
Result:=-1;
for i:=0 to vertices.count-1 do
begin
v:=Vertices[i];
if IsClose(v.x,x) and IsClose(v.y,y) and IsClose(v.z,z) then
begin
Result:=i;
break;
end;
end;
end;
Function TJKSector.AddVertex(x,y,z:double):TJKVertex;
var i:integer;
begin
i:=FindVX(x,y,z);
if i<>-1 then Result:=Vertices[i]
else
begin
Result:=NewVertex;
Result.x:=x;
Result.y:=y;
Result.z:=z;
end;
end;
Procedure TJKSector.Assign;
begin
Flags:=sec.Flags;
Ambient:=sec.Ambient;
extra:=sec.extra;
ColorMap:=sec.ColorMap;
Tint:=sec.Tint;
Sound:=sec.Sound;
snd_vol:=sec.snd_vol;
layer:=sec.layer;
end;
{TJKLevel Methods}
Function TJKLevel.getNewID:integer;
begin
if self=nil then begin result:=0; exit; end;
Result:=CurID;
Inc(CurID);
end;
Function TJKLevel.GetThingByID(id:integer):Integer;
var i:integer;
begin
Result:=-1;
for i:=0 to Things.count-1 do
If Things[i].ID=id then
begin
Result:=i;
exit;
end;
end;
Function TJKLevel.GetSectorByID(id:integer):Integer;
var i:integer;
begin
Result:=-1;
for i:=0 to Sectors.count-1 do
If Sectors[i].ID=id then
begin
Result:=i;
exit;
end;
end;
Function TJKLevel.GetLightByID(id:integer):Integer;
var i:integer;
begin
Result:=-1;
for i:=0 to Lights.count-1 do
If Lights[i].ID=id then
begin
Result:=i;
exit;
end;
end;
Function TJKLevel.GetNodeByID(id:integer):Integer;
var i:integer;
begin
Result:=-1;
for i:=0 to h3donodes.count-1 do
If h3donodes[i].ID=id then
begin
Result:=i;
exit;
end;
end;
Function TJKLevel.NewSector:TJKSector;
begin
Result:=TJKSector.Create(self);
result.ID:=getNewID;
end;
Function TJKLevel.NewThing:TThing;
begin
Result:=TThing.Create{(self)};
Result.Level:=self;
result.ID:=getNewID;
end;
Function TJKLevel.NewLight:TJedLight;
begin
Result:=TJedLight.Create;
result.ID:=getNewID;
end;
Function TJKLevel.New3DONode:THnode;
begin
Result:=THNode.Create;
result.ID:=getNewID;
end;
Procedure TJKLevel.RenumSecs;
var i:integer;
begin
for i:=0 to Sectors.Count-1 do Sectors[i].num:=i;
end;
Procedure TJKLevel.RenumThings;
var i:integer;
begin
for i:=0 to Things.Count-1 do Things[i].num:=i;
end;
Function TJKLevel.GetLayerName(n:integer):String;
begin
if (n<0) or (n>=Layers.count) then Result:=Format('LAYER%d',[n])
else Result:=Layers[n];
end;
Function TJKLevel.AddLayer(const name:string):integer;
begin
Result:=Layers.IndexOf(name);
if Result=-1 then Result:=Layers.Add(name);
end;
Function TJKLevel.GetMasterCMP:string;
begin
Result:=MasterCMP;
if (Result='') and (sectors.count>0) then Result:=sectors[0].ColorMap;
if result='' then result:='dflt.cmp';
end;
Constructor TJKLevel.Create;
begin
Sectors:=TSectors.Create;
Things:=TThings.Create;
cogs:=TCOgs.Create;
Lights:=TJedLights.Create;
Layers:=TStringList.Create;
h3donodes:=THNodes.Create;
end;
Procedure TJKLevel.Clear;
var i,j,k:Integer;
begin
For i:=0 to sectors.count-1 do sectors[i].free;
sectors.clear;
For i:=0 to things.count-1 do things[i].free;
Things.clear;
For i:=0 to cogs.count-1 do cogs[i].free;
cogs.clear;
For i:=0 to lights.count-1 do lights[i].free;
for i:=0 to h3donodes.count-1 do h3donodes[i].Free;
h3donodes.Clear;
lights.clear;
Layers.Clear;
mots:=false;
MasterCmp:='';
LVisString:='';
ppunit:=320;
CurID:=0;
end;
Destructor TJKLevel.Destroy;
begin
Clear;
Sectors.Free;
Things.free;
Lights.Free;
Layers.Free;
end;
Procedure TJKLevel.SetDefaultHeader;
begin
With Header do
begin
version:=1;
Gravity:=4;
CeilingSkyZ:=15;
HorDistance:=100;
HorPixelsPerRev:=768;
HorSkyOffs[1]:=0; HorSkyOffs[2]:=0;
CeilingSkyOffs[1]:=0; CeilingSkyOffs[2]:=0;
MipMapDist[1]:=1; MipMapDist[2]:=2; MipMapDist[3]:=3; MipMapDist[4]:=4;
LODDist[1]:=0.3; LODDist[2]:=0.6; LODDist[3]:=0.9; LODDist[4]:=1.2;
PerspDist:=2;
GouraudDist:=2;
end;
end;
Procedure TJKLevel.AddMissingLayers;
var i:integer;
begin
for i:=0 to sectors.count-1 do
With sectors[i] do
begin
if (layer<0) or (layer>=layers.count) then
layer:=AddLayer(Format('Layer%d',[layer]));
end;
for i:=0 to things.count-1 do
With things[i] do
begin
if (layer<0) or (layer>=layers.count) then
layer:=AddLayer(Format('Layer%d',[layer]));
end;
for i:=0 to Lights.count-1 do
With Lights[i] do
begin
if (layer<0) or (layer>=layers.count) then
layer:=AddLayer(Format('Layer%d',[layer]));
end;
end;
Function TJKLevel.GetSectorN(n:integer):TJKSector;
begin
if n<0 then begin Result:=nil; exit; end;
Try
Result:=Sectors[n];
except
On Exception do result:=nil;
end;
end;
Function TJKLevel.GetSurfaceN(n:integer):TJKSurface;
var s,nsf:integer;
begin
nsf:=0;
if n<0 then begin Result:=nil; exit; end;
for s:=0 to Sectors.count-1 do
With Sectors[s] do
begin
if (n>=nsf) and (n<nsf+Surfaces.count) then
begin
Result:=Surfaces[n-nsf];
exit;
end;
inc(nsf,Surfaces.count);
end;
Result:=nil;
end;
Function TJKLevel.GetThingN(n:integer):TJKthing;
begin
if n<0 then begin Result:=nil; exit; end;
Try
Result:=Things[n];
except
On Exception do begin result:=nil; end;
end;
end;
Function TJKLevel.GetGlobalSFN(sc,sf:integer):Integer;
var i,nsf:integer;
begin
if sc=-1 then begin Result:=-1; exit; end;
nsf:=0;
For i:=0 to sc-1 do
With Sectors[i] do
begin
inc(nsf,Surfaces.Count);
end;
Result:=nsf+sf;
end;
Function SFtoInt(sc,sf:integer):integer;
begin
result:=sc shl 16+sf;
end;
Function EDtoInt(sc,sf,ed:integer):integer;
begin
result:=sc shl 18+sf shl 8+ed;
end;
Function VXToInt(sc,vx:integer):integer;
begin
result:=sc shl 16+vx;
end;
Function FRToInt(th,fr:integer):integer;
begin
result:=th shl 16+fr;
end;
Function GetsfSC(scsf:integer):integer;
begin
result:=scsf shr 16;
end;
Function GetsfSF(scsf:integer):integer;
begin
result:=scsf and $FFFF;
end;
Function GetedSC(scsfed:integer):integer;
begin
result:=scsfed shr 18;
end;
Function GetedSF(scsfed:integer):integer;
begin
result:=(scsfed shr 8) and $3FF;
end;
Function GetedED(scsfed:integer):integer;
begin
result:=scsfed and $FF;
end;
Function GetvxSC(scvx:integer):integer;
begin
result:=scvx shr 16;
end;
Function GetvxVX(scvx:integer):integer;
begin
result:=scvx and $FFFF;
end;
Function GetfrTH(thfr:integer):integer;
begin
result:=thfr shr 16;
end;
Function GetfrFR(thfr:integer):integer;
begin
result:=thfr and $FFFF;
end;
{$i level_io.inc}
{$i DF_import.inc}
{$i Savejkl.inc}
{$i asc_import.inc}
Initialization
begin
level:=TJKLevel.Create;
end;
Finalization
begin
Level.Clear;
level.Free;
end;
end.
|
unit pacifistTree;
interface
uses types, core, Crt, sysutils, TerminalUserInput;
///
/// This is the pacifist tree
///
/// Here is how the naming procedure works, for example pThreeTen (p3-4)
/// means that this is the pacifist tree, layer 3 (after 3 decisions)
/// and the fourth possible outcome in this 3rd layer
///
/// If i have the time i'll write up a nice interface for each one
/// but it is rather self explanitory if you have the design map.
procedure pTree(var character:player);
implementation
procedure pFiveOne(var character:player);
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('You inspect the small window');
writeln('I reckon you''ll fit, give it a go');
writeln('You do.');
next();
if chance(60) then
begin
writeln('Halfway through the window you get stuck');
writeln('You knew you shouldn''t have eaten 2 turkey legs for lunch');
next();
writeln('You hear footsteps');
writeln('A fair looking lady with a basket sees your head sticking out of this building');
writeln('She says "Are you a little stuck?"');
writeln('Finally in this saga of bad luck there''s hope');
writeln('"Yess can you pull me out", you reply.');
writeln('"Of course!", she says as she puts the basket down');
next();
writeln('Out of the basket she pulls a knife');
writeln('She stabs you, you die.');
character.dead := true;
next();
end
else
begin
writeln('You manage to squeeze through!!');
writeln('It''s a borderline miracle that you survived that place');
writeln('You run off into the sunset');
writeln('*******************************************');
next();
end;
end;
end;
procedure pFiveTwo(var character:player);
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('You have a cheeky squizz around the room, theres a window and a door');
writeln('Under the blood stained rug that I totally didnt mention before,');
writeln('There is a cool key');
writeln('Maybe you should try it on the door');
next();
writeln('You do');
if chance(90) then
begin
writeln('The door won''t budge, the window it''ll have to be');
writeln('You head over to the window');
next();
pFiveOne(character);
end
else
begin
writeln('The door opens');
writeln('That was easy I guess that means you escaped');
next();
writeln('Yeah i reckon we leave the game here');
writeln('*******************************************');
next();
end;
end;
end;
procedure pFiveThree(var character:player);
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('The hallway becomes a downward slope, strange');
writeln('You reach an open door, showing you a bloody-floored-room, gross');
next();
pFiveTwo(character);
end;
end;
procedure pFourOne(var character:player);
var drink: integer;
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
if chance(80) then
begin
writeln('As your back is turned, Mr Hook Man runs after you and hooks you');
writeln('Should have killed him when you had the chance.......');
writeln('You die.');
character.dead := true;
next();
end
else
begin
writeln('You come to the end of the hallway where a water well appears');
writeln('I mean, you''re kinda thirsty from avoiding fights all the time');
writeln('Do you want to drink from the well?');
drink := 0;
while ((drink < 1) or (drink > 2)) do
begin
drink := readinteger('1 for drink, 2 for no drink: ');
end;
if drink = 1 then
begin
if chance(95) then
begin
writeln('It was poison that looked like water sorry');
writeln('You die.');
character.dead := true;
next();
end
else
begin
writeln('Mm tasty, moving on...');
next();
pFiveThree(character);
end;
end
else
begin
writeln('Live a little....gosh');
next();
if chance(40) then
begin
writeln('Talking of not living, you die.');
character.dead := true;
next();
end
else
begin
pFiveThree(character);
end;
end;
end;
end;
end;
procedure pFourTwo(var character:player);
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('You open the door to a HUUUGE staircase going down');
if chance(40) then
begin
writeln('You fall down them');
writeln('You die');
character.dead := true;
next();
end
else
begin
writeln('Down the stairs you go');
next();
writeln('You eventually reach the bottom of what appears to be an abyss');
writeln('There is a kind of blood all over the floor, cool');
next();
writeln('There appears to be a little circular window on the far side of the room');
writeln('You head over to it');
Next();
Writeln('Now that you think about it, you could probably fit through it');
writeln('Looks like there is some sun out there');
next();
twoChoice('Do you want to squeeze through or have a look around?', @pFiveOne, @pFiveTwo, character);
end;
next();
end;
end;
procedure pFourThree(var character:player);
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('');
writeln('You jump');
next();
if chance(5) then
begin
writeln('By some ridiculous miracle you survive.');
writeln('You look down to see your legs turned to a fine red mist');
if ((character.first = 3) or (character.second = 3)) then
begin
writeln('You have a potion don''t forget');
writeln('You use it because you know, the leg situation');
next();
writeln('Wow!! Like magic you''re back to normal, legs and all');
next();
writeln('There appears to be a little circular window on the far side of the room');
writeln('You head over to it');
Next();
Writeln('Now that you think about it, you could probably fit through it');
writeln('Looks like there is some sun out there');
twoChoice('Squeeze through or look around?', @pFiveOne, @pFiveTwo, character);
end
else
begin
writeln('Sucks to be you, guess you die sorry');
character.dead := true;
next();
end;
end
else
begin
writeln('I really don''t know what in the fuck you expected...');
writeln('You die.');
character.dead := true;
next();
end;
end;
end;
procedure pThreeOne(var character:player);
begin
ClrScr;
writeln('You''re not exactly the most combat trained...');
writeln('The hook slices through your neck');
writeln('You die.');
character.dead := true;
next();
end;
procedure pThreeTwo(var character:player);
var mercy: integer;
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('You dodge the swing by some voodoo magic');
writeln('He hits the wall behind you and drops his hook');
next();
writeln('"It was just a prank I promise", the poor guy stutters,');
writeln('He is sprawled on the floor');
writeln('Here is your time to take revenge and kill a defenseless man');
mercy := 0;
while ((mercy < 1) or (mercy > 2)) do
begin
mercy := readinteger('1 for kill, 2 for show mercy: ');
end;
if mercy = 1 then
begin
writeln('You monster... How could you');
writeln('Instead of KILLING THE DEFENCELESS HUMAN, you give him a hand up');
next();
if chance(80) then
begin
writeln('He grabs your hand and pulls himself off the ground');
writeln('He picks up his meat hook and holds it out in a grateful gesture');
next();
writeln('Before stabbing you. You die');
character.dead := true;
next();
end
else
begin
writeln('He pulls himself up and thanks you');
Writeln('He goes in the opposite direction never to be seen again');
next();
pFourOne(character);
end;
end
else
begin
writeln('It''s good of you to show mercy');
writeln('You offer him a a hand up, which he takes gratefully');
writeln('"Thank you sir", he says');
writeln('He picks up his hook and heads in the opposite direction');
writeln('Never to be seen again');
next();
pFourOne(character);
end;
end;
end;
procedure pThreeThree(var character:player);
var guess : integer;
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('You''re met by an old guy sitting on a box blocking the next doorway');
writeln('"Hey pal what you doing here?", you ask.');
writeln('"Just protecting this door from people like you", he replies.');
writeln('"Oh okay", you say, defeated.');
writeln('"Don''t sound defeated young one", he says back to you');
writeln('"Oh but I am", you say as if your dialog is being written at 3:13am');
writeln('"You just have to guess my number from 1 to 5 to pass" he says');
writeln('"Oh that''s not too bad", you say back');
next();
writeln('You heard the man, guess...');
guess := 0;
while ((guess < 1) or (guess > 5)) do
begin
guess := readinteger('What will your guess be? [1-5]: ');
end;
randomize();
if guess <> random(5) then
begin
writeln('"',guess, '?? hmm" he says');
writeln('"why what is it?" you ask');
writeln('"Hmm nothing" he says as he stands up and draws a sword');
next();
if ((character.first = 2) or (character.second = 2)) then
begin
if chance(50) then
begin
writeln('He swings at you');
writeln('You run like a coward');
writeln('The old man stumbles and falls');
writeln('"Ah screw it", he says, just go through');
writeln('You do');
next();
pFourTwo(character);
end
else
begin
writeln('He swings at you');
writeln('You go to deflect it with your shield');
writeln('he breaks through your shield');
writeln('The old man still has some strength in him');
writeln('You die');
character.dead := true;
next();
end;
end
else
begin
if chance(20) then
begin
writeln('He swings at you');
writeln('He missed because he''s clearly very old and immobile');
writeln('The old man stumbles and falls');
writeln('"Ah screw it", he says, just go through');
writeln('You do');
next();
pFourTwo(character);
end
else
begin
writeln('He swings at you');
writeln('You go to deflect it with your arm because you''re so combat trained');
writeln('bad idea');
writeln('The old man somehow has the strength to cut through your arm');
writeln('As you fall over crying like a little bitch he stabby stabs you to death');
writeln('You die');
character.dead := true;
next();
end;
end;
end
else
begin
writeln('Wow... good guess');
writeln('The man lets you through');
next();
pFourTwo(character);
end;
end;
end;
procedure pThreeThreeInter(var character:player);
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('You go back to the main room to be only to be faced with one other door');
writeln('The ''West'' door appears to be missing');
writeln('East you go!!');
next();
pThreeThree(character);
end;
end;
procedure pThreeFour(var character:player);
begin
ClrScr;
writeln('If you read the dumb scroll and ended up here,');
writeln('Yeah you wasted you time, You die.');
character.dead := true;
next();
end;
procedure pThreeFive(var character:player);
begin
if killPlayer(character) then
exit
else
begin
ClrScr;
writeln('You go through the door and are faced with what looks like a huge abyss');
writeln('You''re getting light headed just looking down');
writeln('You have the choice of having a little jump or going back');
writeln('Look, jumping is a dumb idea, or am I just tricking you????');
twoChoice('Jump or go back?', @pFourThree, @pThreeThreeInter, character);
end;
end;
procedure pTwoOne(var character:player);
begin
ClrScr;
if killPlayer(character) then
exit
else
begin
writeln('You walk left down the hallway');
next();
writeln('Good one dickhead, you ran into another bad guy,');
writeln('this one has a big meat hook though, watch out.');
writeln('');
writeln('You REALLY don''t want to fight him');
if ((character.first = 1) or (character.second = 1)) then
begin
writeln('Lucky you bought your dagger, stabby stab stab and all..');
next();
if chance(90) then
begin
writeln('But unlucky you chose Pacifist and doesn''nt know how to use one');
writeln('While you''re staring blankly at your dagger, Mr Hook Dude kills you');
character.dead := true;
next();
end
else
pThreeTwo(character);
end
else
begin
next();
writeln('"Oi, come here ma hook", he says');
writeln('"no I''d really rather not thank you", you reply');
writeln('He seems to ignore that kind hearted statement and swings at you');
next();
if ((character.first = 2) or (character.second = 2)) then
begin
if chance(50) then
pThreeTwo(character) //survive
else
pThreeOne(character);
end
else
begin
if chance(30) then
pThreeTwo(character) // survive
else
pThreeOne(character);
end;
end;
end;
end;
procedure pTwoTwo(var character:player);
begin
ClrScr;
if killPlayer(character) then
exit
else
begin
writeln('You walk right down the hallway');
next();
writeln('You eventually reach a slightly ajar door');
writeln('You peer into the dimly lit room to see a locked chest');
if ((character.first = 0) or (character.second = 0)) then
begin
writeln('Wow good job on choosing the lockpick');
writeln('It''s your time to shine');
writeln('You do your little fiddly stuff and wow!');
next();
if chance(60) then
begin
writeln('The chest opens containing a shitty little scroll');
writeln('It says:');
emptyWrite(2);
writeln('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
writeln(' Great treasure lies within these');
writeln(' Ornate walls, which, ');
writeln(' We, the founders of these catacombs');
writeln(' Envisage the success of the future of mankind, a');
writeln(' Superior and elite version of our current selves.');
writeln(' Thrive, our children. Thrive.');
writeln('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~');
next();
writeln('Maybe it was code for something..');
writeln('Maybe you pressed continue too early :/');
writeln('Nevertheless...');
next();
end
else
begin
writeln('It didn''t work RIPPP');
next();
end;
end
else
begin
writeln('You have a quick look at the lock');
writeln('Seems unbreakable without a lockpick (THATS A HINT)');
writeln('You wonder if there is something useful inside the locked chest');
next();
end;
writeln('You look up and turn around to find that the door has disappeared?????');
writeln('what is this wizardry?');
next();
writeln('You turn back towards the chest to see the three walls in front of you, each with a door');
writeln('One East, West, and North. (Signs above the doorways say so..)');
threeChoice('Where will you go? East? West? North?', @pThreeThree, @pThreeFour, @pThreeFive, character);
end;
end;
procedure pTree(var character:player);
begin
writeln('"Why yes, I am" You reply,');
writeln('"Okay cool" he says, and leaves');
writeln('Luckily for you, as he turned away, he hit his head on a beam.');
writeln('He suffers.');
next();
Writeln('You want to go and help but the door is locked...');
writeln('"Hey can I help?", you say');
writeln('He opens the door with a grunt as if to signify he wants you to help him');
next();
writeln('You help him up, "Thank you" he says,');
next();
if chance(70) then
begin
writeln('As he gets up he stabs you, sorry');
writeln('You die');
character.dead := true;
end
else
begin
writeln('He dusts himself off and looks you in the eye');
writeln('"You''re too kind to be here, get youtself out kiddo" he says,');
writeln('You do..');
writeln('You are faced with a hallway going left or right');
twoChoice('Do you go left, or right?', @pTwoOne, @pTwoTwo, character);
end;
end;
end.
|
unit Unit_cn_fr_paymentAnalysis;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FIBDatabase, pFIBDatabase, cxLookAndFeelPainters, StdCtrls,
cxButtons, cxRadioGroup, iBase, cn_common_types, cxControls, cxContainer,
cxEdit, cn_Common_Loader, PackageLoad, ZTypes, DB, FIBDataSet,
pFIBDataSet, cxTextEdit, cxMaskEdit, cxDropDownEdit, Registry, cn_Common_Funcs,
cxLabel;
type
Tform_cn_fr_paymentAnalysis = class(TForm)
cxButtonOk: TcxButton;
cxButtonCancel: TcxButton;
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
DataSet: TpFIBDataSet;
Print_dogs_list: TcxComboBox;
cxLabel1: TcxLabel;
procedure cxButtonCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cxButtonOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
InParameter : TcnSimpleParamsEx;
IndexReg, Length_list : Integer;
PLanguageIndex : Byte;
Array_list : array of array [1..4] of string;
constructor Create(AParameter:TcnSimpleParamsEx);reintroduce;
end;
function frChooseReport(AParameter:TcnSimpleParamsEx):Variant;stdcall;
exports frChooseReport;
var
form_cn_fr_paymentAnalysis: Tform_cn_fr_paymentAnalysis;
implementation
{$R *.dfm}
function frChooseReport(AParameter:TcnSimpleParamsEx):Variant;stdcall;
var
t:Tform_cn_fr_paymentAnalysis;
begin
t:=Tform_cn_fr_paymentAnalysis.Create(AParameter);
t.ShowModal;
t.Free;
end;
constructor Tform_cn_fr_paymentAnalysis.Create(AParameter:TcnSimpleParamsEx);
begin
inherited Create(AParameter.Owner);
InParameter:=TcnSimpleParamsEx.Create;
InParameter:=AParameter;
PLanguageIndex := cnLanguageIndex();
end;
procedure Tform_cn_fr_paymentAnalysis.cxButtonCancelClick(Sender: TObject);
begin
close;
end;
procedure Tform_cn_fr_paymentAnalysis.FormCreate(Sender: TObject);
begin
Caption:='Друк';
cxButtonOk.Caption:='Прийняти';
cxButtonCancel.Caption:='Відмінити';
cxLabel1.Caption := 'Шаблон документу';
end;
procedure Tform_cn_fr_paymentAnalysis.cxButtonOkClick(Sender: TObject);
Var
id_man : Int64;
Reg : TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\Contracts\Print_Dogs_list\', True)
then reg.WriteString('index', IntToStr(Print_dogs_list.ItemIndex));
finally
reg.Free;
end;
if Array_list[Print_dogs_list.ItemIndex,4] <> 'PrintSprDoh' then
begin
RunFunctionFromPackage(InParameter, 'Contracts\' + Array_list[Print_dogs_list.ItemIndex,3], Array_list[Print_dogs_list.ItemIndex,4]);
end;
if Array_list[Print_dogs_list.ItemIndex,4] = 'PrintSprDoh' then
begin
//DB.Handle := InParameter.Db_Handle;
//DB.Connected := True;
//DataSet.Transaction.StartTransaction;
DataSet.Close;
DataSet.SQLs.SelectSQL.Text := 'select id_man from cn_dt_stud where id_stud = :id_stud';
DataSet.ParamByName('id_stud').AsInt64 := InParameter.cnParamsToPakage.ID_STUD;
DataSet.Open;
if DataSet['id_man'] <> null
then id_man := DataSet['id_man']
else id_man := -1;
//DataSet.Close;
//DataSet.Transaction.Rollback;
//DB.Connected := False;
PrintSprSubs(InParameter.Owner,InParameter.Db_Handle, tsOther, id_man);
//PrintSprSubs(InParameter.Owner, InParameter.Db_Handle, tsOther, Id_man);
//PrintSprDoh(InParameter.Owner, InParameter.Db_Handle, tsOther, Id_man);
End;
end;
procedure Tform_cn_fr_paymentAnalysis.FormShow(Sender: TObject);
var
reg : TRegistry;
i : Integer;
begin
DB.Handle := InParameter.Db_Handle;
DB.Connected := True;
DataSet.Transaction.StartTransaction;
DataSet.Close;
DataSet.SQLs.SelectSQL.Text := 'Select * from CN_INI_PRINT_DOG_LIST';
DataSet.Open;
DataSet.FetchAll;
Length_list := DataSet.RecordCount;
SetLength(Array_list,Length_list);
DataSet.First;
i := 0;
while not dataset.Eof do
Begin
if DataSet['NAME_UKR'] <> null
then Array_list[i,1] := DataSet['NAME_UKR']
else Array_list[i,1] := 'Невизначенно';
if DataSet['NAME_RUS'] <> null
then Array_list[i,2] := DataSet['NAME_RUS']
else Array_list[i,2] := 'Неопределенно';
if DataSet['NAME_MODULE'] <> null
then Array_list[i,3] := DataSet['NAME_MODULE']
else Array_list[i,3] := '';
if DataSet['NAME_FUNCTION'] <> null
then Array_list[i,4] := DataSet['NAME_FUNCTION']
else Array_list[i,4] := '';
i := i + 1;
DataSet.Next;
end;
Print_dogs_list.Properties.Items.Clear;
for i:=0 to Length_list-1 do Print_dogs_list.Properties.Items.Add(array_list[i, PLanguageIndex]);
IndexReg := 0;
reg := TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\Contracts\Print_Dogs_list\',False)
then indexReg := StrToInt(reg.ReadString('index'));
finally
reg.Free;
end;
if indexReg > Length_list
then Print_dogs_list.ItemIndex := 0
else Print_dogs_list.ItemIndex := IndexReg;
end;
procedure Tform_cn_fr_paymentAnalysis.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
If FormStyle = fsMDIChild
then action:=caFree
else
begin
DataSet.Close;
ReadTransaction.Rollback;
DB.Connected := False;
End;
end;
end.
|
{$i deltics.io.shellapi.inc}
unit Deltics.IO.ShellApi;
interface
type
ShellApi = class
public
class procedure CopyFile(const aFilename: String; const aDestPath: String);
end;
implementation
uses
ShellApi,
SysUtils,
Deltics.IO.Path;
class procedure ShellApi.CopyFile(const aFilename: String; const aDestPath: String);
var
fileOp: TSHFileOpStruct;
srcFile: String;
srcFileDnt: String;
destFile: String;
destFileDnt: String;
copyResult: Integer;
begin
srcFile := aFilename;
destFile := Path.Append(aDestPath, ExtractFilename(aFilename));
// Shell Api operation filenames must be DOUBLE null-terminated!
srcFileDnt := srcFile + #0;
destFileDnt := destFile + #0;
fileOp.Wnd := 0;
fileOp.wFunc := FO_COPY;
fileOp.pFrom := PChar(srcFileDnt);
fileOp.pTo := PChar(destFileDnt);
fileOp.fFlags := FOF_SILENT;
fileOp.lpszProgressTitle := NIL;
copyResult := ShFileOperation(fileOp);
if copyResult <> 0 then
raise EInOutError.Create(SysErrorMessage(copyResult));
end;
end.
|
unit uI2XOCR;
interface
uses
Windows,
Classes,
uStrUtil,
Graphics,
SysUtils,
OmniXML,
uOmniXML,
uDWImage,
uI2XConstants,
uI2XPlugin,
Contnrs,
JclStrings,
MapStream,
uHashTable,
Typinfo;
const
UNIT_NAME = 'uI2XOCR';
type
TCountArray = array[0..100000000] of Integer;
PCountArray = ^TCountArray;
TOCRItemDataType = ( odtNoneSpecified = 0, odtString, odtNumeric, odtDateTime );
TIndexValueItem = record
idx : Integer;
val: string;
obj: TObject;
end;
TIndexValueArray = array of TIndexValueItem;
TI2XOCRItem = class(TObject)
private
protected
FX : integer;
FY : integer;
FWidth : integer;
FHeight : integer;
FAccuracy : single;
FData : string;
FDataType : TOCRItemDataType;
FPtr : Pointer;
FObj : TObject;
function getX() : integer; virtual;
function getY() : integer; virtual;
function getWidth() : integer; virtual;
function getHeight() : integer; virtual;
function getAccuracy() : single; virtual;
function getData() : string; virtual;
function getDataEnc: string; virtual;
procedure setDataEnc(const Value: string); virtual;
function getDataType: TOCRItemDataType; virtual;
procedure setDataType(const Value: TOCRItemDataType); virtual;
function getAsRect: TRect;
function getBottom: integer;
function getRight: integer;
published
property X : integer read getX Write FX;
property Y : integer read getY Write FY;
property Width : integer read getWidth Write FWidth;
property Height : integer read getHeight Write FHeight;
property Right : integer read getRight;
property Bottom : integer read getBottom;
property Accuracy : single read getAccuracy Write FAccuracy;
property Data : string read getData Write FData;
property DataEnc : string read getDataEnc Write setDataEnc;
property DataType : TOCRItemDataType read getDataType Write setDataType;
property AsRect : TRect read getAsRect;
public
property Ptr : Pointer read FPtr Write FPtr;
property Obj : TObject read FObj Write FObj;
procedure Clear;
function AsXML() : string; virtual;
function FromXML( const XMLString : string ) : boolean;
constructor Create(); virtual;
destructor Destroy; override;
procedure Assign( Source : TI2XOCRItem ); dynamic;
procedure AssignTo( Target : TI2XOCRItem ); dynamic;
end;
TI2XOCRResult = class(TI2XOCRItem)
private
FID: string;
//FItemList : THashTable;
FItemList : TObjectList;
procedure SetID(const Value: string);
function GetItem(Index: Integer): TI2XOCRItem;
procedure SetItem(Index: Integer; const Value: TI2XOCRItem);
function GetCount(): Cardinal;
function IndexListSortedByY() : TIndexValueArray;
published
function Add( const ItemToAdd : TI2XOCRItem ) : integer;
procedure Delete(ItemToDelete : Integer );
property ID : string read FID write SetID;
property Count : Cardinal read GetCount;
procedure Clear;
public
function SortByY: boolean;
property Items[Index: Integer]: TI2XOCRItem read GetItem write SetItem; default;
function AsXML() : string; override;
constructor Create; override;
destructor Destroy; override;
procedure Assign( Source : TI2XOCRItem ); override;
procedure AssignTo( Target : TI2XOCRItem ); override;
end;
TI2XOCRResults = class(TObject)
private
FImageID : string;
//FResultsList : THashTable;
FResultsList : TObjectList;
function GetItem(Index: Integer): TI2XOCRResult;
procedure SetItem(Index: Integer; const Value: TI2XOCRResult);
function GetCount(): Cardinal;
function XMLToResultsObject( const XMLStringData : string; OCRResultsObject : TI2XOCRResults ) : boolean;
function IndexListSortedByX() : TIndexValueArray;
function GetBoundary: TRect;
function GetFirstCharacter: TI2XOCRItem;
published
function Add( const ItemToAdd : TI2XOCRResult ) : integer;
procedure Delete( ItemToDelete : Integer );
procedure Clear;
property ImageID : string read FImageID write FImageID;
property Count : Cardinal read GetCount;
public
function SortByX() : boolean;
property Items[Index: Integer]: TI2XOCRResult read GetItem write SetItem; default;
property Boundary : TRect read GetBoundary;
property FirstCharacter : TI2XOCRItem read GetFirstCharacter;
function AsXML( const RootNodeName : string = 'ocr') : string;
function SaveToFile( fileName : TFileName ) : boolean;
function LoadFromFile( fileName : TFileName ) : boolean;
function LoadXML( XMLString : string ) : boolean;
constructor Create; dynamic;
destructor Destroy; override;
end;
{*
TI2XOCRResultsMM = class(TI2XOCRResults)
private
FMemoryMap : TMapStream;
function getIsMemoryMapped: boolean;
public
property IsMemoryMapped : boolean read getIsMemoryMapped;
function SaveToMemoryMap( var sMapName : string ) : boolean;
function LoadFromMemoryMap( const sMapName: string; const InitSize : Cardinal = OCR_MEMMAP_INIT_SIZE ): boolean;
function ClearMemoryMap() : boolean;
constructor Create(); override;
destructor Destroy; override;
end;
*}
TI2XOCR = class(TI2XPlugin)
private
function GetOCRData(): string;
protected
FImage : TDWImage;
FOCRData : TI2XOCRResults;
public
property OCRData : string read GetOCRData;
function OCRImage( const MemoryMapName, ImageList : string ) : boolean; virtual; abstract;
function OCRImageDLL( MemoryMapName, ImageList : PChar;
LoadImageFromMemoryMap : boolean = true ) : boolean; virtual;
constructor Create( const GUID, ParmFileName : string ); override;
destructor Destroy; override;
end;
TDWPersist = class(TObject)
private
protected
FParent : TDWPersist;
FEnabled : boolean;
public
property Parent : TDWPersist read FParent write FParent;
function AsXML() : string; dynamic; abstract;
procedure Clear(); dynamic; abstract;
function LoadFromXML( xmlString : string ) : boolean; dynamic; abstract;
procedure CopyTo( TargetObject : TDWPersist ); dynamic; abstract;
procedure CopyFrom( SourceObject : TDWPersist ); dynamic; abstract;
property Enabled : boolean read FEnabled write FEnabled;
end;
pTDLLOCRTest = ^TDLLOCRTest;
TDLLOCRTest = class(TDWPersist)
private
FTest : TOCRTest;
function GetName: string;
procedure SetName(const Value: string);
function GetDescr: string;
published
property Test : TOCRTest read FTest write FTest;
property Name : string read GetName write SetName;
property Description : string read GetDescr;
public
procedure Clear(); override;
function AsXML() : string; override;
function LoadFromXML( xmlString : string ) : boolean; override;
procedure CopyTo( TargetObject : TDWPersist ); override;
procedure CopyFrom( SourceObject : TDWPersist ); override;
function Invert : boolean;
function Slice : boolean;
function IsWholePageTest : boolean;
constructor Create(); overload;
constructor Create( TestToDefaultTo : TOCRTest ); overload;
constructor Create( TestToDefaultTo : TOCRTest; const Enabled : boolean ); overload;
constructor Create( TestToDefaultTo : string; const Enabled : boolean ); overload;
end;
TDLLOCRTestEntry = class(TDWPersist)
private
FName : string;
FDescr : string;
FItems : THashTable;
procedure PutItem(idx: TIndex; const Value: TDLLOCRTest);
function GetItem(idx: TIndex) : TDLLOCRTest ;
function GetCount() : integer;
function CheckTest(testToCheck: TOCRTest): boolean;
function GetIndexByWholeTests: TIndexValueArray;
public
procedure Clear( const DeepClear : boolean = false ); overload;
procedure SetOCRTest(testToCheck: TOCRTest; const Value: boolean); overload;
procedure SetOCRTest(testToCheck: string; const Value: boolean); overload;
function AsXML() : string;
function LoadFromXML( xmlString : string ) : boolean;
procedure CopyTo( TargetObject : TDWPersist ); override;
procedure CopyFrom( SourceObject : TDWPersist ); override;
property Name : string read FName write FName;
property Descr : string read FDescr write FDescr;
property Enabled : boolean read FEnabled write FEnabled;
property Items[ idx : TIndex ]: TDLLOCRTest read GetItem write PutItem; default;
property IsActive[ testToCheck : TOCRTest ]: boolean read CheckTest write setOCRTest;
property IndexByWholeTests : TIndexValueArray read GetIndexByWholeTests;
procedure Add( itemToAdd : TDLLOCRTest ); overload;
function Exists( const DLLNameToCheck : string ) : boolean;
property Count : integer read GetCount;
constructor Create(); overload;
constructor Create( const Name : string ); overload;
constructor Create( const Name : string;
DoNormalWholeTest : boolean;
DoNormalSliceTest : boolean;
DoInvertWholeTest : boolean;
DoInvertSliceTest : boolean
); overload;
destructor Destroy(); override;
end;
TDLLOCRTests = class(TDWPersist)
private
FItems : THashTable;
FName : string;
procedure PutItem(idx: TIndex; const Value: TDLLOCRTestEntry);
function GetItem(idx: TIndex) : TDLLOCRTestEntry ;
function GetCount() : integer;
function GetTestCount: integer;
public
property Name : string read FName write FName;
procedure Clear(); override;
function AsXML() : string; override;
function LoadFromXML( xmlString : string ) : boolean; override;
procedure CopyTo( TargetObject : TDWPersist ); override;
procedure CopyFrom( SourceObject : TDWPersist ); override;
procedure Add( itemToAdd : TDLLOCRTestEntry ); overload;
procedure Add( DLLNameToAdd : string;
DoNormalWholeTest : boolean = true;
DoNormalSliceTest : boolean = true;
DoInvertWholeTest : boolean = true;
DoInvertSliceTest : boolean = true
); overload;
function Exists( const DLLNameToCheck : string ) : boolean;
property Items[ idx : TIndex ]: TDLLOCRTestEntry read GetItem write PutItem; default;
property Count : integer read GetCount;
property TestCount : integer read GetTestCount;
constructor Create(); overload;
constructor Create( const Name : string ); overload;
destructor Destroy(); override;
end;
// procedure CountSortIndexValueArray( var List : TIndexValueArray;
// minValue, maxValue : integer ); overload;
// procedure CountSortIndexValueArray( var List, SortedList : TIndexValueArray;
// min, max : integer; minValue, maxValue : integer ); overload;
procedure QuickSortIndexValueArray(var List : TIndexValueArray;
min, max : integer); overload;
procedure QuickSortIndexValueArray(var List : TIndexValueArray ); overload;
implementation
{*
procedure CountSortIndexValueArray( var List : TIndexValueArray;
minValue, maxValue : integer ); overload;
var
SortedList : TIndexValueArray;
Begin
SetLength( SortedList, Length( List ) );
CountSortIndexValueArray( List, SortedList, 0, Length ( List ), minValue, maxValue );
List := SortedList;
End;
procedure CountSortIndexValueArray( var List, SortedList : TIndexValueArray;
min, max : integer; minValue, maxValue : integer );
var
i, j, next_index : integer;
count_index : integer;
//count_index : TIndexValueItem;
counts : PCountArray;
begin
SetLength( SortedList, Length( List ) );
// Create the Counts array.
GetMem(counts, (maxValue - minValue + 1) * SizeOf(integer));
// Initialize the counts to zero.
for i := 0 to maxValue - minValue do
counts[i] := 0;
// Count the items.
for i := min to max do
begin
count_index := List[i].val - minValue;
counts[count_index] := counts[count_index] + 1;
end;
// Place the items in the sorted array.
next_index := min;
for i := minValue to maxValue do
begin
for j := 1 to counts[i - minValue] do
begin
//SortedList[next_index] := i;
SortedList[next_index] := List[i];
next_index := next_index + 1;
end;
end;
// Free the memory allocated for the counts array.
FreeMem(counts);
end;
*}
procedure QuickSortIndexValueArray(var List : TIndexValueArray ); overload;
Begin
QuickSortIndexValueArray( List, 0, Length( List ) - 1);
End;
procedure QuickSortIndexValueArray(var List : TIndexValueArray;
min, max : integer);
var
med_value : TIndexValueItem;
hi, lo, i : integer;
begin
// If the list has <= 1 element, it's sorted.
if (min >= max) then Exit;
// Pick a dividing item randomly.
i := min + Trunc(Random(max - min + 1));
med_value := List[i];
// Swap it to the front so we can find it easily.
List[i] := List[min];
// Move the items smaller than this into the left
// half of the list. Move the others into the right.
lo := min;
hi := max;
while (True) do
begin
// Look down from hi for a value < med_value.
while (List[hi].val >= med_value.val) do
begin
hi := hi - 1;
if (hi <= lo) then Break;
end;
if (hi <= lo) then
begin
// We're done separating the items.
List[lo] := med_value;
Break;
end;
// Swap the lo and hi values.
List[lo] := List[hi];
// Look up from lo for a value >= med_value.
lo := lo + 1;
while (List[lo].val < med_value.val) do
begin
lo := lo + 1;
if (lo >= hi) then Break;
end;
if (lo >= hi) then
begin
// We're done separating the items.
lo := hi;
List[hi] := med_value;
Break;
end;
// Swap the lo and hi values.
List[hi] := List[lo];
end; // while (True) do
// Sort the two sublists.
QuickSortIndexValueArray(List, min, lo - 1);
QuickSortIndexValueArray(List, lo + 1, max);
end;
{ TI2XOCR }
constructor TI2XOCR.Create(const GUID, ParmFileName: string);
begin
inherited Create(GUID, ParmFileName);
FOCRData := TI2XOCRResults.Create;
FImage := TDWImage.Create;
end;
destructor TI2XOCR.Destroy;
begin
FreeAndNil( FOCRData );
FreeAndNil( FImage );
inherited;
end;
function TI2XOCR.GetOCRData: string;
begin
Result := FOCRData.AsXML;
end;
function TI2XOCR.OCRImageDLL(MemoryMapName, ImageList: PChar;
LoadImageFromMemoryMap: boolean): boolean;
var
sMemoryMapName, sImageList : string;
Begin
try
sMemoryMapName := PChar(MemoryMapName);
sImageList := PChar(ImageList);
if ( LoadImageFromMemoryMap ) then
self.FMemoryMapManager.Read( sMemoryMapName, FImage );
//FImage.LoadFromMemoryMap( sMemoryMapName );
Result := self.OCRImage( sMemoryMapName, sImageList );
finally
end;
End;
{ TI2XOCRItem }
procedure TI2XOCRItem.Assign(Source: TI2XOCRItem);
begin
with Self do begin
X := Source.X;
Y := Source.Y;
Width := Source.Width;
Height := Source.Height;
Accuracy := Source.Accuracy;
Data := Source.Data;
DataType := Source.DataType;
end;
end;
procedure TI2XOCRItem.AssignTo(Target: TI2XOCRItem);
begin
with Target do begin
X := self.X;
Y := self.Y;
Width := self.Width;
Height := self.Height;
Accuracy := self.Accuracy;
Data := self.Data;
DataType := self.DataType;
end;
end;
function TI2XOCRItem.AsXML: string;
var
sb : TStringBuilder;
begin
try
sb := TStringbuilder.Create;
sb.Append( '<item' );
sb.Append( ' x="');
sb.Append( IntToStr( self.X ) );
sb.Append( '"');
sb.Append( ' y="');
sb.Append( IntToStr( self.Y ) );
sb.Append( '"');
sb.Append( ' w="');
sb.Append( IntToStr( self.Width ) );
sb.Append( '"');
sb.Append( ' h="');
sb.Append( IntToStr( self.Height ) );
sb.Append( '"');
sb.Append( ' a="');
sb.Append( FloatToStrF( self.Accuracy, ffGeneral, 6, 2) );
sb.Append( '"');
sb.Append( ' t="');
sb.Append( IntToStr( Integer( self.DataType )) );
sb.Append( '"');
sb.Append( ' d="');
sb.Append( self.DataEnc );
sb.Append( '"');
sb.Append( ' />' );
Result := sb.ToString;
finally
FreeAndNil( sb );
end;
end;
procedure TI2XOCRItem.Clear;
begin
self.FX := 0;
self.FY := 0;
self.FWidth := 0;
self.FHeight := 0;
self.FAccuracy := 0;
self.FData := '';
self.FDataType := odtNoneSpecified;
self.FPtr := nil;
self.FObj := nil;
end;
constructor TI2XOCRItem.Create;
begin
self.Clear;
end;
destructor TI2XOCRItem.Destroy;
begin
if ( FObj <> nil ) then FObj.Free;
end;
function TI2XOCRItem.FromXML(const XMLString: string): boolean;
var
xmlDoc: IXMLDocument;
nod : IXMLNode;
xmlNodeList : IXMLNodeList;
iOCRIdx : integer;
Begin
try
if ( XMLString = '' ) then exit;
xmlDoc := CreateXMLDoc;
if (xmlDoc.LoadXML( XMLString ) ) then begin
xmlNodeList := xmldoc.DocumentElement.ChildNodes;
for iOCRIdx := 0 to xmlNodeList.length - 1 do begin
nod := xmlNodeList.Item[iOCRIdx];
if ( nod.NodeName = 'x' ) then
self.X := StrToInt( nod.NodeValue )
else if ( nod.NodeName = 'y' ) then
self.Y := StrToInt( nod.NodeValue )
else if ( nod.NodeName = 'w' ) then
self.Width := StrToInt( nod.NodeValue )
else if ( nod.NodeName = 'h' ) then
self.Height := StrToInt( nod.NodeValue )
else if ( nod.NodeName = 'a' ) then
self.Accuracy := StrToFloat( nod.NodeValue )
else if ( nod.NodeName = 't' ) then
self.DataType := TOCRItemDataType( StrToInt( nod.NodeValue ))
else if ( nod.NodeName = 'd' ) then
self.DataEnc := nod.NodeValue
;
end;
end else begin
raise Exception.Create('Could not load XML. Are you sure it exists and is it well formed?');
end;
finally
end;
end;
function TI2XOCRItem.getAccuracy: single;
begin
Result := self.FAccuracy;
end;
function TI2XOCRItem.getAsRect: TRect;
begin
getAsRect.Left := self.X;
getAsRect.Top := self.Y;
getAsRect.Right := self.X + self.Width;
getAsRect.Bottom := self.Y + self.Height;
end;
function TI2XOCRItem.getBottom: integer;
begin
Result := self.FY + self.FHeight;
end;
function TI2XOCRItem.getData: string;
begin
Result := self.FData;
end;
function TI2XOCRItem.getDataEnc: string;
begin
Result := XMLEnc( self.FData );
end;
function TI2XOCRItem.getDataType: TOCRItemDataType;
begin
Result := self.FDataType;
end;
function TI2XOCRItem.getHeight: integer;
begin
Result := self.FHeight;
end;
function TI2XOCRItem.getRight: integer;
begin
Result := self.FX + self.FWidth;
end;
function TI2XOCRItem.getWidth: integer;
begin
Result := self.FWidth;
end;
function TI2XOCRItem.getX: integer;
begin
Result := self.FX;
end;
function TI2XOCRItem.getY: integer;
begin
Result := self.FY;
end;
procedure TI2XOCRItem.setDataEnc(const Value: string);
begin
FData := XMLDec( Value );
end;
procedure TI2XOCRItem.setDataType(const Value: TOCRItemDataType);
begin
FDataType := Value;
end;
{ TI2XOCRResult }
function TI2XOCRResult.Add(const ItemToAdd: TI2XOCRItem): integer;
begin
//FItemList.Add( IntToStr(FItemList.Count), ItemToAdd );
//Result := FItemList.Count;
//Result := FItemList.Add( IntToStr(FItemList.Count), ItemToAdd );
Result := FItemList.Add( ItemToAdd );
//self.FTI2XOCRItem := TI2XOCRItem.Create();
//FTI2XOCRItem.Assign( ItemToAdd );
//Result := FItemList.Add( IntToStr(FItemList.Count), FTI2XOCRItem );
//FTI2XOCRItem := nil;
end;
procedure TI2XOCRResult.Assign(Source: TI2XOCRItem);
begin
inherited;
end;
procedure TI2XOCRResult.AssignTo(Target: TI2XOCRItem);
begin
inherited;
end;
function TI2XOCRResult.AsXML: string;
var
sb : TStringBuilder;
i : integer;
begin
try
sb := TStringbuilder.Create;
sb.Append( '<slice ' );
sb.Append( ' id="');
sb.Append( self.ID );
sb.Append( '"');
sb.Append( ' x="');
sb.Append( IntToStr( self.X ) );
sb.Append( '"');
sb.Append( ' y="');
sb.Append( IntToStr( self.Y ) );
sb.Append( '"');
sb.Append( ' w="');
sb.Append( IntToStr( self.Width ) );
sb.Append( '"');
sb.Append( ' h="');
sb.Append( IntToStr( self.Height ) );
sb.Append( '"');
sb.Append( ' t="');
sb.Append( IntToStr( integer( self.DataType ) ) );
sb.Append( '"');
sb.Append( ' a="');
sb.Append( FloatToStrF( self.Accuracy, ffGeneral, 6, 2) );
sb.Append( '"');
sb.Append( '>' );
sb.Append( '<items>' );
for i := 0 to self.FItemList.Count - 1 do begin
sb.Append( self.Items[i].AsXML() );
end;
sb.Append( '</items>' );
sb.Append( '</slice>' );
Result := sb.ToString;
finally
FreeAndNil( sb );
end;
end;
procedure TI2XOCRResult.Clear;
begin
FItemList.Clear;
end;
constructor TI2XOCRResult.Create;
begin
inherited;
self.FItemList := TObjectList.Create;
end;
procedure TI2XOCRResult.Delete( ItemToDelete : Integer );
begin
self.FItemList.Delete( ItemToDelete );
end;
destructor TI2XOCRResult.Destroy;
begin
FreeAndNil( FItemList );
inherited;
end;
function TI2XOCRResult.GetCount: Cardinal;
begin
Result := self.FItemList.Count;
end;
function TI2XOCRResult.GetItem(Index: Integer): TI2XOCRItem;
begin
Result := TI2XOCRItem( FItemList.Items[ Index ] );
end;
function TI2XOCRResult.IndexListSortedByY: TIndexValueArray;
var
i : Integer;
begin
SetLength( Result, self.Count );
for i := 0 to self.Count - 1 do begin
Result[i].idx := i;
//Result[i].val := self.Items[i].Y;
Result[i].val := FormatFloat('0000000000', self.Items[i].Y) +
FormatFloat('0000000000', self.Items[i].X);
Result[i].obj := self.Items[i];
end;
QuickSortIndexValueArray( Result );
end;
function TI2XOCRResult.SortByY: boolean;
var
arr : TIndexValueArray;
i : Integer;
begin
arr := self.IndexListSortedByY();
FItemList.OwnsObjects := false;
for i := 0 to Length( arr ) - 1 do begin
self.FItemList.Items[ i ] := arr[i].obj;
end;
FItemList.OwnsObjects := true;
end;
procedure TI2XOCRResult.SetID(const Value: string);
begin
FID := Value;
end;
procedure TI2XOCRResult.SetItem(Index: Integer; const Value: TI2XOCRItem);
begin
TI2XOCRItem( FItemList.Items[ Index ] ).Assign( Value );
end;
{ TI2XOCRResults }
function TI2XOCRResults.Add(const ItemToAdd: TI2XOCRResult): integer;
begin
Result := self.FResultsList.Add( ItemToAdd );
end;
function TI2XOCRResults.AsXML(const RootNodeName : string = 'ocr'): string;
var
sb : TStringBuilder;
i : integer;
begin
try
sb := TStringbuilder.Create;
if ( Length(RootNodeName) > 0 ) then begin
sb.Append( '<' );
sb.Append( RootNodeName );
sb.Append( '>' );
end;
sb.Append( '<image ' );
sb.Append( ' id="');
sb.Append( self.FImageID );
sb.Append( '">');
sb.Append( '<slices>' );
for i := 0 to self.FResultsList.Count - 1 do begin
sb.Append( self[i].AsXML() );
end;
sb.Append( '</slices>' );
sb.Append( '</image>' );
if ( Length(RootNodeName) > 0 ) then begin
sb.Append( '</' );
sb.Append( RootNodeName );
sb.Append( '>' );
end;
Result := sb.ToString;
finally
FreeAndNil( sb );
end;
end;
procedure TI2XOCRResults.Clear;
begin
FResultsList.Clear;
end;
constructor TI2XOCRResults.Create;
begin
self.FResultsList := TObjectList.Create;
end;
procedure TI2XOCRResults.Delete( ItemToDelete: Integer);
begin
FResultsList.Delete( ItemToDelete );
end;
destructor TI2XOCRResults.Destroy;
Begin
FreeAndNil( FResultsList );
End;
function TI2XOCRResults.GetBoundary: TRect;
var
iResult : integer;
iItem : integer;
oItem : TI2XOCRItem;
oResult : TI2XOCRResult;
right : integer;
bottom : integer;
Begin
Initialize( Result );
if ( self.Count = 0 ) then begin
exit;
end;
Result.Left := MAXINT;
Result.Top := MAXINT;
Result.Right := 0;
Result.Bottom := 0;
for iResult := 0 to self.Count - 1 do begin
oResult := self.Items[ iResult ];
for iItem := 0 to oResult.Count - 1 do begin
oItem := oResult.Items[ iItem ];
if ( oItem.X < Result.Left ) then Result.Left := oItem.X;
if ( oItem.Y < Result.Top ) then Result.Top := oItem.Y;
if ( oItem.Right > Result.Right ) then Result.Right := oItem.Right;
if ( oItem.Bottom > Result.Bottom ) then Result.Bottom := oItem.Bottom;
end;
end;
End;
function TI2XOCRResults.GetCount: Cardinal;
Begin
Result := self.FResultsList.Count;
End;
function TI2XOCRResults.GetFirstCharacter: TI2XOCRItem;
var
oItem : TI2XOCRItem;
oResult : TI2XOCRResult;
ResultsIndexSortedByX, ItemsIndexSortedByY: TIndexValueArray;
Begin
//This will obtain an index of the result items from left to right
Result := nil;
if ( self.Count = 0 ) then begin
exit;
end;
self.SaveToFile( 'C:\Users\Administrator\AppData\Local\Temp\i2x\BEFORE_FIRST_CHAR.xml');
ResultsIndexSortedByX := self.IndexListSortedByX();
if ( Length( ResultsIndexSortedByX ) > 0 ) then begin
//This will obtain an index of the result items from left to right
oResult := TI2XOCRResult( ResultsIndexSortedByX[0].obj );
ItemsIndexSortedByY := oResult.IndexListSortedByY();
if ( Length( ItemsIndexSortedByY ) > 0 ) then begin
oItem := TI2XOCRItem( ItemsIndexSortedByY[0].obj );
Result := oItem;
end;
end;
End;
function TI2XOCRResults.GetItem(Index: Integer): TI2XOCRResult;
begin
Result := TI2XOCRResult( self.FResultsList.Items[ Index ] );
end;
function TI2XOCRResults.IndexListSortedByX: TIndexValueArray;
var
i : Integer;
begin
SetLength( Result, self.Count );
for i := 0 to self.Count - 1 do begin
Result[i].idx := i;
//Result[i].val := self.Items[i].Y;
Result[i].val := FormatFloat('0000000000', self.Items[i].X) +
FormatFloat('0000000000', self.Items[i].Y);
Result[i].obj := self.Items[i];
end;
QuickSortIndexValueArray( Result );
end;
function TI2XOCRResults.LoadFromFile(fileName: TFileName): boolean;
var
xmlDoc: IXMLDocument;
Begin
Result := false;
try
xmlDoc := CreateXMLDoc;
if ( xmlDoc.Load( fileName ) ) then begin
Result := XMLToResultsObject( xmlDoc.XML, self );
end else begin
raise Exception.Create('Could not load XML from file ' + fileName + '. Are you sure it exists and is it well formed?');
end;
finally
end;
End;
function TI2XOCRResults.XMLToResultsObject( const XMLStringData : string; OCRResultsObject : TI2XOCRResults ) : boolean;
var
xmlDoc: IXMLDocument;
nod, nodSlice, nodItem : IXMLElement;
oNod : IXMLNode;
parsed : boolean;
xmlNodeList, xmlSubNodeList, nodItemList : IXMLNodeList;
ocrresult: TI2XOCRResult;
ocrresitem : TI2XOCRItem;
iImageIdx, iSliceIdx, iItemIdx : integer;
Begin
try
Result := false;
if ( OCRResultsObject = nil ) then
OCRResultsObject := TI2XOCRResults.Create
else
OCRResultsObject.Clear;
xmlDoc := CreateXMLDoc;
parsed := xmlDoc.loadXML( XMLStringData );
if ( not parsed ) then begin
raise Exception.Create( 'XML Passed to function could not be parsed.' );
end;
xmlNodeList := xmldoc.DocumentElement.ChildNodes;
for iImageIdx := 0 to xmlNodeList.length - 1 do begin
nod := IXMLElement(xmlNodeList.Item[iImageIdx]);
if ( nod.nodeType = ELEMENT_NODE ) then begin
if (nod.nodeName = 'image' ) then begin
OCRResultsObject.ImageID := nod.attributes.getNamedItem('id').text;
xmlSubNodeList := nod.SelectNodes('slices/slice');
if ( xmlSubNodeList.length > 0 ) then begin
for iSliceIdx := 0 to xmlSubNodeList.length - 1 do begin
nodSlice := IXMLElement(xmlSubNodeList.Item[iSliceIdx]);
ocrresult := TI2XOCRResult.Create();
ocrresult.ID := GetAttr( nodSlice, 'id' );
ocrresult.X := GetAttr( nodSlice, 'x', 0 );
ocrresult.Y := GetAttr( nodSlice, 'y', 0);
ocrresult.Width := GetAttr( nodSlice, 'w', 0);
ocrresult.Height := GetAttr( nodSlice, 'h', 0);
ocrresult.Accuracy := GetAttr( nodSlice, 'a', 0.0 );
ocrresult.DataType := TOCRItemDataType( GetAttr( nodSlice, 't', 0 ) );
nodItemList := nodSlice.SelectNodes('items/item');
if ( nodItemList.length > 0 ) then begin
for iItemIdx := 0 to nodItemList.length - 1 do begin
nodItem := IXMLElement(nodItemList.Item[iItemIdx]);
ocrresitem := TI2XOCRItem.Create();
ocrresitem.X := GetAttr( nodItem, 'x', 0 );
ocrresitem.Y := GetAttr( nodItem, 'y', 0 );
ocrresitem.Width := GetAttr( nodItem, 'w', 0 );
ocrresitem.Height := GetAttr( nodItem, 'h', 0 );
ocrresitem.Accuracy := GetAttr( nodItem, 'a', 0.0 );
ocrresitem.Data := GetAttr( nodItem, 'd' );
ocrresitem.DataType := TOCRItemDataType( GetAttr( nodItem, 't', 0 ) );
ocrresult.Add( ocrresitem );
end;
end;
OCRResultsObject.Add( ocrresult );
end;
end;
end;
end;
end;
finally
end;
Result := true;
End;
function TI2XOCRResults.LoadXML(XMLString: string): boolean;
var
xmlDoc: IXMLDocument;
Begin
Result := false;
try
xmlDoc := CreateXMLDoc;
if ( xmlDoc.LoadXML( XMLString ) ) then begin
Result := XMLToResultsObject( xmlDoc.XML, self );
end else begin
raise Exception.Create('Could not load XML. Are you sure it exists and is it well formed?');
end;
finally
end;
End;
function TI2XOCRResults.SaveToFile(fileName: TFileName): boolean;
var
xmlDoc: IXMLDocument;
Begin
Result := false;
try
xmlDoc := CreateXMLDoc;
if ( xmlDoc.LoadXML( AsXML() ) ) then begin
xmlDoc.Save( fileName );
Result := true;
end else begin
raise Exception.Create('File ' + fileName + ' could not be loaded on into OCR Results.');
end;
finally
end;
End;
procedure TI2XOCRResults.SetItem(Index: Integer; const Value: TI2XOCRResult);
begin
TI2XOCRResult( self.FResultsList.Items[ Index ] ).Assign( Value );
end;
function TI2XOCRResults.SortByX: boolean;
var
arr : TIndexValueArray;
i : Integer;
begin
arr := self.IndexListSortedByX();
FResultsList.OwnsObjects := false;
for i := 0 to Length( arr ) - 1 do begin
self.FResultsList.Items[ i ] := arr[i].obj;
end;
FResultsList.OwnsObjects := true;
end;
{ TI2XOCRResultsMM }
{*
function TI2XOCRResultsMM.ClearMemoryMap: boolean;
begin
Result := false;
try
if ( FMemoryMap <> nil ) then
FMemoryMap.Free;
Result := true;
except
raise;
end;
end;
constructor TI2XOCRResultsMM.Create;
begin
inherited Create();
end;
destructor TI2XOCRResultsMM.Destroy;
begin
if ( FMemoryMap <> nil ) then FreeAndNil( FMemoryMap );
inherited;
end;
function TI2XOCRResultsMM.getIsMemoryMapped: boolean;
begin
Result := (self.FMemoryMap <> nil);
end;
//This will read the bitmap from the memory stream. since it is of TBitmap,
// it will then get converted into the FreeBitmap
function TI2XOCRResultsMM.LoadFromMemoryMap(const sMapName: string;
const InitSize: Cardinal): boolean;
var
ms : TMemoryStreamPlus;
Buffer : array of Char;
s : string;
begin
Result := false;
try
if ( FMemoryMap = nil ) then
FMemoryMap := TMapStream.Create( sMapName, InitSize );
ms := TMemoryStreamPlus.Create;
if ( not FMemoryMap.Read( ms ) ) then
raise Exception.Create('Error while copying OCR Results from Memory Map');
self.ClearMemoryMap();
self.LoadXML( ms.Read().StringValue );
Result := true;
finally
FreeAndNil( ms );
end;
end;
function TI2XOCRResultsMM.SaveToMemoryMap( var sMapName: string): boolean;
const
MAX_RETRY = 5;
var
ms : TMemoryStreamPlus;
iRetry : integer;
begin
Result := false;
try
if ( Length(sMapName) = 0 ) then
sMapName := OCR_MEMMAP_HEADER + IntToStr( integer( @self ) );
if ( FMemoryMap = nil ) then begin
FMemoryMap := TMapStream.Create( sMapName, OCR_MEMMAP_INIT_SIZE );
//FMemoryMap := ActiveMemoryMaps.Stream( sMapName, OCR_MEMMAP_INIT_SIZE );
end;
ms := TMemoryStreamPlus.Create( self.AsXML() );
iRetry := 0;
while ( (not Result) and (iRetry < 5) ) do begin
try
if ( not FMemoryMap.Write( ms ) ) then
raise Exception.Create('Error while copying OCR Results from Memory Map');
Result := true;
except
Inc( iRetry );
if ( MAX_RETRY < iRetry ) then
raise;
FMemoryMap.Free;
sMapName := OCR_MEMMAP_HEADER + IntToStr( integer( @self ) ) + '_' + IntToStr( iRetry );
FMemoryMap := TMapStream.Create( sMapName, OCR_MEMMAP_INIT_SIZE );
//FMemoryMap := ActiveMemoryMaps.Stream( sMapName, OCR_MEMMAP_INIT_SIZE );
end;
end;
finally
FreeAndNil( ms );
end;
end;
*}
{ TDLLOCRTests }
procedure TDLLOCRTests.Add(itemToAdd: TDLLOCRTestEntry);
var
sKey : string;
begin
itemToAdd.Parent := self;
if self.Exists( itemToAdd.Name ) then begin
raise Exception.Create('TDLLOCRTests.Add(DLL Entry "' + itemToAdd.Name + '" already exists!');
end;
FItems.Add( itemToAdd.Name, itemToAdd );
end;
procedure TDLLOCRTests.Add(DLLNameToAdd: string;
DoNormalWholeTest,
DoNormalSliceTest,
DoInvertWholeTest,
DoInvertSliceTest: boolean);
Var
newItemToAdd : TDLLOCRTestEntry;
begin
newItemToAdd := TDLLOCRTestEntry.Create(
DLLNameToAdd,
DoNormalWholeTest,
DoNormalSliceTest,
DoInvertWholeTest,
DoInvertSliceTest
);
if self.Exists( DLLNameToAdd ) then begin
raise Exception.Create('TDLLOCRTests.Add(DLL Entry "' + DLLNameToAdd + '" already exists!');
end;
self.Add( newItemToAdd );
end;
function TDLLOCRTests.AsXML: string;
var
sb : TStringBuilder;
i : integer;
begin
try
sb := TStringbuilder.Create;
sb.Append( '<ocr_tests' );
sb.Append( ' name="' );
sb.Append( self.Name );
sb.Append( '">' );
for i := 0 to self.GetCount - 1 do begin
sb.Append( self.Items[i].AsXML());
end;
sb.Append( '</ocr_tests>' );
Result := sb.ToString;
finally
FreeAndNil( sb );
end;
end;
procedure TDLLOCRTests.Clear;
begin
self.Name := '';
self.FItems.Clear;
end;
procedure TDLLOCRTests.CopyFrom(SourceObject: TDWPersist);
begin
self.Clear;
self.LoadFromXML( SourceObject.AsXML() );
end;
procedure TDLLOCRTests.CopyTo(TargetObject: TDWPersist);
begin
TargetObject.Clear;
TargetObject.LoadFromXML( self.AsXML() );
end;
constructor TDLLOCRTests.Create(const Name: string);
begin
self.Name := Name;
self.FItems := THashTable.Create(10);
end;
constructor TDLLOCRTests.Create;
begin
self.FItems := THashTable.Create(10);
end;
destructor TDLLOCRTests.Destroy;
begin
FreeAndNil( FItems );
end;
function TDLLOCRTests.Exists(const DLLNameToCheck: string): boolean;
begin
Result := FItems.ContainsKey( DLLNameToCheck );
end;
function TDLLOCRTests.GetCount: integer;
begin
Result := FItems.Count;
end;
function TDLLOCRTests.GetItem(idx: TIndex) : TDLLOCRTestEntry ;
begin
Result := TDLLOCRTestEntry( FItems[ idx ] );
end;
function TDLLOCRTests.GetTestCount: integer;
var
entry : TDLLOCRTestEntry;
i : integer;
begin
Result := 0;
for i := 0 to self.Count - 1 do begin
entry := self.Items[i];
Inc( Result, entry.Count );
end;
end;
function TDLLOCRTests.LoadFromXML(xmlString: string): boolean;
var
xmlDoc: IXMLDocument;
attr : IXMLNode;
ele: IXMLElement;
nod, nodTest : IXMLNode;
xmlNodeList, testNodeList : IXMLNodeList;
iOCRIdx, iTestIdx : integer;
sTestName, sTestValue : string;
entry : TDLLOCRTestEntry;
Begin
try
self.Clear;
if ( XMLString = '' ) then exit;
xmlDoc := CreateXMLDoc;
if (xmlDoc.LoadXML( XMLString ) ) then begin
self.Name := GetAttr(xmldoc.DocumentElement, 'name' );
xmlNodeList := xmldoc.DocumentElement.ChildNodes;
for iOCRIdx := 0 to xmlNodeList.length - 1 do begin
nod := xmlNodeList.Item[iOCRIdx];
entry := TDLLOCRTestEntry.Create( GetAttr( nod, 'name' ) );
entry.Descr := GetAttr( nod, 'descr' );
entry.Enabled := ( GetAttr( nod, 'enabled' ) = 'true' );
testNodeList := nod.ChildNodes;
for iTestIdx := 0 to testNodeList.length - 1 do begin
nodTest := testNodeList.Item[iTestIdx];
sTestName := nodTest.NodeName;
sTestValue := nodTest.Text;
//entry.Enabled := ( GetAttr( nodTest, 'enabled' ) = 'true' );
entry.SetOCRTest( sTestName, StrToBool( sTestValue ) );
//entry.IsActive[ TOCRTest(GetEnumValue(TypeInfo(TOCRTest),sTestName)) ] := StrToBool( sTestValue );
end;
self.Add( entry );
end;
end else begin
raise Exception.Create('Could not load XML. Are you sure it exists and is it well formed?');
end;
finally
end;
End;
procedure TDLLOCRTests.PutItem(idx: TIndex; const Value: TDLLOCRTestEntry);
begin
FItems[ idx ] := TObject( Value );
end;
{ TDLLOCRTestEntry }
procedure TDLLOCRTestEntry.Add(itemToAdd: TDLLOCRTest);
begin
itemToAdd.Parent := self;
FItems.Add( itemToAdd.Name, itemToAdd );
end;
function TDLLOCRTestEntry.AsXML: string;
var
sb : TStringBuilder;
i : integer;
begin
try
sb := TStringbuilder.Create;
sb.Append( '<test name="');
sb.Append( self.Name );
sb.Append( '" descr="');
sb.Append( self.Descr );
sb.Append( '" enabled="');
if self.Enabled then
sb.Append( 'true' )
else
sb.Append( 'false' );
sb.Append( '">');
for i := 0 to self.GetCount - 1 do begin
sb.Append( self.Items[i].AsXML());
end;
sb.Append( '</test>' );
Result := sb.ToString;
finally
FreeAndNil( sb );
end;
end;
function TDLLOCRTestEntry.CheckTest(testToCheck: TOCRTest): boolean;
begin
end;
procedure TDLLOCRTestEntry.Clear( const DeepClear : boolean = false );
var
DelItems : boolean;
begin
self.Name := '';
self.Descr := '';
DelItems := FItems.FreeObjectsOnDestroy;
FItems.FreeObjectsOnDestroy := DeepClear;
FItems.Clear;
FItems.FreeObjectsOnDestroy := DelItems;
end;
procedure TDLLOCRTestEntry.CopyFrom(SourceObject: TDWPersist);
var
i : integer;
src : TDLLOCRTestEntry;
test : TDLLOCRTest;
begin
src := TDLLOCRTestEntry(SourceObject);
//self.Clear( true );
self.Name := src.Name;
self.Descr := src.Descr;
self.Enabled := src.Enabled;
for i := 0 to src.GetCount - 1 do begin
self.IsActive[ src.Items[i].Test ] := src.Items[i].Enabled;
end;
end;
procedure TDLLOCRTestEntry.CopyTo(TargetObject: TDWPersist);
var
i : integer;
tgt : TDLLOCRTestEntry;
test : TDLLOCRTest;
begin
tgt := TDLLOCRTestEntry(TargetObject);
tgt.Clear( true );
tgt.Name := self.Name;
tgt.Descr := self.Descr;
tgt.Enabled := self.Enabled;
for i := 0 to self.GetCount - 1 do begin
test := TDLLOCRTest.Create();
tgt.Items[i].CopyTo( test );
tgt.Add( test );
//Items[i].Parent := tgt;
//tgt.Add( self.Items[i] );
end;
End;
constructor TDLLOCRTestEntry.Create(const Name: string);
begin
self.Name := Name;
FEnabled := true;
FItems := THashTable.Create(4);
self.Add( TDLLOCRTest.Create( ocrtNormalWhole, true) );
self.Add( TDLLOCRTest.Create( ocrtNormalSliced, true) );
self.Add( TDLLOCRTest.Create( ocrtInvertedWhole, true) );
self.Add( TDLLOCRTest.Create( ocrtInvertedSliced, true) );
end;
constructor TDLLOCRTestEntry.Create(const Name: string; DoNormalWholeTest,
DoNormalSliceTest, DoInvertWholeTest, DoInvertSliceTest: boolean);
begin
self.Name := Name;
FEnabled := true;
FItems := THashTable.Create(4);
self.Add( TDLLOCRTest.Create( ocrtNormalWhole, DoNormalWholeTest) );
self.Add( TDLLOCRTest.Create( ocrtNormalSliced, DoNormalSliceTest) );
self.Add( TDLLOCRTest.Create( ocrtInvertedWhole, DoInvertWholeTest) );
self.Add( TDLLOCRTest.Create( ocrtInvertedSliced, DoInvertSliceTest) );
end;
constructor TDLLOCRTestEntry.Create;
begin
FEnabled := true;
FItems := THashTable.Create(4);
self.Add( TDLLOCRTest.Create( ocrtNormalWhole, true) );
self.Add( TDLLOCRTest.Create( ocrtNormalSliced, true) );
self.Add( TDLLOCRTest.Create( ocrtInvertedWhole, true) );
self.Add( TDLLOCRTest.Create( ocrtInvertedSliced, true) );
end;
destructor TDLLOCRTestEntry.Destroy;
begin
FreeAndNil( FItems );
end;
function TDLLOCRTestEntry.Exists(const DLLNameToCheck: string): boolean;
begin
Result := FItems.ContainsKey( DLLNameToCheck );
end;
function TDLLOCRTestEntry.GetCount: integer;
begin
Result := FItems.Count;
end;
function TDLLOCRTestEntry.GetIndexByWholeTests: TIndexValueArray;
var
arr : TIndexValueArray;
begin
SetLength( arr, self.Count );
//TOCRTest = ( ocrtNormalWhole = 0, ocrtNormalSliced, ocrtInvertedWhole, ocrtInvertedSliced );
arr[0].idx := 0;
arr[0].obj := self.Items[ 'ocrtNormalWhole' ];
arr[1].idx := 1;
arr[1].obj := self.Items[ 'ocrtInvertedWhole' ];
arr[2].idx := 2;
arr[2].obj := self.Items[ 'ocrtNormalSliced' ];
arr[3].idx := 3;
arr[3].obj := self.Items[ 'ocrtInvertedSliced' ];
Result := arr;
end;
function TDLLOCRTestEntry.GetItem(idx: TIndex): TDLLOCRTest;
begin
Result := TDLLOCRTest( FItems[ idx ] );
end;
function TDLLOCRTestEntry.LoadFromXML(xmlString: string): boolean;
var
xmlDoc: IXMLDocument;
nod, nodTest : IXMLNode;
attr : IXMLNode;
testNodeList : IXMLNodeList;
iTestIdx : integer;
sTestName, sTestValue : string;
Begin
try
self.Clear( true );
xmlDoc := CreateXMLDoc;
if ( xmlDoc.LoadXML( XMLString ) ) then begin
nod := xmldoc.DocumentElement;
attr := nod.Attributes.GetNamedItem('name');
if ( attr <> nil ) then
self.Name := attr.Text;
attr := nod.Attributes.GetNamedItem('descr');
if ( attr <> nil ) then
self.Descr := attr.Text;
attr := nod.Attributes.GetNamedItem('enabled');
if ( attr <> nil ) then
self.Enabled := (attr.Text = 'true') or (attr.Text <> '0');
testNodeList := nod.ChildNodes;
for iTestIdx := 0 to testNodeList.length - 1 do begin
nodTest := testNodeList.Item[iTestIdx];
sTestName := nodTest.NodeName;
sTestValue := nodTest.Text;
self.SetOCRTest( sTestName, StrToBool( sTestValue ) );
//entry.IsActive[ TOCRTest(GetEnumValue(TypeInfo(TOCRTest),sTestName)) ] := StrToBool( sTestValue );
end;
end else begin
raise Exception.Create('Could not load XML. Are you sure it exists and is it well formed?');
end;
finally
end;
End;
procedure TDLLOCRTestEntry.PutItem(idx: TIndex; const Value: TDLLOCRTest);
begin
FItems[ idx ] := Value;
end;
procedure TDLLOCRTestEntry.setOCRTest(testToCheck: string;
const Value: boolean);
begin
if ( self.Exists( testToCheck )) then
self.Items[ testToCheck ].Enabled := Value
else
self.Add( TDLLOCRTest.Create( testToCheck, Value ) );
end;
procedure TDLLOCRTestEntry.setOCRTest(testToCheck: TOCRTest;
const Value: boolean);
var
sName : string;
test : TDLLOCRTest;
begin
sName := GetEnumName(TypeInfo(TOCRTest), integer(testToCheck));
if ( self.Exists( sName )) then
self.Items[ sName ].Enabled := Value
else
self.Add( TDLLOCRTest.Create( testToCheck, Value ) );
end;
{ TDLLOCRTest }
constructor TDLLOCRTest.Create;
begin
FTest := ocrtNormalWhole;
self.FEnabled := true;
end;
constructor TDLLOCRTest.Create(TestToDefaultTo: TOCRTest);
begin
Self.Test := TestToDefaultTo;
self.FEnabled := true;
end;
function TDLLOCRTest.AsXML: string;
var
sb : TStringBuilder;
elementName : string;
begin
try
sb := TStringbuilder.Create;
sb.Append( '<' );
sb.Append( self.Name );
sb.Append( '>' );
sb.Append( BoolToStr(self.Enabled) );
sb.Append( '</' );
sb.Append( self.Name );
sb.Append( '>' );
Result := sb.ToString;
finally
FreeAndNil( sb );
end;
end;
procedure TDLLOCRTest.Clear;
begin
self.Name := '';
self.FEnabled := false;
end;
procedure TDLLOCRTest.CopyFrom(SourceObject: TDWPersist);
begin
self.Test := TDLLOCRTest(SourceObject).Test;
self.Enabled := TDLLOCRTest(SourceObject).Enabled;
end;
procedure TDLLOCRTest.CopyTo(TargetObject: TDWPersist);
begin
TDLLOCRTest(TargetObject).Test := self.Test;
TDLLOCRTest(TargetObject).Enabled := self.Enabled;
end;
constructor TDLLOCRTest.Create(TestToDefaultTo: TOCRTest;
const Enabled: boolean);
begin
Self.FTest := TestToDefaultTo;
self.FEnabled := Enabled;
end;
function TDLLOCRTest.GetDescr: string;
begin
Case self.FTest of
ocrtNormalWhole :
Result := 'Normal Whole';
ocrtNormalSliced :
Result := 'Sliced Normal';
ocrtInvertedWhole :
Result := 'Whole Inverted';
ocrtInvertedSliced :
Result := 'Sliced Inverted';
end;
end;
function TDLLOCRTest.GetName: string;
begin
Result := GetEnumName(TypeInfo(TOCRTest), integer( FTest )) ;
end;
function TDLLOCRTest.Invert: boolean;
begin
Result := ( FTest in [ocrtInvertedWhole, ocrtInvertedSliced ] );
end;
function TDLLOCRTest.IsWholePageTest: boolean;
begin
Result := ( FTest in [ocrtInvertedWhole, ocrtNormalWhole ] );
end;
function TDLLOCRTest.LoadFromXML(xmlString: string): boolean;
var
xmlDoc: IXMLDocument;
ele: IXMLElement;
nod : IXMLNode;
xmlNodeList : IXMLNodeList;
iImageIdx : integer;
Begin
try
xmlDoc := CreateXMLDoc;
if ( xmlDoc.LoadXML( XMLString ) ) then begin
self.Name := xmldoc.DocumentElement.nodeName;
xmlNodeList := xmldoc.DocumentElement.ChildNodes;
for iImageIdx := 0 to xmlNodeList.length - 1 do begin
nod := xmlNodeList.Item[iImageIdx];
self.Enabled := StrToBool(nod.Text);
end;
end else begin
raise Exception.Create('Could not load XML. Are you sure it exists and is it well formed?');
end;
finally
end;
End;
procedure TDLLOCRTest.SetName(const Value: string);
begin
FTest := TOCRTest(GetEnumValue(TypeInfo(TOCRTest),Value));
end;
function TDLLOCRTest.Slice: boolean;
begin
Result := ( FTest in [ocrtNormalSliced, ocrtInvertedSliced ] );
end;
constructor TDLLOCRTest.Create(TestToDefaultTo: string; const Enabled: boolean);
begin
self.Name := TestToDefaultTo;
self.Enabled := Enabled;
end;
END.
|
unit CatHashes;
{
Catarinka - Hash functions
Copyright (c) 2003-2020 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
If you have D10 Seattle or up, use System.Hash's MD5, otherwise use the
MD5 function by Stijn Sanders (MIT license, included at the end of this file)
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
{$IFDEF USECROSSVCL}
WinAPI.Windows,
{$ENDIF}
{$IFDEF D10SEATTLE_OR_UP}
System.Hash,
{$ENDIF}
System.Classes, System.SysUtils;
{$ELSE}
Classes, SysUtils;
{$ENDIF}
function MD5Hash(const s: string): string;
function MD5Hash_Sanders(s: UTF8String): UTF8String;
implementation
function MD5Hash(const s: string): string;
begin
{$IFDEF D10SEATTLE_OR_UP}
result := THashMD5.GetHashString(s);
{$ELSE}
result := string(UTF8string(MD5Hash_Sanders(s)));
{$ENDIF}
end;
{
Taken from md5.pas v1.0.3
Copyright 2012-2013 Stijn Sanders
License: MIT (http://opensource.org/licenses/mit-license.php)
https://github.com/stijnsanders/TMongoWire/blob/master/mongoAuth.pas
Based on http://www.ietf.org/rfc/rfc1321.txt
}
function MD5Hash_Sanders(s: UTF8String): UTF8String;
const
roll1: array [0 .. 3] of cardinal = (7, 12, 17, 22);
roll2: array [0 .. 3] of cardinal = (5, 9, 14, 20);
roll3: array [0 .. 3] of cardinal = (4, 11, 16, 23);
roll4: array [0 .. 3] of cardinal = (6, 10, 15, 21);
base1: array [0 .. 15] of cardinal = ($D76AA478, $E8C7B756, $242070DB,
$C1BDCEEE, $F57C0FAF, $4787C62A, $A8304613, $FD469501, $698098D8, $8B44F7AF,
$FFFF5BB1, $895CD7BE, $6B901122, $FD987193, $A679438E, $49B40821);
base2: array [0 .. 15] of cardinal = ($F61E2562, $C040B340, $265E5A51,
$E9B6C7AA, $D62F105D, $02441453, $D8A1E681, $E7D3FBC8, $21E1CDE6, $C33707D6,
$F4D50D87, $455A14ED, $A9E3E905, $FCEFA3F8, $676F02D9, $8D2A4C8A);
base3: array [0 .. 15] of cardinal = ($FFFA3942, $8771F681, $6D9D6122,
$FDE5380C, $A4BEEA44, $4BDECFA9, $F6BB4B60, $BEBFBC70, $289B7EC6, $EAA127FA,
$D4EF3085, $04881D05, $D9D4D039, $E6DB99E5, $1FA27CF8, $C4AC5665);
base4: array [0 .. 15] of cardinal = ($F4292244, $432AFF97, $AB9423A7,
$FC93A039, $655B59C3, $8F0CCC92, $FFEFF47D, $85845DD1, $6FA87E4F, $FE2CE6E0,
$A3014314, $4E0811A1, $F7537E82, $BD3AF235, $2AD7D2BB, $EB86D391);
Hex: array [0 .. 15] of AnsiChar = '0123456789abcdef';
var
a: cardinal;
dl, i, J, k, l: integer;
d: array of cardinal;
g, h: array [0 .. 3] of cardinal;
begin
a := length(s);
dl := a + 9;
if (dl and $3F) <> 0 then
dl := (dl and $FFC0) + $40;
i := dl;
dl := dl shr 2;
SetLength(d, dl);
SetLength(s, i);
J := a + 1;
s[J] := #$80;
while J < i do
begin
inc(J);
s[J] := #0;
end;
Move(s[1], d[0], i);
d[dl - 2] := a shl 3;
h[0] := $67452301;
h[1] := $EFCDAB89;
h[2] := $98BADCFE;
h[3] := $10325476;
i := 0;
while i < dl do
begin
g := h;
J := i;
for k := 0 to 15 do
begin
l := k * 3;
a := h[l and 3] + ((h[(l + 1) and 3] and h[(l + 2) and 3]) or
(not(h[(l + 1) and 3]) and h[(l + 3) and 3])) + d[J] + base1[k];
h[l and 3] := h[(l + 1) and 3] +
((a shl roll1[k and 3]) or (a shr (32 - roll1[k and 3])));
inc(J);
end;
J := 1;
for k := 0 to 15 do
begin
l := k * 3;
a := h[l and 3] + ((h[(l + 3) and 3] and h[(l + 1) and 3]) or
(not(h[(l + 3) and 3]) and h[(l + 2) and 3])) + d[i or (J and $F)]
+ base2[k];
h[l and 3] := h[(l + 1) and 3] +
((a shl roll2[k and 3]) or (a shr (32 - roll2[k and 3])));
inc(J, 5);
end;
J := 5;
for k := 0 to 15 do
begin
l := k * 3;
a := h[l and 3] + (h[(l + 1) and 3] xor h[(l + 2) and 3] xor h[(l + 3) and
3]) + d[i or (J and $F)] + base3[k];
h[l and 3] := h[(l + 1) and 3] +
((a shl roll3[k and 3]) or (a shr (32 - roll3[k and 3])));
inc(J, 3);
end;
J := 0;
for k := 0 to 15 do
begin
l := k * 3;
a := h[l and 3] + (h[(l + 2) and 3] xor (h[(l + 1) and 3] or
not h[(l + 3) and 3])) + d[i or (J and $F)] + base4[k];
h[l and 3] := h[(l + 1) and 3] +
((a shl roll4[k and 3]) or (a shr (32 - roll4[k and 3])));
inc(J, 7);
end;
for k := 0 to 3 do
inc(h[k], g[k]);
inc(i, 16);
end;
SetLength(result, 32);
for k := 0 to 31 do
result[k + 1] := Hex[h[k shr 3] shr ((k xor 1) shl 2) and $F];
end;
// ------------------------------------------------------------------------//
end.
|
//***********************************************************************
//* Проект "Студгородок" *
//* Модуль данных (контейнер для компонентов) *
//* Выполнил: Чернявский А.Э. 2004-2005 г. *
//***********************************************************************
unit DataModule1_Unit;
interface
uses
Windows, Graphics, Forms, Messages, ExtCtrls, ComCtrls, StdActns, ShellAPI,
SysUtils, Classes, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, Controls,
FIBQuery, pFIBQuery, pFIBStoredProc, pFIBErrorHandler, FIB, StdCtrls, Dialogs, ToolWin;
type
TDataModule1 = class(TDataModule)
DB: TpFIBDatabase;
WriteTransaction: TpFIBTransaction;
ReadTransaction: TpFIBTransaction;
ReadTimestampDataSet: TpFIBDataSet;
DataSet_main: TpFIBDataSet;
DataSet_read: TpFIBDataSet;
StoredProc: TpFIBStoredProc;
procedure DBAfterRestoreConnect;
procedure DBLostConnect(Database: TFIBDatabase;
E: EFIBError; var Actions: TOnLostConnectActions);
private
//--------------------------------------------------------------------------
public
CURRENT_TIMESTAMP : TDatetime;
end;
var
DataModule1: TDataModule1;
implementation
uses Main, ST_DT_SQL_WaitForm;
{$R *.dfm}
procedure TDataModule1.DBAfterRestoreConnect;
begin
MessageDlg('Соединение с базой данных было восстановлено!',
mtInformation, [mbOk], 0 );
Screen.Cursor:=crDefault;
SQL_Wait_Form.Free;
MainForm.StatusBar.Panels[1].Text:='Соединение удачно восстановлено';
end;
procedure TDataModule1.DBLostConnect(Database: TFIBDatabase;
E: EFIBError; var Actions: TOnLostConnectActions);
//var
// i:Integer;
begin
If MessageBox(Application.Handle,PChar('Внимание! Соединение с базой данных потеряно! Попытаться восстановить соединение ?'),'Ошибка сети',MB_YESNO or MB_ICONQUESTION)= mrYes then
begin
MessageDlg('В течение минуты приложение автоматически будет пытаться возобновить соединение. Пожалуйста, подождите...',
mtInformation, [mbOk], 0);
MainForm.Update;
Screen.Cursor:=crHourGlass;
SQL_Wait_Form:= TSQL_Wait_Form.Create(Self);
SQL_Wait_Form.Zapis_Label.Caption:='Восстановление связи';
SQL_Wait_Form.Show;
SQL_Wait_Form.FormStyle:=fsStayOnTop;
SQL_Wait_Form.Update;
Actions := laWaitRestore;
end
else
begin
MessageDlg('Приложение будет закрыто. Обратитесь к администратору сети.',
mtInformation, [mbOk], 0);
Actions := laTerminateApp;
end
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 083042
////////////////////////////////////////////////////////////////////////////////
unit android.media.audiofx.DynamicsProcessing_EqBand;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JDynamicsProcessing_EqBand = interface;
JDynamicsProcessing_EqBandClass = interface(JObjectClass)
['{FE9B5BC6-CDD8-4B44-8FB9-E56C0F42C5D6}']
function getGain : Single; cdecl; // ()F A: $1
function init(cfg : JDynamicsProcessing_EqBand) : JDynamicsProcessing_EqBand; cdecl; overload;// (Landroid/media/audiofx/DynamicsProcessing$EqBand;)V A: $1
function init(enabled : boolean; cutoffFrequency : Single; gain : Single) : JDynamicsProcessing_EqBand; cdecl; overload;// (ZFF)V A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure setGain(gain : Single) ; cdecl; // (F)V A: $1
end;
[JavaSignature('android/media/audiofx/DynamicsProcessing_EqBand')]
JDynamicsProcessing_EqBand = interface(JObject)
['{9C82AAFE-6D7E-413A-817C-3B8D3AC015B3}']
function getGain : Single; cdecl; // ()F A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure setGain(gain : Single) ; cdecl; // (F)V A: $1
end;
TJDynamicsProcessing_EqBand = class(TJavaGenericImport<JDynamicsProcessing_EqBandClass, JDynamicsProcessing_EqBand>)
end;
implementation
end.
|
Program NQUEENS (input, output);
{this program finds one solution to the problem of placing N queens}
{on an NxN chessboard so they are mutually non-attacking}
{written by Ron Danielson based on an algorithm by Niklaus Wirth}
{last modified January 15, 2000}
const N = 8; {number of queens}
type board = record
row: array[1..N] of integer; {row[i] = 0 if no queen on row i}
{otherwise row[i] = column number}
{in which queen is placed}
d1: array[2..2*N] of boolean; {d1[i] = T if no queen on the ith}
{upper-right to lower-left (backward) diagonal}
{row i, column j corresponds to diagonal i+j}
d2: array[1..2*N-1] of boolean; {d2[i] = T if no queen on the ith}
{upper-left to lower-right (forward) diagonal}
{row i, column j corresponds to diagonal N+i-j}
var solution: boolean; {True when solution found}
chessbd: board;
procedure clearboard (var chessbd: board);
var i: integer;
begin
for i := 1 to N do
chessbd.row[i] := 0;
for i := 2 to 2*N do
chessbd.d1[i] := True;
for i := 1 to 2*N-1 do
chessbd.d2[i] := True
end; {clearboard}
procedure placequeen (currow, col: integer; var chessbd: board);
{place queen at board square currow, col}
begin
chessbd.row[currow] := col; {row[i] = column containing queen}
chessbd.d1[currow+col] := False; {mark backward diagonal occupied}
chessbd.d2[N+currow-col] := False {mark forward diagonal occupied}
end; {placequeen}
procedure removequeen (currow, col: integer; var chessbd: board);
{remove queen from board square currow,col}
begin
chessbd.row[currow] := 0;
chessbd.d1[currow+col] := True;
chessbd.d2[N+currow-col] := True
end; {removequeen}
procedure printsoln (chessbd: board);
var currow: integer;
begin
writeln ('One successful queens placement is:');
for currow := 1 to N do
write(currow:2, ',', chessbd.row[currow]:2, '; ');
writeln
end; {printsoln}
procedure trycol (col: integer; var solution: Boolean; var chessbd: board);
{try to place a queen in any row in a given column}
{start with row N, column N and move up and left}
var currow: integer;
begin
currow := N;
repeat
if (chessbd.row[currow] = 0) and chessbd.d1[currow+col] and
chessbd.d2[N+currow-col]
then begin {square currow, col is legal}
placequeen(currow, col, chessbd);
if col > 1 {if not leftmost column}
then trycol(col-1, solution, chessbd) {move left}
else begin
solution := True; {solution found}
printsoln
end;
removequeen(currow, col, chessbd) {backtrack – remove queen placed}
{on currow and try another row}
{in the same column}
end;
currow := currow - 1 {try next row}
until (currow = 0) or solution {if 0, no good place in this column}
{backtrack to next column right by}
{returning from the recursive call}
end; {trycol}
begin
solution := False;
clearboard (chessbd);
trycol(N, solution, chessbd)
end. |
unit Unit17;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Win.ScktComp,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, vcl.printers,
IdExplicitTLSClientServerBase, IdFTP, IdIOHandler, IdIOHandlerStream;
type
TPassThroughData = record
nLen: Word;
Data: array[0..255] of Byte;
end;
type
TForm17 = class(TForm)
Button1: TButton;
Button2: TButton;
IdTCPClient1: TIdTCPClient;
Button3: TButton;
Button4: TButton;
IdFTP1: TIdFTP;
IdIOHandlerStream1: TIdIOHandlerStream;
Button5: TButton;
Memo1: TMemo;
edt_IP: TEdit;
procedure Button1Click(Sender: TObject);
procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure ClientSocket1Connecting(Sender: TObject;
Socket: TCustomWinSocket);
procedure ClientSocket1Connect(Sender: TObject; Socket: TCustomWinSocket);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
procedure PrintText(const s: Ansistring);
public
{ Public-Deklarationen }
end;
var
Form17: TForm17;
implementation
{$R *.dfm}
uses
fmx.printer, rawprinting;
procedure TForm17.Button1Click(Sender: TObject);
begin
{
ClientSocket1.Address := '172.16.10.210';
ClientSocket1.Port := 9100;
//ClientSocket1.Active := true;
ClientSocket1.Open;
}
end;
procedure TForm17.ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
begin
//ShowMessage('connect');
//ClientSocket1.Socket.SendStream()
socket.SendText('~W');
//ClientSocket1.Active := false;
//ClientSocket1.Close;
end;
procedure TForm17.ClientSocket1Connecting(Sender: TObject;
Socket: TCustomWinSocket);
begin
ShowMessage('Connecting');
end;
procedure TForm17.ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
ShowMessage(IntToStr(ErrorCode));
end;
procedure TForm17.Button2Click(Sender: TObject);
var
f : TextFile;
i1: Integer;
begin
RAWPrint('ZDesigner GT800 (ZPL)', '', '~W');
exit;
for i1 := 0 to Printer.Count -1 do
begin
if SameText('ZDesigner GT800 (ZPL)', Printer.Printers[i1].Title) then
begin
Printer.ActivePrinter := Printer.Printers[i1];
break;
end;
end;
AssignPrn(f); // Textfile mit Drucker verbinden
try
Rewrite(f); // Textfile initialisieren
Write(f, '' + #10);
Write(f, 'N'+ #10);
Write(f, 'A30,200,0,4,1,1,N,''' + 'TEXT'''+ #10);
Write(f, 'B30,20,0,1,2,5,50,N,''' + 'BARCODE''' + #10);
Write(f, 'P1'+ #10);
finally
CloseFile(f); // Textdatei schließen
end;
end;
procedure TForm17.Button3Click(Sender: TObject);
var
i1: IntegeR;
begin
for i1 := 0 to Printer.Count -1 do
begin
if SameText('ZDesigner GT800 (ZPL)', Printer.Printers[i1].Title) then
begin
Printer.ActivePrinter := Printer.Printers[i1];
break;
end;
end;
Printer.BeginDoc;
PrintText('~WC'); //statt TextOut
Printer.EndDoc;
end;
procedure TForm17.Button4Click(Sender: TObject);
begin
idftp1.Connect;
idftp1.Put('d:\_a\drucker\Test.zpl');
idftp1.Disconnect;
end;
procedure TForm17.Button5Click(Sender: TObject);
var
List: TStringList;
st: TMemoryStream;
begin
List := TStringList.Create;
st := TMemoryStream.Create;
try
//List.Add('~WC');
{
list.Add(#10);
List.Add('N'+ #10);
List.Add('A30,200,0,4,1,1,N,''' + 'TEXT'''+ #10);
List.Add('B30,20,0,1,2,5,50,N,''' + 'BARCODE''' + #10);
List.Add('P1'+ #10);
}
idftp1.Host := edt_IP.Text;
List.Text := Memo1.Text;
List.SaveToStream(st);
list.SaveToFile('o:\zpl.txt');
st.Position := 0;
try
idftp1.Connect;
except
on e: exception do
begin
showMessage('Connect' + e.Message);
end;
end;
try
idftp1.Put(st, 'test.zpl');
except
on e: exception do
begin
showMessage('Put' + e.Message);
end;
end;
try
idftp1.Disconnect;
except
on e: exception do
begin
showMessage('Desconnect' + e.Message);
end;
end;
finally
FreeAndNil(List);
FreeAndNil(st);
end;
end;
procedure TForm17.PrintText(const s: Ansistring);
var
PTBlock: TPassThroughData;
begin
PTBlock.nLen := Length(s);
StrPCopy(@PTBlock.Data, s);
Escape(vcl.printers.Printer.Handle, PASSTHROUGH, 0, @PTBlock, nil);
end;
end.
|
unit uTypes;
{*******************************************************************************
* *
* Название модуля : *
* *
* uTypes *
* *
* Назначение модуля : *
* *
* Централизованное хранение пользовательских типов, констант и пр. *
* *
* Copyright © Год 2005, Автор: Найдёнов Е.А *
* *
*******************************************************************************}
interface
uses Controls;
type
//Множество чисел
TDigits = Set of '0'..'9';
//Перечисляемый тип, определяющий результат выполнения скриптов
TScriptStatus = ( scsTestErr, scsTestSucc, scsExecErr, scsExecSucc );
const
//System constants
cSCR_STATUS : array [0..Int64( High( TScriptStatus ) )] of ShortString = ( 'Tested with Errors', 'Tested Successfully', 'Executed with Errors', 'Executed Successfully' );
cCLRTF = #13#10;
cPOINT = '.';
cDIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; //Множество натуральных чисел
cCHAR_SET = 'win1251'; //Набор символов, используемый в БД по умолчанию
cANY_FILE = '*.*'; //Маска, для выбора всех файлов
cEMPTY_CHAR = '_'; //Символ, указывающий на пропущенный значащий символ в имени файла скрипта
cDIGITS_EXT = ['-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; //Множество натуральных чисел + знак "-"
cSQL_DIALECT = 3; //SQL диалект, используемый в БД по умолчанию
cDB_FILE_EXT = '.IB'; //Расширение файла БД
cUPDATE_EXPR = 'U'; //Ключевое выражение, показывающее вошел ли скрипт в какое-либо обновление или нет
cSCRIPTS_MASK = '*.sql'; //Маска для файлов скриптов
cINI_FILE_NAME = 'Script.ini'; //Имя конфигурационного файла
cDATE_SEPARATOR = '-'; //Символ-разделитель для даты
cERROR_FILE_NAME = 'AppError.log'; //Имя файла-отчёта об ошибках при выполнении скриптов
cSCRIPT_FILE_EXT = '.sql'; //Расширение файлов скриптов
cDATE_DIGITS_COUNT = 10; //Количество цифр, используемых для представления даты
cFORMAT_DATE_TO_STR = 'yyyy-mm-dd'; //Формат даты для конвертации в строку
cFORMAT_STR_TO_DATE = 'dd.mm.yyyy'; //Формат даты для конвертации из строки в дату
cSCRIPT_EXECUTER_NAME = 'ibescript '; //Имя exe-файла для применения скриптов
cSEPARATOR_FOLDER_WIN = '\'; //Символ-разделитель для Win32-путей
cSEPARATOR_FOLDER_UNX = '/'; //Символ-разделитель для UNIX-путей
cCOMMAND_LINE_ARCHIVATOR = 'winrar e -ac -ad -cgf- -inul -o+ '; //Параметры командной строки для архиватора
cCOMMAND_LINE_SCRIPT_EXEC = ' -S -N -V'; //Параметры командной строки для утилиты выполнения скриптов
cSYSTEM_SCRIPT_ERROR_FILE_NAME = 'SystemScriptErrors.txt'; //Имя файла-отчёта об ошибках при выполнении скриптов
resourcestring
//Captions for dialogs
cMsgErr = 'Error';
cMsgWarn = 'Warning';
cMsgInfo = 'Information';
cMsgConf = 'Confirmation';
cTEST_EXPR = 'TEST';
cEXECUTE_EXPR = 'EXEC';
cDESCRIPTION_STR = 'Testing scripts for '' ';
cSCRIPT_STATUS_ERROR = 'Error';
cSCRIPT_STATUS_SUCCESS = 'Success';
//Section Names
cTEST_PARAMS = 'Test Params'; //Название секции конфигурационного INI - файла
cUSELESS_SECTION = 'Useless Sections'; //Название секции конфигурационного INI - файла
//Key Names
//Basic
cUSER = 'User'; //Название ключа в секции конфигурационного INI - файла
cSERVER = 'Server'; //Название ключа в секции конфигурационного INI - файла
cPASSWORD = 'Password'; //Название ключа в секции конфигурационного INI - файла
//Regular
cPATH = 'Path'; //Название ключа в секции конфигурационного INI - файла
cKEY_EXPR = 'KeyExpr'; //Название ключа в секции конфигурационного INI - файла
//Config
cRENAME = 'Rename'; //Название ключа в секции конфигурационного INI - файла
cEXECUTE = 'Execute'; //Название ключа в секции конфигурационного INI - файла
cDATE_BEG = 'DateBeg'; //Название ключа в секции конфигурационного INI - файла
cDATE_END = 'DateEnd'; //Название ключа в секции конфигурационного INI - файла
cFULL_RENAME = 'FullRename'; //Название ключа в секции конфигурационного INI - файла
cSYSTEM_SCRIPT = 'SystemScript'; //Название ключа в секции конфигурационного INI - файла
cERROR_LOG_DIR = 'ErrorLogDir'; //Название ключа в секции конфигурационного INI - файла
cIBESCRIPT_PATH = 'IBEScriptPath'; //Название ключа в секции конфигурационного INI - файла
cDB_PATH_BACKUP = 'DBPathBackUp'; //Название ключа в секции конфигурационного INI - файла
cSEPARATOR_CHAR = 'SeparatorChar'; //Название ключа в секции конфигурационного INI - файла
cARCHIVATOR_PATH = 'ArchivatorPath'; //Название ключа в секции конфигурационного INI - файла
cDB_PATH_COPY_TO = 'DBPathCopyTo'; //Название ключа в секции конфигурационного INI - файла
cBACKUP_DAYS_COUNT = 'BackUpDaysCount'; //Название ключа в секции конфигурационного INI - файла
cERROR_SCRIPT_CHAR = 'ErrorScriptChar'; //Название ключа в секции конфигурационного INI - файла
cPREFIX_CHAR_COUNT = 'PrefixCharCount'; //Название ключа в секции конфигурационного INI - файла
cDEFAULT_DB_FILE_NAME = 'DefaultDBFileName'; //Название ключа в секции конфигурационного INI - файла
cSCRIPTS_PATH_COPY_FROM = 'ScriptPathCopyFrom'; //Название ключа в секции конфигурационного INI - файла
cDB_ARCHIVE_FILE_NAME_PART = 'DBArchiveFileNamePart'; //Название ключа в секции конфигурационного INI - файла
//Default section key values
cDEF_USER = 'sysdba';
cDEF_SERVER = 'localhost';
cDEF_RENAME = '0';
cDEF_EXECUTE = '0';
cDEF_PASSWORD = 'masterkey';
cDEF_FULL_RENAME = '0';
cDEF_ERROR_LOG_DIR = 'Errors';
cDEF_SEPARATOR_CHAR = '=';
cDEF_IBESCRIPT_PATH = 'C:\Program Files\IB Expert 2.0\ibescript.exe';
cDEF_DB_PATH_COPY_TO = 'D:\TestDB';
cDEF_ARCHIVATOR_PATH = 'C:\Program Files\WinRaR\winrar.exe';
cDEF_BACKUP_DAYS_COUNT = '1';
cDEF_ERROR_SCRIPT_CHAR = '#';
cDEF_PREFIX_CHAR_COUNT = '13';
cDEF_DEFAULT_DB_FILE_NAME = 'FULL_DB.IB';
cDEF_SCRIPTS_PATH_COPY_FROM = 'D:\FMAS-WIN\DataBase';
cDEF_DB_ARCHIVE_FILE_NAME_PART = 'RESTORE.IB';
//Status bar's messages
cSPACE = '';
cCOPYING_FILES = 'Copying files...';
cEXTRACTING_FILES = 'Extracting files...';
cEXECUTING_SCRIPTS = 'Executing scripts...';
//Messages
cAPP_EXIT = 'File ''' + cINI_FILE_NAME + ''' is not found' + cCLRTF + 'Application finished and closing';
cCONVERT_ERROR = 'Invalid type convertion: ';
cQUIT_QUESTION = 'Are you shure you wish to quit IBScript Executer?';
cTEST_SCRIPT_STR = 'Script TESTED SUCCESSFULLY!';
cCONVERT_DATE_ERR = 'can''t convert string to date' + cCLRTF + 'Check format of config parameters ''DateBeg'' and ''DateEnd''';
cSCRIPTS_NOT_FOUND = 'There are NO SCRIPTS for testing!';
cAPP_RESULT_OK_MSG = 'ALL Scripts tested and executed SUCCESSFULLY!';
cAPP_RESULT_ERR_MSG = 'SOME Scripts have ERRORS!';
cEXECUTE_SCRIPT_STR = 'Scripts TESTED and EXECUTED SUCCESSFULLY!';
cDB_FILE_NOT_FOUND1 = 'Testing scripts finished abnormally!';
cDB_FILE_NOT_FOUND2 = 'Check files for testing or pathes for them.';
cINI_FILE_NOT_FOUND = 'Can''t find ''' + cINI_FILE_NAME + ''' file' + cCLRTF + 'Do you want to find it?';
cPREPARE_SCRIPT_ERR = 'During Preparing Data Base file for testing one of scripts have been executed with ERRORS!';
cSUCCESS_EXEC_RESULT = 'Script executed successfully';
cINI_FILE_WAS_REMOVED = 'File ''' + cINI_FILE_NAME + ''' was removed or deleted' + cCLRTF + 'Try to use ''Create Test List'' menu item';
cTEST_SCRIPT_STR_ERR = 'Scripts TESTED with ERRORS!';
cEXECUTE_SCRIPT_STR_ERR = 'Scripts EXECUTED with ERRORS!';
cEXEC_SYS_SCRIPT_STR_ERR = 'SYSTEM SCRIPT EXECUTED with ERRORS!';
cEXEC_SYS_SCRIPT_STR_SUCC = 'SYSTEM SCRIPT EXECUTED SUCCESSFULLY!';
cDONT_EXEC_SYS_SCRIPT_STR = 'SYSTEM SCRIPT DON''T EXECUTE,'#13'because ALL scripts are only TESTED!';
type
//Перечисляемый тип, определяющий режим запуска программы
TAppMode = ( amNone, amWin, amCmd );
//Перечисляемый тип, определяющий режим запуска программы
TAppResult = ( arNone, arBackUpFileNotFound, arScrNotFound, arPrepareError, arPrepareSuccess, arTestSuccess, arExecSuccess, arTestError, arExecError );
//Перечисляемый тип, определяющий режим сортировки файлов скриптов
TSortMode = ( smAlphabetically, smDate, smOrder );
//Структура, содержащая параметры для тестирования скриптов
TScriptParams = packed record
KeyExpr : String;
ScriptDir : String;
SeparatorChar : String;
PrefixCharCount : Integer;
ExtModeEnabled : Boolean;
DateBeg : TDate;
DateEnd : TDate;
end;
implementation
end.
|
unit CFPageControl;
interface
uses
Windows, Classes, Controls, Messages, Graphics, ImgList, Menus;
type
TCFButtonState = (cbsDown, cbsMouseIn);
TCFButtonStates = set of TCFButtonState;
TCFPageButton = class(TObject)
strict private
FRect: TRect;
FImageIndex, FHotImageIndex, FDownImageIndex: Integer;
FState: TCFButtonStates;
FOnClick, FOnUpdateView: TNotifyEvent;
procedure DoUpdateView;
procedure SetImageIndex(const Value: Integer);
procedure SetHotImageIndex(const Value: Integer);
procedure SetDownImageIndex(const Value: Integer);
public
constructor Create;
procedure MouseDown;
procedure MouseUp;
procedure MouseEnter;
procedure MouseLeave;
procedure KillFocus;
property ImageIndex: Integer read FImageIndex write FImageIndex;
property HotImageIndex: Integer read FHotImageIndex write FHotImageIndex;
property DownImageIndex: Integer read FDownImageIndex write SetDownImageIndex;
property Rect: TRect read FRect write FRect;
property State: TCFButtonStates read FState;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property OnUpdateView: TNotifyEvent read FOnUpdateView write FOnUpdateView;
end;
TCFPageControl = class;
TCFPage = class;
TPageButtonEvent = procedure(const APage: TCFPage; const AButton: TCFPageButton) of object;
TCFPage = class(TObject)
strict private
FText: string;
FWidth: Integer;
FTextSize: TSize;
FImageIndex: Integer;
FMouseIn, FActive: Boolean;
FButtons: TList;
FHotButton: TCFPageButton;
FControl: TWinControl;
FPageControl: TCFPageControl;
FOnSetControl: TNotifyEvent;
FOnUpdateView: TNotifyEvent;
FOnImageIndexChanged: TNotifyEvent;
FOnResize: TNotifyEvent;
FOnButtonClick: TPageButtonEvent;
procedure DoButtonClick(Sender: TObject);
procedure DoButtonUpdateView(Sender: TObject);
procedure DoSetControl;
procedure DoUpdateView;
procedure DoImageIndexChanged;
procedure DoResize;
procedure CalcWidth;
function GetButtonAt(const X, Y: Integer): TCFPageButton;
procedure SetText(const AText: string);
procedure SetActive(const Value: Boolean);
procedure SetControl(const AControl: TWinControl);
procedure SetImageIndex(const Value: Integer);
public
Data: TObject;
constructor Create; virtual;
destructor Destroy; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure MouseMove(Shift: TShiftState; X, Y: Integer);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure MouseEnter;
procedure MouseLeave;
procedure PintTo(const ACanvas: TCanvas);
function AddButton: TCFPageButton;
procedure KillFocus;
property Text: string read FText write SetText;
property Control: TWinControl read FControl write SetControl;
property Width: Integer read FWidth;
property Active: Boolean read FActive write SetActive;
property ImageIndex: Integer read FImageIndex write SetImageIndex;
property PageControl: TCFPageControl read FPageControl write FPageControl;
property OnSetControl: TNotifyEvent read FOnSetControl write FOnSetControl;
property OnUpdateView: TNotifyEvent read FOnUpdateView write FOnUpdateView;
property OnImageIndexChanged: TNotifyEvent read FOnImageIndexChanged write FOnImageIndexChanged;
property OnResize: TNotifyEvent read FOnResize write FOnResize;
property OnButtonClick: TPageButtonEvent read FOnButtonClick write FOnButtonClick;
end;
TPageList = class(TList)
private
FOnCountChanged: TNotifyEvent;
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
property OnCountChanged: TNotifyEvent read FOnCountChanged write FOnCountChanged;
end;
TControlButton = (cbnNone, cbnMenu, cbnLeft, cbnRight);
TPageControlButtonEvent = procedure(const APageIndex: Integer; const AButton: TCFPageButton) of object;
TCFPageControl = class(TCustomControl) // TGraphicControl
strict private
FPageHeight, FPagePadding, FPageIndex, FHotPageIndex, FUpdateCount: Integer;
FOffset, FPageClientRight: Integer;
FHotControlBtn: TControlButton;
FScrollBtnVisible, FScrolling, FBorderVisible: Boolean;
FPages: TPageList;
FImages: TCustomImageList;
FPagePopupMenu: TPopupMenu;
FActivePageColor: TColor;
FBackGroundText: string;
FOnChange: TNotifyEvent;
FOnPageButtonClick: TPageControlButtonEvent;
procedure DoPageSetControl(Sender: TObject);
procedure DoPageUpateView(Sender: TObject);
procedure DoImageIndexChanged(Sender: TObject);
procedure DoPageResize(Sender: TObject);
procedure DoPageMenuClick(Sender: TObject);
procedure DoPageButtonClick(const APage: TCFPage; const AButton: TCFPageButton);
procedure DoChange;
procedure DoPageCountChanged(Sender: TObject);
function GetCount: Integer;
function GetPageAt(const X, Y: Integer): Integer; overload;
function GetPageAt(const X, Y: Integer; var ARect: TRect): Integer; overload;
function GetPageIndex(const APage: TCFPage): Integer;
function GetPageRect(const APage: TCFPage): TRect; overload;
function GetPageRect(const APageIndex: Integer): TRect; overload;
function GetPageMenuIndex(const APageIndex: Integer): Integer;
function GetButtonsRectWidth: Integer;
procedure AddPageMenu(const APageIndex: Integer);
procedure DeletePageMenu(const APageIndex: Integer);
procedure FreeAllPages;
procedure CalcPageClientRight;
procedure ControlButtonMouseMove(const X, Y: Integer);
procedure SetHotControlBtn(const AControlBtn: TControlButton);
procedure SetPageMenuImageIndex(const APage: TCFPage);
procedure SetActivePageIndex(const AIndex: Integer);
procedure SetPageHeight(const Value: Integer);
procedure SetBorderVisible(const Value: Boolean);
procedure SetActivePageColor(const Value: TColor);
procedure SetImages(const Value: TCustomImageList);
procedure SetBackGroundText(const Value: string);
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure UpdateView(const ARect: TRect); overload;
procedure UpdateView; overload;
procedure DeletePage(const AIndex: Integer); overload;
procedure DeletePage(const APage: TCFPage); overload;
function AddPage(const AText: string; const AControl: TWinControl = nil): TCFPage;
function ActivePage: TCFPage;
function GetPage(Index: Integer): TCFPage;
procedure Clear;
procedure BeginUpdate;
procedure EndUpdate;
property Count: Integer read GetCount;
property PageIndex: Integer read FPageIndex write SetActivePageIndex;
property Pages[Index: Integer]: TCFPage read GetPage; default;
published
property PageHeight: Integer read FPageHeight write SetPageHeight;
property Images: TCustomImageList read FImages write SetImages;
property BackGroundText: string read FBackGroundText write SetBackGroundText;
property ActivePageColor: TColor read FActivePageColor write SetActivePageColor;
property BorderVisible: Boolean read FBorderVisible write SetBorderVisible;
property OnPageButtonClick: TPageControlButtonEvent read FOnPageButtonClick write FOnPageButtonClick;
property Color;
end;
function CreateCanvas(const AFontSize: Integer): TCanvas;
procedure DestroyCanvas(const ACanvas: TCanvas);
implementation
{$R CFPageControl.RES}
const
CustomPadding = 5;
ButtonImageWidth = 16;
function CreateCanvas(const AFontSize: Integer): TCanvas;
var
vDC: HDC;
begin
vDC := CreateCompatibleDC(0);
Result := TCanvas.Create;
Result.Handle := vDC;
Result.Font.Size := AFontSize;
end;
procedure DestroyCanvas(const ACanvas: TCanvas);
var
vDC: HDC;
begin
vDC := ACanvas.Handle;
ACanvas.Handle := 0;
ACanvas.Free;
DeleteDC(vDC);
end;
{ TCFPageControl }
function TCFPageControl.ActivePage: TCFPage;
begin
Result := nil;
if (FPageIndex >= 0) then
Result := TCFPage(FPages[FPageIndex]);
end;
function TCFPageControl.AddPage(const AText: string; const AControl: TWinControl = nil): TCFPage;
var
vPageIndex: Integer;
begin
Result := TCFPage.Create;
Result.PageControl := Self;
Result.OnSetControl := DoPageSetControl;
Result.OnButtonClick := DoPageButtonClick;
Result.OnImageIndexChanged := DoImageIndexChanged;
Result.OnResize := DoPageResize;
Result.OnUpdateView := DoPageUpateView;
Result.Text := AText;
Result.Control := AControl;
if not AControl.Visible then
AControl.Visible := True;
vPageIndex := FPages.Add(Result);
SetActivePageIndex(vPageIndex);
AddPageMenu(vPageIndex);
end;
procedure TCFPageControl.AddPageMenu(const APageIndex: Integer);
var
vMenuItem: TMenuItem;
begin
vMenuItem := TMenuItem.Create(FPagePopupMenu);
vMenuItem.Caption := TCFPage(FPages[APageIndex]).Text;
vMenuItem.ImageIndex := TCFPage(FPages[APageIndex]).ImageIndex;
vMenuItem.Tag := APageIndex;
vMenuItem.OnClick := DoPageMenuClick;
FPagePopupMenu.Items.Add(vMenuItem);
end;
procedure TCFPageControl.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TCFPageControl.CalcPageClientRight;
var
i, vWidth: Integer;
vRect: TRect;
begin
vWidth := 0;
for i := 0 to FPages.Count - 1 do
vWidth := vWidth + TCFPage(FPages[i]).Width + FPagePadding;
FScrollBtnVisible := vWidth > (Width - ButtonImageWidth);
FPageClientRight := Width - GetButtonsRectWidth;
if FPages.Count > 0 then
begin
vRect := GetPageRect(FPages.Count - 1);
if vRect.Right < FPageClientRight then
begin
FOffset := FOffset - (FPageClientRight - vRect.Right);
if FOffset < 0 then
FOffset := 0;
end;
end;
end;
procedure TCFPageControl.Clear;
begin
FPageIndex := -1;
FPages.Clear;
end;
procedure TCFPageControl.CMMouseLeave(var Message: TMessage);
begin
if FHotPageIndex >= 0 then
TCFPage(FPages[FHotPageIndex]).MouseLeave;
FHotPageIndex := -1;
SetHotControlBtn(cbnNone);
inherited;
end;
procedure TCFPageControl.ControlButtonMouseMove(const X, Y: Integer);
var
vControlBtn: TControlButton;
vX: Integer;
begin
vControlBtn := cbnNone;
vX := X - FPageClientRight;
if FScrollBtnVisible then // 左右切换按钮显示
begin
if (vX > ButtonImageWidth * 2) and (vX < ButtonImageWidth * 3) then
vControlBtn := cbnMenu
else
if (vX > ButtonImageWidth) and (vX < ButtonImageWidth * 2) then
vControlBtn := cbnRight
else
if (vX > 0) and (vX < ButtonImageWidth) then
vControlBtn := cbnLeft;
end
else // 只有菜单按钮显示
if (vX > 0) and (vX < ButtonImageWidth) then
vControlBtn := cbnMenu;
SetHotControlBtn(vControlBtn);
end;
constructor TCFPageControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPageIndex := -1;
FHotPageIndex := -1;
FOffset := 0;
FUpdateCount := 0;
FScrollBtnVisible := False;
FBorderVisible := True;
FScrolling := False;
FHotControlBtn := cbnNone;
FPageHeight := 24;
FPagePadding := 10;
FPages := TPageList.Create;
FPages.OnCountChanged := DoPageCountChanged;
FActivePageColor := clWhite;
Self.Width := 300;
Self.Height := FPageHeight;
Self.DoubleBuffered := True;
FPagePopupMenu := TPopupMenu.Create(Self);
//Self.Color := clRed;
end;
procedure TCFPageControl.DeletePage(const APage: TCFPage);
var
i: Integer;
begin
for i := 0 to FPages.Count - 1 do
begin
if APage = TCFPage(FPages[i]) then
begin
DeletePage(i);
Break;
end;
end;
end;
procedure TCFPageControl.DeletePage(const AIndex: Integer);
var
vPageIndex: Integer;
begin
//CalcPageClientRight;
vPageIndex := FPageIndex;
if vPageIndex >= AIndex then
vPageIndex := vPageIndex - 1;
DeletePageMenu(GetPageMenuIndex(AIndex));
TCFPage(FPages[AIndex]).Free;
FPages.Delete(AIndex);
if (vPageIndex < 0) and (FPages.Count > 0) then // 激活第0个,删除第0个
begin
vPageIndex := 0;
FPageIndex := -1;
end;
if vPageIndex <> FPageIndex then
SetActivePageIndex(vPageIndex);
FHotPageIndex := vPageIndex;
UpdateView;
end;
procedure TCFPageControl.DeletePageMenu(const APageIndex: Integer);
var
i: Integer;
begin
if (APageIndex >= 0) and (APageIndex < FPagePopupMenu.Items.Count) then
begin
FPagePopupMenu.Items.Delete(APageIndex);
if APageIndex < FPagePopupMenu.Items.Count then
begin
for i := APageIndex to FPagePopupMenu.Items.Count - 1 do
FPagePopupMenu.Items[i].Tag := FPagePopupMenu.Items[i].Tag - 1;
end;
end;
end;
destructor TCFPageControl.Destroy;
begin
FreeAllPages;
FPages.Free;
FPagePopupMenu.Free;
inherited Destroy;
end;
procedure TCFPageControl.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TCFPageControl.DoImageIndexChanged(Sender: TObject);
begin
SetPageMenuImageIndex(Sender as TCFPage);
end;
procedure TCFPageControl.DoPageButtonClick(const APage: TCFPage;
const AButton: TCFPageButton);
var
vPageIndex: Integer;
begin
if Assigned(FOnPageButtonClick) then
begin
vPageIndex := GetPageIndex(APage);
FOnPageButtonClick(vPageIndex, AButton);
end;
end;
procedure TCFPageControl.DoPageCountChanged(Sender: TObject);
begin
CalcPageClientRight;
end;
procedure TCFPageControl.DoPageMenuClick(Sender: TObject);
var
vPageIndex: Integer;
begin
if Sender is TMenuItem then
begin
vPageIndex := (Sender as TMenuItem).Tag;
if (vPageIndex >= 0) and (vPageIndex <> FPageIndex) then
SetActivePageIndex(vPageIndex);
end;
end;
procedure TCFPageControl.DoPageResize(Sender: TObject);
begin
FOffset := 0;
SetActivePageIndex(FPageIndex);
UpdateView;
end;
procedure TCFPageControl.DoPageSetControl(Sender: TObject);
begin
// if Sender is TWinControl then
// (Sender as TWinControl).Parent := Self;
end;
procedure TCFPageControl.DoPageUpateView(Sender: TObject);
var
vRect: TRect;
begin
vRect := GetPageRect(Sender as TCFPage);
UpdateView(vRect);
end;
procedure TCFPageControl.EndUpdate;
begin
if FUpdateCount > 0 then
Dec(FUpdateCount);
if FUpdateCount = 0 then
UpdateView;
end;
procedure TCFPageControl.FreeAllPages;
var
i: Integer;
begin
for i := 0 to FPages.Count - 1 do
TCFPage(FPages[i]).Free;
end;
function TCFPageControl.GetPageAt(const X, Y: Integer): Integer;
var
vRect: TRect;
begin
Result := GetPageAt(X, Y, vRect);
end;
function TCFPageControl.GetButtonsRectWidth: Integer;
begin
if FScrollBtnVisible then
Result := ButtonImageWidth * 3
else
Result := ButtonImageWidth;
end;
function TCFPageControl.GetCount: Integer;
begin
Result := FPages.Count;
end;
function TCFPageControl.GetPage(Index: Integer): TCFPage;
begin
Result := FPages[Index];
end;
function TCFPageControl.GetPageAt(const X, Y: Integer; var ARect: TRect): Integer;
var
i, vLeft: Integer;
vPage: TCFPage;
begin
Result := -1;
SetRectEmpty(ARect);
vLeft := -FOffset;
for i := 0 to FPages.Count - 1 do
begin
vPage := TCFPage(FPages[i]);
ARect := Bounds(vLeft, 0, vPage.Width, FPageHeight);
if PtInRect(ARect, Point(X, Y)) then
begin
Result := i;
Break;
end;
vLeft := vLeft + vPage.Width + FPagePadding;
end;
end;
function TCFPageControl.GetPageIndex(const APage: TCFPage): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to FPages.Count - 1 do
begin
if APage = FPages[i] then
begin
Result := i;
Break;
end;
end;
end;
function TCFPageControl.GetPageMenuIndex(const APageIndex: Integer): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to FPagePopupMenu.Items.Count - 1 do
begin
if FPagePopupMenu.Items[i].Tag = APageIndex then
begin
Result := i;
Break;
end;
end;
end;
function TCFPageControl.GetPageRect(const APageIndex: Integer): TRect;
begin
Result := GetPageRect(TCFPage(FPages[APageIndex]));
end;
function TCFPageControl.GetPageRect(const APage: TCFPage): TRect;
var
i, vLeft: Integer;
begin
SetRectEmpty(Result);
vLeft := -FOffset;
for i := 0 to FPages.Count - 1 do
begin
if TCFPage(FPages[i]) = APage then
begin
Result := Bounds(vLeft, 0, APage.Width, FPageHeight);
Break;
end;
vLeft := vLeft + TCFPage(FPages[i]).Width + FPagePadding;
end;
end;
procedure TCFPageControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vPageIndex: Integer;
vRect: TRect;
begin
inherited MouseDown(Button, Shift, X, Y);
FScrolling := False;
if not Self.Focused then
Self.SetFocus;
if PtInRect(Bounds(0, 0, Width, FPageHeight), Point(X, Y)) then
begin
vRect := Bounds(FPageClientRight, 0, GetButtonsRectWidth, FPageHeight); // 菜单按钮区域
if PtInRect(vRect, Point(X, Y)) then // 点在了按钮区域
Exit;
vPageIndex := GetPageAt(X, Y, vRect);
if (vPageIndex >= 0) and (vPageIndex <> FPageIndex) then
SetActivePageIndex(vPageIndex);
if (not FScrolling) and (vPageIndex >= 0) then
TCFPage(FPages[vPageIndex]).MouseDown(Button, Shift, X - vRect.Left, Y - vRect.Top);
end;
end;
procedure TCFPageControl.MouseMove(Shift: TShiftState; X, Y: Integer);
var
vRect: TRect;
vPageIndex: Integer;
begin
if PtInRect(Bounds(0, 0, Width, FPageHeight), Point(X, Y)) then
begin
vRect := Bounds(FPageClientRight, 0, GetButtonsRectWidth, FPageHeight); // 菜单按钮区域
if PtInRect(vRect, Point(X, Y)) then // 在按钮区域
begin
vPageIndex := -1;
ControlButtonMouseMove(X, Y);
end
else
begin
vPageIndex := GetPageAt(X, Y, vRect);
SetHotControlBtn(cbnNone);
end;
if vPageIndex <> FHotPageIndex then // 鼠标新移入的和原鼠标位置的不是同一个Page
begin
if FHotPageIndex >= 0 then // 如果原鼠标处有Page
TCFPage(FPages[FHotPageIndex]).MouseLeave;
FHotPageIndex := vPageIndex;
if FHotPageIndex >= 0 then // 当前鼠标处有有效的Page
TCFPage(FPages[FHotPageIndex]).MouseEnter;
end;
if FHotPageIndex >= 0 then // 当前鼠标处有有效的Page
TCFPage(FPages[FHotPageIndex]).MouseMove(Shift, X - vRect.Left, Y - vRect.Top);
end
else // 鼠标移出,由CMMouseLeave处理
FHotPageIndex := -1;
inherited MouseMove(Shift, X, Y);
end;
procedure TCFPageControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vPageIndex: Integer;
vRect: TRect;
vPt: TPoint;
begin
if PtInRect(Bounds(0, 0, Width, FPageHeight), Point(X, Y)) then
begin
vRect := Bounds(FPageClientRight, 0, GetButtonsRectWidth, FPageHeight); // 菜单按钮区域
if PtInRect(vRect, Point(X, Y)) then // 点在了按钮区域
begin
case FHotControlBtn of
cbnNone: ;
cbnMenu:
begin
vPt := Point(vRect.Left, FPageHeight);
vPt := ClientToScreen(vPt);
FPagePopupMenu.Popup(vPt.X, vPt.Y);
end;
cbnLeft:
begin
if FPageIndex > 0 then
SetActivePageIndex(FPageIndex - 1);
end;
cbnRight:
begin
if FPageIndex < FPages.Count - 1 then
SetActivePageIndex(FPageIndex + 1);
end;
end;
Exit;
end;
vPageIndex := GetPageAt(X, Y, vRect);
if (not FScrolling) and (vPageIndex >= 0) then
TCFPage(FPages[vPageIndex]).MouseUp(Button, Shift, X - vRect.Left, Y - vRect.Top);
end;
inherited MouseUp(Button, Shift, X, Y);
end;
procedure TCFPageControl.Paint;
var
i, vLeft, vSaveIndex: Integer;
vRect: TRect;
vPage: TCFPage;
vBmp: TBitmap;
begin
inherited Paint;
Canvas.Font.Color := Font.Color;
Canvas.Brush.Color := Self.Color;
Canvas.FillRect(ClientRect);
if FBorderVisible then // 绘制整个底边框
begin
Canvas.Pen.Color := $005A5A5A;
Canvas.MoveTo(0, FPageHeight - 1);
Canvas.LineTo(Width, FPageHeight - 1);
end;
vLeft := -FOffset;
for i := 0 to FPages.Count - 1 do
begin
if vLeft > FPageClientRight then
Break;
vPage := TCFPage(FPages[i]);
if i = FPageIndex then // 当前激活的压住底部边框线
vRect := Bounds(vLeft, 0, vPage.Width, FPageHeight)
else
vRect := Bounds(vLeft, 0, vPage.Width, FPageHeight - 1);
if vRect.Right > 0 then
begin
if i = FPageIndex then
Canvas.Brush.Color := FActivePageColor
else
Canvas.Brush.Color := Self.Color;
Canvas.FillRect(vRect); // 填充Page标签区域
vSaveIndex := SaveDC(Canvas.Handle);
try
MoveWindowOrg(Canvas.Handle, vLeft, 0);
IntersectClipRect(Canvas.Handle, 0, 0, vPage.Width, FPageHeight - 1);
vPage.PintTo(Canvas);
finally
RestoreDC(Canvas.Handle, vSaveIndex);
end;
if (i = FPageIndex) and FBorderVisible then // 当前页绘制边框线
begin
Canvas.MoveTo(vRect.Left, vRect.Bottom);
Canvas.LineTo(vRect.Left, vRect.Top);
Canvas.LineTo(vRect.Right - 1, vRect.Top);
Canvas.LineTo(vRect.Right - 1, vRect.Bottom);
end;
end;
vLeft := vLeft + vPage.Width + FPagePadding;
end;
if FBackGroundText <> '' then
begin
vSaveIndex := SaveDC(Canvas.Handle);
try
Canvas.Font.Color := clGrayText;
Canvas.Brush.Style := bsClear;
Canvas.TextOut(vLeft, (FPageHeight - Canvas.TextHeight('H')) div 2, FBackGroundText);
finally
RestoreDC(Canvas.Handle, vSaveIndex);
end;
end;
// 填充切换和菜单按钮背景区域
Canvas.Brush.Color := Self.Color;
vRect := Bounds(FPageClientRight, 0, GetButtonsRectWidth, Height - 1);
Canvas.FillRect(vRect);
vBmp := TBitmap.Create;
try
vBmp.Transparent := True;
// 绘制切换按钮
if FScrollBtnVisible then
begin
if FHotControlBtn = cbnLeft then
vBmp.LoadFromResourceName(HInstance, 'LEFTHOT')
else
vBmp.LoadFromResourceName(HInstance, 'LEFTNOR'); // 绘制左按钮
Canvas.Draw(vRect.Left, (FPageHeight - ButtonImageWidth) div 2, vBmp);
vRect.Left := vRect.Left + ButtonImageWidth;
if FHotControlBtn = cbnRight then
vBmp.LoadFromResourceName(HInstance, 'RIGHTHOT')
else
vBmp.LoadFromResourceName(HInstance, 'RIGHTNOR'); // 绘制右按钮
Canvas.Draw(vRect.Left, (FPageHeight - ButtonImageWidth) div 2, vBmp);
vRect.Left := vRect.Left + ButtonImageWidth;
end;
if FHotControlBtn = cbnMenu then
vBmp.LoadFromResourceName(HInstance, 'DOWNHOT')
else
vBmp.LoadFromResourceName(HInstance, 'DOWNNOR'); // 绘制菜单按钮
Canvas.Draw(vRect.Left, (FPageHeight - ButtonImageWidth) div 2, vBmp);
finally
vBmp.Free;
end;
end;
procedure TCFPageControl.SetActivePageColor(const Value: TColor);
begin
if FActivePageColor <> Value then
begin
FActivePageColor := Value;
if Self.HandleAllocated then
UpdateView;
end;
end;
procedure TCFPageControl.SetActivePageIndex(const AIndex: Integer);
procedure ResetPage;
var
vRect: TRect;
begin
if FPageIndex < 0 then Exit;
vRect := GetPageRect(FPageIndex);
if vRect.Right > FPageClientRight then
begin
FScrolling := True;
FOffset := vRect.Right + FOffset - FPageClientRight;
UpdateView;
end
else
if vRect.Left < 0 then
begin
FScrolling := True;
FOffset := FOffset + vRect.Left;
UpdateView;
end;
end;
var
vOldIndex: Integer;
begin
if FPageIndex <> AIndex then
begin
vOldIndex := FPageIndex;
FPageIndex := AIndex;
if (vOldIndex >= 0) and (vOldIndex < FPages.Count) then
TCFPage(FPages[vOldIndex]).Active := False;
if FPageIndex >= 0 then
begin
TCFPage(FPages[FPageIndex]).Active := True;
ResetPage;
end;
DoChange;
end
else
ResetPage;
end;
procedure TCFPageControl.SetBackGroundText(const Value: string);
begin
if FBackGroundText <> Value then
begin
FBackGroundText := Value;
if Self.HandleAllocated then
UpdateView;
end;
end;
procedure TCFPageControl.SetBorderVisible(const Value: Boolean);
begin
if FBorderVisible <> Value then
begin
FBorderVisible := Value;
if Self.HandleAllocated then
UpdateView;
end;
end;
procedure TCFPageControl.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
CalcPageClientRight;
end;
procedure TCFPageControl.SetHotControlBtn(const AControlBtn: TControlButton);
begin
if AControlBtn <> FHotControlBtn then
begin
FHotControlBtn := AControlBtn;
UpdateView(Rect(Width - GetButtonsRectWidth, 0, Width, FPageHeight))
end;
end;
procedure TCFPageControl.SetImages(const Value: TCustomImageList);
begin
FImages := Value;
FPagePopupMenu.Images := FImages;
end;
procedure TCFPageControl.SetPageHeight(const Value: Integer);
begin
if FPageHeight <> Value then
begin
FPageHeight := Value;
Self.Height := Value;
if Self.HandleAllocated then
UpdateView;
end;
end;
procedure TCFPageControl.SetPageMenuImageIndex(const APage: TCFPage);
var
vIndex: Integer;
begin
vIndex := GetPageIndex(APage);
if vIndex >= 0 then
begin
vIndex := GetPageMenuIndex(vIndex);
if vIndex >= 0 then
FPagePopupMenu.Items[vIndex].ImageIndex := APage.ImageIndex;
end;
end;
procedure TCFPageControl.UpdateView(const ARect: TRect);
begin
if FUpdateCount = 0 then
begin
InvalidateRect(Handle, ARect, False);
UpdateWindow(Handle);
end;
end;
procedure TCFPageControl.UpdateView;
begin
UpdateView(ClientRect);
end;
procedure TCFPageControl.WMKillFocus(var Message: TWMKillFocus);
begin
inherited;
if (FPageIndex >= 0) then
ActivePage.KillFocus;
end;
{ TCFPage }
function TCFPage.AddButton: TCFPageButton;
begin
Result := TCFPageButton.Create;
Result.OnClick := DoButtonClick;
Result.OnUpdateView := DoButtonUpdateView;
FButtons.Add(Result);
CalcWidth;
end;
procedure TCFPage.CalcWidth;
var
vCanvas: TCanvas;
vWidth: Integer;
begin
vCanvas := CreateCanvas(FPageControl.Font.Size);
try
FTextSize := vCanvas.TextExtent(FText);
vWidth := FTextSize.cx + CustomPadding + CustomPadding;
vWidth := vWidth + FButtons.Count * (ButtonImageWidth + CustomPadding);
if FImageIndex >= 0 then
vWidth := vWidth + FPageControl.Images.Width + CustomPadding;
if vWidth <> FWidth then
begin
FWidth := vWidth;
DoResize;
end;
finally
DestroyCanvas(vCanvas);
end;
end;
constructor TCFPage.Create;
begin
inherited Create;
FButtons := TList.Create;
FImageIndex := -1;
FHotButton := nil;
FMouseIn := False;
end;
destructor TCFPage.Destroy;
var
i: Integer;
begin
for i := 0 to FButtons.Count - 1 do
TCFPageButton(FButtons[i]).Free;
inherited Destroy;
end;
procedure TCFPage.DoButtonClick(Sender: TObject);
begin
if Assigned(FOnButtonClick) then
FOnButtonClick(Self, Sender as TCFPageButton);
end;
procedure TCFPage.DoButtonUpdateView(Sender: TObject);
begin
DoUpdateView;
end;
procedure TCFPage.DoImageIndexChanged;
begin
if Assigned(FOnImageIndexChanged) then
FOnImageIndexChanged(Self);
end;
procedure TCFPage.DoResize;
begin
if Assigned(FOnResize) then
FOnResize(Self);
end;
procedure TCFPage.DoSetControl;
begin
if Assigned(FOnSetControl) then
FOnSetControl(FControl);
end;
procedure TCFPage.DoUpdateView;
begin
if Assigned(FOnUpdateView) then
FOnUpdateView(Self);
end;
function TCFPage.GetButtonAt(const X, Y: Integer): TCFPageButton;
var
i: Integer;
begin
Result := nil;
for i := 0 to FButtons.Count - 1 do
begin
if PtInRect(TCFPageButton(FButtons[i]).Rect, Point(X, Y)) then
begin
Result := TCFPageButton(FButtons[i]);
Break;
end;
end;
end;
procedure TCFPage.KillFocus;
begin
if Assigned(FHotButton) then
begin
FHotButton.KillFocus;
DoUpdateView;
end;
end;
procedure TCFPage.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vButton: TCFPageButton;
begin
vButton := GetButtonAt(X, Y);
if Assigned(vButton) then
begin
vButton.MouseDown;
DoUpdateView;
end;
end;
procedure TCFPage.MouseEnter;
begin
FMouseIn := True;
DoUpdateView;
end;
procedure TCFPage.MouseLeave;
begin
FMouseIn := False;
if Assigned(FHotButton) then
begin
FHotButton.MouseLeave;
FHotButton := nil;
end;
DoUpdateView;
end;
procedure TCFPage.MouseMove(Shift: TShiftState; X, Y: Integer);
var
vButton: TCFPageButton;
begin
vButton := GetButtonAt(X, Y);
if vButton <> FHotButton then
begin
if Assigned(FHotButton) then
FHotButton.MouseLeave;
FHotButton := vButton;
if Assigned(FHotButton) then
FHotButton.MouseEnter;
DoUpdateView;
end;
end;
procedure TCFPage.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vButton: TCFPageButton;
begin
vButton := GetButtonAt(X, Y);
if Assigned(vButton) then
begin
DoUpdateView;
if (cbsDown in vButton.State) and Assigned(vButton.OnClick) then
vButton.OnClick(vButton);
vButton.MouseUp;
end;
end;
procedure TCFPage.PintTo(const ACanvas: TCanvas);
var
i, vLeft: Integer;
vBtnRect: TRect;
vButton: TCFPageButton;
begin
vLeft := CustomPadding;
if Assigned(FPageControl.Images) and (FImageIndex >= 0) then
begin
FPageControl.Images.Draw(ACanvas, vLeft,
(FPageControl.PageHeight - FPageControl.Images.Height) div 2, FImageIndex);
vLeft := vLeft + FPageControl.Images.Width + CustomPadding;
end;
ACanvas.TextOut(vLeft, (FPageControl.PageHeight - FTextSize.cy) div 2, FText);
if (not FActive) and (not FMouseIn) then Exit;
vLeft := vLeft + FTextSize.cx + CustomPadding;
for i := 0 to FButtons.Count - 1 do
begin
vBtnRect := Bounds(vLeft, (FPageControl.PageHeight - ButtonImageWidth) div 2,
ButtonImageWidth, ButtonImageWidth);
vButton := TCFPageButton(FButtons[i]);
vButton.Rect := vBtnRect;
if Assigned(FPageControl.Images) then
begin
if cbsDown in vButton.State then
begin
if vButton.DownImageIndex >= 0 then
FPageControl.Images.Draw(ACanvas, vButton.Rect.Left, vButton.Rect.Top, vButton.DownImageIndex)
else
if vButton.HotImageIndex >= 0 then
FPageControl.Images.Draw(ACanvas, vButton.Rect.Left, vButton.Rect.Top, vButton.HotImageIndex)
else
if vButton.ImageIndex >= 0 then
FPageControl.Images.Draw(ACanvas, vButton.Rect.Left, vButton.Rect.Top, vButton.ImageIndex);
end
else
if cbsMouseIn in vButton.State then
begin
if vButton.HotImageIndex >= 0 then
FPageControl.Images.Draw(ACanvas, vButton.Rect.Left, vButton.Rect.Top, vButton.HotImageIndex)
else
if vButton.ImageIndex >= 0 then
FPageControl.Images.Draw(ACanvas, vButton.Rect.Left, vButton.Rect.Top, vButton.ImageIndex);
end
else // if vButton.State = [] then
begin
if vButton.ImageIndex >= 0 then
FPageControl.Images.Draw(ACanvas, vButton.Rect.Left, vButton.Rect.Top, vButton.ImageIndex);
end;
end;
vLeft := vLeft + CustomPadding + ButtonImageWidth;
end;
end;
procedure TCFPage.SetActive(const Value: Boolean);
begin
if FActive <> Value then
begin
FActive := Value;
if Assigned(FControl) then
begin
if FActive then
FControl.BringToFront
else
FControl.SendToBack;
end;
DoUpdateView;
end;
end;
procedure TCFPage.SetControl(const AControl: TWinControl);
begin
if FControl <> AControl then
begin
// 原来的控件要在这里释放吗
FControl := AControl;
DoSetControl;
end;
end;
procedure TCFPage.SetImageIndex(const Value: Integer);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
CalcWidth;
DoUpdateView;
DoImageIndexChanged;
end;
end;
procedure TCFPage.SetText(const AText: string);
var
i: Integer;
begin
if FText <> AText then
begin
FText := AText;
CalcWidth;
end;
end;
{ TCFPageButton }
constructor TCFPageButton.Create;
begin
FImageIndex := -1;
FHotImageIndex := -1;
FDownImageIndex := -1;
FState := [];
end;
procedure TCFPageButton.DoUpdateView;
begin
if Assigned(FOnUpdateView) then
FOnUpdateView(Self);
end;
procedure TCFPageButton.KillFocus;
begin
FState := [];
end;
procedure TCFPageButton.MouseDown;
begin
Include(FState, cbsDown);
end;
procedure TCFPageButton.MouseEnter;
begin
Include(FState, cbsMouseIn);
end;
procedure TCFPageButton.MouseLeave;
begin
FState := [];
end;
procedure TCFPageButton.MouseUp;
begin
Exclude(FState, cbsDown);
end;
procedure TCFPageButton.SetDownImageIndex(const Value: Integer);
begin
if FDownImageIndex <> Value then
begin
FDownImageIndex := Value;
DoUpdateView;
end;
end;
procedure TCFPageButton.SetHotImageIndex(const Value: Integer);
begin
if FHotImageIndex <> Value then
begin
FHotImageIndex := Value;
DoUpdateView;
end;
end;
procedure TCFPageButton.SetImageIndex(const Value: Integer);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
DoUpdateView;
end;
end;
{ TPageList }
procedure TPageList.Notify(Ptr: Pointer; Action: TListNotification);
begin
inherited Notify(Ptr, Action);
if (Action = lnAdded) or (Action = lnDeleted) then
begin
if Assigned(FOnCountChanged) then
FOnCountChanged(Self);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.