text stringlengths 14 6.51M |
|---|
unit PidlIcons;
interface
uses
Windows, ShlObj;
function GetPidlLargeIcon( aPidl : PItemIDList ) : HICON;
function GetPidlSmallIcon( aPidl : PItemIDList ) : HICON;
implementation
uses
ShellApi;
function GetPidlLargeIcon( aPidl : PItemIDList ) : HICON;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(aPidl), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_PIDL or SHGFI_ICON or SHGFI_SHELLICONSIZE );
Result := SHInfo.hIcon;
end;
function GetPidlSmallIcon( aPidl : PItemIDList ) : HICON;
var
SHInfo : TSHFileInfo;
begin
SHGetFileInfo( pchar(aPidl), 0, SHInfo, sizeof( TSHFILEINFO ), SHGFI_PIDL or SHGFI_ICON or SHGFI_SHELLICONSIZE or SHGFI_SMALLICON );
Result := SHInfo.hIcon;
end;
end.
|
unit svgtoolfrm;
{$I vg_define.inc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,
xdom, vg_layouts, vg_scene, vg_controls, vg_objects;
type
TfrmSVGTool = class(TForm)
vgScene1: TvgScene;
Root1: TvgBackground;
ToolBar1: TvgToolBar;
OpenDialog1: TOpenDialog;
btnLoad: TvgToolPathButton;
btnSave: TvgToolPathButton;
SaveDialog1: TSaveDialog;
Layout1: TvgLayout;
SVG: TvgScaledLayout;
procedure btnLoadClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
{ Private declarations }
procedure DoExternalSubset(sender: TObject; const parentSystemId: wideString;
var publicId, systemId: wideString; var stream: TStream;
var action: TXmlParserAction);
public
{ Public declarations }
FSvg: TdomDocument;
procedure SvgToVG;
end;
var
frmSVGTool: TfrmSVGTool;
implementation
uses Math;
{$R *.dfm}
(* colors_num = 148;
colors : array[0..colors_num - 1 ] of named_color =
((name:'aliceblue'; r:240; g:248; b:255; a:255 ) ,
(name:'antiquewhite'; r:250; g:235; b:215; a:255 ) ,
(name:'aqua'; r:0; g:255; b:255; a:255 ) ,
(name:'aquamarine'; r:127; g:255; b:212; a:255 ) ,
(name:'azure'; r:240; g:255; b:255; a:255 ) ,
(name:'beige'; r:245; g:245; b:220; a:255 ) ,
(name:'bisque'; r:255; g:228; b:196; a:255 ) ,
(name:'black'; r:0; g:0; b:0; a:255 ) ,
(name:'blanchedalmond'; r:255; g:235; b:205; a:255 ) ,
(name:'blue'; r:0; g:0; b:255; a:255 ) ,
(name:'blueviolet'; r:138; g:43; b:226; a:255 ) ,
(name:'brown'; r:165; g:42; b:42; a:255 ) ,
(name:'burlywood'; r:222; g:184; b:135; a:255 ) ,
(name:'cadetblue'; r:95; g:158; b:160; a:255 ) ,
(name:'chartreuse'; r:127; g:255; b:0; a:255 ) ,
(name:'chocolate'; r:210; g:105; b:30; a:255 ) ,
(name:'coral'; r:255; g:127; b:80; a:255 ) ,
(name:'cornflowerblue'; r:100; g:149; b:237; a:255 ) ,
(name:'cornsilk'; r:255; g:248; b:220; a:255 ) ,
(name:'crimson'; r:220; g:20; b:60; a:255 ) ,
(name:'cyan'; r:0; g:255; b:255; a:255 ) ,
(name:'darkblue'; r:0; g:0; b:139; a:255 ) ,
(name:'darkcyan'; r:0; g:139; b:139; a:255 ) ,
(name:'darkgoldenrod'; r:184; g:134; b:11; a:255 ) ,
(name:'darkgray'; r:169; g:169; b:169; a:255 ) ,
(name:'darkgreen'; r:0; g:100; b:0; a:255 ) ,
(name:'darkgrey'; r:169; g:169; b:169; a:255 ) ,
(name:'darkkhaki'; r:189; g:183; b:107; a:255 ) ,
(name:'darkmagenta'; r:139; g:0; b:139; a:255 ) ,
(name:'darkolivegreen'; r:85; g:107; b:47; a:255 ) ,
(name:'darkorange'; r:255; g:140; b:0; a:255 ) ,
(name:'darkorchid'; r:153; g:50; b:204; a:255 ) ,
(name:'darkred'; r:139; g:0; b:0; a:255 ) ,
(name:'darksalmon'; r:233; g:150; b:122; a:255 ) ,
(name:'darkseagreen'; r:143; g:188; b:143; a:255 ) ,
(name:'darkslateblue'; r:72; g:61; b:139; a:255 ) ,
(name:'darkslategray'; r:47; g:79; b:79; a:255 ) ,
(name:'darkslategrey'; r:47; g:79; b:79; a:255 ) ,
(name:'darkturquoise'; r:0; g:206; b:209; a:255 ) ,
(name:'darkviolet'; r:148; g:0; b:211; a:255 ) ,
(name:'deeppink'; r:255; g:20; b:147; a:255 ) ,
(name:'deepskyblue'; r:0; g:191; b:255; a:255 ) ,
(name:'dimgray'; r:105; g:105; b:105; a:255 ) ,
(name:'dimgrey'; r:105; g:105; b:105; a:255 ) ,
(name:'dodgerblue'; r:30; g:144; b:255; a:255 ) ,
(name:'firebrick'; r:178; g:34; b:34; a:255 ) ,
(name:'floralwhite'; r:255; g:250; b:240; a:255 ) ,
(name:'forestgreen'; r:34; g:139; b:34; a:255 ) ,
(name:'fuchsia'; r:255; g:0; b:255; a:255 ) ,
(name:'gainsboro'; r:220; g:220; b:220; a:255 ) ,
(name:'ghostwhite'; r:248; g:248; b:255; a:255 ) ,
(name:'gold'; r:255; g:215; b:0; a:255 ) ,
(name:'goldenrod'; r:218; g:165; b:32; a:255 ) ,
(name:'gray'; r:128; g:128; b:128; a:255 ) ,
(name:'green'; r:0; g:128; b:0; a:255 ) ,
(name:'greenyellow'; r:173; g:255; b:47; a:255 ) ,
(name:'grey'; r:128; g:128; b:128; a:255 ) ,
(name:'honeydew'; r:240; g:255; b:240; a:255 ) ,
(name:'hotpink'; r:255; g:105; b:180; a:255 ) ,
(name:'indianred'; r:205; g:92; b:92; a:255 ) ,
(name:'indigo'; r:75; g:0; b:130; a:255 ) ,
(name:'ivory'; r:255; g:255; b:240; a:255 ) ,
(name:'khaki'; r:240; g:230; b:140; a:255 ) ,
(name:'lavender'; r:230; g:230; b:250; a:255 ) ,
(name:'lavenderblush'; r:255; g:240; b:245; a:255 ) ,
(name:'lawngreen'; r:124; g:252; b:0; a:255 ) ,
(name:'lemonchiffon'; r:255; g:250; b:205; a:255 ) ,
(name:'lightblue'; r:173; g:216; b:230; a:255 ) ,
(name:'lightcoral'; r:240; g:128; b:128; a:255 ) ,
(name:'lightcyan'; r:224; g:255; b:255; a:255 ) ,
(name:'lightgoldenrodyellow'; r:250; g:250; b:210; a:255 ) ,
(name:'lightgray'; r:211; g:211; b:211; a:255 ) ,
(name:'lightgreen'; r:144; g:238; b:144; a:255 ) ,
(name:'lightgrey'; r:211; g:211; b:211; a:255 ) ,
(name:'lightpink'; r:255; g:182; b:193; a:255 ) ,
(name:'lightsalmon'; r:255; g:160; b:122; a:255 ) ,
(name:'lightseagreen'; r:32; g:178; b:170; a:255 ) ,
(name:'lightskyblue'; r:135; g:206; b:250; a:255 ) ,
(name:'lightslategray'; r:119; g:136; b:153; a:255 ) ,
(name:'lightslategrey'; r:119; g:136; b:153; a:255 ) ,
(name:'lightsteelblue'; r:176; g:196; b:222; a:255 ) ,
(name:'lightyellow'; r:255; g:255; b:224; a:255 ) ,
(name:'lime'; r:0; g:255; b:0; a:255 ) ,
(name:'limegreen'; r:50; g:205; b:50; a:255 ) ,
(name:'linen'; r:250; g:240; b:230; a:255 ) ,
(name:'magenta'; r:255; g:0; b:255; a:255 ) ,
(name:'maroon'; r:128; g:0; b:0; a:255 ) ,
(name:'mediumaquamarine'; r:102; g:205; b:170; a:255 ) ,
(name:'mediumblue'; r:0; g:0; b:205; a:255 ) ,
(name:'mediumorchid'; r:186; g:85; b:211; a:255 ) ,
(name:'mediumpurple'; r:147; g:112; b:219; a:255 ) ,
(name:'mediumseagreen'; r:60; g:179; b:113; a:255 ) ,
(name:'mediumslateblue'; r:123; g:104; b:238; a:255 ) ,
(name:'mediumspringgreen'; r:0; g:250; b:154; a:255 ) ,
(name:'mediumturquoise'; r:72; g:209; b:204; a:255 ) ,
(name:'mediumvioletred'; r:199; g:21; b:133; a:255 ) ,
(name:'midnightblue'; r:25; g:25; b:112; a:255 ) ,
(name:'mintcream'; r:245; g:255; b:250; a:255 ) ,
(name:'mistyrose'; r:255; g:228; b:225; a:255 ) ,
(name:'moccasin'; r:255; g:228; b:181; a:255 ) ,
(name:'navajowhite'; r:255; g:222; b:173; a:255 ) ,
(name:'navy'; r:0; g:0; b:128; a:255 ) ,
(name:'oldlace'; r:253; g:245; b:230; a:255 ) ,
(name:'olive'; r:128; g:128; b:0; a:255 ) ,
(name:'olivedrab'; r:107; g:142; b:35; a:255 ) ,
(name:'orange'; r:255; g:165; b:0; a:255 ) ,
(name:'orangered'; r:255; g:69; b:0; a:255 ) ,
(name:'orchid'; r:218; g:112; b:214; a:255 ) ,
(name:'palegoldenrod'; r:238; g:232; b:170; a:255 ) ,
(name:'palegreen'; r:152; g:251; b:152; a:255 ) ,
(name:'paleturquoise'; r:175; g:238; b:238; a:255 ) ,
(name:'palevioletred'; r:219; g:112; b:147; a:255 ) ,
(name:'papayawhip'; r:255; g:239; b:213; a:255 ) ,
(name:'peachpuff'; r:255; g:218; b:185; a:255 ) ,
(name:'peru'; r:205; g:133; b:63; a:255 ) ,
(name:'pink'; r:255; g:192; b:203; a:255 ) ,
(name:'plum'; r:221; g:160; b:221; a:255 ) ,
(name:'powderblue'; r:176; g:224; b:230; a:255 ) ,
(name:'purple'; r:128; g:0; b:128; a:255 ) ,
(name:'red'; r:255; g:0; b:0; a:255 ) ,
(name:'rosybrown'; r:188; g:143; b:143; a:255 ) ,
(name:'royalblue'; r:65; g:105; b:225; a:255 ) ,
(name:'saddlebrown'; r:139; g:69; b:19; a:255 ) ,
(name:'salmon'; r:250; g:128; b:114; a:255 ) ,
(name:'sandybrown'; r:244; g:164; b:96; a:255 ) ,
(name:'seagreen'; r:46; g:139; b:87; a:255 ) ,
(name:'seashell'; r:255; g:245; b:238; a:255 ) ,
(name:'sienna'; r:160; g:82; b:45; a:255 ) ,
(name:'silver'; r:192; g:192; b:192; a:255 ) ,
(name:'skyblue'; r:135; g:206; b:235; a:255 ) ,
(name:'slateblue'; r:106; g:90; b:205; a:255 ) ,
(name:'slategray'; r:112; g:128; b:144; a:255 ) ,
(name:'slategrey'; r:112; g:128; b:144; a:255 ) ,
(name:'snow'; r:255; g:250; b:250; a:255 ) ,
(name:'springgreen'; r:0; g:255; b:127; a:255 ) ,
(name:'steelblue'; r:70; g:130; b:180; a:255 ) ,
(name:'tan'; r:210; g:180; b:140; a:255 ) ,
(name:'teal'; r:0; g:128; b:128; a:255 ) ,
(name:'thistle'; r:216; g:191; b:216; a:255 ) ,
(name:'tomato'; r:255; g:99; b:71; a:255 ) ,
(name:'turquoise'; r:64; g:224; b:208; a:255 ) ,
(name:'violet'; r:238; g:130; b:238; a:255 ) ,
(name:'wheat'; r:245; g:222; b:179; a:255 ) ,
(name:'white'; r:255; g:255; b:255; a:255 ) ,
(name:'whitesmoke'; r:245; g:245; b:245; a:255 ) ,
(name:'yellow'; r:255; g:255; b:0; a:255 ) ,
(name:'yellowgreen'; r:154; g:205; b:50; a:255 ) ,
(name:'zzzzzzzzzzz'; r:0; g:0; b:0; a:0 ) ); *)
procedure TfrmSVGTool.btnLoadClick(Sender: TObject);
var
DomImpl : TDomImplementation;
Parser : TXmlToDomParser;
begin
if OpenDialog1.Execute then
begin
DomImpl:= TDomImplementation.Create(nil);
Parser:= TXmlToDomParser.Create(nil);
Parser.DomImpl := DomImpl;
Parser.OnExternalSubset := DoExternalSubset;
FSvg := Parser.fileToDom(OpenDialog1.FileName);
SvgToVG;
Parser.Free;
DomImpl.Free;
end;
end;
procedure TfrmSVGTool.btnSaveClick(Sender: TObject);
var
S: TStream;
begin
if SaveDialog1.Execute then
begin
S := TFileStream.Create(SaveDialog1.FileName, fmCreate);
SVG.Align := vaNone;
SVG.SaveToStream(S);
SVG.Align := vaFit;
S.Free;
end;
end;
procedure TfrmSVGTool.DoExternalSubset(sender: TObject;
const parentSystemId: wideString; var publicId, systemId: wideString;
var stream: TStream; var action: TXmlParserAction);
begin
action := paOK;
end;
procedure TfrmSVGTool.SvgToVG;
var
W, H: single;
function FromRGB(Color: longword): longword;
asm
BSWAP EAX
MOV AL, $FF
ROR EAX,8
end;
function parseTransform(var Node: TdomNode): TvgMatrix;
var
Attr: TdomNode;
v, v1, v2, t, Trans: AnsiString;
begin
Result := IdentityMatrix;
Attr := Node.attributes.getNamedItem('transform');
if (Attr <> nil) then
begin
Trans := Attr.NodeValue;
while Trans <> '' do
begin
t := vgGetToken(Trans, '(');
if LowerCase(t) = 'translate' then
begin
v1 := vgGetToken(Trans, ',');
v2 := vgGetToken(Trans, ')');
Result.m31 := vgStrToFloat(v1);
Result.m32 := vgStrToFloat(v2);
end;
if LowerCase(t) = 'matrix' then
begin
v1 := vgGetToken(Trans, ',');
v2 := vgGetToken(Trans, ',');
Result.m11 := vgStrToFloat(v1);
Result.m12 := vgStrToFloat(v2);
v1 := vgGetToken(Trans, ',');
v2 := vgGetToken(Trans, ',');
Result.m21 := vgStrToFloat(v1);
Result.m22 := vgStrToFloat(v2);
v1 := vgGetToken(Trans, ',');
v2 := vgGetToken(Trans, ')');
Result.m31 := vgStrToFloat(v1);
Result.m32 := vgStrToFloat(v2);
end;
end;
end;
end;
function vgStr4ToColor(Value: string): TvgColor;
begin
try
if Length(Value) = 4 then
begin
Result := vgStrToColor('#' + Value[2] + Value[2] + Value[3] + Value[3] + Value[4] + Value[4]);
end
else
Result := 0;
except
end;
end;
function parseColorToInt(str: AnsiString): cardinal;
var
s, v, v1, v2: AnsiString;
c: longint;
o: TvgObject;
begin
Result := 0;
if Length(str) = 0 then Exit;
if Pos('rgb', LowerCase(str)) > 0 then
begin
s := str;
vgGetToken(str, '(');
v := vgGetToken(str, ',');
v1 := vgGetToken(str, ',');
v2 := vgGetToken(str, ')');
try
Result := RGB(StrToInt(v2), StrToInt(v1), StrToInt(v)) or $FF000000;
except
Result := $FFFFFF or $FF000000;
end;
end
else
if LowerCase(str) = 'none' then
Result := 0
else
if not (Pos(Str[1], '#0123456789') > 0) then
begin
if IdentToColor('cl' + Str, c) then
Result := FromRGB(c) or $FF000000;
end
else
if Length(str) = 4 then
begin
Result := vgStr4ToColor(str) or $FF000000;
end
else
begin
Result := vgStrToColor(str) or $FF000000;
end;
end;
procedure parseColor(str: AnsiString; var Fill: TvgBrush);
var
s, v, v1, v2: AnsiString;
c: longint;
o: TvgObject;
begin
if Length(str) = 0 then Exit;
if Pos('rgb', LowerCase(str)) > 0 then
begin
s := str;
vgGetToken(str, '(');
v := vgGetToken(str, ',');
v1 := vgGetToken(str, ',');
v2 := vgGetToken(str, ')');
Fill.Style := vgBrushSolid;
try
Fill.Color := vgColorToStr(RGB(StrToInt(v2), StrToInt(v1), StrToInt(v)) or $FF000000);
except
Fill.Color := vgColorToStr($FFFFFF or $FF000000);
end;
end
else
if Pos('url', LowerCase(str)) > 0 then
begin
vgGetToken(str, '#');
v := vgGetToken(str, ')');
o := FindResource(v);
Fill.Style := vgBrushResource;
if o is TvgBrushObject then
Fill.Resource.Resource := TvgBrushObject(o);
end
else
if LowerCase(str) = 'none' then
Fill.Style := vgBrushNone
else
if not (Pos(Str[1], '#0123456789') > 0) then
begin
Fill.Style := vgBrushSolid;
if IdentToColor('cl' + Str, c) then
Fill.Color := vgColorToStr(FromRGB(c) or $FF000000);
end
else
if Length(str) = 4 then
begin
Fill.Color := vgColorToStr(vgStr4ToColor(str) or $FF000000);
end
else
begin
Fill.Style := vgBrushSolid;
Fill.Color := vgColorToStr(vgStrToColor(str) or $FF000000);
end;
end;
procedure parseStyle(Parent: TvgVisualObject; var Node: TdomNode; var Fill, Stroke: TvgBrush; var StrokeThickness: single);
var
Attr: TdomNode;
v, v1, v2, s, style: AnsiString;
begin
Attr := Node.attributes.getNamedItem('fill');
if (Attr <> nil) then
begin
s := Attr.NodeValue;
parseColor(s, Fill);
end;
Attr := Node.attributes.getNamedItem('stroke');
if (Attr <> nil) then
begin
s := Attr.NodeValue;
parseColor(s, Stroke);
end;
Attr := Node.attributes.getNamedItem('fill-opacity');
if (Attr <> nil) then
begin
s := Attr.NodeValue;
Stroke.Color := vgColorToStr(Stroke.SolidColor and $FFFFFF or (trunc(vgStrToFloat(s) * $FF) shl 24));
end;
Attr := Node.attributes.getNamedItem('stroke-opacity');
if (Attr <> nil) then
begin
s := Attr.NodeValue;
Stroke.Color := vgColorToStr(Stroke.SolidColor and $FFFFFF or (trunc(vgStrToFloat(s) * $FF) shl 24));
end;
Attr := Node.attributes.getNamedItem('stroke-width');
if (Attr <> nil) then
begin
s := Attr.NodeValue;
v := vgGetToken(s, 'abcdefjhiklmnopqrtsuvwxyz,');
StrokeThickness := vgStrToFloat(v);
end;
Attr := Node.attributes.getNamedItem('style');
if (Attr <> nil) then
begin
style := Attr.NodeValue;
while style <> '' do
begin
s := vgGetToken(style, ';');
v := vgGetToken(s, ':');
if LowerCase(v) = 'fill' then
begin
parseColor(s, Fill);
end;
if LowerCase(v) = 'fill-opacity' then
begin
Fill.Color := vgColorToStr(Fill.SolidColor and $FFFFFF or (trunc(vgStrToFloat(s) * $FF) shl 24));
end;
if LowerCase(v) = 'stroke' then
begin
parseColor(s, Stroke);
end;
if LowerCase(v) = 'stroke-opacity' then
begin
Stroke.Color := vgColorToStr(Stroke.SolidColor and $FFFFFF or (trunc(vgStrToFloat(s) * $FF) shl 24));
end;
if LowerCase(v) = 'stroke-width' then
begin
v := vgGetToken(s, 'abcdefjhiklmnopqrtsuvwxyz');
StrokeThickness := vgStrToFloat(v);
end;
end;
end;
// apply
if Parent is TvgShape then
begin
TvgShape(Parent).Fill.Assign(Fill);
TvgShape(Parent).Stroke.Assign(Stroke);
TvgShape(Parent).StrokeThickness := StrokeThickness;
end;
end;
procedure parseGradient(Gradient: TvgGradient; Node: TdomNode);
var
Children: TdomNodeList;
CName: string;
style, v, S: AnsiString;
Attr: TdomNode;
i: integer;
P: TvgGradientPoint;
begin
// children
Children := Node.childNodes;
Gradient.Points.Clear;
Gradient.StopPosition.Point := vgPoint(1, 0);
for i := 0 to Children.length - 1 do
begin
if (Byte(Children.Item(I).nodeType) = 1) then
begin
CName := Children.Item(I).nodeName;
if LowerCase(CName) = 'stop' then
begin
P := TvgGradientPoint(Gradient.Points.Add);
Attr := Children.Item(I).attributes.getNamedItem('offset');
if Attr <> nil then
begin
s := Attr.nodeValue;
if Pos('%', s) > 0 then
P.Offset := vgStrToFloat(vgGetToken(s, '%')) / 100
else
P.Offset := vgStrToFloat(s);
end;
Attr := Children.Item(I).attributes.getNamedItem('stop-color');
if Attr <> nil then
P.Color := vgColorToStr(parseColorToInt(Attr.nodeValue));
Attr := Children.Item(I).attributes.getNamedItem('style');
if Attr <> nil then
begin
style := Attr.nodeValue;
while style <> '' do
begin
s := vgGetToken(style, ';');
v := vgGetToken(s, ':');
if LowerCase(v) = 'stop-color' then
begin
P.Color := vgColorToStr(parseColorToInt(s));
end;
if LowerCase(v) = 'stop-opacity' then
begin
P.Color := vgColorToStr(vgStrToColor(P.Color) and $FFFFFF or (trunc(vgStrToFloat(s) * $FF) shl 24));
end;
end;
end;
end;
end;
end;
end;
procedure processDefs(Parent: TvgVisualObject; var Node: TdomNode);
var
Children: TdomNodeList;
CName: string;
S: AnsiString;
Brush: TvgBrushObject;
Attr: TdomNode;
i: integer;
begin
Children := Node.childNodes;
if Children = nil then Exit;
// children
for i := 0 to Children.length - 1 do
begin
if (Byte(Children.Item(I).nodeType) = 1) then
begin
CName := Children.Item(I).nodeName;
if LowerCase(CName) = 'lineargradient' then
begin
Brush := TvgBrushObject.Create(Self);
Brush.Parent := Parent;
Attr := Children.Item(I).attributes.getNamedItem('id');
if Attr <> nil then
Brush.ResourceName := Attr.nodeValue;
Brush.Brush.Style := vgBrushGradient;
Attr := Children.Item(I).attributes.getNamedItem('xlink:href');
if Attr <> nil then
begin
// assign
s := Attr.nodeValue;
Delete(s, 1, 1);
if (FindResource(s) <> nil) and (FindResource(s) is TvgBrushObject) then
Brush.Brush.Assign(TvgBrushObject(FindResource(s)).Brush);
end
else
parseGradient(Brush.Brush.Gradient, Children.Item(i));
end;
end;
end;
end;
procedure processChild(Parent: TvgVisualObject; var Node: TdomNode; var Matrix: TvgMatrix; var Fill, Stroke: TvgBrush; var StrokeThickness: single);
var
Children: TdomNodeList;
CName: string;
S, tok: AnsiString;
Cur: TvgVisualObject;
CurNode: TdomNode;
Attr: TdomNode;
i: integer;
SaveFill, SaveStroke: TvgBrush;
SaveStrokeThickness: single;
R: TvgRect;
SaveMatrix, M: TvgMatrix;
begin
Children := Node.childNodes;
if Children = nil then Exit;
// case object
CName := Node.nodeName;
// transform
M := vgMatrixMultiply(parseTransform(Node), Matrix);
// object
if LowerCase(CName) = 'svg' then
begin
Cur := Parent;
end
else
if LowerCase(CName) = 'defs' then
begin
processDefs(Parent, Node);
Exit;
end
else
if LowerCase(CName) = 'path' then
begin
// path
Cur := TvgPath.Create(Self);
Cur.Parent := Parent;
Cur.HitTest := false;
Cur.Locked := true;
with TvgPath(Cur) do
begin
WrapMode := vgPathStretch;
Attr := Node.attributes.getNamedItem('d');
if Attr <> nil then
begin
Data.Data := Attr.NodeValue;
Data.ApplyMatrix(M);
R := Data.GetBounds;
Data.Offset(-R.Left, -R.Top);
Position.X := R.Left;
Position.Y := R.Top;
SetSizeWithoutChange(vgRectWidth(R), vgRectHeight(R));
end;
end;
end
else
if LowerCase(CName) = 'polygon' then
begin
// polygon
Cur := TvgPath.Create(Self);
Cur.Parent := Parent;
Cur.HitTest := false;
Cur.Locked := true;
with TvgPath(Cur) do
begin
WrapMode := vgPathStretch;
Attr := Node.attributes.getNamedItem('points');
if Attr <> nil then
begin
S := trim(Attr.NodeValue);
tok := vgGetToken(S, ' ');
Data.MoveTo(vgPoint(vgStrToFloat(vgGetToken(tok, ', ')), vgStrToFloat(vgGetToken(tok, ', '))));
tok := vgGetToken(S, ' ');
while S <> '' do
begin
Data.LineTo(vgPoint(vgStrToFloat(vgGetToken(tok, ', ')), vgStrToFloat(vgGetToken(tok, ', '))));
tok := vgGetToken(S, ' ');
end;
R := Data.GetBounds;
Data.Offset(-R.Left, -R.Top);
Position.X := R.Left;
Position.Y := R.Top;
SetSizeWithoutChange(vgRectWidth(R), vgRectHeight(R));
end;
end;
end
else
if LowerCase(CName) = 'rect' then
begin
// path
Cur := TvgRectangle.Create(Self);
Cur.Parent := Parent;
Cur.HitTest := false;
Cur.Locked := true;
Attr := Node.attributes.getNamedItem('x');
if Attr <> nil then
Cur.Position.X := vgStrToFloat(Attr.nodeValue);
Attr := Node.attributes.getNamedItem('y');
if Attr <> nil then
Cur.Position.Y := vgStrToFloat(Attr.nodeValue);
Attr := Node.attributes.getNamedItem('width');
if Attr <> nil then
Cur.Width := vgStrToFloat(Attr.nodeValue);
Attr := Node.attributes.getNamedItem('height');
if Attr <> nil then
Cur.Height := vgStrToFloat(Attr.nodeValue);
end
else
if LowerCase(CName) = 'text' then
begin
// path
Cur := TvgText.Create(Self);
Cur.Parent := Parent;
Cur.HitTest := false;
Cur.Locked := true;
TvgText(Cur).WordWrap := false;
TvgText(Cur).HorzTextAlign := vgTextAlignNear;
TvgText(Cur).VertTextAlign := vgTextAlignNear;
Attr := Node.attributes.getNamedItem('x');
if Attr <> nil then
Cur.Position.X := vgStrToFloat(Attr.nodeValue);
Attr := Node.attributes.getNamedItem('y');
if Attr <> nil then
Cur.Position.Y := vgStrToFloat(Attr.nodeValue);
Attr := Node.attributes.getNamedItem('font-size');
if Attr <> nil then
TvgText(Cur).Font.Size := vgStrToFloat(Attr.nodeValue);
Attr := Node.attributes.getNamedItem('font-family');
if Attr <> nil then
TvgText(Cur).Font.Family := Attr.nodeValue;
TvgText(Cur).Text := Node.textContent;
TvgText(Cur).AutoSize := true;
Cur.Position.Y := Cur.Position.Y - Cur.Height;
end
else
if LowerCase(CName) = 'line' then
begin
// line
Cur := TvgLine.Create(Self);
Cur.Parent := Parent;
Cur.HitTest := false;
Cur.Locked := true;
Attr := Node.attributes.getNamedItem('x1');
if Attr <> nil then
Cur.Position.X := vgStrToFloat(Attr.nodeValue);
Attr := Node.attributes.getNamedItem('y1');
if Attr <> nil then
Cur.Position.Y := vgStrToFloat(Attr.nodeValue);
Attr := Node.attributes.getNamedItem('x2');
if Attr <> nil then
Cur.Width := vgStrToFloat(Attr.nodeValue) - Cur.Position.X;
Attr := Node.attributes.getNamedItem('y2');
if Attr <> nil then
Cur.Height := vgStrToFloat(Attr.nodeValue) - Cur.Position.Y;
end
else
begin
// default
Cur := TvgLayout.Create(Self);
Cur.Parent := Parent;
Cur.HitTest := false;
Cur.Locked := true;
end;
// correct size
with Cur.AbsoluteRect do
begin
if Right > W then W := Right;
if Bottom > H then H := Bottom;
end;
// set name
Attr := Node.attributes.getNamedItem('id');
if Attr <> nil then
Cur.BindingName := Attr.nodeValue;
// style
parseStyle(Cur, Node, Fill, Stroke, StrokeThickness);
// children
for i := 0 to Children.length - 1 do
begin
if (Byte(Children.Item(I).nodeType) = 1) then
begin
SaveFill := TvgBrush.Create(vgBrushSolid, $FFFFFFFF);
SaveStroke := TvgBrush.Create(vgBrushNone, $FF000000);
SaveStrokeThickness := 1;
SaveFill.Assign(Fill);
SaveStroke.Assign(Stroke);
SaveStrokeThickness := StrokeThickness;
SaveMatrix := M;
CurNode := Children.Item(I);
processChild(Cur, Curnode, M, Fill, Stroke, StrokeThickness);
M := SaveMatrix;
Fill.Assign(SaveFill);
Stroke.Assign(SaveStroke);
StrokeThickness := SaveStrokeThickness;
SaveStroke.Free;
SaveFill.Free;
end;
end;
end;
var
Node: TdomNode;
Attr: TdomNode;
Fill, Stroke: TvgBrush;
StrokeThickness: single;
M: TvgMatrix;
begin
if FSvg = nil then Exit;
Node := FSvg.documentElement;
if not Assigned(Node) then Exit;
Fill := TvgBrush.Create(vgBrushSolid, $FFE0E0E0);
Fill.SolidColor := $FF000000;
Stroke := TvgBrush.Create(vgBrushSolid, $FF000000);
Stroke.SolidColor := $FF000000;
StrokeThickness := 1;
M := IdentityMatrix;
W := 1; H := 1;
SVG.Align := vaNone;
SVG.DeleteChildren;
SVG.DisableAlign;
SVG.SetSizeWithoutChange(1, 1);
SVG.OriginalWidth := 1;
SVG.OriginalHeight := 1;
processChild(SVG, Node, M, Fill, Stroke, StrokeThickness);
with SVG.AbsoluteToLocal(vgPoint(W, H)) do
begin
SVG.SetSizeWithoutChange(x * 1, y * 1);
SVG.OriginalWidth := x;
SVG.OriginalHeight := y;
end;
SVG.EnableAlign;
SVG.Align := vaFit;
Stroke.Free;
Fill.Free;
end;
end.
|
unit System.ConfigList;
interface
uses SysUtils, Classes,System.Generics.collections,
{$ifdef FMX} FMX.Edit {$endif};
const
sConfigList_Configurou = 'Configurou';
type
TConfigListItem = class
public
Nome:String;
Valor:Variant;
ValorDefault:Variant;
Control : TComponent;
end;
TConfigListItemClassOf = class of TConfigListItem;
TConfigList = Class(TObjectList<TConfigListItem>)
private
FFileName: string;
FSessao: String;
FItemClass: TConfigListItemClassOf;
procedure SetFileName(const Value: string);
function GetItem(ANome: String): string;
procedure SetItem(ANome: String; const Value: string);
procedure SetSessao(const Value: String);
public
function ItemClass:TConfigListItemClassOf;virtual;
function add:TConfigListItem;
constructor Create(AItemClass:TConfigListItemClassOf; AFileName:string='');
procedure Gravar;
procedure Carregar;
property FileName:string read FFileName write SetFileName;
property Sessao:String read FSessao write SetSessao;
Property Item[ ANome:String ]:string read GetItem write SetItem;
end;
implementation
{ TConfigList<T> }
uses IniFiles, IniFilesEx;
function TConfigList.add: TConfigListItem;
begin
result := ItemClass.Create;
inherited add(result);
end;
procedure TConfigList.Carregar;
var it:TConfigListItem;
s:string;
begin
with TIniFile.create(FFileName) do
try
for it in self do
begin
if it.control.InheritsFrom(TEdit) then
with TEdit(it.control) do
begin
s := text;
text := ReadString('Config',it.nome,s);
end;
end;
finally
free;
end;
end;
constructor TConfigList.create(AItemClass:TConfigListItemClassOf; AFileName:string='');
begin
inherited create;
FItemClass := TConfigListItem;
if AItemClass<>nil then
FItemClass := AItemClass;
FSessao := 'Config';
FFileName := AFileName;
end;
function TConfigList.GetItem(ANome: String): string;
var it:TConfigListItem;
begin
for it in self do
if sametext(it.nome,ANome) then
begin
if it.control.InheritsFrom(TEdit) then
with TEdit(it.control) do
result := text;
exit;
end;
end;
procedure TConfigList.SetFileName(const Value: string);
begin
FFileName := Value;
end;
procedure TConfigList.SetItem(ANome: String; const Value: string);
var it:TConfigListItem;
begin
for it in self do
if sametext(it.nome,ANome) then
begin
if it.control.InheritsFrom(TEdit) then
with TEdit(it.control) do
text := Value;
exit;
end;
end;
procedure TConfigList.SetSessao(const Value: String);
begin
FSessao := Value;
end;
procedure TConfigList.Gravar;
var it:TConfigListItem;
begin
item[sConfigList_Configurou] :=DatetimeToStr(now);
with TIniFile.create(FFilename) do
try
for it in self do
begin
if it.control.InheritsFrom(TEdit) then
with TEdit(it.control) do
writeString('Config',it.nome,text);
end;
finally
free;
end;
end;
function TConfigList.ItemClass: TConfigListItemClassOf;
begin
result := FItemClass;
end;
end.
|
unit kaneco_pandora;
interface
uses gfx_engine,misc_functions;
type
pandora_gfx=class
constructor create(sprite_mask,color_offset:word;clear_screen:boolean);
destructor free;
public
procedure reset;
procedure update_video(screen,ngfx:byte);
//Read/write 8 bits
procedure spriteram_w8(offset:word;data:byte);
function spriteram_r8(offset:word):byte;
procedure spriteram_w16(offset:word;data:byte);
function spriteram_r16(offset:word):byte;
private
sprite_ram:array[0..$fff] of byte;
bg_color:byte;
clear_screen:boolean;
mask_nchar:word;
color_offset:word;
end;
var
pandora_0:pandora_gfx;
implementation
constructor pandora_gfx.create(sprite_mask,color_offset:word;clear_screen:boolean);
begin
self.mask_nchar:=sprite_mask;
self.color_offset:=color_offset;
self.clear_screen:=clear_screen;
end;
destructor pandora_gfx.free;
begin
end;
procedure pandora_gfx.reset;
begin
self.bg_color:=0;
fillchar(self.sprite_ram,$1000,0);
end;
procedure pandora_gfx.update_video(screen,ngfx:byte);
var
f,color,sx,sy,x,y,nchar,atrib:word;
begin
if self.clear_screen then fill_full_screen(screen,self.bg_color);
x:=0;
y:=0;
for f:=0 to $1ff do begin
atrib:=self.sprite_ram[(f*8)+7];
nchar:=((atrib and $3f) shl 8)+self.sprite_ram[(f*8)+6];
sx:=self.sprite_ram[(f*8)+4];
sy:=self.sprite_ram[(f*8)+5];
color:=self.sprite_ram[(f*8)+3];
sx:=sx+((color and 1) shl 8);
sy:=sy+((color and 2) shl 7);
if (color and 4)<>0 then begin
x:=(x+sx) and $1ff;
y:=(y+sy) and $1ff;
end else begin
x:=sx and $1ff;
y:=sy and $1ff;
end;
if nchar=0 then continue;
put_gfx_sprite(nchar and self.mask_nchar,(color and $f0)+self.color_offset,(atrib and $80)<>0,(atrib and $40)<>0,ngfx);
actualiza_gfx_sprite(x,y,screen,ngfx);
end;
end;
procedure pandora_gfx.spriteram_w8(offset:word;data:byte);
begin
// it's either hooked up oddly on this, or on the 16-bit games
// either way, we swap the address lines so that the spriteram is in the same format
offset:=BITSWAP16(offset,15,14,13,12,11,7,6,5,4,3,2,1,0,10,9,8);
self.sprite_ram[offset]:=data;
end;
function pandora_gfx.spriteram_r8(offset:word):byte;
begin
offset:=BITSWAP16(offset,15,14,13,12,11,7,6,5,4,3,2,1,0,10,9,8);
spriteram_r8:=self.sprite_ram[offset];
end;
procedure pandora_gfx.spriteram_w16(offset:word;data:byte);
begin
self.sprite_ram[offset shr 1]:=data;
end;
function pandora_gfx.spriteram_r16(offset:word):byte;
begin
spriteram_r16:=self.sprite_ram[offset shr 1];
end;
end.
|
unit NOT_FINISHED_l3ProgressComponent;
{* Базовый класс компонентов, имеющих индикатор прогресса. }
// Модуль: "w:\common\components\rtl\Garant\L3\NOT_FINISHED_l3ProgressComponent.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tl3ProgressComponent" MUID: (4754200F029E)
{$Include w:\common\components\rtl\Garant\L3\l3Define.inc}
interface
uses
l3IntfUses
, l3InterfacedComponent
, l3Interfaces
;
type
Tl3ProgressComponent = class(Tl3InterfacedComponent, Il3Progress)
{* Базовый класс компонентов, имеющих индикатор прогресса. }
protected
procedure Start(Count: Integer;
const aMsg: Il3CString); overload;
{* начать процесс. }
procedure Start(Count: Large;
const aMsg: Il3CString); overload;
{* начать процесс. }
procedure Finish;
{* закончить процесс. }
procedure Progress(Current: Integer); overload;
{* изменить текущее состояние. }
procedure Progress(Current: Large); overload;
{* изменить текущее состояние. }
procedure ProgressEx(Current: Integer;
const aMsg: Il3CString);
procedure ChangeIO(Start: Boolean);
{* изменить флаг InIO. }
function InIO: Boolean;
{* в процессе ввода/вывода? }
function InUse: Boolean;
end;//Tl3ProgressComponent
implementation
uses
l3ImplUses
{$If NOT Defined(NoScripts)}
, TtfwClassRef_Proxy
{$IfEnd} // NOT Defined(NoScripts)
//#UC START# *4754200F029Eimpl_uses*
//#UC END# *4754200F029Eimpl_uses*
;
procedure Tl3ProgressComponent.Start(Count: Integer;
const aMsg: Il3CString);
{* начать процесс. }
//#UC START# *476F75DE01E9_4754200F029E_var*
//#UC END# *476F75DE01E9_4754200F029E_var*
begin
//#UC START# *476F75DE01E9_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.Start not implemented');
//#UC END# *476F75DE01E9_4754200F029E_impl*
end;//Tl3ProgressComponent.Start
procedure Tl3ProgressComponent.Start(Count: Large;
const aMsg: Il3CString);
{* начать процесс. }
//#UC START# *476F75F60302_4754200F029E_var*
//#UC END# *476F75F60302_4754200F029E_var*
begin
//#UC START# *476F75F60302_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.Start not implemented');
//#UC END# *476F75F60302_4754200F029E_impl*
end;//Tl3ProgressComponent.Start
procedure Tl3ProgressComponent.Finish;
{* закончить процесс. }
//#UC START# *476F7608002D_4754200F029E_var*
//#UC END# *476F7608002D_4754200F029E_var*
begin
//#UC START# *476F7608002D_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.Finish not implemented');
//#UC END# *476F7608002D_4754200F029E_impl*
end;//Tl3ProgressComponent.Finish
procedure Tl3ProgressComponent.Progress(Current: Integer);
{* изменить текущее состояние. }
//#UC START# *476F76160143_4754200F029E_var*
//#UC END# *476F76160143_4754200F029E_var*
begin
//#UC START# *476F76160143_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.Progress not implemented');
//#UC END# *476F76160143_4754200F029E_impl*
end;//Tl3ProgressComponent.Progress
procedure Tl3ProgressComponent.Progress(Current: Large);
{* изменить текущее состояние. }
//#UC START# *476F7637011A_4754200F029E_var*
//#UC END# *476F7637011A_4754200F029E_var*
begin
//#UC START# *476F7637011A_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.Progress not implemented');
//#UC END# *476F7637011A_4754200F029E_impl*
end;//Tl3ProgressComponent.Progress
procedure Tl3ProgressComponent.ProgressEx(Current: Integer;
const aMsg: Il3CString);
//#UC START# *476F76450378_4754200F029E_var*
//#UC END# *476F76450378_4754200F029E_var*
begin
//#UC START# *476F76450378_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.ProgressEx not implemented');
//#UC END# *476F76450378_4754200F029E_impl*
end;//Tl3ProgressComponent.ProgressEx
procedure Tl3ProgressComponent.ChangeIO(Start: Boolean);
{* изменить флаг InIO. }
//#UC START# *476F76550369_4754200F029E_var*
//#UC END# *476F76550369_4754200F029E_var*
begin
//#UC START# *476F76550369_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.ChangeIO not implemented');
//#UC END# *476F76550369_4754200F029E_impl*
end;//Tl3ProgressComponent.ChangeIO
function Tl3ProgressComponent.InIO: Boolean;
{* в процессе ввода/вывода? }
//#UC START# *476F76660313_4754200F029E_var*
//#UC END# *476F76660313_4754200F029E_var*
begin
//#UC START# *476F76660313_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.InIO not implemented');
//#UC END# *476F76660313_4754200F029E_impl*
end;//Tl3ProgressComponent.InIO
function Tl3ProgressComponent.InUse: Boolean;
//#UC START# *476F767601FC_4754200F029E_var*
//#UC END# *476F767601FC_4754200F029E_var*
begin
//#UC START# *476F767601FC_4754200F029E_impl*
assert(false, 'Tl3ProgressComponent.InUse not implemented');
//#UC END# *476F767601FC_4754200F029E_impl*
end;//Tl3ProgressComponent.InUse
initialization
{$If NOT Defined(NoScripts)}
TtfwClassRef.Register(Tl3ProgressComponent);
{* Регистрация Tl3ProgressComponent }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit NonrectangularForm;
interface
Uses Windows, Graphics, Forms, Controls, Dialogs, SysUtils, Types,
l3Forms, l3Region;
const
cTransparentColor = $123456;
type
TNonrectangularForm = class(Tl3Form)
private
f_Region: Tl3Region;
f_BorderColor: TColor;
procedure pm_SetBorderColor(Value: TColor);
protected
procedure Cleanup; override;
procedure DoCreate; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure Paint; override;
procedure TuneRegion(aRegion: Tl3Region); virtual;
public
property BorderColor: TColor
read f_BorderColor
write pm_SetBorderColor;
end;
implementation
procedure TNonrectangularForm.DoCreate;
begin
BorderStyle := bsNone;
f_BorderColor := clSilver;
if SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYERED) = 0 then
ShowMessage(SysErrorMessage(GetLastError));
if not SetLayeredWindowAttributes(Handle, cTransparentColor, 128, LWA_COLORKEY) then
ShowMessage(SysErrorMessage(GetLastError));
inherited ;
end;
procedure TNonrectangularForm.Cleanup;
begin
FreeAndNil(f_Region);
inherited ;
end;
procedure TNonrectangularForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := Params.Style or WS_POPUP;
end;
procedure TNonrectangularForm.pm_SetBorderColor(Value: TColor);
begin
if f_BorderColor <> Value then
begin
f_BorderColor := Value;
Invalidate;
end;
end;
procedure TNonrectangularForm.TuneRegion(aRegion: Tl3Region);
var
l_R : Tl3Region;
const
cSpace = 16;
begin
l_R := Tl3Region.Create;
try
l_R.Rgn := CreateRoundRectRgn(Left + cSpace, Top, Width, Height, cSpace, cSpace);
aRegion.Combine(l_R, RGN_OR);
finally
FreeAndNil(l_R);
end;
end;
procedure TNonrectangularForm.Paint;
begin
Canvas.Pen.Style := psSolid;
Canvas.Brush.Color := cTransparentColor;
Canvas.FillRect(Rect(0, 0, Width, Height));
Canvas.Brush.Color := Self.Color;
try
if f_Region = nil then
begin
f_Region := Tl3Region.Create;
f_Region.Rgn := CreateRectRgnIndirect(Rect(0, 0, Width-1, Height-1));
end;
// Это временное решение. Планируется:
// 1) TuneRegion() вынести за пределы Paint-а
// 2) f_Region надо заменить на TvgPath
TuneRegion(f_Region);
PaintRgn(Canvas.Handle, f_Region.Rgn);
Canvas.Brush.Color := f_BorderColor;
FrameRgn(Canvas.Handle, f_Region.Rgn, Canvas.Brush.Handle, 2, 2);
finally
FreeAndNil(f_Region);
end;
inherited ;
end;
end.
|
unit DirectAccessDaapi;
interface
uses
classes, System.DateUtils, System.IOUtils,
TCWODT, DBISAMTB, FFSSortTable, FFSRptsTable, FFSLogTable, FFSUserGrpTable,
FFSTypes, FFSUserTable, FFSPasswordOptionsTable, TTSPasswordTable, FFSLendGrpTable, printers, programsettings, LMDProcs,
FFSProcessTable, FFSProcDefTable, TicklerTypes, TTSSemTable, TicklerGlobals, TTSJobTable;
type
TDirectDaapi = class(TDAAPI, IDaapiGlobal)
private
RegFile: TFileStream;
// Registration
Registration: TRegistrationRecord;
// other
WorkBuf: PBuffer;
SaveSortState: boolean;
tblSort: TFFSSortTable;
tblPerm: TFFSUserGrpTable;
tblUser: TFFSUserTable;
tblPasswordOptions: TFFSPasswordOptionsTable;
tblSem: TTTSSemTable;
tblPassword: TTTSPasswordTable;
tblLendGrp: TFFSLendGrpTable;
function LendGetDescriptionString(ALenderNumber: string): string;
// Registration
procedure OpenRegistration;
procedure RegistrationUpdate;
protected
FSession: TDbIsamSession;
FDatabase: TDBISAMDatabase;
FBaseDirectory: string;
tblLog: TFFSLogTable;
tblProcess: TFFSProcessTable;
tblProcDef: TFFSProcDefTable;
tbljob: TTTSJobtable;
procedure OpenSecurity;
procedure CloseSecurity;
public
constructor Create(AOwner: TComponent; ADataPath: string); reintroduce;
destructor Destroy; override;
procedure Shutdown;
// Updating
function UpdateFileCheck(AFileList: string): string; // Check the filelist, return names of files that need to be updated
// Tables & Database
procedure CloseBaseTables; virtual;
procedure OpenBaseTables; virtual;
procedure RepairBaseTables; virtual;
// Logging
procedure LogMessage(LogMsg, UserName, MsgClass: string);
function LogGetRecord(RecNo: integer): string;
procedure LogClearFile;
function LogGetCount: integer;
function LogGetAll(rectype:String): string;
// Security
function SecureRegistered: Boolean; overload;
function SecureRegistered(out aDaysLeft: Integer): Boolean; overload;
function SecureWSActivated(WSSerial: string): boolean;
function SecureConnectUser: integer;
procedure SecureSetNumberOfUsers(n: integer);
function SecureGetNumberOfUsers: integer;
function SecureActivateSerial(CSerial: string): Boolean;
function SecureCheckRunCount: boolean;
procedure SecureSetNumberOfUses(UseCount: integer);
procedure SecureActivateInitial(ARunCount: integer);
procedure SecureSetAutoRegisterCount(RegCount: integer);
function SecureAutoRegister(CSerial: string): boolean;
function SecureCanAutoRegister: boolean;
// Lender
function LendGetList: string; virtual;
function LendGetNumAndNameList: string; virtual;
function LendGetShortRecord(ALender: TStringLender): string; virtual;
function LendGetLendHeaders: string; virtual;
function LendGetDescription(ALender: TStringLender): string; virtual;
procedure LendDelete(ALender: TStringLender); virtual;
// Lender Groups
function LendGrpGetRecord(AGroupName: string): string;
procedure LendGrpAddUpdtRecord(AName, ADescription, ALendList: string);
procedure LendGrpDeleteRecord(AName: string);
function LendGrpGetNameList(csvflag: boolean): string;
function LendGrpGetMaintList: string;
function LendGrpGetListByName(AGroupName: string): string;
// Permission Groups
function PermGrpGetNameList: string;
function PermGrpGetRights(GrpName: string): string;
procedure PermGrpSetRights(GrpName, Rights: string);
procedure PermGrpDelGroup(GrpName: string);
function PermGrpExists(GrpName: string): boolean;
// User
function UserChangePassword(AUserName, OldPassword, NewPassword: string): boolean;
function UserValidateLogin(AUserName, APassword: string): boolean;
function UserGetPasswordStatus(AUserName, APassword: string): string;
function UserValidateLoginWithStatus(AUserName, APassword, AStatus: string): boolean;
function UserUpdateInvalidAttempts(AUserName: string; ACount: integer): boolean;
function UserUnlockAccount(AUserName: string): boolean;
function UserValidatePassword(APassword: string): Boolean;
function PasswordPeriodCheck: boolean;
procedure UserAddRecord(AUser: TFFSUserRecord);
procedure UserUpdateRecord(AUser: TFFSUserRecord);
procedure UserDelete(AuserName: string);
function UserGetLogged: string;
function UserGetNameList: string;
function UserGetRecord(AUserName: string): TFFSUserRecord;
procedure UserGetMaintList(AList: TStringList);
procedure UserLogin(AUserName: string);
procedure UserLogout(AUserName, LastLender: string);
function UserNameIsUser(AUserName: string): boolean;
function UserGetUserID(AWinUser: string): string;
procedure SemReleaseNum;
procedure CorrectUserWithSem;
procedure WriteDefaultPasswordOptionsRecord;
function PasswordOptionsGetRecord: TFFSPasswordOptionsRecord;
procedure PasswordOptionsAddRecord(AUser: TFFSPasswordOptionsRecord);
procedure PasswordOptionsUpdateRecord(AUser: TFFSPasswordOptionsRecord);
procedure PasswordOptionsDelete(AuserName: string);
procedure PasswordCheckEncryptionVersion;
function PasswordGetRecord(AUser, APassword: string): TTTSPasswordRecord;
procedure PasswordAddRecord(AUser: TTTSPasswordRecord);
procedure PasswordUpdateRecord(OldRec, NewRec: TTTSPasswordRecord);
procedure PasswordDelete(AuserName, APassword: string);
function PasswordCheckPrevious(AUserName, APassword: string): Boolean;
function SemGetAvailableNum: Integer;
// Server Printers
procedure ServerPrinters(var aPrinterList: TStringList);
// Files
function DownloadFile(Dest: string; SrcName: string; SrcDir: TFFSDirectory): boolean;
procedure DownloadBlock(SrcName: string; SrcDir: TFFSDirectory; var buf: PBuffer; start, bufsize: integer; var BytesRead, AFileSize, AFileAge: integer);
function UploadFile(Source: string; DestName: string; DestDir: TFFSDirectory): boolean;
procedure UploadBlock(DestName: string; DestDir: TFFSDirectory; var buf: PBuffer; start, bufsize, AFileAge: integer; var BytesWritten: integer);
procedure FileDelete(FileName: string; FFSDir: TFFSDirectory);
// Reports
procedure ProcessAbort(ARptID: integer);
function ProcessGetStatus(ARptID: integer): TFFSReportStatus;
procedure ProcDefSaveRecord(ALendList, AOptions: string; ARecord: TFFSPROCDEFRecord);
function ProcDefLoadRecord(AProcessId: integer): TFFSPROCDEFRecord;
function ProcDefLoadOptions(AProcessId: integer): string;
//jobs
procedure JobUpdateRecord(Ajob: TTTSJobRecord);
procedure JobDelete(aAutoInc: integer);
function JobGetRecord(aAutoInc: integer): TTTSJOBRecord;
end;
implementation
uses sysutils, FFSUtils, db, filectrl, Math;
function TDirectDaapi.UserChangePassword(AUserName, OldPassword, NewPassword: string): boolean;
begin
result := false;
if AUserName = SysAdmin then exit;
tblUser.refresh;
if tblUser.FindKey([AUserName]) then begin
if OldPassword = tblUser.PPassword then begin
tblUser.edit;
tblUser.PPassword := NewPassword;
tblUser.post;
result := true;
end;
end;
end;
procedure TDirectDaapi.CloseBaseTables;
begin
tblLendGrp.Active := false;
tblUser.active := false;
tblPasswordOptions.active := false;
tblSem.Active := false;
tblPassword.active := false;
tblPerm.Active := false;
tblLog.Active := false;
tblSort.Active := false;
if Assigned(RegFile) then
FreeAndNil(RegFile);
tblProcess.Active := false;
tblProcDef.Active := false;
tbljob.Active := false;
end;
procedure TDirectDaapi.CloseSecurity;
begin
tblSort.Active := SaveSortState;
end;
constructor TDirectDaapi.Create(AOwner: TComponent; ADataPath: string);
begin
inherited create(AOwner);
// private session
FSession := TDBISAMSession.Create(self);
FSession.AutoSessionName := true;
FSession.StrictChangeDetection := true;
FSession.Open;
// now the base directory
FBaseDirectory := ADataPath;
if FBaseDirectory = '' then raise Exception.Create('No Datapath given');
FBaseDirectory := IncludeTrailingBackslash(FBaseDirectory);
MakeDirs([]);
// connect the database
FDatabase := TDbisamDatabase.Create(FSession);
FDatabase.SessionName := FSession.SessionName;
FDatabase.Directory := FBaseDirectory + 'DATA';
FDatabase.DatabaseName := 'DADAAPI' + FSession.SessionName;
FDatabase.Connected := true;
// Create the tables
tblSort := TFFSSortTable.create(self, FDataBase, 'Sort');
tblLog := TFFSLogTable.create(self, FDatabase, 'Log');
tblPerm := TFFSUserGrpTable.create(self, FDatabase, 'UserGrp');
tblUser := TFFSUserTable.create(self, FDatabase, 'User');
tblPasswordOptions := TFFSPasswordOptionsTable.create(self, FDatabase, 'PasswordOptions');
tblSem := TTTSSemTable.create(self, FDatabase, 'Sem');
tblPassword := TTTSPasswordTable.create(self, FDatabase, 'Password');
tblLendGrp := TFFSLendGrpTable.create(self, FDatabase, 'LendGrp');
tblProcess := TFFSPROCESSTable.create(self, FDatabase, 'Process');
tblProcDef := TFFSPROCDEFTable.create(self, FDatabase, 'ProcDef');
tbljob := TTTSJOBTable.create(Self, Fdatabase, 'Job');
// buffer
GetMem(WorkBuf, MaxBufferIndex);
end;
procedure TDirectDaapi.LogClearFile;
begin
tblLog.First;
while not tblLog.Eof do tblLog.Delete;
end;
function TDirectDaapi.LogGetCount: integer;
begin
result := tblLog.RecordCount;
end;
function TDirectDaapi.LogGetRecord(RecNo: integer): string;
begin
try
tblLog.RecNo := RecNo;
result := tblLog.GetCSV('');
except
result := '';
end;
end;
procedure TDirectDaapi.LogMessage(LogMsg, UserName, MsgClass: string);
begin
tblLog.Append;
tblLog.PUserID := UserName;
tblLog.PRecordType := msgclass;
tblLog.PLogMessage := LogMsg;
tblLog.PDateStamp := DateTimeStamp;
tblLog.post;
end;
procedure TDirectDaapi.OpenBaseTables;
begin
OpenRegistration;
tblSort.OpenUp;
tblLog.OpenUp;
tblPerm.OpenUp;
tblPerm.close; // No need to keep open. Opened on demand
tblUser.OpenUp;
tblPasswordOptions.OpenUp;
if tblPasswordOptions.RecordCount = 0 then
WriteDefaultPasswordOptionsRecord;
tblSem.OpenUp;
tblPassword.OpenUp;
tblLendGrp.OpenUp;
tblProcess.Openup;
tblProcDef.OpenUp;
tbljob.openup;
end;
procedure TDirectDaapi.OpenSecurity;
begin
SaveSortState := tblSort.Active;
tblSort.OpenUp;
end;
procedure TDirectDaapi.SecureActivateInitial(ARunCount: integer);
begin
if not Registration.SystemActivated then begin
Registration.SystemActivated := true;
Registration.UserCount := 1;
if ARunCount > 0 then begin
Registration.RunsAllowed := ARunCount;
Registration.RunCount := 0;
end;
RegistrationUpdate;
end;
end;
procedure TDirectDaapi.RegistrationUpdate;
begin
RegFile.Position := 0;
RegFile.Write(Registration, SizeOf(Registration));
end;
function TDirectDaapi.SecureActivateSerial(CSerial: string): Boolean;
var SerRec: TDriveSerial;
begin
Result := true; // default
if CSerial = '0' then exit;
Result := SecureWSActivated(CSerial);
if not Result then
begin
RegFile.Seek(0, soEnd);
SerRec := CSerial;
RegFile.Write(SerRec, SizeOf(SerRec));
end;
end;
function TDirectDaapi.SecureAutoRegister(CSerial: string): boolean;
var testdate: TFFSDate;
begin
result := true;
if SecureWSActivated(CSerial) then exit;
result := false;
if not Registration.CanAutoActivate then exit;
testdate := ConvertToDate(Registration.AutoDate);
if testdate < GetglSystemDate then exit; // outside the date range;
if Registration.AutoCount <= 0 then exit; // no more left
// we're here so we can complete the auto
dec(Registration.AutoCount);
RegistrationUpdate;
SecureActivateSerial(CSerial);
result := true;
end;
function TDirectDaapi.SecureCanAutoRegister: boolean;
begin
result := Registration.CanAutoActivate
and (Registration.AutoCount > 0)
and (GetGlSystemDate <= ConvertToDate(Registration.AutoDate));
end;
function TDirectDaapi.SecureCheckRunCount: boolean;
begin
result := true;
if Registration.RunsAllowed > 0 then begin
inc(Registration.RunCount);
RegistrationUpdate;
result := Registration.RunCount <= Registration.RunsAllowed;
end;
end;
procedure TDirectDaapi.SemReleaseNum;
begin
tblSem.EnumIndex := TTSSemBySemNum;
if tblSem.FindKey([CurrentSemaphore]) then begin
tblSort.UnlockSemaphore(CurrentSemaphore); //2012
tblSem.Delete;
end;
end;
function TDirectDaapi.SemGetAvailableNum: Integer;
var
i: integer;
begin
tblSem.EnumIndex := TTSSemBySemNum;
tblSem.First;
i := 1;
while not tblSem.eof do
begin
if tblSem.PSemNum <> i then break;
i := i + 1;
tblSem.Next;
end;
result := i;
end;
function TDirectDaapi.SecureConnectUser: integer;
var
x: integer;
success: boolean;
begin
Result := 0;
tblSem.EnumIndex := TTSSemByUserName;
if tblSem.FindKey([CurrentUser.PUserName]) then begin
success := tblSort.LockSemaphore(tblSem.PSemNum);
if not success then
begin
x := SemGetAvailableNum;
// Limit the number of users, unless this is still a trial period
if (x > Registration.UserCount) and SecureRegistered then
result := 0
else
begin
success := tblSort.LockSemaphore(x);
if not success then result := -1
else
begin
tblSem.Append;
tblSem.PUserName := CurrentUser.PUserName;
tblSem.PSemNum := x;
tblSem.post;
result := x;
end;
end;
end else
Result := tblSem.PSemNum;
end
else
begin
x := SemGetAvailableNum;
// Limit the number of users, unless this is still a trial period
if (x > Registration.UserCount) and SecureRegistered then
result := 0
else
begin
success := tblSort.LockSemaphore(x);
// Try unlock semaphore.
if not success then
tblSort.UnlockSemaphore(x); // added JAn 2016
//
// if not success then result := -1 //commented jan 2016
// else
// begin
tblSem.Append;
tblSem.PUserName := CurrentUser.PUserName;
tblSem.PSemNum := x;
tblSem.post;
result := x;
//end; //commented jan 2016
end;
end;
if result > 0 then
CurrentSemaphore := result;
end;
function TDirectDaapi.SecureRegistered: Boolean;
begin
Result := Registration.SystemActivated;
end;
function TDirectDaapi.SecureRegistered(out aDaysLeft: Integer): Boolean;
var
InitialRunDate: TDateTime;
begin
try
// Check the number of days elapsed since the first run
InitialRunDate := DateStrToDate(Registration.InitialRunDate, GetglDateFmt);
aDaysLeft := 60 - DaysBetween(InitialRunDate, Now);
if aDaysLeft < 0 then
aDaysLeft := 0;
Result := Registration.SystemActivated;
except
Result := false;
end;
end;
procedure TDirectDaapi.SecureSetAutoRegisterCount(RegCount: integer);
begin
Registration.CanAutoActivate := true;
Registration.AutoCount := RegCount;
Registration.AutoDate := DateToShortString(GetglSystemDate + 14);
RegistrationUpdate;
end;
procedure TDirectDaapi.SecureSetNumberOfUsers(n: integer);
begin
Registration.UserCount := n;
RegistrationUpdate;
end;
procedure TDirectDaapi.SecureSetNumberOfUses(UseCount: integer);
begin
Registration.RunsAllowed := UseCount;
Registration.RunCount := 0;
RegistrationUpdate;
end;
function TDirectDaapi.SecureWSActivated(WSSerial: string): boolean;
var SerRec: TDriveSerial;
blkread: integer;
begin
result := false;
RegFile.Seek(SizeOf(Registration), soBeginning); // move pointer to first Workstation record
repeat
blkread := RegFile.Read(SerRec, SizeOf(SerRec));
if blkread = SizeOf(SerRec) then begin
if wsserial = SerRec then result := true;
end;
until (result = true) or (blkread <> sizeof(SerRec));
end;
procedure TDirectDaapi.Shutdown;
begin
end;
procedure TDirectDaapi.PermGrpDelGroup(GrpName: string);
begin
tblPerm.Active := true;
if tblPerm.findkey([GrpName]) then tblPerm.delete;
tblperm.Active := false;
end;
function TDirectDaapi.PermGrpExists(GrpName: string): boolean;
begin
tblPerm.Active := true;
result := tblPerm.findkey([GrpName]);
tblPerm.active := false;
end;
function TDirectDaapi.PermGrpGetNameList: string;
begin
tblPerm.active := true;
result := CsvQuote('No Restrictions');
while not tblPerm.eof do begin
result := result + ',' + CsvQuote(tblPerm.PName);
tblPerm.next;
end;
tblPerm.active := false;
end;
function TDirectDaapi.PermGrpGetRights(GrpName: string): string;
begin
tblPerm.active := true;
if GrpName = EmptyStr then result := RepeatChar('Y', PermissionMax)
else if tblPerm.findkey([GrpName]) then begin
tblPerm.active := true;
result := tblPerm.PRights;
tblPerm.active := false;
end
else result := repeatchar('N', PermissionMax);
end;
procedure TDirectDaapi.PermGrpSetRights(GrpName, Rights: string);
begin
tblPerm.active := true;
if not tblPerm.findkey([GrpName]) then begin
tblPerm.append;
tblPerm.PName := GrpName;
end
else tblPerm.edit;
tblPerm.PRights := Rights;
tblPerm.Post;
end;
procedure TDirectDaapi.UserLogin(AUserName: string);
begin
if AUserName = SysAdmin then exit;
//if (AUserName = SysAdmin) then AUserName := '*'; // jan 2016
tblUser.refresh;
tbluser.Filter := 'UserName=' + QuotedStr(AUserName);
tblUser.FilterOptions := [foCaseInsensitive];
tbluser.Filtered := True;
// if tblUser.findkey([AUserName]) then begin
if tbluser.FindFirst then begin
tblUser.edit;
tblUser.PLoggedInStamp := DateTimeStamp;
tblUser.PLoggedOutStamp := ''; //blank
tblUser.PLoggedInFlag := True;
tblUser.post;
end;
tbluser.Filtered := False; // bug with next login 2012
end;
procedure TDirectDaapi.UserLogout(AUserName, LastLender: string);
begin
//if (trim(AUserName) = '') or (AUserName = SysAdmin) then exit;
if (trim(AUserName) = '') then exit;
if (AUserName = SysAdmin) then AUserName := '*';
tblUser.Refresh;
if tblUser.FindKey([AUserName]) then begin
tblUser.edit;
tblUser.PLoggedInFlag := False;
tblUser.PLoggedOutStamp := DateTimeStamp;
tblUser.PLastLender := LastLender;
tblUser.post;
end;
end;
function TDirectDaapi.UserValidateLogin(AUserName, APassword: string): boolean;
begin
result := false;
tblUser.refresh;
tbluser.Filter := 'UserName=' + QuotedStr(AUserName);
tblUser.FilterOptions := [foCaseInsensitive];
tbluser.Filtered := True;
if tbluser.FindFirst then result := tblUser.PPassword = APassword;
//if tblUser.FindKey([AUserName]) then result := tblUser.PPassword = APassword;
if result = false then if tblUser.FindKey([uppercase(AUserName)]) then result := uppercase(tblUser.PPassword) = uppercase(APassword);
//tbluser.Filtered := False; //2012
if Result = False then tbluser.Filtered := False; //2012
end;
function TDirectDaapi.UserGetPasswordStatus(AUserName, APassword: string): string;
var
found: boolean;
begin
found := false;
tblUser.refresh;
result := '';
tbluser.Filter := 'UserName=' + QuotedStr(AUserName);
tbluser.FilterOptions := [foCaseInsensitive];
tbluser.Filtered := True;
//if tblUser.FindKey([AUserName]) then found := true; //tblUser.PPassword = APassword;
if tbluser.FindFirst then found := true;
if (found = true) then
begin
tblPassword.EnumIndex := TTSPasswordByUserPassword;
if (tblPassword.FindKey([AUserName, APassword])) then result := tblPassword.PStatus;
// tbluser.Filtered := False; // bug with next login 2012
end;
end;
function TDirectDaapi.UserValidateLoginWithStatus(AUserName, APassword, AStatus: string): boolean;
begin
result := false;
tblUser.refresh;
if tblUser.FindKey([AUserName]) then result := tblUser.PPassword = APassword;
if (result = true) then
begin
tblPassword.EnumIndex := TTSPasswordByUserPasswordStatus;
if (tblPassword.FindKey([AUserName, APassword, AStatus])) then result := true;
end;
end;
function TDirectDaapi.UserUpdateInvalidAttempts(AUserName: string; ACount: integer): boolean;
begin
result := false;
tblPassword.EnumIndex := TTSPasswordByUserStatus;
if (tblPassword.FindKey([AUserName, 'Active'])) then
begin
tblPassword.Edit;
if (ACount > 0) then
begin
if (tblPassword.PInvalidAttempts + ACount >= tblPasswordOptions.PMaxLoginAttempts) then
begin
tblPassword.PStatus := 'Locked';
end;
tblPassword.PInvalidAttempts := tblPassword.PInvalidAttempts + ACount;
end
else
begin
tblPassword.PInvalidAttempts := 0;
end;
tblPassword.PLastLoginAttempt := now;
tblPassword.post;
end;
if (tblPassword.FindKey([AUserName, 'Locked'])) then result := true;
end;
function TDirectDaapi.UserUnlockAccount(AUserName: string): Boolean;
var
statusActive: boolean;
//s: String;
t1, t2: TDateTime;
diffsecs: Double;
hrs, mins, secs, msecs, days: word;
begin
result := false;
statusActive := false;
t1 := now;
t2 := tblPassword.PLastLoginAttempt;
diffsecs := t1 - t2;
decodetime(diffsecs, hrs, mins, secs, msecs);
days := floor(t1 - t2);
//s := datetimetostr(now) + ' - ' + datetimetostr(tblPassword.PLastLoginAttempt) + ' = ' + 'Days = ' + floattostr(days) + ' Hours = ' + floattostr(hrs) + ' Mins = ' + floattostr(mins) + ' Secs = ' + floattostr(secs);
// MsgInformation(s);
tblPassword.EnumIndex := TTSPasswordByUserStatus;
if (tblPassword.FindKey([AUserName, 'Locked'])) then
begin
if (uppercase(tblPasswordOptions.PAutoReset) = 'YES') then
begin
if (tblPasswordOptions.PAutoResetUnit = 'D') then
begin
if (now - tblPassword.PLastLoginAttempt >= tblPasswordOptions.PAutoResetPeriod) then
begin
statusActive := true;
end;
end;
if (tblPasswordOptions.PAutoResetUnit = 'H') then
begin
if (((days * 24) + (hrs * 60)) >= tblPasswordOptions.PAutoResetPeriod) then
begin
statusActive := true;
end;
end;
if (tblPasswordOptions.PAutoResetUnit = 'M') then
begin
if (((days * 24) + (hrs * 60) + mins) >= tblPasswordOptions.PAutoResetPeriod) then
begin
statusActive := true;
end;
end;
end;
end;
if statusActive then
begin
tblPassword.edit;
tblPassword.PInvalidAttempts := 0;
tblPassword.PStatus := 'Active';
tblPassword.post;
result := false;
end;
end;
function TDirectDaapi.UserValidatePassword(APassword: string): Boolean;
var
j, found, criteria: integer;
alpha_found, upper_found, lower_found, numeric_found, symbol_found: boolean;
begin
if (length(trim(APassword)) = 0) then
begin
result := tblPasswordOptions.PMinLength = 0;
exit;
end;
alpha_found := false;
upper_found := false;
lower_found := false;
numeric_found := false;
symbol_found := false;
result := false;
APassword := EncryptionWithPassword(APassword, PassKey, false);
found := 0;
tblPasswordOptions.Refresh;
{ criteria := 0;
if (ALPHA_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
for j := 0 to length(APassword) do if (APassword[j] in ['A'..'Z','a'..'z']) then
begin
found := found + 1;
criteria := criteria + ALPHA_CHAR;
break;
end;
end;
if (UPPER_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
for j := 0 to length(APassword) do if (APassword[j] in ['A'..'Z']) then
begin
found := found + 1;
criteria := criteria + UPPER_CHAR;
break;
end;
end;
if (LOWER_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
for j := 0 to length(APassword) do if (APassword[j] in ['a'..'z']) then
begin
found := found + 1;
criteria := criteria + LOWER_CHAR;
break;
end;
end;
if (NUMERIC_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
for j := 0 to length(APassword) do if (APassword[j] in ['0'..'9']) then
begin
found := found + 1;
criteria := criteria + NUMERIC_CHAR;
break;
end;
end;
if (SYMBOL_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
}// for j := 0 to length(APassword) do if (APassword[j] in ['~','!','@','#','$','%','^','&','*','(',')','{','}','[',']','|','\',':',';','"','<',',','>','.','?','/','''','+','-','=','_','`']) then
{ begin
found := found + 1;
criteria := criteria + SYMBOL_CHAR;
break;
end;
end;
}
criteria := tblPasswordOptions.PCriteria;
for j := 0 to length(APassword) do
begin
if (APassword[j] in ['A'..'Z', 'a'..'z']) then
begin
if (ALPHA_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
if (not alpha_found) then
begin
found := found + 1;
alpha_found := true;
end;
end;
if ((ALPHA_CHAR and criteria) = 0) then criteria := criteria + ALPHA_CHAR;
end;
if (APassword[j] in ['A'..'Z']) then
begin
if (UPPER_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
if (not upper_found) then
begin
found := found + 1;
upper_found := true;
end;
end;
if ((UPPER_CHAR and criteria) = 0) then criteria := criteria + UPPER_CHAR;
end;
if (APassword[j] in ['a'..'z']) then
begin
if (LOWER_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
if (not lower_found) then
begin
found := found + 1;
lower_found := true;
end;
end;
if ((LOWER_CHAR and criteria) = 0) then criteria := criteria + LOWER_CHAR;
end;
if (APassword[j] in ['0'..'9']) then
begin
if (NUMERIC_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
if (not numeric_found) then
begin
found := found + 1;
numeric_found := true;
end;
end;
if ((NUMERIC_CHAR and criteria) = 0) then criteria := criteria + NUMERIC_CHAR;
end;
if (APassword[j] in ['~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '{', '}', '[', ']', '|', '\', ':', ';', '"', '<', ',', '>', '.', '?', '/', '''', '+', '-', '=', '_', '`']) then
begin
if (SYMBOL_CHAR and tblPasswordOptions.PCriteria > 0) then
begin
if (not symbol_found) then
begin
found := found + 1;
symbol_found := true;
end;
end;
if ((SYMBOL_CHAR and criteria) = 0) then criteria := criteria + SYMBOL_CHAR;
end;
end;
if (found >= tblPasswordOptions.PCriteriaCount) then result := true;
// if ( (tblPasswordOptions.PCriteria <> criteria) ) then result := false;
end;
function TDirectDaapi.PasswordPeriodCheck: boolean;
begin
result := false;
if (now - tblPassword.PCreated <= tblPasswordOptions.PExpireDays) then result := true;
end;
function TDirectDaapi.UserGetRecord(AUserName: string): TFFSUserRecord;
var
s: string;
begin
Fillchar(result, sizeof(result), 0);
result := result;
if AUserName = SysAdmin then begin
if tblUser.FindKey(['*']) then result := tblUser.GetDataBuffer;
with result do begin
PUserName := SysAdmin;
PRealName := 'System Administrator';
// PLastLender := '';
PUserGroup := '';
PLenderGroup := '';
PUserTable := true;
PAccessGroups := true;
PLenderGroups := true;
end;
exit;
end
else begin
tbluser.refresh;
if tblUser.FindKey([AUserName]) then result := tblUser.GetDataBuffer;
if (applySecurity) then
begin
tblPassword.EnumIndex := TTSPasswordByUserStatus;
if (tblPassword.FindKey([AUserName, 'Active'])) then
begin
result.PPassword := tblPassword.PPassword;
end
else
begin
if (tblPassword.FindKey([AUserName, 'Change'])) then
begin
result.PPassword := tblPassword.PPassword;
end;
end;
end;
s := EncryptionWithPassword(result.PPassword, PassKey, false);
//result.PPassword := EncryptionWithPassword(result.PPassword,PassKey,true);
end;
end;
function TDirectDaapi.UserGetNameList: string;
begin
tblUser.refresh;
tblUser.first;
result := '';
while not tblUser.eof do begin
if result > '' then result := result + ',';
result := result + CsvQuote(tblUser.PUserName);
tblUser.next;
end;
end;
function TDirectDaapi.UserGetLogged: string;
begin
tblUser.refresh;
result := '';
tblUser.first;
while not tblUser.eof do begin
if tblUser.PLoggedInFlag then begin
if result > '' then result := result + ',';
result := result + CsvQuote(tblUser.PUserName) + ','
+ CsvQuote(tblUser.PRealName) + ','
+ CsvQuote(tblUser.PLoggedInStamp);
end;
tblUser.next;
end;
end;
procedure TDirectDaapi.UserAddRecord(AUser: TFFSUserRecord);
begin
tblUser.Refresh;
if not tblUser.FindKey([AUser.PUserName]) then begin
tblUser.append;
tblUser.StoreDataBuffer(AUser);
try
tblUser.Post;
except
tblUser.Cancel;
end;
end;
end;
procedure TDirectDaapi.UserUpdateRecord(AUser: TFFSUserRecord);
begin
tblUser.Refresh;
if Auser.PUserName = SysAdmin then Auser.Pusername := '*';
if tblUser.findkey([AUser.PUserName]) then begin
end
else
if tblUser.findkey([uppercase(AUser.PUserName)]) then begin
end
else exit;
tblUser.edit;
tblUser.StoreDataBuffer(AUser);
try
tblUser.Post;
except
if tblUser.State in [dsedit] then tblUser.Cancel;
end;
if Auser.PUserName = '*' then Auser.Pusername := sysadmin;
end;
procedure TDirectDaapi.UserDelete(AuserName: string);
begin
if (trim(AUserName) = '') or (AUserName = SysAdmin) then exit;
tblUser.Refresh;
if tblUser.FindKey([AUserName]) then tblUser.delete;
end;
procedure TDirectDaapi.WriteDefaultPasswordOptionsRecord;
begin
tblPasswordOptions.append;
tblPasswordOptions.PExpireDays := 90;
tblPasswordOptions.PHistorySize := 6;
tblPasswordOptions.PMinDaysUsage := 10;
tblPasswordOptions.PMinLength := 6;
tblPasswordOptions.PMinChangedChars := 3;
tblPasswordOptions.PMaxLoginAttempts := 6;
tblPasswordOptions.PNameInPassword := 'No';
tblPasswordOptions.PCriteriaCount := 2;
tblPasswordOptions.PCriteria := 14;
tblPasswordOptions.PAutoReset := 'No';
tblPasswordOptions.PAutoResetPeriod := 1;
tblPasswordOptions.PAutoResetUnit := 'D';
tblPasswordOptions.PLastUpdate := now;
tblPasswordOptions.PUserName := '*';
tblPasswordOptions.PEncryptionVersion := 1;
try
tblPasswordOptions.Post;
except
if tblPasswordOptions.State in [dsInsert] then
tblPasswordOptions.Cancel;
end;
end;
function TDirectDaapi.PasswordOptionsGetRecord(): TFFSPasswordOptionsRecord;
begin
Fillchar(result, sizeof(result), 0);
result := result;
tblPasswordOptions.refresh;
tblPasswordOptions.First;
result := tblPasswordOptions.GetDataBuffer;
end;
procedure TDirectDaapi.PasswordOptionsAddRecord(AUser: TFFSPasswordOptionsRecord);
begin
tblPasswordOptions.Refresh;
if not tblPasswordOptions.FindKey([AUser.PUserName]) then begin
tblPasswordOptions.append;
tblPasswordOptions.StoreDataBuffer(AUser);
try
tblPasswordOptions.Post;
except
tblPasswordOptions.Cancel;
end;
end;
end;
procedure TDirectDaapi.PasswordOptionsUpdateRecord(AUser: TFFSPasswordOptionsRecord);
begin
tblPasswordOptions.Refresh;
if tblPasswordOptions.findkey([AUser.PUserName]) then begin
tblPasswordOptions.edit;
tblPasswordOptions.StoreDataBuffer(AUser);
try
tblPasswordOptions.Post;
tblPassword.first;
{ while not tblPassword.Eof do begin //Uncheck this code in case passwords need to be reset when passwordoptions are changed
if tblPassword.PStatus = 'Active' then
begin
if not UserValidatePassword(tblPassword.PPassword) then
begin
tblPassword.edit;
tblPassword.PPassword := 'Change';
tblPassword.Next;
end;
end;
tblPassword.next;
end;
}except
if tblPasswordOptions.State in [dsedit] then tblPasswordOptions.Cancel;
// if tblPassword.State in [dsedit] then tblPassword.Cancel;
end;
end;
end;
procedure TDirectDaapi.PasswordOptionsDelete(AuserName: string);
begin
if (trim(AUserName) = '') or (AUserName = SysAdmin) then exit;
tblPasswordOptions.Refresh;
if tblPasswordOptions.FindKey([AUserName]) then tblPasswordOptions.delete;
end;
procedure TDirectDaapi.PasswordCheckEncryptionVersion;
var
tmpStr: string;
passwordRec: TTTSPasswordRecord;
begin
tblPasswordOptions.First;
if not tblPasswordOptions.Eof then
begin
if tblPasswordOptions.PEncryptionVersion < 1 then
begin
//Go through all records in tblUser and decrypt password using older version
//and encrypt password using newer version
tblUser.first;
while not tblUser.Eof do
begin
tblPassword.EnumIndex := TTSPasswordByUserPassword;
tmpStr := '';
tblPassword.SetRange([tblUser.PUserName], [tblUser.PUserName]);
tblPassword.First;
//If record not found in password table, then add one.
if tblPassword.eof then begin
tmpStr := EncryptionWithPassword(tblUser.PPassword, PassKey, true);
passwordRec.PUsername := tblUser.PUserName;
passwordRec.PPassword := tmpStr;
if length(trim(tmpStr)) = 0 then passwordRec.PStatus := 'Change'
else if UserValidatePassword(tmpStr) then passwordRec.PStatus := 'Active'
else passwordRec.PStatus := 'Change';
passwordRec.PCreated := now;
passwordRec.PInvalidAttempts := 0;
passwordRec.PLastLoginAttempt := now;
passwordRec.PModifiedBy := tblUser.PUserName;
PasswordAddRecord(passwordRec);
end
else begin
//Go through all records in tblPassword and decrypt password using older version
//and encrypt password using newer version
while not tblPassword.Eof do begin
tmpStr := EncryptionWithPasswordVer0(tblPassword.PPassword, PassKeyVer0, false);
tmpStr := EncryptionWithPassword(tmpStr, PassKey, true);
tblPassword.edit;
tblPassword.PPassword := tmpStr;
tblPassword.Next;
end;
tmpStr := EncryptionWithPasswordVer0(tblUser.PPassword, PassKeyVer0, false);
tmpStr := EncryptionWithPassword(tmpStr, PassKey, true);
end;
tblUser.edit;
tblUser.PPassword := tmpStr;
tblUser.post;
tblUser.Next;
end;
//Finally, set the value of EncryptionVersion to the current version
tblPasswordOptions.edit;
tblPasswordOptions.PEncryptionVersion := 1;
tblPasswordOptions.post;
end;
end;
end;
function TDirectDaapi.PasswordGetRecord(AUser, APassword: string): TTTSPasswordRecord;
var
s1, s2: string;
begin
Fillchar(result, sizeof(result), 0);
result := result;
tblPassword.EnumIndex := TTSPasswordByUserCreated;
tblPassword.First;
s1 := EncryptionWithPassword(APassword, PassKey, false);
tblPassword.SetRange([AUser], [AUser]);
while not tblPassword.Eof do
begin
s2 := EncryptionWithPassword(tblPassword.PPassword, PassKey, false);
if (trim(s1) = trim(s2)) then
begin
result := tblPassword.GetDataBuffer;
exit;
end;
tblPassword.Next;
end;
{ if tblPassword.FindKey([AUser, APassword]) then
begin
result := tblPassword.GetDataBuffer;
end;
if tblPassword.FindKey([AUser, APassword, 'Active']) then
begin
result := tblPassword.GetDataBuffer;
exit;
end;
if tblPassword.FindKey([AUser, APassword, 'Change']) then
begin
result := tblPassword.GetDataBuffer;
exit;
end;
if tblPassword.FindKey([AUser, APassword, 'Inactive']) then
begin
result := tblPassword.GetDataBuffer;
exit;
end;
if tblPassword.FindKey([AUser, APassword, 'Locked']) then
begin
result := tblPassword.GetDataBuffer;
exit;
end;
if tblPassword.FindKey([AUser, APassword, 'Xtria']) then
begin
result := tblPassword.GetDataBuffer;
exit;
end;}
end;
procedure TDirectDaapi.PasswordAddRecord(AUser: TTTSPasswordRecord);
var
s: string;
begin
s := EncryptionWithPassword(AUser.PPassword, PassKey, false);
tblPassword.EnumIndex := TTSPasswordByUserPassword;
if not tblPassword.FindKey([AUser.PUserName, AUser.PPassword]) then begin
tblPassword.append;
tblPassword.StoreDataBuffer(AUser);
try
tblPassword.Post;
except
tblPassword.Cancel;
end;
s := EncryptionWithPassword(tblUser.PPassword, PassKey, false);
s := s;
end
else begin
//IF PASSWORD IS ALREADY IN PASSWORD TABLE AND NEED TO BE RESUSED
tblPassword.edit;
tblPassword.PStatus := 'Change';
try
tblPassword.Post;
except
if tblPassword.State in [dsedit] then tblPassword.Cancel;
end;
end;
// NEED TO ADD CODE TO MAKE ALL OTHER ACTIVE PASSWORDS INACTIVE
end;
procedure TDirectDaapi.PasswordUpdateRecord(OldRec, NewRec: TTTSPasswordRecord);
var
numrecs: Integer;
s1, s2: string;
begin
tblPassword.EnumIndex := TTSPasswordByUserPassword;
s1 := EncryptionWithPassword(OldRec.PPassword, PassKey, false);
s2 := EncryptionWithPassword(NewRec.PPassword, PassKey, false);
if tblPassword.findkey([OldRec.PUserName, OldRec.PPassword]) then begin
tblPassword.edit;
tblPassword.PStatus := 'Inactive';
try
tblPassword.Post;
except
if tblPassword.State in [dsedit] then tblPassword.Cancel;
end;
tblPassword.EnumIndex := TTSPasswordByUserCreated;
tblPassword.SetRange([OldRec.PUserName], [OldRec.PUserName]);
numrecs := 0;
tblPassword.Last;
while not tblPassword.Bof do
begin
numrecs := numrecs + 1;
if numrecs >= tblPasswordOptions.PHistorySize then
begin
tblPassword.Delete;
end;
tblPassword.Prior;
end;
PasswordAddRecord(NewRec);
if tblUser.findkey([NewRec.PUserName]) then
begin
tblUser.edit;
tblUser.PPassword := NewRec.PPassword;
try
tblUser.Post;
except
if tblUser.State in [dsedit] then tblUser.Cancel;
end;
end;
end;
end;
procedure TDirectDaapi.PasswordDelete(AuserName, APassword: string);
begin
if (trim(AUserName) = '') or (AUserName = SysAdmin) then exit;
tblPassword.EnumIndex := TTSPasswordByUserPassword;
if (APassword = '') then
begin
tblPassword.SetRange([Ausername], [Ausername]);
while not tblPassword.Eof do
begin
tblPassword.Delete;
end;
end
else
if tblPassword.FindKey([AUserName, APassword]) then tblPassword.delete;
tblPassword.CancelRange;
end;
function TDirectDaapi.PasswordCheckPrevious(AUserName, APassword: string): Boolean;
var
s: string;
begin
tblPassword.EnumIndex := TTSPasswordByUserPassword;
result := true;
s := EncryptionWithPassword(APassword, PassKey, false);
if tblPassword.FindKey([AUserName, APassword]) then
begin
tblPassword.SetRange([AUserName, APassword], [AUserName, APassword]);
while not tblPassword.Eof do
begin
if (tblPassword.PStatus <> 'Active') then
if (tblPassword.PPassword = APassword) then result := false;
tblPassword.Next;
end;
end;
end;
function TDirectDaapi.LendGetList: string;
begin
result := '';
end;
function TDirectDaapi.LendGrpGetNameList(csvflag: boolean): string;
var x: integer;
begin
result := ''; // default
tblLendGrp.First;
for x := 1 to tblLendGrp.RecordCount do begin
if csvflag then result := result + iif(x > 1, ',', '') + CsvQuote(tblLendGrp.PName)
else result := result + tblLendGrp.PName;
tblLendGrp.next;
end;
end;
function TDirectDaapi.UserNameIsUser(AUserName: string): boolean;
var uname: string[10];
begin
tblUser.Refresh;
result := false;
if empty(AUserName) then exit;
uname := AuserName;
result := tblUser.findkey([uname]);
end;
function TDirectDaapi.LendGetLendHeaders: string;
begin
result := '"Number",60,"Name",190,"City ST",190,0,1';
end;
function TDirectDaapi.LendGetShortRecord(ALender: TStringLender): string;
begin
result := CsvQuote(ALender);
end;
procedure TDirectDaapi.RepairBaseTables;
begin
if tblSort.Exists then tblSort.RepairTable;
if tblLog.Exists then tblLog.RepairTable;
if tblPerm.Exists then tblPerm.RepairTable;
if tblUser.Exists then tblUser.RepairTable;
if tblLendGrp.Exists then tblLendGrp.RepairTable;
if tblProcess.Exists then tblProcess.RepairTable;
if tblProcDef.Exists then tblProcDef.RepairTable;
if tbljob.Exists then tbljob.RepairTable;
end;
function TDirectDaapi.LendGetNumAndNameList: string;
begin
result := '';
end;
function TDirectDaapi.LendGrpGetRecord(AGroupName: string): string;
begin
result := '';
if AGroupName = '' then exit;
if tblLendGrp.findkey([AGroupName]) then begin
result := tblLendGrp.PDescription + crlf
+ tblLendGrp.PLender1
+ tblLendGrp.PLender2
+ tblLendGrp.PLender3
+ tblLendGrp.PLender4;
end;
end;
procedure TDirectDaapi.LendGrpAddUpdtRecord(AName, ADescription, ALendList: string);
begin
if AName = '' then exit;
if tblLendGrp.findkey([AName]) then tblLendGrp.Edit
else tblLendGrp.Append;
tblLendGrp.PName := AName;
tblLendGrp.PDescription := ADescription;
tblLendGrp.PLender1 := copy(ALendList, 1, 240);
tblLendGrp.PLender2 := copy(ALendList, 241, 240);
tblLendGrp.PLender3 := copy(ALendList, 481, 240);
tblLendGrp.PLender4 := copy(ALendList, 721, 240);
tblLendGrp.Post;
end;
procedure TDirectDaapi.LendGrpDeleteRecord(AName: string);
begin
if tblLendGrp.Findkey([AName]) then tblLendGrp.delete;
tblUser.first;
while not tblUser.eof do begin
if tblUser.PLenderGroup = AName then begin
tblUser.Edit;
tblUser.PLenderGroup := '';
tblUser.Post;
end;
tblUser.next;
end;
end;
function TDirectDaapi.LendGetDescriptionString(ALenderNumber: string): string;
begin
result := '';
end;
function TDirectDaapi.LendGetDescription(ALender: TStringLender): string;
begin
result := '';
end;
function TDirectDaapi.LendGrpGetMaintList: string;
var s: string;
AList: TSTringList;
begin
result := '';
AList := TStringList.create;
try
tblLendGrp.First;
while not tblLendGrp.Eof do begin
s := csvquote(tblLendGrp.PName) + ',' + csvquote(tblLendGrp.PDescription);
AList.Add(s);
tblLendGrp.Next;
end;
result := AList.text;
finally
AList.free;
end;
end;
procedure TDirectDaapi.UserGetMaintList(AList: TStringList);
var s: string;
sa: string;
begin
AList.Clear;
tblUser.Refresh;
tblUser.first;
while not tblUser.eof do begin
s := csvquote(tblUser.PUserName) + ',' + csvquote(tblUser.PRealName) + ',' + CsvQuote(tblUser.PUserGroup);
sa := '';
if tblUser.PUserTable then sa := sa + 'U';
if tblUser.PAccessGroups then sa := sa + 'P';
if tblUser.PLenderGroups then sa := sa + 'L';
s := s + ',' + csvquote(sa) + ',' + csvquote(tblUser.PSingleLender);
AList.Add(s);
tblUser.next;
end;
end;
function TDirectDaapi.LendGrpGetListByName(AGroupName: string): string;
var s: string;
x,
c: integer;
begin
result := '';
if AGroupName = '' then exit;
if tblLendGrp.findkey([AGroupName]) then begin
s := tblLendGrp.PLender1 + tblLendGrp.PLender2 + tblLendGrp.PLender3 + tblLendGrp.PLender4;
c := (length(s) div 4);
for x := 1 to c do begin
result := result + csvQuote(copy(s, ((x - 1) * 4) + 1, 4));
if x < c then result := result + ',';
end;
end;
end;
procedure TDirectDaapi.LendDelete(ALender: TStringLender);
var slGrps,
slLend: TStringList;
x: integer;
y: integer;
ADesc: TStringList;
ll: string;
begin
ADesc := TStringList.create;
slGrps := TStringList.create;
slLend := TStringList.create;
try
slGrps.CommaText := LendGrpGetNameList(true);
for x := 0 to slGrps.Count - 1 do begin
ADesc.text := LendGrpGetRecord(slGrps[x]);
ll := ADesc[1];
slLend.CommaText := LendGrpGetListByName(slGrps[x]);
y := slLend.IndexOf(ALender);
if y >= 0 then begin
slLend.Delete(y);
ll := '';
for y := 0 to slLend.count - 1 do ll := ll + slLend[y];
LendGrpAddUpdtRecord(slGrps[x], ADesc[0], ll);
end;
end;
finally
ADesc.free;
slGrps.free;
slLend.free;
end;
end;
procedure TDirectDaapi.ServerPrinters(var aPrinterList: TStringList);
var aPrinter: TPrinter;
begin
aPrinter := Printer;
aPrinterList.Assign(aprinter.Printers);
end;
function TDirectDaapi.UpdateFileCheck(AFileList: string): string;
var sl: TStringList;
fname: string;
x: integer;
Ver1, Ver2: String;
APath: string;
UpdateList: TStringList;
FileList: TStringList;
begin
APath := dir(drUpdate);
FileList := TStringList.Create;
FileList.text := AFileList;
UpdateList := TStringList.Create;
sl := TStringList.Create;
try
for x := 0 to FileList.Count - 1 do
begin
sl.CommaText := FileList[x]; // Split into name and age
if sl.Count <> 2 then continue; // must be exactly 2 items
fname := APath + sl[0]; // local name of file being checked
Ver1 := sl[1]; // ver of file on client drive
if Ver1.IsEmpty then
begin // it doesn't exist on the client side so add it anyway if it is available
if FileExists(fname) then
UpdateList.Add(sl[0]);
end else
begin
if FileExists(fname) then
begin // it is in the update directory so check to see which is newer
Ver2 := GetExeVersion(fname);
if (Ver2 <> '') and (CompareVersions(Ver2, Ver1) > 0) then
UpdateList.Add(sl[0]);
end;
end;
end;
result := UpdateList.Text;
finally
Filelist.free;
UpdateList.free;
sl.free;
end;
end;
function TDirectDaapi.DownloadFile(Dest, SrcName: string; SrcDir: TFFSDirectory): boolean;
var srcfull: string;
begin
srcfull := uppercase(dir(srcDir) + SrcName);
if uppercase(Dest) = srcfull then result := true // check to see if source and dest are the same
else result := FileCopy(srcfull, dest);
end;
procedure TDirectDaapi.DownloadBlock(SrcName: string; SrcDir: TFFSDirectory; var buf: PBuffer; start, bufsize: integer; var BytesRead, AFileSize, AFileAge: integer);
var f: file;
readcount: integer;
begin
BytesRead := 0;
AFileSize := 0;
assignfile(f, dir(SrcDir) + SrcName);
try
reset(f, 1);
AFileSize := filesize(f);
AFileAge := fileage(dir(SrcDir) + SrcName);
seek(f, start);
// read it into a buffer to be compressed
blockread(f, WorkBuf^, bufsize, readcount);
// compress the buffer read to the buffer sent
BytesRead := LMDLZRWCompress(WorkBuf, buf, readcount); // bytes read is the compressed size
closefile(f);
except
end;
end;
procedure TDirectDaapi.UploadBlock(DestName: string; DestDir: TFFSDirectory; var buf: PBuffer; start, bufsize, AFileAge: integer; var BytesWritten: integer);
var f: file;
x: integer;
begin
assignfile(f, dir(DestDir, false) + DestName);
if start = 0 then rewrite(f, 1)
else reset(f, 1);
seek(f, filesize(f)); // position at eof
// decompress the block sent
x := LMDLZRWDecompress(buf, WorkBuf, bufSize);
// now write the decompressed
blockwrite(f, WorkBuf^, x, bytesWritten);
closefile(f);
SetFileAge(dir(DestDir, false) + DestName, AFileAge);
end;
function TDirectDaapi.UploadFile(Source, DestName: string; DestDir: TFFSDirectory): boolean;
var destfull: string;
begin
destfull := uppercase(dir(DestDir, false) + DestName);
if destfull = uppercase(source) then result := true
else result := FileCopy(source, destfull);
end;
procedure TDirectDaapi.FileDelete(FileName: string; FFSDir: TFFSDirectory);
begin
if FFSDir in [drData, drUpdate] then exit; // protected directories
try
if fileexists(dir(FFSDir, false) + FileName) then DeleteFile(dir(FFSDir, false) + FileName);
except
end;
end;
destructor TDirectDaapi.Destroy;
begin
FreeMem(WorkBuf, MaxBufferIndex);
inherited;
end;
procedure TDirectDaapi.OpenRegistration;
var fname: string;
begin
// this automatically reads the registration record
fname := Dir(drData) + 'Rpt.Dat';
if FileExists(fname) then
RegFile := TFileStream.Create(fname, fmOpenReadWrite or fmShareDenyNone)
else
RegFile := TFileStream.Create(fname, fmCreate or fmOpenReadWrite or fmShareDenyNone);
if RegFile.Size >= SizeOf(Registration) then
RegFile.Read(Registration, SizeOf(Registration))
else begin
RegFile.Size := 0;
FillChar(Registration, sizeof(Registration), 0);
Registration.InitialRunDate := SystemDateString;
Registration.CanAutoActivate := true;
Registration.AutoCount := 500;
Registration.AutoDate := DateToShortString(GetglSystemDate + 28);
Registration.UserCount := 1;
RegFile.Write(Registration, SizeOf(Registration));
end;
end;
procedure TDirectDaapi.ProcessAbort(ARptID: integer);
begin
if tblProcess.FindKey([ARptID]) then begin
if tblProcess.PStopStatus = '' then begin
while not (tblProcess.State in [dsEdit]) do begin
try
tblProcess.Refresh;
tblProcess.edit;
except
end;
end;
tblProcess.PStopStatus := 'ABORTED';
tblProcess.post;
end;
end;
end;
function TDirectDaapi.ProcessGetStatus(ARptID: integer): TFFSReportStatus;
var s1, s2, s3: shortstring;
begin
tblProcess.refresh;
s1 := '';
s2 := '';
s3 := '';
if tblProcess.FindKey([ARptID]) then begin
s1 := tblProcess.PControlStatus;
s2 := tblProcess.PControlMsg;
s3 := tblProcess.PControlScanMsg;
end;
fillchar(result, sizeof(result), 0);
if trim(s1) = '' then result.Control := rcNone
else if s1 = 'DONE' then result.Control := rcDone
else if s1 = 'PROBLEM' then result.Control := rcProblem
else if s1[1] = 'T' then result.Control := rcScan
else if s1[1] = 'R' then result.Control := rcReport
else result.Control := rcNone;
result.UserMsg := s2;
result.ScanMsg := s3;
if trim(s1) <> '' then begin
if s1[1] in ['T', 'R'] then Result.PercentComp := strtointdef(copy(s1, 2, length(s1)), 0);
end;
end;
function TDirectDaapi.ProcDefLoadRecord(AProcessId: integer): TFFSPROCDEFRecord;
begin
fillchar(result, sizeof(result), 0);
tblProcDef.EnumIndex := FFSPROCDEFPrimaryKey;
tblProcDef.Refresh;
if tblProcDef.FindKey([AProcessID]) then result := tblProcDef.GetDataBuffer;
end;
procedure TDirectDaapi.ProcDefSaveRecord(ALendList, AOptions: string; ARecord: TFFSPROCDEFRecord);
var Processid: integer;
begin
tblProcDef.EnumIndex := FFSPROCDEFByListKeyType;
tblProcDef.Refresh;
if tblProcDef.FindKey([ARecord.PListKey, ARecord.PType, ARecord.PReportID]) then tblProcDef.edit
else tblProcDef.append;
ProcessId := tblProcDef.DFReportID.AsInteger;
try
tblProcDef.StoreDataBuffer(ARecord);
tblProcDef.DFReportID.AsInteger := ProcessId;
tblProcDef.DFLenderList.AsString := ALendList;
tblProcDef.DFOptions.AsString := AOptions;
tblProcDef.post;
except
tblProcDef.Cancel;
tblProcDef.EnumIndex := FFSPROCDEFPrimaryKey;
raise;
end;
tblProcDef.EnumIndex := FFSPROCDEFPrimaryKey;
end;
function TDirectDaapi.SecureGetNumberOfUsers: integer;
begin
result := Registration.UserCount;
end;
function TDirectDaapi.ProcDefLoadOptions(AProcessId: integer): string;
begin
result := '';
tblProcDef.EnumIndex := FFSPROCDEFPrimaryKey;
tblProcDef.Refresh;
if tblProcDef.FindKey([AProcessID]) then result := tblProcDef.DFOptions.AsString;
end;
procedure TDirectDaapi.CorrectUserWithSem;
var ausername: string;
begin
tblUser.refresh;
tblUser.first;
tblsem.refresh;
tblSem.EnumIndex := TTSSemByUserName;
while not tblUser.eof do begin
aUserName := tblUser.PUserName;
if tblUser.PUserName = '*' then aUserName := SysAdmin;
if tblUser.PLoggedInFlag then begin
//if not tblSem.FindKey([tblUser.PUserName]) then begin
if not tblSem.FindKey([aUserName]) then begin
tblUser.edit;
tblUser.PLoggedInFlag := False;
tblUser.PLoggedOutStamp := DateTimeStamp;
//tblUser.PLastLender := LastLender;
tblUser.post;
end;
// if user is logged in more than 5 days, logout and reset sem. //added Jan 2016 2
if ( GetglSystemDate - ConvertToDate( Copy(tblUser.PLoggedInStamp, 1,10) ) ) > 3 then begin
tblUser.edit;
tblUser.PLoggedInFlag := False;
tblUser.PLoggedOutStamp := DateTimeStamp;
//tblUser.PLastLender := LastLender;
tblUser.post;
tblsem.refresh;
tblSem.EnumIndex := TTSSemByUserName;
if tblSem.FindKey([aUserName]) then begin
tblSort.UnlockSemaphore(tblSem.PSemNum); // added new JAn 2016
tblSem.Delete;
end;
end; // end of add jan 2016 2
end
else begin
// aUserName := tblUser.PUserName;
// if tblUser.PUserName = '*' then aUserName := SysAdmin;
tblsem.refresh;
tblSem.EnumIndex := TTSSemByUserName;
if tblSem.FindKey([aUserName]) then begin
tblSort.UnlockSemaphore(tblSem.PSemNum); // added new JAn 2016
tblSem.Delete;
end;
end;
tblUser.next;
end;
// neeed to add a way to delete * and '' in tblsem
end;
procedure TDirectDaapi.JobDelete(aAutoInc: integer);
begin
tbljob.Refresh;
if tbljob.FindKey([aAutoInc]) then tbljob.delete;
end;
procedure TDirectDaapi.JobUpdateRecord(Ajob: TTTSJobRecord);
begin
tbljob.Refresh;
if tbljob.findkey([Ajob.PAutoInc]) then begin
end
else
if tbljob.findkey([Ajob.PAutoInc]) then begin
end
else exit;
tbljob.edit;
tbljob.StoreDataBuffer(Ajob);
try
tbljob.Post;
except
if tbljob.State in [dsedit] then tbljob.Cancel;
end;
end;
function TDirectDaapi.JobGetRecord(aAutoInc: integer): TTTSJOBRecord;
var
s: string;
begin
Fillchar(result, sizeof(result), 0);
result := result;
tbljob.refresh;
if tbljob.FindKey([aAutoInc]) then result := tbljob.GetDataBuffer;
end;
function TDirectDaapi.UserGetUserID(AWinUser: string): string;
var
s: Integer;
begin
tblUser.refresh;
result := '';
tblUser.first;
while not tblUser.eof do begin
s := AnsiCompareText(tblUser.PWinUser, AWinUser);
if s = 0 then begin
result := tblUser.PUserName;
Break;
end;
tblUser.next;
end;
end;
function TDirectDaapi.LogGetAll(rectype:String): string;
begin
tbllog.refresh;
result := '';
tblLog.first;
while not tblLog.eof do begin
if tblLog.PRecordType = rectype then begin
if result > '' then result := result + ',';
result := result + CsvQuote(tblLog.PUserID) + ','
+ CsvQuote(tblLog.PLogMessage) + ','
+ CsvQuote(tblLog.PDateStamp);
end;
tblLog.next;
end;
end;
end.
|
unit Solid.Samples.LSP.Animals.Wrong;
interface
uses
System.SysUtils;
type
{ TAnimal }
TAnimal = class abstract
public
procedure MakeNoise; virtual; abstract;
end;
{ TCat }
TCat = class(TAnimal)
public
procedure MakeNoise; override;
end;
{ TDog }
TDog = class(TAnimal)
public
procedure MakeNoise; override;
end;
{ TFish }
TFish = class(TAnimal)
public
procedure MakeNoise; override;
end;
implementation
{ TCat }
procedure TCat.MakeNoise;
begin
Writeln('Meeeeeaaaaaoooooow!');
end;
{ TDog }
procedure TDog.MakeNoise;
begin
Writeln('Bow wow bow wow!');
end;
{ TFish }
procedure TFish.MakeNoise;
begin
raise Exception.Create('Cannot make any noise... :(');
end;
end.
|
unit UInstructionChoiceDialog;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.Generics.Collections,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
UDialog, FMX.Objects, UInstructionDialog;
type
TInstructionChoiceDialog = class(TDialogFrame)
NoteBtn: TButton;
AddBtn: TButton;
CutBtn: TButton;
MoreBtn: TButton;
LittleBtn: TButton;
NormalBtn: TButton;
CancelBtn: TButton;
Rectangle2: TRectangle;
Instructionlbl: TLabel;
procedure CancelBtnClick(Sender: TObject);
procedure ChoiceBtnClick(Sender: TObject);
private
{ Private declarations }
MarginX, MarginY: Integer;
PaddingX, PaddingY: Integer;
BtnList: TList<TButton>;
public
{ Public declarations }
Constructor Create(ParentForm: TForm; ParentPanel: TPanel;
CallBackProc: IProcessDialogResult);
end;
var
InstructionChoiceDialog: TInstructionChoiceDialog;
implementation
uses Orderfm;
{$R *.fmx}
{ TInstructionChoiceDialog }
procedure TInstructionChoiceDialog.ChoiceBtnClick(Sender: TObject);
begin
Orderfm.OrderForm.ChangeInstructionClick(Sender);
end;
procedure TInstructionChoiceDialog.CancelBtnClick(Sender: TObject);
begin
Orderfm.OrderForm.InstructionChoiceCancelBtnClick(Sender);
end;
constructor TInstructionChoiceDialog.Create(ParentForm: TForm;
ParentPanel: TPanel; CallBackProc: IProcessDialogResult);
var
i: Integer;
begin
inherited;
CloseButton.Visible := False;
MarginX := 4;
MarginY := 4;
PaddingX := 40;
PaddingY := 40;
Rectangle2.Height := 50;
Rectangle2.Position.X := 0;
Rectangle2.Position.Y := 0;
Instructionlbl.Width := Rectangle2.Width - 2;
Instructionlbl.Height := Rectangle2.Height;
Instructionlbl.Position.X := 2;
Instructionlbl.Position.Y := 0;
BtnList := TList<TButton>.Create;
BtnList.add(NoteBtn);
BtnList.add(AddBtn);
BtnList.add(CutBtn);
BtnList.add(MoreBtn);
BtnList.add(LittleBtn);
BtnList.add(NormalBtn);
Rectangle2.Width := Rectangle1.Width;
for i := 0 to BtnList.count - 1 do
begin
BtnList.items[i].Width := (Rectangle1.Width - 2 * MarginX - 2 *
PaddingX) / 3;
BtnList.items[i].Height := (Rectangle1.Height - 2 * MarginY - 2 * PaddingY -
Rectangle2.Height) / 3;
BtnList.items[i].Position.X := (i mod 3) *
(MarginX + BtnList.items[i].Width) + PaddingX;
BtnList.items[i].Position.Y := (i div 3) *
(MarginY + BtnList.items[i].Height) + PaddingY + Rectangle2.Height;
BtnList.items[i].StyleLookup := 'InstructionChoiceButtonStyle';
end;
CancelBtn.Width := (Rectangle1.Width - 2 * MarginX - 2 * PaddingX) / 3;
CancelBtn.Height := (Rectangle1.Height - 2 * MarginY - 2 * PaddingY - rectangle2.Height) / 3;
CancelBtn.StyleLookup := 'InstructionChoiceCancelButtonStyle';
CancelBtn.Position.X := PaddingX + MarginX + BtnList.items[0].Width;
CancelBtn.Position.Y := PaddingY + 2 * MarginY + 2 * BtnList.items[0].Height + 5 +
Rectangle2.Height;
end;
end.
|
//Tempat wisata di Emerald city dikelola datanya menggunakan sebuah program.
//Program tersebut mengelola data usaha wisata berdasarkan tipe wisata (outdoor, indoor),
//(individu, family friendly), harga tiket masuk sesuai dengan hari atau waktunya, dan menyediakan
//fasilitas umum seperti toilet, musholah, dan juga jenis makanan / sourvenir yang dijual ditempat
//pariwisata tersebut. Dan juga ada tidaknya fasilitas untuk para penyandang disabilitas.
program JaJalKuy;
//==================== DICTIONARY ====================\\
uses crt,sysutils;
const
Max = 10000;
type
akun =
record
nama: string;
uname: string;
pass: string;
end;
hari =
record
weekday : string;
weekend : string;
end;
waktu =
record
Buka : string;
tutup : string;
end;
wisata =
record
Nama : String;
inout : string;
indFam : string;
harga : hari;
lokasi : string;
deskripsi : string;
jam : waktu ;
fasilitas : array[1..100] of string;
end;
type arstr = array[1..Max] of string;
var
id,i,j: Integer;
f: file of wisata;
fAkun : file of akun;
arWisata: array [1..Max] of wisata;
arAkun: array [1..Max] of akun;
jumlahdata,jumlahakun:longint;
pilih : Byte;
nama:string;
//==================== PROCEDURE DAN FUNCTION yang dibutuhkan ==========================================================================================\\
procedure tampil(i:integer);
{
IS. Menerima Index
FS. Menampilkan setiap data dari record arWisata indeks ke-i
}
var
k: Integer;
begin
writeln;
writeln('indeks #',i);
writeln(' Nama Tempat Wisata : ', arWisata[i].nama);
writeln(' Alamat tempat wisata : ',arWisata[i].lokasi);
writeln(' Indoor / Outdoor : ', arWisata[i].inout);
writeln(' Individu / Family Friendly : ', arWisata[i].indFam);
writeln(' Harga Weekday : ', arWisata[i].harga.weekday);
writeln(' Harga Weekend : ', arWisata[i].harga.weekend);
writeln(' Jam Operasional : ', arWisata[i].jam.buka,'-',arWisata[i].jam.tutup);
write(' Fasilitas : '); k:=1;
while arWisata[i].fasilitas[k] <> '' do
begin
write(arWisata[i].fasilitas[k],', ');
inc(k);
end;
writeln;
write(' Deskripsi : ', arWisata[i].deskripsi);
writeln;
end;
procedure pilurut(var AsDesc: byte);
{
IS. Menerima nilai melalui variable AsDesc
FS. Mengembalikan nilai inputan terbesar atau terkecil dari inputan melalui AsDesc
}
begin
repeat
writeln;
writeln(' urutkan dari : ');
writeln(' 1.Terkecil');
writeln(' 2.Terbesar');
writeln;
write(' Pilih : '); readln(AsDesc);
until (AsDesc=1) or (AsDesc=2);
end;
procedure preprojam(var tmp:arstr;x:string);
{
pre-process jam
IS. Menerima array tmp dan string x
FS. mengembalikan array tmp yang sudah di isi nilai jam tanpa titik ataupun titik dua
}
var
i,s:integer;
begin
for i:= 1 to Max do
tmp[i]:='';
//pre-process
for i:= 1 to jumlahdata do
begin
s:=Length(arWisata[i].jam.buka);
j:=1;
while (j<=s) do
begin
if x='buka' then
begin
if (arWisata[i].jam.buka[j] <> '.') and (arWisata[i].jam.buka[j] <> ':') then
tmp[i]:=tmp[i]+arWisata[i].jam.buka[j];
end
else if x='tutup' then
begin
if (arWisata[i].jam.tutup[j] <> '.') and (arWisata[i].jam.tutup[j] <> ':') then
tmp[i]:=tmp[i]+arWisata[i].jam.tutup[j];
end;
inc(j);
end;
end;
end;
procedure carFas();
{
IS. -
FS. Mencari Fasilitas di array fasilitas tiap array arWisata
}
var
i,nFas: Integer;
cari:string;
ketemu,ada:boolean;
begin
ada:=false;
nfas:=0;
i:=1;
write(' Masukkan Fasilitas yang di cari (huruf kecil semua) : '); readln(cari);
clrscr;
while i<= jumlahdata do
begin
j:=1;
ketemu:=false;
//cari ada berapa banyak fasilitas yang terisi
while (j<100) and (arWisata[i].fasilitas[j] <> '') do
begin
inc(nFas);
inc(j);
end;
//cari ada gak fasilitas yang di cari
j:=1;
while j <= nFas do
begin
if lowercase(arWisata[i].fasilitas[j]) = cari then
ketemu:=true;
inc(j);
end;
//kalau ada, tampilkan. kalau ngga ya maap aja ye
if ketemu then
begin
tampil(i);
writeln;
readln;
end;
ada:=ada or ketemu;
inc(i);
end;
if not ada then
begin
writeln;
writeln('maaf fasilitas yang anda cari tidak ada di database wisata kami :(');
end;
write('press any key to continue.. '); readln;
end;
procedure switchStr(var c,d:string);
{
Menukar String
}
var
tmp: string;
begin
tmp:=c;
c:=d;
d:=tmp;
end;
procedure switchWis(var c,d:wisata);
{
Menukar Wisata
}
var
tmp: wisata;
begin
tmp:=c;
c:=d;
d:=tmp;
end;
procedure iSort();//jam tutup //done
{
Insertion Sort
}
var
tmp: arstr;
simp:wisata;
simp1:string;
i,sementara: integer;
AsDesc:byte;
begin
//pre-process
preprojam(tmp,'tutup');
writeln;
pilurut(AsDesc);
//mulai
for i:= 2 to jumlahdata do
begin
simp:=arWisata[i];
simp1:=tmp[i];
sementara:=i;
if AsDesc = 1 then
begin
while (sementara>1) and (StrToInt(tmp[sementara-1]) > StrToInt(simp1)) do
begin
arWisata[sementara]:=arWisata[sementara-1];
tmp[sementara]:=tmp[sementara-1];
dec(sementara);
end;
end
else
begin
while (sementara>1) and (StrToInt(tmp[sementara-1]) < StrToInt(simp1)) do
begin
arWisata[sementara]:=arWisata[sementara-1];
tmp[sementara]:=tmp[sementara-1];
dec(sementara);
end;
end;
arWisata[sementara]:=simp;
tmp[sementara]:=simp1;
end;
end;
procedure sSort();//jam buka //done
{
Selection Sort
}
var
i,j,huah,a,b: longint;
tmp: arstr;
AsDesc:byte;
begin
//pre-process
preprojam(tmp,'buka');
writeln;
pilurut(AsDesc);
//mulai sort
for i:= 1 to jumlahdata-1 do
begin
huah:=i;
for j:= i to jumlahdata do
begin
a:=StrToInt(tmp[huah]);
b:=StrToInt(tmp[j]);
case AsDesc of
1 : begin
if a > b then
huah:=j;
end;
2 : begin
if a < b then
huah:=j;
end;
end;
end;
switchWis(arWisata[huah],arWisata[i]);
switchStr(tmp[huah],tmp[i]);
end;
end;
procedure carJam();
{
Cari Jam Buka
}
var
tmp:arstr;
x,cari:string;
kanan, kiri, mid,lokasi:integer;
a,b:longint;
status:boolean;
begin
clrscr;
cari:='';
preprojam(tmp,'buka');
//sort dulu
for i:= 1 to jumlahdata do
begin
for j:= 1 to jumlahdata-1 do
begin
if StrToInt(tmp[j]) > StrToInt(tmp[j+1]) then
begin
switchWis(arWisata[j],arWisata[j+1]);
switchStr(tmp[j],tmp[j+1]);
end;
end;
end;
//minta input
write('masukkan Jam buka yang dicari (09.00)/(09:00) : '); readln(x);
//preproinput
for i:= 1 to Length(x) do
if (x[i] <> ':') and (x[i]<>'.') then
begin
cari:=cari+x[i];
end;
//binary start
kiri:=1;
kanan:=jumlahdata;
status:=false;
while (kiri <= kanan) and (not status) do
begin
mid:=(kiri+kanan) div 2;
a:=StrToInt(tmp[mid]);
b:=StrToInt(cari);
readln;
if a = b then
begin
status:=true;
lokasi:=mid;
end
else if a > b then
begin
kanan:=mid-1;
end
else if a < b then
begin
kiri:=mid+1;
end;
end;
if status then
begin
clrscr;
writeln('data ketemu !');
tampil(lokasi);
readln;
end
else
begin
writeln('maaf data yang di cari tidak ada di database wisata kami :( ');
readln;
end;
end;
procedure bSort(x:string);//harga weekend dan weekday
{
Bubble Sort
}
var
i,j: integer;
a,b:longint;
AsDesc:byte;
begin
clrscr;
pilurut(AsDesc);
for i:=1 to jumlahdata do
begin
for j:= 1 to jumlahdata-1 do
begin
if x = 'day' then
begin
a:=StrToInt(arWisata[j].harga.weekday);
b:=StrToInt(arWisata[j+1].harga.weekday);
end
else if x = 'end' then
begin
a:=StrToInt(arWisata[j].harga.weekend);
b:=StrToInt(arWisata[j+1].harga.weekend);
end;
case AsDesc of
1 : begin
if a > b then
switchWis(arWisata[j],arWisata[j+1]);
end;
2 : begin
if a < b then
switchWis(arWisata[j],arWisata[j+1]);
end;
end;
end;
end;
end;
function getpass(): string;
{
Menerima inputan dari keyboard dan akan di tampilkan sebagai karakter bintang (*) menggembalikan
}
var
x: char; tmp:string;
begin
tmp:='';
x:=readkey;
while x <> #13 do
begin
write('*');
tmp:=tmp+x;
x:=readkey;
end;
getpass:=tmp;
end;
procedure loadAkun;
begin
assign(fAkun,'akun.dat');
reset(fAkun);
while not eof(fAkun) do
begin
inc(jumlahakun);
read(fAkun,arAkun[jumlahakun]);
end;
close(fAkun);
end;
procedure saveAkun;
var
i: Integer;
begin
assign(fAkun,'Akun.dat');
rewrite(fAkun);
for i:= 1 to jumlahakun do
begin
write(fAkun,arAkun[i]);
end;
close(fAkun);
end;
procedure load; {ngebuka file, mindahin data di file ke array}
begin
assign(f,'wisata.dat');
reset(f);
while not eof(f) do
begin
inc(jumlahdata); //jumlahdata:=jumlahdata+1;
read(f,arWisata[jumlahdata]);
end;
close(f);
end;
procedure save;{buka file, masukin semua array }
var
i: Integer;
begin
assign(f,'wisata.dat');
rewrite(f);
for i:= 1 to jumlahdata do
begin
write(f,arWisata[i]);
end;
close(f);
end;
//==================== Admin Menu dan teman teman nya ===================================================================================================\\
procedure cek(idx:integer; var valid : boolean);
begin
if arWisata[idx].nama <> '' then
begin
valid:=true;
writeln('data yang ini?');
writeln;
tampil(idx);
end
else
begin
valid:=false;
writeln('maaf data yang anda cari tidak ada :(');
readln;
end;
end;
procedure insertData(x:integer;stat:string);
var
pilihadmin:char; tmp:integer;
begin
repeat
clrscr;
writeln;
writeln(' === Main Menu >> Admin >> Login Admin >> Menu Admin >> Insert Data ===');
writeln;
write(' Nama Tempat Wisata : '); readln(arWisata[x].nama);
write(' Alamat tempat wisata : '); readln(arWisata[x].lokasi);
repeat
write(' 1. Indoor / 2. Outdoor // Pilih angka : '); readln(tmp);
until (tmp = 1 ) or (tmp=2);
if tmp = 1 then
arWisata[x].inout:='Indoor'
else
arWisata[x].inout:='Outdoor';
repeat
write(' 1. Individu / 2. Family Friendly : '); readln(tmp);
until (tmp = 1 ) or (tmp=2);
if tmp = 1 then
arWisata[x].indFam:='Individu'
else
arWisata[x].indFam:='Family Friendly';
write(' Harga Weekday [Senin-Jumat] (per orang) : '); readln(arWisata[x].harga.weekday);
write(' Harga Weekend [Sabtu-Minggu] (per orang) : '); readln(arWisata[x].harga.weekend);
write(' Jam Buka (09.00)/(09:00) : '); readln(arWisata[x].jam.buka);
write(' Jam Tutup (09.00)/(09:00) : '); readln(arWisata[x].jam.tutup);
writeln(' Fasilitas : ');j:=0;
while arWisata[x].fasilitas[j]<>'' do
begin
inc(j);
write(j,' : '); readln(arWisata[x].fasilitas[j]);
end;
write(' Deskripsi : '); readln(arWisata[x].deskripsi);
writeln;
if stat = 'ins'then
begin
write('Ingin nambah data wisata lagi? [y/t] : '); readln(pilihadmin);
if pilihadmin = 'y' then
begin
inc(jumlahdata);
x:=jumlahdata;
end;
end
else if stat = 'edit' then
begin
writeln('== Data Baru sudah tersimpan! ==');
readln;
pilihadmin:='t';
end;
until (lowercase(pilihadmin)='t');
end;
procedure editData();
var
idx,i: Integer;
pilih:char;
valid:boolean;
begin
clrscr;
writeln;
writeln(' === Main Menu >> Admin >> Login Admin >> Menu Admin >> Edit Data ===');
writeln;
for i:= 1 to jumlahdata do
begin
writeln(i,'. ',arWisata[i].nama);
end;
write('masukkan nomor indeks yang ingin di edit : '); readln(idx);
clrscr;
cek(idx,valid);
if valid then
begin
write('pilih [y/t] : '); readln(pilih);
if lowercase(pilih) = 'y' then
begin
insertData(idx,'edit');
end;
end;
end;
procedure deleteData();
var
pilih: char;
idx:byte;
i:integer;
valid:boolean;
//mencari datanya
begin
clrscr;
writeln;
writeln(' === Main Menu >> Admin >> Login Admin >> Menu Admin >> Delete Data ===');
writeln;
for i:= 1 to jumlahdata do
begin
writeln(i,'. ',arWisata[i].nama);
end;
write('masukkan nomor indeks tempat wisata : '); readln(idx);
clrscr;
cek(idx,valid);
if valid then
begin
write('pilih : [y/t] : '); readln(pilih);
if pilih = 'y'then
begin
//hapus datanya
for i:= idx to jumlahdata do
begin
arWisata[i]:=arWisata[i+1]
end;
dec(jumlahdata);
writeln('== Data ke ',idx,' telah di hapus! ==')
end;
end;
end;
procedure viewData();
var
tmp,flag: Integer;
esc:boolean;
begin
repeat
esc:=false;
clrscr;
flag:=1; i:=1;
while i<=jumlahdata do
begin
if flag <= 2 then
begin
inc(flag);
tampil(i);
inc(i);
end
else
begin
flag:=1;
writeln;
write('press any key to continue.. '); readln;
clrscr;
end;
end;
writeln;
writeln;
if id=2 then
begin
write('[1.Insert 2.Edit 3.Delete 4.Back] : '); readln(tmp);
case tmp of
1 : begin inc(jumlahdata); insertData(jumlahdata,'ins'); end;
2 : begin editData; end;
3 : begin deleteData; end;
4 : begin esc:=true; end;
end;
end
else if id=1 then
begin
writeln;
write('press any key to continue..'); readkey;
clrscr;
writeln;
writeln(' Urutkan Berdasarkan :');
writeln(' 1. Harga Weekday ');
writeln(' 2. Harga Weekend ');
writeln(' 3. Jam Buka ');
writeln(' 4. Jam Tutup');
writeln(' 5. Back');
writeln;
write (' ===>Pilih : '); readln(tmp);
case tmp of
1: begin bSort('day'); end;
2: begin bSort('end'); end;
3: begin sSort(); end;
4: begin iSort(); end;
5: begin esc:=true; end;
end;
end;
until esc;
end;
procedure menuAdmin();
begin
repeat
clrscr;
writeln;
writeln(' === Main Menu >> Admin >> Login Admin >> Menu Admin ===');
writeln;
writeln(' == Admin Menu ==');
writeln(' 1. Insert Data');
writeln(' 2. Edit Data');
writeln(' 3. Delete Data');
writeln(' 4. View Data');
writeln(' 5. Back');
writeln(' jumlah data : ',jumlahdata);
writeln;
write(' ===> Pilih : '); readln(pilih);
case pilih of
1 : begin inc(jumlahdata); insertData(jumlahdata,'ins'); end;
2 : begin editData(); end;
3 : begin deleteData(); end;
4 : begin viewData(); end;
end;
until (pilih=5);
save;
end;
procedure welcomeAdmin();
var
uname,pass: string;
begin
repeat
clrscr;
writeln;
writeln(' === Main Menu >> Admin >> Login Admin ===');
writeln('hint : uname & pass = admin. kosongkan untuk kembali' );
writeln(' == Login Admin ==');
writeln;
write ('===> Username : '); readln(uname);
write ('===> Password : '); pass:=getpass;
until ((uname = 'admin') and (pass = 'admin')) or ((uname = '') or (pass = ''));
if ((uname = 'admin') and (pass = 'admin')) then
menuAdmin();
end;
//==================== User Menu dan teman teman nya ====================================================================================================\\
procedure cekUser(uname,pass:string; var valid : boolean);
var
i:longint;
cek:boolean;
begin
cek:=false;
for i:=1 to jumlahakun do
begin
if (arAkun[i].uname = uname) and (arAkun[i].pass = pass) then
begin
cek:=true;
nama:=arAkun[i].nama;
end;
end;
valid := cek;
end;
procedure cariData();
var
tmp: Integer;
begin
repeat
clrscr;
writeln;
writeln(' === Main Menu >> User >> Login >> Menu User >> Cari Data ===');
writeln;
writeln(' 1. Cari Berdasarkan Jam Buka ');
writeln(' 2. Cari Berdasarkan Fasilitas ');
writeln(' 3. Kembali ');
writeln;
write ('===> Pilih : '); readln(tmp);
case tmp of
1: begin carJam(); end;
2: begin carFas(); end;
end;
until (tmp=3);
end;
procedure menuUser();
var
tmp: byte;
begin
repeat
clrscr;
writeln;
writeln(' === Main Menu >> User >> Login >> Menu User ===');
writeln;
writeln(' Selamat Datang, ',nama);
writeln;
writeln(' 1. Lihat Semua Wisata ');
writeln(' 2. Cari Tempat Wisata ');
writeln(' 3. Back ');
writeln;
write ('===> Pilih : '); readln(tmp);
case tmp of
1: begin viewData(); end;
2: begin cariData(); end;
end;
until (tmp=3);
end;
procedure welcomeUser();
var
uname,pass: string;
pilihan:integer;
valid:boolean;
begin
repeat
clrscr;
writeln;
writeln(' === Main Menu >> User ===');
writeln;
writeln(' 1. Login ');
writeln(' 2. Register ');
writeln(' 3. Kembali ');
writeln;
write ('===> Pilih : ');readln(pilihan);
if pilihan = 1 then
begin
clrscr;
writeln(' === Main Menu >> User >> Login ===');
writeln;
writeln(' ==Login== ');
write ('===> Username : '); readln(uname);
write ('===> Password : '); pass:=getpass;
cekUser(uname,pass,valid);
if valid then
menuUser()
else
begin
writeln;
writeln('!!!! username atau password yang anda masukkan salah !!!!');
write('press any key to continue..'); readkey;
end;
end
else
if pilihan = 2 then
begin
clrscr;
inc(jumlahakun);
writeln;
writeln(' === Main Menu >> User >> Registrasi ===');
writeln;
writeln(' == Daftar == ');
write ('===> Nama Lengkap : '); readln(arAkun[jumlahakun].nama);
write ('===> Username : '); readln(arAkun[jumlahakun].uname);
write ('===> Password : '); readln(arAkun[jumlahakun].pass);
saveAkun;
writeln;
writeln('Registrasi Selesai, Data tersimpan.');
writeln;
write('press anykey to continue.. '); readkey;
end;
until (pilihan = 3);
end;
//==================== PROGRAM UTAMA ====================\\
begin
clrscr;
//buat bikin file kalau filenya ga ada
Assign(f, 'wisata.dat') ;
{$I-} Reset(f) ;
{$I+} if IOResult<>0 then Rewrite(f) ;
close(f);
Assign(fAkun, 'akun.dat') ;
{$I-} Reset(fAkun) ;
{$I+} if IOResult<>0 then Rewrite(fAkun) ;
close(fAkun);
//akhir dari bikin file
jumlahdata:=0;
load;
loadAkun;
repeat
clrscr;
writeln('--------------------------------------------------');
writeln('=========== Selamat Datang di JalJalKuy! ==========');
writeln('=== Aplikasi Wisata terbaik se - Emerald city! ===');
writeln('--------------------------------------------------');
writeln('-------------------------------------------------- ');
writeln('| Main Menu | ');
writeln('| 1.User | ');
writeln('| 2.Admin | ');
writeln('| 3.Log Out | ');
writeln('--------------------------------------------------');
writeln;
write (' ===> Pilih : '); readln(id);
case id of
1: welcomeUser();
2: welcomeAdmin();
end;
until (id=3);
clrscr;
save;
saveAkun;
end. |
(*program 11.4
(*conversion to postfix form *)
Program postfix(input,output);
Var ch: char;
Procedure find;
(* finds next non-blank character*)
Begin
Repeat
read(ch)
Until (ch<>' ') (*-and not eoln(input)-*)
End
(* find *);
Procedure expression;
Var op: char;
Procedure term;
Procedure factor;
Begin
(*factor*)
If ch='(' Then (* (expression) *)
Begin
find;
expression;
(*ch must now be ) *)
End
Else (*identifier*) write(ch);
find
End
(*factor*);
Begin
(* term*)
factor;
While ch= '*' Do
Begin
find;
factor;
write('*')
End
End
(*term*);
Begin
(*expression*)
term;
While (ch='+') Or (ch='-') Do
Begin
op := ch;
find;
term;
write(op)
End;
End
(*expression*);
Begin
(*postfix*)
find;
Repeat
write(' ');
expression;
writeln
Until ch= '.'
End
(*postfix*).
Data7
( a + b ) * ( c - d )
a + b * c - d
(a + b) * c - d
a*a*a*a
b+c*(d+c*a*a)*b+a . |
unit GlobalConfig;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
System.SyncObjs,
System.IniFiles,
Vcl.Menus,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.ExtCtrls,
Vcl.Samples.Spin,
FileFunctions,
FilterAPI;
type
TGlobalConfig = Class
private
INIFileName: String;
GEncoding: TEnCoding;
function GetInIString(Ident, Sect, Def, FileName: String): String;
function WriteInIString(Ident, Sect, Str1, FileName: String): bool;
function VerifySectionExists(Section, Item, FileName: String): Integer;
public
FilterType: LongWord;
ThreadCount: LongWord;
Timeout: LongWord;
AccessFlags:LongWord;
MonitorIOs: LongWord;
MonitorFileEvents: LongWord;
ControlIOs: LongWord;
IncludeFileFilterMask: String;
ExcludeFileFilterMask: String;
EncryptionPasswordPhrase: String;
procedure LoadINI;
procedure SaveINI;
function SendConfigSettingsToFilter(MsgCallback: TMessageCallback): String;
constructor Create(FileName: String);
End;
implementation
constructor TGlobalConfig.Create(FileName: String);
begin
INIFileName := FileName;
FilterType := LongWord(FILE_SYSTEM_EASE_FILTER_ALL);
ThreadCount := 5;
Timeout := 30;
AccessFlags := LongWord(ALLOW_MAX_RIGHT_ACCESS);
MonitorFileEvents := 4064;
MonitorIOs := 2863311530;
ControlIOs := 0;
GEncoding := TEnCoding.Unicode;
IncludeFileFilterMask := 'c:\\test\\*';
ExcludeFileFilterMask := '';
EncryptionPasswordPhrase :='';
end;
procedure TGlobalConfig.LoadINI;
begin
if Not(FileExists(INIFileName)) then
exit;
FilterType := StrToUInt(GetInIString('AppInfo', 'FilterType', '0', INIFileName));
ThreadCount := StrToUInt(GetInIString('AppInfo', 'ThreadCount', '5', INIFileName));
Timeout := StrToUInt(GetInIString('AppInfo', 'Timeout', '30', INIFileName));
AccessFlags := StrToUInt(GetInIString('AppInfo', 'AccessFlags',UIntToStr(AccessFlags), INIFileName));
MonitorIOs := StrToUInt(GetInIString('AppInfo', 'MonitorIOs', UIntToStr(MonitorIOs), INIFileName));
MonitorFileEvents := StrToUInt(GetInIString('AppInfo', 'MonitorFileEvents', UIntToStr(MonitorFileEvents), INIFileName));
ControlIOs := StrToUInt(GetInIString('AppInfo', 'ControlIOs', UIntToStr(ControlIOs), INIFileName));
IncludeFileFilterMask := GetInIString('AppInfo', 'IncludeFileFilterMask', IncludeFileFilterMask, INIFileName);
ExcludeFileFilterMask := GetInIString('AppInfo', 'ExcludeFileFilterMask', ExcludeFileFilterMask, INIFileName);
EncryptionPasswordPhrase := GetInIString('AppInfo', 'EncryptionPasswordPhrase', EncryptionPasswordPhrase, INIFileName);
end;
procedure TGlobalConfig.SaveINI;
begin
WriteInIString('AppInfo', 'FilterType', UIntToStr(FilterType), INIFileName);
WriteInIString('AppInfo', 'ThreadCount', UIntToStr(ThreadCount), INIFileName);
WriteInIString('AppInfo', 'Timeout', UIntToStr(Timeout), INIFileName);
WriteInIString('AppInfo', 'AccessFlags', UIntToStr(AccessFlags), INIFileName);
WriteInIString('AppInfo', 'MonitorIOs', UIntToStr(MonitorIOs), INIFileName);
WriteInIString('AppInfo', 'MonitorFileEvents', UIntToStr(MonitorFileEvents), INIFileName);
WriteInIString('AppInfo', 'ControlIOs', UIntToStr(ControlIOs), INIFileName);
WriteInIString('AppInfo', 'IncludeFileFilterMask', IncludeFileFilterMask, INIFileName);
WriteInIString('AppInfo', 'ExcludeFileFilterMask', ExcludeFileFilterMask, INIFileName);
WriteInIString('AppInfo', 'EncryptionPasswordPhrase', EncryptionPasswordPhrase, INIFileName);
end;
function TGlobalConfig.VerifySectionExists(Section, Item, FileName: String): Integer;
var
Str1: String;
StrList: TStringList;
begin
Result := 0;
if Not(FileExists(FileName)) then
exit;
Str1 := GetInIString(Section, Item, 'XXXXX', FileName);
if (Str1 = 'XXXXX') then
Result := 2;
if Result = 2 then
begin
StrList := TStringList.Create;
try
SetFileAttributesW(PWideChar(FileName), 0);
StrList.LoadFromFile(FileName);
StrList.Add('');
StrList.Add('[' + Section + ']');
StrList.SaveToFile(FileName, GEncoding);
Result := 1;
except
end;
StrList.Free;
end;
end;
/////////////////////////////////////
/// Reg Functions
function TGlobalConfig.GetInIString(Ident, Sect, Def, FileName: String): String;
var
IniFileName: TMemIniFile;
begin
IniFileName := nil;
if (Sect = '') or (Ident = '') then
begin
Result := Def;
exit;
end;
try
IniFileName := TMemIniFile.Create(FileName, GEncoding);
Result := IniFileName.ReadString(Ident, Sect, Def);
except
end;
if IniFileName <> nil then
IniFileName.Free; // Read Only No UpdateFile Needed
end;
function TGlobalConfig.WriteInIString(Ident, Sect, Str1, FileName: String): bool;
var
IniFileName: TMemIniFile;
FATTR: Integer;
begin
IniFileName := nil;
try
IniFileName := TMemIniFile.Create(FileName, GEncoding);
FATTR := FileGetAttr(FileName);
if (FATTR < 0) or ((FATTR and faReadonly) = 0) then
begin
IniFileName.WriteString(Ident, Sect, Str1);
end;
finally
if IniFileName <> nil then
begin
try
IniFileName.UpdateFile;
except
try
Sleep(0);
IniFileName.UpdateFile;
except
end;
end;
IniFileName.Free;
end;
Result := true;
end;
end;
function TGlobalConfig.SendConfigSettingsToFilter(MsgCallback: TMessageCallback): String;
var
ErrMsg: String;
RetVal: ULONG;
ret: Boolean;
PIDValue: ULONG;
AppName: String;
FileCount: ULONG;
AppPID: ULONG;
begin
// Reset the filter config setting.
RetVal := ResetConfigData();
if (RetVal <> 1) then
begin
MsgCallback('ResetConfigData failed. - ' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('Reset config data succeeded.');
RetVal := SetFilterType(FilterType);
if (RetVal <> 1) then
begin
MsgCallback('SetFilterType failed. - ' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('SetFilterType - ' + UIntToStr(FilterType));
PIDValue := GetCurrentProcessId;
RetVal := AddExcludedProcessId(PIDValue);
if (RetVal <> 1) then
begin
MsgCallback('AddExcludedProcessId - ' + UIntToStr(PIDValue) + ' failed.' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('AddExcludedProcessId - ' + UIntToStr(PIDValue));
// Set filter maiximum wait for user mode response time out.
RetVal := SetConnectionTimeout(Timeout);
if (RetVal <> 1) then
begin
MsgCallback('SetConnectionTimeout - ' + UIntToStr(Timeout) + ' failed.' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('SetConnectionTimeout - ' + UIntToStr(Timeout));
RetVal := AddNewFilterRule(AccessFlags,PChar(IncludeFileFilterMask),false);
if (RetVal <> 1) then
begin
MsgCallback('AddNewFilterRule - ' + IncludeFileFilterMask + ' failed.' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('AddNewFilterRule - ' + IncludeFileFilterMask + ' succeeded.');
RetVal := AddExcludeFileMaskToFilterRule(PChar(IncludeFileFilterMask), PChar(ExcludeFileFilterMask));
if (RetVal <> 1) then
begin
MsgCallback('AddExcludeFileMaskToFilterRule - ' + ExcludeFileFilterMask + ' failed.' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('AddExcludeFileMaskToFilterRule - ' + ExcludeFileFilterMask + ' succeeded.');
RetVal := RegisterEventTypeToFilterRule(PChar(IncludeFileFilterMask),MonitorFileEvents);
if (RetVal <> 1) then
begin
MsgCallback('RegisterEventTypeToFilterRule - ' + UIntToStr(MonitorFileEvents) + ' failed.' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('RegisterEventTypeToFilterRule - ' + UIntToStr(MonitorFileEvents) + ' succeeded.');
RetVal := RegisterMoinitorIOToFilterRule(PChar(IncludeFileFilterMask),MonitorIOs);
if (RetVal <> 1) then
begin
MsgCallback('RegisterMoinitorIOToFilterRule - ' + UIntToStr(MonitorIOs) + ' failed.' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('RegisterMoinitorIOToFilterRule - ' + UIntToStr(MonitorIOs) + ' succeeded.');
RetVal := RegisterControlIOToFilterRule(PChar(IncludeFileFilterMask),ControlIOs);
if (RetVal <> 1) then
begin
MsgCallback('RegisterControlIOToFilterRule - ' + UIntToStr(ControlIOs) + ' failed.' + GetLastFilterAPIErrorMsg);
exit;
end;
MsgCallback('RegisterControlIOToFilterRule - ' + UIntToStr(ControlIOs) + ' succeeded.');
Result := '';
end;
end.
|
{--------------------------------------------------------------------------
Objetivo > Implementar o componente TosComboFilter que é o combo que vai
conter o filtro e todas as suas views
Observações>
Criação >
Atualização> 13/02/2006 - Ricardo N. Acras
Adição do evendo onCustomGetExprList para dar a chance ao
programador de adicionar expressões default via código
--------------------------------------------------------------------------}
unit osComboFilter;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, wwdbedit, Wwdotdot, Wwdbcomb, osFilterInspectorForm,
osExtStringList, osUtils, dbclient, variants, db, osCustomFilterUn,
osSQLConnection, acFilterController;
type
TGetCustomExprListEvent = procedure(exprList: TStrings) of object;
TViewDef = class(TObject)
private
FAttrList: TStrings;
FExprList: TStrings;
FConstrList: TStrings;
FOrderList: TStrings;
FQueryText: TStrings;
FNumber: integer;
FOrderColumn: string;
FOrderType: string;
public
constructor Create;
destructor Destroy; override;
property AttrList: TStrings read FAttrList write FAttrList;
property ExprList: TStrings read FExprList write FExprList;
property ConstrList: TStrings read FConstrList write FConstrList;
property OrderList: TStrings read FOrderList write FOrderList;
property QueryText: TStrings read FQueryText write FQueryText;
property Number: integer read FNumber write FNumber;
property OrderColumn: string read FOrderColumn write FOrderColumn;
property OrderType: string read FOrderType write FOrderType;
end;
TosComboFilter = class(TwwDBComboBox)
private
FFilterDefName: string;
FUserID: string;
FViewDefault: integer;
FItemIndexDefault: integer; // indica o item a ser selecionado quando iniciar um novo filtro
customFilterForm: TosCustomFilter;
FonGetCustomExprList: TGetCustomExprListEvent;
procedure SetClientDS(const Value: TClientDataset);
function GetAttrList(PIndex: integer): TStrings;
procedure SetUserID(const Value: string);
procedure SetFilterDefName(const Value: string);
procedure SetViewDefault(const Value: integer);
procedure SetSQLConnection(const Value: TosSQLConnection);
protected
function GetExpressionFromConstraint(const PConstraint, PValue: string): string;
public
FBaseView: TViewDef;
FGetParams: TNotifyEvent;
FParams: TParams;
FLastExpressions: string;
FLastOrder: string;
FClientDS: TClientDataset;
FSQLConnection: TosSQLConnection;
FOrderColumn: string;
FOrderType: string;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CheckDS;
procedure PrepareQuery(PQuery: TSQLStringList; const PExpressions, POrder, PDefaultExpressions: string);
function GetConstrList(PIndex: integer): TStrings;
function GetOrderList(PIndex: integer): TStrings;
function GetExprList(PIndex: integer): TStrings;
function GetQueryText(PIndex: integer): TStrings;
procedure GetViews(PUserID: string = ''; PClassName: string = '');
procedure ClearViews;
function ExecuteFilter(PNewFilter: boolean = True): string;
function ExecuteView(PNumView, PConstraint: integer; PValue: string): boolean;
procedure ConfigFields(PIndex: integer);
procedure ResetToItemDefault;
function getSQLFilter(var index: integer; PNewFilter: boolean = True): String;
function isDefCustomFilter(index: integer): boolean;
function defTemRestricaoUsuario(index: integer): boolean;
published
property ClientDS: TClientDataset read FClientDS write SetClientDS;
property SQLConnection: TosSQLConnection read FSQLConnection write SetSQLConnection;
property Params: TParams read FParams write FParams;
property UserID: string read FUserID write SetUserID;
property FilterDefName: string read FFilterDefName write SetFilterDefName;
property ViewDefault: integer read FViewDefault write SetViewDefault;
property GetParams: TNotifyEvent read FGetParams write FGetParams;
property onGetCustomExprList: TGetCustomExprListEvent read FonGetCustomExprList write FonGetCustomExprList;
end;
procedure Register;
implementation
uses osCustomFilterFunctionUn, osAppResources{, osCustomMainFrm};
procedure Register;
begin
RegisterComponents('OS Controls', [TosComboFilter]);
end;
{ TPsComboFilter }
procedure TosComboFilter.CheckDS;
begin
if not Assigned(FClientDS) then
raise Exception.Create(Self.ClassName + ': propriedade ClientDS não informada');
end;
constructor TosComboFilter.Create(AOwner: TComponent);
begin
inherited;
FFilterDefName := '';
FUserID := '';
FParams := TParams.Create(Self);
end;
destructor TosComboFilter.Destroy;
begin
ClearViews;
inherited;
end;
function TosComboFilter.getSQLFilter(var index: integer; PNewFilter: boolean = True): String;
var
slQuery: TSQLStringList;
iIndex: integer;
slExpr, slConstr, slOrder: TStrings;
InspectorForm: TosFilterInspector;
bExecuteFilter: boolean;
nomeCustomFilterClass: string;
customFilterFunctionClass: TosCustomFilterFunctionClass;
customFilterFunction: TosCustomFilterFunction;
begin
iIndex := 0;
bExecuteFilter := True;
slQuery := TSQLStringList.Create;
try
if Text <> '' then
begin
// Repassa a query para o ClientDataset
FClientDS.Close;
iIndex := Items.IndexOf(Text);
FOrderColumn := TViewDef(Items.Objects[iIndex]).OrderColumn;
FOrderType := TViewDef(Items.Objects[iIndex]).OrderType;
//se a pesquisa for comum pelo filtro
if (trim(TViewDef(Items.Objects[iIndex]).queryText.text)='') OR (trim(TViewDef(Items.Objects[iIndex]).queryText.text)[1] <> 'T') then
begin
slQuery.Assign(GetQueryText(iIndex)); // Copia o texto da query
slExpr := GetExprList(iIndex);
slConstr := GetConstrList(iIndex);
slOrder := GetOrderList(iIndex);
FLastOrder := '';
if (slOrder.Count > 0) and
(Copy(UpperCase(slOrder.Text), 1, 5) <> 'FALSE') then
FLastOrder := GetWord(slOrder[0], 2, '=');
if PNewFilter then
begin
if (Copy(UpperCase(slConstr.Text), 1, 5) <> 'FALSE') and (Trim(slConstr.Text) <> '') then
begin
InspectorForm := TosFilterInspector.Create(Self);
try
if InspectorForm.Execute(slConstr, slOrder) then
begin
FLastExpressions := InspectorForm.Expressions;
FLastOrder := InspectorForm.Order;
PrepareQuery(slQuery, FLastExpressions, FLastOrder, slExpr.Text);
end
else
begin
FLastExpressions := '';
FLastOrder := '';
bExecuteFilter := False;
end;
finally
InspectorForm.Free;
end;
end
else
PrepareQuery(slQuery, '', FLastOrder, slExpr.Text);
end
else
PrepareQuery(slQuery, FLastExpressions, FLastOrder, slExpr.Text);
if bExecuteFilter then
begin
FParams.ParseSQL(slQuery.Text, True);
if FParams.Count > 0 then
begin
if Assigned(FGetParams) then
FGetParams(Self);
FClientDS.Params.Assign(FParams);
end
else
if FClientDS.Params.Count > 0 then
FClientDS.Params.Clear;
Result := slQuery.Text;
end;
end
else
begin
if PNewFilter then
begin
nomeCustomFilterClass := trim(TViewDef(Items.Objects[iIndex]).queryText.text);
customFilterForm := TosCustomFilterClass(OSGetClass(nomeCustomFilterClass)).create(self);
customFilterForm.execute(FBaseView.QueryText.gettext, GetExprList(iIndex));
end;
Result := customFilterForm.getQuery;
end;
//por último faz o tratamento das funções definidas, dando a chance para uma classe que implemente
//a interface ICustomFilterFunction
customFilterFunctionClass := TosCustomFilterFunctionClass(OSGetClass('TFilterFunction'));
if customFilterFunctionClass <> nil then
begin
customFilterFunction := customFilterFunctionClass.Create;
result := customFilterFunction.evaluateFunctionValues(result);
end;
end;
finally
slQuery.Free;
end;
index := iIndex
end;
function TosComboFilter.ExecuteFilter(PNewFilter: boolean = True): String;
var
OldCursor: TCursor;
iIndex: integer;
begin
OldCursor := Screen.Cursor;
Screen.Cursor := crHourglass;
try
try
if Items.Count = 0 then
raise Exception.Create('Não há filtros na lista');
CheckDS;
result := getSQLFilter(iIndex, PNewFilter);
if result <> '' then
begin
FClientDS.CommandText := result;
FClientDS.DisableControls;
try
FClientDS.Open;
except
on e: exception do
begin
if ItemIndex<>0 then
MessageDlg('Ocorreram erros na execução do Filtro. '+#13+#10'O filtro padrão será executado novamente.'+#13+#10+'Erro com a mensagem:'+e.Message, mtError, [mbOK], 0)
else
MessageDlg('Ocorreram erros na execução do Filtro.'+#13+#10+'Erro com a mensagem:'+e.Message, mtError, [mbOK], 0);
if ItemIndex<>0 then
begin
ItemIndex := 0;
ExecuteFilter(true);
end;
end;
end;
ConfigFields(iIndex);
FClientDS.EnableControls;
end;
except
// on EDatabaseError do
begin
FClientDS.Close;
end;
end;
finally
Screen.Cursor := OldCursor;
end;
end;
function TosComboFilter.GetAttrList(PIndex: integer): TStrings;
var
ViewSel, ViewInicial: TViewDef;
begin
ViewSel := TViewDef(Items.Objects[PIndex]);
ViewInicial := FBaseView;
if (not Assigned(ViewSel)) and (not Assigned(ViewInicial)) then
raise Exception.Create('Não há definições de views para os filtros');
if Trim(ViewSel.AttrList.Text) <> '' then
Result := ViewSel.AttrList
else
Result := ViewInicial.AttrList;
end;
function TosComboFilter.GetConstrList(PIndex: integer): TStrings;
var
ViewSel, ViewInicial: TViewDef;
begin
ViewSel := TViewDef(Items.Objects[PIndex]);
ViewInicial := FBaseView;
if (not Assigned(ViewSel)) and (not Assigned(ViewInicial)) then
raise Exception.Create('Não há definições de views para os filtros');
if Trim(ViewSel.ConstrList.Text) <> '' then
Result := ViewSel.ConstrList
else
Result := ViewInicial.ConstrList;
end;
function TosComboFilter.GetOrderList(PIndex: integer): TStrings;
var
ViewSel, ViewInicial: TViewDef;
begin
ViewSel := TViewDef(Items.Objects[PIndex]);
ViewInicial := FBaseView;
if (not Assigned(ViewSel)) and (not Assigned(ViewInicial)) then
raise Exception.Create('Não há definições de views para os filtros');
if Trim(ViewSel.OrderList.Text) <> '' then
Result := ViewSel.OrderList
else
Result := ViewInicial.OrderList;
end;
function TosComboFilter.GetQueryText(PIndex: integer): TStrings;
var
ViewSel, ViewInicial: TViewDef;
begin
ViewSel := TViewDef(Items.Objects[PIndex]);
ViewInicial := FBaseView;
if (not Assigned(ViewSel)) and (not Assigned(ViewInicial)) then
raise Exception.Create('Não há definições de views para os filtros');
if Trim(ViewSel.QueryText.Text) <> '' then
Result := ViewSel.QueryText
else
Result := ViewInicial.QueryText;
end;
{-------------------------------------------------------------------------
Objetivo >
Parâmetros > Conforme documentação
Retorno >
Criação >
Observações> Documentação iniciada em 25.04.2006 por Ricardo N. Acras
Atualização>
------------------------------------------------------------------------}
procedure TosComboFilter.GetViews(PUserID: string; PClassName: string);
var
vViews: variant;
i, iMax, iViewDefault, iAux: integer;
ViewDef: TViewDef;
OldCursor: TCursor;
manager: TosAppResourceManager;
begin
if Application.MainForm <> nil then
manager := TosAppResourceManager(Application.MainForm.FindComponent('Manager'));
OldCursor := Screen.Cursor;
Screen.Cursor := crHourglass;
try
if PUserID = '' then
PUserID := FUserID;
if PClassName = '' then
PClassName := FFilterDefName;
CheckDS;
vViews := TacFilterController(
Application.MainForm.FindComponent('FFilterDepot')
).findFilter(PClassName);
if VarIsEmpty(vViews) then
begin
//if (manager<>nil) AND (UpperCase(manager.currentResource.FilterDefName)=UpperCase(PClassName)) then
// vViews := manager.currentResource.views
//else
vViews := FClientDS.DataRequest('_CMD=GET_VIEWS UID= CLASSNAME=' + PClassName);
TacFilterController(Application.MainForm.FindComponent('FFilterDepot')).
addFilter(PClassName, vViews);
//FClientDS.ProviderName
end;
if ViewDefault <> 0 then
iViewDefault := ViewDefault
else
iViewDefault := -1;
iMax := iAux;
iAux := 0;
iMax := VarArrayHighBound(vViews, 1);
for i:=0 to iMax do
begin
ViewDef := TViewDef.Create;
ViewDef.QueryText.Text := vViews[i][1];
ViewDef.AttrList.Text := vViews[i][2];
ViewDef.ExprList.Text := vViews[i][3];
ViewDef.ConstrList.Text := vViews[i][4];
ViewDef.OrderList.Text := vViews[i][5];
ViewDef.Number := StrToIntDef(vViews[i][6], 0);
ViewDef.OrderColumn := vViews[i][7];
ViewDef.OrderType := vViews[i][8];
if ViewDef.Number <> -1 then // View -1 somente utilizada para definições básicas
begin
Items.AddObject(vViews[i][0], ViewDef);
if (iViewDefault = -1) and (ViewDef.Number = 0) then
iViewDefault := iAux;
Inc(iAux);
end
else
FBaseView := ViewDef;
end;
ItemIndex := iViewDefault;
FItemIndexDefault := ItemIndex;
if not Assigned(FBaseView) then
FBaseView := TViewDef.Create // Cria em branco caso não exista uma view básica
else
Items.AddObject('<genérica>', FBaseView);
finally
Screen.Cursor := OldCursor;
end;
end;
procedure TosComboFilter.PrepareQuery(PQuery: TSQLStringList; const PExpressions, POrder, PDefaultExpressions: string);
begin
with PQuery do
begin
InsertWhere(PDefaultExpressions);
InsertWhere(PExpressions);
InsertOrder(POrder);
end;
end;
procedure TosComboFilter.SetViewDefault(const Value: integer);
begin
FViewDefault := Value;
end;
procedure TosComboFilter.SetClientDS(const Value: TClientDataset);
begin
FClientDS := Value;
end;
procedure TosComboFilter.SetUserID(const Value: string);
begin
FUserID := Value;
end;
procedure TosComboFilter.SetFilterDefName(const Value: string);
begin
FFilterDefName := Value;
end;
{ TPsViewDef }
constructor TViewDef.Create;
begin
FAttrList := TStringList.Create;
FExprList := TStringList.Create;
FConstrList := TStringList.Create;
FOrderList := TStringList.Create;
FQueryText := TStringList.Create;
end;
destructor TViewDef.Destroy;
begin
FAttrList.Free;
FExprList.Free;
FConstrList.Free;
FOrderList.Free;
FQueryText.Free;
inherited;
end;
{--------------------------------------------------------------------------
Objetivo >
Observações>
Criação >
Atualização> 10/02/2006 – Ricardo N. Acras
Alteração na forma de preencher os parâmetros. O preenchimento
normal utilizando assign simplesmente não funciona. Não entendo
o por que disso.
--------------------------------------------------------------------------}
function TosComboFilter.ExecuteView(PNumView, PConstraint: integer;
PValue: string): boolean;
var
slQuery: TSQLStringList;
slConstr, slExpr: TStrings;
//slOrder: TStrings;
sExpr: string;
OldCursor: TCursor;
i: integer;
begin
OldCursor := Screen.Cursor;
Screen.Cursor := crHourglass;
Result := False;
slQuery := TSQLStringList.Create;
try
if PNumView = -1 then
begin
// Repassa a query para o ClientDataset
slQuery.Assign(FBaseView.QueryText);
slExpr := FBaseView.ExprList;
slConstr := FBaseView.ConstrList;
//slOrder := FBaseView.OrderList;
if slConstr.Count > PConstraint then
begin
sExpr := GetExpressionFromConstraint(slConstr[PConstraint], PValue);
PrepareQuery(slQuery, sExpr, '', slExpr.Text);
FClientDS.Close;
//preencher os parâmetros
FParams.ParseSQL(slQuery.Text, True);
if FParams.Count > 0 then
begin
if Assigned(FGetParams) then
FGetParams(Self);
FClientDS.Params.Assign(FParams);
end
else
if FClientDS.Params.Count > 0 then
FClientDS.Params.Clear;
FClientDS.CommandText := slQuery.Text;
//preencher manualmente os parâmetros por que o preenchimento automático
// não funciona.
for i := 0 to FParams.Count-1 do
begin
FClientDS.CommandText := StringReplace(FClientDS.CommandText, ':'+FParams[0].Name,
FParams[0].AsString,[]);
end;
FClientDS.Params.Clear;
FClientDS.DisableControls;
FClientDS.Open;
FClientDS.EnableControls;
Result := True;
end;
end;
finally
slQuery.Free;
Screen.Cursor := OldCursor;
end;
end;
function TosComboFilter.GetExpressionFromConstraint(const
PConstraint, PValue: string): string;
var
sAux: string;
begin
sAux := GetWord(PConstraint, 2, ';'); // Expressão
Result := Format(sAux,[PValue]);
ReplaceConstraintChars(Result);
end;
procedure TosComboFilter.ConfigFields(PIndex: integer);
var
i: integer;
slAttr: TStrings;
sLabel: string;
begin
// Ajusta os fields
slAttr := GetAttrList(PIndex);
for i:=0 to FClientDS.Fields.Count - 1 do
begin
if FClientDS.Fields[i].FieldName = 'OID' then
FClientDS.Fields[i].Visible := False;
sLabel := slAttr.Values[FClientDS.Fields[i].FieldName];
if sLabel <> '' then
begin
if Pos(';', sLabel) <> 0 then // contém o DisplayWidth
begin
FClientDS.Fields[i].DisplayWidth := StrToIntDef(GetWord(sLabel, 2, ';'), FClientDS.Fields[i].DisplayWidth);
if upperCase(GetWord(sLabel, 3, ';')) = 'CURR' then
TFloatField(FClientDS.Fields[i]).currency := true;
sLabel := GetWord(sLabel, 1, ';');
end;
FClientDS.Fields[i].DisplayLabel := sLabel;
end
else
FClientDS.Fields[i].Visible := False;
end;
end;
procedure TosComboFilter.ResetToItemDefault;
begin
ItemIndex := FItemIndexDefault;
end;
procedure TosComboFilter.ClearViews;
var
i: integer;
begin
for i:=0 to Items.Count - 1 do
if Assigned(Items.Objects[i]) then
begin
Items.Objects[i].Free;
Items.Objects[i] := nil;
end;
Items.Clear;
Text := '';
end;
{-------------------------------------------------------------------------
Objetivo > Trazer a lista de expressões default
Parâmetros > PIndex: índice do filtro
Retorno >
Criação >
Observações>
Atualização> 13/02/2006 - Ricardo N. Acras
Alteração para chamar o evento onCustomExprList que, se
atribuído da ao programador a chance de alterar
programáticamente o ExprList.
------------------------------------------------------------------------}
function TosComboFilter.GetExprList(PIndex: integer): TStrings;
var
ViewSel, ViewInicial: TViewDef;
begin
ViewSel := TViewDef(Items.Objects[PIndex]);
ViewInicial := FBaseView;
if (not Assigned(ViewSel)) and (not Assigned(ViewInicial)) then
raise Exception.Create('Não há definições de views para os filtros');
if Trim(ViewSel.ExprList.Text) <> '' then
Result := ViewSel.ExprList
else
Result := ViewInicial.ExprList;
if Assigned(FonGetCustomExprList) then
FonGetCustomExprList(result);
end;
procedure TosComboFilter.SetSQLConnection(const Value: TosSQLConnection);
begin
FSQLConnection := Value;
end;
{-------------------------------------------------------------------------
Objetivo > Verificar se a definição de filtro é referente a uma classe
customizada
Parâmetros > Conforme documentação
Retorno >
Criação > 20.06.2006 - Ricardo N. Acras
Observações>
Atualização>
------------------------------------------------------------------------}
function TosComboFilter.isDefCustomFilter(index: integer): boolean;
begin
result :=
(trim(TViewDef(Items.Objects[index]).queryText.text) <> '') AND
(trim(TViewDef(Items.Objects[index]).queryText.text)[1] = 'T');
end;
{-------------------------------------------------------------------------
Objetivo >
Parâmetros > Conforme documentação
Retorno >
Criação > 20.06.2006 - Ricardo N. Acras
Observações>
Atualização>
------------------------------------------------------------------------}
function TosComboFilter.defTemRestricaoUsuario(index: integer): boolean;
begin
result := TViewDef(Items.Objects[index]).FConstrList.Count>0;
end;
end.
|
unit Benjamim;
{$IF DEFINED(FPC)}
{$MODE DELPHI}{$H+}
{$ENDIF}
interface
uses
{$IF DEFINED(FPC)}
Classes, StrUtils,
{$ELSE}
System.Classes, System.StrUtils,
{$ENDIF}
Benjamim.Utils, Benjamim.Header.Interfaces, Benjamim.Payload.Interfaces,
Benjamim.Signature.Interfaces, Benjamim.Interfaces;
type
TJwtAlgorithm = Benjamim.Utils.TJwtAlgorithm;
type
TJWT = class(TInterfacedObject, iJWT)
class function New(const aSingleton: boolean = true): iJWT;
constructor Create;
destructor Destroy; override;
strict private
FToken: string;
FPassword: string;
FPasswordEncoded: boolean;
FHeader: iHeader;
FPayload: iPayload;
FSignature: iSignature;
private
class var FInstance: iJWT;
public
function Token(aValue: string): iJWT; overload;
function Password(aValue: string; const aEncoded: boolean = false): iJWT; overload;
function PasswordEncoded: boolean;
function Token: string; overload;
function Password: string; overload;
function Header: iHeader;
function Payload: iPayload;
function Signature: iSignature;
end;
function JWT(const aSingleton: boolean = true): iJWT;
implementation
uses
{$IF DEFINED(FPC)}
SysUtils,
{$ELSE}
System.SysUtils,
{$ENDIF}
Benjamim.Header, Benjamim.Payload, Benjamim.Signature;
function JWT(const aSingleton: boolean = true): iJWT;
begin
Result := TJWT.New(aSingleton);
end;
{ TJWT }
class function TJWT.New(const aSingleton: boolean = true): iJWT;
begin
if not aSingleton then
Exit(TJWT.Create);
if not Assigned(TJWT.FInstance) then
TJWT.FInstance := TJWT.Create;
Result := TJWT.FInstance;
end;
constructor TJWT.Create;
begin
FHeader := THeader.New;
FPayload := TPayload.New;
FSignature := TSignature.New(Self);
FPasswordEncoded := false;
end;
destructor TJWT.Destroy;
begin
FHeader := nil;
FPayload := nil;
FSignature := nil;
inherited Destroy;
end;
function TJWT.Password(aValue: string; const aEncoded: boolean = false): iJWT;
begin
FPassword := aValue;
FPasswordEncoded := aEncoded;
Result := Self;
end;
function TJWT.Token(aValue: string): iJWT;
begin
FToken := aValue;
Result := Self;
end;
function TJWT.Header: iHeader;
begin
Result := FHeader;
end;
function TJWT.Payload: iPayload;
begin
Result := FPayload;
end;
function TJWT.Signature: iSignature;
begin
Result := FSignature;
end;
function TJWT.Token: string;
begin
Result := FToken;
end;
function TJWT.Password: string;
begin
Result := FPassword;
end;
function TJWT.PasswordEncoded: boolean;
begin
Result := FPasswordEncoded;
end;
var
LPass: string;
initialization
begin
LPass := GetEnvironmentVariable('JWT_PRIVATE_PASSWORD');
JWT.Password(IFThen(SameStr(LPass, EmptyStr), DEFAULT_PASSWORD, LPass));
end;
finalization
JWT._Release;
end.
|
unit View.ImportarBaixasTFO;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky,
dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White,
dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, dxSkinscxPCPainter, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit,
dxLayoutcxEditAdapters, cxLabel, Control.ControleBaixasTFO, System.Actions, Vcl.ActnList, dxLayoutControlAdapters, Vcl.Menus,
Vcl.StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxButtonEdit, cxMemo, cxProgressBar, Thread.ImportarBaixasTFO, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxDropDownEdit,
ShellAPI, Vcl.ExtCtrls, cxCheckBox, Thread.ImportarBaixasDIRECT;
type
Tview_ImportarBaixasTFO = class(TForm)
dxLayoutControl1Group_Root: TdxLayoutGroup;
dxLayoutControl1: TdxLayoutControl;
cxLabel1: TcxLabel;
dxLayoutItem1: TdxLayoutItem;
edtArquivo: TcxButtonEdit;
dxLayoutItem2: TdxLayoutItem;
cxButton1: TcxButton;
dxLayoutItem3: TdxLayoutItem;
dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup;
memLog: TcxMemo;
dxLayoutItem4: TdxLayoutItem;
cxButton2: TcxButton;
dxLayoutItem5: TdxLayoutItem;
cxButton3: TcxButton;
dxLayoutItem6: TdxLayoutItem;
dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup;
pbImportacao: TcxProgressBar;
dxLayoutItem7: TdxLayoutItem;
OpenDialog: TOpenDialog;
aclBaixas: TActionList;
actFechar: TAction;
actAbrir: TAction;
actImportar: TAction;
actCancelar: TAction;
actVisualizar: TAction;
cboCliente: TcxComboBox;
dxLayoutItem8: TdxLayoutItem;
Timer1: TTimer;
checkBoxLojas: TcxCheckBox;
dxLayoutItem9: TdxLayoutItem;
procedure actImportarExecute(Sender: TObject);
procedure actAbrirExecute(Sender: TObject);
procedure actFecharExecute(Sender: TObject);
procedure actCancelarExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure actVisualizarExecute(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure cboClientePropertiesChange(Sender: TObject);
private
{ Private declarations }
procedure Importar;
procedure VisualizarPlanilha;
procedure ImportarDIRECT;
procedure AtualizaLogTFO;
procedure AtualizaLOGDIRECT;
public
{ Public declarations }
end;
var
view_ImportarBaixasTFO: Tview_ImportarBaixasTFO;
controle : TControleBaixasTFOControl;
planilha : Tthread_ImportarBaixasTFO;
direct : Tthread_ImportarbaixasDirect;
implementation
{$R *.dfm}
uses Data.SisGeF, View.VisualizacaoPlanilha, Global.Parametros;
procedure Tview_ImportarBaixasTFO.actAbrirExecute(Sender: TObject);
begin
if cboCliente.ItemIndex <= 0 then
begin
Application.MessageBox('Selecione o cliente!', 'Atenção', MB_OK + MB_ICONEXCLAMATION);
Exit;
end;
OpenDialog.FilterIndex := cboCliente.ItemIndex;
if OpenDialog.Execute then
begin
edtArquivo.Text := OpenDialog.FileName;
end;
end;
procedure Tview_ImportarBaixasTFO.actCancelarExecute(Sender: TObject);
begin
if cboCliente.ItemIndex = 1 then
begin
planilha.Terminate;
end
else if cboCliente.ItemIndex = 2 then
begin
direct.Terminate;
end;
end;
procedure Tview_ImportarBaixasTFO.actFecharExecute(Sender: TObject);
begin
Perform(WM_CLOSE, 0, 0);
end;
procedure Tview_ImportarBaixasTFO.actImportarExecute(Sender: TObject);
begin
if edtArquivo.Text = '' then
begin
Application.MessageBox('Informe o arquivo da planilha!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if not FileExists(edtArquivo.Text) then
begin
Application.MessageBox('Arquivo da planilha não encontrado!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
if Application.MessageBox('Confirma a importação da planilha?', 'Importar', MB_YESNO + MB_ICONQUESTION) = IDNO then Exit;
case cboCliente.ItemIndex of
1 : Importar;
2 : ImportarDIRECT;
else
Application.MessageBox('Nenhum Cliente foi informado!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
end;
procedure Tview_ImportarBaixasTFO.actVisualizarExecute(Sender: TObject);
begin
VisualizarPlanilha;
end;
procedure Tview_ImportarBaixasTFO.AtualizaLOGDIRECT;
begin
if not Global.Parametros.pbProcess then
begin
Timer1.Enabled := False;
dxLayoutItem7.Visible := False;
actImportar.Enabled := True;
actCancelar.Enabled := False;
actAbrir.Enabled := True;
memLog.Lines.Text := Global.Parametros.psLOG;
Application.MessageBox('Importação concluída!', 'Atenção', MB_OK + MB_ICONEXCLAMATION);
Global.Parametros.psLOG := '';
edtArquivo.Text := '';
pbImportacao.Position := 0;
end
else
begin
pbImportacao.Position := Global.Parametros.pdPos;
memLog.Lines.Text := Global.Parametros.psLOG;
if Length(Global.Parametros.psMessage) > 0 then
begin
Application.MessageBox(PChar(Global.Parametros.psMessage), 'Atenção', MB_OK + MB_ICONEXCLAMATION);
Global.Parametros.psMessage := '';
end;
end;
if direct.bCancel then
begin
Timer1.Enabled := False;
dxLayoutItem7.Visible := False;
actImportar.Enabled := True;
actCancelar.Enabled := False;
actAbrir.Enabled := True;
memLog.Lines.Text := Global.Parametros.psLOG;
if Global.Parametros.psLOG <> '' then
memLog.Lines.Text := Global.Parametros.psLOG;
Application.MessageBox('Importação cancelada!', 'Atenção', MB_OK + MB_ICONEXCLAMATION);
end;
end;
procedure Tview_ImportarBaixasTFO.AtualizaLogTFO;
begin
if not Global.Parametros.pbProcess then
begin
Timer1.Enabled := False;
dxLayoutItem7.Visible := False;
actImportar.Enabled := True;
actCancelar.Enabled := False;
actAbrir.Enabled := True;
memLog.Lines.Text := Global.Parametros.psLOG;
Global.Parametros.psLOG := '';
Application.MessageBox('Importação concluída!', 'Atenção', MB_OK + MB_ICONEXCLAMATION);
edtArquivo.Text := '';
pbImportacao.Position := 0;
end
else
begin
pbImportacao.Position := Global.Parametros.pdPos;
memLog.Lines.Text := Global.Parametros.psLOG;
if Length(Global.Parametros.psMessage) > 0 then
begin
Application.MessageBox(PChar(Global.Parametros.psMessage), 'Atenção', MB_OK + MB_ICONEXCLAMATION);
Global.Parametros.psMessage := '';
end;
end;
if planilha.bCancel then
begin
Timer1.Enabled := False;
dxLayoutItem7.Visible := False;
actImportar.Enabled := True;
actCancelar.Enabled := False;
actAbrir.Enabled := True;
if Global.Parametros.psLOG <> '' then
memLog.Lines.Text := Global.Parametros.psLOG;
Global.Parametros.psLOG := '';
Application.MessageBox('Importação cancelada!', 'Atenção', MB_OK + MB_ICONEXCLAMATION);
end;
end;
procedure Tview_ImportarBaixasTFO.cboClientePropertiesChange(Sender: TObject);
begin
if cboCliente.ItemIndex = 2 then
begin
dxLayoutItem9.Visible := True;
end
else
begin
dxLayoutItem9.Visible := False;
checkBoxLojas.Checked := False;
end;
end;
procedure Tview_ImportarBaixasTFO.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
view_ImportarBaixasTFO := nil;
end;
procedure Tview_ImportarBaixasTFO.Importar;
begin
planilha := Tthread_ImportarBaixasTFO.Create(True);
planilha.FFile := edtArquivo.Text;
planilha.FreeOnTerminate := True;
planilha.Priority := tpNormal;
planilha.iCodigoCliente := 1;
Timer1.Enabled := True;
dxLayoutItem7.Visible := True;
actImportar.Enabled := False;
actCancelar.Enabled := True;
actAbrir.Enabled := False;
planilha.Start;
end;
procedure Tview_ImportarBaixasTFO.ImportarDIRECT;
begin
direct := Tthread_ImportarBaixasDIRECT.Create(True);
direct.FFile :=edtArquivo.Text;
direct.FreeOnTerminate := True;
direct.Priority := tpNormal;
direct.iCodigoCliente := 4; // deverá ser implementado para informar o código do cliente
direct.bLojas := checkBoxLojas.Checked;
Timer1.Enabled := True;
dxLayoutItem7.Visible := True;
actImportar.Enabled := False;
actCancelar.Enabled := True;
actAbrir.Enabled := False;
direct.Start;
end;
procedure Tview_ImportarBaixasTFO.Timer1Timer(Sender: TObject);
begin
case cboCliente.ItemIndex of
1 : AtualizaLogTFO;
2 : AtualizaLogDIRECT;
else
Application.MessageBox('Nenhum Cliente foi informado!', 'Atenção', MB_OK + MB_ICONWARNING);
Exit;
end;
end;
procedure Tview_ImportarBaixasTFO.VisualizarPlanilha;
begin
sFileExt := LowerCase(ExtractFileExt(edtArquivo.Text));
if sFileExt = '.txt' then
begin
if not Assigned(view_VisualizacaoPlanilhas) then
begin
view_VisualizacaoPlanilhas := Tview_VisualizacaoPlanilhas.Create(Application);
end;
view_VisualizacaoPlanilhas.FFile := edtArquivo.Text;
view_VisualizacaoPlanilhas.ShowModal;
end
else if sFileExt = '.csv' then
begin
ShellExecute(Handle, 'open', pchar(edtArquivo.Text), nil, nil, SW_SHOW);
end;
end;
end.
|
namespace Sugar;
interface
type
Encoding = public class {$IF COOPER}mapped to java.nio.charset.Charset{$ELSEIF ECHOES}mapped to System.Text.Encoding{$ELSEIF TOFFEE}mapped to Foundation.NSNumber{$ENDIF}
private
method GetName: String;
public
method GetBytes(Value: array of Char): array of Byte;
method GetBytes(Value: array of Char; Offset: Integer; Count: Integer): array of Byte;
method GetBytes(Value: String): array of Byte;
method GetChars(Value: array of Byte; Offset: Integer; Count: Integer): array of Char;
method GetChars(Value: array of Byte): array of Char;
method GetString(Value: array of Byte): String;
method GetString(Value: array of Byte; Offset: Integer; Count: Integer): String;
class method GetEncoding(aName: String): Encoding;
property Name: String read GetName;
class property ASCII: Encoding read GetEncoding("US-ASCII");
class property UTF8: Encoding read GetEncoding("UTF-8");
class property UTF16LE: Encoding read GetEncoding("UTF-16LE");
class property UTF16BE: Encoding read GetEncoding("UTF-16BE");
class property &Default: Encoding read UTF8;
{$IF TOFFEE}
method AsNSStringEncoding: NSStringEncoding;
class method FromNSStringEncoding(aEncoding: NSStringEncoding): Encoding;
{$ENDIF}
end;
EncodingHelpers = public static class
private
public
class method GetBytes(aEncoding: Encoding; Value: array of Char; Offset: Integer; Count: Integer): array of Byte;
class method GetBytes(aEncoding: Encoding; Value: String): array of Byte;
class method GetChars(aEncoding: Encoding; Value: array of Byte; Offset: Integer; Count: Integer): array of Char;
class method GetString(aEncoding: Encoding; Value: array of Byte; Offset: Integer; Count: Integer): String;
class method GetEncoding(aName: String): Encoding;
end;
implementation
method Encoding.GetBytes(Value: array of Char): array of Byte;
begin
if Value = nil then
raise new SugarArgumentNullException("Value");
exit GetBytes(Value, 0, Value.length);
end;
method Encoding.GetChars(Value: array of Byte): array of Char;
begin
{$IF COOPER}
exit GetChars(Value, 0, Value.length);
{$ELSEIF ECHOES}
exit mapped.GetChars(Value);
{$ELSEIF TOFFEE}
exit GetString(Value).ToCharArray;
{$ENDIF}
end;
method Encoding.GetString(Value: array of Byte): String;
begin
if Value = nil then
raise new SugarArgumentNullException("Value");
exit GetString(Value, 0, Value.length);
end;
class method Encoding.GetEncoding(aName: String): Encoding;
begin
exit EncodingHelpers.GetEncoding(aName);
end;
method Encoding.GetName: String;
begin
{$IF COOPER}
exit mapped.name;
{$ELSEIF ECHOES}
exit mapped.WebName;
{$ELSEIF TOFFEE}
var lName := CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(mapped.unsignedIntValue));
if assigned(lName) then
result := bridge<NSString>(lName, BridgeMode.Transfer);
{$ENDIF}
end;
{$IF TOFFEE}
method Encoding.AsNSStringEncoding: NSStringEncoding;
begin
result := (self as NSNumber).unsignedIntegerValue as NSStringEncoding;
end;
class method Encoding.FromNSStringEncoding(aEncoding: NSStringEncoding): Encoding;
begin
result := NSNumber.numberWithUnsignedInteger(aEncoding);
end;
{$ENDIF}
method Encoding.GetBytes(Value: array of Char; Offset: Integer; Count: Integer): array of Byte;
begin
exit EncodingHelpers.GetBytes(self, Value, Offset, Count);
end;
method Encoding.GetBytes(Value: String): array of Byte;
begin
exit EncodingHelpers.GetBytes(self, Value);
end;
method Encoding.GetChars(Value: array of Byte; Offset: Integer; Count: Integer): array of Char;
begin
exit EncodingHelpers.GetChars(self, Value, Offset, Count);
end;
method Encoding.GetString(Value: array of Byte; Offset: Integer; Count: Integer): String;
begin
exit EncodingHelpers.GetString(self, Value, Offset, Count);
end;
class method EncodingHelpers.GetEncoding(aName: String): Encoding;
begin
SugarArgumentNullException.RaiseIfNil(aName, "Name");
{$IF COOPER}
exit java.nio.charset.Charset.forName(aName);
{$ELSEIF WINDOWS_PHONE}
result := CustomEncoding.ForName(aName);
if result = nil then
result := System.Text.Encoding.GetEncoding(aName);
{$ELSEIF ECHOES}
result := System.Text.Encoding.GetEncoding(aName);
{$ELSEIF TOFFEE}
var lEncoding := NSStringEncoding.UTF8StringEncoding;
case aName of
'UTF8','UTF-8': lEncoding := NSStringEncoding.UTF8StringEncoding;
'UTF16','UTF-16': lEncoding := NSStringEncoding.UTF16StringEncoding;
'UTF32','UTF-32': lEncoding := NSStringEncoding.UTF32StringEncoding;
'UTF16LE','UTF-16LE': lEncoding := NSStringEncoding.UTF16LittleEndianStringEncoding;
'UTF16BE','UTF-16BE': lEncoding := NSStringEncoding.UTF16BigEndianStringEncoding;
'UTF32LE','UTF-32LE': lEncoding := NSStringEncoding.UTF32LittleEndianStringEncoding;
'UTF32BE','UTF-32BE': lEncoding := NSStringEncoding.UTF32BigEndianStringEncoding;
'US-ASCII', 'ASCII','UTF-ASCII': lEncoding := NSStringEncoding.ASCIIStringEncoding;
else begin
var lH := CFStringConvertIANACharSetNameToEncoding(bridge<CFStringRef>(aName));
if lH = kCFStringEncodingInvalidId then
raise new SugarArgumentException();
lEncoding := CFStringConvertEncodingToNSStringEncoding(lH) as NSStringEncoding;
end;
end;
result := NSNumber.numberWithUnsignedInt(lEncoding);
{$ENDIF}
end;
method EncodingHelpers.GetBytes(aEncoding: Encoding; Value: array of Char; Offset: Integer; Count: Integer): array of Byte;
begin
if Value = nil then
raise new SugarArgumentNullException("Value");
if Count = 0 then
exit [];
RangeHelper.Validate(Range.MakeRange(Offset, Count), Value.Length);
{$IF ANDROID}
var Buffer := java.nio.charset.Charset(aEncoding).newEncoder.
onMalformedInput(java.nio.charset.CodingErrorAction.REPLACE).
onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPLACE).
replaceWith([63]).
encode(java.nio.CharBuffer.wrap(Value, Offset, Count));
result := new Byte[Buffer.remaining];
Buffer.get(result);
{$ELSEIF COOPER}
var Buffer := java.nio.charset.Charset(aEncoding).encode(java.nio.CharBuffer.wrap(Value, Offset, Count));
result := new Byte[Buffer.remaining];
Buffer.get(result);
{$ELSEIF ECHOES}
exit System.Text.Encoding(aEncoding).GetBytes(Value, Offset, Count);
{$ELSEIF TOFFEE}
exit GetBytes(aEncoding, new String(Value, Offset, Count));
{$ENDIF}
end;
method EncodingHelpers.GetBytes(aEncoding: Encoding; Value: String): array of Byte;
begin
SugarArgumentNullException.RaiseIfNil(Value, "Value");
{$IF ANDROID}
var Buffer := java.nio.charset.Charset(aEncoding).newEncoder.
onMalformedInput(java.nio.charset.CodingErrorAction.REPLACE).
onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPLACE).
replaceWith([63]).
encode(java.nio.CharBuffer.wrap(Value));
result := new Byte[Buffer.remaining];
Buffer.get(result);
{$ELSEIF COOPER}
var Buffer := java.nio.charset.Charset(aEncoding).encode(Value);
result := new Byte[Buffer.remaining];
Buffer.get(result);
{$ELSEIF ECHOES}
exit System.Text.Encoding(aEncoding).GetBytes(Value);
{$ELSEIF TOFFEE}
result := ((Value as NSString).dataUsingEncoding(aEncoding.AsNSStringEncoding) allowLossyConversion(true) as Binary).ToArray;
if not assigned(result) then
raise new SugarFormatException("Unable to convert data");
{$ENDIF}
end;
method EncodingHelpers.GetChars(aEncoding: Encoding; Value: array of Byte; Offset: Integer; Count: Integer): array of Char;
begin
{$IF COOPER}
var Buffer := java.nio.charset.Charset(aEncoding).newDecoder.
onMalformedInput(java.nio.charset.CodingErrorAction.REPLACE).
onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPLACE).
replaceWith("?").
decode(java.nio.ByteBuffer.wrap(Value, Offset, Count));
result := new Char[Buffer.remaining];
Buffer.get(result);
{$ELSEIF ECHOES}
exit System.Text.Encoding(aEncoding).GetChars(Value, Offset, Count);
{$ELSEIF TOFFEE}
exit GetString(aEncoding, Value, Offset, Count).ToCharArray;
{$ENDIF}
end;
method EncodingHelpers.GetString(aEncoding: Encoding; Value: array of Byte; Offset: Integer; Count: Integer): String;
begin
if Value = nil then
raise new SugarArgumentNullException("Value");
if Count = 0 then
exit "";
RangeHelper.Validate(Range.MakeRange(Offset, Count), Value.Length);
{$IF COOPER}
var Buffer := java.nio.charset.Charset(aEncoding).newDecoder.
onMalformedInput(java.nio.charset.CodingErrorAction.REPLACE).
onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPLACE).
replaceWith("?").
decode(java.nio.ByteBuffer.wrap(Value, Offset, Count));
result := Buffer.toString;
{$ELSEIF ECHOES}
result := System.Text.Encoding(aEncoding).GetString(Value, Offset, Count);
{$ELSEIF TOFFEE}
result := new NSString withBytes(@Value[Offset]) length(Count) encoding(aEncoding.AsNSStringEncoding);
if not assigned(result) then
raise new SugarFormatException("Unable to convert input data");
{$ENDIF}
end;
end. |
unit UFrameKP;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, ExtCtrls, Buttons, IniFiles, Contnrs, UTreeItem;
type
TItemKP = class;
TFrameKP = class(TFrame)
gbKP: TGroupBox;
Panel: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
gbEvents: TGroupBox;
edName: TEdit;
edAddress: TEdit;
BtnChange: TButton;
Memo: TMemo;
Label5: TLabel;
stLastConnect: TStaticText;
BtnKvit: TButton;
memoComm: TMemo;
lblCommMsg: TLabel;
Label4: TLabel;
edDataLag: TEdit;
OpenDialog: TOpenDialog;
procedure BtnChangeClick(Sender: TObject);
procedure BtnKvitClick(Sender: TObject);
private
{ Private declarations }
KP:TItemKP;
public
{ Public declarations }
end;
TItemKP = class(TTreeItem)
private
procedure SetLastDataTime(const Value: TDateTime);
protected
FKP:TFrameKP;
// Persistent variables
FName:String;
FAddress:Byte;
FPeriod:TDateTime;
FDataLag:Integer;
FLastDataTime,FLastEvntTime:TDateTime;
Port:Integer;
Analogs:TList;
Services:TObjectList;
SvcReprog:Pointer;
//
FEvents:String;
FCommMsgs:TStringList;
AlarmTimer:Integer;
procedure RefreshFrame;
public
function Enter(Owner:TComponent):TFrame;override;
function Leave:Boolean;override;
function Validate:Boolean;override;
constructor Load(Nodes:TTreeNodes; ParentNode:TTreeNode; Ini,Cfg:TIniFile; const Section:String);
destructor Destroy;override;
procedure SaveCfg(Cfg:TIniFile);override;
procedure TimerProc;override;
procedure AddEvent(Time:TDateTime; Event:String);
procedure CommMsg(Msg:String; DataSize:Integer);
function handleADCService(const Data:String):Integer;
procedure SwitchProgramming;
procedure SendSoftReset;
public
Alarm:Boolean;
property LastDataTime:TDateTime read FLastDataTime write SetLastDataTime;
property LastEvntTime:TDateTime read FLastEvntTime write FLastEvntTime;
property Name:String read FName;
property Address:Byte read FAddress;
property Period:TDateTime read FPeriod;
property DataLag:Integer read FDataLag;
end;
const
ADCSampleSize=2;
implementation
uses
UFormMain, UFrameAnalog, Misc, DataTypes, UNetW,
UServices, UTime, UPRT_Liner;
{$R *.DFM}
procedure TFrameKP.BtnChangeClick(Sender: TObject);
begin
KP.ChangeData(BtnChange,Panel);
end;
{ TItemKP }
function TItemKP.Enter(Owner:TComponent): TFrame;
begin
FKP:=TFrameKP.Create(Owner);
FKP.KP:=Self;
FKP.Name:='';
FKP.edName.Text:=Name;
FKP.edAddress.Text:=IntToStr(Address);
FKP.edDataLag.Text:=IntToStr(DataLag);
RefreshFrame;
FKP.Memo.Text:=FEvents;
FKP.memoComm.Text:=FCommMsgs.Text;
Result:=FKP;
end;
function TItemKP.Leave: Boolean;
begin
FKP.Free; FKP:=nil;
Result:=True;
end;
constructor TItemKP.Load(Nodes:TTreeNodes; ParentNode:TTreeNode; Ini,Cfg: TIniFile; const Section: String);
var
i,Cnt:Integer;
S:String;
begin
Self.Section:=Section;
Node:=Nodes.AddChildObject(ParentNode,Section,Self);
FName:=Ini.ReadString(Section,'Name',Section);
FAddress:=Ini.ReadInteger(Section,'Address',0);
FPeriod:=1/Ini.ReadInteger(Section,'RecsPerDay',nSecsPerDay);
Port:=Ini.ReadInteger(Section,'Port',22000+Address);
FLastDataTime:=Cfg.ReadDateTime(Section,'LastDataTime',0);
FLastEvntTime:=Cfg.ReadDateTime(Section,'LastEvntTime',0);
FDataLag:=Cfg.ReadInteger(Section,'DataLag',30);
FCommMsgs:=TStringList.Create;
Cnt:=Ini.ReadInteger(Section,'ADCCount',0);
Analogs:=TList.Create;
for i:=1 to Cnt do begin
S:=Ini.ReadString(Section,Format('ADC%.2d',[i]),'');
if S<>''
then Analogs.Add(TItemAnalog.Load(Nodes,Node,Ini,Cfg,S));
end;
Services:=TObjectList.Create;
Services.Add(TServicePing.Create(Self));
Services.Add(TServiceTimeServer.Create(Self));
Services.Add(TServiceAlarm.Create(Self,Ini));
Services.Add(TServiceADC.Create(Self));
SvcReprog:=TServiceReprog.Create(Self);
Services.Add(SvcReprog);
// register services
for i:=0 to Services.Count-1
do NetW_addService(FAddress,TService(Services[i]));
end;
procedure TItemKP.TimerProc;
begin
if Alarm then begin
if AlarmTimer=0 then begin
FormMain.Visible:=True;
SetForegroundWindow(FormMain.Handle);
FormMain.TreeView.Selected:=Node;
if FKP<>nil then FKP.BtnKvit.SetFocus;
MessageBeep(MB_OK);
AlarmTimer:=5;
end
else Dec(AlarmTimer);
end;
end;
function TItemKP.Validate: Boolean;
var
Name_:String;
Interv:Double;
begin
try
Name_:=FKP.edName.Text;
// CheckMinMax(Addr,0,255,FKP.edAddress);
CheckMinMax(Interv,1,60,FKP.edDataLag);
FName:=Name_;
// FAddress:=Trunc(Addr);
FDataLag:=Trunc(Interv);
Result:=True;
except
Result:=False;
end;
end;
procedure TItemKP.SaveCfg(Cfg: TIniFile);
var
dtET:TDateTime;
begin
if LastDataTime>LastEvntTime
then dtET:=LastEvntTime+dtOneSecond*0.999
else dtET:=LastEvntTime;
Cfg.WriteDateTime(Section,'LastDataTime',LastDataTime);
Cfg.WriteDateTime(Section,'LastEvntTime',dtET);
Cfg.WriteInteger(Section,'DataLag',FDataLag);
end;
destructor TItemKP.Destroy;
var
i:Integer;
begin
for i:=0 to Services.Count-1
do NetW_remService(FAddress,TService(Services[i])); // net svc
Services.Free;
// for i:=0 to Analogs.Count-1 do TItemAnalog(Analogs[i]).Free;
Analogs.Free;
FCommMsgs.Free;
inherited;
end;
procedure TItemKP.SetLastDataTime(const Value: TDateTime);
begin
FLastDataTime := Value;
if FKP<>nil then RefreshFrame;
end;
procedure TItemKP.RefreshFrame;
begin
FKP.stLastConnect.Caption:=DateTimeToStr(LastDataTime);
end;
procedure TItemKP.AddEvent(Time:TDateTime; Event: String);
var
Msg:String;
CharBuf:array[0..255] of Char;
n:Integer;
begin
Msg:=LogMsg(Time,Event);
if FKP<>nil then begin
FKP.Memo.SelStart:=0;
FKP.Memo.SelText:=Msg;
end;
FEvents:=Msg+FEvents;
WriteToLog(Msg);
// Îòñûëêà
FormMain.NMUDP.RemoteHost:='127.0.0.1';
FormMain.NMUDP.RemotePort:=Port;
Msg:=#255+LogMsg(Time, Misc.GetUserName+#9+Name+#9+Event+#9);
n:=Length(Msg);
if n>256 then n:=256;
Move(Msg[1],CharBuf[0],n);
// "time \t user \t addr \t id \t info \r\n"
FormMain.NMUDP.SendBuffer(CharBuf,n);
end;
procedure TFrameKP.BtnKvitClick(Sender: TObject);
begin
KP.Alarm:=False;
KP.AddEvent(GetMyTime,'***** ÊÂÈÒÈÐÎÂÀÍÎ');
end;
{$DEFINE UseTSclRecN}
function TItemKP.handleADCService(const Data: String):Integer;
var
ID:^TADCServiceInData;
QntSamples,n,i,j:Integer;
MaxQntSamples:Integer;
BegDataTime,EndDataTime,CurTime:TDateTime;
// sending
IA:TItemAnalog;
ST:TSystemTime;
{$IFDEF UseTSclRecN}
CharBuf:array[0..SizeOf(TSclRecN)-1] of Char;
Buf:TSclRecN absolute CharBuf;
SizeToSend:Integer;
{$ELSE}
CharBuf:array[0..SizeOf(TSclRec)-1] of Char;
Buf:TSclRec absolute CharBuf;
{$ENDIF}
begin
if Data<>'' then
begin
ID:=@(Data[1]);
if ID.SensQnt>0
then begin
// 5 = ToAddr + FromAdd + SvcID + 2 bytes of CRC
MaxQntSamples:=(LINER_TXBSIZE-5-SizeOf(TIME_STAMP)) div (ID.SensQnt*ADCSampleSize);
QntSamples:=(Length(Data)-1-SizeOf(TIME_STAMP)) div (ID.SensQnt*ADCSampleSize);
{$IFDEF UseTSclRecN}
if QntSamples>High(Buf.P)+1
then QntSamples:=High(Buf.P)+1;
{$ENDIF}
end
else begin
MaxQntSamples:=1;
QntSamples:=0;
end;
BegDataTime:=ToDateTime(ID.Time);
EndDataTime:=BegDataTime+QntSamples*Period;
// Result = we need to receive
CurTime := GetMyTime;
if (LastDataTime<>0) and (LastDataTime+Period*1.5 < BegDataTime)
then AddEvent(CurTime,Format('Äàííûå ñ %s ïî %s óòåðÿíû(?)',[DateTimeToStr(LastDataTime+Period),DateTimeToStr(BegDataTime)]));
if (QntSamples = 0) or (CurTime <= EndDataTime)
then Result:=DataLag
else begin
Result := Round((CurTime - EndDataTime) * nSecsPerDay);
if Result < DataLag
then Result:=DataLag-Result
else if QntSamples<MaxQntSamples
then Result:=((MaxQntSamples - QntSamples)*DataLag + MaxQntSamples-1) div MaxQntSamples
else Result:=0;
end;
CommMsg(
Format('Data: %s.%.3d %d*%d',[
DateTimeToStr(BegDataTime),
ID.Time mod 1000, ID.SensQnt, QntSamples ]
), Length(Data)
);
LastDataTime:=EndDataTime;
// Send data cycle
n:=Analogs.Count;
if n>ID.SensQnt then n:=ID.SensQnt;
FormMain.NMUDP.RemoteHost:='127.0.0.1';
FormMain.NMUDP.RemotePort:=Port;
{$IFDEF UseTSclRecN}
DateTimeToSystemTime(BegDataTime,ST);
with Buf.Time do begin
Year:=ST.wYear-1900;
Month:=ST.wMonth;
Day:=ST.wDay;
Hour:=ST.wHour;
Min:=ST.wMinute;
Sec:=ST.wSecond;
Sec100:=Trunc(ST.wMilliseconds*0.1);
end;
SizeToSend:=SizeOf(TSclRec)+(QntSamples-1)*SizeOf(Single);
for i:=0 to n-1 do
begin
IA:=TItemAnalog(Analogs[i]);
Buf.Number:=IA.NetNumber;
for j:=0 to QntSamples-1 do
IA.GetX(ID.Data[i*QntSamples+j],Buf.P[j]);
// Îòñûëêà
FormMain.NMUDP.SendBuffer(CharBuf,SizeToSend);
end;
{$ELSE}
for j:=0 to QntSamples-1 do
begin
DateTimeToSystemTime(BegDataTime+j*Period,ST);
with Buf.Time do begin
Year:=ST.wYear-1900;
Month:=ST.wMonth;
Day:=ST.wDay;
Hour:=ST.wHour;
Min:=ST.wMinute;
Sec:=ST.wSecond;
Sec100:=Trunc(ST.wMilliseconds*0.1);
end;
for i:=0 to n-1 do
begin
IA:=TItemAnalog(Analogs[i]);
Buf.Number:=IA.NetNumber;
IA.GetX(ID.Data[i*QntSamples+j],Buf.P);
// Îòñûëêà
FormMain.NMUDP.SendBuffer(CharBuf,SizeOf(CharBuf));
end;
end;
{$ENDIF}
end
else
begin
CommMsg('Data: [empty answer = not ready]',Length(Data));
Result:=DataLag;
end;
end;
procedure TItemKP.CommMsg(Msg: String; DataSize:Integer);
var
fmt: String;
begin
if DataSize<>0 then
begin
if DataSize>0
then fmt := '%s %d:> %s'
else fmt := '%s %d:< %s';
DataSize := Abs(DataSize);
end
else
fmt := '%s %2:s';
Msg:=Format(fmt,[TimeToStr(GetMyTime),DataSize+3, Msg]);
FCommMsgs.Insert(0,Msg);
if FCommMsgs.Count=128 then FCommMsgs.Delete(127);
if FKP<>nil then FKP.memoComm.Text:=FCommMsgs.Text;
end;
procedure TItemKP.SwitchProgramming;
var
SR:TServiceReprog;
begin
SR:=SvcReprog;
if SR.State = sNone
then begin
if (FKP<>nil) and FKP.OpenDialog.Execute
then SR.startProgramming(FKP.OpenDialog.FileName);
end
else SR.stopProgramming;
end;
procedure TItemKP.SendSoftReset;
begin
TServiceReprog(SvcReprog).SendSoftReset;
end;
end.
|
unit IndyDbServerForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ScktComp, StdCtrls, Grids, DBGrids, Db, DBTables, ComCtrls, DBClient,
IdBaseComponent, IdComponent, IdTCPServer;
type
TForm1 = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
lbLog: TListBox;
cds: TClientDataSet;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
IdTCPServer1: TIdTCPServer;
cdsCompany: TStringField;
cdsCompID: TFloatField;
cdsAddress: TStringField;
cdsState: TStringField;
cdsCountry: TStringField;
cdsEmail: TStringField;
cdsContact: TStringField;
cdsLoggedBy: TStringField;
cdsLoggedOn: TDateField;
procedure FormCreate(Sender: TObject);
procedure IdTCPServer1TIdCommandHandler0Command(ASender: TIdCommand);
procedure IdTCPServer1Connect(AThread: TIdPeerThread);
procedure IdTCPServer1Disconnect(AThread: TIdPeerThread);
private
{ Private declarations }
end;
var
Form1: TForm1;
implementation
var
ID: Integer;
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
IdTCPServer1.Active := True;
// create the table, if it doesn't exist
if not FileExists (cds.FileName) then
cds.CreateDataSet;
cds.Active := True;
cds.LogChanges := False; // don't use delta
end;
procedure TForm1.IdTCPServer1TIdCommandHandler0Command(
ASender: TIdCommand);
var
Data: TStrings;
I: Integer;
begin
Data := TStringList.Create;
try
ASender.Thread.Connection.ReadStrings(Data);
cds.Insert;
// set the fields using the strings
for I := 0 to cds.FieldCount - 1 do
cds.Fields [I].AsString :=
Data.Values [cds.Fields[I].FieldName];
// complete with ID, sender, and date
Inc(ID);
cdsCompID.AsInteger := ID;
cdsLoggedBy.AsString := ASender.Thread.Connection.Socket.Binding.PeerIP;
cdsLoggedOn.AsDateTime := Date;
cds.Post;
// return the ID
ASender.Thread.Connection.WriteLn(cdsCompID.AsString);
finally
Data.Free;
end;
end;
procedure TForm1.IdTCPServer1Connect(AThread: TIdPeerThread);
begin
lbLog.Items.Add ('Connected from: ' +
AThread.Connection.Socket.Binding.PeerIP);
end;
procedure TForm1.IdTCPServer1Disconnect(AThread: TIdPeerThread);
begin
lbLog.Items.Add ('Diconnected from: ' +
AThread.Connection.Socket.Binding.PeerIP);
end;
initialization
// Setup first ID for this session
ID := GetTickCount;
end.
|
{
statusitem.pas
This example shows how to create a window with several buttons which will
control a NSStatusItem (a menubar extras icon).
Compilation of this example requires the following options:
-k-framework -kcocoa -k-lobjc
This example project is released under public domain
AUTHORS: Felipe Monteiro de Carvalho
}
program statusitem;
{$mode delphi}
{$linkframework Cocoa}
{$linklib objc}
uses
objc, ctypes, MacOSAll, AppKit, Foundation, controller, cocoa_pkg;
const
Str_Window_Title = 'StatusItem example project';
Str_Show_Button = 'Show StatusItem';
Str_Hide_Button = 'Hide StatusItem';
Str_Close_Button = 'Exit Program';
begin
{ Creates the AutoreleasePool }
pool := NSAutoreleasePool.Create;
{ Creates the application NSApp object }
NSApp := NSApplication.sharedApplication;
{ Creates a simple window }
MainWindowRect.origin.x := 300.0;
MainWindowRect.origin.y := 300.0;
MainWindowRect.size.width := 300.0;
MainWindowRect.size.height := 500.0;
MainWindow := NSWindow.initWithContentRect_styleMask_backing_defer(MainWindowRect,
NSTitledWindowMask or NSClosableWindowMask or NSMiniaturizableWindowMask or NSResizableWindowMask,
NSBackingStoreBuffered, LongBool(NO));
MainWindowView := NSView.CreateWithHandle(MainWindow.contentView);
CFTitle := CFStringCreateWithPascalString(nil, Str_Window_Title, kCFStringEncodingUTF8);
MainWindow.setTitle(CFTitle);
{ Initializes the controller object }
myController := TMyController.Create();
{ Adds the buttons }
myController.CreateButton(MainWindowView, Str_Show_Button,
50.0, MainWindowRect.size.height - 50.0, 200.0, 25.0,
Str_doShowStatusItem, myController);
myController.CreateButton(MainWindowView, Str_Hide_Button,
50.0, MainWindowRect.size.height - 100.0, 200.0, 25.0,
Str_doHideStatusItem, myController);
myController.CreateButton(MainWindowView, Str_Close_Button,
50.0, MainWindowRect.size.height - 150.0, 200.0, 25.0,
Str_doClose, myController);
{ Enters main message loop }
MainWindow.orderFrontRegardless;
NSApp.setDelegate(myController.Handle);
NSApp.run;
{ Releases the AutoreleasePool }
pool.Free;
end.
|
unit DMX.Data.DataSetRepository;
interface
uses
System.Classes,
System.Generics.Collections,
DMX.Data.VirtualDataSet,
DMX.Data.DSRepDataSets;
type
TDataSetRepManager = class;
TDataSetRepService = class;
TDataSetRepository = class(TComponent)
private
FDataSet: TVirtualDataSet;
FDataName: string;
FManager: TDataSetRepManager;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property DataName: string read FDataName write FDataName;
property DataSet: TVirtualDataSet read FDataSet write FDataSet;
property Manager: TDataSetRepManager read FManager write FManager;
end;
TDataSetRepManager = class(TComponent)
private
FActiveService: TDataSetRepService;
FServices: TList<TDataSetRepService>;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure RegistService(AService: TDataSetRepService);
procedure UnregistService(AService: TDataSetRepService);
published
property ActiveService: TDataSetRepService read FActiveService write FActiveService;
end;
TDataSetRepService = class(TComponent)
private
FManager: TDataSetRepManager;
procedure SetManager(const Value: TDataSetRepManager);
published
property Manager: TDataSetRepManager read FManager write SetManager;
end;
TDataSetRepDAOs = class(TComponent)
private
FService: TDataSetRepService;
FDataSets: TDataSetRepDataSets;
published
property Service: TDataSetRepService read FService write FService;
property DataSets: TDataSetRepDataSets read FDataSets write FDataSets;
end;
implementation
{ TDataSetRepository }
constructor TDataSetRepository.Create(AOwner: TComponent);
begin
inherited;
FDataSet := TVirtualDataSet.Create(Self);
FDataSet.Name := 'VirDataSet';
FDataSet.SetSubComponent(True);
end;
destructor TDataSetRepository.Destroy;
begin
inherited;
end;
{ TDataSetRepService }
procedure TDataSetRepService.SetManager(const Value: TDataSetRepManager);
begin
if FManager = Value then
Exit;
if Assigned(FManager) then
FManager.UnregistService(Self);
FManager := Value;
end;
{ TDataSetRepManager }
constructor TDataSetRepManager.Create(AOwner: TComponent);
begin
inherited;
FServices := TList<TDataSetRepService>.Create;
end;
destructor TDataSetRepManager.Destroy;
begin
FServices.Clear;
FServices.Free;
inherited;
end;
procedure TDataSetRepManager.RegistService(AService: TDataSetRepService);
begin
FServices.Add(AService);
end;
procedure TDataSetRepManager.UnregistService(AService: TDataSetRepService);
begin
FServices.Remove(AService);
end;
end.
|
// the code formatter configuration dialog
// Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html)
// Contributors: Thomas Mueller (http://www.dummzeuch.de)
unit GX_CodeFormatterConfig;
{$I GX_CondDefine.inc}
interface
uses
Windows,
SysUtils,
Classes,
Graphics,
Forms,
Controls,
StdCtrls,
Buttons,
ExtCtrls,
ComCtrls,
Dialogs,
Grids,
Menus,
SynEdit,
GX_CodeFormatterTypes,
GX_CodeFormatterEngine,
GX_CodeFormatterSettings,
GX_EnhancedEditor,
GX_GenericUtils;
type
TStringGrid = class(Grids.TStringGrid)
private
FSpacingOptions: TStringList;
protected
function GetEditStyle(_Col: Integer; _Row: Integer): TEditStyle; override;
function CreateEditor: TInplaceEdit; override;
function CanEditModify: Boolean; override;
function CanEditShow: Boolean; override;
procedure OnGetSpacingOptions(_Col, _Row: Integer; _Items: TStrings);
public
constructor Create(_Owner: TComponent); override;
destructor Destroy; override;
end;
type
TfmCodeFormatterConfig = class(TForm)
pc_Main: TPageControl;
ts_Indent: TTabSheet;
ts_Spacing: TTabSheet;
ts_LineBreaks: TTabSheet;
ed_SpacePerIndent: TEdit;
ud_SpacePerIndent: TUpDown;
l_SpacesPerIndent: TLabel;
ts_Capitalization: TTabSheet;
chk_IndentBegin: TCheckBox;
chk_UpperCompDirectives: TCheckBox;
chk_BlankProc: TCheckBox;
chk_BlankSubProc: TCheckBox;
chk_IndentTry: TCheckBox;
chk_FeedAfterSemiColon: TCheckBox;
cmb_FeedRoundBegin: TComboBox;
l_BeginStyle: TLabel;
chk_FeedAfterThen: TCheckBox;
chk_FeedBeforeEnd: TCheckBox;
chk_UpperNumbers: TCheckBox;
chk_IndentTryElse: TCheckBox;
l_Capitalize: TLabel;
ts_Align: TTabSheet;
OpenDialog: TOpenDialog;
chk_WrapLines: TCheckBox;
l_WrapAtPosition: TLabel;
ed_WrapPosition: TEdit;
ud_WrapPosition: TUpDown;
chk_FeedAfterVar: TCheckBox;
l_ReservedWords: TLabel;
cmb_ReservedCase: TComboBox;
l_StandardDirectives: TLabel;
cmb_StandDirectives: TComboBox;
l_Identifiers: TLabel;
cmb_IdentifiersCase: TComboBox;
chk_IndentComments: TCheckBox;
chk_IndentCompDirectives: TCheckBox;
ts_Misc: TTabSheet;
chk_AlignComments: TCheckBox;
l_AlignComentsAtPosition: TLabel;
ed_AlignCommentPos: TEdit;
ud_AlignCommentPos: TUpDown;
chk_AlignVar: TCheckBox;
l_AlignVarAtPosition: TLabel;
ed_AlignVarPos: TEdit;
ud_AlignVarPos: TUpDown;
chk_FeedElseIf: TCheckBox;
chk_NoFeedBeforeThen: TCheckBox;
chk_NoIndentElseIf: TCheckBox;
chk_IndentCaseElse: TCheckBox;
chk_RemoveDoubleBlank: TCheckBox;
b_EditCapitalization: TButton;
ts_Preview: TTabSheet;
l_Before: TLabel;
l_After: TLabel;
grid_Spacing: TStringGrid;
chk_FeedEachUnit: TCheckBox;
chk_ExceptSingle: TCheckBox;
p_Botton: TPanel;
b_Help: TButton;
b_Ok: TButton;
b_Cancel: TButton;
pm_Extra: TPopupMenu;
mi_ResetTo: TMenuItem;
mi_ResetToDefault: TMenuItem;
mi_Import: TMenuItem;
mi_Export: TMenuItem;
b_Tools: TButton;
od_Import: TOpenDialog;
sd_Export: TSaveDialog;
grp_ExtraIndentBefore: TGroupBox;
grp_AlwaysBreakLine: TGroupBox;
grp_ForceBlankLineBetween: TGroupBox;
l_TryStyle: TLabel;
cmb_FeedRoundTry: TComboBox;
rb_CapitalizationInRegistry: TRadioButton;
rb_CapitalizationInFile: TRadioButton;
ed_CapitalizationFile: TEdit;
b_CapitalizationSelect: TButton;
rg_Capitalization: TRadioGroup;
od_CapitalizationFile: TOpenDialog;
grp_ConfigPrecedence: TGroupBox;
grp_DirectivesPreventFormatting: TGroupBox;
l_MiscStart: TLabel;
l_MiscEnd: TLabel;
ed_StartComment: TEdit;
ed_EndCommentOut: TEdit;
lb_Precedence: TListBox;
b_PrecedenceUp: TButton;
b_PrecedenceDown: TButton;
procedure b_HelpClick(Sender: TObject);
procedure b_EditCapitalizationClick(Sender: TObject);
procedure ts_PreviewShow(Sender: TObject);
procedure HandleOnStatusChange(Sender: TObject; Changes: TSynStatusChanges);
procedure FormShow(Sender: TObject);
procedure chk_FeedAfterThenClick(Sender: TObject);
procedure ts_PreviewResize(Sender: TObject);
procedure b_ToolsClick(Sender: TObject);
procedure mi_ResetToDefaultClick(Sender: TObject);
procedure mi_ImportClick(Sender: TObject);
procedure mi_ExportClick(Sender: TObject);
procedure rb_CapitalizationInRegistryClick(Sender: TObject);
procedure rb_CapitalizationInFileClick(Sender: TObject);
procedure b_CapitalizationSelectClick(Sender: TObject);
procedure lb_PrecedenceClick(Sender: TObject);
procedure b_PrecedenceUpClick(Sender: TObject);
procedure b_PrecedenceDownClick(Sender: TObject);
private
FCapitalization: TGXUnicodeStringList;
m_PreviewBefore: TGxEnhancedEditor;
m_PreviewAfter: TGxEnhancedEditor;
procedure EngineSettingsToForm(const _EngineSettings: TCodeFormatterEngineSettings);
procedure SettingsToForm(const _Settings: TCodeFormatterSettings);
procedure FormToEngineSettings(var _Settings: TCodeFormatterEngineSettings);
procedure FormToSettings(_Settings: TCodeFormatterSettings);
procedure FillPreview;
procedure AddSpaceRow(_RowNo: Integer; const _StrCol1, _StrCol2: string;
_Space: TSpaceSet);
function GetSpaceItem(_Idx: Integer): TSpaceSet;
procedure SetDefault(_Which: string);
procedure HandleCaptitalizationFileDropped(_Sender: TObject; _Files: TStrings);
procedure m_PreviewFileDropped(_Sender: TObject; _Files: TStrings);
procedure UpdatePreview;
public
constructor Create(_Owner: TComponent); override;
destructor Destroy; override;
class function Execute(_Settings: TCodeFormatterSettings): TModalResult;
end;
implementation
{$R *.DFM}
uses
Messages,
GX_dzVclUtils,
GX_CodeFormatterConfigHandler,
GX_CodeFormatterEditCapitalization,
GX_CodeFormatterDefaultSettings;
resourcestring
str_None = 'None';
str_Before = 'Before only';
str_after = 'After only';
str_BeforeAfter = 'Before and after';
str_DefaultSettings = '<default>';
str_PrecedenceDirective = 'GXFormatter.config directive';
str_PrecedenceIniFile = 'GXFormatter.ini file';
str_PrecedenceMySettings = 'my settings as configured here';
constructor TfmCodeFormatterConfig.Create(_Owner: TComponent);
var
st: TStringList;
i: Integer;
mi: TMenuItem;
begin
inherited;
FCapitalization := TGXUnicodeStringList.Create;
st := TStringList.Create;
try
TCodeFormatterConfigHandler.GetDefaultsList(st);
for i := 0 to st.Count - 1 do begin
mi := TMenuItem.Create(Self);
mi.Caption := st[i];
mi.OnClick := mi_ResetToDefaultClick;
mi_ResetTo.Add(mi);
end;
finally
st.Free;
end;
TWinControl_ActivateDropFiles(ed_CapitalizationFile, HandleCaptitalizationFileDropped);
TEdit_ActivateAutoComplete(ed_CapitalizationFile, [acsFileSystem], [actSuggest]);
m_PreviewBefore := TGxEnhancedEditor.Create(Self);
m_PreviewBefore.Name := 'm_PreviewBefore';
m_PreviewBefore.Parent := ts_Preview;
m_PreviewBefore.Left := 0;
m_PreviewBefore.Top := 16;
m_PreviewBefore.Width := 241;
m_PreviewBefore.Height := 337;
m_PreviewBefore.TabOrder := 0;
m_PreviewBefore.OnChange := ts_PreviewShow;
m_PreviewBefore.OnStatusChange := HandleOnStatusChange;
m_PreviewBefore.Highlighter := gxpPas;
m_PreviewAfter := TGxEnhancedEditor.Create(Self);
m_PreviewAfter.Name := 'm_PreviewAfter';
m_PreviewAfter.Parent := ts_Preview;
m_PreviewAfter.Left := 248;
m_PreviewAfter.Top := 16;
m_PreviewAfter.Width := 214;
m_PreviewAfter.Height := 337;
m_PreviewAfter.Anchors := [akLeft, akTop, akRight];
m_PreviewAfter.TabOrder := 1;
m_PreviewAfter.Highlighter := gxpPas;
TWinControl_ActivateDropFiles(m_PreviewBefore, m_PreviewFileDropped);
TWinControl_ActivateDropFiles(m_PreviewAfter, m_PreviewFileDropped);
grid_Spacing.DefaultRowHeight := grid_Spacing.Canvas.TextHeight('Mg') + 4;
lb_Precedence.Items.AddObject(str_PrecedenceDirective, Pointer(cpDirective));
lb_Precedence.Items.AddObject(str_PrecedenceIniFile, Pointer(cpIniFile));
lb_Precedence.Items.AddObject(str_PrecedenceMySettings, Pointer(cpMyConfig));
end;
destructor TfmCodeFormatterConfig.Destroy;
begin
FCapitalization.Free;
inherited;
end;
procedure TfmCodeFormatterConfig.HandleCaptitalizationFileDropped(_Sender: TObject; _Files: TStrings);
begin
ed_CapitalizationFile.Text := _Files[0];
end;
procedure TfmCodeFormatterConfig.m_PreviewFileDropped(_Sender: TObject; _Files: TStrings);
begin
m_PreviewBefore.LoadFromFile(_Files[0]);
UpdatePreview;
end;
function TfmCodeFormatterConfig.GetSpaceItem(_Idx: Integer): TSpaceSet;
var
s: string;
begin
s := grid_Spacing.Cells[2, _Idx];
Result := spNone;
if s = str_Before then
Result := [spBefore]
else if s = str_after then
Result := [spAfter]
else if s = str_BeforeAfter then
Result := spBoth;
end;
procedure TfmCodeFormatterConfig.lb_PrecedenceClick(Sender: TObject);
var
Idx: Integer;
begin
Idx := lb_Precedence.ItemIndex;
b_PrecedenceUp.Enabled := (Idx <> 0);
b_PrecedenceDown.Enabled := (Idx <> 2);
end;
procedure TfmCodeFormatterConfig.b_PrecedenceUpClick(Sender: TObject);
var
Idx: Integer;
begin
Idx := lb_Precedence.ItemIndex;
if Idx = 0 then
Exit;
lb_Precedence.Items.Exchange(Idx, Idx - 1);
lb_PrecedenceClick(lb_Precedence);
end;
procedure TfmCodeFormatterConfig.b_PrecedenceDownClick(Sender: TObject);
var
Idx: Integer;
begin
Idx := lb_Precedence.ItemIndex;
if Idx = 2 then
Exit;
lb_Precedence.Items.Exchange(Idx, Idx + 1);
lb_PrecedenceClick(lb_Precedence);
end;
procedure TfmCodeFormatterConfig.AddSpaceRow(_RowNo: Integer; const _StrCol1, _StrCol2: string;
_Space: TSpaceSet);
procedure SetColText(_Col: Integer; const _s: string; _Offset: Integer = 4);
var
w: Integer;
begin
grid_Spacing.Cells[_Col, _RowNo] := _s;
w := grid_Spacing.Canvas.TextWidth(_s) + _Offset;
if grid_Spacing.ColWidths[_Col] < w then
grid_Spacing.ColWidths[_Col] := w;
end;
begin
SetColText(0, _StrCol1);
SetColText(1, _StrCol2);
if _Space = spNone then
SetColText(2, str_None, 40)
else if _Space = spBoth then
SetColText(2, str_BeforeAfter, 40)
else if spBefore in _Space then
SetColText(2, str_Before, 40)
else
SetColText(2, str_after, 40);
end;
function GetModuleDir: string;
begin
Result := ExtractFilePath(GetModuleName(HInstance));
end;
procedure TfmCodeFormatterConfig.FillPreview;
var
s: string;
begin
s := IncludeTrailingPathDelimiter(GetModuleDir) + 'preview.pas';
if FileExists(s) then begin
m_PreviewBefore.Clear;
m_PreviewBefore.LoadFromFile(s);
end
end;
procedure TfmCodeFormatterConfig.FormToEngineSettings(var _Settings: TCodeFormatterEngineSettings);
begin
_Settings := BorlandDefaults;
_Settings.SpacePerIndent := ud_SpacePerIndent.Position;
_Settings.IndentBegin := chk_IndentBegin.Checked;
_Settings.IndentComments := chk_IndentComments.Checked;
_Settings.IndentCompDirectives := chk_IndentCompDirectives.Checked;
_Settings.IndentTry := chk_IndentTry.Checked;
_Settings.IndentTryElse := chk_IndentTryElse.Checked;
_Settings.IndentCaseElse := chk_IndentCaseElse.Checked;
_Settings.UpperCompDirectives := chk_UpperCompDirectives.Checked;
_Settings.UpperNumbers := chk_UpperNumbers.Checked;
_Settings.ReservedCase := TCase(cmb_ReservedCase.ItemIndex);
_Settings.StandDirectivesCase := TCase(cmb_StandDirectives.ItemIndex);
_Settings.IdentifiersCase := TCase(cmb_IdentifiersCase.ItemIndex);
_Settings.BlankProc := chk_BlankProc.Checked;
_Settings.BlankSubProc := chk_BlankSubProc.Checked;
_Settings.RemoveDoubleBlank := chk_RemoveDoubleBlank.Checked;
_Settings.WrapLines := chk_WrapLines.Checked;
_Settings.WrapPosition := ud_WrapPosition.Position;
_Settings.AlignComments := chk_AlignComments.Checked;
_Settings.AlignCommentPos := ud_AlignCommentPos.Position;
_Settings.AlignVar := chk_AlignVar.Checked;
_Settings.AlignVarPos := ud_AlignVarPos.Position;
_Settings.SpaceEqualOper := GetSpaceItem(1);
_Settings.SpaceOperators := GetSpaceItem(2);
_Settings.SpaceColon := GetSpaceItem(3);
_Settings.SpaceSemiColon := GetSpaceItem(4);
_Settings.SpaceComma := GetSpaceItem(5);
_Settings.SpaceLeftBr := GetSpaceItem(6);
_Settings.SpaceRightBr := GetSpaceItem(7);
_Settings.SpaceLeftHook := GetSpaceItem(8);
_Settings.SpaceRightHook := GetSpaceItem(9);
_Settings.FeedAfterThen := chk_FeedAfterThen.Checked;
_Settings.ExceptSingle := chk_ExceptSingle.Checked;
_Settings.FeedEachUnit := chk_FeedEachUnit.Checked;
_Settings.NoFeedBeforeThen := chk_NoFeedBeforeThen.Checked;
_Settings.FeedAfterVar := chk_FeedAfterVar.Checked;
_Settings.FeedElseIf := chk_FeedElseIf.Checked;
_Settings.NoIndentElseIf := chk_NoIndentElseIf.Checked;
_Settings.FeedBeforeEnd := chk_FeedBeforeEnd.Checked;
_Settings.FeedAfterSemiColon := chk_FeedAfterSemiColon.Checked;
_Settings.FillNewWords := IntToCapfileMode(rg_Capitalization.ItemIndex);
_Settings.StartCommentOut := Trim(ed_StartComment.Text);
_Settings.EndCommentOut := Trim(ed_EndCommentOut.Text);
_Settings.FeedRoundBegin := TFeedBegin(cmb_FeedRoundBegin.ItemIndex);
_Settings.FeedRoundTry := TFeedBegin(cmb_FeedRoundTry.ItemIndex);
end;
procedure TfmCodeFormatterConfig.FormToSettings(_Settings: TCodeFormatterSettings);
var
Settings: TCodeFormatterEngineSettings;
i: Integer;
Idx: Integer;
begin
_Settings.UseCapitalizationFile := rb_CapitalizationInFile.Checked;
_Settings.CapitalizationFile := ed_CapitalizationFile.Text;
_Settings.CapNames.Assign(FCapitalization);
for i := Low(TOneToThree) to High(TOneToThree) do begin
Idx := i - Low(TOneToThree);
_Settings.ConfigPrecedence[i] := TConfigPrecedenceEnum(lb_Precedence.Items.Objects[Idx])
end;
FormToEngineSettings(Settings);
_Settings.Settings := Settings;
end;
procedure TfmCodeFormatterConfig.EngineSettingsToForm(const _EngineSettings: TCodeFormatterEngineSettings);
resourcestring
str_Description = 'Description';
str_Operators = 'Operators';
str_Spacing = 'Spacing';
str_Equals = 'Equals';
str_MathOperators = 'Math. operators';
str_MathOperatorsExample = '< > = + - / * etc.';
str_Colon = 'Colon';
str_SemiColon = 'Semicolon';
str_Comma = 'Comma';
str_LeftParenthesis = 'Left parenthesis';
str_RightParenthesis = 'Right parenthesis';
str_LeftBracket = 'Left bracket';
str_RightBracket = 'Right bracket';
begin
ud_SpacePerIndent.Position := _EngineSettings.SpacePerIndent;
chk_IndentBegin.Checked := _EngineSettings.IndentBegin;
chk_IndentComments.Checked := _EngineSettings.IndentComments;
chk_IndentCompDirectives.Checked := _EngineSettings.IndentCompDirectives;
chk_IndentTry.Checked := _EngineSettings.IndentTry;
chk_IndentTryElse.Checked := _EngineSettings.IndentTryElse;
chk_IndentCaseElse.Checked := _EngineSettings.IndentCaseElse;
chk_UpperCompDirectives.Checked := _EngineSettings.UpperCompDirectives;
chk_UpperNumbers.Checked := _EngineSettings.UpperNumbers;
cmb_ReservedCase.ItemIndex := Ord(_EngineSettings.ReservedCase);
cmb_StandDirectives.ItemIndex := Ord(_EngineSettings.StandDirectivesCase);
cmb_IdentifiersCase.ItemIndex := Ord(_EngineSettings.IdentifiersCase);
chk_BlankProc.Checked := _EngineSettings.BlankProc;
chk_BlankSubProc.Checked := _EngineSettings.BlankSubProc;
chk_RemoveDoubleBlank.Checked := _EngineSettings.RemoveDoubleBlank;
with grid_Spacing do begin
RowCount := 10;
Cells[0, 0] := str_Description;
Cells[1, 0] := str_Operators;
Cells[2, 0] := str_Spacing;
AddSpaceRow(1, str_Equals, ':=', _EngineSettings.SpaceEqualOper);
AddSpaceRow(2, str_MathOperators, str_MathOperatorsExample,
_EngineSettings.SpaceOperators);
AddSpaceRow(3, str_Colon, ':', _EngineSettings.SpaceColon);
AddSpaceRow(4, str_SemiColon, ';', _EngineSettings.SpaceSemiColon);
AddSpaceRow(5, str_Comma, ',', _EngineSettings.SpaceComma);
AddSpaceRow(6, str_LeftParenthesis, '(', _EngineSettings.SpaceLeftBr);
AddSpaceRow(7, str_RightParenthesis, ')', _EngineSettings.SpaceRightBr);
AddSpaceRow(8, str_LeftBracket, '[', _EngineSettings.SpaceLeftHook);
AddSpaceRow(9, str_RightBracket, ']', _EngineSettings.SpaceRightHook);
end;
chk_FeedAfterSemiColon.Checked := _EngineSettings.FeedAfterSemiColon;
chk_FeedEachUnit.Checked := _EngineSettings.FeedEachUnit;
chk_FeedAfterThen.Checked := _EngineSettings.FeedAfterThen;
chk_ExceptSingle.Checked := _EngineSettings.ExceptSingle;
chk_NoFeedBeforeThen.Checked := _EngineSettings.NoFeedBeforeThen;
chk_FeedAfterVar.Checked := _EngineSettings.FeedAfterVar;
chk_FeedElseIf.Checked := _EngineSettings.FeedElseIf;
chk_NoIndentElseIf.Checked := _EngineSettings.NoIndentElseIf;
chk_FeedBeforeEnd.Checked := _EngineSettings.FeedBeforeEnd;
chk_WrapLines.Checked := _EngineSettings.WrapLines;
ud_WrapPosition.Position := _EngineSettings.WrapPosition;
chk_AlignComments.Checked := _EngineSettings.AlignComments;
ud_AlignCommentPos.Position := _EngineSettings.AlignCommentPos;
chk_AlignVar.Checked := _EngineSettings.AlignVar;
ud_AlignVarPos.Position := _EngineSettings.AlignVarPos;
rg_Capitalization.ItemIndex := CapfileModeToInt(_EngineSettings.FillNewWords);
ed_StartComment.Text := string(_EngineSettings.StartCommentOut);
ed_EndCommentOut.Text := string(_EngineSettings.EndCommentOut);
cmb_FeedRoundBegin.ItemIndex := Integer(_EngineSettings.FeedRoundBegin);
cmb_FeedRoundTry.ItemIndex := Integer(_EngineSettings.FeedRoundTry);
ud_SpacePerIndent.Associate := ed_SpacePerIndent;
ud_WrapPosition.Associate := ed_WrapPosition;
ud_AlignCommentPos.Associate := ed_AlignCommentPos;
ud_AlignVarPos.Associate := ed_AlignVarPos;
chk_FeedAfterThenClick(nil)
end;
procedure TfmCodeFormatterConfig.SettingsToForm(const _Settings: TCodeFormatterSettings);
procedure AddPrecedenceSetting(_cp: TConfigPrecedenceEnum);
begin
case _cp of
cpDirective: lb_Precedence.Items.AddObject(str_PrecedenceDirective, Pointer(cpDirective));
cpIniFile: lb_Precedence.Items.AddObject(str_PrecedenceIniFile, Pointer(cpIniFile));
cpMyConfig: lb_Precedence.Items.AddObject(str_PrecedenceMySettings, Pointer(cpMyConfig));
end;
end;
var
i: Integer;
cp: TConfigPrecedenceEnum;
PrecedenceSet: set of TConfigPrecedenceEnum;
begin
rb_CapitalizationInFile.Checked := _Settings.UseCapitalizationFile;
ed_CapitalizationFile.Text := string(_Settings.CapitalizationFile);
FCapitalization.Assign(_Settings.CapNames);
lb_Precedence.Items.Clear;
// the set is used to prevent manipulated settings from crashing the program
PrecedenceSet := [cpDirective, cpIniFile, cpMyConfig];
for i := Low(TOneToThree) to High(TOneToThree) do begin
if _Settings.ConfigPrecedence[i] in PrecedenceSet then begin
AddPrecedenceSetting(_Settings.ConfigPrecedence[i]);
Exclude(PrecedenceSet, _Settings.ConfigPrecedence[i]);
end;
end;
for cp := Low(TConfigPrecedenceEnum) to High(TConfigPrecedenceEnum) do begin
if cp in PrecedenceSet then
AddPrecedenceSetting(cp);
end;
EngineSettingsToForm(_Settings.Settings);
end;
procedure TfmCodeFormatterConfig.SetDefault(_Which: string);
resourcestring
str_CouldNotReadS = 'Could not read default configuration %s.';
var
Defaults: TCodeFormatterSettings;
begin
_Which := StringReplace(_Which, '&', '', [rfReplaceAll]);
grid_Spacing.EditorMode := False;
Defaults := TCodeFormatterSettings.Create;
try
if _Which <> str_DefaultSettings then begin
if not TCodeFormatterConfigHandler.GetDefaultConfig(_Which, Defaults) then begin
MessageDlg(Format(str_CouldNotReadS, [_Which]), mtError, [mbOK], 0);
Exit;
end;
end;
SettingsToForm(Defaults);
finally
Defaults.Free;
end;
if pc_Main.ActivePage = ts_Preview then
ts_PreviewShow(nil);
end;
procedure TfmCodeFormatterConfig.b_CapitalizationSelectClick(Sender: TObject);
var
s: string;
begin
od_CapitalizationFile.FileName := ed_CapitalizationFile.Text;
if not od_CapitalizationFile.Execute then
Exit;
s := od_CapitalizationFile.FileName;
if FileExists(s) then begin
if FCapitalization.Count > 0 then begin
if mrYes <> MessageDlg(
'Your current capitalization list is not empty and the file already exists.'#13#10
+ 'Do you want to discard your list and load the selected file instead?',
mtWarning, [mbYes, mbCancel], 0) then
Exit;
end;
FCapitalization.LoadFromFile(s);
end else begin
if FCapitalization.Count > 0 then begin
FCapitalization.SaveToFile(s);
end;
end;
ed_CapitalizationFile.Text := s;
end;
procedure TfmCodeFormatterConfig.b_HelpClick(Sender: TObject);
var
HlpFile: string;
begin
{ TODO : replace with GExperts help (and add contents of DelFor help to GExperts help) }
HlpFile := GetModuleDir + 'delfor.hlp';
WinHelp(0, PChar(HlpFile), HELP_KEY, Integer(pc_Main.ActivePage.Caption));
end;
procedure TfmCodeFormatterConfig.b_EditCapitalizationClick(Sender: TObject);
var
FileEditDlg: TfmCodeFormatterEditCapitalization;
Cur: TCursor;
begin
Cur := Screen.Cursor;
Screen.Cursor := crHourGlass;
FileEditDlg := TfmCodeFormatterEditCapitalization.Create(Self);
try
FileEditDlg.ListToForm(FCapitalization);
Screen.Cursor := Cur;
if mrOk = FileEditDlg.ShowModal then begin
if FileEditDlg.IsChanged then
FileEditDlg.FormToList(FCapitalization);
end;
finally
Screen.Cursor := Cur;
FileEditDlg.Free;
end;
end;
procedure TfmCodeFormatterConfig.ts_PreviewShow(Sender: TObject);
begin
UpdatePreview;
end;
procedure TfmCodeFormatterConfig.HandleOnStatusChange(Sender: TObject; Changes: TSynStatusChanges);
begin
if m_PreviewAfter.TopLine <> m_PreviewBefore.TopLine then
m_PreviewAfter.TopLine := m_PreviewBefore.TopLine;
end;
procedure TfmCodeFormatterConfig.rb_CapitalizationInFileClick(Sender: TObject);
begin
ed_CapitalizationFile.Enabled := True;
b_CapitalizationSelect.Enabled := True;
end;
procedure TfmCodeFormatterConfig.rb_CapitalizationInRegistryClick(Sender: TObject);
begin
ed_CapitalizationFile.Enabled := False;
b_CapitalizationSelect.Enabled := False;
end;
procedure TfmCodeFormatterConfig.FormShow(Sender: TObject);
begin
FillPreview;
pc_Main.ActivePage := ts_Indent;
end;
procedure TfmCodeFormatterConfig.chk_FeedAfterThenClick(Sender: TObject);
begin
chk_ExceptSingle.Enabled := chk_FeedAfterThen.Checked;
end;
procedure TfmCodeFormatterConfig.ts_PreviewResize(Sender: TObject);
var
w: Integer;
begin
w := (ts_Preview.ClientWidth - 16) div 2;
m_PreviewBefore.Left := 8;
l_Before.Left := 8;
m_PreviewBefore.Width := w;
m_PreviewBefore.Height := ts_Preview.ClientHeight - m_PreviewBefore.Top - 8;
l_After.Left := w + 9;
m_PreviewAfter.Left := w + 9;
m_PreviewAfter.Width := w;
m_PreviewAfter.Height := ts_Preview.ClientHeight - m_PreviewAfter.Top - 8;
end;
procedure TfmCodeFormatterConfig.b_ToolsClick(Sender: TObject);
var
Point: TPoint;
begin
Point.X := b_Tools.Width;
Point.Y := 0;
Point := b_Tools.ClientToScreen(Point);
pm_Extra.Popup(Point.X, Point.Y);
end;
procedure TfmCodeFormatterConfig.mi_ResetToDefaultClick(Sender: TObject);
begin
SetDefault(TMenuItem(Sender).Caption);
end;
procedure TfmCodeFormatterConfig.mi_ImportClick(Sender: TObject);
var
Settings: TCodeFormatterSettings;
begin
grid_Spacing.EditorMode := False;
od_Import.FileName := 'DelForExOptions.ini';
if not od_Import.Execute then
Exit;
Settings := TCodeFormatterSettings.Create;
try
TCodeFormatterConfigHandler.ImportFromFile(od_Import.FileName, Settings);
SettingsToForm(Settings);
finally
Settings.Free;
end;
if pc_Main.ActivePage = ts_Preview then
ts_PreviewShow(nil);
end;
procedure TfmCodeFormatterConfig.mi_ExportClick(Sender: TObject);
var
Settings: TCodeFormatterSettings;
begin
grid_Spacing.EditorMode := False;
sd_Export.FileName := 'DelForExOptions.ini';
if not sd_Export.Execute then
Exit;
Settings := TCodeFormatterSettings.Create;
try
FormToSettings(Settings);
TCodeFormatterConfigHandler.ExportToFile(sd_Export.FileName, Settings);
finally
Settings.Free;
end;
end;
class function TfmCodeFormatterConfig.Execute(_Settings: TCodeFormatterSettings): TModalResult;
var
frm: TfmCodeFormatterConfig;
begin
frm := TfmCodeFormatterConfig.Create(nil);
try
frm.HelpFile := 'delfor.hlp';
frm.SettingsToForm(_Settings);
Result := frm.ShowModal;
if Result = mrOk then
frm.FormToSettings(_Settings);
finally
frm.Free;
end;
end;
procedure TfmCodeFormatterConfig.UpdatePreview;
var
sl: TGXUnicodeStringList;
Formatter: TCodeFormatterEngine;
begin
sl := nil;
Formatter := TCodeFormatterEngine.Create;
try
// this temporary string list is necessary to prevent an infinite loop (whose reason I don't really understand :-( )
sl := TGXUnicodeStringList.Create;
m_PreviewBefore.GetLines(sl);
FormToSettings(Formatter.Settings);
Formatter.Execute(sl);
m_PreviewAfter.SetLines(sl);
finally
Formatter.Free;
sl.Free;
end;
end;
{ TStringGrid }
constructor TStringGrid.Create(_Owner: TComponent);
begin
inherited;
FSpacingOptions := TStringList.Create;
FSpacingOptions.Add(str_None);
FSpacingOptions.Add(str_Before);
FSpacingOptions.Add(str_after);
FSpacingOptions.Add(str_BeforeAfter);
end;
function TStringGrid.GetEditStyle(_Col, _Row: Integer): TEditStyle;
begin
if Col = 2 then
Result := esPickList
else
Result := esSimple;
end;
function TStringGrid.CreateEditor: TInplaceEdit;
begin
Result := TInplaceEditList.Create(Self);
(Result as TInplaceEditList).OnGetPickListitems := OnGetSpacingOptions;
(Result as TInplaceEditList).DropDownRows := 15;
end;
procedure TStringGrid.OnGetSpacingOptions(_Col, _Row: Integer; _Items: TStrings);
begin
_Items.Assign(FSpacingOptions);
end;
destructor TStringGrid.Destroy;
begin
FSpacingOptions.Free;
inherited;
end;
function TStringGrid.CanEditModify: Boolean;
begin
Result := False;
end;
function TStringGrid.CanEditShow: Boolean;
begin
Result := (Col = 2);
end;
end.
|
unit IGraphicObject_primitives;
interface
uses IGraphicObject_commands,streaming_class_lib,types,classes,graphics;
type
TScreenCoord = 0..9999; //тут главное - правильный размер окошечка
TPointGraphicObject = class (TStreamingClass, IGraphicObject)
protected
fx,fy: Integer; //кто знает, с какими размерами мы работаем?
//иначе с Geofrac конкретные проблемы
public
function Rect: TRect; virtual; //реальные размеры
function SymbolRect: TRect; virtual; //как оно отобр. на экране
function DistanceSquaredFromPoint(x,y: Integer): Real; virtual;
function DistanceTo(ax,ay: Integer): Real; virtual;
procedure Move(dx,dy: Integer); virtual;
procedure Resize(dx1,dy1,dx2,dy2: Integer;Corrector: TGraphicResizeCorrector=nil); virtual;
procedure Rotate(alpha: Real; Xcenter,Ycenter: Integer; corrector: TGraphicResizeCorrector=nil); virtual;
function ResizableByX: boolean; virtual;
function ResizableByY: boolean; virtual;
function isOkToPaste: boolean; virtual;
function Implementor: TComponent; virtual;
procedure Draw(canvas: TCanvas); virtual;
end;
TLineGraphicObject = class (TStreamingClass, IGraphicObject)
protected
fc: array [0..3] of Integer; //0:x1, 1:y1, 2: x2, 3:y2
//не знаем масштабов исп. чисел
public
function Rect: TRect; virtual; //реальные размеры
function SymbolRect: TRect; virtual; //как оно отобр. на экране
function DistanceSquaredFromPoint(x,y: Integer): Real; virtual;
function DistanceTo(ax,ay: Integer): Real;
procedure Move(dx,dy: Integer); virtual;
procedure Resize(dx1,dy1,dx2,dy2: Integer;Corrector: TGraphicResizeCorrector=nil); virtual;
procedure Rotate(alpha: Real; Xcenter,Ycenter: Integer; corrector: TGraphicResizeCorrector=nil); virtual;
function ResizableByX: boolean; virtual;
function ResizableByY: boolean; virtual;
function isOkToPaste: boolean; virtual;
function Implementor: TComponent; virtual;
procedure Draw(canvas: TCanvas); virtual;
end;
implementation
(*
TPointGraphicObject
*)
function TPointGraphicObject.Rect: TRect;
begin
Result:=types.Rect(fx,fy,fx,fy);
end;
function TPointGraphicObject.SymbolRect: TRect;
begin
Result:=types.Rect(fx-5,fy-5,fx+5,fy+5); //дальнейшее сделают производные классы, если захотят
end;
function TPointGraphicObject.DistanceSquaredFromPoint(x,y: Integer): real;
begin
Result:=Sqr(x-fx)+Sqr(y-fy);
end;
function TPointGraphicObject.DistanceTo(ax,ay: Integer): Real;
begin
Result:=Sqrt(DistanceSquaredFromPoint(ax,ay));
end;
procedure TPointGraphicObject.Draw(canvas: TCanvas);
begin
canvas.FillRect(types.Rect(fx-5,fy-5,fx+5,fy+5)); //почему б и нет?
end;
function TPointGraphicObject.Implementor: TComponent;
begin
Result:=self;
end;
function TPointGraphicObject.isOkToPaste: Boolean;
begin
Result:=true; //производные классы могут не согласиться, их право
end;
procedure TPointGraphicObject.Move(dx,dy: Integer);
begin
inc(fx,dx);
inc(fy,dy);
end;
function TPointGraphicObject.ResizableByX: Boolean;
begin
Result:=false;
end;
function TPointGraphicObject.ResizableByY: Boolean;
begin
Result:=false;
end;
procedure TPointGraphicObject.Resize(dx1,dy1,dx2,dy2: Integer; corrector: TGraphicResizeCorrector=nil);
begin
//никаких хитростей, действие обратимо
fx:=fx+(dx1+dx2) div 2;
fy:=fy+(dy1+dy2) div 2;
end;
procedure TPointGraphicObject.Rotate(alpha: Real; Xcenter,YCenter: Integer; corrector: TGraphicResizeCorrector=nil);
var dx,dy,bux,buy: Integer;
si,co: Real;
corRect: TRect;
begin
dx:=fx-Xcenter;
dy:=fy-Ycenter;
bux:=fx;
buy:=fy;
si:=sin(alpha);
co:=cos(alpha);
fx:=Xcenter+Round(dx*co-dy*si);
fy:=Ycenter+Round(dx*si+dy*co);
if Assigned(corrector) then
if corrector.reverse then begin
corRect:=corrector.Pop;
inc(fx,corRect.Left);
inc(fy,corRect.Top);
end
else begin
dx:=fx-Xcenter;
dy:=fy-Ycenter;
corRect.Left:=Xcenter+Round(dx*co+dy*si);
corRect.Top:=Ycenter+Round(-dx*si+dy*co);
corRect.Left:=bux-correct.Left;
corRect.Top:=buy-correct.Top;
corRect.Right:=0;
corRect.Bottom:=0;
corrector.Push(corRect);
end;
end;
(*
TLineGraphicObject
*)
function TLineGraphicObject.Rect: TRect;
begin
//что важно, должно быть top<bottom и left<right
Result:=types.Rect(fc[0],fc[1],fc[2],fc[3]);
if Result.Left>result.Right then swapIntegers(Result.left,Result.right);
if Result.Top>result.Bottom then swapIntegers(Result.Top,Result.bottom);
end;
function TLineGraphicObject.SymbolRect: TRect;
begin
Result:=Rect; //дальнейшее сделают производные классы, если захотят
end;
function TLineGraphicObject.DistanceSquaredFromPoint(x,y: Integer): Real;
var ax,ay,bx,by,cx,cy,k: Real;
begin
ax:=fc[2]-fc[0];
ay:=fc[3]-fc[1];
bx:=x-fc[0];
by:=y-fc[1];
cx:=fc[2]-x;
cy:=fc[3]-y;
if (ax=0) and (ay=0) then Result:=bx*bx+by*by
else begin
k:=(ax*bx+ay*by)/(ax*ax+ay*ay);
if k<0 then Result:=bx*bx+by*by
else if k>1 then Result:=cx*cx+cy*cy
else begin
bx:=bx-k*ax;
by:=by-k*ay;
Result:=bx*bx+by*by;
end;
end;
end;
function TLineGraphicObject.DistanceTo(ax,ay: Integer): Real;
begin
Result:=sqrt(DistanceSquaredFromPoint(ax,ay));
end;
procedure TLineGraphicObject.Move(dx,dy: Integer);
begin
inc(fc[0],dx);
inc(fc[1],dy);
inc(fc[2],dx);
inc(fc[3],dy);
end;
procedure TLineGraphicObject.Resize(dx1,dy1,dx2,dy2: Integer;Corrector: TGraphicResizeCorrector=nil);
var infrect: TRect;
mirrx,mirry: boolean;
begin
mirrx:=(fc[0]>fc[2]);
if mirrx then SwapIntegers(dx1,dx2);
mirry:=(fc[1]>fc[3]);
if mirry then SwapIntegers(dy1,dy2);
if Assigned(corrector) and corrector.reverse and ((fc[0]=fc[2]) or (fc[1]=fc[3])) then begin
infrect:=corrector.Pop;
if infrect.Left=1 then SwapIntegers(dx1,dx2);
if infrect.Top=1 then SwapIntegers(dy1,dy2);
end;
inc(fc[0],dx1);
inc(fc[1],dy1);
inc(fc[2],dx2);
inc(fc[3],dy2);
if Assigned(corrector) and (not corrector.reverse) and ((fc[0]=fc[2]) or (fc[1]=fc[3])) then begin
infrect:=Types.Rect(0,0,0,0);
if (fc[0]=fc[2]) and mirrx then infrect.Left:=1;
if (fc[1]=fc[3]) and mirry then infrect.Top:=1;
corrector.Push(infrect);
end;
end;
procedure TLineGraphicObject.Rotate(alpha: Real; Xcenter,Ycenter: Integer; corrector: TGraphicResizeCorrector=nil);
var dx1,dy1,dx2,dy2: Integer;
bux1,buy1,bux2,buy2: Integer;
si,co: Real;
corRect: TRect;
begin
dx1:=fc[0]-XCenter;
dy1:=fc[1]-YCenter;
dx2:=fc[2]-XCenter;
dy2:=fc[3]-YCenter;
bux1:=fc[0];
buy1:=fc[1];
bux2:=fc[2];
buy2:=fc[3];
si:=sin(alpha);
co:=cos(alpha);
fc[0]:=XCenter+Round(dx1*co-dy1*si);
fc[1]:=YCenter+Round(dx1*si+dy1*co);
fc[2]:=XCenter+Round(dx2*co-dy2*si);
fc[3]:=YCenter+Round(dx2*si+dy2*co);
if Assigned(corrector) then
if corrector.reverse then begin
corRect:=corrector.Pop;
inc(fc[0],corRect.Left);
inc(fc[1],corRect.Top);
inc(fc[2],corRect.Right);
inc(fc[3],corRect.Bottom);
end
else begin
dx1:=fc[0]-XCenter;
dy1:=fc[1]-YCenter;
dx2:=fc[2]-XCenter;
dy2:=fc[3]-YCenter;
alpha:=-alpha;
si:=sin(alpha);
co:=cos(alpha);
corRect.Left:=XCenter+Round(dx1*co-dy1*si);
corRect.Top:=YCenter+Round(dx1*si+dy1*co);
corRect.Right:=XCenter+Round(dx2*co-dy2*si);
corRect.Bottom:=YCenter+Round(dx2*si+dy2*co);
corRect.Left:=bux1-corRect.Left;
corRect.Top:=buy1-corRect.Top;
corRect.Right:=bux2-corRect.Right;
corRect.Bottom:=buy2-corRect.Bottom;
corrector.Push(corRect);
end;
end;
function TLineGraphicObject.ResizableByX: Boolean;
begin
Result:=(fc[0]<>fc[2]);
end;
function TLineGraphicObject.ResizableByY: Boolean;
begin
Result:=(fc[1]<>fc[3]);
end;
function TLineGraphicObject.isOkToPaste: Boolean;
begin
Result:=true; //производные классы наверняка решат по-другому
end;
function TLineGraphicObject.Implementor: TComponent;
begin
Result:=self;
end;
procedure TLineGraphicObject.Draw(canvas: TCanvas);
var doc: TDocumentWithImage;
begin
doc:=FindOwner as TDocumentWithImage;
//весьма условно - линия с теми параметрами pen, какие сидели по умолч.
//в системе коорд., в которой заданы fx1,fy1 и пр.
with Canvas do begin
MoveTo(doc.XVal2Pix(fc[0]),doc.YVal2Pix(fc[1]));
LineTo(doc.XVal2Pix(fc[2]),doc.YVal2Pix(fc[3]));
end;
end;
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.0 11/28/2004 9:20:22 PM JPMugaas
Preliminary support for NCSA Telnet's FTP Server for MacIntosh.
}
unit IdFTPListParseNCSAForMACOS;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase, IdFTPListTypes;
{
NCSA Telnet for MacIntosh's FTP Server only lists the filenames followed by a /
if they are directories instead of files.
About the only way I can see to detect this server type is to use the greeting banner:
"Macintosh Resident FTP server, ready" or maybe, the SYST reply "MACOS NCSA".
Unlike many system types, spaces are permitted in filenames.
This also may work on an old Intercon TCP/Connect for MacIntosh. I only found that
by looking at some source-code in LibWWW which has some contributions from Dartmouth College.
The code is at:
http://dev.w3.org/cvsweb/libwww/Library/src/HTFTP.c?rev=1.109&content-type=text/x-cvsweb-markup
http://dev.w3.org/cvsweb/libwww/Library/src/HTFTPDir.c?rev=2.18&content-type=text/x-cvsweb-markup
and
http://web.mit.edu/afs/dev.mit.edu/project/andydev/src/andrew-8.0/WWW/Library/Implementation/HTFTP.c
}
type
TIdNCSAforMACOSFTPListItem = class(TIdMinimalFTPListItem);
TIdFTPLPNCSAforMACOS = class(TIdFTPLPNList)
protected
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParseNCSAForMACOS"'*)
implementation
uses
IdException,
IdGlobal;
{ TIdFTPLPNCSAforMACOS }
class function TIdFTPLPNCSAforMACOS.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
begin
// From Google: http://groups.google.com/groups?q=MAC-OS+TCP/Connect&hl=en&lr=&selm=881%40lts.UUCP&rnum=4
//Intercon's MAC-OS reports "MAC-OS TCP/Connect for the Macintosh Version x.x"
//but LibWWW
//http://dev.w3.org/cvsweb/libwww/Library/src/HTFTP.c?rev=1.109&content-type=text/x-cvsweb-markup
//"MAC-OS TCP/ConnectII"
Result := (ASysDescript = 'MAC NCSA') or
TextStartsWith(ASysDescript, ' MAC-OS TCP/Connect');
end;
class function TIdFTPLPNCSAforMACOS.GetIdent: String;
begin
Result := 'NCSA for MACOS'; {do not localize}
end;
class function TIdFTPLPNCSAforMACOS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdNCSAforMACOSFTPListItem.Create(AOwner);
end;
class function TIdFTPLPNCSAforMACOS.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
begin
Result := True;
try
if CharIsInSet(AItem.Data, Length(AItem.Data), '/\') then
begin
AItem.ItemType := ditDirectory;
AItem.FileName := Copy(AItem.Data, 1, Length(AItem.Data)-1);
end else
begin
AItem.ItemType := ditFile;
AItem.FileName := AItem.Data;
end;
except
Result := False;
end;
end;
initialization
RegisterFTPListParser(TIdFTPLPNCSAforMACOS);
finalization
UnRegisterFTPListParser(TIdFTPLPNCSAforMACOS);
end.
|
PROGRAM SarahRevere(INPUT, OUTPUT);
{Џечать сообщения о том как идут британцы, в зависимости
от того, первым во входе встречается ли 'land', 'sea'}
VAR
W1, W2, W3, W4: CHAR;
Looking, Land, Sea: BOOLEAN;
BEGIN {SarahRevere}
W1 := ' ';
W2 := ' ';
W3 := ' ';
W4 := ' ';
Looking := TRUE;
Land := FALSE;
Sea := FALSE;
WHILE Looking AND NOT (Land OR Sea) AND NOT EOLN
DO
BEGIN
W1 := W2;
W2 := W3;
W3 := W4;
READ(W4);
IF EOLN THEN Looking := FALSE;
Land := (W1 = 'l') AND (W2 = 'a') AND (W3 = 'n') AND (W4 = 'd');
Sea := (W1 = 's') AND (W2 = 'e') AND (W3 = 'a');
END;
IF Land
THEN
WRITE('The British are coming by land')
ELSE
IF Sea
THEN
WRITE('The British are coming by sea')
ELSE
WRITE('Sarah didn''t say');
WRITELN
END. {SarahRevere}
|
program StoryGen;
type
replacementPair = record
oldWord : string;
newWord : string;
end;
replacementPairArray = array of replacementPair;
var
replacementWords : replacementPairArray;
function fileExists(fromFileName : string) : boolean;
var
f : TEXT;
begin
(*$I-*)
assign(f, fromFileName);
Reset(f); //Creates error
if IOResult <> 0 then begin
fileExists := FALSE;
end else
fileExists := TRUE;
(*$I+*)
end;
function isDelimiter(character : string) : boolean;
begin
if(character = ' ') or (character = '.') or (character = '!') or (character = '?') then
isDelimiter := TRUE
else
isDelimiter := FALSE;
end;
function isEqual(oldWord, newWord : string) : boolean;
var
lengthOldWord : integer;
lengthNewWord : integer;
begin
lengthOldWord := length(oldWord);
lengthNewWord := length(newWord);
if(isDelimiter(oldWord[lengthOldWord])) then
delete(oldWord,lengthOldWord,1);
if oldWord = newWord then
isEqual := TRUE
else
isEqual := FALSE;
end;
function getAndRemoveFirstWord(var line : string) : string;
var
i : integer;
finished : boolean;
curWord : string;
begin
i := 1;
finished := FALSE;
curWord := '';
while (i <= length(line)) and (finished = FALSE) do begin
if(isDelimiter(line[i])) or (i = length(line)) then begin
if not(line[i] = ' ') then
curWord := curWord + line[i];
getAndRemoveFirstWord := curWord;
Delete(line,1,i);
finished := TRUE;
end else begin
curWord := curWord + line[i];
end;
inc(i);
end;
end;
procedure splitLine(line : string; var lineWords : array of string);
var
words : integer;
finished : boolean;
begin
words := 0;
finished := FALSE;
while (line <> '') and (finished = FALSE) do begin
lineWords[words] := getAndRemoveFirstWord(line);
if(words >= 2) then
finished := TRUE;
inc(words);
end;
end;
procedure copyText(fromFileName, toFileName : string);
var
inFile, outFile : TEXT;
line : string;
begin
assign(inFile, fromFileName);
assign(outFile, toFileName);
reset(inFile);
rewrite(outFile); // overwrite if file exists
while not eof(inFile) do begin
readln(inFile, line);
writeln(outFile, line);
end;
close(inFile);
close(outFile);
end;
procedure parseRepls(fromFileName : string);
var
inFile : TEXT;
line : string;
lineWords : array[0..1] of string;
i : integer;
begin
i := 0;
assign(inFile, fromFileName);
reset(inFile);
while not eof(inFile) do begin
setLength(replacementWords, length(replacementWords)+1);
readln(inFile, line);
splitLine(line, lineWords);
replacementWords[i].oldWord := lineWords[0];
replacementWords[i].newWord := lineWords[1];
inc(i);
end;
close(inFile);
end;
function replaceWordsInLine(line : string) : string;
var
curWord : string;
i : integer;
newLine : string;
finished : boolean;
endSymbol : string;
begin
newLine := '';
finished := FALSE;
while (line <> '') do begin
i := 0;
endSymbol := '';
finished := FALSE;
curWord := getAndRemoveFirstWord(line);
while(i < length(replacementWords)) and (finished = FALSE) do begin
if(isDelimiter(curWord[length(curWord)])) then begin
endSymbol := curWord[length(curWord)];
end;
if(isEqual(curWord,replacementWords[i].oldWord)) then begin
curWord := replacementWords[i].newWord + endSymbol;
finished := TRUE;
end;
inc(i);
end;
if not (curWord = ' ') then
newLine := newLine + curWord + ' ';
end;
replaceWordsInLine := newLine;
end;
procedure createNewStory(fromFileName, toFileName : string);
var
inFile, outFile : TEXT;
line : string;
newLine : string;
begin
assign(inFile, fromFileName);
assign(outFile, toFileName);
reset(inFile);
rewrite(outFile); // overwrite if file exists
while not eof(inFile) do begin
readln(inFile, line);
newLine := replaceWordsInLine(line);
writeln(outFile, newLine);
end;
close(inFile);
close(outFile);
end;
var
repls : string;
fromFileName, toFileName : string;
i : integer;
begin
fromFileName := '';
toFileName := '';
i := 0;
if not (paramCount = 3) then begin
writeLn('Usage: StoryGen REPLACEMENTFILE OLDSTORYFILE NEWSTORYFILE');
halt;
end;
repls := paramStr(1);
fromFileName := paramStr(2);
toFileName := paramStr(3);
if not fileExists(repls) then begin
writeln('Replacement file does not exist!');
halt;
end;
if not fileExists(fromFileName) then begin
writeln('Old story file does not exist!');
halt;
end;
parseRepls(repls);
createNewStory(fromFileName, toFileName);
writeLn('Wrote story just for you <3');
end.
|
unit GX_ComponentGrid;
{$I GX_CondDefine.inc}
interface
uses
GX_Experts, Classes, Controls, Forms, Grids, SortGrid,
StdCtrls, ComCtrls, ActnList, ToolWin, GX_BaseForm;
type
TfmComponentGrid = class(TfmBaseForm)
ToolBar: TToolBar;
tbnSave: TToolButton;
tbnSep1: TToolButton;
tbnHelp: TToolButton;
tbnSep2: TToolButton;
tbnPrint: TToolButton;
lblStart: TLabel;
lblSkipBy: TLabel;
tbnSep3: TToolButton;
tbnSep4: TToolButton;
Actions: TActionList;
actFileSave: TAction;
actHelpHelp: TAction;
actFilePrint: TAction;
tbnRenumber: TToolButton;
actFileRenumber: TAction;
edtStart: TEdit;
udStart: TUpDown;
edtSkipBy: TEdit;
udSkipBy: TUpDown;
procedure StringGridSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: string);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure StringGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
procedure StringGridResize(Sender: TObject);
procedure actFileSaveExecute(Sender: TObject);
procedure actFilePrintExecute(Sender: TObject);
procedure actFileRenumberExecute(Sender: TObject);
procedure actHelpHelpExecute(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
private
FComponentList: TInterfaceList;
FModified: Boolean;
StringGrid: TSortGrid;
procedure FillComponentList;
procedure ClearComponentList;
procedure PopulateGrid;
procedure PrintComponentGrid;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TGridExpert = class(TGX_Expert)
protected
procedure UpdateAction(Action: TCustomAction); override;
public
constructor Create; override;
function GetActionCaption: string; override;
class function GetName: string; override;
procedure Execute(Sender: TObject); override;
function HasConfigOptions: Boolean; override;
end;
implementation
{$R *.dfm}
uses
SysUtils, Graphics, Printers, Windows, Dialogs, ToolsAPI,
GX_Consts, GX_GxUtils, GX_GenericUtils, GX_OtaUtils, GX_SharedImages;
type
TGridProperty = record
PropertyName: string;
ColWidth: Integer;
end;
const // Do not localize.
FixedColumns = 2;
SHelpContextPropertyName = 'HelpContext';
STagPropertyName = 'Tag';
SHintPropertyName = 'Hint';
GridProperties: array[0..2] of TGridProperty = (
(
PropertyName: STagPropertyName;
ColWidth: 55;
),
(
PropertyName: SHelpContextPropertyName;
ColWidth: 75;
),
(
PropertyName: SHintPropertyName;
ColWidth: 150;
));
resourcestring
SNotAvailable = 'N/A';
procedure TfmComponentGrid.StringGridSetEditText(Sender: TObject; ACol,
ARow: Integer; const Value: string);
begin
FModified := True;
end;
procedure TfmComponentGrid.FormClose(Sender: TObject; var Action: TCloseAction);
resourcestring
SSaveChanges = 'Would you like to save your changes before closing?';
begin
if FModified then
if MessageDlg(SSaveChanges, mtConfirmation, [mbYes, mbNo], 0) = mrYes then
actFileSave.Execute;
end;
procedure TfmComponentGrid.StringGridSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
if (ACol > 2) and (StringGrid.Cells[ACol, ARow] = SNotAvailable) then
CanSelect := False;
end;
procedure TfmComponentGrid.PrintComponentGrid;
var
F: TextFile;
Page: Integer;
procedure PrintPageHeader(const ReportName: string);
begin
WriteLn(F, 'Page #' + IntToStr(Page) + #9#9#9#9 + ReportName);
WriteLn(F, ' ');
WriteLn(F, 'Component.Name'#9#9'Parent'#9#9'Tag'#9#9'Help ID');
end;
var
i: Integer;
ReportName: string;
begin
if not InputQuery('Report Name', 'Enter the name for this report', ReportName) then
Exit;
Printer.Canvas.Font.Size := 10;
Printer.Canvas.Font.Pitch := fpFixed;
Printer.Title := 'Component Help Context Report';
Printer.Orientation := poPortrait;
Page := -1;
AssignPrn(F);
Rewrite(F);
try
for i := 1 to StringGrid.RowCount -1 do
begin
if Page <> Printer.PageNumber then
begin
Page := Printer.PageNumber;
PrintPageHeader(ReportName);
end;
with StringGrid do
begin
WriteLn(F, GetPaddedString(Cells[0, i], 23) +
GetPaddedString(Cells[1, i], 15) +
GetPaddedString(Cells[2, i], 15) +
Cells[3, i]);
end;
end;
finally
System.CloseFile(F);
end;
end;
{ TGridExpert }
procedure TGridExpert.UpdateAction(Action: TCustomAction);
begin
Action.Enabled := GxOtaCurrentlyEditingForm;;
end;
procedure TGridExpert.Execute(Sender: TObject);
var
Dlg: TfmComponentGrid;
begin
Dlg := TfmComponentGrid.Create(nil);
try
SetFormIcon(Dlg);
Dlg.ShowModal;
finally
FreeAndNil(Dlg);
end;
end;
constructor TGridExpert.Create;
begin
inherited Create;
end;
function TGridExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Component &Grid...';
begin
Result := SMenuCaption;
end;
class function TGridExpert.GetName: string;
begin
Result := 'ComponentGrid';
end;
function TGridExpert.HasConfigOptions: Boolean;
begin
Result := False;
end;
procedure TfmComponentGrid.ClearComponentList;
begin
// Is anything necessary here?
end;
procedure TfmComponentGrid.FillComponentList;
procedure FillComponentListFromComponent(const AComponent: IOTAComponent);
var
i: Integer;
RetrievedComponent: IOTAComponent;
begin
Assert(Assigned(AComponent));
FComponentList.Add(AComponent);
for i := 0 to AComponent.GetComponentCount-1 do
begin
RetrievedComponent := AComponent.GetComponent(i);
FillComponentListFromComponent(RetrievedComponent);
end;
end;
var
FormEditor: IOTAFormEditor;
RootComponent: IOTAComponent;
begin
if not IsForm(GxOtaGetCurrentSourceFile) then
begin
MessageDlg(SOnlyForFormFiles, mtError, [mbOK], 0);
Exit;
end;
FormEditor := GxOtaGetCurrentFormEditor;
Assert(Assigned(FormEditor));
RootComponent := FormEditor.GetRootComponent;
Assert(Assigned(RootComponent));
FillComponentListFromComponent(RootComponent);
end;
procedure TfmComponentGrid.PopulateGrid;
function ComponentName(const AComponent: IOTAComponent): string;
begin
Result := GxOtaGetComponentName(AComponent);
if Result = '' then
Result := SNotAvailable;
end;
function ParentName(const AComponent: IOTAComponent): WideString;
begin
Result := GxOtaGetComponentParentName(AComponent);
if Result = '' then
Result := SNotAvailable;
end;
function ComponentProperty(const PropName: string; const AComponent: IOTAComponent): WideString;
begin
if GxOtaPropertyExists(AComponent, PropName) then
Result := GxOtaGetComponentPropertyAsString(AComponent, PropName)
else
Result := SNotAvailable;
end;
resourcestring
SCellComponent = 'Component';
var
CurrentRow: Integer;
AComponent: IOTAComponent;
AComponentName: WideString;
i, j: Integer;
begin
Assert(Assigned(FComponentList));
StringGrid.RowCount := 1;
StringGrid.ColCount := FixedColumns + Length(GridProperties);
for i := Low(GridProperties) to High(GridProperties) do
StringGrid.ColWidths[i + FixedColumns] := GridProperties[i].ColWidth;
StringGrid.Cells[0, 0] := SCellComponent;
StringGrid.Cells[1, 0] := 'Parent';
for i := Low(GridProperties) to High(GridProperties) do
StringGrid.Cells[i + FixedColumns, 0] := GridProperties[i].PropertyName;
for i := 0 to FComponentList.Count-1 do
begin
AComponent := FComponentList.Items[i] as IOTAComponent;
Assert(Assigned(AComponent));
AComponentName := ComponentName(AComponent);
if Length(AComponentName) = 0 then
Continue;
CurrentRow := StringGrid.RowCount;
StringGrid.RowCount := StringGrid.RowCount + 1;
StringGrid.Cells[0, CurrentRow] := AComponentName;
StringGrid.Cells[1, CurrentRow] := ParentName(AComponent);
StringGrid.Objects[0, CurrentRow] := Pointer(i);
for j := Low(GridProperties) to High(GridProperties) do
StringGrid.Cells[FixedColumns + j, CurrentRow] := ComponentProperty(GridProperties[j].PropertyName, AComponent)
end;
StringGrid.FixedCols := FixedColumns;
StringGrid.FixedRows := 1;
StringGridResize(StringGrid);
end;
constructor TfmComponentGrid.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FComponentList := TInterfaceList.Create;
FModified := False;
FillComponentList;
PopulateGrid;
end;
destructor TfmComponentGrid.Destroy;
begin
ClearComponentList;
FreeAndNil(FComponentList);
inherited Destroy;
end;
procedure TfmComponentGrid.StringGridResize(Sender: TObject);
const
MinimumLastColWidth = 100;
var
SendingGrid: TSortGrid;
i: Integer;
WidthDelta: Integer;
LastColWidth: Integer;
begin
SendingGrid := Sender as TSortGrid;
Assert(Assigned(SendingGrid));
WidthDelta := SendingGrid.ClientWidth;
for i := 0 to SendingGrid.ColCount - 1 do
Dec(WidthDelta, SendingGrid.ColWidths[i]);
Dec(WidthDelta, SendingGrid.ColCount * SendingGrid.GridLineWidth);
LastColWidth := SendingGrid.ColWidths[SendingGrid.ColCount-1];
Inc(LastColWidth, WidthDelta);
if LastColWidth < MinimumLastColWidth then
LastColWidth := MinimumLastColWidth;
SendingGrid.ColWidths[SendingGrid.ColCount-1] := LastColWidth;
end;
procedure TfmComponentGrid.actFileSaveExecute(Sender: TObject);
var
Row, j: Integer;
ComponentIndex: Integer;
AComponent: IOTAComponent;
Value: string;
begin
Assert(Assigned(FComponentList));
for Row := 1 to StringGrid.RowCount - 1 do
begin
ComponentIndex := Integer(StringGrid.Objects[0, Row]);
AComponent := FComponentList.Items[ComponentIndex] as IOTAComponent;
Assert(Assigned(AComponent));
for j := Low(GridProperties) to High(GridProperties) do begin
Value := StringGrid.Cells[FixedColumns + j, Row];
if Value <> SNotAvailable then
GxOtaSetComponentPropertyAsString(AComponent, GridProperties[j].PropertyName, Value);
end;
end;
FModified := False;
ModalResult := mrOk;
end;
procedure TfmComponentGrid.actFilePrintExecute(Sender: TObject);
begin
PrintComponentGrid;
end;
procedure TfmComponentGrid.actFileRenumberExecute(Sender: TObject);
var
i: Integer;
StartAt: Longint;
SkipBy: Longint;
begin
StartAt := udStart.Position;
SkipBy := udSkipBy.Position;
for i := 1 to StringGrid.RowCount - 1 do
begin
if StringGrid.Cells[3, i] <> SNotAvailable then
begin
StringGrid.Cells[3, i] := IntToStr(StartAt);
StartAt := StartAt + SkipBy;
end;
end;
end;
procedure TfmComponentGrid.actHelpHelpExecute(Sender: TObject);
begin
GxContextHelp(Self, 22);
end;
procedure TfmComponentGrid.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
begin
Key := 0;
Close;
end;
end;
procedure TfmComponentGrid.FormCreate(Sender: TObject);
begin
SetToolbarGradient(ToolBar);
StringGrid := TSortGrid.Create(Self);
with StringGrid do
begin
Name := 'StringGrid';
Parent := Self;
Left := 0;
Top := 22;
Width := 449;
Height := 218;
Align := alClient;
ColCount := FixedColumns + Length(GridProperties);
DefaultRowHeight := 18;
DefaultColWidth := 130;
FixedCols := FixedColumns;
RowCount := 2;
Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goEditing, goTabs, goColSizing];
TabOrder := 0;
OnSelectCell := StringGridSelectCell;
OnSetEditText := StringGridSetEditText;
CaseSensitive := False;
AlignmentHorz := taLeftJustify;
AlignmentVert := taTopJustify;
ClickSorting := True;
BevelStyle := cbNone;
ProportionalScrollBars := True;
ExtendedKeys := False;
OnResize := StringGridResize;
end;
end;
initialization
RegisterGX_Expert(TGridExpert);
end.
|
{----------------------------------------------------------------------------
|
| Library: Envision
|
| Module: EnDiGrph
|
| Description: Abstract TGraphic descendant which supports a device indenpendent
| drawing surface.
|
| History: Oct 29, 1998. Michel Brazeau, first version
| Feb 13, 1999. MB Add AssignFromDIBHandle
| Sep 06, 1999. MB fix SaveToClipboardFormat to work under NT
|
|---------------------------------------------------------------------------}
unit EnDiGrph;
{$I Envision.Inc}
interface
uses
Windows, { for TRect, PMaxLogPalette }
SysUtils, { for Exception, PByteArray }
ExtCtrls, { for TTimer }
Classes, { for TStream }
Controls, { for TControl }
Graphics, { for TGraphic, TCanvas }
EnMisc; { for PMaxLogPalette }
type
TBitmapInfo = packed record
BmpHeader : TBitmapInfoHeader;
Palette : array[Byte] of TRgbQuad;
end;
TRgb = packed record
Red : Byte;
Green : Byte;
Blue : Byte;
Filler : Byte;
end;
TSetPixelProc = procedure( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt );
TGetPixelFunc = function( const ScanLine : PByteArray;
const X : LongInt ) : LongInt;
type
TIndexCacheEntry = packed record
Color : TRgb;
Index : SmallInt;
end;
TRgbToPaletteConverter = class(TObject)
protected
pPalette : PMaxLogPalette;
{ lower bound of Cache must always be 0.}
Cache : array[0..1019] of TIndexCacheEntry;
Hits : LongInt;
Misses : LongInt;
public
constructor Create(var Palette : TMaxLogPalette);
function GetIndex(const Color : TRgb) : Word;
end;
TDibGraphic = class(TGraphic)
protected
FBitmapHandle : HBITMAP;
FDC : HDC;
FBits : PByteArray;
FPaletteHandle : HPALETTE;
FImageFormat : TImageFormat;
FBitmapInfo : TBitmapInfo;
FPalette : TMaxLogPalette;
{ size in bytes of a scan line, longword alligned }
FScanLineSize : LongInt;
FCanvas : TCanvas;
FImageToLoad : LongInt;
{ when MultiLoad is True, LoadFromStream will load all the frames (images)
when the file format supports multiple images }
FMultiLoad : Boolean;
{ list of frames when supporting multiple image file formats. See
MultiLoad property. This object is only created when MultiLoad is
set True }
FFrames : TList;
{ Delay in milli seconds, which indicates the display duration when the
Animated property is True }
FImageDelay : LongInt;
FAnimated : Boolean;
FAnimationTimer : TTimer;
{ current frame being displayed. 1..FrameCount }
FCurrentFrame : LongInt;
FGetPixelFunc : TGetPixelFunc;
FSetPixelProc : TSetPixelProc;
FRgbToPaletteConverter : TRgbToPaletteConverter;
FOldBitmapHandle : HBitmap;
procedure AnimateTimer( Sender : TObject );
procedure SetMultiLoad( const Multi : Boolean );
procedure SetAnimated( const InAnimated : Boolean );
function GetEmpty: Boolean; override;
function GetHeight: Integer; override;
function GetWidth: Integer; override;
procedure SetWidth(Value: Integer); override;
procedure SetHeight(Value: Integer); override;
function GetXDotsPerInch : Word;
function GetYDotsPerInch : Word;
procedure SetXDotsPerInch( const XDpi : Word );
procedure SetYDotsPerInch( const YDpi : Word );
function GetScanLine( const Y : LongInt ) : PByteArray; register;
function GetRGB( const X,Y : LongInt ) : TRgb; register;
procedure SetRGB( const X,Y : LongInt;
const RGB : TRgb ); register;
function GetPaletteIndex( const X,Y : LongInt ) : Byte; register;
procedure SetPaletteIndex( const X,Y : LongInt;
Index : Byte ); register;
function GetPaletteHandle : HPalette;
function GetPalettePtr : PMaxLogPalette;
function GetFrame(FrameNo : LongInt) : TDibGraphic;
function GetFrameCount : LongInt;
procedure SetCurrentFrame( FrameNo : LongInt );
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure AssignTo(Dest : TPersistent); override;
procedure Draw(ACanvas: TCanvas; const Rect: TRect); override;
procedure AssignFromBitmapHandle( const InBitmapHandle : HBITMAP );
procedure AssignFromDIBHandle( const InDibHandle : THandle );
function GetImageCount( const Stream : TStream ) : LongInt; virtual;
function IsEmpty : Boolean;
{ if MultiLoad is False, ImageToLoad may be set before calling
LoadFromStream to specify which image to load. Default is 1.
It is the user's responsible to ensure ImageToLoad contains a
valid value, by first invoking GetImageCount. }
property ImageToLoad : LongInt read FImageToLoad
write FImageToLoad;
procedure LoadFromStream(Stream: TStream); override;
procedure SingleLoadFromStream( const Stream : TStream;
const ImageToLoad : LongInt
); virtual;
procedure SaveToStream(Stream: TStream); override;
procedure AppendToStream(Stream : TStream); virtual;
procedure LoadFromClipboardFormat(AFormat: WorD; AData: THandle;
APalette: HPalette); override;
procedure SaveToClipboardFormat(var AFormat: WorD; var AData: THandle;
var APalette: HPalette); override;
procedure NewImage( const Width : LongInt;
const Height : LongInt;
const ImageFormat : TImageFormat;
pPalette : PMaxLogPalette;
const InXDotsPerInch : Word;
const InYDotsPerInch : Word ); virtual;
procedure Clear;
property ImageFormat : TImageFormat read FImageFormat;
property Bits : PByteArray read FBits;
{ 0 <= Y < Height. No validation for performance }
property ScanLine[ const Y : LongInt ] : PByteArray
read GetScanLine;
property ScanLineSize : LongInt
read FScanLineSize;
property RGB[ const X,Y : LongInt ] : TRgb
read GetRGB
write SetRGB;
property PaletteIndex[ const X,Y : LongInt ] : Byte
read GetPaletteIndex
write SetPaletteIndex;
property Palette : TMaxLogPalette read FPalette;
property PalettePtr : PMaxLogPalette read GetPalettePtr;
property PaletteHandle : HPalette
read GetPaletteHandle;
property BitmapHandle : HBitmap
read FBitmapHandle;
property XDotsPerInch : Word read GetXDotsPerInch
write SetXDotsPerInch;
property YDotsPerInch : Word read GetYDotsPerInch
write SetYDotsPerInch;
property Canvas : TCanvas read FCanvas;
property DC : HDC read FDC;
property BitmapInfo : TBitmapInfo read FBitmapInfo;
property MultiLoad : Boolean read FMultiLoad
write SetMultiLoad;
property ImageDelay : LongInt read FImageDelay
write FImageDelay;
property Animated : Boolean read FAnimated
write SetAnimated;
property Frames[FrameNo: LongInt] : TDibGraphic read GetFrame;
property FrameCount : LongInt read GetFrameCount;
{ current frame being displayed. Must only be set when MultiLoad is
True. 1..FrameCount }
property CurrentFrame : LongInt read FCurrentFrame
write SetCurrentFrame;
end;
TDibGraphicClass = class of TDibGraphic;
{--------------------------------------------------------------------------}
function MakeRgb( Red : Byte; Green : Byte; Blue : Byte ) : TRgb;
{--------------------------------------------------------------------------}
function GetBitDepth( const ImageFormat : TImageFormat ) : Word;
{--------------------------------------------------------------------------}
procedure SetBWPalette( var Palette : TMaxLogPalette );
procedure SetGray16Palette( var Palette : TMaxLogPalette );
procedure SetGray256Palette( var Palette : TMaxLogPalette );
procedure SetColor16Palette( var Palette : TMaxLogPalette );
procedure SetColor256Palette( var Palette : TMaxLogPalette );
{--------------------------------------------------------------------------}
procedure SetPixelBc1( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt ); register;
function GetPixelBc1( const ScanLine : PByteArray;
const X : LongInt ) : LongInt; register;
{--------------------------------------------------------------------------}
procedure SetPixelBc4( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt ); register;
function GetPixelBc4( const ScanLine : PByteArray;
const X : LongInt ) : LongInt; register;
{--------------------------------------------------------------------------}
procedure SetPixelBc8( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt ); register;
function GetPixelBc8( const ScanLine : PByteArray;
const X : LongInt ) : LongInt; register;
{--------------------------------------------------------------------------}
procedure SetPixelBc24( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt ); register;
function GetPixelBc24( const ScanLine : PByteArray;
const X : LongInt ) : LongInt; register;
{--------------------------------------------------------------------------}
{ swap the Red and Blue channels on a 24 bit scan line. }
procedure SwapRBOnScanLine( const pScanLine : PByteArray;
const ScanLineSize : LongInt);
{--------------------------------------------------------------------------}
function ImageFormatStr( const ImageFormat : TImageFormat ) : String;
{--------------------------------------------------------------------------}
{ Register a TDibGraphic for integration with Delphi's TImage component.
This routine should be used instread of TPicture.RegisterFileFormat,
in order to use the FindDibGraphicClass function. Extension must NOT
include the leading '.'
MB Oct 25, 1999. Very nasty bug in CBuilder, where when passing a
metaclass as a parameter, the linker was unable to link the function. By
making a pointer a generic pointer, and typecasting inside the function,
the link is successful.
MB Nov 07, 1999. Since the DCU's of the evaluation version are compiled
with Delphi, the evaluation version of CBuilder was not able to link
this function. So to workaround this bug, the DibGraphicClass is
passed as Pointer with all compilers.
}
procedure RegisterDibGraphic( const Extension : String;
const Description : String;
const DibGraphicClass : Pointer
);
{--------------------------------------------------------------------------}
{ Returns a TDibGraphicClass which is capable of reading FileName. FileName
may be a complete file name or an extension. Returns nil, if there is not
any TDibGraphicClass registered to open FileName. }
function FindDibGraphicClass( const FileName : String ) : TDibGraphicClass;
{--------------------------------------------------------------------------}
{ Returns a TDibGraphic instance capable of reading FileName. FileName
may be a complete file name or an extension. Returns nil, if there is not
an TDibGraphicClass registered to open FileName. }
function NewDibGraphic( const FileName : String ) : TDibGraphic;
{--------------------------------------------------------------------------}
const
CSetPixelArray : array[TImageFormat] of TSetPixelProc = (
SetPixelBc1,
SetPixelBc4,
SetPixelBc8,
SetPixelBc4,
SetPixelBc8,
SetPixelBc24 );
CGetPixelArray : array[TImageFormat] of TGetPixelFunc = (
GetPixelBc1,
GetPixelBc4,
GetPixelBc8,
GetPixelBc4,
GetPixelBc8,
GetPixelBc24 );
CWhiteRgb : TRgb = (Red:255; Green:255; Blue:255; Filler:0);
CBlackRgb : TRgb = (Red:0; Green:0; Blue:0; Filler:0);
var
{ default Palettes }
pBlackWhitePalette : PMaxLogPalette;
pGray16Palette : PMaxLogPalette;
pGray256Palette : PMaxLogPalette;
pColor16Palette : PMaxLogPalette;
pColor256Palette : PMaxLogPalette;
{ ScreenGamma default = 2.2. This value should be a good guess on the
PC platform. }
ScreenGamma : Double;
{--------------------------------------------------------------------------}
implementation
uses
{$ifdef __Evaluation}
Dialogs, { for MessageDlg }
{$endif}
Forms, { for Application }
ClipBrd, { for ClipBoard }
EnIcoGr, { for TIconGraphic }
EnMsg; { for EEnvisionError }
var
DibClasses : TStringList;
{--------------------------------------------------------------------------}
function MakeRgb( Red : Byte; Green : Byte; Blue : Byte ) : TRgb;
begin
Result.Red := Red;
Result.Green := Green;
Result.Blue := Blue;
Result.Filler := 0;
end;
{--------------------------------------------------------------------------}
function GetBitDepth( const ImageFormat : TImageFormat ) : Word;
begin
case ImageFormat of
ifBlackWhite : Result := 1;
ifGray16 : Result := 4;
ifGray256 : Result := 8;
ifColor16 : Result := 4;
ifColor256 : Result := 8;
ifTrueColor : Result := 24;
else
raise EEnvisionError.Create(msgInvalidImageFormat);
end;
end; { GetBitCount }
{--------------------------------------------------------------------------}
function ImageFormatStr( const ImageFormat : TImageFormat ) : String;
begin
Result := '';
case ImageFormat of
ifBlackWhite : Result := 'Black and white';
ifGray16 : Result := '16 shades of gray';
ifGray256 : Result := '256 shades of gray';
ifColor16 : Result := '16 color';
ifColor256 : Result := '256 color';
ifTrueColor : Result := 'True color';
end;
end;
{--------------------------------------------------------------------------}
procedure RegisterDibGraphic( const Extension : String;
const Description : String;
const DibGraphicClass : Pointer
);
begin
TPicture.RegisterFileFormat(Extension, Description, TDibGraphicClass(DibGraphicClass));
{ MB Aug 13, 1999. This routine may be called before this unit
is initialized, so create the object if it is nil. The unit
initialization will not recreate it. }
if DibClasses = nil then
DibClasses := TStringList.Create;
DibClasses.AddObject(AnsiUpperCase(Extension), TObject(DibGraphicClass));
end;
{--------------------------------------------------------------------------}
function FindDibGraphicClass( const FileName : String ) : TDibGraphicClass;
var
Index : Integer;
Ext : String;
begin
Result := nil;
Ext := AnsiUpperCase(ExtractFileExt(FileName));
if (Ext = '') then
begin
{ assume FileName is an extension }
Ext := '.' + FileName;
end;
Delete(Ext, 1, 1);
Index := DibClasses.IndexOf(Ext);
if Index >= 0 then
Result := TDibGraphicClass(DibClasses.Objects[Index]);
end;
{--------------------------------------------------------------------------}
function NewDibGraphic(const FileName : String) : TDibGraphic;
var
DibGraphicClass : TDibGraphicClass;
begin
DibGraphicClass := FindDibGraphicClass(FileName);
if DibGraphicClass = nil then
raise EEnvisionError.Create(
Format( msgFileFormatNotSupported,
[ExtractFileExt(FileName)]));
Result := DibGraphicClass.Create;
end;
{--------------------------------------------------------------------------}
function ComputeScanLineSize( const Width : LongInt;
const BitCount : Word ) : LongInt;
begin
Result := (((Width * BitCount) + 31) and not 31) div 8;
end;
{--------------------------------------------------------------------------}
procedure GetBitmapHeader( const Bitmap : HBITMAP;
var Header : TBitmapInfoHeader );
var
DibSection : TDIBSection;
Bytes : Integer;
begin
DibSection.dsbmih.biSize := 0;
Bytes := GetObject(Bitmap, SizeOf(DibSection), @DibSection);
if Bytes = 0 then
EInvalidGraphic.Create(msgInvalidBitmap)
else if (Bytes >= (sizeof(DibSection.dsbm) + sizeof(DibSection.dsbmih))) and
(DibSection.dsbmih.biSize >= (sizeof(DibSection.dsbmih))) then
Header := DibSection.dsbmih
else
begin
FillChar(Header, sizeof(Header), 0);
Header.biSize := SizeOf(Header);
Header.biWidth := DibSection.dsbm.bmWidth;
Header.biHeight := DibSection.dsbm.bmHeight;
end;
Header.biBitCount := DibSection.dsbm.bmBitsPixel * DibSection.dsbm.bmPlanes;
if Header.biBitCount in [16, 32] then
begin
Header.biBitCount := 24; { only 24 True color bitmaps supported }
{ MB Apr 26, 1999. GetDiBits was failing because the image size was
not properly set. }
Header.biSizeImage := 0; { force recalculating size with new bit count }
end;
Header.biPlanes := 1;
if Header.biSizeImage = 0 then
Header.biSizeImage := ComputeScanLineSize(Header.biWidth, Header.biBitCount) * Abs(Header.biHeight);
end;
{--------------------------------------------------------------------------}
procedure GetDIBSizes( const BitmapHandle : HBITMAP;
var InfoHeaderSize : DWORD;
var ImageSize : DWORD );
var
Header : TBitmapInfoHeader;
begin
GetBitmapHeader(BitmapHandle, Header);
if Header.biBitCount > 8 then
begin
InfoHeaderSize := SizeOf(TBitmapInfoHeader);
if (Header.biCompression and BI_BITFIELDS) <> 0 then
Inc(InfoHeaderSize, 12);
end
else
InfoHeaderSize := SizeOf(TBitmapInfoHeader) + SizeOf(TRGBQuad) *
(1 shl Header.biBitCount);
ImageSize := Header.biSizeImage;
end;
{--------------------------------------------------------------------------}
function GetDIB( const BitmapHandle : HBITMAP;
var BitmapInfo : Windows.TBitmapInfo;
const Bits : PByteArray ): Boolean;
var
DC : HDC;
SavedHeader : TBitmapInfoHeader;
begin
GetBitmapHeader(BitmapHandle, BitmapInfo.bmiHeader);
DC := CreateCompatibleDC(0);
try
{ Oct 05, 1999. MB. GetDIBits seems to overwrite the biClrUsed field,
so a temporary copy is saved. }
SavedHeader := BitmapInfo.bmiHeader;
Result := GetDIBits( DC, BitmapHandle, 0,
BitmapInfo.bmiHeader.biHeight,
Bits, BitmapInfo,
DIB_RGB_COLORS) <> 0;
BitmapInfo.bmiHeader := SavedHeader;
finally
DeleteDC(DC);
end;
end;
{--------------------------------------------------------------------------}
constructor TDibGraphic.Create;
begin
inherited Create;
FBitmapHandle := 0;
FPaletteHandle := 0;
FDC := 0;
FOldBitmapHandle := 0;
FBits := nil;
FRgbToPaletteConverter := nil;
FillChar(FPalette, SizeOf(FPalette), 0);
FFrames := TList.Create;
FAnimationTimer := TTimer.Create(nil);
FAnimationTimer.OnTimer := AnimateTimer;
FAnimationTimer.Enabled := False;
FMultiLoad := False;
FImageDelay := 200;
FAnimated := False;
FCurrentFrame := -1;
FImageToLoad := 1;
end;
{--------------------------------------------------------------------------}
destructor TDibGraphic.Destroy;
var
ImageNo : LongInt;
begin
FAnimationTimer.Enabled := False;
FAnimationTimer.Free;
for ImageNo := 0 to (FFrames.Count-1) do
begin
TDibGraphic(FFrames.Items[ImageNo]).Free;
end;
FFrames.Free;
Clear;
inherited Destroy;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.NewImage( const Width : LongInt;
const Height : LongInt;
const ImageFormat : TImageFormat;
pPalette : PMaxLogPalette;
const InXDotsPerInch : Word;
const InYDotsPerInch : Word );
begin
Clear;
FDC := CreateCompatibleDC(0);
try
FImageFormat := ImageFormat;
if (ImageFormat <> ifTrueColor) and
(pPalette = nil) then
begin
case ImageFormat of
ifBlackWhite : pPalette := pBlackWhitePalette;
ifGray16 : pPalette := pGray16Palette;
ifGray256 : pPalette := pGray256Palette;
ifColor16 : pPalette := pColor16Palette;
ifColor256 : pPalette := pColor256Palette;
else
raise EEnvisionError.Create(msgInvalidImageFormat);
end;
end;
with FBitmapInfo.BmpHeader do
begin
biSize := SizeOf(FBitmapInfo.BmpHeader);
biWidth := Width;
biHeight := Height;
biPlanes := 1;
biBitCount := GetBitDepth(ImageFormat);
biCompression := Windows.BI_RGB;
FScanLineSize := ComputeScanLineSize(
biWidth,
biBitCount );
biSizeImage := biHeight * FScanLineSize;
biClrImportant := 0;
if ImageFormat = ifTrueColor then
biClrUsed := 0
else
begin
biClrUsed := pPalette^.palNumEntries;
Move( pPalette^.palPalEntry, FBitmapInfo.Palette,
biClrUsed*SizeOf(TRgbQuad));
FRgbToPaletteConverter := TRgbToPaletteConverter.Create(
pPalette^ );
{ ensure palette version is always set }
pPalette^.palVersion := $0300;
end;
end;
if InXDotsPerInch > 0 then
XDotsPerInch := InXDotsPerInch
else
XDotsPerInch := GetDeviceCaps(FDC, LOGPIXELSX);
if InYDotsPerInch > 0 then
YDotsPerInch := InYDotsPerInch
else
YDotsPerInch := GetDeviceCaps(FDC, LOGPIXELSY);
FBitmapHandle := CreateDibSection( FDC, Windows.PBitmapInfo(@FBitmapInfo)^,
DIB_RGB_COLORS, Pointer(FBits),
0, 0);
if FBitmapHandle = 0 then
raise EEnvisionError.Create('CreateDibSection failed');
FGetPixelFunc := CGetPixelArray[ImageFormat];
FSetPixelProc := CSetPixelArray[ImageFormat];
FOldBitmapHandle := SelectObject(FDC, FBitmapHandle);
FillChar(FPalette, SizeOf(FPalette), 0);
if ImageFormat <> ifTrueColor then
begin
Move( pPalette^, FPalette,
4 + (pPalette^.palNumEntries*SizeOf(Windows.TPaletteEntry)));
FPalette.palVersion := $0300;
end;
FCanvas := TCanvas.Create;
FCanvas.Handle := FDC;
except
Clear;
raise;
end;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.Clear;
begin
if FCanvas <> nil then
begin
FCanvas.Free;
FCanvas := nil;
end;
{ it is very important to restore the old bitmap handle into the
device contexts. Omitting this operation creates a heavy resource
leak. }
if (FOldBitmapHandle <> 0) and
(FDC <> 0) then
begin
SelectObject(FDC, FOldBitmapHandle);
FOldBitmapHandle := 0;
end;
if FRgbToPaletteConverter <> nil then
begin
FRgbToPaletteConverter.Free;
FRgbToPaletteConverter := nil;
end;
if FPaletteHandle <> 0 then
begin
DeleteObject(FPaletteHandle);
FPaletteHandle := 0;
end;
if FBitmapHandle <> 0 then
begin
DeleteObject(FBitmapHandle);
FBitmapHandle := 0;
end;
if FDC <> 0 then
begin
DeleteDC(FDC);
FDC := 0;
end;
FBits := nil;
FillChar(FBitmapInfo, SizeOf(FBitmapInfo), 0);
end;
{--------------------------------------------------------------------------}
function TDibGraphic.IsEmpty : Boolean;
begin
Result := (FBitmapHandle = 0);
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.Draw(ACanvas: TCanvas; const Rect: TRect);
var
CanvasPalette : HPalette;
OldPalette : HPalette;
StretchMode : Integer;
begin
{ using HALFTONE stretch mode, the stretch quality is better.
The API help on SetStretchBltMode specifies that SetBrushOrgEx
must be called afterwords.
MB Jun 05, 1999. "Terwiske, John J." <JTerwiske@Kronos.com>, reported
that with true color images, COLORONCOLOR procduces better results. On
my video driver, I did not see any difference though. Windows API help
does mention that HALFTONE should produce better results. }
if FImageFormat = ifTrueColor then
StretchMode := Windows.COLORONCOLOR
else
StretchMode := Windows.HALFTONE;
SetStretchBltMode( ACanvas.Handle, StretchMode );
if StretchMode = Windows.HALFTONE then
SetBrushOrgEx( ACanvas.Handle, 0, 0, nil );
OldPalette := 0;
if (GetDeviceCaps(ACanvas.Handle, Windows.RASTERCAPS) and Windows.RC_PALETTE) <> 0 then
begin
{ screen is uses a palette }
{ MB Apr 3, 1999. The display quality is better with CreateHalftonePalette,
but I still have not figured out how have the displayed image dithered
as in Navigator
CanvasPalette := CreatePalette(PLogPalette(pColor256Palette)^);
}
CanvasPalette := CreateHalftonePalette(ACanvas.Handle);
try
OldPalette := SelectPalette(ACanvas.Handle, CanvasPalette, False);
RealizePalette(ACanvas.Handle);
finally
DeleteObject(CanvasPalette);
end;
end;
StretchDiBits( ACanvas.Handle, Rect.Left, Rect.Top,
Rect.Right - Rect.Left, Rect.Bottom - Rect.Top,
0, 0,
FBitmapInfo.BmpHeader.biWidth, FBitmapInfo.BmpHeader.biHeight,
Pointer(FBits), Windows.PBitmapInfo(@FBitmapInfo)^,
DIB_RGB_COLORS, SRCCOPY);
{$ifdef __Evaluation}
ACanvas.Font.Size := 10;
ACanvas.Font.Name := 'Arial';
ACanvas.Font.Style := [fsBold];
ACanvas.Font.Color := clLime;
SetBkMode(ACanvas.Handle, Windows.TRANSPARENT);
ACanvas.TextOut(4, 2, 'Envision Image Library Demo');
ACanvas.Font.Color := clGray;
ACanvas.Font.Size := 9;
ACanvas.TextOut(4, 20, 'www.intervalsoftware.com');
SetBkMode(ACanvas.Handle, Windows.OPAQUE);
{$endif}
if OldPalette <> 0 then
SelectPalette(ACanvas.Handle, OldPalette, False);
end;
{--------------------------------------------------------------------------}
type
TProtectedGraphic = class(TGraphic);
procedure TDibGraphic.Assign(Source: TPersistent);
var
SourceDib : TDibGraphic;
BitmapHandle : HBITMAP;
PaletteHandle : HPALETTE;
Rect : TRect;
begin
if (Source = nil) or (Source is TDibGraphic) then
begin
Self.Clear;
if (Source = nil) then
SourceDib := nil
else
SourceDib := TDibGraphic(Source);
if (SourceDib <> nil) and (SourceDib.Width > 0) and (SourceDib.Height > 0) then
begin
Self.NewImage( SourceDib.Width,
SourceDib.Height,
SourceDib.ImageFormat,
@SourceDib.FPalette,
SourceDib.XDotsPerInch,
SourceDib.YDotsPerInch );
Self.XDotsPerInch := SourceDib.XDotsPerInch;
Self.YDotsPerInch := SourceDib.YDotsPerInch;
Self.ImageDelay := SourceDib.ImageDelay;
Move( SourceDib.FBits^, Self.FBits^,
SourceDib.ScanLineSize * SourceDib.Height);
end;
end
else if Source is TClipBoard then
begin
Clipboard.Open;
try
BitmapHandle := GetClipboardData(CF_BITMAP);
PaletteHandle := GetClipboardData(CF_PALETTE);
Self.LoadFromClipboardFormat(CF_BITMAP, BitmapHandle, PaletteHandle);
finally
Clipboard.Close;
end;
end
else if Source is TBitmap then
begin
{ AssignFromBitmapHandle reads the X and Y resolutions }
{ MB Oct 28, 1999. The AssignFromBitmapHandle works with a device
dependent bitmap. This is required to load 16 bit bitmaps, in order
to convert them to 24 bits using the GetDIB function. }
TBitmap(Source).HandleType := bmDDB;
Self.AssignFromBitmapHandle(TBitmap(Source).Handle);
end
else if Source is TGraphic then
begin
{ any TGraphic (other than TBitmap) use the Draw method. The resolution
is not available }
Rect.Left := 0;
Rect.Top := 0;
Rect.Right := TGraphic(Source).Width;
Rect.Bottom := TGraphic(Source).Height;
NewImage( Rect.Right, Rect.Bottom, ifTrueColor, nil, 0, 0 );
FillChar(Self.Bits^, Self.Height*ScanLineSize, 0);
TProtectedGraphic(Source).Draw(Self.Canvas, Rect);
end
else
inherited Assign(Source);
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.AssignTo(Dest : TPersistent);
var
Rect : TRect;
IconGraphic : TIconGraphic;
Stream : TMemoryStream;
begin
if Dest is TDibGraphic then
Dest.Assign(Self)
else
begin
if Dest is TBitmap then
begin
{ MB Aug 11, 1999. This code seemed to work, but a subsequent
Bitmap.SaveToFile would raise an out of resources exception.
Using the Draw method seems to be more stable
TBitmap(Dest).Palette := Self.PaletteHandle;
TBitmap(Dest).Handle := Self.BitmapHandle;
}
Rect.Left := 0;
Rect.Top := 0;
Rect.Right := Self.Width;
Rect.Bottom := Self.Height;
TBitmap(Dest).PixelFormat := pf24bit;
TBitmap(Dest).Width := Self.Width;
TBitmap(Dest).Height := Self.Height;
Self.Draw( TBitmap(Dest).Canvas, Rect );
end
else if Dest is TIcon then
begin
{ assigning to a TIcon is important to allow specify the
Application's Icon at design in the project options }
Stream := TMemoryStream.Create;
try
if (Self is TIconGraphic) then
Self.SaveToStream(Stream)
else
begin
IconGraphic := TIconGraphic.Create;
try
IconGraphic.Assign(Self);
IconGraphic.SaveToStream(Stream);
finally
IconGraphic.Free;
end;
end;
Stream.Seek(0, soFromBeginning);
TIcon(Dest).LoadFromStream(Stream);
finally
Stream.Free;
end;
end
else
raise EEnvisionError.Create(
Format( msgCannotAssign,
['TDibGraphic', Dest.ClassName]));
end;
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetEmpty: Boolean;
begin
Result := (FBitmapHandle = 0);
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetHeight: Integer;
begin
Result := FBitmapInfo.BmpHeader.biHeight;
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetWidth: Integer;
begin
Result := FBitmapInfo.BmpHeader.biWidth;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetWidth(Value: Integer);
begin
raise EEnvisionError.Create(msgUseNewImageToChangeSize);
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetHeight(Value: Integer);
begin
raise EEnvisionError.Create(msgUseNewImageToChangeSize);
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetImageCount( const Stream : TStream ) : LongInt;
begin
Result := 1;
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetPaletteHandle : HPalette;
begin
if ImageFormat <> ifTrueColor then
begin
if FPaletteHandle = 0 then
begin
FPaletteHandle := CreatePalette(PLogPalette(@FPalette)^);
Result := FPaletteHandle;
end
else
Result := FPaletteHandle;
end
else
Result := 0;
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetPalettePtr : PMaxLogPalette;
begin
Result := @FPalette;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.LoadFromStream(Stream: TStream);
var
ImageNo : LongInt;
ImageCount : LongInt;
DibGraphic : TDibGraphic;
DibGraphicClass : TDibGraphicClass;
WasAnimated : Boolean;
SavedPos : LongInt;
begin
WasAnimated := Animated;
Animated := False;
try
{ MB Mar 08, 1999. Do NOT seek to the beginning of the stream,
as this prevents the image from being loaded at design time
in a TImage component. }
SavedPos := 0; { prevent compiler warning }
if MultiLoad then
begin
{ MB Aug 8, 1999. Ensure the stream positioned is not changed
after calling GetImageCount, previously with TIFF images, the
TTiffGraphic.SingleLoadFrom stream still behaved properly
but a temporary memory stream was created without reason.
With the new TDcxGraphic, this problem was found }
SavedPos := Stream.Position;
ImageCount := GetImageCount(Stream);
if ImageCount = 1 then
MultiLoad := False;
end
else
ImageCount := 1; { prevent compiler warning }
if MultiLoad then
begin
for ImageNo := 1 to ImageCount do
begin
{ use ClassType to create the proper type of TDibGraphic }
DibGraphicClass := TDibGraphicClass(Self.ClassType);
DibGraphic := DibGraphicClass.Create;
{ restore the original stream position }
Stream.Seek(SavedPos, soFromBeginning);
DibGraphic.SingleLoadFromStream(Stream, ImageNo);
FFrames.Add(DibGraphic);
end;
CurrentFrame := 1;
end
else
begin
Self.SingleLoadFromStream(Stream, FImageToLoad);
end;
finally
Animated := WasAnimated;
end;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SingleLoadFromStream(
const Stream : TStream;
const ImageToLoad : LongInt
);
begin
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SaveToStream(Stream: TStream);
begin
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.AppendToStream(Stream : TStream);
begin
raise EEnvisionError.Create(
Format( msgSingleImageFileFormat,
[Self.ClassName]));
end;
{--------------------------------------------------------------------------}
function GetImageFormat( const BitCount : Word ) : TImageFormat;
begin
case BitCount of
1 : Result := ifBlackWhite;
4 : Result := ifColor16;
8 : Result := ifColor256;
24: Result := ifTrueColor;
else
raise EEnvisionError.Create('Unsupported bit count');
end;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.AssignFromBitmapHandle( const InBitmapHandle : HBITMAP );
var
BitmapHeaderPtr : PBitmapInfo;
BitmapBits : PByteArray;
HeaderSize : DWORD;
ImageSize : DWORD;
Palette : TMaxLogPalette;
PalettePtr : PMaxLogPalette;
XDpi : Integer;
YDpi : Integer;
begin
GetDIBSizes(InBitmapHandle, HeaderSize, ImageSize);
GetMem(BitmapHeaderPtr, HeaderSize);
GetMem(BitmapBits, ImageSize);
try
if not GetDIB(InBitmapHandle, BitmapHeaderPtr^, BitmapBits) then
raise EEnvisionError.Create('GetDIB failed');
with BitmapHeaderPtr^.bmiHeader do
begin
if biCompression <> Windows.BI_RGB then
raise EEnvisionError.Create('Unsupported compression');
PalettePtr := nil;
if (biClrUsed > 0) and (biClrUsed <= 256) then
begin
Palette.palNumEntries := biClrUsed;
Palette.palVersion := $0300;
Move( BitmapHeaderPtr^.bmiColors, Palette.palPalEntry,
biClrUsed*SizeOf(TRgbQuad));
PalettePtr := @Palette;
end;
XDpi := 0;
YDpi := 0;
if biXPelsPerMeter > 0 then
XDpi := Round(biXPelsPerMeter / CInchesPerMeter);
if biYPelsPerMeter > 0 then
YDpi := Round(biYPelsPerMeter / CInchesPerMeter);
if (XDpi > $FFFF) or (XDpi < 0) then
XDpi := 0;
if (YDpi > $FFFF) or (YDpi < 0) then
YDpi := 0;
Self.NewImage( biWidth, biHeight, GetImageFormat(biBitCount),
PalettePtr, XDpi, YDpi );
Move(BitmapBits^, Self.FBits^, ImageSize);
end;
finally
FreeMem(BitmapHeaderPtr, HeaderSize);
FreeMem(BitmapBits, ImageSize);
end;
end;
{--------------------------------------------------------------------------}
procedure DibToBmpStream( const HDIB : THandle;
const Stream : TStream );
var
BmpHeader : TBitmapFileHeader;
pBmpInfoHeader : ^TBitmapInfoHeader;
BitsPerPixel : Word;
ColorCount : LongInt;
ScanLineSize : LongInt;
BytesToWrite : LongInt;
begin
pBmpInfoHeader := GlobalLock(HDIB);
try
BitsPerPixel := pBmpInfoHeader^.biBitCount;
ColorCount := pBmpInfoHeader^.biClrUsed;
if (ColorCount = 0) and (BitsPerPixel <= 8) then
ColorCount := (1 shl BitsPerPixel);
if pBmpInfoHeader^.biCompression = BI_RGB then
begin
ScanLineSize := ((pBmpInfoHeader^.biWidth * BitsPerPixel) + 31) and (not 31);
ScanLineSize := ScanLineSize div 8;
pBmpInfoHeader^.biSizeImage := ScanLineSize * pBmpInfoHeader^.biHeight;
end
else if (pBmpInfoHeader^.biSizeImage = 0) then
raise EEnvisionError.Create('Invalid HDIB');
FillChar(BmpHeader, SizeOf(BmpHeader), 0);
BmpHeader.bfType := $4d42;
BmpHeader.bfOffBits := SizeOf(TBitmapFileHeader) +
SizeOf(TBitmapInfoHeader) +
SizeOf(TRgbQuad) * ColorCount;
BmpHeader.bfSize := BmpHeader.bfOffBits +
pBmpInfoHeader^.biSizeImage;
BytesToWrite := BmpHeader.bfSize - SizeOf(BmpHeader);
if Stream is TMemoryStream then
TMemoryStream(Stream).SetSize(SizeOf(BmpHeader) + BytesToWrite);
Stream.Write(BmpHeader, SizeOf(BmpHeader));
Stream.Write(pBmpInfoHeader^, BytesToWrite);
finally
GlobalUnLock(HDIB);
end;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.AssignFromDIBHandle( const InDibHandle : THandle );
var
pBmpInfoHeader : ^TBitmapInfoHeader;
pBitmapInfo : Windows.PBitmapInfo;
BitsPerPixel : Word;
ColorCount : LongInt;
Palette : TMaxLogPalette;
pPalette : PMaxLogPalette;
ImageFormat : TImageFormat;
Stream : TMemoryStream;
Bitmap : TBitmap;
begin
pBmpInfoHeader := GlobalLock(InDibHandle);
try
pBitmapInfo := Pointer(pBmpInfoHeader);
BitsPerPixel := pBmpInfoHeader^.biBitCount;
ColorCount := pBmpInfoHeader^.biClrUsed;
{ determine size of palette, if biClrUsed was not specified. }
if (ColorCount = 0) and (BitsPerPixel <= 8) then
ColorCount := (1 shl BitsPerPixel);
if BitsPerPixel > 8 then
ColorCount := 0;
if BitsPerPixel <= 8 then
begin
FillChar(Palette, SizeOf(Palette), 0);
Palette.palVersion := $0300;
Palette.palNumEntries := ColorCount;
Move( pBitmapInfo^.bmiColors[0],
Palette.palPalEntry[0],
ColorCount*SizeOf(TRgbQuad));
pPalette := @Palette;
end
else
pPalette := nil;
if BitsPerPixel in [16,32] then
ImageFormat := ifTrueColor
else
ImageFormat := GetImageFormat(BitsPerPixel);
Self.NewImage( pBmpInfoHeader^.biWidth, pBmpInfoHeader^.biHeight,
ImageFormat, pPalette,
Round(pBmpInfoHeader^.biXPelsPerMeter / CInchesPerMeter),
Round(pBmpInfoHeader^.biYPelsPerMeter / CInchesPerMeter) );
if (BitsPerPixel in [1, 4, 8, 24]) and
(pBmpInfoHeader^.biCompression = BI_RGB) then
begin
{ most DIB's are 1,4,8 or 24 bits, not compressed. This is
supported directly by TDibGraphic }
Move( PByteArray(pBmpInfoHeader)^[SizeOf(TBitmapInfoHeader) + ColorCount*SizeOf(TRgbQuad)],
Self.Bits^,
Self.ScanLineSize*pBmpInfoHeader^.biHeight);
end
else
begin
{ bit (16,32) count not supported directly by TDibGraphic. Convert
to a bitmap stream, and let Delphi's TBitmap class do the
conversion. }
Stream := TMemoryStream.Create;
Bitmap := TBitmap.Create;
try
DibToBmpStream(InDibHandle, Stream);
Stream.Seek(0, soFromBeginning);
Bitmap.LoadFromStream(Stream);
{ free the stream to reduce memory usage }
Stream.Free;
Stream := nil;
AssignFromBitmapHandle(Bitmap.Handle);
finally
Bitmap.Free;
Stream.Free;
end;
end;
finally
GlobalUnLock(InDibHandle);
end;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.LoadFromClipboardFormat(
AFormat: WorD; AData: THandle;
APalette: HPalette);
begin
if (AFormat <> CF_BITMAP) or (AData = 0) then
raise EInvalidGraphic.Create(
Format(msgUnsupportedClipboardFormat, [AFormat]));
AssignFromBitmapHandle(AData);
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SaveToClipboardFormat(
var AFormat : Word;
var AData : THandle;
var APalette : HPalette);
var
ScreenDC, NewImageDC : HDC;
OldBitmapHandle : HBITMAP;
begin
AFormat := CF_BITMAP;
ScreenDC := GetDC(0);
NewImageDC := CreateCompatibleDC(ScreenDC);
try
if Self.ImageFormat = ifBlackWhite then
AData := CreateBitmap(Self.Width, Self.Height, 1, 1, nil)
else
AData := CreateCompatibleBitmap(ScreenDC, Self.Width, Self.Height);
if AData = 0 then
raise EEnvisionError.Create('CopyBitmap: CreateBitmap failed');
OldBitmapHandle := SelectObject(NewImageDC, AData);
try
BitBlt( NewImageDC, 0, 0, Self.Width, Self.Height,
Self.FDC, 0, 0, SRCCOPY);
finally
SelectObject(NewImageDC, OldBitmapHandle);
end;
finally
DeleteDC(NewImageDC);
ReleaseDC(0, ScreenDC);
end;
end;
(* MB Sep 06, 1999 Old version not saving to clipboard properly on NT
var
NewDibGraphic : TDibGraphic;
begin
NewDibGraphic := TDibGraphic.Create;
try
NewDibGraphic.Assign(Self);
AFormat := CF_BITMAP;
APalette := NewDibGraphic.PaletteHandle;
AData := NewDibGraphic.BitmapHandle;
finally
{ set the palete and bitmap handles to 0, because the clipboard
is responsible to delete them }
NewDibGraphic.FPaletteHandle := 0;
NewDibGraphic.FBitmapHandle := 0;
NewDibGraphic.Free;
end;
end;
*)
{--------------------------------------------------------------------------}
function TDibGraphic.GetScanLine( const Y : LongInt ) : PByteArray;
begin
Result := Pointer( LongInt(FBits) +
(FBitmapInfo.BmpHeader.biHeight-Y-1)*FScanLineSize);
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetRGB( const X,Y : LongInt ) : TRgb;
var
Index : Word;
begin
if ImageFormat = ifTrueColor then
Result := TRgb(FGetPixelFunc(ScanLine[Y], X))
else
begin
Index := PaletteIndex[X, Y];
{ carefull with TRgbQuad inversion }
TRgb(Result).Blue := FPalette.palPalEntry[Index].peBlue;
TRgb(Result).Green := FPalette.palPalEntry[Index].peGreen;
TRgb(Result).Red := FPalette.palPalEntry[Index].peRed;
TRgb(Result).Filler := 0;
end;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetRGB( const X,Y : LongInt;
const RGB : TRgb );
begin
if ImageFormat = ifTrueColor then
FSetPixelProc(ScanLine[Y], X, LongInt(RGB))
else
PaletteIndex[X, Y] := FRgbToPaletteConverter.GetIndex(RGB);
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetPaletteIndex( const X,Y : LongInt ) : Byte;
begin
if ImageFormat = ifTrueColor then
raise EEnvisionError.Create(msgImageDoesNotHavePalette);
Result := FGetPixelFunc(ScanLine[Y], X);
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetPaletteIndex( const X,Y : LongInt;
Index : Byte );
begin
if ImageFormat = ifTrueColor then
raise EEnvisionError.Create(msgImageDoesNotHavePalette);
FSetPixelProc(ScanLine[Y], X, Index);
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetXDotsPerInch : Word;
begin
Result := Round(FBitmapInfo.BmpHeader.biXPelsPerMeter/CInchesPerMeter);
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetYDotsPerInch : Word;
begin
Result := Round(FBitmapInfo.BmpHeader.biYPelsPerMeter/CInchesPerMeter);
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetXDotsPerInch( const XDpi : Word );
begin
FBitmapInfo.BmpHeader.biXPelsPerMeter := Round(XDpi*CInchesPerMeter);
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetYDotsPerInch( const YDpi : Word );
begin
FBitmapInfo.BmpHeader.biYPelsPerMeter := Round(YDpi*CInchesPerMeter);
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.AnimateTimer( Sender : TObject );
begin
if FFrames.Count = 0 then
Exit;
FAnimationTimer.Enabled := False;
try
if CurrentFrame = FrameCount then
CurrentFrame := 1
else
CurrentFrame := CurrentFrame + 1;
finally
FAnimationTimer.Interval := Self.ImageDelay;
FAnimationTimer.Enabled := True;
end;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetMultiLoad( const Multi : Boolean );
begin
FMultiLoad := Multi;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetAnimated( const InAnimated : Boolean );
begin
FAnimated := InAnimated;
if FAnimated and (FFrames.Count > 0)then
begin
FAnimationTimer.Interval := FImageDelay;
FAnimationTimer.Enabled := True;
end
else
FAnimationTimer.Enabled := False;
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetFrame(FrameNo : LongInt) : TDibGraphic;
begin
{ convert to 0 based }
FrameNo := FrameNo - 1;
if (FrameNo < 0) or (FrameNo >= FFrames.Count) then
raise EEnvisionError.Create(
Format( msgFrameDoesNotExist, [FrameNo+1]));
Result := TDibGraphic(FFrames[FrameNo]);
end;
{--------------------------------------------------------------------------}
function TDibGraphic.GetFrameCount : LongInt;
begin
Result := FFrames.Count;
end;
{--------------------------------------------------------------------------}
procedure TDibGraphic.SetCurrentFrame(FrameNo : LongInt);
begin
if (FrameNo = FCurrentFrame) then
Exit;
FrameNo := FrameNo - 1;
if (FrameNo < 0) or (FrameNo >= FFrames.Count) then
raise EEnvisionError.Create(
Format( msgFrameDoesNotExist, [FrameNo+1]));
Self.Assign(TDibGraphic(FFrames.Items[FrameNo]));
Changed(Self);
Application.ProcessMessages;
FCurrentFrame := FrameNo + 1;
end;
{--------------------------------------------------------------------------}
constructor TRgbToPaletteConverter.Create(var Palette : TMaxLogPalette);
var
Index : Integer;
begin
inherited Create;
pPalette := @Palette;
for Index := Low(Cache) to High(Cache) do
Cache[Index].Index := -1;
end;
{--------------------------------------------------------------------------}
function TRgbToPaletteConverter.GetIndex(const Color : TRgb) : Word;
var
Index : LongInt;
MinDistance : LongInt;
Distance : LongInt;
DiffRed : LongInt;
DiffGreen : LongInt;
DiffBlue : LongInt;
CacheIndex : Integer;
begin
Result := 0;
{ this calculation assumes Cache array starts at 0. }
CacheIndex := DWORD(Color) mod (High(Cache)+1);
{ check if color is in cache }
if (LongInt(Cache[CacheIndex].Index) >= 0) and
(LongInt(Cache[CacheIndex].Color) = LongInt(Color)) then
begin
Result := Cache[CacheIndex].Index;
Inc(Hits);
end
else
begin
Inc(Misses);
MinDistance := MaxLongInt;
for Index := 0 to (pPalette^.palNumEntries - 1) do
begin
DiffRed := (Color.Red - pPalette^.palPalEntry[Index].peRed);
DiffGreen := (Color.Green - pPalette^.palPalEntry[Index].peGreen);
DiffBlue := (Color.Blue - pPalette^.palPalEntry[Index].peBlue);
Distance := DiffRed*DiffRed + DiffGreen*DiffGreen + DiffBlue*DiffBlue;
if Distance < MinDistance then
begin
MinDistance := Distance;
Result := Index;
if Distance = 0 then
Break;
end;
end;
Cache[CacheIndex].Color := Color;
Cache[CacheIndex].Index := Result;
end;
end;
{--------------------------------------------------------------------------}
procedure SwapRBOnScanLine( const pScanLine : PByteArray;
const ScanLineSize : LongInt);
var
pRGB : ^TRgbQuad;
Index : LongInt;
TempByte : Byte;
Width : LongInt;
begin
Width := ScanLineSize div 3;
for Index := 0 to (Width-1) do
begin
pRGB := @pScanLine^[Index*3];
TempByte := pRGB^.rgbRed;
pRGB^.rgbRed := pRGB^.rgbBlue;
pRGB^.rgbBlue := TempByte;
end;
end;
{--------------------------------------------------------------------------}
procedure SetPixelBc1( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt );
var
pByte : ^Byte;
begin
pByte := @ScanLine^[(X div 8)];
if Value > 0 then
{ set the bit }
pByte^ := pByte^ or ($01 shl (8 - ((X mod 8) + 1)))
else
{ clear the bit }
pByte^ := pByte^ and not ($01 shl (8 - ((X mod 8) + 1)));
end;
{--------------------------------------------------------------------------}
function GetPixelBc1( const ScanLine : PByteArray;
const X : LongInt ) : LongInt;
begin
if (ScanLine^[(X div 8)] and ($01 shl (8 - ((X mod 8) + 1)))) <> 0 then
Result := 1
else
Result := 0;
end;
{--------------------------------------------------------------------------}
procedure SetPixelBc4( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt );
var
pByte : ^Byte;
begin
pByte := @ScanLine^[(X div 2)];
if (X and $01) = 0 then
pByte^ := (pByte^ and $0F) or (Value shl 4)
else
pByte^ := (pByte^ and $F0) or (Value);
end;
{--------------------------------------------------------------------------}
function GetPixelBc4( const ScanLine : PByteArray;
const X : LongInt ) : LongInt;
begin
if (X and $01) = 0 then
Result := (ScanLine^[(X div 2)] shr 4) and $0F
else
Result := ScanLine^[(X div 2)] and $0F;
end;
{--------------------------------------------------------------------------}
procedure SetPixelBc8( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt );
begin
ScanLine^[X] := Value;
end;
{--------------------------------------------------------------------------}
function GetPixelBc8( const ScanLine : PByteArray;
const X : LongInt ) : LongInt; register;
begin
Result := ScanLine^[X];
end;
{--------------------------------------------------------------------------}
procedure SetPixelBc24( const ScanLine : PByteArray;
const X : LongInt;
const Value : LongInt ); register;
var
pRGB : ^Windows.TRGBTriple;
begin
pRGB := @ScanLine^[X+X+X];
pRGB^.rgbtBlue := (Value shr 0) and $FF;
pRGB^.rgbtGreen := (Value shr 8) and $FF;
pRGB^.rgbtRed := (Value shr 16) and $FF;
end;
{--------------------------------------------------------------------------}
function GetPixelBc24( const ScanLine : PByteArray;
const X : LongInt ) : LongInt; register;
var
pRGB : ^Windows.TRGBTriple;
begin
pRGB := @ScanLine^[X+X+X];
Result := pRGB^.rgbtBlue or (pRGB^.rgbtGreen shl 8) or (pRGB^.rgbtRed shl 16);
end;
{--------------------------------------------------------------------------}
function PaletteSize( const ColorCount : Integer ) : Integer;
begin
Result := 4 + ColorCount*SizeOf(Windows.TPaletteEntry);
end;
{--------------------------------------------------------------------------}
procedure SetBWPalette( var Palette : TMaxLogPalette );
var
Index : Integer;
begin
Palette.palVersion := $0300;
Palette.palNumEntries := 2;
for Index := 0 to (Palette.palNumEntries-1) do
begin
Palette.palPalEntry[Index].peRed := 255 * Index;
Palette.palPalEntry[Index].peGreen := 255 * Index;
Palette.palPalEntry[Index].peBlue := 255 * Index;
end;
end;
{--------------------------------------------------------------------------}
procedure SetGray16Palette( var Palette : TMaxLogPalette );
var
Index : Integer;
begin
Palette.palVersion := $0300;
Palette.palNumEntries := 16;
for Index := 0 to (Palette.palNumEntries-1) do
begin
Palette.palPalEntry[Index].peRed := 17 * Index;
Palette.palPalEntry[Index].peGreen := 17 * Index;
Palette.palPalEntry[Index].peBlue := 17 * Index;
end;
end;
{--------------------------------------------------------------------------}
procedure SetGray256Palette( var Palette : TMaxLogPalette );
var
Index : Integer;
begin
Palette.palVersion := $0300;
Palette.palNumEntries := 256;
for Index := 0 to (Palette.palNumEntries-1) do
begin
Palette.palPalEntry[Index].peRed := Index;
Palette.palPalEntry[Index].peGreen := Index;
Palette.palPalEntry[Index].peBlue := Index;
end;
end;
{--------------------------------------------------------------------------}
procedure SetColor16Palette( var Palette : TMaxLogPalette );
const
Color16Entries : packed array [0..15] of TPaletteEntry =
(
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $AA),
(peRed : $00; peGreen : $AA; peBlue : $00),
(peRed : $00; peGreen : $AA; peBlue : $AA),
(peRed : $AA; peGreen : $00; peBlue : $00),
(peRed : $AA; peGreen : $00; peBlue : $AA),
(peRed : $AA; peGreen : $55; peBlue : $00),
(peRed : $AA; peGreen : $AA; peBlue : $AA),
(peRed : $55; peGreen : $55; peBlue : $55),
(peRed : $55; peGreen : $55; peBlue : $FF),
(peRed : $55; peGreen : $FF; peBlue : $55),
(peRed : $55; peGreen : $FF; peBlue : $FF),
(peRed : $FF; peGreen : $55; peBlue : $55),
(peRed : $FF; peGreen : $55; peBlue : $FF),
(peRed : $FF; peGreen : $FF; peBlue : $55),
(peRed : $FF; peGreen : $FF; peBlue : $FF)
);
begin
Palette.palVersion := $0300;
Palette.palNumEntries := 16;
Move(Color16Entries, Palette.palPalEntry, SizeOf(Color16Entries));
end;
{--------------------------------------------------------------------------}
procedure SetColor256Palette( var Palette : TMaxLogPalette );
const
Color256Entries : packed array [0..255] of TPaletteEntry =
(
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $AA),
(peRed : $00; peGreen : $AA; peBlue : $00),
(peRed : $00; peGreen : $AA; peBlue : $AA),
(peRed : $AA; peGreen : $00; peBlue : $00),
(peRed : $AA; peGreen : $00; peBlue : $AA),
(peRed : $AA; peGreen : $55; peBlue : $00),
(peRed : $AA; peGreen : $AA; peBlue : $AA),
(peRed : $55; peGreen : $55; peBlue : $55),
(peRed : $55; peGreen : $55; peBlue : $FF),
(peRed : $55; peGreen : $FF; peBlue : $55),
(peRed : $55; peGreen : $FF; peBlue : $FF),
(peRed : $FF; peGreen : $55; peBlue : $55),
(peRed : $FF; peGreen : $55; peBlue : $FF),
(peRed : $FF; peGreen : $FF; peBlue : $55),
(peRed : $FF; peGreen : $FF; peBlue : $FF),
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $14; peGreen : $14; peBlue : $14),
(peRed : $20; peGreen : $20; peBlue : $20),
(peRed : $2C; peGreen : $2C; peBlue : $2C),
(peRed : $38; peGreen : $38; peBlue : $38),
(peRed : $45; peGreen : $45; peBlue : $45),
(peRed : $51; peGreen : $51; peBlue : $51),
(peRed : $61; peGreen : $61; peBlue : $61),
(peRed : $71; peGreen : $71; peBlue : $71),
(peRed : $82; peGreen : $82; peBlue : $82),
(peRed : $92; peGreen : $92; peBlue : $92),
(peRed : $A2; peGreen : $A2; peBlue : $A2),
(peRed : $B6; peGreen : $B6; peBlue : $B6),
(peRed : $CB; peGreen : $CB; peBlue : $CB),
(peRed : $E3; peGreen : $B3; peBlue : $B3),
(peRed : $FF; peGreen : $FF; peBlue : $FF),
(peRed : $00; peGreen : $00; peBlue : $FF),
(peRed : $41; peGreen : $00; peBlue : $FF),
(peRed : $7D; peGreen : $00; peBlue : $FF),
(peRed : $BE; peGreen : $00; peBlue : $FF),
(peRed : $FF; peGreen : $00; peBlue : $FF),
(peRed : $FF; peGreen : $00; peBlue : $BE),
(peRed : $FF; peGreen : $00; peBlue : $7D),
(peRed : $FF; peGreen : $00; peBlue : $41),
(peRed : $FF; peGreen : $00; peBlue : $00),
(peRed : $FF; peGreen : $41; peBlue : $00),
(peRed : $FF; peGreen : $7D; peBlue : $00),
(peRed : $FF; peGreen : $BE; peBlue : $00),
(peRed : $FF; peGreen : $FF; peBlue : $00),
(peRed : $BE; peGreen : $FF; peBlue : $00),
(peRed : $7D; peGreen : $FF; peBlue : $00),
(peRed : $41; peGreen : $FF; peBlue : $00),
(peRed : $00; peGreen : $FF; peBlue : $00),
(peRed : $00; peGreen : $FF; peBlue : $41),
(peRed : $00; peGreen : $FF; peBlue : $7D),
(peRed : $00; peGreen : $FF; peBlue : $BE),
(peRed : $00; peGreen : $FF; peBlue : $FF),
(peRed : $00; peGreen : $BE; peBlue : $FF),
(peRed : $00; peGreen : $7D; peBlue : $FF),
(peRed : $00; peGreen : $41; peBlue : $FF),
(peRed : $7D; peGreen : $7D; peBlue : $FF),
(peRed : $9E; peGreen : $7D; peBlue : $FF),
(peRed : $BE; peGreen : $7D; peBlue : $FF),
(peRed : $DF; peGreen : $7D; peBlue : $FF),
(peRed : $FF; peGreen : $7D; peBlue : $FF),
(peRed : $FF; peGreen : $7D; peBlue : $DF),
(peRed : $FF; peGreen : $7D; peBlue : $BE),
(peRed : $FF; peGreen : $7D; peBlue : $9E),
(peRed : $FF; peGreen : $7D; peBlue : $7D),
(peRed : $FF; peGreen : $9E; peBlue : $7D),
(peRed : $FF; peGreen : $BE; peBlue : $7D),
(peRed : $FF; peGreen : $DF; peBlue : $7D),
(peRed : $FF; peGreen : $FF; peBlue : $7D),
(peRed : $DF; peGreen : $FF; peBlue : $7D),
(peRed : $BE; peGreen : $FF; peBlue : $7D),
(peRed : $9E; peGreen : $FF; peBlue : $7D),
(peRed : $7D; peGreen : $FF; peBlue : $7D),
(peRed : $7D; peGreen : $FF; peBlue : $9E),
(peRed : $7D; peGreen : $FF; peBlue : $BE),
(peRed : $7D; peGreen : $FF; peBlue : $DF),
(peRed : $7D; peGreen : $FF; peBlue : $FF),
(peRed : $7D; peGreen : $DF; peBlue : $FF),
(peRed : $7D; peGreen : $BE; peBlue : $FF),
(peRed : $7D; peGreen : $9E; peBlue : $FF),
(peRed : $B6; peGreen : $B6; peBlue : $FF),
(peRed : $C7; peGreen : $B6; peBlue : $FF),
(peRed : $DB; peGreen : $B6; peBlue : $FF),
(peRed : $EB; peGreen : $B6; peBlue : $FF),
(peRed : $FF; peGreen : $B6; peBlue : $FF),
(peRed : $DF; peGreen : $B6; peBlue : $EB),
(peRed : $FF; peGreen : $B6; peBlue : $DB),
(peRed : $FF; peGreen : $B6; peBlue : $C7),
(peRed : $FF; peGreen : $B6; peBlue : $B6),
(peRed : $FF; peGreen : $C7; peBlue : $B6),
(peRed : $FF; peGreen : $DB; peBlue : $B6),
(peRed : $FF; peGreen : $EB; peBlue : $B6),
(peRed : $FF; peGreen : $FF; peBlue : $B6),
(peRed : $EB; peGreen : $FF; peBlue : $B6),
(peRed : $DB; peGreen : $FF; peBlue : $B6),
(peRed : $C7; peGreen : $FF; peBlue : $B6),
(peRed : $B6; peGreen : $DF; peBlue : $B6),
(peRed : $B6; peGreen : $FF; peBlue : $C7),
(peRed : $B6; peGreen : $FF; peBlue : $DB),
(peRed : $B6; peGreen : $FF; peBlue : $EB),
(peRed : $B6; peGreen : $FF; peBlue : $FF),
(peRed : $B6; peGreen : $EB; peBlue : $FF),
(peRed : $B6; peGreen : $DB; peBlue : $FF),
(peRed : $B6; peGreen : $C7; peBlue : $FF),
(peRed : $00; peGreen : $00; peBlue : $71),
(peRed : $1C; peGreen : $00; peBlue : $71),
(peRed : $38; peGreen : $00; peBlue : $71),
(peRed : $55; peGreen : $00; peBlue : $71),
(peRed : $71; peGreen : $00; peBlue : $71),
(peRed : $71; peGreen : $00; peBlue : $55),
(peRed : $71; peGreen : $00; peBlue : $38),
(peRed : $71; peGreen : $00; peBlue : $1C),
(peRed : $71; peGreen : $00; peBlue : $00),
(peRed : $71; peGreen : $1C; peBlue : $00),
(peRed : $71; peGreen : $38; peBlue : $00),
(peRed : $71; peGreen : $55; peBlue : $00),
(peRed : $71; peGreen : $71; peBlue : $00),
(peRed : $55; peGreen : $71; peBlue : $00),
(peRed : $38; peGreen : $71; peBlue : $00),
(peRed : $1C; peGreen : $71; peBlue : $00),
(peRed : $00; peGreen : $71; peBlue : $00),
(peRed : $00; peGreen : $71; peBlue : $1C),
(peRed : $00; peGreen : $71; peBlue : $38),
(peRed : $00; peGreen : $71; peBlue : $55),
(peRed : $00; peGreen : $71; peBlue : $71),
(peRed : $00; peGreen : $55; peBlue : $71),
(peRed : $00; peGreen : $38; peBlue : $71),
(peRed : $00; peGreen : $1C; peBlue : $71),
(peRed : $38; peGreen : $38; peBlue : $71),
(peRed : $45; peGreen : $38; peBlue : $71),
(peRed : $55; peGreen : $38; peBlue : $71),
(peRed : $61; peGreen : $38; peBlue : $71),
(peRed : $71; peGreen : $38; peBlue : $71),
(peRed : $71; peGreen : $38; peBlue : $61),
(peRed : $71; peGreen : $38; peBlue : $55),
(peRed : $71; peGreen : $38; peBlue : $45),
(peRed : $71; peGreen : $38; peBlue : $38),
(peRed : $71; peGreen : $45; peBlue : $38),
(peRed : $71; peGreen : $55; peBlue : $38),
(peRed : $71; peGreen : $61; peBlue : $38),
(peRed : $71; peGreen : $71; peBlue : $38),
(peRed : $61; peGreen : $71; peBlue : $38),
(peRed : $55; peGreen : $71; peBlue : $38),
(peRed : $45; peGreen : $71; peBlue : $38),
(peRed : $38; peGreen : $71; peBlue : $38),
(peRed : $38; peGreen : $71; peBlue : $45),
(peRed : $38; peGreen : $71; peBlue : $55),
(peRed : $38; peGreen : $71; peBlue : $61),
(peRed : $38; peGreen : $71; peBlue : $71),
(peRed : $38; peGreen : $61; peBlue : $71),
(peRed : $38; peGreen : $55; peBlue : $71),
(peRed : $38; peGreen : $45; peBlue : $71),
(peRed : $51; peGreen : $51; peBlue : $71),
(peRed : $59; peGreen : $51; peBlue : $71),
(peRed : $61; peGreen : $51; peBlue : $71),
(peRed : $69; peGreen : $51; peBlue : $71),
(peRed : $71; peGreen : $51; peBlue : $71),
(peRed : $71; peGreen : $51; peBlue : $69),
(peRed : $71; peGreen : $51; peBlue : $61),
(peRed : $71; peGreen : $51; peBlue : $59),
(peRed : $71; peGreen : $51; peBlue : $51),
(peRed : $71; peGreen : $59; peBlue : $51),
(peRed : $71; peGreen : $61; peBlue : $51),
(peRed : $71; peGreen : $69; peBlue : $51),
(peRed : $71; peGreen : $71; peBlue : $51),
(peRed : $69; peGreen : $71; peBlue : $51),
(peRed : $61; peGreen : $71; peBlue : $51),
(peRed : $59; peGreen : $71; peBlue : $51),
(peRed : $51; peGreen : $71; peBlue : $51),
(peRed : $51; peGreen : $71; peBlue : $59),
(peRed : $51; peGreen : $71; peBlue : $61),
(peRed : $51; peGreen : $71; peBlue : $69),
(peRed : $51; peGreen : $71; peBlue : $71),
(peRed : $51; peGreen : $69; peBlue : $71),
(peRed : $51; peGreen : $61; peBlue : $71),
(peRed : $51; peGreen : $59; peBlue : $71),
(peRed : $00; peGreen : $00; peBlue : $41),
(peRed : $10; peGreen : $00; peBlue : $41),
(peRed : $20; peGreen : $00; peBlue : $41),
(peRed : $30; peGreen : $00; peBlue : $41),
(peRed : $41; peGreen : $00; peBlue : $41),
(peRed : $41; peGreen : $00; peBlue : $30),
(peRed : $41; peGreen : $00; peBlue : $20),
(peRed : $41; peGreen : $00; peBlue : $10),
(peRed : $41; peGreen : $00; peBlue : $00),
(peRed : $41; peGreen : $10; peBlue : $00),
(peRed : $41; peGreen : $20; peBlue : $00),
(peRed : $41; peGreen : $30; peBlue : $00),
(peRed : $41; peGreen : $41; peBlue : $00),
(peRed : $30; peGreen : $41; peBlue : $00),
(peRed : $20; peGreen : $41; peBlue : $00),
(peRed : $10; peGreen : $41; peBlue : $00),
(peRed : $00; peGreen : $41; peBlue : $00),
(peRed : $00; peGreen : $41; peBlue : $10),
(peRed : $00; peGreen : $41; peBlue : $20),
(peRed : $00; peGreen : $41; peBlue : $30),
(peRed : $00; peGreen : $41; peBlue : $41),
(peRed : $00; peGreen : $30; peBlue : $41),
(peRed : $00; peGreen : $20; peBlue : $41),
(peRed : $00; peGreen : $10; peBlue : $41),
(peRed : $20; peGreen : $20; peBlue : $41),
(peRed : $28; peGreen : $20; peBlue : $41),
(peRed : $30; peGreen : $20; peBlue : $41),
(peRed : $38; peGreen : $20; peBlue : $41),
(peRed : $41; peGreen : $20; peBlue : $41),
(peRed : $41; peGreen : $20; peBlue : $38),
(peRed : $41; peGreen : $20; peBlue : $30),
(peRed : $41; peGreen : $20; peBlue : $28),
(peRed : $41; peGreen : $20; peBlue : $20),
(peRed : $41; peGreen : $28; peBlue : $20),
(peRed : $41; peGreen : $30; peBlue : $20),
(peRed : $41; peGreen : $38; peBlue : $20),
(peRed : $41; peGreen : $41; peBlue : $20),
(peRed : $38; peGreen : $41; peBlue : $20),
(peRed : $30; peGreen : $41; peBlue : $20),
(peRed : $28; peGreen : $41; peBlue : $20),
(peRed : $20; peGreen : $41; peBlue : $20),
(peRed : $20; peGreen : $41; peBlue : $28),
(peRed : $20; peGreen : $41; peBlue : $30),
(peRed : $20; peGreen : $41; peBlue : $38),
(peRed : $20; peGreen : $41; peBlue : $41),
(peRed : $20; peGreen : $38; peBlue : $41),
(peRed : $20; peGreen : $30; peBlue : $41),
(peRed : $20; peGreen : $28; peBlue : $41),
(peRed : $2C; peGreen : $2C; peBlue : $41),
(peRed : $30; peGreen : $2C; peBlue : $41),
(peRed : $34; peGreen : $2C; peBlue : $41),
(peRed : $3C; peGreen : $2C; peBlue : $41),
(peRed : $41; peGreen : $2C; peBlue : $41),
(peRed : $41; peGreen : $2C; peBlue : $3C),
(peRed : $41; peGreen : $2C; peBlue : $34),
(peRed : $41; peGreen : $2C; peBlue : $30),
(peRed : $41; peGreen : $2C; peBlue : $2C),
(peRed : $41; peGreen : $30; peBlue : $2C),
(peRed : $41; peGreen : $34; peBlue : $2C),
(peRed : $41; peGreen : $3C; peBlue : $2C),
(peRed : $41; peGreen : $41; peBlue : $2C),
(peRed : $3C; peGreen : $41; peBlue : $2C),
(peRed : $34; peGreen : $41; peBlue : $2C),
(peRed : $30; peGreen : $41; peBlue : $2C),
(peRed : $2C; peGreen : $41; peBlue : $2C),
(peRed : $2C; peGreen : $41; peBlue : $30),
(peRed : $2C; peGreen : $41; peBlue : $34),
(peRed : $2C; peGreen : $41; peBlue : $3C),
(peRed : $2C; peGreen : $41; peBlue : $41),
(peRed : $2C; peGreen : $3C; peBlue : $41),
(peRed : $2C; peGreen : $34; peBlue : $41),
(peRed : $2C; peGreen : $30; peBlue : $41),
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $00),
(peRed : $00; peGreen : $00; peBlue : $00)
);
begin
Palette.palVersion := $0300;
Palette.palNumEntries := 256;
Move(Color256Entries, Palette.palPalEntry, SizeOf(Color256Entries));
end;
{--------------------------------------------------------------------------}
procedure InitPalettes;
begin
GetMem(pBlackWhitePalette, PaletteSize(2));
SetBWPalette(pBlackWhitePalette^);
GetMem(pGray16Palette, PaletteSize(16));
SetGray16Palette(pGray16Palette^);
GetMem(pGray256Palette, PaletteSize(256));
SetGray256Palette(pGray256Palette^);
GetMem(pColor16Palette, PaletteSize(16));
SetColor16Palette(pColor16Palette^);
GetMem(pColor256Palette, PaletteSize(256));
SetColor256Palette(pColor256Palette^);
end;
{--------------------------------------------------------------------------}
procedure FreePalette( const pPalette : PMaxLogPalette );
begin
FreeMem(pPalette, PaletteSize(pPalette^.palNumEntries));
end;
{--------------------------------------------------------------------------}
initialization
ScreenGamma := 2.2;
InitPalettes;
if DibClasses = nil then
DibClasses := TStringList.Create;
TPicture.RegisterClipboardFormat(CF_BITMAP, TDibGraphic);
{$ifdef __Evaluation}
MessageDlg( 'This software was created with an evaluation'#13 +
'version of the Envision Image Library. Contact'#13 +
'your program vendor to obtain a licensed copy.',
mtInformation, [mbOk], 0);
{$endif}
finalization
{ unregister the TDibGraphic clipboard format, otherwise
a GPF would occur when closing Delphi at design time.}
TPicture.UnregisterGraphicClass(TDibGraphic);
DibClasses.Free;
FreePalette(pBlackWhitePalette);
FreePalette(pGray16Palette);
FreePalette(pGray256Palette);
FreePalette(pColor16Palette);
FreePalette(pColor256Palette);
end.
|
unit BasicProfitCalc;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm6 = class(TForm)
ListBox1: TListBox;
Label1: TLabel;
Label2: TLabel;
Edit1: TEdit;
Edit2: TEdit;
Button1: TButton;
Label3: TLabel;
Edit3: TEdit;
procedure calculateNextBetCost(round: integer);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form6: TForm6;
multiply, targetProfitPerRound: Integer;
computedBetList, computedProfitList, computedCostList: Array of Extended;
implementation
{$R *.dfm}
procedure TForm6.calculateNextBetCost(round: integer);
var index: Integer;
addedCost, newBet:extended;
begin
addedCost := 0;
newBet := 0;
for index := Low(computedBetList) to High(computedBetList) do
begin
addedCost := addedCost + computedBetList[index];
end;
setLength(computedBetList, length(computedBetList) + 1);
setLength(computedProfitList, length(computedProfitList) + 1);
setLength(computedCostList, length(computedCostList) + 1);
while ((newBet * multiply) - addedCost - newBet < targetProfitPerRound) do
newBet := newBet + 1;
computedBetList[high(computedBetList)] := newBet;
if (high(computedCostList) - 1 >= 0) then
computedCostList[high(computedCostList)] := computedCostList[high(computedCostList) - 1] + newBet
else
computedCostList[high(computedCostList)] := newBet;
computedProfitList[high(computedProfitList)] := (newBet * multiply) - computedCostList[high(computedBetList)];
end;
procedure TForm6.Button1Click(Sender: TObject);
var i: Integer;
begin
listbox1.Clear;
multiply := strtoint(edit1.Text);
targetProfitPerRound := strtoint(edit2.Text);
setLength(computedCostList, 0);
setLength(computedProfitList, 0);
setLength(computedBetList, 0);
listbox1.Items.Add('Round, TotalCost, Profit');
for I := 1 to strtoint(edit3.Text) do
begin
calculateNextBetCost(i-1);
listbox1.Items.Add(inttostr(i) + '/' + floattostr(computedCostList[i-1]) + '/' + floattostr(computedProfitList[i-1]) + '/' + floattostr(computedBetList[i-1]));
end;
end;
end.
|
unit uCadastros;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Data.DB,
Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.Buttons, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, uVariaveis;
type
TFCadastros = class(TForm)
PageControl1: TPageControl;
tsBancos: TTabSheet;
Label1: TLabel;
Label2: TLabel;
edtCodBancos: TEdit;
edtDescricaoBancos: TEdit;
Panel1: TPanel;
btnGravar: TBitBtn;
btnExcluir: TBitBtn;
btnSair: TBitBtn;
DSCadastros: TDataSource;
FDCadastros: TFDQuery;
dbCadastros: TDBGrid;
tsConta: TTabSheet;
Label3: TLabel;
edtBancoContaCorrente: TEdit;
Label4: TLabel;
edtDescricaoConta: TEdit;
Label5: TLabel;
edtContaCorrente: TEdit;
edtAgenciaConta: TEdit;
Label6: TLabel;
btnCons_Bancos: TBitBtn;
procedure btnSairClick(Sender: TObject);
procedure btnCons_BancosClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure dbCadastrosDblClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
private
procedure pcdCriaCamposTabela(piNumeroCampo, piTamanhoCampo: Integer;
psTitulo, psNomeCampo: String; poAlinhamento: System.Classes.TAlignment;
var poDBGrid: TDBGrid);
procedure pcdColunasDBGRID(Tabela: TTipoTabelaCadastro);
procedure pcdGravaDados;
procedure LimpaDados(voTabela: TTipoTabelaCadastro);
procedure pcdExcluirDados(voTabelas: TTipoTabelaCadastro);
{ Private declarations }
public
vgoTipoTabela : TTipoTabelaCadastro;
procedure HabilitaPaletas(vPaleta: TTabSheet);
{ Public declarations }
end;
var
FCadastros: TFCadastros;
implementation
{$R *.dfm}
uses uConsultas, uPrincipal, uFuncoes, udmPrincipal;
procedure TFCadastros.btnCons_BancosClick(Sender: TObject);
begin
Application.CreateForm(TFConsultas, FConsultas);
FConsultas.vgsTabelaConsulta := ttcBanco;
FConsultas.vgsFormConsulta := tfcCadastro;
FConsultas.ShowModal;
edtBancoContaCorrente.SetFocus;
FreeAndNil(FConsultas);
end;
procedure TFCadastros.btnExcluirClick(Sender: TObject);
begin
if vgoTipoTabela = tt_Banco then
begin
if Trim(edtCodBancos.Text) = '' then
begin
ShowMessage('Banco inválido para exclusão.');
edtCodBancos.SetFocus;
Abort;
end;
end
else if vgoTipoTabela = tt_Conta then
begin
if Trim(edtBancoContaCorrente.Text) = '' then
begin
ShowMessage('Banco inválido para exclusão.');
edtBancoContaCorrente.SetFocus;
Abort;
end;
if Trim(edtContaCorrente.Text) = '' then
begin
ShowMessage('Conta Corrente inválida para exclusão.');
edtContaCorrente.SetFocus;
Abort;
end;
end;
pcdExcluirDados(vgoTipoTabela);
end;
procedure TFCadastros.btnGravarClick(Sender: TObject);
begin
if vgoTipoTabela = tt_Banco then
begin
if Trim(edtCodBancos.Text) = '' then
begin
ShowMessage('Digite um banco válido.');
edtCodBancos.SetFocus;
Abort;
end;
if Trim(edtDescricaoBancos.Text) = '' then
begin
ShowMessage('Digite uma descrição válida para o Banco.');
edtDescricaoBancos.SetFocus;
Abort;
end;
end
else if vgoTipoTabela = tt_Conta then
begin
if Trim(edtBancoContaCorrente.Text) = '' then
begin
ShowMessage('Digite um banco válido.');
edtBancoContaCorrente.SetFocus;
Abort;
end;
if Trim(edtAgenciaConta.Text) = '' then
begin
ShowMessage('Digite uma agência válida.');
edtAgenciaConta.SetFocus;
Abort;
end;
if Trim(edtContaCorrente.Text) = '' then
begin
ShowMessage('Digite um número de conta corrente válido.');
edtContaCorrente.SetFocus;
Abort;
end;
if Trim(edtDescricaoConta.Text) = '' then
begin
ShowMessage('Digite uma descrição válida para a conta corrente.');
edtDescricaoConta.SetFocus;
Abort;
end;
end;
pcdGravaDados;
end;
procedure TFCadastros.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure TFCadastros.dbCadastrosDblClick(Sender: TObject);
begin
if vgoTipoTabela = tt_Banco then
begin
edtCodBancos.Text := FDCadastros.FieldByName('BC_CODIGO').AsString;
edtDescricaoBancos.Text := FDCadastros.FieldByName('BC_DESCRICAO').AsString;
end
else if vgoTipoTabela = tt_Conta then
begin
edtBancoContaCorrente.Text := FDCadastros.FieldByName('CC_BANCO').AsString;
edtAgenciaConta.Text := FDCadastros.FieldByName('CC_AGENCIA').AsString;
edtContaCorrente.Text := FDCadastros.FieldByName('CC_NUMERO').AsString;
edtDescricaoConta.Text := FDCadastros.FieldByName('CC_DESCRICAO').AsString;
end;
end;
procedure TFCadastros.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
Perform(Wm_NextDlgCtl,0,0);
Key := #0;
end
else if Key = #27 then {ESC}
begin
Close;
end;
end;
procedure TFCadastros.FormShow(Sender: TObject);
begin
FPrincipal.PadronizaDbGrid(dbCadastros);
end;
procedure TFCadastros.pcdColunasDBGRID(Tabela: TTipoTabelaCadastro);
var
I: Integer;
begin
dbCadastros.Columns.Clear;
if Tabela = tt_Banco then
begin
pcdCriaCamposTabela(0, 80, 'Codigo', 'BC_CODIGO', System.Classes.taLeftJustify, dbCadastros);
pcdCriaCamposTabela(1, 360, 'Descrição', 'BC_DESCRICAO', System.Classes.taLeftJustify, dbCadastros);
end
else if Tabela = tt_Conta then
begin
pcdCriaCamposTabela(0, 40, 'Banco', 'CC_BANCO', System.Classes.taLeftJustify, dbCadastros);
pcdCriaCamposTabela(1, 55, 'Agência', 'CC_AGENCIA', System.Classes.taLeftJustify, dbCadastros);
pcdCriaCamposTabela(2, 95, 'Conta Corrente', 'CC_NUMERO', System.Classes.taLeftJustify, dbCadastros);
pcdCriaCamposTabela(3, 250, 'Descrição', 'CC_DESCRICAO', System.Classes.taLeftJustify, dbCadastros);
end;
for I := 0 to dbCadastros.Columns.Count - 1 do
begin
dbCadastros.Columns[i].Title.Font.Style := [fsBold];
end;
end;
procedure TFCadastros.pcdCriaCamposTabela(piNumeroCampo, piTamanhoCampo: Integer; psTitulo, psNomeCampo: String; poAlinhamento: System.Classes.TAlignment; var poDBGrid: TDBGrid);
begin
poDBGrid.Columns.Add;
poDBGrid.Columns[piNumeroCampo].Title.Caption := psTitulo;
poDBGrid.Columns[piNumeroCampo].FieldName := psNomeCampo;
poDBGrid.Columns[piNumeroCampo].Width := piTamanhoCampo;
poDBGrid.Columns[piNumeroCampo].Alignment := poAlinhamento;
end;
procedure TFCadastros.HabilitaPaletas(vPaleta: TTabSheet);
begin
tsBancos.TabVisible := vPaleta = tsBancos;
tsConta.TabVisible := vPaleta = tsConta;
FDCadastros.Connection := vgConexao;
if tsBancos.TabVisible then
begin
pcdCarregaDadosCadastro(FDCadastros, tt_Banco);
pcdColunasDBGRID(tt_Banco)
end
else if tsConta.TabVisible then
begin
pcdCarregaDadosCadastro(FDCadastros, tt_Conta);
pcdColunasDBGRID(tt_Conta);
end;
end;
procedure TFCadastros.pcdGravaDados;
var
FDGravar : TFDQuery;
begin
FDGravar := TFDQuery.Create(nil);
try
FDGravar.Close;
FDGravar.Connection := vgConexao;
if vgoTipoTabela = tt_Conta then
begin
FDGravar.Close;
FDGravar.SQL.Clear;
FDGravar.SQL.Add('SELECT * FROM CONTAS WHERE CC_NUMERO = :NUMERO AND CC_BANCO = :BANCO');
FDGravar.ParamByName('NUMERO').AsString := edtContaCorrente.Text;
FDGravar.ParamByName('BANCO').AsString := edtBancoContaCorrente.Text;
FDGravar.Open;
if FDGravar.IsEmpty then
begin
FDGravar.SQL.Clear;
FDGravar.SQL.Add('INSERT INTO CONTAS (CC_NUMERO, CC_BANCO, CC_DESCRICAO, CC_AGENCIA) VALUES (:CC_NUMERO, :CC_BANCO, :CC_DESCRICAO, :CC_AGENCIA)');
end
else
begin
FDGravar.SQL.Add('UPDATE CONTAS');
FDGravar.SQL.Add('SET CC_DESCRICAO = :CC_DESCRICAO,');
FDGravar.SQL.Add(' CC_AGENCIA = :CC_AGENCIA');
FDGravar.SQL.Add('WHERE (CC_NUMERO = :CC_NUMERO) AND (CC_BANCO = :CC_BANCO)');
end;
FDGravar.ParamByName('CC_NUMERO').AsString := edtContaCorrente.Text;
FDGravar.ParamByName('CC_BANCO').AsString := edtBancoContaCorrente.Text;
FDGravar.ParamByName('CC_DESCRICAO').AsString := edtDescricaoConta.Text;
FDGravar.ParamByName('CC_AGENCIA').AsString := edtAgenciaConta.Text;
end
else if vgoTipoTabela = tt_Banco then
begin
FDGravar.Close;
FDGravar.SQL.Clear;
FDGravar.SQL.Add('SELECT * FROM BANCOS WHERE BC_CODIGO = :BANCO');
FDGravar.ParamByName('BANCO').AsString := edtCodBancos.Text;
FDGravar.Open;
if FDGravar.IsEmpty then
begin
FDGravar.SQL.Clear;
FDGravar.SQL.Add('INSERT INTO BANCOS (BC_CODIGO, BC_DESCRICAO) VALUES (:BC_CODIGO, :BC_DESCRICAO)');
end
else
begin
FDGravar.SQL.Clear;
FDGravar.SQL.Clear;
FDGravar.SQL.Add('UPDATE BANCOS');
FDGravar.SQL.Add('SET BC_DESCRICAO = :BC_DESCRICAO');
FDGravar.SQL.Add('WHERE (BC_CODIGO = :BC_CODIGO)');
end;
FDGravar.ParamByName('BC_CODIGO').AsString := edtCodBancos.Text;
FDGravar.ParamByName('BC_DESCRICAO').AsString := edtDescricaoBancos.Text;
end;
FDGravar.ExecSQL;
finally
pcdCarregaDadosCadastro(FDCadastros, vgoTipoTabela);
LimpaDados(vgoTipoTabela);
FreeAndNil(FDGravar);
end;
end;
procedure TFCadastros.LimpaDados(voTabela : TTipoTabelaCadastro);
begin
if voTabela = tt_Banco then
begin
edtCodBancos.Clear;
edtDescricaoBancos.Clear;
if edtCodBancos.CanFocus then
edtCodBancos.SetFocus;
end
else if voTabela = tt_Conta then
begin
edtBancoContaCorrente.Clear;
edtDescricaoConta.Clear;
edtAgenciaConta.Clear;
edtContaCorrente.Clear;
if edtBancoContaCorrente.CanFocus then
edtBancoContaCorrente.SetFocus;
end
end;
procedure TFCadastros.pcdExcluirDados(voTabelas : TTipoTabelaCadastro);
var
FDGravar : TFDQuery;
begin
FDGravar := TFDQuery.Create(nil);
try
FDGravar.Close;
FDGravar.Connection := vgConexao;
if voTabelas = tt_Conta then
begin
if MessageDlg('Deseja realmente excluir a conta '+edtDescricaoConta.Text+' ?', MtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
FDGravar.SQL.Clear;
FDGravar.SQL.Add('DELETE FROM CONTAS WHERE CC_NUMERO = :NUMERO AND CC_BANCO = :BANCO');
FDGravar.ParamByName('NUMERO').AsString := edtContaCorrente.Text;
FDGravar.ParamByName('BANCO').AsString := edtBancoContaCorrente.Text;
FDGravar.ExecSQL;
end;
end
else if voTabelas = tt_Banco then
begin
if MessageDlg('Deseja realmente excluir o banco '+edtDescricaoBancos.Text+' ?', MtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
FDGravar.SQL.Clear;
FDGravar.SQL.Add('DELETE FROM BANCOS WHERE BC_CODIGO = :BANCO');
FDGravar.ParamByName('BANCO').AsString := edtCodBancos.Text;
FDGravar.ExecSQL;
end;
end;
finally
pcdCarregaDadosCadastro(FDCadastros, vgoTipoTabela);
LimpaDados(vgoTipoTabela);
FreeAndNil(FDGravar);
end;
end;
end.
|
(*
DLL HyTech для Win95/NT
HyTech 2.56 Copyright (c) 1993, 99 by SKAZ_M Ltd
*)
Unit HTW32;
INTERFACE
{$A-}
(* Эти переменные носят только информационный характер, менять их нельзя *)
Const FNAME_LEN = 10; (* Длина имени поля в таблице *)
Const TFULL_LEN = 140; (* Длина буфера для полного имени таблицы *)
Const TNAME_LEN = 8; (* Длина имени таблицы *)
Const TPATH_LEN = 128; (* Длина полного пути на таблицу *)
Const MAX_BUF_LEN = $FFF0; (* Максимальная длина буфера для чтения *)
Const MAX_REC_LEN = $FFED; (* Максимальная длина записи в таблице *)
Const MAX_REC_NUM = $FFFFFE;(* Максимальное число записей в таблице *)
Const MAX_SORT_LEN = $FFED; (* Максимальная длина элемента сортировки *)
Const MAX_SORT_ORDER = 63; (* Максимальное число полей сортировки *)
Const MAX_TAB_ELEM = 4095; (* Максимальное число элементов в таблице *)
Const MAX_TAB_LINK = 64; (* Максимальное число связанных таблиц *)
Const MAX_TAB_NUM = 96; (* Максимальное число обрабатываемых таблиц *)
Const CODE_LEN = 8; (* Максимальная длина ключа в кодификаторе *)
Const MAX_CODER_CNT = 255; (* Максимальное число кодификаторов *)
(* Возможные значения класса элементов *)
Const EC_FIELD = 0; (* Элемент - поле *)
Const EC_GROUP = 1; (* Элемент - группа *)
Const EC_SUBSTR = 2; (* Элемент - подстрока *)
(* Возможные значения типов ключа для элементов *)
Const EK_NOTKEY = 0; (* Элемент не ключ *)
Const EK_COMMON = 1; (* Обычный ключ *)
Const EK_UNIQUE = 2; (* Уникальный ключ *)
Const EK_SURRGT = 3; (* Суррогатный ключ *)
(* Модификаторы атрибутов ключа (допустимы только для полей) *)
Const EK_MASK = $C0; (* Маска для отделения модификаторов ключа от типа *)
Const EK_AUTO = $40; (* Уникальный ключ является автоинкрементным *)
Const EK_NULL = $80; (* Поле (не только ключ) допускает NULL значения *)
(* Возможные значения типа элементов *)
Const ET_CHAR = 0; (* Массив символов длиной не более заданной *)
Const ET_ARRA = 1; (* Массив байтов заданной длины *)
Const ET_BYTE = 2; (* Элемент - короткое целое (1 байт) без знака *)
Const ET_INTR = 3; (* Элемент - целое со знаком *)
Const ET_WORD = 4; (* Элемент - целое без знака *)
Const ET_DATE = 5; (* Дата - целое без знака *)
Const ET_NMBR = 6; (* Номер - 3-х байтовое целое без знака *)
Const ET_LONG = 7; (* Элемент - длинное целое со знаком *)
Const ET_DWRD = 8; (* Элемент - длинное целое без знака *)
Const ET_FLOA = 9; (* Элемент - single *)
Const ET_CURR =10; (* Деньги - double *)
Const ET_DFLT =11; (* Элемент - double *)
(*======================== Новые типы ====================*)
Type
CHANDLE = SmallInt; (* Обработчик кодификатора *)
RHANDLE = LongInt; (* Обработчик для записи *)
LPRHANDLE=^RHANDLE; (* Указатель на обработчик *)
THANDLE = SmallInt; (* Обработчик для таблицы *)
LPTHANDLE=^THANDLE; (* Указатель на обработчик *)
PSmallInt=^SmallInt; (* Указатель на SmallInt *)
NameStr = Array[0..TNAME_LEN] of Char;(* Для хранения имени файла или станции *)
PathStr = Array[0..TPATH_LEN] of Char;(* Для хранения пути на файлы *)
(* Блок Доступа к Сервису (БДС) *)
SAB=Record
gFoundCnt:LongInt; (* Число элементов в результате *)
nRetCode :SmallInt; (* Код завершения операции *)
mPrivate :Array[1..110] of Char; (* Системные пеpеменные *)
End;
PSAB=^SAB; (* Ссылка на БДС *)
LPSAB=^SAB; (* Ссылка на БДС *)
LPPSAB=^LPSAB; (* Адрес ссылки на БДС *)
(* Описатель атрибута таблицы (поля, группы или подстроки *)
(* Эта структура заполняется функцией htTableElement *)
ELEMENT=Record
wLength: Word; (* Длина элемента *)
wOffset: Word; (* Смещение элемента в записи *)
cClass : Byte; (* Класс элемента *)
cType : Byte; (* Тип элемента *)
cKey : Byte; (* Пpизнак ключа *)
mName : Array[0..FNAME_LEN] of Char; (* Имя элемента (ASCIIZ строка) *)
End;
LPELEMENT =^ELEMENT;
(* Далее следует описание call-back процедур, адреса которых *)
(* могут быть заданы при инициализации СУБД в качестве последних *)
(* членов структуры INIT. Коды сообщений для функций описаны в HTERRS.PAS *)
(* Сообщение об ошибке при выполнении операции *)
UFERM=Procedure(
nMessID:SmallInt (* Номер сообщения (код завершения) *)
);
LPUFERM=^UFERM;
(* Информационное сообщение об ошибке или завершении операции *)
UFINF=Procedure(
nInfoID: SmallInt; (* Номер информационного сообщения *)
gParm1: LongInt; (* Первый числовой параметр *)
gParm2: LongInt; (* Второй числовой параметр *)
fpStr: PChar (* Символьный параметр (ASCIIZ строка) *)
);
LPUFINF=^UFINF;
(* Сообщение об ошибке В/В *)
UFIOM=Procedure(
fpFileName: PChar; (* Имя файла (ASCIIZ строка), вызвавшего ошибку *)
nIoCode: SmallInt;(* Код операции В/В, вызвавшей ошибку *)
nDosError: SmallInt (* Код ошибки, сообщенный DOS *)
);
LPUFIOM=^UFIOM;
(* Пользовательские процедуры работы с прогресс-индикатором *)
(* Будут вызываться СУБД при выполнении длительных операций *)
(* Инициализация прогресс-индикатора *)
UFPIS=Procedure(
nPindID: SmallInt;(* Номер сообщения прогресс-индикатора *)
dwLimit: Cardinal;(* Предельное число элементов индикатора *)
fpName: PChar (* Строковый (ASCIIZ) параметр *)
);
LPUFPIS=^UFPIS;
(* Продвижение прогресс-индикатора *)
UFPID=Procedure(
wDelta: Word (* Очередное число обработанных элементов *)
);
LPUFPID=^UFPID;
(* Снятие прогресс-индикатора *)
UFPIP=Procedure;
LPUFPIP=^UFPIP;
(* Активизация других процессов *)
UFYLD=Procedure;
LPUFYLD=^UFYLD;
(* Call-back функции инициализации по умолчанию *)
(* Для вызова встроенных call-back функций следует *)
(* Задать вместо адресов Nil *)
(* Игнорирование соответствующих call-back функций инициализации *)
(* Для полного запрещения вызова call-back функций следует *)
(* задать вместо адресов Pointer(LongInt(-1)) *)
(* Описатель параметров функции инициализации *)
(* Заполняется до вызова htInit *)
INIT=Record
nTableCnt:SmallInt; (* Число таблиц, с которыми будут работать (1-64) *)
nTaskCnt:SmallInt; (* Число файлов, которые может открыть задача *)
nHtCnt:SmallInt; (* Число файлов, которые может открыть СУБД *)
nLockTimeOut:SmallInt; (* Таймаут разделения ресурсов сети *)
nPollDelay:SmallInt; (* Задержка опроса сети (тиков) *)
nTransTimeOut:SmallInt; (* Таймаут выполнения транзакций *)
nTrsMode:SmallInt; (* Режимы механизма транзакций *)
fpTmpPath: PChar; (* Каталог для создания временных файлов *)
fpNetPath: PChar; (* Каталог для сетевых замков *)
fpNetName: PChar; (* Имя станции в сети (до 8 символов) *)
fpTrtPath: PChar; (* Каталог журнала транзакций *)
fpfInfo: LPUFINF; (* Функция информационного сообщения *)
fpfIoMess: LPUFIOM; (* Функция сообщения об ошибке В/В *)
fpfErrMess:LPUFERM; (* Функция сообщения об ошибке *)
fpfPiStart:LPUFPIS; (* Функция инициализации прогресс-индикатора *)
fpfPiDraw: LPUFPID; (* Функция продвижения прогресс-индикатора *)
fpfPiStop: LPUFPIP; (* Функция снятия прогресс-индикатора *)
fpfYield: LPUFYLD; (* Функция активации других процессов *)
gHeapCtrl: LongInt; (* <0 - размер кучи пользователя (остальное - СУБД) *)
(* =0 - обе кучи по умолчанию *)
(* >0 - размер кучи СУБД (остальное - пользователю) *)
gHeapTask: LongInt; (* Куча экземпляра СУБД для внутреннего использования *)
End;
LPINIT = ^INIT;
(* Описатель основных характеристик открытой таблицы *)
(* Эта структура заполняется функцией htTableInfo *)
TABLE=Record
mPath : PathStr; (* Полный путь на таблицу *)
mName : NameStr; (* Имя таблицы (без расширения) *)
nFieldCnt : SmallInt; (* Число полей *)
nGroupCnt : SmallInt; (* Число групп *)
nSubstrCnt : SmallInt; (* Число подстрок *)
wRecordLen : Cardinal; (* Длина записи таблицы *)
nFlags : Integer; (* Флаги таблицы (см.константы TAB_????) *)
End;
LPTABLE=^TABLE;
(* Состояние открытой таблицы *)
(* Эта структура заполняется функцией htTableState() *)
STATT=Record
gConstCnt : LongInt; (* Число записей в постоянной части таблицы *)
gAddedCnt : LongInt; (* Число добавленных записей *)
gChangedCnt: LongInt; (* Число измененных записей *)
gDeletedCnt: LongInt; (* Число удаленных записей *)
End;
LPSTATT=^STATT;
(* Константы, определяющие реакцию на ошибку *)
(* при пакетных операциях. *)
ERROR_MODE=(
ERROR_ABORT, (* Прервать операцию *)
ERROR_REPEAT, (* Повторить обработку *)
ERROR_DELETE (* Удалить запись *)
);
(* Прототип пользовательской функции, вызываемой при *)
(* обнаружении ошибки в процессе обработки пачки записей *)
(* (добавление, модификация, вывод в таблицу). *)
EFUNC=Function(
nErrCode: SmallInt; (* Код ошибки *)
fpRecord: Pointer; (* Тело "плохой" записи для анализа *)
fpUser : Pointer (* Доп.параметр пользователя *)
):ERROR_MODE;
LPEFUNC=^EFUNC;
(*======================== Функции СУБД =======================*)
(*-------------------- Инициализация и завершение -------------*)
(* Первичная инициализация библиотеки API - одна на все приложения *)
Function htGlobalInit( hInstance: Integer ):Integer; Pascal;
(* Первичное завершение библиотеки API - одно на все приложения *)
Procedure htGlobalShut;
(* Инициализация СУБД. Выполняется один раз в начале программы. *)
(* Эта функция должна быть вызвана ДО первого обращения к СУБД *)
Function htInit(
fpInit:LPINIT; (* Параметры для функции или Nil *)
nSize:SmallInt (* Размер заполненной части записи *)
):Integer;Pascal;
(* Завершение работы СУБД *)
(* Эта процедура вызывается последней *)
Procedure htShut;
(*------------------ Работа с таблицами ------------------*)
(* Константы, используемые при задании режима доступа к таблице *)
Const TAB_PRIVATE = 0; (* Таблица используется в монопольном режиме *)
Const TAB_SHARE = 1; (* Таблица используется в совместном режиме *)
Const TAB_READ = 2; (* Таблица не допускает операций модификации *)
Const TAB_CONST = 4; (* Работа только с постоянной частью таблицы *)
Const TAB_FLUSH = 8; (* Немедленная запись данных на диск *)
Const TAB_WRITE = 16; (* Спец.режим записи (не допускает поисков) *)
Const TAB_APPEND = 32; (* Таблица допускает только добавление *)
Const TAB_ANSI = 64; (* Таблица в ANSI-кодировке (при создании) *)
Const TAB_CREATE =128; (* Безусловное создание новой таблицы *)
(* Закрыть все открытые таблицы *)
Procedure htCloseAllTables;
(* Сравнить обработчики таблиц *)
(* =0 - обработчика указывают на одну и ту же таблицу *)
Function htCompareTabHandles(
hTable1 : THANDLE; (* Обработчик таблицы *)
hTable2 : THANDLE (* Другой обработчик таблицы *)
):SmallInt;Pascal;
(* Дублировать обработчик таблицы *)
(* Дубли не входят в общее число таблиц *)
Function htDupTableHandle(
hTable : THANDLE; (* Исходный обработчик *)
Var fpTable: THANDLE (* Дубль обработчика *)
):SmallInt;Pascal;
(* Удалить таблицу и связанные с ней файлы *)
(* Таблица должна быть закрыта *)
Function htDropTable(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль для доступа на чтение *)
fpWritePswd: PChar (* Пароль для доступа на запись *)
):SmallInt;Pascal;
(* Удалить изменения, выполненные для таблицы *)
(* Таблица должна быть закрыта *)
Function htDropTableChanges(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль для доступа на чтение *)
fpWritePswd: PChar (* Пароль для доступа на запись *)
):SmallInt;Pascal;
(* Удалить все данные таблицы (оставить один описатель) *)
(* Таблица должна быть закрыта *)
Function htDropTableData(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль для доступа на чтение *)
fpWritePswd: PChar (* Пароль для доступа на запись *)
):SmallInt;Pascal;
(* Сброс буферов В/В таблицы на диск *)
(* Полезна после операций обновления *)
Function htFlushTable(
hTable: THANDLE (* Обработчик для таблицы *)
):SmallInt;Pascal;
(* Закрыть открытую таблицу *)
Function htTableClose(
hTable: THANDLE (* Обработчик для таблицы *)
):SmallInt;Pascal;
(* Копировать таблицу в другую *)
(* Если таблица с заданным именем существует, она будет уничтожена *)
(* Исходная таблица должна быть закрыта *)
Function htTableCopy(
fpDstTable: PChar; (* Имя таблицы-копии (можно без расширения) *)
fpSrcTable: PChar; (* Имя исходной таблицы (можно без расширения) *)
fpSrcRdPswd:PChar; (* Пароль для доступа на чтение *)
nSrcOpenMode: SmallInt (* Режим открытия исходной таблицы *)
):SmallInt;Pascal;
(* Создать новую таблицу и получить к ней доступ *)
Function htTableCreate(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpElems : LPELEMENT; (* Описатели элементов таблицы *)
nElemCnt : SmallInt; (* Число описателей элементов *)
fpCryptoKey : PChar; (* Ключ для крипто-закрытия данных *)
fpReadPswd : PChar; (* Пароль для доступа на чтение *)
fpWritePswd : PChar; (* Пароль для доступа на запись *)
nOpenMode : SmallInt; (* Режим открытия (константы TAB_????)*)
Var fpHandle: THANDLE (* Для приема обработчика таблицы *)
):SmallInt;Pascal;
(* Добавление агрегатов (групп и/или подстрок) в таблицу *)
(* Таблица должна быть закрыта *)
Function htTableAgregateAppend(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd: PChar; (* Пароль для доступа на чтение *)
fpWritePswd: PChar; (* Пароль для доступа на запись *)
fpAgres: LPELEMENT;(* Массив структур описаний агрегатов *)
nAgreCnt: SmallInt (* Число элементов *)
):SmallInt;Pascal;
(* Удаление агрегатов (групп и/или подстрок) из таблицы *)
(* Таблица должна быть закрыта *)
Function htTableAgregateDelete(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd: PChar; (* Пароль для доступа на чтение *)
fpWritePswd: PChar; (* Пароль для доступа на запись *)
nPos: SmallInt; (* Номер первого агрегата из группы *)
nDelCnt: SmallInt (* Число удалемых элементов *)
):SmallInt;Pascal;
(* Модификация агрегатов (групп и/или подстрок) в таблице *)
(* Таблица должна быть закрыта *)
Function htTableAgregateModify(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd: PChar; (* Пароль для доступа на чтение *)
fpWritePswd: PChar; (* Пароль для доступа на запись *)
fpAgres: LPELEMENT;(* Массив структур описаний агрегатов *)
nAgreCnt: SmallInt; (* Число элементов *)
nFirstNo: SmallInt (* Номер первого агрегата из группы *)
):SmallInt;Pascal;
(* Получить описание элемента открытой таблицы. *)
(* Первый элемент таблицы имеет номер 1, второй - 2 и т.п. *)
(* Характеристики элемента берутся из системных переменных. *)
(* Имя элемента считывается из файла описания таблицы, если *)
(* задан флаг чтения, иначе поле имени ничего не содержит. *)
Function htTableElement(
hTable : THANDLE; (* Обработчик для таблицы *)
nElemNo : SmallInt; (* Номер элемента таблицы (от 1) *)
Var sElem: ELEMENT; (* Структура для описания элемента *)
bReadName: Boolean (* Для true читать имя элемента из файла *)
):SmallInt;Pascal;
(* Получить описание всех элементов открытой таблицы. *)
(* Первый элемент таблицы имеет номер 1, второй - 2 и т.п. *)
(* Необходимо выделить массив структур длиной по числу *)
(* элементов таблицы. Число можно узнать из htTableInfo *)
Function htTableElementList(
hTable : THANDLE; (* Обработчик для таблицы *)
fpElement: LPELEMENT (* Массив структур описаний элементов *)
):SmallInt;Pascal;
(* Определить обработчик для открытой таблицы по имени *)
Function htTableHandleByName(
fpTabName : PChar; (* Имя таблицы (можно без расширения) *)
Var fpHandle : THANDLE (* Для приема обработчика таблицы *)
):SmallInt;Pascal;
(* Получить параметры открытой таблицы *)
Function htTableInfo(
hTable : THANDLE; (* Обработчик для таблицы *)
Var sTable: TABLE (* Структура для описания таблицы *)
):SmallInt;Pascal;
(* Получить состояние открытой таблицы *)
Function htTableState(
hTable : THANDLE; (* Обработчик для таблицы *)
Var sStat : STATT (* Структура для описания таблицы *)
):SmallInt;Pascal;
(* Открыть доступ к таблице *)
(* Таблица должна быть закрыта *)
Function htTableOpen(
fpTableName : PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd : PChar; (* Пароль доступа на запись *)
nOpenMode : SmallInt; (* Режим открытия (константы TAB_????) *)
Var fpHandle: THANDLE (* Для приема обработчика таблицы *)
):SmallInt;Pascal;
(* Переименовать таблицу *)
(* Таблица должна быть закрыта *)
(* Переименование возможно лишь в пределах устройства *)
Function htTableRename(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
fpNewName : PChar (* Новое имя таблицы (можно в другом каталоге) *)
):SmallInt;Pascal;
(* Режимы проверки таблицы *)
Const HTVF_INDEX = 1; (* Проверка целостности индексов ключей *)
Const HTVF_DUPS = 2; (* Анализ дублей для уникальных ключей *)
(* Проверить таблицу *)
(* Таблица должна быть закрыта *)
Function htTableVerify(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
nMode : SmallInt (* Режим проверки (HTVF_????) *)
):SmallInt;Pascal;
(* Восстановить таблицу адресов постоянной части *)
(* Таблица должна быть закрыта *)
Function htRepairTable(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar (* Пароль доступа на запись *)
):LongInt;Pascal;
(* Восстановить журнал изменений таблицы *)
(* Таблица должна быть закрыта *)
Function htRepairTableLog(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
gItemCnt : LongInt (* Число элементов к восстановлению *)
(* <0 - число элементов из HDN *)
(* =0 - по умолчанию *)
(* >0 - число элементов из HDR *)
):SmallInt;Pascal;
(* Перенести изменения в постоянную часть таблицы *)
(* Таблица должна быть закрыта *)
Function htUpdateTable(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
bReIndex : Boolean; (* Для true перепостроение индексов *)
bTestSpace : Boolean (* Для true проверка места на диске *)
):SmallInt;Pascal;
(*------------- Работа с индексами таблицы ------------*)
(* Построение индексов для ключевых элементов *)
(* Таблица должна быть закрыта *)
(* Возвращает число отвергнутых записей или код ошибки *)
Function htBuildIndexes(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
bTestSpace : Boolean; (* Проверка пространства на диске *)
bDenyOut : Boolean (* Для true вывод отвергнутых записей в таблицу *)
):LongInt;Pascal;
(* Сменить тип ключа для элемента таблицы *)
(* Таблица должна быть закрыта *)
(* Возвращает число отвергнутых записей или код ошибки *)
Function htChangeKeyType(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
nElemNo : SmallInt; (* Номер элемента таблицы (от 1) *)
nNewKeyType: SmallInt; (* Новый тип ключа *)
bTestSpace : Boolean; (* Проверка пространства на диске *)
bDenyOut : Boolean (* Для true вывод отвергнутых записей в таблицу *)
):LongInt;Pascal;
(* Удаление индексов *)
(* Таблица должна быть закрыта *)
Function htDropIndexes(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar (* Пароль доступа на запись *)
):SmallInt;Pascal;
(*------------- Операции модификации таблицы -------------*)
(* Добавление записи в таблицу *)
(* Возвращает физический номер добавленной записи *)
Function htRecordAdd(
hTable : THANDLE; (* Обработчик для таблицы *)
fpRecord: Pointer (* Тело записи *)
):LongInt;Pascal;
(* Удаление записи из таблицы *)
Function htRecordDelete(
hTable : THANDLE; (* Обработчик для таблицы *)
gRecordNo : LongInt (* Физический номер удаляемой записи *)
):SmallInt;Pascal;
(* Модификация записи в таблице *)
Function htRecordModify(
hTable : THANDLE; (* Обработчик для таблицы *)
gRecordNo : LongInt; (* Физический номер модифицируемой записи *)
fpRecord : Pointer (* Тело записи *)
):SmallInt;Pascal;
(*----------- Пакетные операции модификации ------------*)
(* Константы, определяющие порядок вызова пользовательской *)
(* функции подготовки данных. При последнем вызове подготовка *)
(* данных не выполняется, это сигнал к завершению обработки *)
Type ADD_MODE=(
ADD_FIRST, (* Первый вызов (сигнал к инициализации) *)
ADD_NEXT, (* Очередной вызов *)
ADD_LAST (* Последний вызов (завершение обработки) *)
);
(* Описатель автоинекрементного ключа *)
(* для доступа к данным в сборке значений *)
AUTO=Record
nType: SmallInt; (* Тип данных *)
nLength: SmallInt; (* Длина ключа *)
nKeyNum: SmallInt; (* Номер ключа (от 1) *)
wOffset: Cardinal; (* Смещение в сборке значений *)
acResrvd: Array[1..12] of Byte;
End;
Type LPAUTO=^AUTO;
(* Описатель, используемый при добавлении пачки записей *)
(* Эта структура передается как параметр при вызове *)
(* пользовательской функции из функции htAddRecords *)
Type APARM=Record
fpBuf : Pointer; (* Буфер для записей *)
wBufLen : Cardinal; (* Длина буфера *)
wRecordLen: Cardinal; (* Длина записи *)
(* Следующие члены заполняются для первой записи пачки *)
gFirstRecNum: LongInt; (* Номер для первой записи пачки *)
dFirstSurrogate:Cardinal; (* Значение суррогатного ключа для первой записи *)
nAutoCnt: SmallInt; (* Число автоинкрементных ключей *)
fpAuto: LPAUTO; (* Описатели автоинкрементных ключей *)
pFirstAuto: Pointer; (* Сборка значений автоинкрементных ключей *)
End;
LPAPARM = ^APARM;
(* Прототип пользовательской функции, вызываемой для *)
(* подготовки очередной пачки добавляемых записей. *)
(* Функция должна заполнить предоставленный буфер *)
(* добавляемыми записями. Длина буфера задана. *)
(* Функция должна возвращать: *)
(* длину заполненной части буфера (в байтах); *)
(* 0 при необходимости прервать процесс обработки. *)
Type AFUNC=Function(
nOrder: ADD_MODE; (* Порядок вызова *)
fpParm: LPAPARM; (* Параметры пачки записей *)
fpUser: Pointer (* Доп.параметр пользователя *)
):Cardinal;
LPAFUNC = ^AFUNC;
(* Добавление группы записей в таблицу *)
(* Возвращает число отвергнутых записей или код ошибки *)
Function htAddRecords(
hTable : THANDLE; (* Обработчик для таблицы *)
gAppendLim: LongInt; (* Максимальное число записей для добавления *)
fpfAddProc: LPAFUNC; (* Пользовательская функция подготовки данных *)
fpfErrProc: LPEFUNC; (* Пользовательская функция обработки ошибок *)
(* Nil - ошибки отменяют операцию *)
fpUser : Pointer; (* Доп.параметр пользователя *)
bDenyOut : Boolean (* True - вывод отвергнутых записей в таблицу *)
):LongInt;Pascal;
(* Добавление пачки записей в постоянную часть таблицы *)
(* Возвращает число отвергнутых записей или код ошибки *)
Function htLoadRecords(
fpTableName: PChar; (* Имя таблицы *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
gLoadLim : LongInt; (* Максимальное число записей для добавления *)
fpfAddProc : LPAFUNC; (* Пользовательская функция подготовки данных *)
fpfErrProc : LPEFUNC; (* Пользовательская функция обработки ошибок *)
(* Nil - ошибки отменяют операцию *)
fpUser : Pointer; (* Доп.параметр пользователя *)
bDenyOut : Boolean (* Для true вывод отвергнутых записей в таблицу *)
):LongInt;Pascal;
(* Удаление подмножества записей из таблицы *)
Function htDeleteRecords(
Var fpSrc: SAB (* Адрес БДС, содержащего подмножество записей *)
):LongInt;Pascal;
(* Прототип пользовательской функции, вызываемой для каждой *)
(* записи. Функция должна выполнить требуемые действия по *)
(* модификации записи. Функция возвращает значения: *)
(* false - прервать процесс модификации *)
(* true - запись модифицирована *)
Type MFUNC=Function(
gRecNo : LongInt; (* Номер модифицируемой записи *)
fpRecord: Pointer; (* Тело модифицируемой записи *)
fpUser : Pointer (* Доп.параметр пользователя *)
):Boolean;
LPMFUNC = ^MFUNC;
(* Модификация подмножества записей из таблицы *)
(* Возвращает число отвергнутых записей или код ошибки *)
Function htModifyRecords(
Var fpSrc : SAB; (* Адрес БДС, содержащего подмножество записей *)
fpfMdfProc: LPMFUNC; (* Функция модификации записей *)
fpfErrProc: LPEFUNC; (* Пользовательская функция обработки ошибок *)
(* Nil - ошибки отменяют операцию *)
fpUser : Pointer; (* Доп.параметр пользователя *)
bDenyOut : Boolean (* Для true вывод отвергнутых записей в таблицу *)
):LongInt;Pascal;
(* Безусловное добавление группы записей в таблицу *)
(* Добавляются либо все заданные записи, либо ничего *)
(* Появление проблемных записей приводит к отказу от операции *)
Function htPureAddRecords(
hTable : THANDLE; (* Обработчик для таблицы *)
gAppendLim: LongInt; (* Максимальное число записей для добавления *)
fpfAddProc: LPAFUNC; (* Пользовательская функция подготовки данных *)
fpUser : Pointer (* Доп.параметр пользователя *)
):SmallInt;Pascal;
(* Безусловная модификация подмножества записей из таблицы *)
(* Модифицируются либо все заданные записи, либо ничего *)
(* Появление проблемных записей приводит к отказу от операции *)
Function htPureModifyRecords(
Var fpSrc : SAB; (* Адрес БДС, содержащего подмножество записей *)
fpfMdfProc: LPMFUNC; (* Функция модификации записей *)
fpUser : Pointer (* Доп.параметр пользователя *)
):SmallInt;Pascal;
(*============== Поисковые операции в таблице ===============*)
(*----------------------- Атомарный поиск ------------------------*)
(* Элементы таблицы (поля, группы и подстроки) имеют сквозную *)
(* нумерацию от 1. Номер 0 отведен для доступа по физическому *)
(* номеру записи (значение задается как LongInt). *)
(* Прототип пользовательской функции, вызываемой для каждого *)
(* значения искомого элемента записи. Функция возвращает значения: *)
(* 1 - элемент подходит *)
(* 0 - элемент не подходит *)
Type CFUNC=Function(
fpItem: Pointer; (* Тело проверяемого элемента записи *)
fpUser: Pointer (* Доп.параметр пользователя *)
):Boolean;
LPCFUNC = ^CFUNC;
(* Константы, определяющие условие поиска по одному элементу записи *)
(* (2) - требуется два пороговых значения *)
Type CONDITION=(
EMPTY_COND, (* Такого условия нет - незначащий код *)
BETWEEN, (* (2) Значения элемента лежат в диапазоне (исключающее) *)
EQUAL, (* Значения элемента равны заданному *)
GREAT, (* Значения элемента больше заданного *)
GREAT_EQUAL, (* Значения элемента больше или равны заданному *)
IN_RANGE, (* (2) Значения элемента лежат в диапазоне (включающее) *)
LESS, (* Значения элемента меньше заданного *)
LESS_EQUAL, (* Значения элемента меньше или равны заданному *)
NOT_BETWEEN, (* (2) Значения элемента лежат вне диапазона (включающее) *)
NOT_EQUAL, (* Значения элемента не равны заданному *)
NOT_GREAT, (* Значения элемента не больше заданного *)
NOT_IN_RANGE, (* (2) Значения элемента лежат вне диапазона (исключающее)*)
NOT_LESS, (* Значения элемента не меньше заданного *)
WILDCARD, (* Значения символьного элемента совпадают с шаблоном *)
WILDCASE, (* Значения элемента совпадают с шаблоном без учета регистра *)
USER_DEF (* Значения элемента удовлетворяют критерию пользователя *)
);
(* Поиск по условию для элемента таблицы (поля, группы, подстроки) *)
(* Поиск производится в заданном временном снимке таблицы *)
Function htSearch(
fpPhoto : LPSAB; (* БДС "снимка" (Nil - если первый запрос) *)
Var fpSave: SAB; (* БДС для сохранения результата *)
hTable : THANDLE; (* Обработчик для таблицы *)
nElemNum : SmallInt; (* Номер элемента таблицы *)
(* (0-физ.номер, 1-первый и т.п.) *)
nCond : CONDITION;(* Условие, см. константы условий *)
fpValue1 : Pointer; (* Пеpвое пороговое значение или функция *)
fpValue2 : Pointer (* Второе пороговое значение или параметр функции *)
(* Nil, если не нужно *)
):LPSAB;Pascal;
(* Поиск по условию для элемента таблицы (поля, группы, подстроки) *)
(* Поиск производится в заданном множествев записей таблицы *)
Function htSubSearch(
Var fpSet : SAB; (* БДС множества записей *)
Var fpSave: SAB; (* БДС для сохранения результата *)
hTable : THANDLE; (* Обработчик для таблицы *)
nElemNum : SmallInt; (* Номер элемента таблицы *)
(* (0-физ.номер, 1-первый и т.п.) *)
nCond : CONDITION;(* Условие, см. константы условий *)
fpValue1 : Pointer; (* Пеpвое пороговое значение или функция *)
fpValue2 : Pointer (* Второе пороговое значение или параметр функции *)
(* Nil, если не нужно *)
):LPSAB;Pascal;
(*---------------- Сложные поиски записей ---------------*)
(* Получить записи по списку значений элемента *)
(* Отбираются записи, для которых элемент принимает значения из списка *)
Function htRecordsByKey(
Var fpDst : SAB; (* Для приема результата *)
Var fpList: SAB (* Адрес БДС, содержащего список значений *)
):LPSAB;Pascal;
(* Найти запись по значению уникального ключа *)
(* Возвращает физ.номер записи с заданным значением ключа *)
(* 0 нет таких записей, <0 - код ошибки *)
Function htRecordByUniq(
fpPHO: LPSAB; (* БДС "снимка" *)
hTable: THANDLE; (* Обработчик таблицы *)
nKeyNo: SmallInt; (* Номер ключа (0-физ.номер, 1-первое поле и т.д.) *)
fpValue: Pointer; (* Искомоме значение уникального ключа *)
fphRecord: LPRHANDLE (* Для обработчика записи *)
):LongInt;Pascal;
(* Получить записи для заданного соотношения значений двух элементов *)
(* Отбираются записи, для которых значения элемента nElemNo1 и *)
(* nElemNo2 удовлетворяют заданному соотношению на подмножестве *)
(* записей fpSrc. *)
Function htRecordsForTwoKeys(
Var fpDst: SAB; (* Для приема результата *)
Var fpSrc: SAB; (* Адрес БДС, содержащего список записей таблицы *)
nElemNo1 : SmallInt; (* Номер первого элемента записи *)
nCond : CONDITION; (* Условие сравнения (пока только EQUAL) *)
nElemNo2 : SmallInt (* Номер второго элемента записи *)
):LPSAB;Pascal;
(* Определить подмножество записей таблицы, попавших в результат сортировки *)
Function htSortedRecords(
Var fpDst : SAB; (* Блок для приема результата *)
Var fpSort: SAB (* Результат сортировки *)
):LPSAB;Pascal;
(* Определить подмножество записей таблицы, попавших в результат сортировки, *)
(* для заданного снимка *)
Function htSortedRecordsEx(
Var fpDst : SAB; (* Блок для приема результата *)
Var fpSort: SAB; (* Результат сортировки *)
Var fpPhoto:SAB (* Снимок для множества *)
):LPSAB;Pascal;
(*------------ Операции над значениями элемента записи -------------*)
(* Импликация (деление) столбцов таблицы *)
Function htDivision(
Var fpDst: SAB; (* Для приема результата *)
Var fpSET: SAB; (* Подмножество записей *)
nElemNo : SmallInt;(* Номер поля делимого *)
Var fpLST: SAB (* Список значений делителя *)
):LPSAB;Pascal;
(* Получить гистограмму значений элемента для подмножества записей *)
Function htHistogramOfKey(
Var fpDst: SAB; (* Для приема результата *)
nElemNo : SmallInt;(* Номер элемента записи *)
Var fpSrc: SAB (* Подмножество записей *)
):SmallInt;Pascal;
(* Получить гистограмму значений элемента с заданным числом повторов *)
Function htHistogramByCount(
Var fpDst: SAB; (* Для приема результата *)
nElemNo : SmallInt;(* Номер элемента записи *)
Var fpSrc : SAB; (* Подмножество записей *)
gMin : LongInt; (* Минимальное число повторов (не менее 1) *)
gMax : LongInt (* Максимальное число повтоpов *)
):SmallInt;Pascal;
(* Перенести список значений элемента в другую таблицу *)
(* Может быть использована для смены номера элемента *)
Function htTransferToTable(
Var fpSrc: SAB; (* Адpес БДС, содержащего список значений *)
hTable : THANDLE; (* Обработчик для другой таблицы *)
nElemNo : SmallInt (* Номер элемента в другой таблице *)
):LPSAB;Pascal;
(* Перенести список значений элемента в заданный "снимок" другой таблицы *)
Function htTransferToPhoto(
Var fpSrc : SAB; (* Адpес БДС, содержащего список значений *)
Var fpPhoto: SAB; (* Адрес БДС, содержащего снимок другой таблицы *)
nElemNo : SmallInt (* Номер элемента в другой таблице *)
):LPSAB;Pascal;
(* Получить список значений элемента для подмножества записей *)
Function htValuesOfKey(
Var fpDst: SAB; (* Для приема результата *)
nElemNo : SmallInt;(* Номер элемента записи *)
Var fpSrc: SAB (* Подмножество записей *)
):LPSAB;Pascal;
(* Получить список значений элемента с заданным числом повторов *)
Function htValuesByCount(
Var fpDst: SAB; (* Для приема результата *)
nElemNo : SmallInt;(* Номер элемента записи *)
Var fpSrc : SAB; (* Подмножество записей *)
gMin : LongInt; (* Минимальное число повторов (не менее 1) *)
gMax : LongInt (* Максимальное число повтоpов *)
):LPSAB;Pascal;
(*----------------- Обработка значений элемента -------------------*)
(* Получить среднее значение элемента для подмножества записей *)
Function htAverageOfKeyValues(
Var fpSrc: SAB; (* Адрес БДС, содержащего подмножество записей *)
nElemNo : SmallInt; (* Номер элемента записи *)
fpAverage: Pointer (* Сюда поместят среднее значение *)
(* LongInt для - целочисленных, Double - для действительных *)
):SmallInt;Pascal;
(* Получить максимальное значение элемента для подмножества записей *)
Function htKeyMaximum(
Var fpSrc: SAB; (* Адрес БДС, содержащего подмножество записей *)
nElemNo : SmallInt; (* Номер элемента записи *)
fpMax : Pointer (* Сюда поместят максимальное значение *)
):SmallInt;Pascal;
(* Получить минимальное значение элемента для подмножества записей *)
Function htKeyMinimum(
Var fpSrc: SAB; (* Адрес БДС, содержащего подмножество записей *)
nElemNo : SmallInt; (* Номер элемента записи *)
fpMin : Pointer (* Сюда поместят минимальное значение *)
):SmallInt;Pascal;
(* Получить сумму значений элемента для подмножества записей *)
Function htSumOfKeyValues(
Var fpSrc: SAB; (* Адрес БДС, содержащего подмножество записей *)
nElemNo : SmallInt; (* Номер элемента записи *)
fpSum : Pointer (* Сюда поместят сумму значений элемента *)
(* LongInt для - целочисленных, Double - для действительных *)
):SmallInt;Pascal;
(*--------- Логические операции над результатами поиска ---------*)
(* Уточнение результата условием *)
Function htAndResults(
Var fpDst : SAB; (* Блок для приема результата *)
Var fpSrc1: SAB; (* Блок с первым результатом *)
Var fpSrc2: SAB (* Блок со вторым результатом *)
):LPSAB;Pascal;
(* Расширение результата условием *)
Function htOrResults(
Var fpDst : SAB; (* Блок для приема результата *)
Var fpSrc1: SAB; (* Блок с первым результатом *)
Var fpSrc2: SAB (* Блок со вторым результатом *)
):LPSAB;Pascal;
(* Отрицание результата *)
Function htNotResults(
Var fpDst: SAB; (* Блок для приема результата *)
Var fpSrc: SAB (* Блок с отрицаемым результатом *)
):LPSAB;Pascal;
(* Исключение результата *)
Function htXorResults(
Var fpDst : SAB; (* Блок для приема результата *)
Var fpSrc1: SAB; (* Блок с первым операндом *)
Var fpSrc2: SAB (* Блок со вторым операндом *)
):LPSAB;Pascal;
(*---------------- Операции над группами -----------------*)
(* В результате выполнения операции образуется массив элементов. *)
(* Каждый элемент содержит значения полей, входящих в группу, за *)
(* которыми следуют значения функционалов для заданных полей. *)
(* Константы, определяющие функции для полей, вычисляемых *)
(* для каждого экземпляра сгруппированных полей. *)
(* Длина функционала указана в скобках *)
Const GROUP_AVERAGE =0; (* Среднее значение (LongInt/Double) *)
Const GROUP_COUNT =1; (* Подсчет числа значений (всегда LongInt) *)
Const GROUP_MAX =2; (* Максимальное значение (по типу поля) *)
Const GROUP_MIN =3; (* Минимальное значение (по типу поля) *)
Const GROUP_SUM =4; (* Сумма значений (LongInt/Double) *)
Const GROUP_DISTINCT=5; (* Подсчет числа уникальных значений (всегда LongInt) *)
Const GROUP_FIRST =6; (* Первое значение (по типу поля) *)
Const GROUP_LAST =7; (* Последнее значение (по типу поля) *)
(* Прототип пользовательской функции-фильтра *)
(* для реализации HAVING_TO групповой операции *)
(* Возвращает: *)
(* true - элемент подходит *)
(* false - элемент не подходит *)
Type HAVING = Function(
fpGroupBody: Pointer; (* Тело группы и функционалов *)
fpUser : Pointer (* Доп.параметр пользователя *)
):Boolean;
LPHAVING = ^HAVING;
(* Описатель поля для групповой операции *)
(* Используется при вызове функции htGroupByHavingTo *)
Type GROUP=Record
nField : SmallInt; (* Номер поля *)
nType : SmallInt; (* Тип функции для поля GROUP_??? *)
mSystem: Array [1..36] of Char; (* Будет использоваться СУБД *)
End;
LPGROUP = ^GROUP;
(* Отработка групповой операции на подмножестве записей таблицы *)
(* На каждое сформированное значение группы вызывается функция *)
(* fpfHavingTo, которая может выполнить обработку значения и *)
(* примет решению о выводе данного элемента группы. *)
Function htGroupByHavingTo(
Var fpDst : SAB; (* Блок для приема результата *)
Var fpSrc : SAB; (* БДС, задающий подмножество записей *)
fpnGroup : PSmallInt;(* Номера полей, образующих группу *)
nGroupCnt : SmallInt; (* Число таких полей (до MAX_SORT_ORDER+1) *)
fpsFunc : LPGROUP; (* Описатели вычислимых выражений *)
nFuncCnt : SmallInt; (* Их число *)
fpfHavingTo: LPHAVING; (* Функция, реализующая условие HavingTo *)
fpUser : Pointer (* Доп.параметр пользователя *)
):SmallInt;Pascal;
(* Прототип пользовательской функции, вызываемой для сравнения *)
(* пары элементов. Функция возвращает значения: *)
(* <0 - первый элемент меньше второго *)
(* =0 - элементы равны *)
(* >0 - первый элемент больше второго *)
Type OFUNC=Function(
fpFirst : Pointer; (* Адрес первого элемента *)
fpSecond: Pointer; (* Адрес второго элемента *)
fpUser : Pointer (* Доп.параметр пользователя *)
):SmallInt;
LPOFUNC = ^OFUNC;
(* Отработка групповой операции на подмножестве записей таблицы *)
(* контролируемая пользователем *)
Function htGroupByUser(
Var fpDst : SAB; (* Блок для приема результата *)
Var fpSrc : SAB; (* БДС, задающий подмножество записей *)
fpnGroup : PSmallInt;(* Номера полей, образующих группу *)
nGroupCnt : SmallInt; (* Число таких полей (до MAX_SORT_ORDER+1) *)
fpsFunc : LPGROUP; (* Описатели вычислимых выражений *)
nFuncCnt : SmallInt; (* Их число *)
fpfSort : LPOFUNC; (* Функция сравнения для сортировки *)
fpfDiff : LPOFUNC; (* Функция сравнения для группировки *)
fpfHavingTo: LPHAVING; (* Функция, реализующая условие HavingTo *)
fpUser : Pointer (* Доп.параметр пользователя *)
):SmallInt;Pascal;
(* Построение списка значений ключа по результатам группировки *)
(* Доступ к исходным результатам должен быть закрыт *)
Function htValuesFromGroup(
Var fpDst : SAB; (* Блок для приема списка значений ключа *)
nKeyNo : SmallInt; (* Номер поля, значения которого собираются *)
wOffset : Word; (* Смещение начала поля в группе *)
Var fpSrc : SAB (* БДС, задающий результаты группировки *)
):LPSAB;Pascal;
(*---------------- Межтабличные операции -----------------*)
(* Константы, определяющие режимы обработки неполных пар или групп таблиц *)
Const DRAFT_ZERO = 0; (* Сбор несопадающих групп запрещен *)
Const DRAFT_LEFT = 1; (* Сбор несопадающих групп из левого операнда *)
Const DRAFT_RIGHT= 2; (* Сбор несопадающих групп из правого операнда *)
Const DRAFT_ALL = 3; (* Сбор несопадающих групп обеих операндов *)
(* Слияние двух таблиц через общий элемент *)
Function htTablesJoin(
Var fpDst : SAB; (* Блок для приема результата *)
Var fpFRST: SAB; (* Условие для первой таблицы *)
nFiElNo : SmallInt; (* Номер элемента-связки в первой таблице *)
nCond : CONDITION; (* Тип слияния (пока только EQUAL) *)
Var fpSCND: SAB; (* Условие для второй таблицы *)
nScElNo : SmallInt; (* Номер элемента-связки во второй таблице *)
fpCOND : LPSAB; (* Если не Nil, выполняется отбор записей, *)
(* попавших в JOIN, для одной из таблиц *)
bFirst : Boolean; (* Если true, то отбор записей из первой *)
(* таблицы *)
nMode : SmallInt (* Режим отобра неполных пар *)
):LPSAB;Pascal;
Const LINK_AUTO = 0; (* Автоматическое определение типа связи *)
Const LINK_MULY = 4; (* Всегда "декартовое" произведение *)
(* Объединение/слияние нескольких связанных таблиц *)
Function htTablesLink(
Var fpDst: SAB; (* Блок для приема результата *)
Var fpGroup: SAB; (* Группа связанных таблиц *)
Var fpPair: SAB; (* Пара связанных таблиц *)
bSkipLink: Boolean;(* Для true выходная группа будет без *)
(* таблицы-связки *)
nMode: SmallInt (* Режим работы (DRAFT_??? Or LINK_???*)
):LPSAB;Pascal;
(* Определить подмножество записей таблицы, попавших в слияние *)
Function htJoinedRecords(
fpStart : LPSAB; (* "Снимок" таблицы для подмножества *)
Var fpDst : SAB; (* Блок для приема результата *)
Var fpGroup: SAB; (* Группа связанных таблиц *)
nTabNo : SmallInt (* Номер таблицы группе таблиц (отсчет от 0) *)
):LPSAB;Pascal;
(* Определить число таблиц в выходной группе таблиц и *)
(* порядок их расположения. Возвращает число таблиц и *)
(* заполняет массив обработчиками таблиц в порядке их *)
(* расположения в выходной группе. Размер массива для *)
(* приема обработчиков подсхе должен быть не менее *)
(* константы MAX_TAB_LINK *)
(* Если обработчики не нужны, можно задать Nil *)
Function htTellJoinOrder(
Var fpSrc: SAB; (* Результат связи *)
fpHandles: LPTHANDLE (* Сюда занесут обработчики таблиц *)
):SmallInt;Pascal;
(* Определить характеристики элемента одной из таблиц, *)
(* входящих в группу слияния. Смещение элемента будет *)
(* определено от начала обобщенной записи, т.е. записи, *)
(* состоящей из записей всех таблиц группы. *)
Function htJoinElement(
Var fpSrc: SAB; (* Результат связи *)
nTableNo : SmallInt; (* Номер таблицы в группе таблиц (от 1) *)
nElemNo : SmallInt; (* Номер элемента в таблице (от 0, включая физ.номер) *)
fpElement: LPELEMENT; (* Структура для описания элемента *)
bReadName: Boolean (* Для true читать имя элемента из файла *)
):SmallInt;Pascal;
(*----------------------- Кластеры ----------------------*/
(* Создать кластерную таблицу для связки таблиц *)
Function htCreateClusterTable(
Var fpLink: SAB; (* БДС со связкой таблиц *)
fpTableName: PChar; (* Имя таблицы кластеров *)
fpCryptoKey: PChar; (* Ключ для крипто-закрытия данных *)
fpReadPswd : PChar; (* Пароль для доступа на чтение *)
fpWritePswd: PChar; (* Пароль для доступа на запись *)
bIndex: Boolean (* True - индексировать таблицу кластеров *)
):SmallInt;Pascal;
(* Преобразовать запись кластерной таблицы в результат связи таблиц *)
Function htClusterItemToLink(
Var fpDst: SAB; (* Для приема результата *)
hTable: THANDLE; (* Таблица кластеров *)
hRecord: RHANDLE; (* Запись таблицы кластеров *)
fpHandles: LPTHANDLE (* Обработчики связываемых таблиц *)
):LPSAB;Pascal;
(* Преобразовать записи кластерной таблицы в результат связи таблиц *)
Function htClusterRecsToLink(
Var fpDst: SAB; (* Для приема результата *)
Var fpSrc: SAB; (* Записи таблицы кластеров *)
fpHandles: LPTHANDLE (* Обработчики связываемых таблиц *)
):LPSAB;Pascal;
(*----------------------- Фильтры ----------------------*)
(* Прототип пользовательской функции, вызываемой *)
(* при фильтрации подмножества записей. *)
(* Функция должна возвращать: *)
(* 1 - запись удовлетовряет условию фильтрации *)
(* 0 - запись не удовлетворяет условию фильтрации *)
(* -1 - прекратить фильтрацию на текущем элементе *)
Type SFUNC = Function(
gRecNo : LongInt; (* Номер анализируемой записи или элемента *)
fpField: Pointer; (* Значения отобранных полей для анализа *)
fpUser : Pointer (* Доп.параметр пользователя *)
): SmallInt;
LPSFUNC = ^SFUNC;
(* Фильтрация списка записей пользователем *)
(* Можно заказать выборку некоторых полей записи *)
Function htFilterRecords(
Var fpDst: SAB; (* Для приема результата *)
Var fpSrc: SAB; (* Адрес БДС, содержащего список записей *)
fpFieldNo: PSmallInt;(* Номера полей, подлежащих выборке из записи *)
(* Nil - все поля записи *)
nFieldCnt: SmallInt; (* Число выбираемых полей *)
fpfFilter: LPSFUNC; (* Адрес пользовательской функции фильтрации *)
fpUser : Pointer (* Доп.параметр пользователя *)
):LPSAB;Pascal;
(* Описатель связи пары таблиц *)
Type LINK=Record
nFiTab :SmallInt; (* Индекс первой таблицы в группе (от 0) *)
nFiKey :SmallInt; (* Номер элемента-связки в первой таблице *)
nScTab :SmallInt; (* Индекс второй таблицы в группе (от 0) *)
nScKey :SmallInt; (* Номер элемента-связки во второй таблице *)
End;
LPLINK = ^LINK;
(* Режимы выполнения операции *)
Const FLT_AUTO = 0; (* Автоматическое определение типа связки *)
Const FLT_MULT = 1; (* Всегда "декартовое" произведение таблиц *)
Const FLT_DRAFT= 2; (* Допустимо "черновое" связывание таблиц *)
(* Фильтрация записей группы связаных таблиц *)
Function htFilterTables(
Var fpDst: SAB; (* Для приема результата *)
fppSABs: LPPSAB; (* Группа таблиц и подмножества записей в них *)
nTableCnt: SmallInt; (* Число таблиц (БДС'ов) *)
fpFieldNo: PSmallInt;(* Номера полей таблиц для анализа *)
nFieldCnt: SmallInt; (* Число выбираемых полей *)
fpLinks: LPLINK; (* Описатели связей таблиц *)
nLinkCnt: SmallInt; (* Число связей *)
fpfFilter: LPSFUNC; (* Адрес пользовательской функции фильтрации *)
fpUser : Pointer; (* Доп.параметр пользователя *)
nMode : SmallInt (* Режимы связывания таблиц *)
):LPSAB;Pascal;
(*------------ Работа с результатами поиска ------------*)
(* Удалить результаты поиска для БДС {HTCOD2] *)
Procedure htClearResults( Var fpSrc: SAB );Pascal;
(* Закрыть доступ к результатам поиска в БДС *)
Procedure htCloseResults( Var fpSrc: SAB );Pascal;
(* Скопировать результаты поиска *)
(* Доступ к исходным результатам должен быть закрыт *)
Function htCopyResults(
Var fpDst: SAB; (* Адрес БДС для приема копии *)
Var fpSrc: SAB (* Адрес исходного БДС *)
):SmallInt;Pascal;
(* Уникализовать результаты поиска по заданным полям *)
(* Доступ к исходным результатам должен быть закрыт *)
Function htDistinctResults(
Var fpDst: SAB; (* Для приема уникализованных результатов *)
Var fpSrc: SAB; (* Неуникализованные результаты поиска *)
fpFieldNo: PSmallInt;(* Список полей - критериев уникализации *)
(* Nil - по всей записи в совокупности *)
nFieldCnt: SmallInt (* Число полей-критериев *)
):SmallInt;Pascal;
(* Уникализовать результаты поиска по счетчику повторов *)
(* Оставляет те результаты, число повторов которых по *)
(* заданному критерию попадает в определенный диапазон *)
(* Доступ к исходным результатам должен быть закрыт *)
Function htDistinctResultsByCount(
Var fpDst: SAB; (* Для приема уникализованных результатов *)
Var fpSrc: SAB; (* Неуникализованные результаты поиска *)
fpFieldNo: PSmallInt;(* Список полей - критериев уникализации *)
(* Nil - по всей записи в совокупности *)
nFieldCnt: SmallInt; (* Число полей-критериев *)
gMin: LongInt; (* Минимальное число повторов *)
gMax: LongInt (* Максимальное число повторов *)
):SmallInt;Pascal;
(* Константы, определяющие режим открытия *)
(* доступа к результатам поиска htOpenResults *)
(* Могут комбинироваться операцией OR *)
Const ROPEN_READ = 0; (* Чтение результатов *)
Const ROPEN_BODY = 2; (* Чтение тела записи (без номера) *)
Const ROPEN_HNDL = 4; (* Чтение обработчика вместо физ.номера *)
(* Открыть доступ к результатам поиска в БДС *)
Function htOpenResults(
Var fpSrc: SAB; (* Адрес исходного БДС *)
(* Следующие параметры имеют смысл только для результатов-записей *)
nMode : SmallInt; (* Режим открытия (см.ROPEN_????) *)
fpElemNo: PSmallInt; (* Номера читаемых элементов записи *)
(* Если Nil - выводятся все элементы записи *)
nElemCnt: SmallInt (* Число выводимых элементов *)
):SmallInt;Pascal;
(* Читать результаты поиска из БДС *)
(* Возвращает число считанных байтов. *)
(* Размер читаемого блока не более MAX_BUF_LEN байтов. *)
(* Коды возврата от MAX_BUF_LEN до $FFFF - коды ошибок *)
Function htReadResults(
Var fpSrc: SAB; (* Адрес исходного БДС *)
fpBuff : Pointer; (* Буфер для чтения данных *)
wLen : Cardinal (* Длина буфера *)
):Word;Pascal;
(* Определить длину одного элемента результата *)
(* Доступ к результатам должен быть открыт *)
Function htResultsItemLen(
Var fpSrc : SAB; (* Адрес исходного БДС *)
Var wItemLen: Cardinal (* Длина элемента *)
):SmallInt;Pascal;
(* Определить число полей отбора в открытом результате *)
Function htResultsItemCnt(
Var fpSAB: SAB (* Адрес открытого БДС *)
): SmallInt;Pascal;
(* Описатель поля отбора в открытом результате *)
Type OPEL=record
nType: SmallInt; (* Тип поля *)
nNum: SmallInt; (* Номер поля *)
wLen: Cardinal; (* Длина поля *)
wOff: Cardinal; (* Место вывода среди других полей *)
hCoder: CHANDLE; (* Кодификатор поля *)
End;
LPOPEL=^OPEL;
(* Получить описатели полей отбора в открытом результате *)
Function htResultsItemParm(
Var fpSAB: SAB; (* Адрес открытого БДС *)
fpParm: LPOPEL (* Для приема параметров *)
): SmallInt;Pascal;
(* Константы, определяющие режим перемещения логического *)
(* указателя по результатам поиска htSeekResults *)
Type RSEEK_MODE=(
RSEEK_SET, (* От начала *)
RSEEK_CUR, (* От текущей позиции *)
RSEEK_END, (* От конца *)
RSEEK_REC (* Установиться на запись, заданную физ.номеpом *)
);
(* Перемещение логического указателя по результатам поиска *)
Function htSeekResults(
Var fpSrc : SAB; (* Адрес исходного БДС *)
gOffset : LongInt; (* Величина перемещения *)
nFromWhere: RSEEK_MODE (* Режим перемещения *)
):LongInt;Pascal;
(* Получить порядковый номер записи по ее физическому номеру. *)
(* Отсчет от 0. Доступ к результатам должен быть открыт. *)
(* Имеет смысл для результатов типа RES_RCRD *)
Function htRecordOrdinalNumber(
Var fpSrc : SAB; (* Адрес исходного БДС *)
gNumber : LongInt (* Физический номер *)
):LongInt;Pascal;
(* Описатель маркера записи в открытом результате *)
Type MARKER=Record
hTable: THANDLE; (* Таблица, которой принадлежит запись *)
hRecord:RHANDLE; (* Обработчик помеченной записи *)
End;
LPMARK=^MARKER;
(* Установить маркер на текущую запись открытого результата поиска *)
Function htMarkRecord(
Var fpSrc : SAB; (* Адрес открытого для чтения БДС *)
Var fpMark : MARKER (* Маркер записи *)
):SmallInt;Pascal;
(* Установить маркер на текущую запись одной из таблиц слияния *)
Function htMarkJoinedRecord(
Var fpSrc : SAB; (* Адрес открытого для чтения БДС *)
nTabNo : SmallInt; (* Номер таблицы группе таблиц (отсчет от 0) *)
Var fpMark : MARKER (* Маркер записи *)
):SmallInt;Pascal;
(* Установить маркер на текущую запись слияния таблиц *)
Function htMarkJoinedRecordEx(
Var fpSrc : SAB; (* Адрес открытого для чтения БДС *)
fpMark : LPMARK (* Массив маркеров (по числу таблиц) *)
):SmallInt;Pascal;
(* Перемещение логического указателя на установленный ранее маркер *)
Function htSeekMarkedJoin(
Var fpSrc : SAB; (* Адрес открытого для чтения БДС *)
nTabNo : SmallInt; (* Номер таблицы группе таблиц (отсчет от 0) *)
Var fpMark : MARKER (* Маркер записи *)
):SmallInt;Pascal;
(* Перемещение логического указателя на маркированную связку *)
Function htSeekMarkedJoinEx(
Var fpSrc : SAB; (* Адрес открытого для чтения БДС *)
fpMark : LPMARK (* Массив маркеров (по числу таблиц) *)
):SmallInt;Pascal;
(* Перемещение логического указателя на установленный ранее маркер *)
Function htSeekMarkedRecord(
Var fpSrc : SAB; (* Адрес открытого для чтения БДС *)
Var fpMark : MARKER (* Маркер записи *)
):SmallInt;Pascal;
(* Сортировка результатов поиска (если это записи) *)
(* Положительный номер ключа - сортировка по возрастанию *)
(* Отрицательный номер ключа - сортировка по убыванию *)
Function htSortResults(
Var fpDst: SAB; (* Для приема результата *)
Var fpSrc: SAB; (* Адрес исходного БДС *)
mOrder : PSmallInt; (* Номера ключей упорядочивания *)
nOrderCnt: SmallInt (* Число ключей упорядочивания *)
):SmallInt;Pascal;
(* Сортировка результатов поиска под контролем пользователя *)
Function htSortResultsByUser(
Var fpDst: SAB; (* Для приема результата *)
Var fpSrc: SAB; (* Адрес исходного БДС *)
mOrder : PSmallInt; (* Номера ключей упорядочивания *)
nOrderCnt: SmallInt; (* Число ключей упорядочивания *)
fpfComp : LPOFUNC; (* Функция сравнения элементов *)
fpUser : Pointer (* Параметр пользователя для функции *)
):SmallInt;Pascal;
(* Проверить адекватность результатов поиска. *)
(* Имеет смысл для всех результатов, кроме RES_JOIN. *)
Function htIsResultObsolete(
Var fpSrc : SAB (* Результаты поиска *)
):LPSAB;Pascal;
(* "Сравнять" результаты поиска (записи), привести *)
(* их в соответствие с заданным состоянием таблицы. *)
(* Доступ к исходным результатам должен быть закрыт *)
Function htSyncResults(
Var fpFresh : SAB; (* Блок для приема "свежего" результата *)
Var fpPhoto : SAB; (* Блок с заданным снимком *)
Var fpOld : SAB (* Блок со старым результатом *)
):LPSAB;Pascal;
(* "Освежить" результаты поиска (записи), привести *)
(* их в соответствие с текущим состоянием таблицы. *)
(* Доступ к исходным результатам должен быть закрыт *)
Function htTouchResults(
Var fpFresh : SAB; (* Блок для приема "свежего" результата *)
Var fpOld : SAB (* Блок со старым результатом *)
):LPSAB;Pascal;
(* Константы, определяющие тип результатов, хранимых в БДС *)
(* Возвращаются функцией htResultsType *)
Const RES_NPROC = -1; (* БДС не обработан, или результаты удалены *)
Const RES_RECORD = 0; (* БДС содержит список записей *)
Const RES_VALUE = 1; (* БДС содержит список значений ключа *)
Const RES_HISTO = 2; (* БДС содержит гистограмму *)
Const RES_JOIN = 3; (* БДС содержит результат слияния таблиц *)
Const RES_SORTED = 4; (* БДС содержит отсортированный список записей *)
Const RES_GROUP = 5; (* БДС содержит результаты операции GROUP_BY *)
Const RES_SORTJOIN = 6; (* БДС содержит сортированное слияние таблиц *)
(* Определить номер элемента, для которого получен результат в БДС *)
(* Имеет смысл для результатов типа RES_VALUE и RES_HISTO. *)
Function htResultsElement(
Var fpSrc : SAB; (* Адрес исходного БДС *)
Var fpElemNo: SmallInt (* Номер элемента *)
):SmallInt;Pascal;
(* Определить таблицу, для которой получен результат в БДС *)
(* Имеет смысл для всех результатов, кроме RES_JOIN. *)
Function htResultsTable(
Var fpSrc : SAB; (* Адрес исходного БДС *)
Var fpHandle: THANDLE (* Таблица, для которой получен результат *)
):SmallInt;Pascal;
(* Определить тип результата для БДС *)
(* Возвращает одну из констант RES_????? *)
Function htResultsType( Var fpSrc: SAB ):SmallInt;Pascal;
(* Освободить память из-под результата *)
(* Переносит результаты из памяти в файл *)
Function htResultsToHard( Var fpSrc: SAB ):SmallInt;Pascal;
(* Проверить, открыт ли доступ к результатам поиска *)
(* 0 - нет, !=0 - да *)
Function htIsResultOpen( Var fpSrc: SAB ):Boolean;Pascal;
(* Подменить обработчик таблицы в результатах на дубль *)
(* Результаты должны быть закрыты *)
Function htReplaceResultsTable(
Var fpSrc : SAB; (* Адрес исходного БДС *)
hTable : THANDLE; (* Другой обработчик таблицы *)
nTabNo : SmallInt (* Порядковый номер таблицы для JOIN (от 0) *)
):SmallInt;Pascal;
(*---------- Работа с отдельными записями ----------*)
(* Определить обработчик записи по физ.номеру и снимку *)
(* Если снимок пуст (Nil), берется последнее состояние таблицы *)
Function htHandleFromRecNo(
fpPHO: LPSAB; (* Снимок для записи *)
hTable: THANDLE; (* Обработчик таблицы *)
gRecNo:LongInt; (* Номер записи *)
Var fphHandle:RHANDLE (* Для приема обработчика *)
):SmallInt;Pascal;
(* Определить номер записи по обработчику *)
Function htRecNoFromHandle(
hTable: THANDLE; (* Обработчик таблицы *)
hHandle: RHANDLE (* Обработчик записи *)
):LongInt;Pascal;
(* Добавление записи в таблицу. Аналогична htRecordAdd, *)
(* но возвращает также обработчик добавленной записи. *)
Function htHandleAdd(
hTable: THANDLE; (* Обработчик для таблицы *)
fpRecord: Pointer; (* Тело записи *)
Var fphRecord: RHANDLE (* Обработчик добавленной записи *)
):LongInt;Pascal;
(* Модификация записи в таблице. Аналогична htRecordModify, *)
(* но возвращает также обработчик модифицированной записи. *)
Function htHandleModify(
hTable: THANDLE; (* Дескриптор таблицы *)
gRecNumber: LongInt; (* Номер модифицируемой записи *)
fpRecord: Pointer; (* Тело записи *)
Var fphRecord: RHANDLE (* Обработчик измененной записи *)
):SmallInt;Pascal;
(* Считать тело записи по ее номеру в пределах "снимка" *)
(* Если снимка нет (Nill), читает последнее состояние записи *)
Function htReadRecord(
fpPHO: LPSAB; (* Снимок для записи *)
hTable: THANDLE; (* Дескриптор таблицы *)
gRecNo: LongInt; (* Номер читаемой записи *)
fpBody: Pointer (* Для приема тела записи *)
):SmallInt;Pascal;
(* Считать запись по ее обработчику *)
(* Проверки корректности обработчика не производится *)
Function htReadRecordByHandle(
hTable: THANDLE; (* Обработчик таблицы *)
hHandle: RHANDLE; (* Обработчик читаемой записи *)
fpRecord: Pointer (* Для приема тела записи C НОМЕРОМ *)
):SmallInt;Pascal;
(*---------- Редактирование результатов поиска ----------*)
(* Создать пустой результат для таблицы *)
Function htCreateEmptySAB(
fpPHO: LPSAB; (* Снимок таблицы *)
Var fpSAB: SAB; (* Адрес БДС *)
hTable: THANDLE; (* Обработчик таблицы *)
nItemNo: SmallInt; (* Номер элемента *)
nType: SmallInt (* Тип БДС (см.RES_????) *)
):LPSAB;Pascal;
(* Создать пустой результат для связки таблиц *)
Function htCreateEmptyJoin(
Var fpSAB: SAB; (* БДС *)
fphTabs: LPTHANDLE; (* Обработчики таблиц *)
nTabCnt: SmallInt (* Число таблиц *)
):LPSAB;Pascal;
(* Исключить элемент из результатов поиска *)
(* Доступ к исходным результатам должен быть открыт *)
Function htExcludeResultsItem(
Var fpSrc: SAB; (* Адрес исходного БДС *)
gItemNo: LongInt (* Порядковый номер элемента (от 0) *)
(* RES_RECORD - физ.номер записи *)
):SmallInt;Pascal;
(* Считать элемент результата поиска - обработчик записи(ей) *)
(* Доступ к исходным результатам должен быть открыт *)
(* Допустим для результатов RES_SORTED и RES_JOIN *)
Function htGetResultsItem(
Var fpSrc: SAB; (* Адрес исходного БДС *)
gItemNo: LongInt; (* Порядковый номер элемента (от 0) *)
fpItem: LPRHANDLE (* Для чтения элемента результата *)
(* Длина элемента определяется типом результата: *)
(* RES_SORTED - sizeof(RHANDLE) *)
(* RES_JOIN - sizeof(RHANDLE) * число_таблиц_слияния *)
):SmallInt;Pascal;
(* Добавить пачку элементов в результаты поиска *)
(* Доступ к исходным результатам должен быть открыт *)
Function htIncludeResultsBlock(
Var fpSrc: SAB; (* Адрес исходного БДС *)
gInsPos: LongInt; (* Позиция вставки элемента (отсчет от 0) *)
(* RES_RECORD - не имеет смысла *)
fpBlock: Pointer; (* Пачка новых элементов результата *)
wBlockLen: Cardinal (* Длина пачки в байтах *)
):SmallInt;Pascal;
(* Добавить элемент в результаты поиска *)
(* Доступ к исходным результатам должен быть открыт *)
Function htIncludeResultsItem(
Var fpSrc: SAB; (* Адрес исходного БДС *)
gItemNo: LongInt; (* Позиция вставки элемента (отсчет от 0) *)
(* RES_RECORD - физ.номер записи *)
fpNewItem: Pointer (* Новый элемент результата: *)
(* RES_SORTED - обработчик записи *)
(* RES_JOIN - группа обработчиков записей для таблиц слияния *)
(* RES_VALUE, RES_HISTO, RES_GROUP - тело элемента *)
):SmallInt;Pascal;
(* Заменить элемент в результатах поиска *)
(* Доступ к исходным результатам должен быть открыт *)
Function htReplaceResultsItem(
Var fpSrc: SAB; (* Адрес исходного БДС *)
gItemNo: LongInt; (* Позиция элемента (отсчет от 0) *)
fpNewItem: Pointer (* Новый элемент результата: *)
(* RES_SORTED - обработчик записи *)
(* RES_JOIN - группа обработчиков записей для таблиц слияния *)
(* RES_VALUE, RES_HISTO, RES_GROUP - тело элемента *)
):SmallInt;Pascal;
(*---------- Вывод результатов поиска в таблицу ----------*)
(* Описатель, используемый при обработке записей *)
(* Эта структура передается как параметр при вызове *)
(* пользовательской функции из функции htResultsToTable *)
Type RPARM=Record
gDstRecNum : LongInt; (* Номер текущей образуемой записи *)
gSrcItemNum: LongInt; (* Номер текущего исходного элемента *)
wDstRecLen : Cardinal;(* Длина образуемой записи *)
wSrcItemLen: Cardinal;(* Длина исходного элемента *)
fpSrcItem : Pointer; (* Тело исходного элемента *)
fpDstRec : Pointer; (* Буфер для приема образуемой записи *)
End;
(* Прототип пользовательской функции, вызываемой *)
(* при обработке результатов для каждой записи. *)
(* Функция должна возвращать: *)
(* >0 - преобразование выполнено *)
(* =0 - прекратить процесс вывода *)
(* <0 - пропустить данную запись *)
Type RFUNC=Function(
Var fpParm: RPARM; (* Параметры вывода *)
fpUser : Pointer (* Доп.параметр пользователя *)
):SmallInt;
LPRFUNC=^RFUNC;
(* Преобразование результатов в таблицу *)
(* Выполняется чтение результатов и запись их в таблицу hOutTable. *)
(* На каждый элемент результата выполняется вызов fpfRecProc(), которая *)
(* может произвести необходимую доработку элемента результата по прев- *)
(* ращению его в запись таблицы hOutTable. Каждая запись этой таблицы *)
(* проверяется на допустимость значений. В случае ошибки вызывается *)
(* функция fpfErrProc. Для результатов-записей (RES_RECORD, RES_SORTED, *)
(* RES_JOIN) могут быть заданы номера полей, которые будут отбираться *)
(* для формирования выходной записи. *)
(* Возвращает число отвергнутых записей или код ошибки *)
Function htResultsToTable(
Var fpSrc : SAB; (* Адрес исходного БДС *)
hOutTable : THANDLE; (* Обработчик для заполняемой таблицы *)
fpfRecProc: LPRFUNC; (* Пользовательская функция обработки записи *)
(* Nil - обработка не нужна (все готово) *)
fpfErrProc: LPEFUNC; (* Пользовательская функция обработки ошибок *)
(* Nil - ошибки прерывают ввод *)
fpUser : Pointer; (* Доп.параметр пользователя *)
(* Следующие имеют смысл для результатов - записей *)
fpElemNo : PSmallInt;(* Номера выводимых элементов исх.записи *)
nElemCnt : SmallInt; (* Число выводимых элементов *)
bDenyOut : Boolean; (* Для true вывод отвергнутых записей в таблицу *)
bCorrect : Boolean (* Для true коррекция суррогатного и авто-ключей *)
):LongInt;Pascal;
(*------------------- Управление доступом ------------------*)
(* Сменить крипто-ключ закрытия данных *)
(* Таблица должна быть закрыта *)
Function htChangeCryptoKey(
fpTableName: PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
fpOldCrypto: PChar; (* Старый крипто-ключ закрытия данных *)
fpNewCrypto: PChar; (* Новый крипто-ключ закрытия данных *)
bReIndex : Boolean (* Перепостроить индексы *)
):SmallInt;Pascal;
(* Сменить пароль доступа на чтение *)
(* Таблица должна быть закрыта *)
Function htChangeReadPassword(
fpTableName : PChar; (* Имя таблицы (можно без расширения) *)
fpWritePswd : PChar; (* Пароль доступа на запись *)
fpOldReadPswd: PChar; (* Старый пароль доступа на чтение *)
fpNewReadPswd: PChar (* Новый пароль доступа на чтение *)
):SmallInt;Pascal;
(* Сменить пароль доступа на запись *)
(* Таблица должна быть закрыта *)
Function htChangeWritePassword(
fpTableName : PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpOldWritePswd: PChar; (* Старый пароль доступа на запись *)
fpNewWritePswd: PChar (* Новый пароль доступа на запись *)
):SmallInt;Pascal;
(*-------------------- Сетевая поддержка -------------------*)
(* Определить свободные от захвата записи и захватить их *)
Function htHoldFreeRecords(
hTable : THANDLE; (* Обработчик таблицы *)
Var fdDst: SAB (* Блок для списка свободных от захвата записей *)
):LPSAB;Pascal;
(* Захватить запись таблицы *)
Function htHoldRecord(
hTable: THANDLE; (* Обработчик таблицы *)
gRecNo: LongInt (* Номер захватываемой записи *)
):SmallInt;Pascal;
(* Захватить запись таблицы и считать ее тело *)
Function htHoldReadRecord(
hTable : THANDLE; (* Обработчик таблицы *)
gRecNo : LongInt; (* Номер захватываемой записи *)
fpRecord: Pointer (* Для приема тела записи *)
):SmallInt;Pascal;
(* Захватить результаты поиска - множество записей *)
Function htHoldResults( Var fpSrc: SAB ):SmallInt;Pascal;
(* Захватить таблицу целиком *)
Function htHoldTable( hTable: THANDLE ):SmallInt;Pascal;
(* Освободить захваченную запись таблицы *)
Function htReleaseRecord(
hTable: THANDLE; (* Обработчик таблицы *)
gRecNo: LongInt (* Номер захватываемой записи *)
):SmallInt;Pascal;
(* Освободить захваченные результаты поиска - множество записей *)
Function htReleaseResults( Var fpSrc: SAB ):SmallInt;Pascal;
(* Освободить захваченную таблицу *)
Function htReleaseTable( hTable: THANDLE ):SmallInt;Pascal;
(* Установить таймаут для сетевых операций *)
Procedure htSetLockTimeOut(
Second:Word (* Величина таймаута в секундах *)
);Pascal;
(*------------------- Поддержка транзакций -----------------*)
(* Флаги задания режимов системы транзакций *)
(* Устанавливаются в переменной HTCOD1.htTrsMode *)
(* Могут комбинироваться операцией OR *)
Const TRS_OFF =0; (* Выключить систему транзакций *)
Const TRS_ON =1; (* Включить систему транзакций *)
Const TRS_PREP =2; (* Предварительное распределение ресурсов *)
Const TRS_FLUSH =4; (* Немедленная запись журнала транзакции на диск *)
Const TRS_ALONE =8; (* Транзакции на одной локальной машине *)
Const TRS_EASY =1; (* "Облегченный" режим работы системы транзакций *)
Const TRS_HARD =7; (* "Полный" режим работы системы транзакций *)
(* Описатель идентифкатора транзакции *)
(* Эта запись используется функциями управления транзакциями *)
Type TRID=Record
mTrID: Array [1..6] of Byte; (* Идентификатор транзакции *)
End;
(* Установить таймаут для транзакций *)
Procedure htSetTransTimeOut(
Second:Word (* Величина таймаута в секундах *)
);Pascal;
(* Начать транзакцию на группе таблиц *)
Function htStartTransaction(
fpTables: LPTHANDLE; (* Список обработчиков таблиц *)
nTabCnt : SmallInt; (* Число таблиц в списке *)
Var fpTrans:TRID (* Для приема идентификатора транзакции *)
):SmallInt;Pascal;
(* Успешное завершение транзакции *)
Function htCommitTransaction(
Var fpTrans:TRID (* Идентификатор транзакции *)
):SmallInt;Pascal;
(* Аварийное завершение транзакции *)
Function htRollBackTransaction(
Var fpTrans:TRID (* Идентификатор транзакции *)
):SmallInt;Pascal;
(* Проверить необходимость отката транзакции для таблицы *)
(* Можно вызывать после получения ошибки HT_ERR_TRT_ROLLED *)
(* при поиске таблиц, вызвавших эту ошибку и их транзакции *)
Function htIsNeedToRoll(
hTable : THANDLE; (* Обработчик таблицы *)
Var fpTrans:TRID (* Идентификатор транзакции *)
):SmallInt;Pascal;
(* Проверить принадлежность таблицы какой-либо транзакции *)
Function htIsTransactionalTable(
hTable : THANDLE (* Обработчик таблицы *)
):SmallInt;Pascal;
(*--------------------- Кодификаторы ----------------------*)
(* Кодификатор - упорядоченные пары {ключ:толкование}. *)
(* Используются для расширенного толкования значений ключа *)
(* при операциях чтения результатов. *)
(* Длина толкования ключа не может быть короче ключа. *)
(* Перед использованием кодификатор должен быть загружен *)
(* в память. *)
(* Описатель поля чтения *)
(* Используется при открытии доступа к кодированным записям *)
(* для указания отбираемых полей и порядка их расположения. *)
Type CDF=Record
nFieldNum :SmallInt; (* Номер поля *)
hCoder :CHANDLE; (* Кодификатор для поля (0 - нет кодификатора) *)
End;
Type LPCDF=^CDF; (* Длинная ссылка на описатель *)
(* Информация о кодификаторе *)
Type CODINF=Record
wItemCnt :Cardinal; (* Число элементов в кодификаторе *)
nItemLen :SmallInt; (* Длина элемента в кодификаторе *)
nKeyType :SmallInt; (* Тип ключа кодификатора *)
nKeyLen :SmallInt; (* Длина ключа кодификатора *)
nNameLen :SmallInt; (* Длина толкования *)
pArray :Pointer; (* Массив ключ-толкование *)
End;
(* Получить информацию о кодификаторе *)
Function htCoderInfo(
hCoder : CHANDLE; (* Обработчик кодификатора *)
Var fpInfo: CODINF (* Структура для заполнения *)
):SmallInt;Pascal;
(* Найти ключ для заданного толкования *)
Function htFindCoderKey(
hCoder : CHANDLE; (* Обработчик кодификатора *)
fpKey : Pointer; (* Для приема значения ключа *)
fpValue: Pointer (* Тестируемое значение толкования *)
):SmallInt;Pascal;
(* Найти для заданного ключа его толкование *)
Function htFindCoderValue(
hCoder : CHANDLE; (* Обработчик кодификатора *)
fpKey : Pointer; (* Тестируемое значение ключа *)
fpValue: Pointer (* Для приема значения толкования *)
):SmallInt;Pascal;
(* Загрузить кодификатор в память *)
(* Таблица может быть уже открыта *)
Function htLoadCoder(
fpTableName : PChar; (* Имя таблицы (можно без расширения) *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
nOpenMode : SmallInt; (* Режим ее открытия (если еще не открыта) *)
anFieldsNum : PSmallInt;(* Задействованные номера полей таблицы *)
(* Первый номер - номер ключа для кодификатора *)
(* Последующие номера задают поля, образующие толкование ключа *)
nFieldCnt : SmallInt; (* Число полей в массиве *)
Var fpCoder : CHANDLE (* Для приема обработчика кодификатора *)
):SmallInt;Pascal;
(* Удалить кодификатор из памяти *)
Procedure htPurgeCoder(
hCoder : CHANDLE (* Обработчик кодификатора *)
);Pascal;
(* Считать кодификатор в прямом или обратном порядке *)
(* Прямой порядок - сортировка по значению кода *)
(* Буфер содержит пары {ключ:толкование} *)
(* Обратный порядок - сортировка по значению толкования *)
(* Буфер содержит пары {толкование:ключ} *)
Function htReadCoder(
hCoder : CHANDLE; (* Обработчик кодификатора *)
fpBuf : Pointer; (* Буфер для чтения *)
bInverse: Boolean (* true - вывод в обратном порядке *)
):SmallInt;Pascal;
(* Открыть доступ к результатам поиска в БДС *)
(* в случае, если поля записей имеют кодификаторы *)
Function htOpenCodedResults(
Var fpSrc : SAB; (* Адрес исходного БДС *)
fpFields : LPCDF; (* Описатели читаемых элементов *)
nFieldCnt : SmallInt (* Число читаемых элементов *)
):SmallInt;Pascal;
(* Преобразование кодированных результатов в таблицу *)
(* Функция аналогична htResultsToTable, но позволяет выполнить *)
(* декодирование полей. *)
Function htCodedResultsToTable(
Var fpSrc : SAB; (* Адрес исходного БДС *)
hOutTable : THANDLE; (* Обработчик для заполняемой таблицы *)
fpfRecProc: LPRFUNC; (* Пользовательская функция обработки записи *)
(* Nil - обработка не нужна (все готово) *)
fpfErrProc: LPEFUNC; (* Пользовательская функция обработки ошибок *)
(* Nil - ошибки прерывают ввод *)
fpUser : Pointer; (* Доп.параметр пользователя *)
fpElemNo : LPCDF; (* Номера выводимых элементов исх.записи *)
nElemCnt : SmallInt; (* Число выводимых элементов *)
bDenyOut : Boolean; (* Для true вывод отвергнутых записей в таблицу *)
bCorrect : Boolean (* Для true коррекция суррогатного и авто-ключей *)
):LongInt;Pascal;
(*------------------------ Импорт/экспорт --------------------------*)
(* Варианты отображения даты в символьном виде *)
(* Используются в описателе формата при операциях импорта/экспорта *)
Type DATES=(
DATE1, (* дд мм гг - Израиль *)
DATE2, (* дд-мм-гг - Великобритания *)
DATE3, (* дд.мм.гг - Германия *)
DATE4, (* дд/мм/гг - Россия *)
DATE5, (* мм-дд-гг - Америка *)
DATE6, (* гг-мм-дд - Азия *)
DATE7 (* ггггммдд - dBase *)
);
(* Варианты выходных файлов экспорта *)
EXPMODE=(
EXP_ASCII, (* Выходный файл - текстовый файл *)
EXP_DBASE (* Выходный файл - файл dBaseIII *)
);
(* Варианты исходных файлов импорта *)
IMPMODE=(
IMP_ASCII, (* Исходный файл - регулярный текстовый файл *)
IMP_DBASE, (* Исходный файл - файл dBaseIII *)
IMP_HYTECH (* Исходный файл - файл HyTech 1.6 *)
);
(* Формат вывода FLOAT (например '%- 10.2f') *)
(* '%' - признак форматирования *)
(* '-' - выравнивание вправо (иначе - влево) *)
(* ' ' - заполнитель при выравнивании (можно '0') *)
(* '10' - общая ширина вывода числа - 10 символов *)
(* '.2' - точность (число десятичных разрядов) *)
(* 'f' - вывод с фиксированной точкой *)
FLOAT_FMT = Array [0..8] Of Char;
(* Формат вывода DOUBLE (например '%- 12.6lE') *)
(* '%' - признак форматирования *)
(* '-' - выравнивание вправо (иначе - влево) *)
(* ' ' - заполнитель при выравнивании (можно '0') *)
(* '12' - общая ширина вывода числа - 12 символов *)
(* '.6' - точность (число десятичных разрядов) *)
(* 'l' - числой двойной точности (double) *)
(* 'E' - число будет иметь десятичный порядок (можно 'e') *)
DOUBLE_FMT = Array [0..9] Of Char;
(* Описатель параметров преобразования символьных и цифровых *)
(* данных при импорте/экспорте *)
FORMAT=Record
nDateType : SmallInt; (* Тип даты (DATES) *)
bCentury : SmallInt; (* Полный год, если TRUE *)
mFloatFormat:FLOAT_FMT; (* Формат вывода float *)
mDoubleFormat:DOUBLE_FMT; (* Формат вывода double *)
mCurrencyFormat:DOUBLE_FMT; (* Формат вывода currency *)
End;
LPFORMAT = ^FORMAT;
(* Операция экспорта данных таблицы в файлы других форматов *)
(* Таблица может быть открыта *)
Function htExport(
nMode: EXPMODE; (* Тип экспорта *)
fpSrcTabName:PChar; (* Имя таблицы исходного файла *)
fpReadPswd: PChar; (* Пароль чтения *)
nOpenMode: SmallInt; (* Режим открытия исходной таблицы *)
fpDstName: PChar; (* Имя порождаемого файла *)
fpFmt: LPFORMAT (* Описатель форматов *)
):SmallInt;Pascal;
(* Операция импорта данных таблицы из файлов других форматов *)
(* Таблица должна быть закрыта *)
Function htImport(
nMode: IMPMODE; (* Тип импорта *)
fpDstTabName:PChar; (* Имя таблицы, образуемой при импорте *)
fpReadPswd: PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
nOpenMode: SmallInt; (* Режим открытия образуемой таблицы *)
fpSrcName: PChar; (* Имя исходного файла *)
fpSrcTabName:PChar; (* Имя таблицы для исходного ASCII файла *)
fpFmt: LPFORMAT; (* Описатель форматов *)
bLogFile: Boolean; (* !=0 вести журнал импорта *)
bToConst: Boolean (* !=0 вывод в постоянную часть таблицы *)
):LongInt;Pascal;
(* Операция импорта описателя таблицы из файлов других форматов *)
(* Допустимы только типы dBase и HyTech1.6 *)
Function htImportTitle(
fpSrcName : PChar; (* Имя исходного файла dBase или HyTech 1.6 *)
fpTableName: PChar; (* Имя таблицы, образуемой при импорте *)
fpCryptoKey: PChar; (* Пароль шифрования данных *)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
bAnsi : Boolean (* Образуем ANSI-таблицу *)
):SmallInt;Pascal;
(* Операция вывода данных таблицы в другую таблицу *)
(* Исходная таблица может быть открыта, *)
(* таблица-приемник - должна быть закрыта *)
Function htOutTo(
fpSrcTabName: PChar; (* Имя таблицы исходного файла *)
fpReadPswd: PChar; (* Пароль чтения *)
nOpenMode: SmallInt;(* Режим открытия исходной таблицы *)
fpDstTabName: PChar; (* Имя таблицы, образуемой при выводе *)
fpDstReadPswd: PChar; (* Пароль доступа на чтение *)
fpDstWritePswd:PChar; (* Пароль доступа на запись *)
fpFmt: LPFORMAT;(* Описатель форматов *)
bLogFile: Boolean; (* TRUE - вести журнал вывода *)
bCorrect: Boolean (* TRUE - коррекция суррогатного и авто-ключей *)
):LongInt;Pascal;
(*------------- Поддержка распределенных таблиц ------------*)
(* Типы регистрируемых в журнале операций *)
Const LOG_ADD = 0; (* Добавление записи *)
Const LOG_DEL = 1; (* Удаление записи *)
Const LOG_MDF = 2; (* Модификация записи *)
(* Описатель доступа к журналу изменений *)
Type LOGON=Record
wItemLen: Cardinal; (* Длина читаемого элемента журнала *)
gItemCnt: LongInt; (* Число элементов в журнале *)
mSystem: Array [1..128] of Char; (* Будет использоваться СУБД *)
End;
(* Закрыть доступ к журналу изменений *)
Procedure htLogClose(
Var sLog:LOGON (* Описатель доступа к журналу *)
);Pascal;
(* Открыть доступ к журналу изменений *)
Function htLogOpen(
fpTableName: PChar; (* Имя таблицы (можно без расширения)*)
fpReadPswd : PChar; (* Пароль доступа на чтение *)
fpWritePswd: PChar; (* Пароль доступа на запись *)
fpElemNo: PSmallInt; (* Номера читаемых элементов записи *)
(* Если Nil - читаются все элементы записи *)
nElemCnt: SmallInt; (* Число читаемых элементов *)
Var sLog: LOGON (* Описатель доступа к журналу *)
):SmallInt;Pascal;
(* Считать пачку записей (или их полей) из журнала изменений *)
(* Читаются элементы журнала изменений таблицы, начиная с заданного. *)
(* Каждый элемент предваряется байтом с признаком операции (LOG_???). *)
(* Под элементом понимается вся запись с номером или ее заданнные поля.*)
Function htLogRead(
Var sLog: LOGON; (* Описатель доступа к журналу *)
gStart: LongInt; (* Номер первого читаемого элемента журнала (от 0) *)
fpBuf: Pointer; (* Буфер для чтения записей *)
wBufLen: Cardinal (* Длина буфера *)
):Word;Pascal;
(*------------ Резервное копирование/восстановление таблицы -----------*)
(* Сделать резервную копию таблицы от заданного снимка. *)
(* Копия представляет собой неиндексированную постоянную часть. *)
Function htBackupTable(
cpPhoto: LPSAB; (* Снимок таблицы *)
hTable: THANDLE; (* Таблица *)
cpNewName: PChar (* Имя резервной копии *)
):SmallInt;Pascal;
(* Восстановить таблицу с резервной копии (копирует и индексирует). *)
(* Требуется совпадение паролей у копии и существующей таблицы. *)
(* Возвращает: число отвергнутых при индексировании записей или код ошибки. *)
Function htRestoreTable(
pBackName : PChar; (* Имя резервной копии *)
pReadPswd : PChar; (* Пароль доступа на чтение к резервной копии *)
pWritePswd : PChar; (* Пароль доступа на запись к исходной таблице *)
pTabName : PChar (* Имя восстанавливаемой таблицы *)
):LongInt;Pascal;
(*------------------------ Прочее --------------------------*)
(* Прервать выполнение текущей операции HyTech *)
(* Не меняет содержимое регистров и флагов процессора. *)
(* Можно вызывать, например, из обработчика Ctrl-Break *)
Procedure htBreak;Pascal;
(* Установить задержку опроса сети *)
Procedure htSetPollDelay( wMSec: Word );Pascal;
(* Получить "снимок" таблицы без выполнения поиска *)
Function htMakePhoto(
Var fpPhoto : SAB; (* БДС для "снимка" *)
hTable : THANDLE (* Обработчик для таблицы *)
):LPSAB;Pascal;
(* Получить "снимки" нескольких таблиц одномоментно *)
Function htMakeGroupPhoto(
fpPhotos : LPSAB; (* БДС'ы для "снимков" *)
fphTables : LPTHANDLE; (* Обработчики таблиц *)
nTabCnt: SmallInt (* Число таблиц в группе *)
):SmallInt;Pascal;
(* Получить текстовую строку по коду завершения функции *)
(* Возвращает сообщение типа 'Нет памяти для работы'. *)
Function htErrorMessage(
nCode: SmallInt; (* Код завершения *)
lpszBuff80: PChar (* Буфер для приема текста сообщения *)
):PChar;Pascal;
(* Получить дополнительную информацию о последней ошибке HyTech *)
(* Возвращает имя файла, при работе с которым произошла ошибка, *)
(* а также код ошибки ДОС и код операции, приведшей к ошибке. *)
(* Последующие ошибки переписывают данные о предыдущей. *)
Function htExtError(
Var nDosError : SmallInt; (* Сюда занесут код, возвращенный ДОС *)
Var nOperation: SmallInt; (* Сюда занесут код операции, приведшей /к ошибке *)
lpszBuff140: PChar (* Буфер для приема имени файла *)
):PChar;Pascal;
(* Получить дополнительную информацию о последней ошибке HyTech *)
(* Возвращает текстовую строку, содержащую название операции, *)
(* имя файла и возможную причину ошибки. *)
(* Последующие ошибки переписывают данные о предыдущей. *)
Function htIOMessage(
lpszBuff220: PChar (* Буфер для приема текста сообщения *)
):PChar;Pascal;
(* Функция возвращает указатель на строку содержащую сообщение *)
(* в зависимости от типа ошибки (В/В или прочие), например: *)
(* "Нет памяти для работы" или *)
(* "Ошибка открытия d:\xxxx файл не найден". *)
Function htMessage(
nRetCode: SmallInt; (* Код сообщения *)
lpszBuff220: PChar (* Буфер для приема текста сообщения *)
):PChar;Pascal;
(* Очистить информацию о предыдущей ошибке СУБД *)
Procedure htPurgeError;Pascal;
(* Определить каталог сетевых замков *)
(* Имя каталога имеет замыкающий '\' *)
Procedure htNetPath( Var stBuf: PathStr );Pascal;
(* Определить каталог временных файлов *)
(* Имя каталога имеет замыкающий '\' *)
Procedure htTmpPath( Var stBuf: PathStr );Pascal;
(* Дата и время инициализации HyTech *)
(* Формат даты и времени как принято в ДОС для файлов *)
(* Младшее слово возврата - время, старшее - дата *)
Function htStartTimeDate: LongInt;Pascal;
(* Проверка установки поля в "пустое" значение *)
Function htIsFieldNull(
nType :SmallInt; (* Тип поля *)
wLen :Cardinal; (* Длина поля *)
pField :Pointer (* Тело проверямого поля *)
):SmallInt;Pascal;
(* Установка поля в "пустое" значение *)
Function htNullField(
nType :SmallInt; (* Тип поля *)
nKeyType:SmallInt; (* Тип ключа *)
wLen :Cardinal; (* Длина поля *)
fpField :Pointer (* Тело ключа *)
):SmallInt;Pascal;
(* Установка записи в "пустое" значение *)
Function htNullRecord(
hTable:THANDLE; (* Обработчик таблицы *)
fpRec :Pointer (* Адрес тела записи *)
):SmallInt;Pascal;
(* Преобразование строки в массив байтов *)
(* Копирует строку в массив и дополняет символами #0 *)
Procedure htStringToArray(
fpArray : Pointer; (* Адрес массива-приемника *)
fpString: PChar; (* Адрес исходной строки *)
wDimens : Cardinal (* Длина массива *)
);Pascal;
(* Преобразование строки в массив символов *)
(* Копирует строку в массив и дополняет пробелами *)
Procedure htStringToChars(
fpChars : Pointer; (* Адрес массива символов *)
fpString: PChar; (* Адрес исходной строки *)
wDimens : Cardinal (* Длина массива *)
);Pascal;
(* Режимы капитализации регистра симоволов строки *)
Type CASE_MODE = (
CASE_NATIVE, (* Сохранить исходный регистр символов *)
CASE_ANSI_UP, (* Капитализировать в ANSI *)
CASE_OEM_UP (* Капитализировать в OEM *)
);
(* Сравнить массив символов с шаблоном *)
(* =0 - равны, <>0 - не равны *)
Function htWildCmp(
fpArray : PChar; (* Адрес сканируемого массива *)
wDimens : Word; (* Длина массива *)
fpWild : PChar; (* Адрес шаблона (ASCIIZ-строки) *)
nCaseMode: CASE_MODE (* Режим капитализации регистра *)
):SmallInt;Pascal;
(* Для преобразования даты в/из внутреннего представления. *)
(* Дата хранится в записи в виде целого числа без знака, *)
(* определяющего номер дня, считая от 01.01.1900 (понедельник).*)
(* Для получения дня недели - взять остаток от деления даты на *)
(* 7 (0-воскресенье, 1 - понедельник и т.п.). *)
Type DATE=Record
Day : Byte; (* День - отсчет от 1 *)
Month: Byte; (* Месяц - отсчет от 1 *)
Year : SmallInt; (* Год - в виде 1993 *)
End;
(* Преобразование даты во внутренний формат (целое без знака) *)
(* Неверно заданные даты дают на выходе 0. *)
Function htDateToWord( sDate: DATE ):Word;Pascal;
(* Преобразование даты из внутреннего формата в структуру *)
Procedure htWordToDate( wWord: Word; Var sDate: DATE);Pascal;
Type
(* Одно изменение таблицы *)
CHANGER=Record
gNumber:LongInt; (* Физ.номер *)
hRecord:RHANDLE; (* Обработчик записи *)
End;
LPCHANGER=^CHANGER;
(* Получить состояние таблицы (снимок) для БДС *)
Function htTableSABStat(
Var pSAB: SAB; (* Результат поиска *)
Var pStat: STATT (* Состояние таблицы *)
):SmallInt;Pascal;
(* Определить длину диф.части для БДС на момент поиска *)
Function htGetDiffLength(Var fpSAB:SAB):LongInt;Pascal;
(* Считать пачку описателей изменений БДС с заданной позиции журнала *)
Function htReadSABChanges(
Var fpSAB:SAB;
fpBuf:LPCHANGER;
nCnt:SmallInt;
Var gPos:LongInt
):SmallInt;Pascal;
(* Считать пачку описателей изменений с заданной позиции журнала *)
Function htReadTableChanges(
hTable:THANDLE;
gStart:LongInt;
fpBuf:LPCHANGER;
nCnt:SmallInt;
Var gPos:LongInt
):SmallInt;Pascal;
Type
(* Описатель хозяина таблицы или ее части *)
OWNER=Record
nOrdinal:SmallInt; (* Порядковый номер экземпляра *)
szUser: NameStr; (* Имя станции в сети *)
End;
(* Определить захватчика записи *)
Function htWhoLockRecord(
fpTabName:PChar;
gRecNo:LongInt;
Var sOwner:OWNER
):SmallInt;Pascal;
(* Определить захватчика множества записей *)
Function htWhoLockSet(Var sSAB:SAB;Var sOwner:OWNER):SmallInt;Pascal;
(* Определить захватчика таблицы *)
Function htWhoLockTable(fpTabName:PChar;Var sOwner:OWNER):SmallInt;Pascal;
(* Управление флагом подмены обработчика CtrlBreak (вызов SetConsoleCtrlHandler) *)
(* Возвращает старое состояние флаги и проставляет новое *)
(* Ненулевой флаг запрещает подмену обработчика в функциях HyTech *)
Function htCtrlCtrl(NewState: Integer):Integer;Pascal;
(* Свободная память в заданной куче процесса *)
Function htMemoAvailByTask(hTask : LongWord;bGlobal : ShortInt) : LongInt;Pascal;
(* Печать заданной кучи процесса *)
Procedure htPrintHytechHeap(hTask : LongWord;bGlobal : ShortInt);Pascal;
IMPLEMENTATION
Function htAddRecords; external 'HTW32PAS.DLL' name 'HTADDRECORDS' ;
Function htAndResults; external 'HTW32PAS.DLL' name 'HTANDRESULTS' ;
Function htAverageOfKeyValues; external 'HTW32PAS.DLL' name 'HTAVERAGEOFKEYVALUES' ;
Function htBuildIndexes; external 'HTW32PAS.DLL' name 'HTBUILDINDEXES' ;
Function htBackupTable; external 'HTW32PAS.DLL' name 'HTBACKUPTABLE' ;
Function htChangeCryptoKey; external 'HTW32PAS.DLL' name 'HTCHANGECRYPTOKEY' ;
Function htChangeKeyType; external 'HTW32PAS.DLL' name 'HTCHANGEKEYTYPE' ;
Function htChangeReadPassword; external 'HTW32PAS.DLL' name 'HTCHANGEREADPASSWORD' ;
Function htChangeWritePassword; external 'HTW32PAS.DLL' name 'HTCHANGEWRITEPASSWORD' ;
Procedure htCloseResults; external 'HTW32PAS.DLL' name 'HTCLOSERESULTS' ;
Function htClusterItemToLink; external 'HTW32PAS.DLL' name 'HTCLUSTERITEMTOLINK' ;
Function htClusterRecsToLink; external 'HTW32PAS.DLL' name 'HTCLUSTERRECSTOLINK' ;
Function htCodedResultsToTable; external 'HTW32PAS.DLL' name 'HTCODEDRESULTSTOTABLE' ;
Function htCoderInfo; external 'HTW32PAS.DLL' name 'HTCODERINFO' ;
Function htCommitTransaction; external 'HTW32PAS.DLL' name 'HTCOMMITTRANSACTION' ;
Function htCompareTabHandles; external 'HTW32PAS.DLL' name 'HTCOMPARETABHANDLES' ;
Function htCopyResults; external 'HTW32PAS.DLL' name 'HTCOPYRESULTS' ;
Function htCreateClusterTable; external 'HTW32PAS.DLL' name 'HTCREATECLUSTERTABLE' ;
Function htCreateEmptySAB; external 'HTW32PAS.DLL' name 'HTCREATEEMPTYSAB' ;
Function htCreateEmptyJoin; external 'HTW32PAS.DLL' name 'HTCREATEEMPTYJOIN' ;
Function htDateToWord; external 'HTW32PAS.DLL' name 'HTDATETOWORD' ;
Function htDeleteRecords; external 'HTW32PAS.DLL' name 'HTDELETERECORDS' ;
Function htDistinctResults; external 'HTW32PAS.DLL' name 'HTDISTINCTRESULTS' ;
Function htDistinctResultsByCount; external 'HTW32PAS.DLL' name 'HTDISTINCTRESULTSBYCOUNT';
Function htDivision; external 'HTW32PAS.DLL' name 'HTDIVISION' ;
Function htDropIndexes; external 'HTW32PAS.DLL' name 'HTDROPINDEXES' ;
Function htDropTable; external 'HTW32PAS.DLL' name 'HTDROPTABLE' ;
Function htDropTableChanges; external 'HTW32PAS.DLL' name 'HTDROPTABLECHANGES' ;
Function htDropTableData; external 'HTW32PAS.DLL' name 'HTDROPTABLEDATA' ;
Function htDupTableHandle; external 'HTW32PAS.DLL' name 'HTDUPTABLEHANDLE' ;
Function htErrorMessage; external 'HTW32PAS.DLL' name 'HTERRORMESSAGE' ;
Function htExcludeResultsItem; external 'HTW32PAS.DLL' name 'HTEXCLUDERESULTSITEM' ;
Function htExport; external 'HTW32PAS.DLL' name 'HTEXPORT' ;
Function htExtError; external 'HTW32PAS.DLL' name 'HTEXTERROR' ;
Function htFilterRecords; external 'HTW32PAS.DLL' name 'HTFILTERRECORDS' ;
Function htFilterTables; external 'HTW32PAS.DLL' name 'HTFILTERTABLES' ;
Function htFindCoderKey; external 'HTW32PAS.DLL' name 'HTFINDCODERKEY' ;
Function htFindCoderValue; external 'HTW32PAS.DLL' name 'HTFINDCODERVALUE' ;
Function htFlushTable; external 'HTW32PAS.DLL' name 'HTFLUSHTABLE' ;
Function htGetDiffLength; external 'HTW32PAS.DLL' name 'HTGETDIFFLENGTH' ;
Function htGetResultsItem; external 'HTW32PAS.DLL' name 'HTGETRESULTSITEM' ;
Function htGlobalInit; external 'HTW32PAS.DLL' name 'HTGLOBALINIT' ;
Procedure htGlobalShut; external 'HTW32PAS.DLL' name 'HTGLOBALSHUT' ;
Function htGroupByHavingTo; external 'HTW32PAS.DLL' name 'HTGROUPBYHAVINGTO' ;
Function htGroupByUser; external 'HTW32PAS.DLL' name 'HTGROUPBYUSER' ;
Function htHandleAdd; external 'HTW32PAS.DLL' name 'HTHANDLEADD' ;
Function htHandleFromRecNo; external 'HTW32PAS.DLL' name 'HTHANDLEFROMRECNO' ;
Function htHandleModify; external 'HTW32PAS.DLL' name 'HTHANDLEMODIFY' ;
Function htHistogramByCount; external 'HTW32PAS.DLL' name 'HTHISTOGRAMBYCOUNT' ;
Function htHistogramOfKey; external 'HTW32PAS.DLL' name 'HTHISTOGRAMOFKEY' ;
Function htHoldFreeRecords; external 'HTW32PAS.DLL' name 'HTHOLDFREERECORDS' ;
Function htHoldReadRecord; external 'HTW32PAS.DLL' name 'HTHOLDREADRECORD' ;
Function htHoldRecord; external 'HTW32PAS.DLL' name 'HTHOLDRECORD' ;
Function htHoldResults; external 'HTW32PAS.DLL' name 'HTHOLDRESULTS' ;
Function htHoldTable; external 'HTW32PAS.DLL' name 'HTHOLDTABLE' ;
Function htImport; external 'HTW32PAS.DLL' name 'HTIMPORT' ;
Function htImportTitle; external 'HTW32PAS.DLL' name 'HTIMPORTTITLE' ;
Function htIncludeResultsBlock; external 'HTW32PAS.DLL' name 'HTINCLUDERESULTSBLOCK' ;
Function htIncludeResultsItem; external 'HTW32PAS.DLL' name 'HTINCLUDERESULTSITEM' ;
Function htInit; external 'HTW32PAS.DLL' name 'HTINIT' ;
Function htIOMessage; external 'HTW32PAS.DLL' name 'HTIOMESSAGE' ;
Function htIsNeedToRoll; external 'HTW32PAS.DLL' name 'HTISNEEDTOROLL' ;
Function htIsResultObsolete; external 'HTW32PAS.DLL' name 'HTISRESULTOBSOLETE' ;
Function htIsResultOpen; external 'HTW32PAS.DLL' name 'HTISRESULTOPEN' ;
Function htIsTransactionalTable; external 'HTW32PAS.DLL' name 'HTISTRANSACTIONALTABLE';
Function htJoinedRecords; external 'HTW32PAS.DLL' name 'HTJOINEDRECORDS' ;
Function htJoinElement; external 'HTW32PAS.DLL' name 'HTJOINELEMENT' ;
Function htKeyMaximum; external 'HTW32PAS.DLL' name 'HTKEYMAXIMUM' ;
Function htKeyMinimum; external 'HTW32PAS.DLL' name 'HTKEYMINIMUM' ;
Function htLoadCoder; external 'HTW32PAS.DLL' name 'HTLOADCODER' ;
Function htLoadRecords; external 'HTW32PAS.DLL' name 'HTLOADRECORDS' ;
Procedure htLogClose; external 'HTW32PAS.DLL' name 'HTLOGCLOSE' ;
Function htLogOpen; external 'HTW32PAS.DLL' name 'HTLOGOPEN' ;
Function htLogRead; external 'HTW32PAS.DLL' name 'HTLOGREAD' ;
Function htMakeGroupPhoto; external 'HTW32PAS.DLL' name 'HTMAKEGROUPPHOTO' ;
Function htMakePhoto; external 'HTW32PAS.DLL' name 'HTMAKEPHOTO' ;
Function htMarkJoinedRecord; external 'HTW32PAS.DLL' name 'HTMARKJOINEDRECORD' ;
Function htMarkJoinedRecordEx; external 'HTW32PAS.DLL' name 'HTMARKJOINEDRECORDEX' ;
Function htMarkRecord; external 'HTW32PAS.DLL' name 'HTMARKRECORD' ;
Function htMemoAvailByTask; external 'HTW32PAS.DLL' name 'HTMEMOAVAILBYTASK' ;
Function htMessage; external 'HTW32PAS.DLL' name 'HTMESSAGE' ;
Function htModifyRecords; external 'HTW32PAS.DLL' name 'HTMODIFYRECORDS' ;
Function htNotResults; external 'HTW32PAS.DLL' name 'HTNOTRESULTS' ;
Function htNullField; external 'HTW32PAS.DLL' name 'HTNULLFIELD' ;
Function htNullRecord; external 'HTW32PAS.DLL' name 'HTNULLRECORD' ;
Function htOpenCodedResults; external 'HTW32PAS.DLL' name 'HTOPENCODEDRESULTS' ;
Function htOpenResults; external 'HTW32PAS.DLL' name 'HTOPENRESULTS' ;
Function htOrResults; external 'HTW32PAS.DLL' name 'HTORRESULTS' ;
Function htOutTo; external 'HTW32PAS.DLL' name 'HTOUTTO' ;
Procedure htPrintHytechHeap; external 'HTW32PAS.DLL' name 'HTPRINTHYTECHHEAP' ;
Function htPureAddRecords; external 'HTW32PAS.DLL' name 'HTPUREADDRECORDS' ;
Function htPureModifyRecords; external 'HTW32PAS.DLL' name 'HTPUREMODIFYRECORDS' ;
Function htReadCoder; external 'HTW32PAS.DLL' name 'HTREADCODER' ;
Function htReadRecord; external 'HTW32PAS.DLL' name 'HTREADRECORD' ;
Function htReadRecordByHandle; external 'HTW32PAS.DLL' name 'HTREADRECORDBYHANDLE' ;
Function htReadResults; external 'HTW32PAS.DLL' name 'HTREADRESULTS' ;
Function htReadSABChanges; external 'HTW32PAS.DLL' name 'HTREADSABCHANGES' ;
Function htReadTableChanges; external 'HTW32PAS.DLL' name 'HTREADTABLECHANGES' ;
Function htRecNoFromHandle; external 'HTW32PAS.DLL' name 'HTRECNOFROMHANDLE' ;
Function htRecordAdd; external 'HTW32PAS.DLL' name 'HTRECORDADD' ;
Function htRecordByUniq; external 'HTW32PAS.DLL' name 'HTRECORDBYUNIQ' ;
Function htRecordDelete; external 'HTW32PAS.DLL' name 'HTRECORDDELETE' ;
Function htRecordModify; external 'HTW32PAS.DLL' name 'HTRECORDMODIFY' ;
Function htRecordOrdinalNumber; external 'HTW32PAS.DLL' name 'HTRECORDORDINALNUMBER' ;
Function htRecordsByKey; external 'HTW32PAS.DLL' name 'HTRECORDSBYKEY' ;
Function htRecordsForTwoKeys; external 'HTW32PAS.DLL' name 'HTRECORDSFORTWOKEYS' ;
Function htReleaseRecord; external 'HTW32PAS.DLL' name 'HTRELEASERECORD' ;
Function htReleaseResults; external 'HTW32PAS.DLL' name 'HTRELEASERESULTS' ;
Function htReleaseTable; external 'HTW32PAS.DLL' name 'HTRELEASETABLE' ;
Function htRepairTable; external 'HTW32PAS.DLL' name 'HTREPAIRTABLE' ;
Function htRepairTableLog; external 'HTW32PAS.DLL' name 'HTREPAIRTABLELOG' ;
Function htReplaceResultsItem; external 'HTW32PAS.DLL' name 'HTREPLACERESULTSITEM' ;
Function htReplaceResultsTable; external 'HTW32PAS.DLL' name 'HTREPLACERESULTSTABLE' ;
Function htRestoreTable; external 'HTW32PAS.DLL' name 'HTRESTORETABLE' ;
Function htResultsElement; external 'HTW32PAS.DLL' name 'HTRESULTSELEMENT' ;
Function htResultsItemCnt; external 'HTW32PAS.DLL' name 'HTRESULTSITEMCNT' ;
Function htResultsItemLen; external 'HTW32PAS.DLL' name 'HTRESULTSITEMLEN' ;
Function htResultsItemParm; external 'HTW32PAS.DLL' name 'HTRESULTSITEMPARM' ;
Function htResultsTable; external 'HTW32PAS.DLL' name 'HTRESULTSTABLE' ;
Function htResultsToHard; external 'HTW32PAS.DLL' name 'HTRESULTSTOHARD' ;
Function htResultsToTable; external 'HTW32PAS.DLL' name 'HTRESULTSTOTABLE' ;
Function htResultsType; external 'HTW32PAS.DLL' name 'HTRESULTSTYPE' ;
Function htRollBackTransaction; external 'HTW32PAS.DLL' name 'HTROLLBACKTRANSACTION' ;
Function htSearch; external 'HTW32PAS.DLL' name 'HTSEARCH' ;
Function htSeekMarkedJoin; external 'HTW32PAS.DLL' name 'HTSEEKMARKEDJOIN' ;
Function htSeekMarkedJoinEx; external 'HTW32PAS.DLL' name 'HTSEEKMARKEDJOINEX' ;
Function htSeekMarkedRecord; external 'HTW32PAS.DLL' name 'HTSEEKMARKEDRECORD' ;
Function htSeekResults; external 'HTW32PAS.DLL' name 'HTSEEKRESULTS' ;
Function htSortedRecords; external 'HTW32PAS.DLL' name 'HTSORTEDRECORDS' ;
Function htSortedRecordsEx; external 'HTW32PAS.DLL' name 'HTSORTEDRECORDSEX' ;
Function htSortResults; external 'HTW32PAS.DLL' name 'HTSORTRESULTS' ;
Function htSortResultsByUser; external 'HTW32PAS.DLL' name 'HTSORTRESULTSBYUSER' ;
Function htStartTimeDate; external 'HTW32PAS.DLL' name 'HTSTARTTIMEDATE' ;
Function htStartTransaction; external 'HTW32PAS.DLL' name 'HTSTARTTRANSACTION' ;
Function htSubSearch; external 'HTW32PAS.DLL' name 'HTSUBSEARCH' ;
Function htSumOfKeyValues; external 'HTW32PAS.DLL' name 'HTSUMOFKEYVALUES' ;
Function htSyncResults; external 'HTW32PAS.DLL' name 'HTSYNCRESULTS' ;
Function htTableClose; external 'HTW32PAS.DLL' name 'HTTABLECLOSE' ;
Function htTableCopy; external 'HTW32PAS.DLL' name 'HTTABLECOPY' ;
Function htTableCreate; external 'HTW32PAS.DLL' name 'HTTABLECREATE' ;
Function htTableElement; external 'HTW32PAS.DLL' name 'HTTABLEELEMENT' ;
Function htTableElementList; external 'HTW32PAS.DLL' name 'HTTABLEELEMENTLIST' ;
Function htTableHandleByName; external 'HTW32PAS.DLL' name 'HTTABLEHANDLEBYNAME' ;
Function htTableInfo; external 'HTW32PAS.DLL' name 'HTTABLEINFO' ;
Function htTableOpen; external 'HTW32PAS.DLL' name 'HTTABLEOPEN' ;
Function htTableRename; external 'HTW32PAS.DLL' name 'HTTABLERENAME' ;
Function htTableVerify; external 'HTW32PAS.DLL' name 'HTTABLEVERIFY' ;
Function htTellJoinOrder; external 'HTW32PAS.DLL' name 'HTTELLJOINORDER' ;
Function htTouchResults; external 'HTW32PAS.DLL' name 'HTTOUCHRESULTS' ;
Function htTransferToPhoto; external 'HTW32PAS.DLL' name 'HTTRANSFERTOPHOTO' ;
Function htTransferToTable; external 'HTW32PAS.DLL' name 'HTTRANSFERTOTABLE' ;
Function htUpdateTable; external 'HTW32PAS.DLL' name 'HTUPDATETABLE' ;
Function htValuesByCount; external 'HTW32PAS.DLL' name 'HTVALUESBYCOUNT' ;
Function htValuesFromGroup; external 'HTW32PAS.DLL' name 'HTVALUESFROMGROUP' ;
Function htValuesOfKey; external 'HTW32PAS.DLL' name 'HTVALUESOFKEY' ;
Function htXorResults; external 'HTW32PAS.DLL' name 'HTXORRESULTS' ;
Procedure htBreak; external 'HTW32PAS.DLL' name 'HTBREAK' ;
Procedure htClearResults; external 'HTW32PAS.DLL' name 'HTCLEARRESULTS' ;
Procedure htCloseAllTables; external 'HTW32PAS.DLL' name 'HTCLOSEALLTABLES' ;
Procedure htNetPath; external 'HTW32PAS.DLL' name 'HTNETPATH' ;
Procedure htPurgeCoder; external 'HTW32PAS.DLL' name 'HTPURGECODER' ;
Procedure htPurgeError; external 'HTW32PAS.DLL' name 'HTPURGEERROR' ;
Procedure htSetLockTimeOut; external 'HTW32PAS.DLL' name 'HTSETLOCKTIMEOUT' ;
Procedure htSetPollDelay; external 'HTW32PAS.DLL' name 'HTSETPOLLDELAY' ;
Procedure htSetTransTimeOut; external 'HTW32PAS.DLL' name 'HTSETTRANSTIMEOUT' ;
Procedure htShut; external 'HTW32PAS.DLL' name 'HTSHUT' ;
Procedure htStringToArray; external 'HTW32PAS.DLL' name 'HTSTRINGTOARRAY' ;
Procedure htStringToChars; external 'HTW32PAS.DLL' name 'HTSTRINGTOCHARS' ;
Function htTableSABStat; external 'HTW32PAS.DLL' name 'HTTABLESABSTAT' ;
Function htTablesJoin; external 'HTW32PAS.DLL' name 'HTTABLESJOIN' ;
Function htTablesLink; external 'HTW32PAS.DLL' name 'HTTABLESLINK' ;
Procedure htTmpPath; external 'HTW32PAS.DLL' name 'HTTMPPATH' ;
Function htWhoLockRecord; external 'HTW32PAS.DLL' name 'HTWHOLOCKRECORD' ;
Function htWhoLockSet; external 'HTW32PAS.DLL' name 'HTWHOLOCKSET' ;
Function htWhoLockTable; external 'HTW32PAS.DLL' name 'HTWHOLOCKTABLE' ;
Function htWildCmp; external 'HTW32PAS.DLL' name 'HTWILDCMP' ;
Procedure htWordToDate; external 'HTW32PAS.DLL' name 'HTWORDTODATE' ;
Function htTableState; external 'HTW32PAS.DLL' name 'HTTABLESTATE' ;
Function htTableAgregateModify; external 'HTW32PAS.DLL' name 'HTTABLEAGREGATEMODIFY' ;
Function htTableAgregateDelete; external 'HTW32PAS.DLL' name 'HTTABLEAGREGATEDELETE' ;
Function htTableAgregateAppend; external 'HTW32PAS.DLL' name 'HTTABLEAGREGATEAPPEND' ;
Function htIsFieldNull; external 'HTW32PAS.DLL' name 'HTISFIELDNULL' ;
Function htCtrlCtrl; external 'HTW32PAS.DLL' name 'AMCTRLCTRL' ;
End.
|
unit K610503532;
{* [Requestlink:610503532] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K610503532.pas"
// Стереотип: "TestCase"
// Элемент модели: "K610503532" MUID: (5633572B02BE)
// Имя типа: "TK610503532"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK610503532 = class(TRTFtoEVDWriterTest)
{* [Requestlink:610503532] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK610503532
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *5633572B02BEimpl_uses*
//#UC END# *5633572B02BEimpl_uses*
;
function TK610503532.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.12';
end;//TK610503532.GetFolder
function TK610503532.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '5633572B02BE';
end;//TK610503532.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK610503532.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit MFichas.Model.Configuracao;
interface
uses
System.SysUtils,
MFichas.Model.Configuracao.Interfaces,
MFichas.Model.Entidade.CONFIGURACOES,
MFichas.Model.Conexao.Interfaces,
MFichas.Model.Conexao.Factory,
ORMBR.Container.ObjectSet.Interfaces,
ORMBR.Container.ObjectSet,
ORMBR.Container.DataSet.Interfaces,
ORMBR.Container.FDMemTable,
FireDAC.Comp.Client;
type
TModelConfiguracao = class(TInterfacedObject, iModelConfiguracao, iModelConfiguracaoMetodos)
private
FFDMemTable: TFDMemTable;
FConn : iModelConexaoSQL;
FDAO : iContainerObjectSet<TCONFIGURACOES>;
FDAODataSet: iContainerDataSet<TCONFIGURACOES>;
constructor Create;
public
destructor Destroy; override;
class function New: iModelConfiguracao;
function Metodos : iModelConfiguracaoMetodos;
function DAO : iContainerObjectSet<TCONFIGURACOES>;
function DAODataSet: iContainerDataSet<TCONFIGURACOES>;
//METODOS
function BuscarModel: iModelConfiguracaoMetodosBuscarModel;
function EditarView : iModelConfiguracaoMetodosEditarView;
function BuscarView : iModelConfiguracaoMetodosBuscarView;
function &End : iModelConfiguracao;
end;
implementation
{ TModelConfiguracao }
uses
MFichas.Model.Configuracao.Metodos.Buscar.Model,
MFichas.Model.Configuracao.Metodos.Buscar.View,
MFichas.Model.Configuracao.Metodos.Editar.View;
function TModelConfiguracao.&End: iModelConfiguracao;
begin
Result := Self;
end;
function TModelConfiguracao.BuscarModel: iModelConfiguracaoMetodosBuscarModel;
begin
Result := TModelConfiguracaoMetodosBuscarModel.New(Self);
end;
function TModelConfiguracao.BuscarView: iModelConfiguracaoMetodosBuscarView;
begin
Result := TModelConfiguracaoMetodosBuscarView.New(Self);
end;
constructor TModelConfiguracao.Create;
begin
FFDMemTable := TFDMemTable.Create(nil);
FConn := TModelConexaoFactory.New.ConexaoSQL;
FDAO := TContainerObjectSet<TCONFIGURACOES>.Create(FConn.Conn);
FDAODataSet := TContainerFDMemTable<TCONFIGURACOES>.Create(FConn.Conn, FFDMemTable);
end;
function TModelConfiguracao.DAO: iContainerObjectSet<TCONFIGURACOES>;
begin
Result := FDAO;
end;
function TModelConfiguracao.DAODataSet: iContainerDataSet<TCONFIGURACOES>;
begin
Result := FDAODataSet;
end;
destructor TModelConfiguracao.Destroy;
begin
{$IFDEF MSWINDOWS}
FreeAndNil(FFDMemTable);
{$ELSE}
FFDMemTable.Free;
FFDMemTable.DisposeOf;
{$ENDIF}
inherited;
end;
function TModelConfiguracao.EditarView: iModelConfiguracaoMetodosEditarView;
begin
Result := TModelConfiguracaoMetodosEditarView.New(Self);
end;
function TModelConfiguracao.Metodos: iModelConfiguracaoMetodos;
begin
Result := Self;
end;
class function TModelConfiguracao.New: iModelConfiguracao;
begin
Result := Self.Create;
end;
end.
|
unit uContentResolver;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ IContentResolver }
IContentResolver = interface
['{A426E92E-5F53-4C46-8969-AA047F30B81A}']
function GetPath: string;
function GetName: string;
function GetDescription: string;
function GetIcon: string;
end;
{ TBaseResolver }
TBaseResolver = class(TInterfacedObject, IContentResolver)
private
FFileName: string;
public
constructor Create(const aFileName: string); virtual;
function GetPath: string; virtual;
function GetName: string; virtual;
function GetDescription: string; virtual;
function GetIcon: string; virtual;
end;
{ TDesktopResolver }
TDesktopResolver = class(TInterfacedObject, IContentResolver)
private
FFileName: string;
FName: string;
FNameCz: string;
FComment: string;
FCommentCz: string;
FKeywords: string;
FIcon: string;
procedure GetValue(const lLine, aPrefix: string; var aVar: string);
public
constructor Create(const aFileName: string);
function GetPath: string;
function GetName: string;
function GetDescription: string;
function GetIcon: string;
end;
{ TMhtResolver }
TMhtResolver = class(TBaseResolver, IContentResolver)
private
public
function GetName: string; override;
end;
function NewContentResolver(const aFileName: string): IContentResolver;
implementation
uses strutils, FileUtil, LazFileUtils;
function NewContentResolver(const aFileName: string): IContentResolver;
begin
if AnsiEndsText('.desktop', aFileName) and FileIsReadable(aFileName) then
Result := TDesktopResolver.Create(aFileName)
else if AnsiEndsText('.mht', aFileName) then
Result := TMhtResolver.Create(aFileName)
else
Result := TBaseResolver.Create(aFileName);
end;
{ TMhtResolver }
Function TMhtResolver.GetName: string;
Var
lName: String;
Begin
lName := Inherited;
Result := StringReplace(lName, '_', ' ', [rfReplaceAll]);
Result := StringReplace(Result, '.mht', ' ', [rfReplaceAll, rfIgnoreCase]);
End;
{ TBaseResolver }
constructor TBaseResolver.Create(const aFileName: string);
begin
FFileName := aFileName;
end;
function TBaseResolver.GetPath: string;
begin
Result := FFileName;
end;
function TBaseResolver.GetName: string;
begin
Result := ExtractFileName(FFileName);
end;
function TBaseResolver.GetDescription: string;
begin
Result := '';
end;
function TBaseResolver.GetIcon: string;
begin
Result := '';
end;
{ TDesktopResolver }
Procedure TDesktopResolver.GetValue(Const lLine, aPrefix: string; Var aVar: string);
begin
if AnsiStartsStr(aPrefix, lLine) and (aVar = '') then
begin
aVar := Copy(lLine, Pos('=', lLine) + 1, Length(lLine) - Pos('=', lLine));
end;
end;
Constructor TDesktopResolver.Create(Const aFileName: string);
var
F: Text;
lLine: string;
begin
FFileName := aFileName;
AssignFile(F, FFileName);
try
Reset(F);
while not EOF(F) do
begin
ReadLn(F, lLine);
GetValue(lLine, 'Name=', FName);
GetValue(lLine, 'Name[cz]=', FNameCz);
GetValue(lLine, 'Comment=', FComment);
GetValue(lLine, 'Comment[cz]=', FCommentCz);
GetValue(lLine, 'Keywords=', FKeywords);
GetValue(lLine, 'Icon=', FIcon);
end;
finally
Close(F);
end;
end;
Function TDesktopResolver.GetPath: string;
begin
Result := FFileName;
end;
Function TDesktopResolver.GetName: string;
begin
if FName <> '' then
Result := FName
else
Result := ExtractFileName(FFileName);
//WriteLn(Result);
end;
Function TDesktopResolver.GetDescription: string;
begin
Result := FName + ' ' + FNameCz + ' ' + FComment + ' ' + FCommentCz + ' ' + FKeywords + ' ' + ExtractFileName(FFileName);
//WriteLn(Result);
end;
Function TDesktopResolver.GetIcon: string;
Begin
Result := FIcon;
End;
end.
|
unit UPedidoRepositoryImpl;
interface
uses
UPedidoRepositoryIntf, UPizzaTamanhoEnum, UPizzaSaborEnum, UDBConnectionIntf, FireDAC.Comp.Client;
type
TPedidoRepository = class(TInterfacedObject, IPedidoRepository)
private
FDBConnection: IDBConnection;
FFDQuery: TFDQuery;
public
procedure efetuarPedido(const APizzaTamanho: TPizzaTamanhoEnum; const APizzaSabor: TPizzaSaborEnum; const AValorPedido: Currency;
const ATempoPreparo: Integer; const ACodigoCliente: Integer);
procedure consultarPedido(const ADocumentoCliente: String; out AFDQuery: TFDQuery );
constructor Create; reintroduce;
destructor Destroy; override;
end;
implementation
uses
UDBConnectionImpl, System.SysUtils, Data.DB, FireDAC.Stan.Param;
const
CMD_INSERT_PEDIDO
: String =
'INSERT INTO tb_pedido (cd_cliente, dt_pedido, dt_entrega, vl_pedido, ' +
'nr_tempopedido, sabor_pizza, tamanho_pizza) VALUES (:pCodigoCliente, ' +
' :pDataPedido, :pDataEntrega, :pValorPedido, :pTempoPedido, :pSaborPizza, ' +
':pTamanhoPizza)';
const
CMD_CONSULTA_PEDIDO
: String =
'SELECT tamanho_pizza, sabor_pizza,'+
'vl_pedido, nr_tempopedido from tb_pedido ped inner join tb_cliente cli '+
'on (ped.cd_cliente = cli.id) where cli.nr_documento = :pdocumentoCliente '+
'order by cli.id desc limit 1';
{ TPedidoRepository }
procedure TPedidoRepository.consultarPedido(const ADocumentoCliente: String;
out AFDQuery: TFDQuery);
begin
AFDQuery.Connection := FDBConnection.getDefaultConnection;
AFDQuery.SQL.Text := CMD_CONSULTA_PEDIDO;
AFDQuery.ParamByName('pdocumentoCliente').AsString := ADocumentoCliente;
AFDQuery.Prepare;
AFDQuery.Open;
end;
constructor TPedidoRepository.Create;
begin
inherited;
FDBConnection := TDBConnection.Create;
FFDQuery := TFDQuery.Create(nil);
FFDQuery.Connection := FDBConnection.getDefaultConnection;
end;
destructor TPedidoRepository.Destroy;
begin
FFDQuery.Free;
inherited;
end;
procedure TPedidoRepository.efetuarPedido(const APizzaTamanho: TPizzaTamanhoEnum; const APizzaSabor: TPizzaSaborEnum; const AValorPedido: Currency;
const ATempoPreparo: Integer; const ACodigoCliente: Integer);
var
pizzaTamanho, pizzaSabor : string;
begin
case APizzaTamanho of
enPequena:
pizzaTamanho := 'enPequena';
enMedia:
pizzaTamanho := 'enMedia';
enGrande:
pizzaTamanho := 'enGrande';
end;
case APizzaSabor of
enCalabresa:
pizzaSabor := 'enCalabresa';
enMarguerita:
pizzaSabor := 'enMarguerita';
enPortuguesa:
pizzaSabor := 'enPortuguesa';
end;
FFDQuery.SQL.Text := CMD_INSERT_PEDIDO;
FFDQuery.ParamByName('pCodigoCliente').AsInteger := ACodigoCliente;
FFDQuery.ParamByName('pDataPedido').AsDateTime := now();
FFDQuery.ParamByName('pDataEntrega').AsDateTime := now();
FFDQuery.ParamByName('pValorPedido').AsCurrency := AValorPedido;
FFDQuery.ParamByName('pTempoPedido').AsInteger := ATempoPreparo;
FFDQuery.ParamByName('pSaborPizza').AsString := pizzaSabor;
FFDQuery.ParamByName('pTamanhoPizza').AsString := pizzaTamanho;
FFDQuery.Prepare;
FFDQuery.ExecSQL();
end;
end.
|
(*
The function to_braille from this unit translates a string from UTF8 chars to Braille chars.
The dictionaries were taken from http://www.ibc.gov.br/?catid=110&blogid=1&itemid=479
and from http://www.braillevirtual.fe.usp.br/pt/Portugues/braille.html
Copyright 2011
*)
unit mod_braille;
interface
{$mode objfpc}{$H+}
uses
browsermodules, lclproc;
type
{ TBrailleBrowserModule }
TBrailleBrowserModule = class(TBrowserModule)
public
constructor Create; override;
function HandleOnPageLoad(AInput: string; out AOutput: string): Boolean; override;
end;
function ConvertUTF8CharToBraille(Char: string; lCharSize: integer; OrdChar: integer): string;
function ConvertUTF8TextToBraille(Text: string): string;
function ConvertUTF8HtmlTextToBraille(AInput: string): string;
implementation
{type
dictionary = array[1..32] of string;
const
number_signal = chr($e2) + chr($a0) + chr($bc);
caps_signal = chr($e2) + chr($a0) + chr($a8);
d1: dictionary = ({!} chr($96), {"} chr($a6), {# TODO} chr($80), {(*$*)} chr($b0),
{%} chr($b8) + chr($e2) + chr($a0) + chr($b4), {&} chr($af), {'} chr($84),
{(} chr($a3) + chr($e2) + chr($a0) + chr($84), {)} chr($a0) + chr($e2) + chr($a0) + chr($9c),
{*} chr($94), {+} chr($96), {,} chr($82), {-} chr($a4), {.} chr($84),
{/} chr($90) + chr($e2) + chr($a0) + chr($b2), {0} chr($9a), {1} chr($81),
{2} chr($83), {3} chr($89), {4} chr($99), {5} chr($91), {6} chr($8b),
{7} chr($9b), {8} chr($93), {9} chr($8a), {:} chr($92), {;} chr($86),
{<} chr($aa), {=} chr($b6), {>} chr($95), {?} chr($a2), {@ TODO} chr($80));
d2: dictionary = ({a} chr($81), {b} chr($83), {c} chr($89), {d} chr($99),
{e} chr($91), {f} chr($8b), {g} chr($9b), {h} chr($93), {i} chr($8a),
{j} chr($9a), {k} chr($85), {l} chr($87), {m} chr($8d), {n} chr($9d),
{o} chr($95), {p} chr($8f), {q} chr($9f), {r} chr($97), {s} chr($8e),
{t} chr($9e), {u} chr($a5), {v} chr($a7), {w} chr($ba), {x} chr($ad),
{y} chr($bd), {z} chr($b5), '', '', '', '', '', '');
d3: dictionary = ({a + grave} chr($ab), {a + acute} chr($b7),
{a + circumflex} chr($a1), {a + tilde} chr($9c), {a + diaeresis TODO} chr($80),
{a + ring above TODO} chr($80), {ae TODO} chr($80), {c + cedilla} chr($af),
{e + grave} chr($ae), {e + acute} chr($bf), {e + circumflex} chr($a3),
{e + diaeresis TODO} chr($80), {i + grave} chr($a9), {i + acute} chr($8c),
{i + circumflex TODO} chr($80), {i + diaeresis} chr($bb), {eth TODO} chr($80),
{n + tilde TODO} chr($80), {o + grave} chr($ba), {o + acute} chr($ac),
{o + circumflex} chr($b9), {o + tilde} chr($aa), {o + diaeresis TODO} chr($80),
{division sign TODO} chr($80), {o + stroke TODO} chr($80), {u + grave} chr($b1),
{u + acute} chr($be), {u + circumflex TODO} chr($80), {u + diaeresis} chr($b3),
{y + acute TODO} chr($80), {thorn TODO} chr($80), {y + diaeresis TODO} chr($80)); }
{function ConvertUTF8TextToBraille(Line: string): string;
{var
lCharSize, count, n, next_n, len: integer;
Braille_string: string;
Pline: Pchar;
num, caps: boolean;
begin
Braille_string := '';
num := False;
caps := False;
count := 1;
if Line = '' then Result := '';
len := length(Line);
Pline := PChar(Line); }
while count <= len do
begin
lCharSize := LCLProc.UTF8CharacterLength(PLine);
if (lCharSize = 1) then
begin
n := Ord(Line[count]);
if (n = 9) then Braille_string := Braille_string + #9
else
if (n = 10) then Braille_string := Braille_string + #10
else
if (n = 32) then Braille_string := Braille_string + #32
else
begin
if ((n >= 97) and (n <= 122)) then {a lower case letter}
Braille_string := Braille_string + chr($e2) + chr($a0) + d2[n - 96]
else
begin
if ((n >= 65) and (n <= 90)) then {an upper case letter}
begin
if not caps then
begin
Braille_string := Braille_string + caps_signal;
if (count + 2 < length(Line)) then
begin
next_n := Ord(Line[count + 1]);
if ((next_n >= 65) and (next_n <= 90)) or ((next_n = 195) and ((Ord(Line[count + 2]) >= 128) and (Ord(Line[count + 2]) <= 159))) then {if the next char is also upper case, add another caps signal}
begin
Braille_string := Braille_string + caps_signal;
caps := True;
end;
end;
end;
Braille_string := Braille_string + chr($e2) + chr($a0) + d2[n - 64];
if (count + 1 <= length(Line)) then
begin
next_n := Ord(Line[count + 1]);
if not(((next_n >= 65) and (next_n <= 90)) or ((next_n = 195) and ((Ord(Line[count + 2]) >= 128) and (Ord(Line[count + 2]) <= 159)))) then caps := False; {if the next char is not upper case, unflag <caps>}
end;
end
else
begin
if (n >= 48) and (n <= 57) then {a number}
begin
if not num then Braille_string := Braille_string + number_signal; {first algarism of a number, add a number signal}
num := True;
Braille_string := Braille_string + chr($e2) + chr($a0) + d1[n - 31];
if (count + 1 <= length(Line)) then
begin
next_n := Ord(Line[count + 1]);
if not ((next_n >= 48) and (next_n <= 57) or (next_n = 44) or (next_n = 46)) then num := False; {the next char is not a number, nor ',', nor '.', then unflag <num>}
end;
end
else
begin
if (n >= 33) and (n <= 64) then {a char from the first dictionary}
begin
Braille_string := Braille_string + chr($e2) + chr($a0) + d1[n - 32];
if (count + 1 <= length(Line)) then
begin
next_n := Ord(Line[count + 1]);
if ((n = 44) or (n = 46)) and not ((next_n >= 48) and (next_n <= 57)) then num := False; {if the char is a ',' or a '.' but the next is not a number, unflag <num>}
end;
end;
end;
end;
end;
end;
end
else
begin
if (lCharSize = 2) then
begin
n := Ord(Line[count]);
if (n = 195) then
begin
n := Ord(Line[count + 1]);
if (n >= 128) and (n <= 159) then {upper case accented char}
begin
if not caps then
begin
Braille_string := Braille_string + caps_signal;
if (count + 2 <= length(Line)) then
begin
next_n := Ord(Line[count + 2]);
if ((next_n >= 65) and (next_n <= 90)) or ((next_n = 195) and ((Ord(Line[count + 2]) >= 128) and (Ord(Line[count + 2]) <= 159))) then {if the next char is also upper case, add another caps signal}
begin
Braille_string := Braille_string + caps_signal;
caps := True;
end;
end;
end;
Braille_string := Braille_string + chr($e2) + chr($a0) + d3[n - 127];
if (count + 3 <= length(Line)) then
begin
next_n := Ord(Line[count + 2]);
if not(((next_n >= 65) and (next_n <= 90)) or ((next_n = 195) and ((Ord(Line[count + 3]) >= 128) and (Ord(Line[count + 3]) <= 159)))) then {if the next char is not upper case, unflag <caps>}
caps := False;
end;
end
else
if (n >= 160) and (n <= 191) then Braille_string := Braille_string + chr($e2) + chr($a0) + d3[n - 159]; {lower case accented letter}
end;
end;
end;
count := count + lCharSize;
Inc(Pline, lCharSize);
end;
Result := Braille_string;
end; }
const
number_signal = chr($e2) + chr($a0) + chr($bc);
caps_signal = chr($e2) + chr($a0) + chr($a8);
function ConvertUTF8CharToBraille(Char: string; lCharSize: integer; OrdChar: integer): string;
const
aux = chr($e2) + chr($a0);
begin
{If the character can't be found in any of the cases, write a Braille space}
Result := aux + chr($80);
case lCharSize of
1:
begin
case OrdChar of
9: {\t}
Result := #9;
10: {\n}
Result := #10;
32: {<space>}
Result := #32;
33, 43: {!, +}
Result := aux + chr($96);
34: {"}
Result := aux + chr($a6);
36: {*$*}
Result := aux + chr($b0);
37: {%}
Result := aux + chr($b8) + chr($e2) + chr($a0) + chr($b4);
38: {&}
Result := aux + chr($af);
39, 46: {', .}
Result := aux + chr($84);
40: {(}
Result := aux + chr($a3) + chr($e2) + chr($a0) + chr($84);
41: {)}
Result := aux + chr($a0) + chr($e2) + chr($a0) + chr($9c);
42: {*}
Result := aux + chr($94);
44: {,}
Result := aux + chr($82);
45: {-}
Result := aux + chr($a4);
47: {/}
Result := aux + chr($90) + chr($e2) + chr($a0) + chr($b2);
48, 74, 106: {0, J, j}
Result := aux + chr($9a);
49, 65, 97: {1, A, a}
Result := aux + chr($81);
50, 66, 98: {2, B, b}
Result := aux + chr($83);
51, 67, 99: {3, C, c}
Result := aux + chr($89);
52, 68, 100: {4, D, d}
Result := aux + chr($99);
53, 69, 101: {5, E, e}
Result := aux + chr($91);
54, 70, 102: {6, F, f}
Result := aux + chr($8b);
55, 71, 103: {7, G, g}
Result := aux + chr($9b);
56, 72, 104: {8, H, h}
Result := aux + chr($93);
57, 73, 105: {9, I, i}
Result := aux + chr($8a);
58: {:}
Result := aux + chr($92);
59: {;}
Result := aux + chr($86);
60: {<}
Result := aux + chr($aa);
61: {=}
Result := aux + chr($b6);
63: {?}
Result := aux + chr($a2);
75, 107: {K, k}
Result := aux + chr($85);
76, 108: {L, l}
Result := aux + chr($87);
77, 109: {M, m}
Result := aux + chr($8d);
78, 110: {N, n}
Result := aux + chr($9d);
79, 111, 62: {O, o, >}
Result := aux + chr($95);
80, 112: {P, p}
Result := aux + chr($8f);
81, 113: {Q, q}
Result := aux + chr($9f);
82, 114: {R, r}
Result := aux + chr($97);
83, 115: {S, s}
Result := aux + chr($8e);
84, 116: {T, t}
Result := aux + chr($9e);
85, 117: {U, u}
Result := aux + chr($a5);
86, 118: {V, v}
Result := aux + chr($a7);
87, 119: {W, w}
Result := aux + chr($ba);
88, 120: {X, x}
Result := aux + chr($ad);
89, 121: {Y, y}
Result := aux + chr($bd);
90, 122: {Z, z}
Result := aux + chr($b5);
end;
end;
2:
begin
case OrdChar of
195: {accented letter}
begin
OrdChar := Ord(Char[2]);
case OrdChar of
128, 160: {A + grave, a + grave}
Result := aux + chr($ab);
129, 161: {A + acute, a + acute}
Result := aux + chr($b7);
130, 162: {A + circumflex, a + circumflex}
Result := aux + chr($a1);
131, 163: {A + tilde, a + tilde}
Result := aux + chr($9c);
135, 167: {C + cedilla, c + cedilla}
Result := aux + chr($af);
136, 168: {E + grave, e + grave}
Result := aux + chr($ae);
137, 169: {E + acute, e + acute}
Result := aux + chr($bf);
138, 170: {E + circumflex, e + circumflex}
Result := aux + chr($a3);
140, 172: {I + grave, i + grave}
Result := aux + chr($a9);
141, 173: {I + acute, i + acute}
Result := aux + chr($8c);
143, 175: {I + diaresis, i + diaresis}
Result := aux + chr($bb);
146, 178: {O + grave, o + grave}
Result := aux + chr($ba);
147, 179: {O + acute, o + acute}
Result := aux + chr($ac);
148, 180: {O + circumflex, o + circumflex}
Result := aux + chr($b9);
149, 181: {O + tilde, o + tilde}
Result := aux + chr($aa);
153, 185: {U + grave, u + grave}
Result := aux + chr($b1);
154, 186: {U + acute, u + acute}
Result := aux + chr($be);
156, 188: {U + diaeresis, u + diaeresis}
Result := aux + chr($b3);
end;
end;
end;
end;
end;
end;
function ConvertUTF8TextToBraille(Text:string): string;
var
lCharSize, TextSize, i, OrdChar, nextOrdChar: integer;
Braille_string: string;
PText: Pchar;
IsNum: boolean;
begin
Braille_string := '';
IsNum := False;
if Text = '' then Result := '';
TextSize := Length(Text);
PText := PChar(Text);
i := 1;
while i <= TextSize do
begin
lCharSize := LCLProc.UTF8CharacterLength(PText);
OrdChar := Ord(Text[i]);
case lCharSize of
1:
begin
case OrdChar of
48..57: {a number}
begin
if not IsNum then
begin
Braille_string := Braille_string + number_signal; {first algarism of a number, add a number signal}
IsNum := True
end;
if (i + 1 <= TextSize) then
begin
nextOrdChar := Ord(Text[i + 1]);
if not ((nextOrdChar >= 48) and (nextOrdChar <= 57) or (nextOrdChar = 44) or (nextOrdChar = 46)) then IsNum := False; {the next char is not a number, nor ',', nor '.', then unflag <IsNum>}
end;
end;
65..90: {Upper case letter, add a caps_signal}
Braille_string := Braille_string + caps_signal;
end;
Braille_string := Braille_string + ConvertUTF8CharToBraille(Text[i], 1, OrdChar);
i := i + 1;
end;
2:
begin
nextOrdChar := Ord(Text[i+1]);
case nextOrdChar of
{Accented upper case letter, add a caps_signal}
128..159:
Braille_string := Braille_string + caps_signal;
end;
Braille_string := Braille_string + ConvertUTF8CharToBraille(copy(Text,i,2), 2, OrdChar);
i := i + 2;
end;
end;
Inc(PText, lCharSize);
end;
Result := Braille_string;
end;
function ConvertUTF8HtmlTextToBraille(AInput: string): string;
var
i, lCharSize: integer;
output, aux_string, end_string: string;
is_text: boolean;
Pline : PChar;
begin
i := 1;
output := '';
aux_string := '';
is_text := False;
Pline := PChar(AInput);
while i <= length(AInput) do
begin
end_string := '';
while is_text and (i <= length(AInput)) do
begin
if (AInput[i] = '<') then { an instruction comes next }
begin
is_text := False;
i := i + 1;
Inc(Pline, 1);
end_string := '<';
if (copy(AInput, i, 6) = 'script') then { if it's a script, go through it and
keep reading the text}
begin
i := i + 6;
Inc(Pline, 6);
end_string := end_string + 'script';
while (copy(AInput, i, 9) <> '</script>') do
begin
end_string := end_string + AInput[i];
i := i + 1;
Inc(Pline, 1);
end;
is_text := True;
end;
break;
end;
{ Read the next UTF8 character add it to aux_string }
lCharSize := LCLProc.UTF8CharacterLength(Pline);
aux_string := aux_string + copy(AInput, i, lCharSize);
i := i + lCharSize;
Inc(Pline, lCharSize);
end;
{ Translate aux_string to Braille and add it to output }
output := output + ConvertUTF8TextToBraille(aux_string) + end_string;
aux_string := '';
while (not is_text) and (i <= length(AInput))do
begin
if (AInput[i] = '>') then { End of instruction }
begin
is_text := True;
i := i + 1;
Inc(Pline, 1);
output := output + '>';
break
end;
{ Add the next UTF8 character straight to output, without translating it }
lCharSize := LCLProc.UTF8CharacterLength(Pline);
output := output + copy(AInput, i, lCharSize);
i := i + lCharSize;
Inc(Pline, lCharSize);
end;
end;
ConvertUTF8HtmlTextToBraille := output;
end;
{ TBrailleBrowserModule }
constructor TBrailleBrowserModule.Create;
begin
inherited Create;
ShortDescription := 'Braille Module';
end;
function TBrailleBrowserModule.HandleOnPageLoad(AInput: string; out
AOutput: string): Boolean;
begin
AOutput := ConvertUTF8HtmlTextToBraille(AInput);
Result := True;
end;
initialization
RegisterBrowserModule(TBrailleBrowserModule.Create());
end.
|
unit uSceneHelp;
interface
uses Graphics, uScene, uButton, uGraph;
type
TPage = (hpMain, hpKeys);
TSceneHelp = class(TSceneFrame)
private
FPage: TPage;
FBack: TBitmap;
FGraph: TGraph;
FYA, FYB: Word;
FIsLoad: Boolean;
FButton: array [0..2] of TButton;
procedure AddLine(S: string; K: string = '');
procedure AddWideLine(S: string; K: string = '');
procedure AddCaption(S: string);
procedure AddSpace();
procedure MainPage();
procedure KeysPage();
procedure Load;
public
//** Конструктор.
constructor Create;
destructor Destroy; override;
function Keys(var Key: Word): Boolean; override;
function MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean; override;
function MouseMove(X, Y: Integer): Boolean; override;
function Click(Button: TMouseBtn): Boolean; override;
procedure Draw(); override;
end;
var
SceneHelp: TSceneHelp;
implementation
uses
uBox, SysUtils, Types, uUtils, uSceneMenu, uSounds, uGUIBorder, uColors;
{ TSceneHelp }
const Span = 6;
procedure TSceneHelp.AddLine(S: string; K: string = '');
var
L, T: Word;
SZ: TSize;
IsLeft: Boolean;
begin
IsLeft := (FYA = FYB);
if IsLeft then T := FYA else T := FYB;
if IsLeft then L := Span else L := 400 + (Span * 2);
with Back.Canvas do
begin
if (K <> '') then
begin
Font.Style := [fsBold];
if IsHelp then Font.Color := cBlackRare else Font.Color := cRare;
SZ := TextExtent('[' + K + ']');
TextOut(L, T, '[' + K + ']');
L := L + (SZ.cx) + Span;
end;
Font.Style := [];
if IsHelp then Font.Color := cBlackText else Font.Color := cDarkRare;
TextOut(L, T, S);
if IsLeft then Inc(FYA, 30) else Inc(FYB, 30);
end;
end;
procedure TSceneHelp.AddSpace;
begin
FYB := FYA;
Inc(FYA, Span);
Inc(FYB, Span);
end;
procedure TSceneHelp.AddWideLine(S: string; K: string = '');
begin
AddLine(S, K);
FYB := FYA;
end;
function TSceneHelp.Click(Button: TMouseBtn): Boolean;
begin
Result := True;
if IsHelp and FButton[0].MouseOver then
begin
SceneManager.SetScene(SceneMenu);
Sound.PlayClick;
Exit;
end;
if (FButton[1].MouseOver or FButton[2].MouseOver) and (FPage <> hpMain) then
begin
FPage := hpMain;
Sound.PlayClick;
SceneManager.Draw;
end;
inherited Click(Button);
end;
constructor TSceneHelp.Create;
begin
FPage := hpMain;
FIsLoad := False;
FGraph := TGraph.Create(Path + 'Data\Images\Screens\');
inherited Create(spFull);
end;
destructor TSceneHelp.Destroy;
var
I: Byte;
begin
for I := 0 to High(FButton) do FButton[I].Free;
FGraph.Free;
FBack.Free;
inherited;
end;
procedure TSceneHelp.Draw;
begin
inherited;
if not FIsLoad then Load;
if IsHelp then Back.Assign(FBack);
case FPage of
hpMain: MainPage;
hpKeys: KeysPage;
end;
if IsHelp then FButton[0].Draw;
if (FPage <> hpMain) then
begin
if IsHelp then FButton[1].Draw else FButton[2].Draw;
end;
Refresh;
end;
function TSceneHelp.Keys(var Key: Word): Boolean;
begin
Result := True;
if IsHelp then
case Key of
13, 27:
if (FPage <> hpMain) then
begin
FPage := hpMain;
Sound.PlayClick;
SceneManager.Draw;
Exit;
end else begin
SceneManager.SetScene(SceneMenu);
Sound.PlayClick;
Exit;
end;
end;
case Key of
49:
begin
FPage := hpKeys;
Sound.PlayClick;
SceneManager.Draw;
Exit;
end;
end;
inherited Keys(Key);
end;
procedure TSceneHelp.MainPage;
begin
AddCaption('Сердце Тьмы - Разделы справки');
AddLine('Клавиши управления в игре', '1');
end;
procedure TSceneHelp.KeysPage;
begin
AddCaption('Сердце Тьмы - Управление');
AddLine('Перемещение аватара', 'Стрелки');
AddLine('Стрельба', 'ALT + Стрелки');
AddWideLine('Перемещение аватара по диагонали', 'CTRL + Стрелки');
AddWideLine('Перемещение аватара во все стороны', 'Цифровая клавиатура');
AddWideLine('Перебраться через препятствие', 'SHIFT + Стрелки');
AddWideLine('Подобрать предмет и положить в инвентарь', 'SPACE] [G');
AddWideLine('Подобрать все предметы, активировать руну', 'ENTER');
AddWideLine('Переключение между частями инвентаря', 'TAB');
AddSpace;
AddLine('Сердце Тьмы - Руководство', 'H');
AddLine('Отмена или выход', 'ESC');
AddLine('Статистика персонажа', 'C');
AddLine('Инвентарь и снаряжение', 'I');
AddLine('Журнал квестов', 'Q');
AddLine('Игровая статистика', 'S');
AddLine('Дерево умений', 'A');
AddLine('Изменить режим лога', 'L');
AddLine('Миникарта', 'M');
AddLine('Сделать скриншот', 'F11');
AddLine('Ждать на месте', 'W');
AddLine('Игровая консоль', '~');
AddSpace;
AddWideLine('Использовать/поставить предметы в пояс', '1 - 0');
end;
procedure TSceneHelp.Load;
begin
FButton[0] := TButton.Create(590, 540, Back.Canvas, 'Назад');
FButton[0].Sellected := True;
FButton[1] := TButton.Create(10, 540, Back.Canvas, 'FB7.bmp', btShort);
FButton[2] := TButton.Create(10, 510, Back.Canvas, 'FB7.bmp', btShort);
FBack := Graphics.TBitmap.Create;
FGraph.LoadImage('Blank.jpg', FBack);
GUIBorder.Make(FBack);
end;
function TSceneHelp.MouseDown(Button: TMouseBtn; X, Y: Integer): Boolean;
begin
Result := False;
FButton[0].MouseDown(X, Y);
if (FPage <> hpMain) then FButton[1].MouseDown(X, Y);
SceneManager.Draw;
end;
function TSceneHelp.MouseMove(X, Y: Integer): Boolean;
begin
Result := False;
FButton[0].Draw;
if (FPage <> hpMain) then FButton[1].Draw;
SceneManager.Draw;
end;
procedure TSceneHelp.AddCaption(S: string);
var
SZ: TSize;
begin
S := AnsiUpperCase(S);
with Back.Canvas do
begin
Font.Style := [fsBold];
if IsHelp then Font.Color := cBlackRare else Font.Color := cRare;
Font.Size := 25;
SZ := TextExtent(S);
TextOut(400 - (SZ.cx div 2), 5, S);
if IsHelp then Font.Color := cBlackText else Font.Color := cDarkRare;
Font.Style := [];
Font.Size := 20;
FYA := 40;
FYB := 40;
end;
end;
initialization
SceneHelp := TSceneHelp.Create;
finalization
SceneHelp.Free;
end.
|
unit cCadCargo;
interface
uses System.Classes, Vcl.Controls,
Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils;
// LISTA DE UNITS
type
TCargo = class
private
// VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE
ConexaoDB: TFDConnection;
F_cod_cargo: Integer;
F_nivel: Integer;
F_cargo: string;
public
constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE
destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
// VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE
// PARA FORNECER INFORMAÇÕESD EM RUMTIME
property cod_cargo: Integer read F_cod_cargo
write F_cod_cargo;
property cargo: string read F_cargo
write F_cargo;
property nivel: Integer read F_nivel
write F_nivel;
end;
implementation
{$REGION 'Constructor and Destructor'}
constructor TCargo.Create;
begin
ConexaoDB := aConexao;
end;
destructor TCargo.Destroy;
begin
inherited;
end;
{$ENDREGION}
{$REGION 'CRUD'}
function TCargo.Apagar: Boolean;
var
Qry: TFDQuery;
begin
if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' +
IntToStr(F_cod_cargo) + #13 + 'Descrição: ' + F_cargo,
mtConfirmation, [mbYes, mbNo], 0) = mrNO then
begin
Result := false;
Abort;
end;
Try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM tb_cargo WHERE cod_cargo=:cod_cargo');
Qry.ParamByName('cod_cargo').AsInteger := F_cod_cargo;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
Finally
if Assigned(Qry) then
FreeAndNil(Qry)
End;
end;
function TCargo.Atualizar: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE tb_cargo SET cargo=:cargo ,nivel=:nivel WHERE cod_cargo=:cod_cargo');
Qry.ParamByName('cod_cargo').AsInteger := F_cod_cargo;
Qry.ParamByName('cargo').AsString := F_cargo;
Qry.ParamByName('nivel').AsInteger := F_nivel;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TCargo.Inserir: Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO igreja.tb_cargo (cargo,nivel) '+
' VALUES(:cargo,:nivel)');
Qry.ParamByName('cargo').AsString := Self.F_cargo;
Qry.ParamByName('nivel').AsInteger := Self.F_nivel;
try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
except
ConexaoDB.Rollback;
Result:=false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
function TCargo.Selecionar(id: Integer): Boolean;
var
Qry: TFDQuery;
begin
try
Result := True;
Qry := TFDQuery.Create(nil);
Qry.Connection := ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT cod_cargo, cargo,nivel '+
' FROM tb_cargo where cod_cargo=:cod_cargo ');
Qry.ParamByName('cod_cargo').AsInteger := id;
try
Qry.Open;
Self.F_cod_cargo := Qry.FieldByName('cod_cargo').AsInteger;
Self.F_cargo := Qry.FieldByName('cargo').AsString;
Self.F_nivel := Qry.FieldByName('nivel').AsInteger;
Except
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry)
end;
end;
{$ENDREGION}
end.
|
unit DirectoryManager;
interface
uses DBTables;
// Node Type
const
ntKey = 0;
ntBoolean = 1;
ntInteger = 2;
ntFloat = 3;
ntString = 4;
ntDate = 5;
ntCurrency = 6;
ntBigString = 7;
type
TDirectoryManager =
class
public
constructor Create( aTableName : widestring; SetSecurity : wordbool );
destructor Destroy; override;
function GetCurrentKey : olevariant; safecall;
function SetCurrentKey( FullPathKey : widestring ) : olevariant; safecall;
function CreateFullPathKey( FullPathKey : widestring; ForcePath : wordbool ) : olevariant; safecall;
function CreateKey ( KeyName : widestring ) : olevariant; safecall;
function FullPathKeyExists( FullPathKey : widestring ) : olevariant; safecall;
function KeyExists ( KeyName : widestring ) : olevariant; safecall;
function KeysCount : olevariant; safecall;
function ValuesCount : olevariant; safecall;
function GetKeyNames : olevariant; safecall;
function GetValueNames : olevariant; safecall;
function WriteBoolean ( Name : widestring; Value : wordbool ) : olevariant; safecall;
function WriteInteger ( Name : widestring; Value : integer ) : olevariant; safecall;
function WriteFloat ( Name : widestring; Value : double ) : olevariant; safecall;
function WriteString ( Name, Value : widestring ) : olevariant; safecall;
function WriteDate ( Name : wideString; Value : TDateTime ) : olevariant; safecall;
function WriteDateFromStr( Name, Value : widestring ) : olevariant; safecall;
function WriteCurrency ( Name : widestring; Value : currency ) : olevariant; safecall;
function ReadBoolean ( Name : widestring ) : olevariant; safecall;
function ReadInteger ( Name : widestring ) : olevariant; safecall;
function ReadFloat ( Name : widestring ) : olevariant; safecall;
function ReadString ( Name : widestring ) : olevariant; safecall;
function ReadDate ( Name : widestring ) : olevariant; safecall;
function ReadDateAsStr( Name : widestring ) : olevariant; safecall;
function ReadCurrency ( Name : widestring ) : olevariant; safecall;
function FullPathValueExists( FullPathName : widestring ) : olevariant; safecall;
function ValueExists ( Name : widestring ) : olevariant; safecall;
function DeleteFullPathNode( FullPathNode : widestring ) : olevariant; safecall;
function DeleteNode ( NodeName : widestring ) : olevariant; safecall;
function FullQuery( aQuery : widestring; Kind : integer ) : olevariant; safecall;
function Query ( aQuery : widestring; Kind : integer ) : olevariant; safecall;
function IsSecureKey ( FullKeyName : widestring ) : olevariant; safecall;
function SetSecurityOfKey( FullKeyName : widestring; Security : wordbool ) : olevariant; safecall;
function TypeOf( FullPathNode : widestring ) : olevariant; safecall;
function IntegrateValues( RelValuePath : widestring ) : olevariant; safecall;
function QueryKey ( FullKeyName, ValueNameList : widestring ) : oleVariant; safecall;
function SearchKey( SearchPattern, ValueNameList : widestring ) : oleVariant; safecall;
function EditKey ( FullPathKey, newName : widestring; Security : integer ) : olevariant; safecall;
private
function pFullPathKeyExists( FullPathKey : string ) : boolean;
function GetFullPath( Name : string ) : string;
function GetParentID( KeyName : string ) : integer;
function WriteValue( aName, Value : widestring; aType : integer ) : boolean;
function ReadValue ( aName : widestring ) : string;
function WriteBigString( Name, Value : widestring ) : boolean;
function ReadBigString( Name : widestring ) : string;
function IsBigString( Name : widestring ) : boolean;
function pIsSecureKey( FullKeyName : string ) : boolean;
function IsOrHaveSecureKey( FullKeyName : string ) : boolean;
private
fTableName : string;
fCurrentKey : widestring;
fDirSecurity : wordbool;
fQuerySession : TQuery;
end;
var
fDataBase : TDataBase;
implementation
uses
Classes, SysUtils, ComObj, DB, Logs;
const
MaxStringLength = 32760;
DriverName = 'MSSQL1';
////////////////////////////////////////////////////////////////////////////////
// TDirectoryManager
// Generals procedures
procedure Log( Msg : string );
begin
Logs.Log('queries', DateTimeToStr(Now) + ' ' + Msg);
end;{ TDirectoryManager.LogThis }
function TDirectoryManager.GetCurrentKey : olevariant;
begin
result := fCurrentKey;
end;{ TDirectoryManager.GetCurrentKey }
function TDirectoryManager.GetFullPath( Name : string ) : string;
begin
if GetCurrentKey = ''
then result := Name
else result := GetCurrentKey + '/' + Name;
end; { TDirectoryManager.GetFullPath }
function TDirectoryManager.Query( aQuery : widestring; Kind : integer ) : olevariant;
begin
result := FullQuery( GetFullPath( aQuery ), Kind );
end;{ TDirectoryManager.Query }
function TDirectoryManager.KeyExists( KeyName : widestring ) : olevariant;
begin
result := FullPathKeyExists( GetFullPath( KeyName ));
end;{ TDirectoryManager.KeyExists }
function TDirectoryManager.ValueExists( Name : widestring ) : olevariant;
begin
result := FullPathValueExists( GetFullPath( Name ));
end;{ TDirectoryManager.ValueExists }
function TDirectoryManager.SetCurrentKey( FullPathKey : widestring ) : olevariant;
begin
if FullPathKey = ''
then result := true
else
begin
try
result := pFullPathKeyExists( FullPathKey ) and ((not fDirSecurity) or (not pIsSecureKey( FullPathKey )));
except
on e : EOleException do
begin
Log( 'ERROR: ' + e.Message + ' @ SetCurrentKey(' + FullPathKey + ')' );
result := false;
end;
end;
end;
if result
then fCurrentKey := FullPathKey;
end;{ TDirectoryManager.SetCurrentKey }
function TDirectoryManager.DeleteNode( NodeName : widestring ) : olevariant;
begin
result := DeleteFullPathNode( ( NodeName ));
end;{ TDirectoryManager.DeleteNode }
function TDirectoryManager.CreateKey( KeyName : widestring ) : olevariant;
begin
result := CreateFullPathKey( GetFullPath( KeyName ), true );
end;{ TDirectoryManager.SetCurrentKey }
function TDirectoryManager.WriteBoolean( Name : widestring; Value : wordbool ) : olevariant;
begin
if Value
then result := WriteValue( Name, 'true' , ntBoolean )
else result := WriteValue( Name, 'false', ntBoolean );
end;{ TDirectoryManager.WriteBoolean }
function TDirectoryManager.WriteInteger( Name : widestring; Value : Integer ) : olevariant;
begin
result := WriteValue( Name, IntToStr( Value ), ntInteger );
end;{ TDirectoryManager.WriteInteger }
function TDirectoryManager.WriteFloat( Name : widestring; Value : Double ) : olevariant;
begin
result := WriteValue( Name, FloatToStr( Value ), ntFloat );
end;{ TDirectoryManager.WriteFloat }
function TDirectoryManager.WriteString( Name, Value : widestring ) : olevariant;
begin
if( Length( Value ) > 250 )
then result := WriteBigString( Name, Value )
else result := WriteValue( Name, Value, ntString );
end;{ TDirectoryManager.WriteString }
function TDirectoryManager.WriteDate( Name : widestring; Value : TDateTime ) : olevariant;
begin
result := WriteValue( Name, FloatToStr( Value ), ntDate );
end;{ TDirectoryManager.WriteDate }
function TDirectoryManager.WriteDateFromStr( Name, Value : widestring ) : olevariant;
begin
result := WriteDate( Name, StrToDate( Value ));
end;{ TDirectoryManager.WriteDateFromStr }
function TDirectoryManager.WriteCurrency( Name : widestring; Value : Currency ) : olevariant;
begin
result := WriteValue( Name, FloatToStr( Value ), ntCurrency );
end;{ TDirectoryManager.WriteCurrency }
function TDirectoryManager.ReadBoolean( Name : widestring ) : olevariant;
var
aux : string;
begin
aux := ReadValue( Name );
result := (aux = 'true') or (aux = '1');
end;{ TDirectoryManager.ReadBoolean }
function TDirectoryManager.ReadInteger( Name : widestring ) : olevariant;
begin
try
result := StrToInt( ReadValue( Name ));
except
result := 0;
end;
end;{ TDirectoryManager.ReadInteger }
function TDirectoryManager.ReadFloat( Name : widestring ) : olevariant;
begin
try
result := StrToFloat( ReadValue( Name ));
except
result := 0.0;
end;
end;{ TDirectoryManager.ReadFloat }
function TDirectoryManager.ReadString( Name : widestring ) : olevariant;
begin
if IsBigString( Name )
then result := ReadBigString( Name )
else result := ReadValue( Name );
end;{ TDirectoryManager.ReadString }
function TDirectoryManager.ReadDate( Name : widestring ) : olevariant;
begin
try
result := StrToFloat( ReadValue( Name ));
except
result := 0;
end;
end;{ TDirectoryManager.ReadDate }
function TDirectoryManager.ReadDateAsStr( Name : widestring ) : olevariant;
begin
try
result := DateToStr( ReadDate( Name ));
except
result := '';
end;
end;{ TDirectoryManager.ReadDateAsStr }
function TDirectoryManager.ReadCurrency( Name : widestring ) : olevariant;
begin
try
result := StrToFloat( ReadValue( Name ));
except
result := 0.0;
end;
end;{ TDirectoryManager.ReadCurrency }
// Specifics procedures
constructor TDirectoryManager.Create( aTableName : widestring; SetSecurity : wordbool );
begin
try
inherited Create;
fCurrentKey := '';
fTableName := aTableName;
fDirSecurity := SetSecurity;
fQuerySession := TQuery.Create(nil);
fQuerySession.DataBaseName := DriverName;
except
on e : Exception do
begin
Log('ERROR: Create ' + ' ' + e.Message);
raise;
end;
end;
end;{ TDirectoryManager.Create }
destructor TDirectoryManager.Destroy;
begin
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.Destroy;
inherited;
except
on e : Exception do
begin
Log('ERROR: Destroy ' + ' ' + e.Message);
raise;
end;
end;
end;{ TDirectoryManager.Destroy }
function TDirectoryManager.FullPathKeyExists( FullPathKey : widestring ) : olevariant;
begin
try
if pFullPathKeyExists( FullPathKey )
then
if fDirSecurity
then result := not pIsSecureKey( FullPathKey )
else result := true
else result := false;
except
on e : Exception do
begin
result := false;
Log('ERROR: FullPathKeyExists ' + e.Message + ' Key: ' + FullPathKey );
end;
end;
end;{ TDirectoryManager.FullPathKeyExists }
function TDirectoryManager.FullPathValueExists( FullPathName : widestring ) : olevariant;
var
lsPos : integer;
begin
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE "' + FullPathName + '"' + ' and Kind <> ' + IntToStr(ntKey) );
fQuerySession.Open;
if fQuerySession.FindFirst
then
begin
if not fDirSecurity
then
begin
lsPos := LastDelimiter( '/', FullPathName );
if lsPos > 0
then result := not pIsSecureKey( Copy( FullPathName, 0, lsPos - 1))
else result := false;
end
else result := false;
end
else result := false;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := false;
Log('ERROR: FullPathValueExists ' + ' ' + e.Message );
end;
end;
end;{ TDirectoryManager.FullPathValueExists }
function TDirectoryManager.CreateFullPathKey( FullPathKey : widestring; ForcePath : wordbool ) : olevariant;
function recCreateFullPathKey( keyPath, keyName : string ) : boolean;
var
lsPos : integer;
ParentID : integer;
newKeyPath : string;
newKeyName : string;
begin
if ( keyPath <> '' ) and not pFullPathKeyExists( keyPath )
then
begin
lsPos := LastDelimiter('/', keyPath );
if lsPos > 0
then
begin
newKeyPath := Copy( keyPath, 0, lsPos - 1 );
newKeyName := Copy( keyPath, lsPos + 1, Length( keyPath));
end
else
begin
newKeyPath := '';
newKeyName := keyPath;
end;
result := recCreateFullPathKey( newKeyPath, newKeyName );
end
else result := true;
if result
then
begin
if KeyPath = ''
then
begin
ParentID := 0;
newKeyName := KeyName;
end
else
begin
ParentID := GetParentID(keyPath);
newKeyName := keyPath + '/' + KeyName;
end;
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('INSERT INTO ' + fTableName + '(Entry, ParentID, Kind)' );
fQuerySession.SQL.Add('VALUES (' + '"' + newKeyName + '"' + ',' + IntToStr(ParentID) + ',' + IntToStr(ntKey) + ')' );
fQuerySession.ExecSQL;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
if ForcePath
then Log('ERROR: recCreateFullPathKey (true ) ' + e.Message )
else Log('ERROR: recCreateFullPathKey (false) ' + e.Message );
result := false;
end;
end;
end;
end; { recCreateFullPathKey }
var
keyPath : string;
keyName : string;
lsPos : integer;
begin
try
if pFullPathKeyExists( FullPathKey )
then
if fDirSecurity
then result := not pIsSecureKey( FullPathKey )
else result := true
else
begin
lsPos := LastDelimiter('/', FullPathKey );
if lsPos > 0
then
begin
KeyPath := Copy( FullPathKey, 0, lsPos - 1 );
KeyName := Copy( FullPathKey, lsPos + 1, Length( FullPathKey ));
end
else
begin
KeyPath := '';
KeyName := FullPathKey;
end;
if ForcePath or (KeyPath = '') or FullPathKeyExists( keyPath )
then result := recCreateFullPathKey( keyPath, keyName )
else result := false;
end;
except
on e : Exception do
begin
if ForcePath
then Log('ERROR: CreateFullPathKey (true) ' + e.Message )
else Log('ERROR: CreateFullPathKey (false) ' + e.Message );
result := false;
end;
end;
end;{ TDirectoryManager.CreateFullPathKey }
function TDirectoryManager.KeysCount : olevariant;
var
pID : integer;
currKey : string;
begin
try
currKey := GetCurrentKey;
pID := GetParentID(currKey);
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT count(*) Counter');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE ParentID = ' + IntToStr(pID) + ' and Kind = ' + IntToStr(ntKey) );
fQuerySession.Open;
if fQuerySession.FindFirst
then result := fQuerySession.FieldByName('Counter').AsInteger
else result := 0;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
Log('ERROR: KeysCount ' + e.message );
result := -1;
end;
end;
end;{ TDirectoryManager.KeysCount }
function TDirectoryManager.ValuesCount : olevariant;
var
pID : integer;
currKey : string;
begin
try
currKey := GetCurrentKey;
pID := GetParentID(currKey);
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT count(*) Counter');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE ParentID = ' + IntToStr(pID) + ' and Kind <> ' + IntToStr(ntKey) );
fQuerySession.Open;
if fQuerySession.FindFirst
then result := fQuerySession.FieldByName('Counter').AsInteger
else result := 0;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := -1;
Log('ERROR: ValuesCount ' + e.Message );
end;
end;
end;{ TDirectoryManager.ValuesCount }
function TDirectoryManager.GetKeyNames : olevariant;
var
currKey : string;
KeyName : string;
keyNames : TStringList;
pID : integer;
begin
result := '';
keyNames := TStringList.Create;
try
currKey := GetCurrentKey;
try
if currKey <> ''
then
begin
pID := GetParentID(currKey);
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE ParentID = ' + IntToStr(pID) + ' and Kind = ' + IntToStr(ntKey) );
fQuerySession.Open;
if fQuerySession.FindFirst
then
begin
while not fQuerySession.EOF do
begin
KeyName := fQuerySession.FieldByName('Entry').AsString;
KeyName := Copy( KeyName, length(currKey) + 2, length(KeyName) );
KeyNames.Add(KeyName);
fQuerySession.Next;
end;
result := KeyNames.Text;
end;
end
else
begin
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE ParentID = 0' );
fQuerySession.Open;
if fQuerySession.FindFirst
then
begin
while not fQuerySession.EOF do
begin
KeyName := fQuerySession.FieldByName('Entry').AsString;
KeyNames.Add(KeyName);
fQuerySession.Next;
end;
result := KeyNames.Text;
end;
end;
finally
KeyNames.free;
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := '';
Log('ERROR: GetKeyNames ' + e.message );
end;
end;
end;{ TDirectoryManager.GetKeyNames }
function TDirectoryManager.GetValueNames : olevariant;
var
currKey : string;
valueName : string;
valueNames : TStringList;
pID : integer;
begin
result := '';
valueNames := TStringList.Create;
try
currKey := GetCurrentKey;
pID := GetParentID(currKey);
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE ParentID = ' + IntToStr(pID) + ' and Kind <> ' + IntToStr(ntKey) );
fQuerySession.Open;
if fQuerySession.FindFirst
then
begin
while not fQuerySession.EOF do
begin
valueName := fQuerySession.FieldByName('Entry').AsString;
valueName := Copy( valueName, length(currKey) + 2, length(valueName) );
valueNames.Add(valueName);
fQuerySession.Next;
end;
result := valueNames.Text;
end;
finally
fQuerySession.Close;
valueNames.Free;
end;
except
on e : Exception do
begin
result := '';
Log('ERROR: GetValueNames ' + e.Message );
end;
end;
end;{ TDirectoryManager.GetValueNames }
function TDirectoryManager.DeleteFullPathNode( FullPathNode : widestring ) : olevariant;
begin
if fDirSecurity and FullPathKeyExists( FullPathNode ) and IsOrHaveSecureKey( FullPathNode )
then result := false
else
begin
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Add('DELETE FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + FullPathNode + '/%"'); //SubNodes
fQuerySession.ExecSQL;
finally
fQuerySession.Close;
end;
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('DELETE FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + FullPathNode + '"'); //Node
fQuerySession.ExecSQL;
result := true;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
Log('ERROR: DeleteFullPathNode ' + e.Message );
result := false;
end;
end;
end;
end;{ TDirectoryManager.DeleteFullPathNode }
function TDirectoryManager.SetSecurityOfKey( FullKeyName : widestring; Security : wordbool ) : olevariant;
begin
if not fDirSecurity and FullPathKeyExists( FullKeyName )
then
begin
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('UPDATE ' + fTableName);
if Security
then fQuerySession.SQL.Add('SET Security = 1')
else fQuerySession.SQL.Add('SET Security = 0');
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + FullKeyName + '"');
fQuerySession.ExecSQL;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
Log('ERROR: SetSecurityOfKey ' + e.message );
result := false;
end;
end;
result := true;
end
else result := false;
end;{ TDirectoryManager.SetSecurityOfKey }
function TDirectoryManager.IsSecureKey( FullKeyName : widestring ) : olevariant;
begin
if fDirSecurity
then result := true
else
try
result := pIsSecureKey( FullKeyName );
except
on e : Exception do
begin
result := true;
Log('ERROR: IsSecureKey ' + e.message );
end;
end;
end;{ TDirectoryManager.IsSecureKey }
function TDirectoryManager.IsOrHaveSecureKey( FullKeyName : string ) : boolean;
begin
try
result := true;
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Security');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE "' + FullKeyName + '"' + ' and Kind = ' + IntToStr(ntKey) );
fQuerySession.Open;
if fQuerySession.FindFirst
then
while result and not fQuerySession.Eof do
begin
result := result and fQuerySession.FieldByName('Security').AsBoolean;
fQuerySession.Next;
end
else result := false;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := false;
Log('ERROR: IsOrHaveSecureKey ' + e.message );
end;
end;
end;{ TDirectoryManager.IsOrHaveSecureKey }
function TDirectoryManager.WriteValue( aName, Value: widestring; aType : integer ) : boolean;
var
Find : boolean;
lsPos : integer;
pID : integer;
keyName : string;
valueName : string;
sec : boolean;
begin
try
valueName := GetFullPath(aName);
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Kind ');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE "' + valueName + '"' + ' and Kind <> ' + IntToStr(ntKey) );
fQuerySession.SQL.Add('Group By Kind');
fQuerySession.Open;
Find := fQuerySession.FindFirst;
if Find and (fQuerySession.FieldByName('Kind').AsInteger = 7)
then
begin
DeleteFullPathNode( valueName );
Find := false;
end;
finally
fQuerySession.Close;
end;
if Find
then
begin
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('UPDATE ' + fTableName);
fQuerySession.SQL.Add('SET Value = ' + '"' + Value + '",' + 'Kind = ' + IntToStr(aType) );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + valueName + '"');
fQuerySession.ExecSQL;
result := true;
finally
fQuerySession.Close;
end;
end
else
begin
try
lsPos := LastDelimiter('/', valueName);
keyName := copy(valueName, 0, lsPos - 1);
sec := pIsSecureKey(keyName);
pID := GetParentID (keyName);
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('INSERT INTO ' + fTableName + '(Entry, ParentID, Kind, Value, Security, ValueSize)' );
fQuerySession.SQL.Add('VALUES (' + '"' + valueName + '"' + ',' + IntToStr(pID) + ',' );
fQuerySession.SQL.Add( IntToStr(aType) + ',"' + Value + '",' + IntToStr( Ord(sec) ) + ',' + '0' + ')' );
fQuerySession.ExecSQL;
result := true;
finally
fQuerySession.Close;
end;
end;
except
on e : Exception do
begin
result := false;
Log('ERROR: WriteValue ' + e.message );
end;
end;
end;{ TDirectoryManager.WriteValue }
function TDirectoryManager.ReadValue( aName : widestring ) : string;
var
Trap : integer;
begin
try
try
Trap := 1;
if fQuerySession.Active
then
begin
Trap := 1;
fQuerySession.Close;
Trap := 2;
end;
Trap := 3;
fQuerySession.SQL.Clear;
Trap := 4;
fQuerySession.SQL.Add('SELECT Value');
Trap := 5;
fQuerySession.SQL.Add('FROM ' + fTableName );
Trap := 6;
fQuerySession.SQL.Add('WHERE Entry LIKE "' + GetFullPath(aName) + '"' );
Trap := 7;
fQuerySession.Open;
Trap := 8;
if fQuerySession.FindFirst
then
begin
Trap := 9;
result := fQuerySession.FieldByName('Value').AsString;
Trap := 10;
end
else result := '';
Trap := 11;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := '';
Log('ERROR: ReadValue ' + e.message );
end;
end;
end;{ TDirectoryManager.ReadValue }
function TDirectoryManager.TypeOf( FullPathNode : widestring ) : olevariant; safecall;
begin
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Kind');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE "' + FullPathNode + '"');
fQuerySession.SQL.Add('GROUP BY Kind');
fQuerySession.Open;
if fQuerySession.FindFirst
then result := fQuerySession.FieldByName('Kind').AsInteger
else result := -1;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := false;
Log('ERROR: TypeOf ' + e.message );
end;
end;
end;{ TDirectoryManager.TypeOf }
function TDirectoryManager.IntegrateValues( RelValuePath : widestring ) : olevariant;
var
str : string;
value : string;
ValueName : string;
intSum : integer;
floatSum : double;
ntType : integer;
begin
intSum := 0;
floatSum := 0;
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT *');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + RelValuePath + '"' + '/%');
fQuerySession.Open;
if fQuerySession.FindFirst
then
while not fQuerySession.Eof do
begin
ValueName := fQuerySession.FieldByName('Entry').AsString;
str := Copy( ValueName, length(GetCurrentKey) + 2, length(ValueName) );
if (LastDelimiter( '/', str ) = 0)
then
begin
value := fQuerySession.FieldByName('Value').AsString;
if (fQuerySession.FieldByName('Kind').AsInteger = ntInteger )
then ntType := ntInteger
else ntType := ntFloat;
case ntType of
ntInteger : intSum := intSum + StrToInt (value);
ntFloat : floatSum := floatSum + StrToFloat(value);
else result := 0;
end;
end;
fQuerySession.Next;
end;
finally
fQuerySession.Close;
end;
result := floatSum + intSum;
except
on e : Exception do
begin
result := 0;
Log('ERROR: IntegrateValues ' + e.message );
end;
end;
end;{ TDirectoryManager.IntegrateValues }
function TDirectoryManager.SearchKey( SearchPattern, ValueNameList : widestring ) : oleVariant; safecall;
var
resultList : TStringList;
valueNames : TStringList;
count : integer;
i, idx : integer;
subElement : string;
element : string;
str : string;
value : string;
FullKeyName : string;
bool : oleVariant;
function GetKeyName( KeyName : string ) : string;
var
lsPos : integer;
begin
result := copy(KeyName, length(FullKeyName) + 2, length(KeyName) );
lsPos := System.Pos( '/', result );
result := copy(result, 0, lsPos - 1 );
end;{ GetKeyName }
function FormatQuery( str : string ) : string;
var
i : integer;
begin
for i := 1 to length(str) do
if str[i] = '*'
then str[i] := '%';
result := str;
end;{ FormatQuery }
begin
try
valueNames := TStringList.Create;
try
valueNames.Text := string(ValueNameList);
if valueNames.Count > 0
then
begin
FullKeyName := GetCurrentKey;
str := '''' + FullKeyName + '/' + FormatQuery(SearchPattern) + '''' + ' and (';
for i := 0 to ValueNames.Count - 1 do
begin
str := str + '(';
str := str + 'Entry LIKE ' + '''' + '%/' + ValueNames[i] + '''' + ' and Kind <> ' + IntToStr(ntKey);
str := str + ')';
if i < (ValueNames.Count - 1)
then str := str + ' or '
else str := str + ')';
end;
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT *');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + str );
fQuerySession.Open;
if fQuerySession.FindFirst
then
begin
count := 1;
element := GetKeyName( fQuerySession.FieldByName('Entry').AsString );
while not fQuerySession.EOF do
begin
subElement := GetKeyName( fQuerySession.FieldByName('Entry').AsString );
if subElement <> element
then
begin
element := subElement;
inc(count);
end;
fQuerySession.Next;
end;
end
else count := 0;
if count > 0
then
begin
resultList := TStringList.Create;
try
resultList.Values['Count'] := IntToStr( count );
idx := 0;
fQuerySession.First;
while not fQuerySession.Eof do
begin
element := GetKeyName( fQuerySession.FieldByName('Entry').AsString );
resultList.Values['Key' + IntToStr(idx)] := element;
for i := 0 to ValueNames.Count - 1 do
begin
subElement := fQuerySession.FieldByName('Entry').AsString;
while not fQuerySession.EOF and (fQuerySession.FieldByName('Entry').AsString <> subElement ) do
fQuerySession.Next;
if not fQuerySession.EOF
then
begin
bool := true;
value := fQuerySession.FieldByName('Value').AsString
end
else bool := false;
if bool
then resultList.Values[valueNames[i] + IntTostr(idx)] := value;
fQuerySession.Next;
end;
inc(idx);
end;
result := resultList.Text;
finally
resultList.Free;
end;
end
else result := '';
finally
fQuerySession.Close;
end;
end;
finally
valueNames.free;
end;
except
on e : Exception do
begin
Log('ERROR: SearchKey ' + e.message );
result := '';
end;
end;
end;{ TDirectoryManager.SearchKey }
function TDirectoryManager.QueryKey( FullKeyName, ValueNameList : widestring ) : olevariant;
var
resultList : TStringList;
valueNames : TStringList;
count : integer;
i, idx : integer;
Pos : integer;
subElement : string;
element : string;
str : string;
value : string;
bool : oleVariant;
Trap : integer;
function GetKeyName( KeyName : string ) : string;
var
lsPos : integer;
begin
result := copy(KeyName, length(FullKeyName) + 2, length(KeyName) );
lsPos := System.Pos( '/', result );
result := copy(result, 0, lsPos - 1 );
end;{ GetKeyName }
function FindByName( EntryName : string ) : string;
var
lsPos : integer;
begin
result := copy(EntryName, length(FullKeyName) + 2, length(EntryName) );
lsPos := System.Pos( '/', result );
result := copy(result, lsPos + 1, length(result) );
end;{ FindByName }
function GetPosInResultList( Entry : string ) : integer;
var
i : integer;
Find : boolean;
begin
i := 0;
Find := false;
while not Find and (i < valueNames.Count) do
begin
if system.Pos( valueNames[i], Entry ) > 0
then Find := true
else inc(i);
end;
if Find
then result := i
else result := -1;
end;{ GetPosInResultList }
begin
try
valueNames := TStringList.Create;
try
valueNames.Text := string(ValueNameList);
if valueNames.Count > 0
then
begin
str := '''' + FullKeyName + '/%' + '''' + ' and (';
for i := 0 to ValueNames.Count - 1 do
begin
str := str + '(';
str := str + 'Entry LIKE ' + '''' + '%/' + ValueNames[i] + '''' + ' and Kind <> ' + IntToStr(ntKey);
str := str + ')';
if i < (ValueNames.Count - 1)
then str := str + ' or '
else str := str + ')';
end;
try
Trap := 1;
if fQuerySession.Active
then
begin
Trap := 2;
fQuerySession.Close;
Trap := 3;
end;
fQuerySession.SQL.Clear;
Trap := 4;
fQuerySession.SQL.Add('SELECT *');
Trap := 5;
fQuerySession.SQL.Add('FROM ' + fTableName );
Trap := 6;
fQuerySession.SQL.Add('WHERE Entry LIKE ' + str );
Trap := 7;
fQuerySession.Open;
Trap := 8;
if fQuerySession.FindFirst
then
begin
count := 1;
Trap := 8;
element := GetKeyName( fQuerySession.FieldByName('Entry').AsString );
Trap := 9;
while not fQuerySession.EOF do
begin
Trap := 9;
subElement := GetKeyName( fQuerySession.FieldByName('Entry').AsString );
Trap := 10;
if subElement <> element
then
begin
element := subElement;
inc(count);
end;
Trap := 8;
fQuerySession.Next;
Trap := 9;
end;
end
else count := 0;
resultList := TStringList.Create;
resultList.Values['Count'] := IntToStr( count );
if count > 0
then
begin
try
idx := 0;
Trap := 10;
fQuerySession.First;
Trap := 11;
while not fQuerySession.Eof do
begin
Trap := 12;
element := GetKeyName( fQuerySession.FieldByName('Entry').AsString );
Trap := 13;
resultList.Values['Key' + IntToStr(idx)] := element;
for i := 0 to ValueNames.Count - 1 do
begin
Trap := 14;
subElement := fQuerySession.FieldByName('Entry').AsString;
Trap := 15;
while not fQuerySession.EOF and (fQuerySession.FieldByName('Entry').AsString <> subElement ) do
fQuerySession.Next;
Trap := 16;
if not fQuerySession.EOF
then
begin
Trap := 17;
bool := true;
value := fQuerySession.FieldByName('Value').AsString;
Trap := 18;
end
else bool := false;
if bool
then
begin
Pos := GetPosInResultList(subElement);
if Pos >= 0
then resultList.Values[valueNames[Pos] + IntTostr(idx)] := value;
end;
Trap := 18;
fQuerySession.Next;
end;
inc(idx);
end;
result := resultList.Text;
finally
resultList.Free;
end;
end;
finally
fQuerySession.Close;
end;
end;
finally
valueNames.free;
end;
except
on e : Exception do
begin
result := '';
Log('ERROR: QueryKey ' + IntToStr(Trap) + ' ' + e.message );
end;
end;
end;{ TDirectoryManager.QueryKey }
function TDirectoryManager.EditKey( FullPathKey, newName : widestring; Security : integer ) : olevariant;
var
EntryKey : string;
curKeyName : string;
lsPos : integer;
begin
lsPos := LastDelimiter('/', FullPathKey );
if lsPos > 0
then curKeyName := copy( FullPathKey, lsPos + 1, length(FullPathKey) )
else curKeyName := FullPathKey;
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.RequestLive := true;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry, Security');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + string(FullPathKey) + '/%' + '"' );
fQuerySession.Open;
fQuerySession.RequestLive := false;
if fQuerySession.FindFirst
then
while not fQuerySession.Eof do
begin
EntryKey := fQuerySession.FieldByName('Entry').AsString;
if length(EntryKey) > length(curKeyName)
then lsPos := Pos( curKeyName + '/', EntryKey )
else lsPos := 0;
System.Delete(EntryKey, lsPos, length(curKeyName) );
System.Insert(NewName, EntryKey, lsPos );
fQuerySession.Edit;
fQuerySession.FieldByName('Entry').AsString := EntryKey;
fQuerySession.FieldByName('Security').AsBoolean := (Security <> 0);
fQuerySession.Post;
fQuerySession.Next;
end;
finally
fQuerySession.Close;
end;
try
fQuerySession.RequestLive := true;
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry, Security');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + string(FullPathKey) + '"' );
fQuerySession.Open;
fQuerySession.RequestLive := false;
if fQuerySession.FindFirst
then
begin
fQuerySession.Edit;
EntryKey := fQuerySession.FieldByName('Entry').AsString;
lsPos := Pos( curKeyName, EntryKey );
System.Delete(EntryKey, lsPos, length(curKeyName) );
System.Insert(NewName, EntryKey, lsPos );
fQuerySession.Edit;
fQuerySession.FieldByName('Entry').AsString := EntryKey;
fQuerySession.FieldByName('Security').AsBoolean := ( Security <> 0);
fQuerySession.Post;
result := true;
end
else result := false;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := false;
Log('ERROR: EditKey ' + e.message );
end;
end;
end;{ TDirectoryManager..FullQuery }
function TDirectoryManager.FullQuery( aQuery : widestring; Kind : integer ) : olevariant;
var
elementNames : TStringList;
Aux1, Aux2 : string;
value : string;
lsPos : integer;
pID : integer;
function ClearQuery : string;
const
CharQuerySet = [ '%', '_' ];
var
s : string;
i : integer;
begin
result := '';
s := string(aQuery);
for i := 1 to length(s) do
if not (s[i] in CharQuerySet)
then result := result + s[i];
if result[length(result)] = '/'
then delete(result, length(result), 1);
end;
begin
Aux1 := string(aQuery);
if Kind >= 0
then Aux2 := ' and Kind = ' + IntToStr(Kind)
else Aux2 := '';
pID := GetParentID(Aux1);
elementNames := TStringList.Create;
try
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry, Value, Kind');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + Aux1 + '"' + Aux2 + ' and ParentID = ' + IntToStr(pID) );
fQuerySession.SQL.Add('Group By Entry');
fQuerySession.Open;
Aux2 := ClearQuery;
if fQuerySession.FindFirst
then
while not fQuerySession.Eof do
begin
Aux1 := fQuerySession.FieldByName('Entry').AsString;
Aux1 := Copy( Aux1, length(Aux2) + 2, length(Aux1) );
lsPos := System.Pos( '/', Aux1 );
if lsPos = 0
then
begin
if fQuerySession.FieldByName('Kind').AsInteger = 0
then elementNames.Add(Aux1)
else
begin
value := fQuerySession.FieldByName('Value').AsString;
elementNames.Values['ValueName'] := Aux1;
elementNames.Values['value'] := Value;
end;
end;
fQuerySession.Next;
end;
result := elementNames.Text;
finally
fQuerySession.Close;
end;
finally
elementNames.Free;
end;
except
on e : Exception do
begin
result := '';
Log('ERROR: FullQuery ' + e.message );
end;
end;
end;{ TDirectoryManager.FullQuery }
function TDirectoryManager.pFullPathKeyExists( FullPathKey : string ) : boolean;
var
Trap : integer;
begin
try
try
Trap := 1;
if fQuerySession.Active
then
begin
Trap := 2;
fQuerySession.Close;
Trap := 3;
end;
Trap := 4;
fQuerySession.SQL.Clear;
Trap := 5;
fQuerySession.SQL.Add('SELECT Entry');
Trap := 6;
fQuerySession.SQL.Add('FROM ' + fTableName );
Trap := 7;
fQuerySession.SQL.Add('WHERE Entry LIKE "' + FullPathKey + '"' + ' and Kind = ' + IntToStr(ntKey) );
Trap := 8;
fQuerySession.Open;
Trap := 9;
result := fQuerySession.FindFirst;
Trap := 10;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := false;
Log('ERROR: pFullPathKeyExists ' + IntToStr(Trap) + ' ' + e.message);
end;
end
end;{ TDirectoryManager.pFullPathKeyExists }
function TDirectoryManager.pIsSecureKey( FullKeyName : string ) : boolean;
begin
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE "' + FullKeyName + '"' + ' and Security <> 0');
fQuerySession.Open;
result := fQuerySession.FindFirst
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := false;
Log('ERROR: pIsSecureKey ' + e.message );
end;
end;
end;{ TDirectoryManager.IsSecureKey }
function TDirectoryManager.GetParentID( keyName : string ) : integer;
begin
result := 0;
try
if KeyName <> ''
then
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT ID');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + keyName + '"');
fQuerySession.Open;
if fQuerySession.FindFirst
then result := fQuerySession.FieldByName('ID').AsInteger
else result := -1;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
result := -1;
Log('ERROR: GetParentID ' + e.message );
end;
end;
end;{ TDirectoryManager.GetParentID }
function TDirectoryManager.IsBigString( Name : widestring ) : boolean;
var
trap : integer;
begin
try
try
trap := 1;
if fQuerySession.Active then fQuerySession.Close;
trap := 2;
fQuerySession.SQL.Clear;
trap := 3;
fQuerySession.SQL.Add('SELECT Kind');
trap := 4;
fQuerySession.SQL.Add('FROM ' + fTableName );
trap := 5;
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + GetFullPath(Name) + '"');
trap := 6;
fQuerySession.Open;
trap := 7;
if fQuerySession.FindFirst
then
begin
trap := 8;
result := (fQuerySession.FieldByName('Kind').AsInteger = ntBigString);
trap := 9;
end
else result := false;
trap := 10;
finally
fQuerySession.Close;
end;
except
on e : exception do
begin
Log('IsBigString --> ERROR: ( ' + IntToStr(Trap) + ' ' + e.Message + ' key: ' + GetFullPath(Name) );
result := false;
end;
end;
end;{ TDirectoryManager.IsBigString }
function TDirectoryManager.ReadBigString( Name : widestring ) : string;
var
FullPathName : string;
ValueName : array[0..20] of string;
ValueSize : array[0..20] of integer;
Count, i : integer;
begin
try
try
FullPathName := GetFullPath(Name);
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry, ValueSize');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE ' + '"' + FullPathName + '%"' );
fQuerySession.Open;
Count := 0;
if fQuerySession.FindFirst
then
while not fQuerySession.EOF do
begin
ValueName[Count] := fQuerySession.FieldByName('Entry').AsString;
ValueSize[Count] := fQuerySession.FieldByName('ValueSize').AsInteger;
inc(Count);
fQuerySession.Next;
end;
finally
fQuerySession.Close;
end;
try
for i := 0 to Count - 1do
begin
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('sp_dboption FiveDirManager, "select into/bulkcopy", true');
fQuerySession.SQL.Add('DECLARE @@ptrval varbinary(16)');
fQuerySession.SQL.Add('SET TEXTSIZE ' + IntToStr(ValueSize[i]) );
fQuerySession.SQL.Add('SELECT @@ptrval = TEXTPTR(Value)');
fQuerySession.SQL.Add('FROM ' + fTableName);
fQuerySession.SQL.Add('WHERE Entry Like ' + '"' + ValueName[i] + '"' );
fQuerySession.SQL.Add('READTEXT ' + fTableName + '.Value @@ptrval 0 ' + IntToStr(ValueSize[i]) );
fQuerySession.Open;
result := result + fQuerySession.FieldByName('Value').AsString;
end;
finally
fQuerySession.Close;
end;
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('sp_dboption FiveDirManager, "select into/bulkcopy", false');
fQuerySession.ExecSQL;
finally
fQuerySession.Close;
end;
except
on e : Exception do
begin
Log('ERROR: ReadBigString ' + e.message );
result := '';
end;
end;
end;{ TDirectoryManager.ReadBigString }
function TDirectoryManager.WriteBigString( Name, Value : widestring ) : boolean;
const
MaxTextSize = 32700;
var
Find : boolean;
KeyName : string;
theName : string;
saveValue : string;
ValueSize : integer;
lsPos, i : integer;
pID : integer;
sec : boolean;
begin
theName := GetFullPath(Name);
try
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('SELECT Entry');
fQuerySession.SQL.Add('FROM ' + fTableName );
fQuerySession.SQL.Add('WHERE Entry LIKE "' + theName + '"' + ' and Kind <> ' + IntToStr(ntKey) );
fQuerySession.Open;
Find := fQuerySession.FindFirst;
finally
fQuerySession.Close;
end;
if Find then DeleteFullPathNode( theName );
lsPos := LastDelimiter('/', theName);
keyName := copy(theName, 0, lsPos - 1);
sec := pIsSecureKey(keyName);
pID := GetParentID (keyName);
for i := 0 to Length( Value ) div MaxTextSize do
begin
saveValue := Copy( Value, i*MaxTextSize + 1, MaxTextSize );
ValueSize := length(saveValue);
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('INSERT INTO ' + fTableName + '(Entry, ParentID, Kind, Value, Security, ValueSize)' );
fQuerySession.SQL.Add('VALUES (' + '"' + theName + '"' + ',' + IntToStr(pID) + ',' );
fQuerySession.SQL.Add( '7' + ',"' + ' ' + '",' + IntToStr( Ord(sec) ) + ',' + IntToStr(valueSize) + ')' );
fQuerySession.ExecSQL;
finally
fQuerySession.Close;
end;
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('sp_dboption FiveDirManager, "select into/bulkcopy", true');
fQuerySession.SQL.Add('DECLARE @@ptrval varbinary(16)');
fQuerySession.SQL.Add('SET TEXTSIZE ' + IntToStr(ValueSize) );
fQuerySession.SQL.Add('SELECT @@ptrval = TEXTPTR(Value)');
fQuerySession.SQL.Add('FROM ' + fTableName);
fQuerySession.SQL.Add('WHERE Entry Like ' + '"' + theName + '"' );
fQuerySession.SQL.Add('WRITETEXT ' + fTableName + '.Value @@ptrval ' + '"' + saveValue + '"');
fQuerySession.ExecSQL;
finally
fQuerySession.Close;
end;
try
if fQuerySession.Active then fQuerySession.Close;
fQuerySession.SQL.Clear;
fQuerySession.SQL.Add('sp_dboption FiveDirManager, "select into/bulkcopy", false');
fQuerySession.ExecSQL;
finally
fQuerySession.Close;
end;
theName := theName + '/V' + IntToStr(i);
end;
result := true;
except
on e : Exception do
begin
result := false;
Log('ERROR: WriteString ' + e.message );
end;
end;
end;{ TDirectoryManager.WriteBigString }
initialization
Log( 'Restarting ........................ ' + DateTimeToStr(Now) );
fDataBase := TDataBase.Create(nil);
fDataBase.DataBaseName := DriverName;
fDataBase.LoginPrompt := False;
fDataBase.Params.Values['USER NAME'] := 'sa';
fDataBase.Params.Values['PASSWORD'] := 'elmanicero';
finalization
Log( 'Closing ........................ ' + DateTimeToStr(Now) );
fDataBase.Close;
fDataBase.Free;
end.
|
unit mainform;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
EditBtn, ExtCtrls, ComCtrls,
synaser;
type
{ TformSerial }
TformSerial = class(TForm)
btnConnect: TButton;
comboClientServer: TComboBox;
editDevice: TEdit;
editFileName: TFileNameEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
editFileSize: TLabeledEdit;
editReceivedFileName: TLabeledEdit;
ScrollBox1: TScrollBox;
StatusBar: TStatusBar;
timerClientConnect: TTimer;
timerServerConnect: TTimer;
procedure btnConnectClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure timerClientConnectTimer(Sender: TObject);
procedure timerServerConnectTimer(Sender: TObject);
private
{ private declarations }
connected: Boolean;
ser: TBlockSerial;
procedure ServerSendFile();
procedure ClientReceiveFile();
public
{ public declarations }
end;
var
formSerial: TformSerial;
implementation
const
INT_COMBO_SERVER = 0;
INT_COMBO_CLIENT = 1;
// Data records
BYTE_REQUEST_CONNECTION = $00;
// Followed by nothing else
BYTE_ACCEPT_CONNECTION = $01;
// Followed by nothing else
BYTE_FILE_NAME = $02;
// Followed by:
// File name size - 1 Byte indicating the size sz_size. The name doesn't include path.
// File name - sz_size bytes in UTF-8
BYTE_FILE_DATA = $03;
// Followed by:
// File size - 8 Bytes, a Int64 in Little Endian, indicates sz_size
// File data - sz_size bytes
{$R *.lfm}
{ TformSerial }
procedure TformSerial.FormCreate(Sender: TObject);
begin
ser := TBlockSerial.Create;
end;
procedure TformSerial.btnConnectClick(Sender: TObject);
begin
btnConnect.Enabled := False;
try
if connected then raise Exception.Create('Already connected');
// Check the input data
if (editDevice.Text = '') then raise Exception.Create('Invalid serial port name');
if (editFileName.Text = '') then raise Exception.Create('Invalid file path');
if (comboClientServer.ItemIndex = INT_COMBO_SERVER)
and (not FileExists(editFileName.Text)) then raise Exception.Create('Invalid input file. It doesn''t exist');
if (comboClientServer.ItemIndex = INT_COMBO_CLIENT)
and (not DirectoryExists(editFileName.Text)) then raise Exception.Create('Invalid output directory. It doesn''t exist');
StatusBar.SimpleText := 'Connecting';
Application.ProcessMessages;
ser.Connect(editDevice.Text); //ComPort
Sleep(1000);
Application.ProcessMessages;
ser.config(115000, 8, 'N', SB1, False, False);
Sleep(1000);
Application.ProcessMessages;
StatusBar.SimpleText := 'Device: ' + ser.Device +
' Status: ' + ser.LastErrorDesc + ' ' +
Inttostr(ser.LastError);
if ser.LastError = 0 then connected := True;
if comboClientServer.ItemIndex = INT_COMBO_SERVER then
timerServerConnect.Enabled := True
else
timerClientConnect.Enabled := True;
finally
btnConnect.Enabled := True;
end;
end;
procedure TformSerial.FormDestroy(Sender: TObject);
begin
ser.free;
end;
procedure TformSerial.timerClientConnectTimer(Sender: TObject);
var
Data: Byte;
begin
Data := ser.RecvByte(timerClientConnect.Interval div 2);
if (Data = BYTE_REQUEST_CONNECTION) and (ser.LastError = 0) then
begin
Connected := True;
timerClientConnect.Enabled := False;
ser.SendByte(BYTE_ACCEPT_CONNECTION);
ClientReceiveFile();
end;
end;
procedure TformSerial.timerServerConnectTimer(Sender: TObject);
var
Data: Byte;
begin
ser.SendByte(BYTE_REQUEST_CONNECTION);
Data := ser.RecvByte(timerServerConnect.Interval div 2);
if (Data = BYTE_ACCEPT_CONNECTION) and (ser.LastError = 0) then
begin
Connected := True;
timerServerConnect.Enabled := False;
ServerSendFile();
end;
end;
procedure TformSerial.ServerSendFile();
var
ShortStr: shortstring;
Data, StrLen: Byte;
i: Integer;
lStream: TFileStream;
lSize: Int64;
begin
StatusBar.SimpleText := 'Sending file';
Application.ProcessMessages;
// Send the file name:
ShortStr := ExtractFileName(editFileName.Text);
StrLen := Length(ShortStr);
ser.SendByte(BYTE_FILE_NAME);
ser.SendByte(StrLen);
for i := 1 to StrLen do
ser.SendByte(Byte(ShortStr[i]));
// Send the file data:
lStream := TFileStream.Create(editFileName.Text, fmOpenRead);
try
lSize := Length(ShortStr);
ser.SendByte(BYTE_FILE_DATA);
ser.SendBuffer(@lSize, 8);
for i := 0 to lSize - 1 do
begin
Data := lStream.ReadByte();
ser.SendByte(Data);
// Process messages each 100 bytes
if (i div 100) = 0 then Application.ProcessMessages();
end;
finally
lStream.Free;
end;
end;
procedure TformSerial.ClientReceiveFile();
var
ShortStr: shortstring;
Data, StrLen: Byte;
i: Integer;
lStream: TFileStream;
lSize: Int64;
filePath: string;
begin
StatusBar.SimpleText := 'Receiving file';
Application.ProcessMessages;
// Read the file name:
Data := ser.RecvByte(5000);
// Process any remaining connect messages
while (Data = BYTE_REQUEST_CONNECTION) do
Data := ser.RecvByte(5000);
if (Data <> BYTE_FILE_NAME) then raise Exception.Create('Expected record BYTE_FILE_SIZE, but received: ' + IntToStr(Data));
StrLen := ser.RecvByte(5000);
ShortStr := '';
for i := 1 to StrLen do
ShortStr := ShortStr + Char(ser.RecvByte(1000));
editReceivedFileName.Text := ShortStr;
// Read the file data:
Data := ser.RecvByte(5000);
if (Data <> BYTE_FILE_DATA) then raise Exception.Create('Expected record BYTE_FILE_DATA, but received: ' + IntToStr(Data));
filePath := IncludeTrailingPathDelimiter(editFileName.Text) + editReceivedFileName.Text;
lStream := TFileStream.Create(filePath, fmOpenWrite or fmCreate);
try
ser.RecvBuffer(@lSize, 8);
for i := 0 to lSize - 1 do
begin
Data := ser.RecvByte(1000);
lStream.WriteByte(Data);
// Process messages each 100 bytes
if (i div 100) = 0 then Application.ProcessMessages();
end;
finally
lStream.Free;
end;
end;
end.
|
unit TestuProtoBufParserClasses;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
System.Classes,
System.Generics.Collections,
uProtoBufParserClasses,
uProtoBufParserAbstractClasses;
type
//anchestor class:
TestTAbstractProtoBufParserItem = class(TTestCase)
strict protected
FLastiPos: Integer;
public
procedure CallParseFromProto(const Proto: string; AParserItem: TAbstractProtoBufParserItem);
property LastiPos: Integer read FLastiPos;
end;
// Test methods for class TProtoBufPropOption
TestTProtoBufPropOption = class(TTestCase)
strict private
FProtoBufPropOption: TProtoBufPropOption;
public
procedure SetUp; override;
procedure TearDown; override;
end;
// Test methods for class TProtoBufPropOptions
TestTProtoBufPropOptions = class(TTestCase)
strict private
FProtoBufPropOptions: TProtoBufPropOptions;
public
procedure SetUp; override;
procedure TearDown; override;
end;
// Test methods for class TProtoBufProperty
TestTProtoBufProperty = class(TestTAbstractProtoBufParserItem)
strict private
FProtoBufProperty: TProtoBufProperty;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParseFromProto;
procedure TestCommentAfter;
end;
// Test methods for class TProtoBufEnumValue
TestTProtoBufEnumValue = class(TestTAbstractProtoBufParserItem)
strict private
FProtoBufEnumValue: TProtoBufEnumValue;
procedure ParserErrorEnumValueNameMissing;
procedure ParserErrorEnumValueEqualsMissing;
procedure ParserErrorEnumValueValueMissing;
procedure ParserErrorEnumValueTerminatorMissing;
procedure ParserErrorEnumValueStrToIntFailure;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParseFromProto;
procedure TestParseFromProtoHexValue;
procedure TestParseFromProtoErrors;
procedure TestComments;
end;
// Test methods for class TProtoBufEnum
TestTProtoBufEnum = class(TTestCase)
strict private
FProtoBufEnum: TProtoBufEnum;
FLastiPos: Integer;
procedure ParserErrorOptionNameMissing;
procedure ParserErrorOptionEqualsMissing;
procedure ParserErrorOptionValueMissing;
procedure ParserErrorOptionTerminatorMissing;
procedure ParserErrorOptionUnknownOptionName;
private
procedure CallParseFromProto(const AProto: string);
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParseFromProto;
procedure TestEnumAliasOption;
procedure TestEnumAliasOptionParserErrors;
procedure TestParseWithHexadecimals;
procedure TestComments;
end;
// Test methods for class TProtoBufOne
TestTProtoBufOneOf = class(TestTAbstractProtoBufParserItem)
strict private
FProtoBufProperty: TProtoBufProperty;
procedure ParserErrorNameMissing;
procedure ParserErrorOpenBracketMissing;
procedure ParserErrorUnexpectedFieldNumber;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParseFromProto;
end;
// Test methods for class TProtoBufMessage
TestTProtoBufMessage = class(TTestCase)
strict private
FProtoBufMessage: TProtoBufMessage;
FLastiPos: Integer;
private
procedure CallParseFromProto(const AProto: string);
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParseFromProto;
procedure TestMessageComments;
procedure TestOneOfComments;
end;
// Test methods for class TProtoFile
TestTProtoFile = class(TTestCase)
strict private
FProtoFile: TProtoFile;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParseFromProto;
procedure TestParseFromProto1;
procedure TestNestedEnum;
procedure TestParseSyntaxReservedWord;
end;
implementation
uses
System.SysUtils;
{ TestTAbstractProtoBufParserItem }
procedure TestTAbstractProtoBufParserItem.CallParseFromProto(
const Proto: string; AParserItem: TAbstractProtoBufParserItem);
begin
FLastiPos:= 1;
AParserItem.ParseFromProto(Proto, FLastiPos);
end;
procedure TestTProtoBufPropOption.SetUp;
begin
FProtoBufPropOption := TProtoBufPropOption.Create(nil);
end;
procedure TestTProtoBufPropOption.TearDown;
begin
FProtoBufPropOption.Free;
FProtoBufPropOption := nil;
end;
procedure TestTProtoBufPropOptions.SetUp;
begin
FProtoBufPropOptions := TProtoBufPropOptions.Create(nil);
end;
procedure TestTProtoBufPropOptions.TearDown;
begin
FProtoBufPropOptions.Free;
FProtoBufPropOptions := nil;
end;
procedure TestTProtoBufProperty.SetUp;
begin
FProtoBufProperty := TProtoBufProperty.Create(nil);
end;
procedure TestTProtoBufProperty.TearDown;
begin
FProtoBufProperty.Free;
FProtoBufProperty := nil;
end;
procedure TestTProtoBufProperty.TestCommentAfter;
begin
CallParseFromProto('int32 Field = 1; //with comment', FProtoBufProperty);
CheckTrue(ptDefaultOptional = FProtoBufProperty.PropKind);
CheckEquals('int32', FProtoBufProperty.PropType);
CheckEquals('Field', FProtoBufProperty.Name);
CheckEquals(1, FProtoBufProperty.PropFieldNum);
CheckEquals(0, FProtoBufProperty.PropOptions.Count);
CheckEquals('with comment', FProtoBufProperty.Comments.Text);
CallParseFromProto('int32 Field = 1; //one comment'#13#10'//this is for the next one', FProtoBufProperty);
CheckTrue(ptDefaultOptional = FProtoBufProperty.PropKind);
CheckEquals('int32', FProtoBufProperty.PropType);
CheckEquals('Field', FProtoBufProperty.Name);
CheckEquals(1, FProtoBufProperty.PropFieldNum);
CheckEquals(0, FProtoBufProperty.PropOptions.Count);
CheckEquals('one comment', FProtoBufProperty.Comments.Text);
end;
procedure TestTProtoBufProperty.TestParseFromProto;
begin
CallParseFromProto('int32 DefField1 = 1;', FProtoBufProperty);
CheckTrue(ptDefaultOptional = FProtoBufProperty.PropKind);
CheckEquals('int32', FProtoBufProperty.PropType);
CheckEquals('DefField1', FProtoBufProperty.Name);
CheckEquals(1, FProtoBufProperty.PropFieldNum);
CheckEquals(0, FProtoBufProperty.PropOptions.Count);
CheckEquals('', FProtoBufProperty.Comments.Text);
CallParseFromProto('int32 DefField1=1;', FProtoBufProperty);
CheckTrue(ptDefaultOptional = FProtoBufProperty.PropKind);
CheckEquals('int32', FProtoBufProperty.PropType);
CheckEquals('DefField1', FProtoBufProperty.Name);
CheckEquals(1, FProtoBufProperty.PropFieldNum);
CheckEquals(0, FProtoBufProperty.PropOptions.Count);
CheckEquals('', FProtoBufProperty.Comments.Text);
CallParseFromProto('optional int32 DefField1 = 1 [default = Val2, packed = true ]; // def field 1, default value 2', FProtoBufProperty);
CheckTrue(ptOptional = FProtoBufProperty.PropKind);
CheckEquals('int32', FProtoBufProperty.PropType);
CheckEquals('DefField1', FProtoBufProperty.Name);
CheckEquals(1, FProtoBufProperty.PropFieldNum);
CheckEquals(2, FProtoBufProperty.PropOptions.Count);
CheckEquals('default', FProtoBufProperty.PropOptions[0].Name);
CheckEquals('Val2', FProtoBufProperty.PropOptions[0].OptionValue);
CheckEquals('packed', FProtoBufProperty.PropOptions[1].Name);
CheckEquals('true', FProtoBufProperty.PropOptions[1].OptionValue);
CheckEquals('def field 1, default value 2', FProtoBufProperty.Comments.Text);
CallParseFromProto('optional int32 DefField1 = 1 [default = Val2, packed = "true"" value"""'#13#10' ]; // def field 1, default value 2', FProtoBufProperty);
CheckTrue(ptOptional = FProtoBufProperty.PropKind);
CheckEquals('int32', FProtoBufProperty.PropType);
CheckEquals('DefField1', FProtoBufProperty.Name);
CheckEquals(1, FProtoBufProperty.PropFieldNum);
CheckEquals(2, FProtoBufProperty.PropOptions.Count);
CheckEquals('default', FProtoBufProperty.PropOptions[0].Name);
CheckEquals('Val2', FProtoBufProperty.PropOptions[0].OptionValue);
CheckEquals('packed', FProtoBufProperty.PropOptions[1].Name);
CheckEquals('"true"" value"""', FProtoBufProperty.PropOptions[1].OptionValue);
CheckEquals('def field 1, default value 2', FProtoBufProperty.Comments.Text);
CallParseFromProto('required int32 DefField1 = 1 [default = Val2, packed = "true value" ]; // def field 1, default value 2', FProtoBufProperty);
CheckTrue(ptRequired = FProtoBufProperty.PropKind);
CheckEquals('int32', FProtoBufProperty.PropType);
CheckEquals('DefField1', FProtoBufProperty.Name);
CheckEquals(1, FProtoBufProperty.PropFieldNum);
CheckEquals(2, FProtoBufProperty.PropOptions.Count);
CheckEquals('default', FProtoBufProperty.PropOptions[0].Name);
CheckEquals('Val2', FProtoBufProperty.PropOptions[0].OptionValue);
CheckEquals('packed', FProtoBufProperty.PropOptions[1].Name);
CheckEquals('"true value"', FProtoBufProperty.PropOptions[1].OptionValue);
CheckEquals('def field 1, default value 2', FProtoBufProperty.Comments.Text);
CallParseFromProto('repeated string DefField1 = 1 [default = "Va""l2" , packed = true ]; // def field 1, default value 2', FProtoBufProperty);
CheckTrue(ptRepeated = FProtoBufProperty.PropKind);
CheckEquals('string', FProtoBufProperty.PropType);
CheckEquals('DefField1', FProtoBufProperty.Name);
CheckEquals(1, FProtoBufProperty.PropFieldNum);
CheckEquals(2, FProtoBufProperty.PropOptions.Count);
CheckEquals('default', FProtoBufProperty.PropOptions[0].Name);
CheckEquals('"Va""l2"', FProtoBufProperty.PropOptions[0].OptionValue);
CheckEquals('packed', FProtoBufProperty.PropOptions[1].Name);
CheckEquals('true', FProtoBufProperty.PropOptions[1].OptionValue);
CheckEquals('def field 1, default value 2', FProtoBufProperty.Comments.Text);
end;
procedure TestTProtoBufEnumValue.ParserErrorEnumValueEqualsMissing;
begin
CallParseFromProto('Enum1 1;', FProtoBufEnumValue);
end;
procedure TestTProtoBufEnumValue.ParserErrorEnumValueNameMissing;
begin
CallParseFromProto('= 1;', FProtoBufEnumValue);
end;
procedure TestTProtoBufEnumValue.ParserErrorEnumValueStrToIntFailure;
begin
CallParseFromProto('Enum1= ThisIsNoInteger', FProtoBufEnumValue);
end;
procedure TestTProtoBufEnumValue.ParserErrorEnumValueTerminatorMissing;
begin
CallParseFromProto('Enum1= 1', FProtoBufEnumValue);
end;
procedure TestTProtoBufEnumValue.ParserErrorEnumValueValueMissing;
begin
CallParseFromProto('Enum1= ;', FProtoBufEnumValue);
end;
procedure TestTProtoBufEnumValue.SetUp;
begin
FProtoBufEnumValue := TProtoBufEnumValue.Create(nil);
end;
procedure TestTProtoBufEnumValue.TearDown;
begin
FProtoBufEnumValue.Free;
FProtoBufEnumValue := nil;
end;
procedure TestTProtoBufEnumValue.TestComments;
begin
CallParseFromProto('Enum1 = 1;//after'#13#10'//not for us', FProtoBufEnumValue);
CheckEquals('Enum1', FProtoBufEnumValue.Name);
CheckEquals(1, FProtoBufEnumValue.Value);
CheckFalse(FProtoBufEnumValue.IsHexValue, 'HexValue recognized');
CheckEquals('after', FProtoBufEnumValue.Comments.Text);
end;
procedure TestTProtoBufEnumValue.TestParseFromProto;
begin
CallParseFromProto('Enum1 = 1;', FProtoBufEnumValue);
CheckEquals('Enum1', FProtoBufEnumValue.Name);
CheckEquals(1, FProtoBufEnumValue.Value);
CheckFalse(FProtoBufEnumValue.IsHexValue, 'HexValue recognized');
CallParseFromProto('Enum1=1;', FProtoBufEnumValue);
CheckEquals('Enum1', FProtoBufEnumValue.Name);
CheckEquals(1, FProtoBufEnumValue.Value);
CheckFalse(FProtoBufEnumValue.IsHexValue, 'HexValue recognized');
CallParseFromProto('Enum1=1 ;', FProtoBufEnumValue);
CheckEquals('Enum1', FProtoBufEnumValue.Name);
CheckEquals(1, FProtoBufEnumValue.Value);
CheckFalse(FProtoBufEnumValue.IsHexValue, 'HexValue recognized');
CallParseFromProto(' Enum1 = 1 ;', FProtoBufEnumValue);
CheckEquals('Enum1', FProtoBufEnumValue.Name);
CheckEquals(1, FProtoBufEnumValue.Value);
CheckFalse(FProtoBufEnumValue.IsHexValue, 'HexValue recognized');
end;
procedure TestTProtoBufEnumValue.TestParseFromProtoErrors;
begin
CheckException(ParserErrorEnumValueNameMissing, Exception, 'missing enum value name must cause exception');
CheckException(ParserErrorEnumValueEqualsMissing, Exception, 'missing equal sign for enum value must cause exception');
CheckException(ParserErrorEnumValueValueMissing, Exception, 'missing enum value must cause exception');
CheckException(ParserErrorEnumValueTerminatorMissing, Exception, 'missing enum value terminator must cause exception');
CheckException(ParserErrorEnumValueStrToIntFailure, Exception, 'incorrect string enum value must cause exception');
end;
procedure TestTProtoBufEnumValue.TestParseFromProtoHexValue;
begin
CallParseFromProto('Enum1 = 0x02;', FProtoBufEnumValue);
CheckEquals('Enum1', FProtoBufEnumValue.Name);
CheckEquals($02, FProtoBufEnumValue.Value);
Check(FProtoBufEnumValue.IsHexValue, 'HexValue not recognized');
CallParseFromProto('Enum1 = 0xABCD ;', FProtoBufEnumValue);
CheckEquals('Enum1', FProtoBufEnumValue.Name);
CheckEquals($ABCD, FProtoBufEnumValue.Value);
Check(FProtoBufEnumValue.IsHexValue, 'HexValue not recognized');
end;
procedure TestTProtoBufEnum.CallParseFromProto(const AProto: string);
begin
FLastiPos:= 1;
FProtoBufEnum.ParseFromProto(AProto, FLastiPos);
end;
procedure TestTProtoBufEnum.ParserErrorOptionEqualsMissing;
begin
CallParseFromProto('Enum1{'#13#10' option allow_alias; ');
end;
procedure TestTProtoBufEnum.ParserErrorOptionNameMissing;
begin
CallParseFromProto('Enum1{'#13#10' option; ');
end;
procedure TestTProtoBufEnum.ParserErrorOptionTerminatorMissing;
begin
CallParseFromProto('Enum1{'#13#10' option allow_alias = true '#13#10' newvalue = 1');
end;
procedure TestTProtoBufEnum.ParserErrorOptionUnknownOptionName;
begin
CallParseFromProto('Enum1{'#13#10' option unknown = true;');
end;
procedure TestTProtoBufEnum.ParserErrorOptionValueMissing;
begin
CallParseFromProto('Enum1{'#13#10' option allow_alias = ;');
end;
procedure TestTProtoBufEnum.SetUp;
begin
FProtoBufEnum := TProtoBufEnum.Create(nil);
end;
procedure TestTProtoBufEnum.TearDown;
begin
FProtoBufEnum.Free;
FProtoBufEnum := nil;
end;
procedure TestTProtoBufEnum.TestComments;
begin
CallParseFromProto('Enum1{Val1=1;Val2=2;}//after'#13#10'//not for us');
CheckEquals('Enum1', FProtoBufEnum.Name);
CheckEquals(2, FProtoBufEnum.Count);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('Val2', FProtoBufEnum[1].Name);
CheckEquals(2, FProtoBufEnum[1].Value);
CheckEquals('after', FProtoBufEnum.Comments.Text);
CallParseFromProto('Enum1{'#13#10'//before'#13#10'Val1=1;Val2=2;}');
CheckEquals('Enum1', FProtoBufEnum.Name);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('before', FProtoBufEnum[0].Comments.Text);
end;
procedure TestTProtoBufEnum.TestEnumAliasOption;
begin
CallParseFromProto('Enum1{'#13#10' option allow_alias = true; '#13#10' Val1 = 1 ;'#13#10' Val2= 2 ;'#13#10' }');
CheckEquals('Enum1', FProtoBufEnum.Name);
Check(FProtoBufEnum.AllowAlias, 'AllowAlias not set');
CheckEquals(2, FProtoBufEnum.Count);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('Val2', FProtoBufEnum[1].Name);
CheckEquals(2, FProtoBufEnum[1].Value);
CallParseFromProto('Enum1{'#13#10' option allow_alias = false; '#13#10' Val1 = 1 ;'#13#10' Val2= 2 ;'#13#10' }');
CheckEquals('Enum1', FProtoBufEnum.Name);
Check(not FProtoBufEnum.AllowAlias, 'AllowAlias must be false');
CheckEquals(2, FProtoBufEnum.Count);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('Val2', FProtoBufEnum[1].Name);
CheckEquals(2, FProtoBufEnum[1].Value);
end;
procedure TestTProtoBufEnum.TestEnumAliasOptionParserErrors;
begin
CheckException(ParserErrorOptionNameMissing, Exception, 'missing option name must cause exception');
CheckException(ParserErrorOptionEqualsMissing, Exception, 'missing equal sign for option must cause exception');
CheckException(ParserErrorOptionValueMissing, Exception, 'missing option value must cause exception');
CheckException(ParserErrorOptionTerminatorMissing, Exception, 'missing option terminator must cause exception');
CheckException(ParserErrorOptionUnknownOptionName, Exception, 'unsupported option name must cause exception');
end;
procedure TestTProtoBufEnum.TestParseFromProto;
begin
CallParseFromProto('Enum1{Val1=1;Val2=2;}');
CheckEquals('Enum1', FProtoBufEnum.Name);
CheckEquals(2, FProtoBufEnum.Count);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('Val2', FProtoBufEnum[1].Name);
CheckEquals(2, FProtoBufEnum[1].Value);
CallParseFromProto('Enum1 {Val1=1;Val2=2;}');
CheckEquals('Enum1', FProtoBufEnum.Name);
CheckEquals(2, FProtoBufEnum.Count);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('Val2', FProtoBufEnum[1].Name);
CheckEquals(2, FProtoBufEnum[1].Value);
CallParseFromProto('Enum1 { Val1=1;Val2=2;}');
CheckEquals('Enum1', FProtoBufEnum.Name);
CheckEquals(2, FProtoBufEnum.Count);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('Val2', FProtoBufEnum[1].Name);
CheckEquals(2, FProtoBufEnum[1].Value);
CallParseFromProto('Enum1{Val1 = 1 ; Val2= 2 ; }');
CheckEquals('Enum1', FProtoBufEnum.Name);
CheckEquals(2, FProtoBufEnum.Count);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('Val2', FProtoBufEnum[1].Name);
CheckEquals(2, FProtoBufEnum[1].Value);
CallParseFromProto('Enum1{'#13#10' Val1 = 1 ;'#13#10' Val2= 2 ;'#13#10' }');
CheckEquals('Enum1', FProtoBufEnum.Name);
CheckEquals(2, FProtoBufEnum.Count);
CheckEquals('Val1', FProtoBufEnum[0].Name);
CheckEquals(1, FProtoBufEnum[0].Value);
CheckEquals('Val2', FProtoBufEnum[1].Name);
CheckEquals(2, FProtoBufEnum[1].Value);
end;
procedure TestTProtoBufEnum.TestParseWithHexadecimals;
begin
CallParseFromProto('EnumFlags{'#13#10' flag1 = 0x01; '#13#10' flagMask= 0xFFFF ;'#13#10' flag0C = 0xC0000 ;'#13#10' }');
CheckEquals('EnumFlags', FProtoBufEnum.Name);
CheckEquals(3, FProtoBufEnum.Count);
CheckEquals('flag1', FProtoBufEnum[0].Name);
CheckEquals($1, FProtoBufEnum[0].Value);
Check(FProtoBufEnum[0].IsHexValue);
CheckEquals('$00000001', FProtoBufEnum.GetEnumValueString(0));
CheckEquals('flagMask', FProtoBufEnum[1].Name);
CheckEquals($FFFF, FProtoBufEnum[1].Value);
Check(FProtoBufEnum[1].IsHexValue);
CheckEquals('$0000FFFF', FProtoBufEnum.GetEnumValueString(1));
CheckEquals('flag0C', FProtoBufEnum[2].Name);
CheckEquals($C0000, FProtoBufEnum[2].Value);
Check(FProtoBufEnum[2].IsHexValue);
CheckEquals('$000C0000', FProtoBufEnum.GetEnumValueString(2));
end;
procedure TestTProtoBufMessage.CallParseFromProto(const AProto: string);
begin
FLastiPos:= 1;
FProtoBufMessage.ParseFromProto(AProto, FLastiPos);
end;
procedure TestTProtoBufMessage.SetUp;
begin
FProtoBufMessage := TProtoBufMessage.Create(nil);
end;
procedure TestTProtoBufMessage.TearDown;
begin
FProtoBufMessage.Free;
FProtoBufMessage := nil;
end;
procedure TestTProtoBufMessage.TestMessageComments;
begin
CallParseFromProto('//before'#13#10'//second'#13#10'TestMsg0 { int32 Field1 = 1;} //after'#13#10'//not for us');
CheckEquals('TestMsg0', FProtoBufMessage.Name);
CheckEquals(1, FProtoBufMessage.Count);
CheckEquals('Field1', FProtoBufMessage[0].Name);
CheckEquals('before'#13#10'second'#13#10'after', FProtoBufMessage.Comments.Text);
end;
procedure TestTProtoBufMessage.TestOneOfComments;
begin
CallParseFromProto('TestMsg0 { '#13#10'//before'#13#10'//second'#13#10'oneof Field1 {} //after'#13#10'}');
CheckEquals('TestMsg0', FProtoBufMessage.Name);
CheckEquals(1, FProtoBufMessage.Count);
CheckEquals('Field1', FProtoBufMessage[0].Name);
CheckEquals('before'#13#10'second'#13#10'after', FProtoBufMessage[0].Comments.Text);
end;
procedure TestTProtoBufMessage.TestParseFromProto;
begin
CallParseFromProto('TestMsg0 { required int32 Field1 = 1; required int64 Field2 = 2; }');
CheckEquals('TestMsg0', FProtoBufMessage.Name);
CheckEquals(2, FProtoBufMessage.Count);
CheckEquals('Field1', FProtoBufMessage[0].Name);
CheckEquals('Field2', FProtoBufMessage[1].Name);
end;
procedure TestTProtoFile.SetUp;
begin
FProtoFile := TProtoFile.Create(nil);
end;
procedure TestTProtoFile.TearDown;
begin
FProtoFile.Free;
FProtoFile := nil;
end;
procedure TestTProtoFile.TestNestedEnum;
var
Proto: string;
iPos: Integer;
begin
Proto := '// * Bytes type e.g. optional bytes DefField10 = 10 [default = "123"];'#13#10 + //
#13#10 + //
'package test1;'#13#10 + //
#13#10 + //
// 'import "TestImport1.proto";'#13#10 + //
// #13#10 + //
'// enumeration'#13#10 + //
'enum EnumG0 {'#13#10 + //
' // enum value 1'#13#10 + 'g1 = 1;'#13#10 + //
'g2 = 2;'#13#10 + //
'}'#13#10;
Proto := Proto + 'message TestMsg1 {' + #13#10 + '' + #13#10 + '// fields with defaults' + #13#10 + 'optional int32 DefField1 = 1 [default = 2];'#13#10 +
'optional int64 DefField2 = 2 [default = -1];'#13#10 + 'message NestedMsg0 { '#13#10 + ' optional int32 NestedField1 = 1; }' +
'optional string DefField3 = 3 [default = "yes it is"];'#13#10 + 'optional double DefField4 = 4 [default = 1.1];'#13#10 +
'optional bool DefField5 = 5 [default = true];'#13#10 + 'optional EnumG0 DefField6 = 6 [default = g2];'#13#10 +
'optional sint64 DefField7 = 7 [default = 100];'#13#10 + 'optional fixed32 DefField8 = 8 [default = 1];'#13#10 +
'optional float DefField9 = 9 [default = 1.23e1];'#13#10 + ''#13#10 + '// field of message type'#13#10 + 'optional NestedMsg0 FieldMsg0 = 20;'#13#10 +
''#13#10 + '// repeated fields'#13#10 + 'repeated int32 FieldArr1 = 40;'#13#10 + 'repeated int32 FieldArr2 = 41 [packed = true];'#13#10 +
'repeated string FieldArr3 = 42;'#13#10 + 'repeated Enum1 FieldArrE1 = 43;'#13#10 + 'repeated TestMsg0 FieldMArr2 = 44;'#13#10 + ''#13#10 +
'// fields of imported types'#13#10 + 'optional EnumGlobal FieldImp2 = 51;'#13#10 + ''#13#10 + '// extensions 1000 to 1999;'#13#10 + '}';
iPos := 1;
FProtoFile.ParseFromProto(Proto, iPos);
CheckEquals('test1', FProtoFile.Name);
CheckEquals(1, FProtoFile.ProtoBufEnums.Count);
CheckEquals('EnumG0', FProtoFile.ProtoBufEnums[0].Name);
CheckEquals(2, FProtoFile.ProtoBufMessages.Count);
CheckEquals('NestedMsg0', FProtoFile.ProtoBufMessages[0].Name);
CheckEquals(1, FProtoFile.ProtoBufMessages[0].Count);
CheckEquals('TestMsg1', FProtoFile.ProtoBufMessages[1].Name);
CheckEquals(16, FProtoFile.ProtoBufMessages[1].Count);
// all others check tested in TestuProtoBufParserClasses.pas
end;
procedure TestTProtoFile.TestParseFromProto;
var
Proto: string;
iPos: Integer;
begin
Proto := '// * Bytes type e.g. optional bytes DefField10 = 10 [default = "123"];'#13#10 + //
#13#10 + //
'package test1;'#13#10 + //
#13#10 + //
// 'import "TestImport1.proto";'#13#10 + //
// #13#10 + //
'// enumeration'#13#10 + //
'enum EnumG0 {'#13#10 + //
' // enum value 1'#13#10 + 'g1 = 1;'#13#10 + //
'g2 = 2;'#13#10 + //
'};';
iPos := 1;
FProtoFile.FileName := ChangeFileExt(ParamStr(0), '.proto');
FProtoFile.ParseFromProto(Proto, iPos);
CheckEquals('test1', FProtoFile.Name);
CheckEquals(1, FProtoFile.ProtoBufEnums.Count);
CheckEquals('EnumG0', FProtoFile.ProtoBufEnums[0].Name);
end;
procedure TestTProtoFile.TestParseFromProto1;
var
Proto: string;
iPos: Integer;
begin
Proto := '// * Bytes type e.g. optional bytes DefField10 = 10 [default = "123"];'#13#10 + //
#13#10 + //
'package test1;'#13#10 + //
#13#10 + //
// 'import "TestImport1.proto";'#13#10 + //
// #13#10 + //
'// enumeration'#13#10 + //
'enum EnumG0 {'#13#10 + //
' // enum value 1'#13#10 + 'g1 = 1;'#13#10 + //
'g2 = 2;'#13#10 + //
'}'#13#10;
Proto := Proto + 'message TestMsg1 {' + #13#10 + '' + #13#10 + '// fields with defaults' + #13#10 + 'optional int32 DefField1 = 1 [default = 2];' + #13#10
+ 'optional int64 DefField2 = 2 [default = -1];' + #13#10 + 'optional string DefField3 = 3 [default = "yes it is"];' + #13#10 +
'optional double DefField4 = 4 [default = 1.1];' + #13#10 + 'optional bool DefField5 = 5 [default = true];' + #13#10 +
'optional EnumG0 DefField6 = 6 [default = g2];' + #13#10 + 'optional sint64 DefField7 = 7 [default = 100];' + #13#10 +
'optional fixed32 DefField8 = 8 [default = 1];' + #13#10 + 'optional float DefField9 = 9 [default = 1.23e1];' + #13#10 + '' + #13#10 +
'// field of message type' + #13#10 + 'optional TestMsg0 FieldMsg1 = 20;' + #13#10 + '' + #13#10 + '// repeated fields' + #13#10 +
'repeated int32 FieldArr1 = 40;' + #13#10 + 'repeated int32 FieldArr2 = 41 [packed = true];' + #13#10 + 'repeated string FieldArr3 = 42;' +
#13#10 + 'repeated Enum1 FieldArrE1 = 43;' + #13#10 + 'repeated TestMsg0 FieldMArr2 = 44;' + #13#10 + '' + #13#10 + '// fields of imported types' +
#13#10 + 'optional EnumGlobal FieldImp2 = 51;' + #13#10 + '' + #13#10 + '// extensions 1000 to 1999;' + #13#10 + '}';
iPos := 1;
FProtoFile.ParseFromProto(Proto, iPos);
CheckEquals('test1', FProtoFile.Name);
CheckEquals(1, FProtoFile.ProtoBufEnums.Count);
CheckEquals('EnumG0', FProtoFile.ProtoBufEnums[0].Name);
CheckEquals(1, FProtoFile.ProtoBufMessages.Count);
CheckEquals('TestMsg1', FProtoFile.ProtoBufMessages[0].Name);
CheckEquals(16, FProtoFile.ProtoBufMessages[0].Count);
end;
procedure TestTProtoFile.TestParseSyntaxReservedWord;
var
Proto: string;
iPos: Integer;
begin
Proto := 'syntax = "proto3";'#13#10 + //
' // * Bytes type e.g. optional bytes DefField10 = 10 [default = "123"];'#13#10 + //
#13#10 + //
'package test1;'#13#10 + //
#13#10 + //
'// enumeration'#13#10 + //
'enum EnumG0 {'#13#10 + //
' // enum value 1'#13#10 + //
'g1 = 1;'#13#10 + //
'g2 = 2;'#13#10 + //
'}';
iPos := 1;
FProtoFile.ParseFromProto(Proto, iPos);
CheckTrue(FProtoFile.ProtoSyntaxVersion = psv3);
CheckEquals('test1', FProtoFile.Name);
CheckEquals(1, FProtoFile.ProtoBufEnums.Count);
CheckEquals('EnumG0', FProtoFile.ProtoBufEnums[0].Name);
CheckEquals(0, FProtoFile.ProtoBufMessages.Count);
// all others check tested in another tests in TestuProtoBufParserClasses.pas
end;
{ TestTProtoBufOneOf }
procedure TestTProtoBufOneOf.ParserErrorNameMissing;
begin
CallParseFromProto('oneof { }', FProtoBufProperty);
end;
procedure TestTProtoBufOneOf.ParserErrorOpenBracketMissing;
begin
CallParseFromProto('oneof field_oneof', FProtoBufProperty);
end;
procedure TestTProtoBufOneOf.ParserErrorUnexpectedFieldNumber;
begin
CallParseFromProto('oneof field_oneof = 25 { }', FProtoBufProperty);
end;
procedure TestTProtoBufOneOf.SetUp;
begin
inherited;
FProtoBufProperty := TProtoBufProperty.Create(nil);
end;
procedure TestTProtoBufOneOf.TearDown;
begin
inherited;
FProtoBufProperty.Free;
FProtoBufProperty := nil;
end;
procedure TestTProtoBufOneOf.TestParseFromProto;
begin
CallParseFromProto('oneof field_oneof {', FProtoBufProperty);
CheckTrue(ptOneOf = FProtoBufProperty.PropKind);
CheckEquals('field_oneof', FProtoBufProperty.PropType);
CheckEquals('field_oneof', FProtoBufProperty.Name);
CheckEquals(0, FProtoBufProperty.PropFieldNum); //oneof has no num!
CheckEquals(0, FProtoBufProperty.PropOptions.Count);
CheckException(ParserErrorNameMissing, Exception, 'ParserErrorNameMissing did not raise Exception');
CheckException(ParserErrorOpenBracketMissing, Exception, 'ParserErrorOpenBracketMissing did not raise Exception');
CheckException(ParserErrorUnexpectedFieldNumber, Exception, 'ParserErrorUnexpectedFieldNumber did not raise Exception');
end;
initialization
RegisterTest('Parser', TestTProtoBufPropOption.Suite);
RegisterTest('Parser', TestTProtoBufPropOptions.Suite);
RegisterTest('Parser', TestTProtoBufProperty.Suite);
RegisterTest('Parser', TestTProtoBufOneOf.Suite);
RegisterTest('Parser', TestTProtoBufEnumValue.Suite);
RegisterTest('Parser', TestTProtoBufEnum.Suite);
RegisterTest('Parser', TestTProtoBufMessage.Suite);
RegisterTest('Parser', TestTProtoFile.Suite);
end.
|
unit UIWrapper_StageEditorUnit;
interface
uses
FMX.Layouts, FMX.Types, Frame_SchOpt_StageInfo, StageOptionPart,
UIWrapper_LogSearchUnit, DBManager, SearchOption_Intf;
type
TUIWrapper_StageEditor = class(TObject)
private
FScrollBox_StageList: TScrollBox;
FLogSearch: TUIWrapper_LogSearch;
protected
procedure StageRelocation(Sender: TObject);
procedure StageAdding(Sender: TObject);
public
constructor Create( stageList: TScrollBox; logSearch: TUIWrapper_LogSearch );
procedure Add;
procedure Remove( stage: TFmxObject );
procedure Delete(index: Integer);
procedure DeleteLast;
function GetStageInfo(index: Integer): TFrame_SchOpt_StageInfo;
function GetStageOption(index: Integer): TStageOptionPart;
//function GetStageOptionList: TStageOptionList;
procedure SetEnabled(val: Boolean);
function Count: Integer;
procedure SetDBManager(dbm: TAbsDBManager);
procedure AddLogData(logData: ILogData);
end;
implementation
uses
FMX.Edit, System.SysUtils;
{ TEvent_SchOpt_StageEditor }
procedure TUIWrapper_StageEditor.Add;
var
frameStage: TFrame_SchOpt_StageInfo;
iCount: Integer;
begin
frameStage := TFrame_SchOpt_StageInfo.Create( FScrollBox_StageList );
iCount := self.Count; //Default 2
frameStage.Position.X := FRAME_STAGEINFO_PADDING;
frameStage.Position.Y := FRAME_STAGEINFO_PADDING +
( ( FRAME_STAGEINFO_HEIGHT + FRAME_STAGEINFO_PADDING ) * iCount );
frameStage.Opacity := 0.5;
frameStage.OnRemove := StageRelocation;
frameStage.OnInsertLogData := StageAdding;
FScrollBox_StageList.AddObject( frameStage );
end;
procedure TUIWrapper_StageEditor.AddLogData(logData: ILogData);
var
i: Integer;
stageInfo: TFrame_SchOpt_StageInfo;
begin
for i := 1 to Count + 1 do
begin
stageInfo := GetStageInfo( i );
if stageInfo.IsStartEmpty = true then
begin
stageInfo.SetStart( logData );
StageAdding( stageInfo );
exit;
end
else if stageInfo.IsEndEmpty = true then
begin
stageInfo.SetEnd( logData );
StageAdding( stageInfo );
exit;
end;
end;
end;
function TUIWrapper_StageEditor.Count: Integer;
begin
result := FScrollBox_StageList.ComponentCount - 2;
end;
constructor TUIWrapper_StageEditor.Create(stageList: TScrollBox; logSearch: TUIWrapper_LogSearch);
begin
FScrollBox_StageList := stageList;
FLogSearch := logSearch;
Add;
end;
procedure TUIWrapper_StageEditor.Delete(index: Integer);
begin
FScrollBox_StageList.Components[ index ].Destroy;
end;
procedure TUIWrapper_StageEditor.DeleteLast;
begin
Delete( FScrollBox_StageList.ComponentCount - 1 );
end;
function TUIWrapper_StageEditor.GetStageInfo(
index: Integer): TFrame_SchOpt_StageInfo;
begin
result := FScrollBox_StageList.Components[ index ] as TFrame_SchOpt_StageInfo;
end;
function TUIWrapper_StageEditor.GetStageOption(index: Integer): TStageOptionPart;
var
stgOpt: TStageOptionPart;
begin
if ( FScrollBox_StageList.ComponentCount - 2 ) < index then
begin
result := nil;
end
else
begin
result := ( FScrollBox_StageList.Components[ index + 1 ] as
TFrame_SchOpt_StageInfo ).GetStageOption;
end;
end;
//function TUIWrapper_StageEditor.GetStageOptionList: TStageOptionList;
//var
// stgOptList: TStageOptionList;
// i: Integer;
//begin
// stgOptList := TStageOptionList.Create;
//
// for i := 0 to FScrollBox_StageList.ComponentCount - 3 do
// begin
// stgOptList.Add( GetStageOption( i ) );
// end;
//
// result := stgOptList;
//end;
procedure TUIWrapper_StageEditor.Remove(stage: TFmxObject);
begin
FScrollBox_StageList.RemoveObject( stage );
end;
procedure TUIWrapper_StageEditor.SetDBManager(dbm: TAbsDBManager);
begin
FLogSearch.SetDBManager( dbm );
end;
procedure TUIWrapper_StageEditor.SetEnabled(val: Boolean);
begin
FScrollBox_StageList.Enabled := val;
FLogSearch.SetEnabled( val );
end;
procedure TUIWrapper_StageEditor.StageAdding(Sender: TObject);
var
stage: TFrame_SchOpt_StageInfo;
iCount: Integer;
i: Integer;
begin
stage := Sender as TFrame_SchOpt_StageInfo;
iCount := FScrollBox_StageList.ComponentCount;
for i := 0 to iCount - 1 do
begin
if FScrollBox_StageList.Components[ i ].Equals( Sender ) = true then
begin
if i = ( iCount - 1 ) then
begin
stage.SetUse( true );
Add;
end;
end;
end;
end;
procedure TUIWrapper_StageEditor.StageRelocation(Sender: TObject);
var
i: Integer;
frameStage: TFrame_SchOpt_StageInfo;
begin
for i := 1 to FScrollBox_StageList.ComponentCount - 1 do
begin
frameStage := TFrame_SchOpt_StageInfo( FScrollBox_StageList.Components[ i ] );
frameStage.Position.X := FRAME_STAGEINFO_PADDING;
frameStage.Position.Y := FRAME_STAGEINFO_PADDING +
( FRAME_STAGEINFO_PADDING + FRAME_STAGEINFO_HEIGHT ) * ( i - 1 );
end;
end;
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2016 * }
{ *********************************************************** }
unit tfSHA512;
interface
{$I TFL.inc}
uses tfTypes;
type
PSHA512Alg = ^TSHA512Alg;
TSHA512Alg = record
private type
TData = record
Digest: TSHA512Digest;
Block: array[0..127] of Byte;
Count: UInt64; // number of bytes processed
end;
private
FVTable: Pointer;
FRefCount: Integer;
FData: TData;
procedure Compress;
public
class procedure Init(Inst: PSHA512Alg);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class procedure Update(Inst: PSHA512Alg; Data: PByte; DataSize: Cardinal);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class procedure Done(Inst: PSHA512Alg; PDigest: PSHA512Digest);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetDigestSize(Inst: PSHA512Alg): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetBlockSize(Inst: PSHA512Alg): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function Duplicate(Inst: PSHA512Alg; var DupInst: PSHA512Alg): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
type
PSHA384Alg = ^TSHA384Alg;
TSHA384Alg = record
private type
TData = record
Digest: TSHA512Digest; // !! 512 bits
Block: array[0..127] of Byte;
Count: UInt64; // number of bytes processed
end;
private
FVTable: Pointer;
FRefCount: Integer;
FData: TData;
public
class procedure Init(Inst: PSHA384Alg);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class procedure Done(Inst: PSHA384Alg; PDigest: PSHA384Digest);
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetDigestSize(Inst: PSHA384Alg): Integer;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
function GetSHA512Algorithm(var Inst: PSHA512Alg): TF_RESULT;
function GetSHA384Algorithm(var Inst: PSHA384Alg): TF_RESULT;
implementation
uses tfRecords;
const
SHA512VTable: array[0..9] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@HashAlgRelease,
@TSHA512Alg.Init,
@TSHA512Alg.Update,
@TSHA512Alg.Done,
@TSHA512Alg.Init,
@TSHA512Alg.GetDigestSize,
@TSHA512Alg.GetBlockSize,
@TSHA512Alg.Duplicate
);
const
SHA384VTable: array[0..9] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@HashAlgRelease,
@TSHA384Alg.Init,
@TSHA512Alg.Update,
@TSHA384Alg.Done,
@TSHA384Alg.Init,
@TSHA384Alg.GetDigestSize,
@TSHA512Alg.GetBlockSize,
@TSHA512Alg.Duplicate
);
function GetSHA512Algorithm(var Inst: PSHA512Alg): TF_RESULT;
var
P: PSHA512Alg;
begin
try
New(P);
P^.FVTable:= @SHA512VTable;
P^.FRefCount:= 1;
TSHA512Alg.Init(P);
if Inst <> nil then HashAlgRelease(Inst);
Inst:= P;
Result:= TF_S_OK;
except
Result:= TF_E_OUTOFMEMORY;
end;
end;
function GetSHA384Algorithm(var Inst: PSHA384Alg): TF_RESULT;
var
P: PSHA384Alg;
begin
try
New(P);
P^.FVTable:= @SHA384VTable;
P^.FRefCount:= 1;
TSHA384Alg.Init(P);
if Inst <> nil then HashAlgRelease(Inst);
Inst:= P;
Result:= TF_S_OK;
except
Result:= TF_E_OUTOFMEMORY;
end;
end;
{ TSHA512Alg }
function Swap64(Value: UInt64): UInt64;
begin
Result:= ((Value and $FF) shl 56) or ((Value and $FF00) shl 40) or
((Value and $FF0000) shl 24) or ((Value and $FF000000) shl 8) or
((Value and $FF00000000) shr 8) or ((Value and $FF0000000000) shr 24) or
((Value and $FF000000000000) shr 40) or ((Value and $FF00000000000000) shr 56);
end;
procedure TSHA512Alg.Compress;
var
a, b, c, d, e, f, g, h, t1, t2: UInt64;
W: array[0..79] of UInt64;
I: Cardinal;
begin
a:= FData.Digest[0]; b:= FData.Digest[1]; c:= FData.Digest[2]; d:= FData.Digest[3];
e:= FData.Digest[4]; f:= FData.Digest[5]; g:= FData.Digest[6]; h:= FData.Digest[7];
Move(FData.Block, W, SizeOf(FData.Block));
for I:= 0 to 15 do
W[I]:= Swap64(W[I]);
for I:= 16 to 79 do
W[I]:= (((W[I-2] shr 19) or (W[I-2] shl 45)) xor
((W[I-2] shr 61) or (W[I-2] shl 3)) xor (W[I-2] shr 6)) + W[I-7] +
(((W[I-15] shr 1) or (W[I-15] shl 63)) xor
((W[I-15] shr 8) or (W[I-15] shl 56)) xor (W[I-15] shr 7)) + W[I-16];
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$428a2f98d728ae22 + W[0];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$7137449123ef65cd + W[1];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$b5c0fbcfec4d3b2f + W[2];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$e9b5dba58189dbbc + W[3];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$3956c25bf348b538 + W[4];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$59f111f1b605d019 + W[5];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$923f82a4af194f9b + W[6];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$ab1c5ed5da6d8118 + W[7];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$d807aa98a3030242 + W[8];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$12835b0145706fbe + W[9];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$243185be4ee4b28c + W[10];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$550c7dc3d5ffb4e2 + W[11];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$72be5d74f27b896f + W[12];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$80deb1fe3b1696b1 + W[13];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$9bdc06a725c71235 + W[14];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$c19bf174cf692694 + W[15];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$e49b69c19ef14ad2 + W[16];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$efbe4786384f25e3 + W[17];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$0fc19dc68b8cd5b5 + W[18];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$240ca1cc77ac9c65 + W[19];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$2de92c6f592b0275 + W[20];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$4a7484aa6ea6e483 + W[21];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$5cb0a9dcbd41fbd4 + W[22];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$76f988da831153b5 + W[23];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$983e5152ee66dfab + W[24];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$a831c66d2db43210 + W[25];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$b00327c898fb213f + W[26];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$bf597fc7beef0ee4 + W[27];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$c6e00bf33da88fc2 + W[28];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$d5a79147930aa725 + W[29];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$06ca6351e003826f + W[30];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$142929670a0e6e70 + W[31];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$27b70a8546d22ffc + W[32];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$2e1b21385c26c926 + W[33];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$4d2c6dfc5ac42aed + W[34];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$53380d139d95b3df + W[35];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$650a73548baf63de + W[36];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$766a0abb3c77b2a8 + W[37];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$81c2c92e47edaee6 + W[38];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$92722c851482353b + W[39];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$a2bfe8a14cf10364 + W[40];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$a81a664bbc423001 + W[41];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$c24b8b70d0f89791 + W[42];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$c76c51a30654be30 + W[43];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$d192e819d6ef5218 + W[44];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$d69906245565a910 + W[45];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$f40e35855771202a + W[46];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$106aa07032bbd1b8 + W[47];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$19a4c116b8d2d0c8 + W[48];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$1e376c085141ab53 + W[49];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$2748774cdf8eeb99 + W[50];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$34b0bcb5e19b48a8 + W[51];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$391c0cb3c5c95a63 + W[52];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$4ed8aa4ae3418acb + W[53];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$5b9cca4f7763e373 + W[54];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$682e6ff3d6b2b8a3 + W[55];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$748f82ee5defb2fc + W[56];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$78a5636f43172f60 + W[57];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$84c87814a1f0ab72 + W[58];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$8cc702081a6439ec + W[59];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$90befffa23631e28 + W[60];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$a4506cebde82bde9 + W[61];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$bef9a3f7b2c67915 + W[62];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$c67178f2e372532b + W[63];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$ca273eceea26619c + W[64];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$d186b8c721c0c207 + W[65];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$eada7dd6cde0eb1e + W[66];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$f57d4f7fee6ed178 + W[67];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$06f067aa72176fba + W[68];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$0a637dc5a2c898a6 + W[69];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$113f9804bef90dae + W[70];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$1b710b35131c471b + W[71];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
t1:= h + (((e shr 14) or (e shl 50)) xor ((e shr 18) or (e shl 46)) xor
((e shr 41) or (e shl 23))) + ((e and f) xor (not e and g)) +
$28db77f523047d84 + W[72];
t2:= (((a shr 28) or (a shl 36)) xor ((a shr 34) or (a shl 30)) xor
((a shr 39) or (a shl 25))) + ((a and b) xor (a and c) xor (b and c));
d:= d + t1;
h:= t1 + t2;
t1:= g + (((d shr 14) or (d shl 50)) xor ((d shr 18) or (d shl 46)) xor
((d shr 41) or (d shl 23))) + ((d and e) xor (not d and f)) +
$32caab7b40c72493 + W[73];
t2:= (((h shr 28) or (h shl 36)) xor ((h shr 34) or (h shl 30)) xor
((h shr 39) or (h shl 25))) + ((h and a) xor (h and b) xor (a and b));
c:= c + t1;
g:= t1 + t2;
t1:= f + (((c shr 14) or (c shl 50)) xor ((c shr 18) or (c shl 46)) xor
((c shr 41) or (c shl 23))) + ((c and d) xor (not c and e)) +
$3c9ebe0a15c9bebc + W[74];
t2:= (((g shr 28) or (g shl 36)) xor ((g shr 34) or (g shl 30)) xor
((g shr 39) or (g shl 25))) + ((g and h) xor (g and a) xor (h and a));
b:= b + t1;
f:= t1 + t2;
t1:= e + (((b shr 14) or (b shl 50)) xor ((b shr 18) or (b shl 46)) xor
((b shr 41) or (b shl 23))) + ((b and c) xor (not b and d)) +
$431d67c49c100d4c + W[75];
t2:= (((f shr 28) or (f shl 36)) xor ((f shr 34) or (f shl 30)) xor
((f shr 39) or (f shl 25))) + ((f and g) xor (f and h) xor (g and h));
a:= a + t1;
e:= t1 + t2;
t1:= d + (((a shr 14) or (a shl 50)) xor ((a shr 18) or (a shl 46)) xor
((a shr 41) or (a shl 23))) + ((a and b) xor (not a and c)) +
$4cc5d4becb3e42b6 + W[76];
t2:= (((e shr 28) or (e shl 36)) xor ((e shr 34) or (e shl 30)) xor
((e shr 39) or (e shl 25))) + ((e and f) xor (e and g) xor (f and g));
h:= h + t1;
d:= t1 + t2;
t1:= c + (((h shr 14) or (h shl 50)) xor ((h shr 18) or (h shl 46)) xor
((h shr 41) or (h shl 23))) + ((h and a) xor (not h and b)) +
$597f299cfc657e2a + W[77];
t2:= (((d shr 28) or (d shl 36)) xor ((d shr 34) or (d shl 30)) xor
((d shr 39) or (d shl 25))) + ((d and e) xor (d and f) xor (e and f));
g:= g + t1;
c:= t1 + t2;
t1:= b + (((g shr 14) or (g shl 50)) xor ((g shr 18) or (g shl 46)) xor
((g shr 41) or (g shl 23))) + ((g and h) xor (not g and a)) +
$5fcb6fab3ad6faec + W[78];
t2:= (((c shr 28) or (c shl 36)) xor ((c shr 34) or (c shl 30)) xor
((c shr 39) or (c shl 25))) + ((c and d) xor (c and e) xor (d and e));
f:= f + t1;
b:= t1 + t2;
t1:= a + (((f shr 14) or (f shl 50)) xor ((f shr 18) or (f shl 46)) xor
((f shr 41) or (f shl 23))) + ((f and g) xor (not f and h)) +
$6c44198c4a475817 + W[79];
t2:= (((b shr 28) or (b shl 36)) xor ((b shr 34) or (b shl 30)) xor
((b shr 39) or (b shl 25))) + ((b and c) xor (b and d) xor (c and d));
e:= e + t1;
a:= t1 + t2;
FData.Digest[0]:= FData.Digest[0] + a;
FData.Digest[1]:= FData.Digest[1] + b;
FData.Digest[2]:= FData.Digest[2] + c;
FData.Digest[3]:= FData.Digest[3] + d;
FData.Digest[4]:= FData.Digest[4] + e;
FData.Digest[5]:= FData.Digest[5] + f;
FData.Digest[6]:= FData.Digest[6] + g;
FData.Digest[7]:= FData.Digest[7] + h;
FillChar(W, SizeOf(W), 0);
FillChar(FData.Block, SizeOf(FData.Block), 0);
end;
class procedure TSHA512Alg.Init(Inst: PSHA512Alg);
begin
Inst.FData.Digest[0]:= $6a09e667f3bcc908;
Inst.FData.Digest[1]:= $bb67ae8584caa73b;
Inst.FData.Digest[2]:= $3c6ef372fe94f82b;
Inst.FData.Digest[3]:= $a54ff53a5f1d36f1;
Inst.FData.Digest[4]:= $510e527fade682d1;
Inst.FData.Digest[5]:= $9b05688c2b3e6c1f;
Inst.FData.Digest[6]:= $1f83d9abfb41bd6b;
Inst.FData.Digest[7]:= $5be0cd19137e2179;
FillChar(Inst.FData.Block, SizeOf(Inst.FData.Block), 0);
Inst.FData.Count:= 0;
end;
class procedure TSHA512Alg.Update(Inst: PSHA512Alg; Data: PByte; DataSize: Cardinal);
var
Cnt, Ofs: Cardinal;
begin
while DataSize > 0 do begin
Ofs:= Cardinal(Inst.FData.Count) and $7F;
Cnt:= $80 - Ofs;
if Cnt > DataSize then Cnt:= DataSize;
Move(Data^, PByte(@Inst.FData.Block)[Ofs], Cnt);
if (Cnt + Ofs = $80) then Inst.Compress;
Inc(Inst.FData.Count, Cnt);
Dec(DataSize, Cnt);
Inc(Data, Cnt);
end;
end;
class procedure TSHA512Alg.Done(Inst: PSHA512Alg; PDigest: PSHA512Digest);
var
Ofs: Cardinal;
begin
Ofs:= Cardinal(Inst.FData.Count) and $7F;
Inst.FData.Block[Ofs]:= $80;
if Ofs >= 112 then
Inst.Compress;
Inst.FData.Count:= Inst.FData.Count shl 3;
PUInt64(@Inst.FData.Block[112])^:= 0;
PUInt64(@Inst.FData.Block[120])^:= Swap64(Inst.FData.Count);
Inst.Compress;
Inst.FData.Digest[0]:= Swap64(Inst.FData.Digest[0]);
Inst.FData.Digest[1]:= Swap64(Inst.FData.Digest[1]);
Inst.FData.Digest[2]:= Swap64(Inst.FData.Digest[2]);
Inst.FData.Digest[3]:= Swap64(Inst.FData.Digest[3]);
Inst.FData.Digest[4]:= Swap64(Inst.FData.Digest[4]);
Inst.FData.Digest[5]:= Swap64(Inst.FData.Digest[5]);
Inst.FData.Digest[6]:= Swap64(Inst.FData.Digest[6]);
Inst.FData.Digest[7]:= Swap64(Inst.FData.Digest[7]);
Move(Inst.FData.Digest, PDigest^, SizeOf(TSHA512Digest));
Init(Inst);
end;
class function TSHA512Alg.GetBlockSize(Inst: PSHA512Alg): Integer;
begin
Result:= 128;
end;
class function TSHA512Alg.GetDigestSize(Inst: PSHA512Alg): Integer;
begin
Result:= SizeOf(TSHA512Digest);
end;
class function TSHA512Alg.Duplicate(Inst: PSHA512Alg;
var DupInst: PSHA512Alg): TF_RESULT;
begin
Result:= GetSHA512Algorithm(DupInst);
if Result = TF_S_OK then
DupInst.FData:= Inst.FData;
end;
{ TSHA384Alg }
class procedure TSHA384Alg.Done(Inst: PSHA384Alg; PDigest: PSHA384Digest);
var
Ofs: Cardinal;
begin
Ofs:= Cardinal(Inst.FData.Count) and $7F;
Inst.FData.Block[Ofs]:= $80;
if Ofs >= 112 then
PSHA512Alg(Inst).Compress;
Inst.FData.Count:= Inst.FData.Count shl 3;
PUInt64(@Inst.FData.Block[112])^:= 0;
PUInt64(@Inst.FData.Block[120])^:= Swap64(Inst.FData.Count);
PSHA512Alg(Inst).Compress;
Inst.FData.Digest[0]:= Swap64(Inst.FData.Digest[0]);
Inst.FData.Digest[1]:= Swap64(Inst.FData.Digest[1]);
Inst.FData.Digest[2]:= Swap64(Inst.FData.Digest[2]);
Inst.FData.Digest[3]:= Swap64(Inst.FData.Digest[3]);
Inst.FData.Digest[4]:= Swap64(Inst.FData.Digest[4]);
Inst.FData.Digest[5]:= Swap64(Inst.FData.Digest[5]);
Move(Inst.FData.Digest, PDigest^, SizeOf(TSHA384Digest));
Init(Inst);
end;
class function TSHA384Alg.GetDigestSize(Inst: PSHA384Alg): Integer;
begin
Result:= SizeOf(TSHA384Digest);
end;
class procedure TSHA384Alg.Init(Inst: PSHA384Alg);
begin
Inst.FData.Digest[0]:= $cbbb9d5dc1059ed8;
Inst.FData.Digest[1]:= $629a292a367cd507;
Inst.FData.Digest[2]:= $9159015a3070dd17;
Inst.FData.Digest[3]:= $152fecd8f70e5939;
Inst.FData.Digest[4]:= $67332667ffc00b31;
Inst.FData.Digest[5]:= $8eb44a8768581511;
Inst.FData.Digest[6]:= $db0c2e0d64f98fa7;
Inst.FData.Digest[7]:= $47b5481dbefa4fa4;
FillChar(Inst.FData.Block, SizeOf(Inst.FData.Block), 0);
Inst.FData.Count:= 0;
end;
end.
|
unit CircuitsHandler;
interface
uses
Controls,
Classes,
Circuits,
VoyagerServerInterfaces;
type
TSegmentsRenderer = function (const SegmentsReport : TSegmentReport; Left, Top, Width, Height : integer) : ICircuitsRendering;
type
TOnAreaRefreshedNotification = procedure (const Segments : TSegmentReport; const CircuitsRendering : ICircuitsRendering) of object;
type
ICircuitsHandler =
interface
procedure SetClientView(const ClientView : IClientView);
function RefreshArea(CircuitKind, x, y, dx, dy : integer; Renderer : TSegmentsRenderer; out Segments : TSegmentReport) : ICircuitsRendering;
procedure AsyncRefreshArea(CircuitKind, x, y, dx, dy : integer; Renderer : TSegmentsRenderer; OnAreaRefreshed : TOnAreaRefreshedNotification);
end;
type
TCircuitsHandler =
class( TInterfacedObject, ICircuitsHandler )
public
constructor Create;
destructor Destroy; override;
private // ICircuitsHandler
procedure SetClientView(const ClientView : IClientView);
function RefreshArea(CircuitKind, x, y, dx, dy : integer; Renderer : TSegmentsRenderer; out Segments : TSegmentReport) : ICircuitsRendering;
procedure AsyncRefreshArea(CircuitKind, x, y, dx, dy : integer; Renderer : TSegmentsRenderer; OnAreaRefreshed : TOnAreaRefreshedNotification );
private
fClientView : IClientView;
end;
implementation
uses
SysUtils, Protocol;
type
TAreaCircuitsRefresherThread =
class( TThread )
private
fCircuitKind : integer;
fX, fY, fDX, fDY : integer;
fClientView : IClientView;
fRenderer : TSegmentsRenderer;
fOnAreaRefreshed : TOnAreaRefreshedNotification;
public
constructor Create(CircuitKind, x, y, dx, dy : integer; ClientView : IClientView; Renderer : TSegmentsRenderer; OnAreaRefreshed : TOnAreaRefreshedNotification);
protected
procedure Execute; override;
end;
// TAreaCircuitsRefresherThread
constructor TAreaCircuitsRefresherThread.Create(CircuitKind, x, y, dx, dy : integer; ClientView : IClientView; Renderer : TSegmentsRenderer; OnAreaRefreshed : TOnAreaRefreshedNotification);
begin
inherited Create(true);
fCircuitKind := CircuitKind;
fX := x;
fY := y;
fDX := dx;
fDY := dy;
fClientView := ClientView;
fRenderer := Renderer;
fOnAreaRefreshed := OnAreaRefreshed;
Resume;
end;
procedure TAreaCircuitsRefresherThread.Execute;
var
CircuitsRendering : ICircuitsRendering;
SegmentReport : TSegmentReport;
ErrorCode : TErrorCode;
NewX : integer;
NewY : integer;
begin
if fX > 0
then NewX := fX - 1
else NewX := 0;
if fY > 0
then NewY := fY - 1
else NewY := 0;
SegmentReport := fClientView.SegmentsInArea(fCircuitKind, NewX, NewY, fDX + 2, fDY + 2, ErrorCode);
if ErrorCode = NOERROR
then
begin
//ClipSegments( SegmentReport, NewX, NewY, NewX + fDX + 1, NewY + fDY + 1 );
if assigned(fRenderer)
then CircuitsRendering := fRenderer(SegmentReport, NewX, NewY, fDX + 2, fDY + 2)
else CircuitsRendering := nil;
if assigned(fOnAreaRefreshed)
then fOnAreaRefreshed(SegmentReport, CircuitsRendering);
end
else
if assigned(fOnAreaRefreshed)
then fOnAreaRefreshed(SegmentReport, nil);
end;
// TCircuitsHandler
constructor TCircuitsHandler.Create;
begin
inherited Create;
end;
destructor TCircuitsHandler.Destroy;
begin
assert(RefCount = 0);
inherited;
end;
procedure TCircuitsHandler.SetClientView(const ClientView : IClientView);
begin
fClientView := ClientView;
end;
function TCircuitsHandler.RefreshArea(CircuitKind, x, y, dx, dy : integer; Renderer : TSegmentsRenderer; out Segments : TSegmentReport) : ICircuitsRendering;
var
ErrorCode : TErrorCode;
NewX : integer;
NewY : integer;
begin
if x > 0
then NewX := x - 1
else NewX := 0;
if Y > 0
then NewY := y - 1
else NewY := 0;
Segments := fClientView.SegmentsInArea(CircuitKind, NewX, NewY, dx + 2, dy + 2, ErrorCode);
if ErrorCode = NOERROR
then
begin
//ClipSegments(SegmentReport, NewX, NewY, NewX + dx + 1, NewY + dy + 1);
if assigned(Renderer)
then Result := Renderer(Segments, NewX, NewY, dx + 2, dy + 2)
else Result := nil;
end
else Result := nil;
end;
procedure TCircuitsHandler.AsyncRefreshArea(CircuitKind, x, y, dx, dy : integer; Renderer : TSegmentsRenderer; OnAreaRefreshed : TOnAreaRefreshedNotification);
begin
TAreaCircuitsRefresherThread.Create(CircuitKind, x, y, dx, dy, fClientView, Renderer, OnAreaRefreshed);
end;
end.
|
unit Model.ManutencaoVeiculos;
interface
type
TManutencaoVeiculos = class
private
var
FID: Integer;
FTipo: String;
FVeiculo: Integer;
FMotorista: Integer;
FItem: Integer;
FDataManuencao: System.TDate;
FKmManutencao: Double;
FDataPrevisao: System.TDate;
FKmPrevisao: Double;
FValor: Double;
FDataLiberacao: System.TDate;
FSituacao: Integer;
FObs: String;
FArquivo: String;
FCCusto: Integer;
FLog: String;
public
property ID: Integer read FID write FID;
property Tipo: String read FTipo write FTipo;
property Veiculo: Integer read FVeiculo write FVeiculo;
property Motorista: Integer read FMotorista write FMotorista;
property Item: Integer read FItem write FItem;
property DataManutencao: System.TDate read FDataManuencao write FDataManuencao;
property KMManutencao: Double read FKmManutencao write FKmManutencao;
property DataPrevisao: System.TDate read FDataPrevisao write FDataPrevisao;
property KMPrevisao: Double read FKmPrevisao write FKmPrevisao;
property Valor: Double read FValor write FValor;
property DataLiberacao: System.TDate read FDataLiberacao write FDataLiberacao;
property Situacao: Integer read FSituacao write FSituacao;
property Obs: String read FObs write FObs;
property Arquivo: String read FArquivo write FArquivo;
property CCusto: Integer read FCCusto write FCCusto;
property Log: String read FLog write FLog;
constructor Create; overload;
constructor Create(pFID: Integer; pFTipo: String; pFVeiculo: Integer; pFMotorista: Integer; pFItem: Integer;
pFDataManuencao: System.TDate; pFKmManutencao: Double; pFDataPrevisao: System.TDate; pFKmPrevisao: Double;
pFValor: Double; pFDataLiberacao: System.TDate; pFSituacao: Integer; pFObs: String; pFArquivo: String;
pFCCusto: Integer; pFLog: String); overload;
end;
implementation
constructor TManutencaoVeiculos.Create;
begin
inherited Create;
end;
constructor TManutencaoVeiculos.Create(pFID: Integer; pFTipo: String; pFVeiculo: Integer; pFMotorista: Integer; pFItem: Integer;
pFDataManuencao: System.TDate; pFKmManutencao: Double; pFDataPrevisao: System.TDate; pFKmPrevisao: Double;
pFValor: Double; pFDataLiberacao: System.TDate; pFSituacao: Integer; pFObs: String; pFArquivo: String;
pFCCusto: Integer; pFLog: String);
begin
FID := pFID;
FTipo := pFTipo;
FVeiculo := pFVeiculo;
FMotorista := pFMotorista;
FItem := pFItem;
FDataManuencao := pFDataManuencao;
FKmManutencao := pFKmManutencao;
FDataPrevisao := pFDataPrevisao;
FKmPrevisao := pFKmPrevisao;
FValor := pFValor;
FDataLiberacao := pFDataLiberacao;
FSituacao := pFSituacao;
FObs := pFObs;
FArquivo := pFArquivo;
FCCusto := pFCCusto;
FLog := pFLog;
end;
end.
|
namespace Nancy.Bootstrappers.Autofac;
uses
Autofac;
type
ComponentContextExtensions = public extension class(IComponentContext)
public
method Update(builderAction: Action<ContainerBuilder>): IComponentContext;
begin
if not assigned(self) then
begin
raise new ArgumentNullException('context');
end;
if not assigned(builderAction) then
begin
raise new ArgumentNullException('builderAction');
end;
var builder := new ContainerBuilder();
builderAction.Invoke(builder);
builder.Update(self.ComponentRegistry);
exit self;
end;
end;
end. |
unit uEditorBase;
interface
uses
uEditorIntf, Classes, SysUtils, Dialogs, Graphics;
type
// 这个类的功能主要是对要操作的文件进行控制。
TEditorBase = class(TInterfacedObject, IEditorIntf)
private
FFileName: string;
protected
procedure DoLoadFromFile(FileName: string); virtual; abstract;
function DoSaveFile(FileName: string): Boolean; virtual; abstract;
// 获取所有文本
function GetText: string; virtual; abstract;
public
procedure LoadFormFile(FileName: string);
function GetFileName: string;
function GetWordCount: TWordCount;
function GetWordWarp: Boolean; virtual; abstract; // 是否分行
procedure SetWordWarp(WordWarp: Boolean); virtual; abstract;
function CanUndo: Boolean; virtual; abstract;
procedure Undo; virtual; abstract;
function CanRedo: Boolean; virtual; abstract;
procedure Redo; virtual; abstract;
function CanCopy: Boolean; virtual; abstract;
procedure Copy; virtual; abstract;
function CanCut: Boolean; virtual; abstract;
procedure Cut; virtual; abstract;
function CanPaster: Boolean; virtual; abstract;
procedure Paster; virtual; abstract;
function CanDeleteSelection: Boolean; virtual; abstract;
procedure DelectSelection; virtual; abstract;
procedure SetFont(Font: TFont); virtual; abstract;
function FindNext(Text: String; Option: TFindOptions): Boolean; virtual; abstract;
function Replace(FindText, ReplaceText: String; Option: TFindOptions): Integer; virtual; abstract;
function Save: Boolean; virtual;
function SaveAs: Boolean; virtual;
procedure SelectAll; virtual; abstract;
// 在保存的时候判断该文件是否已修改
function GetSaved: Boolean; virtual; abstract;
function GetSelectText: String; virtual; abstract;
// 这里构建方法不属于这里,但是如果没有构建方法就不能够直接使用
// 该类直接创建 编辑器 对象。
// constructor Create(AOwner: TComponent); override;
// property FileName: string read FFileName;
end;
implementation
{ TEditorBase }
//constructor TEditorBase.Create(AOwner: TComponent);
//begin
// inherited;
//
//end;
function TEditorBase.GetFileName: string;
begin
Result := FFileName;
end;
function TEditorBase.GetWordCount: TWordCount;
var
TextStr: string;
I: Integer;
bHalf : Boolean;
nAsc: Integer;
begin
TextStr := GetText();
for I := 1 to Length(TextStr) do
begin
nAsc := ord(TextStr[I]);
if bHalf then
begin
bHalf := false;
nAsc := 0;
end;
if nAsc > 127 then
begin //chinese
if not bHalf then
Inc(Result.MultiChar);
bHalf := not bHalf;
end
else if (nAsc >= 48) and (nAsc <= 57) then
Inc(Result.NumChar)
else if (nAsc >= 65) and (nAsc <= 90) then
Inc(Result.AnsiChar)
else if (nAsc >= 97) and (nAsc <= 122) then
Inc(Result.AnsiChar)
else if (nAsc <> 32) and (nAsc <> 0) and (nAsc <> 13) and (nAsc <> 10) then
Inc(Result.Other);
end;
end;
procedure TEditorBase.LoadFormFile(FileName: string);
begin
FFileName := FileName;
if FFileName <> EmptyStr then
DoLoadFromFile(FFileName);
end;
function TEditorBase.Save: Boolean;
begin
if FFileName = EmptyStr then
begin
Result := SaveAs;
Exit;
end;
Result := DoSaveFile(FFileName);
end;
function TEditorBase.SaveAs: Boolean;
var
FSaveDlg: TSaveDialog;
begin
Result := False;
FSaveDlg := TSaveDialog.Create(nil);
try
FSaveDlg.Options := [ofOverwritePrompt, ofHideReadOnly];
if FSaveDlg.Execute() then
Result := DoSaveFile(FSaveDlg.FileName);
finally
FSaveDlg.Free;
FSaveDlg := nil;
end;
end;
end.
|
unit uAutomato;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uEStado, uParamTransicao, strutils, uConstantes, contnrs,
StdCtrls;
type
{ TAutomato }
TAutomato = class(TObject)
private
var
FPilha: TStack;
FEstadosPossiveis: TListaEstado;
FEstadoAtual: TEstado;
FMemoLogPilha: TMemo;
FCharInsere: Char;
FStrRev: string;
FTopStr: string;
FvetIns: array of string;
FVetStackShow: array of string;
procedure ConfigurarEstados;
procedure ConfigurarListaTransicoes(var pEstado: TEstado);
procedure Push(const pTrans: TParamTransicao);
procedure ProcessaTransicao(const pTransicoes: TListaParamTransicao);
function Pop: string;
function Peek: string;
function EscrevePilha: string;
function GetTransicaoInput(const pInput: string; const pEstado: TEstado): TListaParamTransicao;
public
constructor Create;
destructor Destroy;override;
function Execute(const pCadeia: String): string;
procedure IniciarPilha;
property Pilha: TStack read FPilha write FPilha;
property EstadosPossiveis: TListaEstado read FEstadosPossiveis;
property MemoLogPilha: TMemo read FMemoLogPilha write FMemoLogPilha;
end;
implementation
{ TAutomato }
procedure TAutomato.ConfigurarEstados;
var
lEstado: TEstado;
lIndex: Integer;
begin
FEstadosPossiveis.Clear;
lEstado := TEstado.Create('qe', False);
FEstadosPossiveis.Add(lEstado);
//Estado q0
lEstado := TEstado.Create('q0', False);
FEstadosPossiveis.Add(lEstado);
lEstado := TEstado.Create('q1', False);
FEstadosPossiveis.Add(lEstado);
lEstado := TEstado.Create('q2', False);
FEstadosPossiveis.Add(lEstado);
lEstado := TEstado.Create('q3', True);
FEstadosPossiveis.Add(lEstado);
for lIndex := 0 to Pred(FEStadosPossiveis.Count) do
begin
lEstado := FEstadosPossiveis.Items[lIndex];
ConfigurarListaTransicoes(lEstado);
end;
end;
procedure TAutomato.ConfigurarListaTransicoes(var pEstado: TEstado);
var
lTransicao: TParamTransicao;
begin
if pEstado <> nil then
begin
//Estado inicial
if pEstado.Id = 'q0' then
begin
lTransicao := TParamTransicao.Create('0', '', 'F', FEstadosPossiveis.ItemByID('q1'));
pEstado.ListaParamTransicoes.Add(lTransicao);
lTransicao := TParamTransicao.Create('1', '', '', FEstadosPossiveis.ItemByID('q1'));
pEstado.ListaParamTransicoes.Add(lTransicao);
end
else if pEstado.Id = 'q1' then
begin
lTransicao := TParamTransicao.Create('0', 'X', 'XX', pEstado);
pEstado.ListaParamTransicoes.Add(lTransicao);
lTransicao := TParamTransicao.Create('0', 'F', 'XF', pEstado);
pEstado.ListaParamTransicoes.Add(lTransicao);
lTransicao := TParamTransicao.Create('1', 'X', '', FEstadosPossiveis.ItemByID('q2'));
pEstado.ListaParamTransicoes.Add(lTransicao);
end
else if pEstado.Id = 'q2' then
begin
lTransicao := TParamTransicao.Create('1', 'X', '', pEstado);
pEstado.ListaParamTransicoes.Add(lTransicao);
lTransicao := TParamTransicao.Create('1', 'F', '', FEstadosPossiveis.ItemByID('q3'));
pEstado.ListaParamTransicoes.Add(lTransicao);
end
//Estado final
else if pEstado.Id = 'q3' then
begin
lTransicao := TParamTransicao.Create('1', '', '', pEstado);
pEstado.ListaParamTransicoes.Add(lTransicao);
end;
end;
end;
procedure TAutomato.Push(const pTrans: TParamTransicao);
var
lIndex: integer;
begin
if pTrans.SimboloPilhaInsere <> '' then
begin
FStrRev := ReverseString(pTrans.SimboloPilhaInsere);
for FCharInsere in FStrRev do
begin
lIndex := Length(FvetIns);
SetLength(FvetIns, lIndex + 1);
FvetIns[lIndex] := FCharInsere;
FPilha.Push(PChar(FvetIns[lIndex]));
end;
end;
end;
procedure TAutomato.ProcessaTransicao(const pTransicoes: TListaParamTransicao);
var
lIndexTran: integer;
lTrans: TParamTransicao;
begin
for lIndexTran:= 0 to pred (pTransicoes.Count) do
begin
FTopStr := Self.Peek;
lTrans := pTransicoes.Items[lIndexTran];
if (UpperCase(lTrans.SimboloPilhaCompara) = UpperCase(FTopStr)) or
(lTrans.SimboloPilhaCompara = '') then
begin
Self.Pop;
Self.Push(lTrans);
FEstadoAtual := TEstado(lTrans.Destino);
Exit;
end;
end;
end;
function TAutomato.Pop: string;
begin
Result := PChar(FPilha.Pop)^;
if FPilha.Count = 0 then
begin
FPilha.Push(PChar(STACK_GROUND));
end;
end;
function TAutomato.Peek: string;
begin
Result := PChar(FPilha.Peek)^;
end;
function TAutomato.EscrevePilha: string;
var
lIndice: integer;
begin
Result := '';
if FPilha.Count > 0 then
begin
SetLength(FVetStackShow, 0);
while FPilha.Count > 0 do
begin
lIndice := Length(FVetStackShow);
SetLength(FVetStackShow, lIndice + 1);
FVetStackShow[lIndice] := PChar(FPilha.Pop)^;
end;
for lIndice := Pred(Length(FVetStackShow)) downto 0 do
begin
FPilha.Push(PChar(FVetStackShow[lIndice]));
Result := Result + FVetStackShow[lIndice];
end;
end;
end;
function TAutomato.GetTransicaoInput(const pInput: string; const pEstado: TEstado): TListaParamTransicao;
var
lParam: TParamTransicao;
lIndex: Integer;
begin
Result := TListaParamTransicao.Create;
Result.OwnsObjects := False;
for lIndex:= 0 to Pred(pEstado.ListaParamTransicoes.count) do
begin
lParam := pEstado.ListaParamTransicoes.Items[lIndex];
if lParam.Imput = pInput then
begin
Result.Add(lParam);
end;
end;
end;
constructor TAutomato.Create;
begin
inherited Create;
FEstadosPossiveis := TListaEstado.Create;
ConfigurarEstados;
IniciarPilha;
SetLength(FvetIns, 0);
SetLength(FVetStackShow, 0);
end;
destructor TAutomato.Destroy;
begin
FPilha.Destroy;
FEstadosPossiveis.Destroy;
inherited Destroy;
end;
function TAutomato.Execute(const pCadeia: String): string;
var
lCharCadeia: Char;
lTransicoes: TListaParamTransicao;
lLogPilha: string;
begin
IniciarPilha;
FEstadoAtual := FEstadosPossiveis.ItemByID('q0');
for lCharCadeia in pCadeia do
begin
if Assigned(FMemoLogPilha) then
begin
lLogPilha := Self.EscrevePilha;
if lLogPilha <> EmptyStr then
begin
FMemoLogPilha.Lines.Add(lLogPilha);
end;
end;
if MatchStr(UnicodeString(lCharCadeia), INPUT_ALPHABET) then
begin
lTransicoes := GetTransicaoInput(lCharCadeia, FEstadoAtual);
try
if lTransicoes.Count > 0 then
begin
ProcessaTransicao(lTransicoes);
end
else
begin
FEstadoAtual := FEstadosPossiveis.ItemByID('qe');
break;
end;
finally
lTransicoes.Free;
end;
end
else
begin
FEstadoAtual := FEstadosPossiveis.ItemByID('qe');
Break;
end;
end;
if FEstadoAtual.Final then
begin
Result := 'Cadeia: ' + pCadeia + sLineBreak + 'Status: ' + 'Aceita!' + sLineBreak;
end
else
begin
Result := 'Cadeia: ' + pCadeia + sLineBreak + 'Status: ' + 'Rejeitada!' + sLineBreak;
end;
end;
procedure TAutomato.IniciarPilha;
begin
if not Assigned(FPilha) then
begin
FPilha := TStack.Create;
end
else
begin
while FPilha.Count > 0 do
begin
FPilha.Pop();
end;
end;
FPilha.Push(PChar(STACK_GROUND));
end;
end.
|
unit u_Padrao;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,
Vcl.DBCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, U_DM;
type
TfrmPadrao = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
btnNovo: TBitBtn;
btnDeletar: TBitBtn;
btnEditar: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
btnAtualizar: TBitBtn;
DBNavigator1: TDBNavigator;
btnPesquisar: TBitBtn;
qryPadrao: TFDQuery;
dsPadrao: TDataSource;
btnSair: TBitBtn;
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnNovoClick(Sender: TObject);
procedure btnDeletarClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnAtualizarClick(Sender: TObject);
procedure Tratabotoes();
procedure btnSairClick(Sender: TObject); //DESCLARANDO PROCEDURE DE TRATAMENTO DE BOTÕES
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmPadrao: TfrmPadrao;
implementation
{$R *.dfm}
procedure TfrmPadrao.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure TfrmPadrao.btnAtualizarClick(Sender: TObject);
begin
Tratabotoes;
qryPadrao.Refresh;
Messagedlg('Registro atualizado com sucesso!',mtInformation,[mbOk],0);
end;
procedure TfrmPadrao.btnCancelarClick(Sender: TObject);
begin
Tratabotoes;
qryPadrao.Cancel;
Messagedlg('Ação cancelada pelo usuário!',mtInformation,[mbOk],0);
end;
procedure TfrmPadrao.btnDeletarClick(Sender: TObject);
begin
Tratabotoes;
if messagedlg('Deseja deletar este registro?', mtConfirmation,[mbOk,mbNo],0)=mrOk then
begin
qryPadrao.Delete;
Messagedlg('Registro dletado com sucesso!',mtInformation,[mbOk],0);
Tratabotoes;
end
else
begin
Tratabotoes;
abort;
end;
end;
procedure TfrmPadrao.btnEditarClick(Sender: TObject);
begin
Tratabotoes;
if messagedlg('Deseja editar este registro?', mtConfirmation,[mbOk,mbNo],0)=mrOk then
begin
qryPadrao.edit;
end
else
begin
Tratabotoes;
abort;
end;
end;
procedure TfrmPadrao.btnGravarClick(Sender: TObject);
begin
Tratabotoes;
qryPadrao.Post;
Messagedlg('Registro salvo com sucesso!',mtInformation,[mbok],0);
end;
procedure TfrmPadrao.btnNovoClick(Sender: TObject);
begin
qryPadrao.Open;
Tratabotoes;
qryPadrao.Append;
end;
procedure TfrmPadrao.FormKeyPress(Sender: TObject; var Key: Char);
begin
//FAZ O ENTER TER A MESMA FUNÇÃO DO TAB (RECEITA DE BOLO, NÃO MUDA ESSE CODIGO)
if key=#13 then
begin
key:=#0;
Perform(wm_nextDlgCtl,0,0)
end;
end;
procedure TfrmPadrao.Tratabotoes;
begin
//HABILITA E DESABILITA BOTÕES
//SE ESTA HABILITADO DESABILITA E SE ESTA DESABILITADO HABILITA.
btnNovo.Enabled:=not btnNovo.Enabled;
btnDeletar.Enabled:=not btnDeletar.Enabled;
btnEditar.Enabled:=not btnEditar.Enabled;
btnGravar.Enabled:=not btnGravar.Enabled;
btnAtualizar.Enabled:=not btnAtualizar.Enabled;
end;
end.
|
unit adErrorBox;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OvcBase, afwControlPrim, afwBaseControl, afwControl,
afwInputControl, vtLister, StdCtrls, ExtCtrls, l3StringList, l3Interfaces;
type
TErrorBox = class(TForm)
lstErrors: TvtLister;
Image1: TImage;
txtText: TStaticText;
btnOne: TButton;
btnTwo: TButton;
procedure FormDestroy(Sender: TObject);
procedure lstErrorsGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString);
private
f_ErrorList: Tl3StringList;
f_IsYesNo: Boolean;
procedure pm_SetIsYesNo(const Value: Boolean);
{ Private declarations }
public
constructor Create(const aTitle, aText: AnsiString; const ErrList: Tl3StringList);
property IsYesNo: Boolean read f_IsYesNo write pm_SetIsYesNo;
{ Public declarations }
end;
var
ErrorBox: TErrorBox;
implementation
uses l3StringListPrim;
{$R *.dfm}
constructor TErrorBox.Create(const aTitle, aText: AnsiString; const ErrList: Tl3StringList);
begin
inherited Create(nil);
Caption := aTitle;
txtText.Caption := aText;
ErrList.SetRefTo(f_ErrorList);
if f_ErrorList <> nil then
lstErrors.Total := f_ErrorList.Count;
IsYesNo := False;
end;
procedure TErrorBox.FormDestroy(Sender: TObject);
begin
FreeAndNil(f_ErrorList);
end;
procedure TErrorBox.lstErrorsGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString);
begin
ItemString := f_ErrorList.ItemC[Index];
end;
procedure TErrorBox.pm_SetIsYesNo(const Value: Boolean);
begin
f_IsYesNo := Value;
btnOne.Visible := f_IsYesNo;
if f_IsYesNo then
btnTwo.Caption := 'Νες'
else
btnTwo.Caption := 'OK';
end;
end.
|
(**
* This unit contains a class ~TTextIniFile~ that implements
* textual initialization files. The files are fully interface
* compatible with those in the (Delphi) IniFiles unit, but they
* provide some additional methods for reading and writing data
* other than String, Integer, and Boolean.
*
* @author Joerg Pleumann <pleumann@uni-duisburg.de>
*
* @version 15-May-98
*)
unit TextInis;
{$H+,R-}
interface
uses
SysUtils, Classes, Consts;
type
(**
* The TTextIniFile class implements textual initialization
* files. The files are fully interface compatible with the ones
* in the (Delphi) IniFiles unit, but provide some additional
* methods for reading and writing data other than String,
* Integer, and Boolean. The files do not use any operating
* system stuff, so they works alike in OS/2 and Windows.
* <p>
* The files are divided into sections and identifiers, as
* usual, but there is one exception: If a file contains a
* section whose name is the empty string, it is written
* without a section heading when the file is created. This
* allows to use the class for 'flat' initialization files,
* just specify the empty string as section identifier.
* <p>
* The class does not change data that is not affected by
* a writing call, nor does it sort anything. That should
* allow you to use it for most existing text-based
* initialization files, since commentc etc. will not get
* lost.
*)
TTextIniFile = class(TObject)
private
(**
* Holds the fully qualified name of the file.
*)
FFileName: string;
(**
* Holds a string list of sections contained in
* the file. The Objects[] array property holds
* references to the string lists that hold the
* identifiers and values of a section.
*)
FSections: TStringList;
(**
* Is True if the file has been changed since
* is was last loaded, otherwiese False.
*)
FModified: Boolean;
public
(**
* Loads the contents of an initialization file. If
* the file does not exist, the object is empty.
*
* @see ~Destroy~
*)
constructor Create(const FileName: string);
(**
* Checks, whether the file has been ~modified~. If so,
* the new contents are written. Afterwards, the object
* is destroyed.
*
* @see ~Create~
*)
destructor Destroy; override;
(**
* Reads a string from the file. If either the given section
* or the given identifier does not exist, the default value
* is returned instead.
*
* @see ~WriteString~
*)
function ReadString(const Section, Ident, Default: string): string;
(**
* Writes a string value to the file. If the destination
* section does not exist, it is created. If a value with
* the given identifier already exists, it is overwritten.
*
* @see ~ReadString~
*)
procedure WriteString(const Section, Ident, Value: String);
(**
* Reads an Integer value from the file. If either the given section
* or the given identifier does not exist, or the value cannot be
* converted to Integer, the default value is returned instead.
*
* @see ~WriteInteger~
*)
function ReadInteger(const Section, Ident: string; Default: LongInt): LongInt;
(**
* Writes an Integer value to the file. If the destination
* section does not exist, it is created. If a value with
* the given identifier already exists, it is overwritten.
*
* @see ~ReadInteger~
*)
procedure WriteInteger(const Section, Ident: string; Value: LongInt);
(**
* Reads a Boolean value from the file. If either the given section
* or the given identifier does not exist, or the value cannot be
* converted to Boolean, the default value is returned instead.
*
* @see ~WriteBool~
*)
function ReadBool(const Section, Ident: string; Default: Boolean): Boolean;
(**
* Writes a Boolean value to the file. If the destination
* section does not exist, it is created. If a value with
* the given identifier already exists, it is overwritten.
*
* @see ~ReadBool~
*)
procedure WriteBool(const Section, Ident: string; Value: Boolean);
(**
* Reads an character value from the file. If either the given section
* or the given identifier does not exist, or the value cannot be
* converted to Char, the default value is returned instead.
*
* @see ~WriteChar~
*)
function ReadChar(const Section, Ident: string; Default: Char): Char;
(**
* Writes a character value to the file. If the destination
* section does not exist, it is created. If a value with
* the given identifier already exists, it is overwritten.
*
* @see ~ReadChar~
*)
procedure WriteChar(const Section, Ident: string; Value: Char);
(**
* Reads an Currency value from the file. If either the given section
* or the given identifier does not exist, or the value cannot be
* converted to Currency, the default value is returned instead.
*
* @see ~WriteCurrency~
*)
function ReadCurrency(const Section, Ident: string; const Default: Currency): Currency;
(**
* Writes a Currency value to the file. If the destination
* section does not exist, it is created. If a value with
* the given identifier already exists, it is overwritten.
*
* @see ~ReadCurrency~
*)
procedure WriteCurrency(const Section, Ident: string; Value: Currency);
(**
* Reads an floating point value from the file. If either the
* given section or the given identifier does not exist, or the
* value cannot be converted to Extended, the default value is
* returned instead.
*
* @see ~WriteFloat~
*)
function ReadFloat(const Section, Ident: string; const Default: Extended): Extended;
(**
* Writes a floating point value to the file. If the destination
* section does not exist, it is created. If a value with
* the given identifier already exists, it is overwritten.
*
* @see ~ReadFloat~
*)
procedure WriteFloat(const Section, Ident: string; Value: Extended);
(**
* Reads an date-and-time value from the file. If either the
* given section or the given identifier does not exist, or
* the value cannot be converted to TDateTime, the default
* value is returned instead.
*
* @see ~WriteDateTime~
*)
function ReadDateTime(const Section, Ident: string; const Default: TDateTime): TDateTime;
(**
* Writes a date-and-time value to the file. If the destination
* section does not exist, it is created. If a value with
* the given identifier already exists, it is overwritten.
*
* @see ~ReadDateTime~
*)
procedure WriteDateTime(const Section, Ident: string; Value: TDateTime);
(**
* Reads binary data from the file. A maximum of Count bytes is read and
* written to the given buffer. The function returns the number of
* bytes actually contained in the desired identifier, that is, the
* buffer size needed for reading all data. If either the given section
* or the given identifier does not exist, 0 is returned. If a
* conversion error occurs (since the function expects hex-coded,
* comma-separated values), -1 is returned.
*
* @see ~WriteBinary~
*)
function ReadBinary(const Section, Ident: string; Buffer: Pointer; Count: LongInt): LongInt;
(**
* Writes binary data to the file. The data is taken from the given
* Buffer, with Count specifying the number of bytes to write. The
* bytes are written as a hex-coded, comma-separated list of values.
* If the destination section does not exist, it is created. If a
* value with the given identifier already exists, it is overwritten.
*
* @see ~ReadBinary~
*)
procedure WriteBinary(const Section, Ident: string; Buffer: Pointer; Count: LongInt);
(**
* Queries a list of all identifiers in the given section.
* The identifiers are written to the given string object.
*
* @see ~ReadSections~, ~ReadSectionValues~, ~WriteSectionValues~
*)
procedure ReadSection(const Section: string; Strings: TStrings);
(**
* Queries a list of all sections in the initialization file.
* The section names are written to the given string object.
*
* @see ~ReadSection~, ~ReadSectionValues~, ~WriteSectionValues~
*)
procedure ReadSections(Strings: TStrings);
(**
* Queries a list of all identifiers and values of a given section.
* The identifiers and values are written to the given string object.
* They are accessible via the Names[] and Values[] array
* properties.
*
* @see ~ReadSection~, ~ReadSections~, ~WriteSectionValues~
*)
procedure ReadSectionValues(const Section: string; Strings: TStrings);
(**
* Writes a series of names and values to a given section.
* The method takes all names contained in the string object
* and writes their values to the given section. Old values
* are overwritten.
*
* @see ~ReadSection~, ~ReadSections~, ~ReadSectionValues~
*)
procedure WriteSectionValues(const Section: string; Strings: TStrings);
(**
* Erases a section. If the given section does not exist,
* nothing happens.
*
* @see ~DeleteKey~
*)
procedure EraseSection(const Section: string);
(**
* Erases an identifier from a section. If the given identifer
* does not exist, nothing happens.
*
* @see ~EraseSection~
*)
procedure DeleteKey(const Section, Ident: String);
(**
* Holds the fully qualified name of the file.
*)
property FileName: string read FFileName;
(**
* Is True if the file has been changed since
* is was last loaded, otherwiese False.
*)
property Modified: Boolean read FModified;
end;
implementation
const
DecToHex: array[0 .. 15] of Char = '0123456789ABCDEF';
HexToDec: array['0'..'F'] of Byte = ( 0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 0, 0, 0, 0, 0, 0,
0, 10, 11, 12, 13, 14, 15 );
constructor TTextIniFile.Create(const FileName: string);
var
Strings, Section: TStringList;
Line: string;
I: Integer;
begin
inherited Create;
FFileName := ExpandFileName(FileName);
FSections := TStringList.Create;
Strings := TStringList.Create;
if FileExists(FFileName) then
Strings.LoadFromFile(FileName);
Section := nil;
try
for I := 0 to Strings.Count - 1 do
begin
Line := Strings[I];
if Line <> '' then
begin
if Line[1] = '[' then
begin
Line := Copy(Line, 2, Length(Line) - 2);
Section := TStringList.Create;
FSections.AddObject(Line, Section);
end
else
begin
if Section = nil then
begin
Section := TStringList.Create;
FSections.AddObject('', Section);
end;
Section.Add(Line);
end;
end;
end;
finally
Strings.Free;
end;
end;
destructor TTextIniFile.Destroy;
var
Strings: TStringList;
I: Integer;
begin
if FSections <> nil then
begin
if FModified then
begin
Strings := TStringList.Create;
try
for I := 0 to FSections.Count - 1 do
begin
if (I <> 0) or (FSections[I] <> '') then
Strings.Add('[' + FSections[I] + ']');
Strings.AddStrings(TStringList(FSections.Objects[I]));
Strings.Add('');
end;
Strings.SaveToFile(FileName);
finally
Strings.Free;
end;
end;
for I := 0 to FSections.Count - 1 do
FSections.Objects[I].Free;
FSections.Free;
end;
inherited Destroy;
end;
function TTextIniFile.ReadString(const Section, Ident, Default: string): string;
var
I: Integer;
begin
if Ident <> '' then
begin
I := FSections.IndexOf(Section);
if I <> -1 then
begin
Result := TStrings(FSections.Objects[I]).Values[Ident];
if Result <> '' then Exit;
end;
Result := Default;
end
else
Result := '';
end;
procedure TTextIniFile.WriteString(const Section, Ident, Value: String);
var
I: Integer;
begin
if Ident <> '' then
begin
I := FSections.IndexOf(Section);
if I = -1 then
begin
if Section = '' then
begin
FSections.InsertObject(0, Section, TStringList.Create);
I := 0;
end
else
I := FSections.AddObject(Section, TStringList.Create);
end;
TStringList(FSections.Objects[I]).Values[Ident] := Value;
FModified := True;
end;
end;
function TTextIniFile.ReadInteger(const Section, Ident: string; Default: Longint): Longint;
begin
Result := StrToIntDef(ReadString(Section, Ident, ''), Default);
end;
procedure TTextIniFile.WriteInteger(const Section, Ident: string; Value: Longint);
begin
WriteString(Section, Ident, IntToStr(Value));
end;
function TTextIniFile.ReadBool(const Section, Ident: string; Default: Boolean): Boolean;
begin
Result := (ReadInteger(Section, Ident, Ord(Default)) <> 0);
end;
procedure TTextIniFile.WriteBool(const Section, Ident: string; Value: Boolean);
begin
if Value then
WriteInteger(Section, Ident, 1)
else
WriteInteger(Section, Ident, 0);
end;
function TTextIniFile.ReadChar(const Section, Ident: string; Default: Char): Char;
var
S: string;
begin
S := ReadString(Section, Ident, Default);
if (S <> '') then
Result := S[1]
else
S := Default;
end;
procedure TTextIniFile.WriteChar(const Section, Ident: string; Value: Char);
begin
WriteString(Section, Ident, Value);
end;
function TTextIniFile.ReadCurrency(const Section, Ident: string; const Default: Currency): Currency;
var
S: string;
E: LongInt;
begin
S := ReadString(Section, Ident, '');
Val(S, Result, E);
if E <> 0 then Result := Default;
end;
procedure TTextIniFile.WriteCurrency(const Section, Ident: string; Value: Currency);
var
S: string;
begin
Str(Value, S);
WriteString(Section, Ident, Trim(S));
end;
function TTextIniFile.ReadFloat(const Section, Ident: string; const Default: Extended): Extended;
var
S: string;
E: LongInt;
begin
S := ReadString(Section, Ident, '');
Val(S, Result, E);
if E <> 0 then Result := Default;
end;
procedure TTextIniFile.WriteFloat(const Section, Ident: string; Value: Extended);
var
S: string;
begin
Str(Value, S);
WriteString(Section, Ident, Trim(S));
end;
function TTextIniFile.ReadDateTime(const Section, Ident: string; const Default: TDateTime): TDateTime;
var
Temp: string;
Y, M, D, H, N, S: LongInt;
begin
Temp := ReadString(Section, Ident, '');
Y := StrToIntDef(Copy(Temp, 1, 4), 0);
M := StrToIntDef(Copy(Temp, 6, 2), 0);
D := StrToIntDef(Copy(Temp, 9, 2), 0);
H := StrToIntDef(Copy(Temp, 12, 2), 0);
N := StrToIntDef(Copy(Temp, 15, 2), 0);
S := StrToIntDef(Copy(Temp, 18, 2), 0);
try
Result := EncodeDate(Y, M, D) + EncodeTime(H, N, S, 0);
except
Result := Default;
end;
end;
procedure TTextIniFile.WriteDateTime(const Section, Ident: string; Value: TDateTime);
begin
WriteString(Section, Ident, FormatDateTime('yyyy"/"mm"/"dd hh":"nn":"ss', Value));
end;
function TTextIniFile.ReadBinary(const Section, Ident: string; Buffer: Pointer; Count: LongInt): LongInt;
var
Value: string;
Bytes: PByteArray absolute Buffer;
I: Integer;
C: Char;
begin
Value := ReadString(Section, Ident, '');
Result := (Length(Value) + 1) div 3;
if Count > Result then Count := Result;
for I := 0 to Count - 1 do
begin
C := UpCase(Value[1 + 3 * I + 0]);
if C in ['0'..'9', 'A'..'F'] then
Bytes^[I] := HexToDec[C] shl 4
else
begin
Result := -1;
Exit;
end;
C := UpCase(Value[1 + 3 * I + 1]);
if C in ['0'..'9', 'A'..'F'] then
Bytes^[I] := Bytes^[I] or HexToDec[C]
else
begin
Result := -1;
Exit;
end;
end;
end;
procedure TTextIniFile.WriteBinary(const Section, Ident: string; Buffer: Pointer; Count: LongInt);
var
Value: string;
Bytes: PByteArray absolute Buffer;
I: Integer;
begin
Value := StringOfChar(',', Count * 3 - 1);
for I := 0 to Count - 1 do
begin
Value[1 + 3 * I + 0] := DecToHex[Bytes^[I] shr 4];
Value[1 + 3 * I + 1] := DecToHex[Bytes^[I] and 15];
end;
WriteString(Section, Ident, Value);
end;
procedure TTextIniFile.ReadSection(const Section: string; Strings: TStrings);
var
I, J: Integer;
Idents: TStringList;
S: string;
begin
I := FSections.IndexOf(Section);
if I <> -1 then
begin
Idents := TStringList(FSections.Objects[I]);
Strings.BeginUpdate;
try
for J := 0 to Idents.Count - 1 do
begin
S := Idents.Names[J];
if (S <> '') and (S[1] <> ';') then
Strings.Add(S);
end;
finally
Strings.EndUpdate;
end;
end;
end;
procedure TTextIniFile.ReadSections(Strings: TStrings);
begin
Strings.Assign(FSections);
end;
procedure TTextIniFile.ReadSectionValues(const Section: string; Strings: TStrings);
var
I: Integer;
begin
I := FSections.IndexOf(Section);
if I <> -1 then
Strings.Assign(TStringList(FSections.Objects[I]));
end;
procedure TTextIniFile.WriteSectionValues(const Section: string; Strings: TStrings);
var
I: Integer;
begin
for I := 0 to Strings.Count - 1 do
begin
WriteString(Section, Strings.Names[I], Strings.Values[Strings.Names[I]]);
end;
end;
procedure TTextIniFile.EraseSection(const Section: string);
var
I: Integer;
begin
if (Section <> '') then
with FSections do
begin
I := IndexOf(Section);
if I <> -1 then
begin
Objects[I].Free;
Delete(I);
FModified := True;
end;
end;
end;
procedure TTextIniFile.DeleteKey(const Section, Ident: string);
var
I, J: Integer;
begin
if (Section <> '') and (Ident <> '') and (Ident[1] <> ';') then
begin
I := FSections.IndexOf(Section);
if I <> -1 then
with TStringList(FSections[I]) do
begin
J := IndexOfName(Ident);
if J <> -1 then
begin
Delete(J);
FModified := True;
end;
end;
end;
end;
end.
|
unit abastecimento;
interface
uses
SysUtils, DateUtils;
type
// Classe modelo de abastecimentos
T_Abastecimento = class(TObject)
F_Id: Integer;
F_DataHora: TDateTime;
F_Bomba_ID: Integer;
F_Litros: Double;
F_ValorPorLitro: Double;
F_ValorParcial: Double;
F_PercentualImposto: Double;
F_ValorImposto: Double;
F_ValorTotal: Double;
// F_DataHora
procedure setDataHora(pDataHora: TDateTime);
function getDataHora(): TDateTime;
// F_Litros
procedure setLitros(pLitros: Double);
function getLitros(): Double;
// F_ValorPorLitro
procedure setValorPorLitro(pValor: Double);
function getValorPorLitro(): Double;
// F_ValorParcial
procedure serValorParcial(pValor: Double);
function getValorParcial(): Double;
// F_PercentualImpostos
procedure setPercentualImposto(pPercentual: Double);
function getPercentualImposto(): Double;
// F_ValorImposto
function getValorImposto(): Double;
// F_ValorTotal
function getValorTotal(): Double;
// Totalizar
procedure Totalizar();
public
constructor Create(
pId: Integer;
pDataHora: TDateTime;
pBomba_ID: Integer;
pLitros: Double;
pValorPorLitro: Double;
pValorParcial: Double;
pPercentualImposto: Double;
pValorImposto: Double;
pValorTotal: Double
); overload;
constructor Create(
pDataHora: TDateTime;
pBomba_ID: Integer;
pLitros: Double;
pValorPorLitro: Double;
pPercentualImposto: Double); overload;
constructor Create(); overload;
published
property Id: Integer read F_Id write F_Id;
property DataHora: TDateTime read getDataHora write setDataHora;
property Bomba_ID: Integer read F_Bomba_ID write F_Bomba_ID;
property Litros: Double read getLitros write setLitros;
property ValorPorLitro: Double read getValorPorLitro write setValorPorLitro;
property ValorParcial: Double read getValorParcial; // somente leitura
property PercentualImposto: Double read getPercentualImposto write setPercentualImposto;
property ValorImposto: Double read getValorImposto; // somente leitura
property ValorTotal: Double read getValorTotal; // somente leitura
end;
implementation
constructor T_Abastecimento.Create(
pDataHora: TDateTime;
pBomba_ID: Integer;
pLitros: Double;
pValorPorLitro: Double;
pPercentualImposto: Double);
begin
if (pDataHora = 0) then
pDataHora := Now();
Self.F_Litros := pLitros;
Self.F_Bomba_ID := pBomba_ID;
Self.F_DataHora := pDataHora;
Self.F_ValorPorLitro := pValorPorLitro;
Self.F_PercentualImposto := pPercentualImposto;
Self.Totalizar();
end;
// utilizar no load da classe Dao
constructor T_Abastecimento.Create(
pId: Integer;
pDataHora: TDateTime;
pBomba_ID: Integer;
pLitros: Double;
pValorPorLitro: Double;
pValorParcial: Double;
pPercentualImposto: Double;
pValorImposto: Double;
pValorTotal: Double
);
begin
F_Id := pId;
F_DataHora := pDataHora;
F_Bomba_Id := pBomba_Id;
F_Litros := pLitros;
F_ValorPorLitro := pValorPorLitro;
F_ValorParcial := pValorParcial;
F_PercentualImposto := pPercentualImposto;
F_ValorImposto := pValorImposto;
F_ValorTotal := pValorTotal;
end;
constructor T_Abastecimento.Create();
begin
end;
procedure T_Abastecimento.Totalizar();
begin
try
F_ValorParcial := F_Litros * F_ValorPorLitro;
F_ValorImposto := (F_PercentualImposto / 100) * F_ValorParcial;
F_ValorTotal := F_ValorParcial + F_ValorImposto;
except
end;
end;
procedure T_Abastecimento.setDataHora(pDataHora: TDateTime);
begin
F_DataHora := pDataHora;
end;
function T_Abastecimento.getDataHora(): TDateTime;
begin
result := F_DataHora;
end;
// F_Litros
procedure T_Abastecimento.setLitros(pLitros: Double);
begin
F_Litros := pLitros;
Totalizar();
end;
function T_Abastecimento.getLitros(): Double;
begin
result := F_Litros;
end;
// F_ValorPorLitro
procedure T_Abastecimento.setValorPorLitro(pValor: Double);
begin
F_ValorPorLitro := pValor;
Totalizar();
end;
function T_Abastecimento.getValorPorLitro(): Double;
begin
result := F_ValorPorLitro;
end;
// F_ValorParcial
procedure T_Abastecimento.serValorParcial(pValor: Double);
begin
F_ValorParcial := pValor;
end;
function T_Abastecimento.getValorParcial(): Double;
begin
result := F_ValorParcial;
end;
// F_PercentualImposto
procedure T_Abastecimento.setPercentualImposto(pPercentual: Double);
begin
F_PercentualImposto := pPercentual;
Totalizar();
end;
function T_Abastecimento.getPercentualImposto(): Double;
begin
result := F_PercentualImposto;
end;
// F_ValorImposto
function T_Abastecimento.getValorImposto(): Double;
begin
result := F_ValorImposto;
end;
// F_ValorTotal
function T_Abastecimento.getValorTotal(): Double;
begin
result := F_ValorTotal;
end;
end.
|
{***********************************************************************************************************************
*
* TERRA Game Engine
* ==========================================
*
* Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com)
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************
* TERRA_Sound
* Implements a Sound resource
***********************************************************************************************************************
}
Unit TERRA_Sound;
{$I terra.inc}
Interface
Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF}
TERRA_String, TERRA_Utils, TERRA_Stream, TERRA_Resource, TERRA_Collections, TERRA_AL;
Const
DefaultSampleRate = 44100;
sndStopped = 0;
sndPlaying = 1;
sndPaused = 2;
SOUND_FORMAT_16BIT = 1;
SOUND_FORMAT_8BIT = 0;
Type
Sound = Class(Resource)
Protected
_Buffer:Cardinal;
_Data:Pointer;
_BufferSize:Cardinal;
_Frequency:Cardinal;
_BitsPerSample:Cardinal;
_Channels:Cardinal;
_AttachList:Array Of Pointer;
_AttachCount:Integer;
Function GetBufferLength(Size,Channels,BitsPerSample,Frequency:Cardinal):Cardinal;
Function GetBufferSize(Length,Channels,BitsPerSample,Frequency:Cardinal):Cardinal;
Function GetSampleSize:Cardinal;
Function GetLength:Cardinal;
Function GetFormat:Integer;
Function GetHandle:Cardinal;
Public
Function Load(Source:Stream):Boolean; Override;
Function Unload:Boolean; Override;
Function Update:Boolean; Override;
Procedure AttachSource(Source:Pointer);
Procedure RemoveSource(Source:Pointer);
Class Function GetManager:Pointer; Override;
Procedure New(Size,Channels,BitsPerSample,Frequency:Cardinal);
Property Data:Pointer Read _Data;
Property Size:Cardinal Read _BufferSize;
Property BufferSize:Cardinal Read _BufferSize Write _BufferSize;
Property Frequency:Cardinal Read _Frequency;
Property BitsPerSample:Cardinal Read _BitsPerSample;
Property SampleSize:Cardinal Read GetSampleSize;
Property Channels:Cardinal Read _Channels;
Property Format:Integer Read GetFormat;
Property Buffer:Cardinal Read _Buffer;
End;
SoundStreamValidateFunction=Function(Source:Stream):Boolean;
SoundLoader=Function(Source:Stream; Sound:Sound):Boolean;
SoundSaver=Procedure(Source:Stream; Sound:Sound; Const Options:TERRAString='');
PSoundClassInfo = ^SoundClassInfo;
SoundClassInfo = Record
Name:TERRAString;
Validate:SoundStreamValidateFunction;
Loader:SoundLoader;
Saver:SoundSaver;
End;
Function GetSoundLoader(Source:Stream):SoundLoader;
//Function GetSoundSaver(Format:TERRAString):SoundSaver;
Procedure RegisterSoundFormat(Name:TERRAString;
Validate:SoundStreamValidateFunction;
Loader:SoundLoader;
Saver:SoundSaver=Nil);
Var
_SoundExtensions:Array Of SoundClassInfo;
_SoundExtensionCount:Integer = 0;
Implementation
Uses TERRA_Error, TERRA_OS, TERRA_Application, TERRA_Log, TERRA_SoundManager, TERRA_SoundSource;
Function Sound.Unload:Boolean;
Var
I:Integer;
Begin
For I:=0 To Pred(_AttachCount) Do
SoundManager.Instance().Delete(SoundSource(_AttachList[I]));
_AttachCount := 0;
If (_Buffer<>0) Then
Begin
alDeleteBuffers(1, @_Buffer); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
_Buffer := 0;
End;
If Assigned(_Data) Then
Begin
FreeMem(_Data);
_Data:=Nil;
End;
Result := Inherited Unload();
End;
Procedure Sound.New(Size, Channels, BitsPerSample, Frequency: Cardinal);
Begin
_Channels:=Channels;
_Frequency:=Frequency;
_BitsPerSample:=BitsPerSample;
_BufferSize:=Size;
_Buffer := 0;
GetMem(_Data,_BufferSize);
SetStatus(rsReady);
End;
Function Sound.Update:Boolean;
Begin
Inherited Update();
Result := False;
If (_Buffer=0) Then
Begin
alGenBuffers(1, @_Buffer); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
End Else
Exit;
If Format=-1 Then
Begin
RaiseError('Invalid sound format.');
Result := False;
Exit;
End;
alBufferData(_Buffer, Format, Data, BufferSize, Frequency); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF}
SetStatus(rsReady);
End;
Function Sound.GetSampleSize:Cardinal;
Begin
Result := BitsPerSample Div 8;
End;
Function Sound.GetHandle:Cardinal;
Begin
Result := _Buffer;
End;
Function Sound.GetBufferLength(Size,Channels,BitsPerSample,Frequency:Cardinal):Cardinal;
Begin
Result := Round((((Size/Self.Channels)/Self.SampleSize)*1000)/Frequency);
End;
Function Sound.GetBufferSize(Length,Channels,BitsPerSample,Frequency:Cardinal):Cardinal;
Begin
Result := Round((Length/1000)*Frequency*Self.SampleSize*Self.Channels);
End;
Function Sound.GetLength:Cardinal;
Begin
Result := GetBufferLength(BufferSize,Channels,SampleSize,Frequency);
End;
Function Sound.GetFormat:Integer;
Begin
Result := -1;
If Channels=2 Then
Begin
If BitsPerSample=8 Then
Result := AL_FORMAT_STEREO8
Else
If BitsPerSample=16 Then
Result := AL_FORMAT_STEREO16;
End Else
Begin
If BitsPerSample=8 Then
Result := AL_FORMAT_MONO8
Else
If BitsPerSample=16 Then
Result := AL_FORMAT_MONO16;
End;
End;
Procedure Sound.AttachSource(Source:Pointer);
Var
I:Integer;
Begin
For I:=0 To Pred(_AttachCount) Do
If (_AttachList[I] = Source) Then
Exit;
Inc(_AttachCount);
If Length(_AttachList)<_AttachCount Then
SetLength(_AttachList, _AttachCount);
_AttachList[Pred(_AttachCount)] := Source;
End;
Procedure Sound.RemoveSource(Source:Pointer);
Var
N,I:Integer;
Begin
N := -1;
For I:=0 To Pred(_AttachCount) Do
If (_AttachList[I] = Source) Then
Begin
N := I;
Break;
End;
If (N<0) Then
Exit;
_AttachList[I] := _AttachList[Pred(_AttachCount)];
Dec(_AttachCount);
End;
Function GetSoundLoader(Source:Stream):SoundLoader;
Var
Pos:Cardinal;
I:Integer;
Begin
Log(logDebug, 'Sound', 'Getting sound loader for '+Source.Name);
Result := Nil;
If Not Assigned(Source) Then
Exit;
Pos := Source.Position;
Log(logDebug, 'Sound', IntToString(_SoundExtensionCount)+ ' sound extensions active');
For I:=0 To Pred(_SoundExtensionCount) Do
Begin
Source.Seek(Pos);
Log(logDebug, 'Sound', 'Testing sound extension: '+_SoundExtensions[I].Name);
If _SoundExtensions[I].Validate(Source) Then
Begin
Log(logDebug, 'Sound', 'Sound extension '+_SoundExtensions[I].Name+' matched!');
Result := _SoundExtensions[I].Loader;
Log(logDebug, 'Sound', 'Seeking... '+CardinalToString(Pos));
Source.Seek(Pos);
Log(logDebug, 'Sound', 'Returning...');
Exit;
End;
End;
Log(logWarning, 'Sound', 'No sound extensions matched!');
Result := NIl;
End;
Function Sound.Load(Source:Stream):Boolean;
Var
I:Integer;
Loader:SoundLoader;
Begin
Loader := GetSoundLoader(Source);
If Not Assigned(Loader) Then
Begin
Result := False;
RaiseError('Unknown sound format. ['+Source.Name+']');
{Log(logError, 'Sound', 'Unknown sound format. ['+Source.Name+']');
_Status := rsInvalid;}
Exit;
End;
Log(logDebug, 'Sound', 'Calling sound loader...');
Result := Loader(Source, Self);
SetStatus(rsReady);
End;
Procedure RegisterSoundFormat(Name:TERRAString;
Validate:SoundStreamValidateFunction;
Loader:SoundLoader;
Saver:SoundSaver=Nil);
Var
I,N:Integer;
Begin
Name := StringLower(Name);
For I:=0 To Pred(_SoundExtensionCount) Do
If (_SoundExtensions[I].Name = Name) Then
Exit;
N := _SoundExtensionCount;
Inc(_SoundExtensionCount);
SetLength(_SoundExtensions, _SoundExtensionCount);
_SoundExtensions[N].Name := Name;
_SoundExtensions[N].Validate :=Validate;
_SoundExtensions[N].Loader := Loader;
_SoundExtensions[N].Saver := Saver;
End;
Class Function Sound.GetManager: Pointer;
Begin
Result := SoundManager.Instance;
End;
End.
|
unit SimHints;
interface
uses
Languages;
const
mtidHintsDenied : TRegMultiString = nil; // 'This facility belongs to %s. There are no hints for you.';
mtidVisitWebSite : TRegMultiString = nil; // 'No hints for this facility.';
mtidNeedsMoney : TRegMultiString = nil; // 'Hint: Stop all facilities that are losing money.';
mtidNeedsConnection : TRegMultiString = nil; // 'Hint: Go to "Settings" and hire some suppliers.';
mtidNeedsSomeConnection : TRegMultiString = nil; // 'Warning: This facility needs supplier for %s.';
mtidSuppliesDropped : TRegMultiString = nil; // 'Warning: Supplier of %s have dropped. Hire another suppliers.';
mtidSalesDropped : TRegMultiString = nil; // 'Warning: Sales of %s have dropped. Get hired by another facilities.';
mtidSuppliesBeingImported : TRegMultiString = nil; // 'Hint: You are importing %s because your suppliers are selling to another people.';
mtidSuppliesRedirected : TRegMultiString = nil; // 'Warning: Your suppliers of %s are selling their entire production to different people.';
mtidNeedsWorkForce : TRegMultiString = nil; // 'Warning: this facility needs more %s work force.';
mtidNeedsCompSupport : TRegMultiString = nil; // 'Warning: Not enough company support. You must build more headquarters or attract more people to those already built.';
mtidBlockNeedsWorkForce : TRegMultiString = nil; // 'Warning: This facility needs %s work force.';
mtidUpgrading : TRegMultiString = nil;
mtidUpgradeLevel : TRegMultiString = nil;
// Construction
mtidConstFromTradeCenter : TRegMultiString = nil; // 'Hint: The Trade Center was hired to construct this. You could hire someone cheaper.';
// Residentials
mtidResVeryUnderPopulated : TRegMultiString = nil; // 'Warning: You need to attract more people to this building.';
mtidResUnderPopulated : TRegMultiString = nil; // 'Hint: You need to attract more people to this building.';
mtidResMildUnderPopulated : TRegMultiString = nil; // 'Hint: You still can attract more people to this building.';
mtidTownUnderPopulated : TRegMultiString = nil; // 'Hint: There are too few people in %s. You will have to compete fiercely. Try making the rent lower.';
mtidResWorkingFine : TRegMultiString = nil; // 'Congratulations: This building is working OK. Perhaps you can rise the rent a little bit.';
mtidResWorking : TRegMultiString = nil;
mtidResClosedHeader : TRegMultiString = nil;
mtidResClosedByLine : TRegMultiString = nil;
mtidResRepaired : TRegMultiString = nil;
mtidResSecReport : TRegMultiString = nil;
mtidPopBlkClone : TRegMultiString = nil;
// Public facilities
mtidVisitTownHall : TRegMultiString = nil; // 'Hint: Visit Town Hall''s Web Site to find valuable information.';
mtidVisitTradeCenter : TRegMultiString = nil; // 'Hint: Visit Trade Center''s Web Site to see who is selling or buying what.';
mtidPeopleIn : TRegMultiString = nil; // '%d citizens of %s moved in last day. ';
mtidPeopleInRes : TRegMultiString = nil; // '%d%% due to good residential offers, ';
mtidPeopleInWork : TRegMultiString = nil; // '%d%% to find a job, ';
mtidPeopleInQOL : TRegMultiString = nil; // '%d%% due to good quality of public services. ';
mtidPeopleOut : TRegMultiString = nil; // '%d citizens of %s moved out last day. ';
mtidPeopleOutWork : TRegMultiString = nil; // '%d%% due to salaries and work conditions, ';
mtidPeopleOutRes : TRegMultiString = nil; // '%d%% due to residential conditions, ';
mtidPeopleOutQOL : TRegMultiString = nil; // '%d%% due to low coverage of public services, ';
mtidPeopleOutUnemp : TRegMultiString = nil; // '%d%% due to unemployment, ';
mtidPeopleOutServ : TRegMultiString = nil; // '%d%% due to lack of products and services. ';
mtidPeopleOutDisasters : TRegMultiString = nil; // '%d%% due to disasters. ';
mtidNoMovements : TRegMultiString = nil; // 'No %s movements.';
mtidTHMainText : TRegMultiString = nil;
mtidTHPopReport : TRegMultiString = nil;
// Headquarters
mtidGeneralHQResearch : TRegMultiString = nil; // 'Hint: Be sure there are enought workers to carry out the research.';
mtidHQResearch : TRegMultiString = nil; // 'Hint: Well, %s, this is a good time to go to Voyager''s Mail and write a love letter...';
mtidHQIdle : TRegMultiString = nil; // 'Hint: Go to "Settings" to carry out new researchs.';
mtidResearchMain : TRegMultiString = nil;
mtidResearchSec : TRegMultiString = nil;
mtidCompSupported : TRegMultiString = nil;
mtidImplementationCost : TRegMultiString = nil;
mtidResCenterCloneMenu : TRegMultiString = nil;
// Services
mtidServiceHiClassSpecialized : TRegMultiString = nil; // 'Hint: Are you trying to sell mainly to high class people? Then quality is the key.';
mtidServiceLoClassSpecialized : TRegMultiString = nil; // 'Hint: Are you trying to sell mainly to low class people? Then price is the key.';
mtidServiceHighCompetition : TRegMultiString = nil; // 'Warning: You have a problem with competition. Get some advertisement.';
mtidServiceWrongConception : TRegMultiString = nil; // 'Warning: It seams that you are targeting costumers in a wrong way.';
mtidServiceWrongPlace : TRegMultiString = nil; // 'Hint: Try to attract more customers by offering better quality and prices.';
mtidServiceWorkingFineButLow : TRegMultiString = nil; // 'Congratulations: This facility is running OK. Anyway you could attend more people.';
mtidServiceWorkingFine : TRegMultiString = nil; // 'Congratulations: This facility is running OK. Just keep this way.';
mtidServiceLowSupplies : TRegMultiString = nil; // 'Warning: %s service need more supplies.';
mtidServiceOpening : TRegMultiString = nil; // 'The facility started just few hours ago, there are no hints for now.';
mtidServiceSecondary : TRegMultiString = nil;
mtidServiceEfficiency : TRegMultiString = nil; // Efficiency
mtidServiceDesirability : TRegMultiString = nil; // Desirability
mtidServiceCloneMenu : TRegMultiString = nil;
// Evaluated blocks
mtidEvalBlockNotProducing : TRegMultiString = nil; // 'Hint: Not producing %s. You have no customers.';
mtidEvalBlockNeedsBasicInput : TRegMultiString = nil; // 'Warning: This facility requires %s to produce. Hire some suppliers or try to overpay those you already have.';
mtidEvalBlockNeedsMoreSupplies : TRegMultiString = nil; // 'Hint: This facility needs more %s to produce %s.';
mtidEvalBlockNeedsConnections : TRegMultiString = nil; // 'Hint: Go to "Settings" and hire more suppliers for %s.';
mtidEvalBlockAvoidTradeCenter : TRegMultiString = nil; // 'Hint: You are buying from a Trade Center. Find some local suppliers.';
mtidEvalBlockBadWeatherCond : TRegMultiString = nil; // 'There is nothing we can do about the weather but wait.';
mtidEvalBlockNeedTechnology : TRegMultiString = nil; // 'Warning: Cannot operate until you research again %s.';
mtidEvalBlockNeedsMoreCompSupplies : TRegMultiString = nil; // 'Warning: This facility is lacking services. Check the Services Tab on the INSPECT panel.';
mtidSupplies : TRegMultiString = nil;
mtidEvalBlockCloneMenu : TRegMultiString = nil; // 'Price|%d|Suppliers|%d|Clients|%d|'
mtidEvalBlockProducing : TRegMultiString = nil; // Producing :
// Public
mtidTownNeedsMoreResidentials : TRegMultiString = nil; // 'Hint: This town requires more residentials for %s people.';
mtidTownNeedsMoreCommerce : TRegMultiString = nil; // 'Hint: New stores and other services would encourage economic activity.';
mtidTownHighUnemployment : TRegMultiString = nil; // 'Warning: There is a %d%% of unemployment in %s people.';
mtidTownLowPublicService : TRegMultiString = nil; // 'Warning: There is a problem with %s.';
mtidPublicFacNeedsWorkers : TRegMultiString = nil; // 'Hint: You should attract more workers to this facility in case you want to rise its operation ratio.';
mtidPublicFacNeedsSupport : TRegMultiString = nil; // 'Hint: This facility needs more support from its headquarters.';
mtidPubFacCov : TRegMultiString = nil; // '%s coverage accross the city reported at %d%%.';
mtidEmptyCity : TRegMultiString = nil; // 'This city is not populated!';
// Context status texts
mtidDesertedTown : TRegMultiString = nil; // '%s is not populated. Invest here and the %s order will give you an aditional amount of money.';
mtidPublicServiceNeeded : TRegMultiString = nil; // 'Citizens of %s demand more %s.';
mtidServiceNeeded : TRegMultiString = nil; // 'Citizens of %s demand more %s.';
mtidVisitNewspaper : TRegMultiString = nil; // 'For more information about %s visit %s, the local newspaper.';
// Facility Descriptions
mtidDescResidential : TRegMultiString = nil; // '%s residential. %d inhabitants. %d%% resistent to crime, %d%% resistent to pollution. Design quality: %d%%.';
mtidDescOffice : TRegMultiString = nil; // '%d offices to rent. Design quality: %d%%.';
mtidDescFactoryHead : TRegMultiString = nil; // 'Produces up to ';
mtidDescFactoryHeadN : TRegMultiString = nil; // '%s of %s';
mtidDescFactoryReq : TRegMultiString = nil; // 'Requires ';
mtidDescFactoryReqN : TRegMultiString = nil; // '%s';
mtidWorkCenterHead : TRegMultiString = nil; // 'Employs: ';
mtidTechRequired : TRegMultiString = nil; // 'Requires research %s at %s.';
mtidWHHead : TRegMultiString = nil; // 'Stores up to ';
mtidWCenterClone : TRegMultiString = nil;
mtidDescStoreInput : TRegMultiString = nil;
mtidDescStoreResell1 : TRegMultiString = nil;
mtidDescStoreTailStr : TRegMultiString = nil;
mtidDescStoreCombine1 : TRegMultiString = nil;
mtidDescStoreCombine2 : TRegMultiString = nil;
// Alerts
mtidFacilityWillBeDemolished : TRegMultiString = nil; // 'ATENTION! THE MAYOR OF %s REQUESTED THE DEMOLITION OF THIS BUILDING DUE TO CITY PLANNING. DEMOLITION WILL TAKE PLACE IN %d MONTHS. THE GOVERNMENT WILL PAY YOU %s AS A COMPENSATION.';
// Curriculum
mtidOwnershipReport : TRegMultiString = nil; // 'Controls %d companies, %d facilities.';
mtidResearchReport : TRegMultiString = nil; // 'Research report
mtidWonElections : TRegMultiString = nil; // 'Was elected Mayor of %s in the campaign of %d.';
mtidWasMayor : TRegMultiString = nil; // 'Was Mayor of %s from %d to %d with a %d%% of popular rating.';
mtidWasFiredFromMayor : TRegMultiString = nil; // 'Was fired from Mayor of %s in %d.';
mtidWasPresident : TRegMultiString = nil; // 'Was President of %s from %d to %d with a %d%% of popular rating.';
mtidWonWorldElections : TRegMultiString = nil; // 'Was elected President of %s in the campaign of %d.';
mtidWasMinister : TRegMultiString = nil; // 'Was Minister of %s from %d to %d with a %d%% of IFEL rating.';
mtidAppointedMinister : TRegMultiString = nil; // 'Was appointed Minister of %s in the campaign of %d by %s.';
mtidBankrupt : TRegMultiString = nil; // 'Was declared in bankrupty in %d';
mtidTranscended : TRegMultiString = nil; // 'Transcended in %d';
// Levels
mtidLevelAchieved : TRegMultiString = nil; // 'Achieved level %s in %d';
mtidNotEnoughMoney : TRegMultiString = nil; // 'Could not upgrade level last year. You failed to pay $%.0n';
mtidNotEnoughProfit : TRegMultiString = nil; // 'Could not upgrade level last year. You require an average profit ratio of $%.0n/h (last year you had $%.0n/h)';
mtidMustHaveBeenMayor : TRegMultiString = nil; // 'You need to be elected Mayor at least once.';
mtidMustHaveBeenPresident : TRegMultiString = nil; // 'You need to be elected President at least once.';
mtidPrestigeRequired : TRegMultiString = nil; // 'Could not upgrade level last year. You require %d prestige points';
mtidNotEnoughPrestigeLostLevel : TRegMultiString = nil; // 'You failed to pay $%.0n';
mtidNotEnoughProfitLostLevel : TRegMultiString = nil; // 'You require an average profit ratio of $%.0n/h (last year you had $%.0n/h)';
mtidLevelLost : TRegMultiString = nil;
mtidCouldNotUpgrade : TRegMultiString = nil; // 'Could not
// Misc
mtidJoinedWorld : TRegMultiString = nil; // 'Joined %s in %d';
mtidAND : TRegMultiString = nil; //
// Events
mtidSetTaxes : TRegMultiString = nil;
mtidSubsidy : TRegMultiString = nil;
mtidLaunchedCampaign : TRegMultiString = nil;
mtidCancelledCampaign : TRegMultiString = nil;
mtidMayorElected : TRegMultiString = nil;
mtidMayorReElected : TRegMultiString = nil;
mtidCityHasNoMayor : TRegMultiString = nil;
mtidMayorFired : TRegMultiString = nil;
mtidSubsidiesRemoved : TRegMultiString = nil;
mtidTycoonBankrupt : TRegMultiString = nil;
mtidFacBuilt : TRegMultiString = nil;
mtidAccountReset : TRegMultiString = nil;
mtidMsgJoinedWorld : TRegMultiString = nil;
mtidSatelliteUpdated : TRegMultiString = nil;
mtidMinisterElected : TRegMultiString = nil;
mtidPresidentElected : TRegMultiString = nil;
mtidPresidentReElected : TRegMultiString = nil;
mtidNoPresident : TRegMultiString = nil;
mtidPresidenCampaignLaunched : TRegMultiString = nil;
mtidPresidenCampaignCancelled : TRegMultiString = nil;
// Arrange later
mtidCiviHQPrest : TRegMultiString = nil;
mtidPubFacMain : TRegMultiString = nil;
mtidCapitolMain : TRegMultiString = nil;
mtidCapitolWithPresSec : TRegMultiString = nil;
mtidCapitolWithNoPresSec : TRegMultiString = nil;
mtidCapitolHint : TRegMultiString = nil;
mtidTVMainOne : TRegMultiString = nil;
mtidTVMainTwo : TRegMultiString = nil;
mtidTVSec : TRegMultiString = nil;
mtidHiringWorkForce : TRegMultiString = nil;
mtidHiringWorkForceSec : TRegMultiString = nil;
mtidTVWarning : TRegMultiString = nil;
mtidAntenaAudience : TRegMultiString = nil;
mtidAntenaRating : TRegMultiString = nil;
mtidAntenaHint : TRegMultiString = nil;
mtidConstruction : TRegMultiString = nil;
mtidStoppedDueWeather : TRegMultiString = nil;
mtidOfficeReport : TRegMultiString = nil;
mtidOfficeTitle : TRegMultiString = nil;
mtidOfficeOccup : TRegMultiString = nil;
mtidWarehouseRepHead : TRegMultiString = nil;
mtidWarehouseRepN : TRegMultiString = nil;
mtidMinisterName : TRegMultiString = nil;
mtidMinistryName : TRegMultiString = nil;
mtidCommerceMain : TRegMultiString = nil;
mtidOutputEvalFull : TRegMultiString = nil;
mtidOutputEval : TRegMultiString = nil;
mtidOutputSec : TRegMultiString = nil;
mtidInvPrice : TRegMultiString = nil;
mtidInvLicense : TRegMultiString = nil;
mtidInvImpCostYear : TRegMultiString = nil;
mtidInvImpCostHour : TRegMultiString = nil;
mtidInvUsage : TRegMultiString = nil;
mtidInvNobPoints : TRegMultiString = nil;
mtidInvPrestige : TRegMultiString = nil;
mtidInvLevel : TRegMultiString = nil;
mtidInvPayReduct : TRegMultiString = nil;
mtidInvJobQ : TRegMultiString = nil;
mtidInvBeauty : TRegMultiString = nil;
mtidInvMaintenance : TRegMultiString = nil;
mtidInvPrivacy : TRegMultiString = nil;
mtidInvCrimeRes : TRegMultiString = nil;
mtidInvPollRes : TRegMultiString = nil;
mtidInvEff : TRegMultiString = nil;
mtidInvDesirability : TRegMultiString = nil;
mtidInvQ : TRegMultiString = nil;
mtidOfficeClone : TRegMultiString = nil;
// Transcendence
mtidPlayerWillTranscend : TRegMultiString = nil;
mtidBewareOfTranscend : TRegMultiString = nil;
// Lumber Industry
mtidGrowingTrees : TRegMultiString = nil; // 'Growing trees at %d%%'
// Movie Studios
mtidLicensingFilm : TRegMultiString = nil; // 'Licensing: "%s" Quality Index: %d%%.'
mtidFilmProject : TRegMultiString = nil; // 'Roling: "%s" Day %d of %d, %d%% done.'
mtidNowPlaying : TRegMultiString = nil; // Now playing
// Inventions
mtidInvCatGeneral : TRegMultiString = nil; // General
mtidInvCatCommerce : TRegMultiString = nil; // Commerce
mtidInvCatIndustry : TRegMultiString = nil; // Industry
mtidInvCatRlEstate : TRegMultiString = nil; // Real Estate
function GetHintText( HintId : string; parms : array of const ) : string;
procedure InitMLS;
implementation
uses
SysUtils;
function GetHintText( HintId : string; parms : array of const ) : string;
begin
try
result := Format( HintId, parms );
except
result := '';
end;
end;
procedure InitMLS;
begin
mtidHintsDenied := TRegMultiString.Create( 'mtidHintsDenied', 'This facility belongs to %s. There are no hints for you.' );
mtidVisitWebSite := TRegMultiString.Create( 'mtidVisitWebSite', 'No hints for this facility.' );
mtidNeedsMoney := TRegMultiString.Create( 'mtidNeedsMoney', 'Hint: Stop all facilities that are losing money.' );
mtidNeedsConnection := TRegMultiString.Create( 'mtidNeedsConnection', 'Hint: Go to "Settings" and hire some suppliers.' );
mtidNeedsSomeConnection := TRegMultiString.Create( 'mtidNeedsSomeConnection', 'Warning: This facility needs supplier for %s.' );
mtidSuppliesDropped := TRegMultiString.Create( 'mtidSuppliesDropped', 'Warning: Supplier of %s have dropped. Hire another suppliers.' );
mtidSalesDropped := TRegMultiString.Create( 'mtidSalesDropped', 'Warning: Sales of %s have dropped. Get hired by another facilities.' );
mtidSuppliesBeingImported := TRegMultiString.Create( 'mtidSuppliesBeingImported', 'Hint: You are importing %s because your suppliers are selling to another people.' );
mtidSuppliesRedirected := TRegMultiString.Create( 'mtidSuppliesRedirected', 'Warning: Your suppliers of %s are selling their entire production to different people.' );
mtidNeedsWorkForce := TRegMultiString.Create( 'mtidNeedsWorkForce', 'Warning: this facility needs more %s work force.' );
mtidNeedsCompSupport := TRegMultiString.Create( 'mtidNeedsCompSupport', 'Warning: Not enough company support. You must build more headquarters or attract more people to those already built.' );
mtidBlockNeedsWorkForce := TRegMultiString.Create( 'mtidBlockNeedsWorkForce', 'Warning: This facility needs %s work force.' );
mtidUpgrading := TRegMultiString.Create( 'mtidUpgrading', 'Upgrading: %d%%' );
mtidUpgradeLevel := TRegMultiString.Create( 'mtidUpgradeLevel', 'Upgrade Level: %d' );
// Construction
mtidConstFromTradeCenter := TRegMultiString.Create( 'mtidConstFromTradeCenter', 'Hint: The Trade Center was hired to construct this. You could hire someone cheaper.' );
// Residentials
mtidResVeryUnderPopulated := TRegMultiString.Create( 'mtidResVeryUnderPopulated', 'Warning: You need to attract more people to this building.' );
mtidResUnderPopulated := TRegMultiString.Create( 'mtidResUnderPopulated', 'Hint: You need to attract more people to this building.' );
mtidResMildUnderPopulated := TRegMultiString.Create( 'mtidResMildUnderPopulated', 'Hint: You still can attract more people to this building.' );
mtidTownUnderPopulated := TRegMultiString.Create( 'mtidTownUnderPopulated', 'Hint: There are too few people in %s. You will have to compete fiercely. Try making the rent lower.' );
mtidResWorkingFine := TRegMultiString.Create( 'mtidResWorkingFine', 'Congratulations: This building is working OK. Perhaps you can rise the rent a little bit.' );
mtidResWorking := TRegMultiString.Create( 'mtidResWorking', '%d%% %s occupancy' );
mtidResClosedHeader := TRegMultiString.Create( 'mtidResClosedHeader', '%s real estate' );
mtidResClosedByLine := TRegMultiString.Create( 'mtidResClosedByLine', '[closed]' );
mtidResRepaired := TRegMultiString.Create( 'mtidResRepaired', '%d%% repaired' );
mtidResSecReport := TRegMultiString.Create( 'mtidResSecReport', '%d inhabitants. %d quality index. QOL: %d%% Neighborhood Quality: %d%% Beauty: %d%% Crime: %d%% Pollution: %d%%.' );
mtidPopBlkClone := TRegMultiString.Create( 'mtidPopBlkClone', 'Rent|%d|Maintenance|%d|' );
// Public facilities
mtidVisitTownHall := TRegMultiString.Create( 'mtidVisitTownHall', 'Hint: Visit Town Hall''s Web Site to find valuable information.' );
mtidVisitTradeCenter := TRegMultiString.Create( 'mtidVisitTradeCenter', 'Hint: Visit Trade Center''s Web Site to see who is selling or buying what.' );
mtidPeopleIn := TRegMultiString.Create( 'mtidPeopleIn', '%d citizens of %s moved in last day.' );
mtidPeopleInRes := TRegMultiString.Create( 'mtidPeopleInRes', '%d%% due to good residential offers, ' );
mtidPeopleInWork := TRegMultiString.Create( 'mtidPeopleInWork', '%d%% to find a job, ' );
mtidPeopleInQOL := TRegMultiString.Create( 'mtidPeopleInQOL', '%d%% due to good quality of public services.' );
mtidPeopleOut := TRegMultiString.Create( 'mtidPeopleOut', '%d citizens of %s moved out last day.' );
mtidPeopleOutWork := TRegMultiString.Create( 'mtidPeopleOutWork', '%d%% due to salaries and work conditions, ' );
mtidPeopleOutRes := TRegMultiString.Create( 'mtidPeopleOutRes', '%d%% due to residential conditions, ' );
mtidPeopleOutQOL := TRegMultiString.Create( 'mtidPeopleOutQOL', '%d%% due to low coverage of public services, ' );
mtidPeopleOutUnemp := TRegMultiString.Create( 'mtidPeopleOutUnemp', '%d%% due to unemployment, ' );
mtidPeopleOutServ := TRegMultiString.Create( 'mtidPeopleOutServ', '%d%% due to lack of products and services.' );
mtidPeopleOutDisasters := TRegMultiString.Create( 'mtidPeopleOutDisasters', '%d%% due to disasters.' );
mtidNoMovements := TRegMultiString.Create( 'mtidNoMovements', 'No %s movements.' );
mtidTHMainText := TRegMultiString.Create( 'mtidTHMainText', '%s inhabitants' );
mtidTHPopReport := TRegMultiString.Create( 'mtidTHPopReport', '%s %s (%d%% unemp)' );
// Headquarters
mtidGeneralHQResearch := TRegMultiString.Create( 'mtidGeneralHQResearch', 'Hint: Be sure there are enought workers to carry out the research.' );
mtidHQResearch := TRegMultiString.Create( 'mtidHQResearch', 'Hint: Well, %s, this is a good time to go to Voyager''s Mail and write a love letter...' );
mtidHQIdle := TRegMultiString.Create( 'mtidHQIdle', 'Hint: Go to "Settings" to carry out new researchs.' );
mtidResearchMain := TRegMultiString.Create( 'mtidResearchMain', '%d%% research completed' );
mtidResearchSec := TRegMultiString.Create( 'mtidResearchSec', 'Researching %s. Cost: %s.' );
mtidCompSupported := TRegMultiString.Create( 'mtidCompSupported', 'Company supported at %d%%.' );
mtidImplementationCost := TRegMultiString.Create( 'mtidImplementationCost', 'Research Implementation: %s.' );
mtidResCenterCloneMenu := TRegMultiString.Create( 'mtidResCenterCloneMenu', 'Suppliers|%d|' );
// Services
mtidServiceHiClassSpecialized := TRegMultiString.Create( 'mtidServiceHiClassSpecialized', 'Hint: Are you trying to sell mainly to high class people? Then quality is the key.' );
mtidServiceLoClassSpecialized := TRegMultiString.Create( 'mtidServiceLoClassSpecialized', 'Hint: Are you trying to sell mainly to low class people? Then price is the key.' );
mtidServiceHighCompetition := TRegMultiString.Create( 'mtidServiceHighCompetition', 'Warning: You have a problem with competition. Get some advertisement.' );
mtidServiceWrongConception := TRegMultiString.Create( 'mtidServiceWrongConception', 'Warning: It seams that you are targeting costumers in a wrong way.' );
mtidServiceWrongPlace := TRegMultiString.Create( 'mtidServiceWrongPlace', 'Hint: Try to attract more customers by offering better quality and prices.' );
mtidServiceWorkingFineButLow := TRegMultiString.Create( 'mtidServiceWorkingFineButLow', 'Congratulations: This facility is running OK. Anyway you could attend more people.' );
mtidServiceWorkingFine := TRegMultiString.Create( 'mtidServiceWorkingFine', 'Congratulations: This facility is running OK. Just keep this way.' );
mtidServiceLowSupplies := TRegMultiString.Create( 'mtidServiceLowSupplies', 'Warning: %s service need more supplies.' );
mtidServiceOpening := TRegMultiString.Create( 'mtidServiceOpening', 'The facility started just few hours ago, there are no hints for now.' );
mtidServiceSecondary := TRegMultiString.Create( 'mtidServiceSecondary', 'Potential customers (per day): %d hi, %d mid, %d low. Actual customers: %d hi, %d mid, %d low.' );
mtidServiceEfficiency := TRegMultiString.Create( 'mtidServiceEfficiency', 'Efficiency: %d%%' );
mtidServiceDesirability := TRegMultiString.Create( 'mtidServiceDesirability', 'Desirability: %d' );
mtidServiceCloneMenu := TRegMultiString.Create( 'mtidServiceCloneMenu', 'Price|%d|Suppliers|%d|Ads|%d|' );
// Evaluated blocks
mtidEvalBlockNotProducing := TRegMultiString.Create( 'mtidEvalBlockNotProducing', 'Hint: Not producing %s. You have no customers.' );
mtidEvalBlockNeedsBasicInput := TRegMultiString.Create( 'mtidEvalBlockNeedsBasicInput', 'Warning: This facility requires %s to produce. Hire some suppliers or try to overpay those you already have.' );
mtidEvalBlockNeedsMoreSupplies := TRegMultiString.Create( 'mtidEvalBlockNeedsMoreSupplies', 'Hint: This facility needs more %s to produce %s.' );
mtidEvalBlockNeedsConnections := TRegMultiString.Create( 'mtidEvalBlockNeedsConnections', 'Hint: Go to "Settings" and hire more suppliers for %s.' );
mtidEvalBlockAvoidTradeCenter := TRegMultiString.Create( 'mtidEvalBlockAvoidTradeCenter', 'Hint: You are buying from a Trade Center. Find some local suppliers.' );
mtidEvalBlockBadWeatherCond := TRegMultiString.Create( 'mtidEvalBlockBadWeatherCond', 'There is nothing we can do about the weather but wait.' );
mtidEvalBlockNeedTechnology := TRegMultiString.Create( 'mtidEvalBlockNeedTechnology', 'Warning: Cannot operate until you research again %s.' );
mtidEvalBlockNeedsMoreCompSupplies := TRegMultiString.Create( 'mtidEvalBlockNeedsMoreCompSupplies', 'Warning: This facility is lacking services. Check the Services Tab on the INSPECT panel.' );
mtidSupplies := TRegMultiString.Create( 'mtidSupplies', 'supplies' );
mtidEvalBlockCloneMenu := TRegMultiString.Create('mtidEvalBlockCloneMenu', 'Price|%d|Suppliers|%d|Clients|%d|');
mtidEvalBlockProducing := TRegMultiString.Create('mtidEvalBlockProducing', 'Producing: ');
// Public
mtidTownNeedsMoreResidentials := TRegMultiString.Create( 'mtidTownNeedsMoreResidentials', 'Hint: This town requires more residentials for %s people.' );
mtidTownNeedsMoreCommerce := TRegMultiString.Create( 'mtidTownNeedsMoreCommerce', 'Hint: New stores and other services would encourage economic activity.' );
mtidTownHighUnemployment := TRegMultiString.Create( 'mtidTownHighUnemployment', 'Warning: There is a %d%% of unemployment in %s people.' );
mtidTownLowPublicService := TRegMultiString.Create( 'mtidTownLowPublicService', 'Warning: There is a problem with %s.' );
mtidPublicFacNeedsWorkers := TRegMultiString.Create( 'mtidPublicFacNeedsWorkers', 'Hint: You should attract more workers to this facility in case you want to rise its operation ratio.' );
mtidPublicFacNeedsSupport := TRegMultiString.Create( 'mtidPublicFacNeedsSupport', 'Hint: This facility needs more support from its headquarters.' );
mtidPubFacCov := TRegMultiString.Create( 'mtidPubFacCov', '%s coverage accross the city reported at %d%%.' );
mtidEmptyCity := TRegMultiString.Create( 'mtidEmptyCity', 'This city is not populated!' );
// Context status texts
mtidDesertedTown := TRegMultiString.Create( 'mtidDesertedTown', '%s is not populated. Invest here and the %s order will give you an aditional amount of money.' );
mtidPublicServiceNeeded := TRegMultiString.Create( 'mtidPublicServiceNeeded', 'Citizens of %s demand more %s.' );
mtidServiceNeeded := TRegMultiString.Create( 'mtidServiceNeeded', 'Citizens of %s demand more %s.' );
mtidVisitNewspaper := TRegMultiString.Create( 'mtidVisitNewspaper', 'For more information about %s visit %s, the local newspaper.' );
// Facility Descriptions
mtidDescResidential := TRegMultiString.Create( 'mtidDescResidential', '%s residential. %d inhabitants. %d%% resistent to crime, %d%% resistent to pollution. Design quality: %d%%.' );
mtidDescOffice := TRegMultiString.Create( 'mtidDescOffice', '%d offices to rent. Design quality: %d%%.' );
mtidDescFactoryHead := TRegMultiString.Create( 'mtidDescFactoryHead', 'Produces up to' );
mtidDescFactoryHeadN := TRegMultiString.Create( 'mtidDescFactoryHeadN', '%s of %s' );
mtidDescFactoryReq := TRegMultiString.Create( 'mtidDescFactoryReq', 'Requires' );
mtidDescFactoryReqN := TRegMultiString.Create( 'mtidDescFactoryReqN', '%s' );
mtidWorkCenterHead := TRegMultiString.Create( 'mtidWorkCenterHead', 'Employs:' );
mtidTechRequired := TRegMultiString.Create( 'mtidTechRequired', 'Requires research %s at %s.' );
mtidWHHead := TRegMultiString.Create( 'mtidWHHead', 'Stores up to ' );
mtidWCenterClone := TRegMultiString.Create( 'mtidWCenterClone', 'Salaries|%d|' );
mtidDescStoreInput := TRegMultiString.Create( 'mtidDescStoreInput', '%d %s of %s' );
mtidDescStoreResell1 := TRegMultiString.Create( 'mtidDescStoreResell1', 'Sells up to' );
mtidDescStoreTailStr := TRegMultiString.Create( 'mtidDescStoreTailStr', 'per level.' );
mtidDescStoreCombine1 := TRegMultiString.Create( 'mtidDescStoreCombine1', 'Buys up to' );
mtidDescStoreCombine2 := TRegMultiString.Create( 'mtidDescStoreCombine2', 'to serve %d customers maximum' );
// Alerts
mtidFacilityWillBeDemolished := TRegMultiString.Create( 'mtidFacilityWillBeDemolished', 'ATTENTION! THE MAYOR OF %s REQUESTED THE DEMOLITION OF THIS BUILDING DUE TO CITY PLANNING. DEMOLITION WILL TAKE PLACE IN %d MONTHS. THE IFEL WILL PAY YOU %s AS A COMPENSATION.' );
// Curriculum
mtidOwnershipReport := TRegMultiString.Create( 'mtidOwnershipReport', 'Controls %d companies, %d facilities, %d tiles in the map (%s in land taxes).' );
mtidResearchReport := TRegMultiString.Create( 'mtidResearchReport', '%d completed research items.' );
mtidWonElections := TRegMultiString.Create( 'mtidWonElections', 'Was elected Mayor of %s in the campaign of %d.' );
mtidWasMayor := TRegMultiString.Create( 'mtidWasMayor', 'Was Mayor of %s from %d to %d with a %d%% of popular rating.' );
mtidWasFiredFromMayor := TRegMultiString.Create( 'mtidWasFiredFromMayor', 'Was fired from Mayor of %s in %d.' );
mtidWasPresident := TRegMultiString.Create( 'mtidWasPresident', 'Was President of %s from %d to %d with a %d%% of popular rating.' );
mtidWonWorldElections := TRegMultiString.Create( 'mtidWonWorldElections', 'Was elected President of %s in the campaign of %d.' );
mtidWasMinister := TRegMultiString.Create( 'mtidWasMinister', 'Was Minister of %s from %d to %d with a %d%% of IFEL rating.' );
mtidAppointedMinister := TRegMultiString.Create( 'mtidAppointedMinister', 'Was appointed Minister of %s in the campaign of %d by %s.' );
mtidBankrupt := TRegMultiString.Create( 'mtidBankrupt', 'Was declared in bankrupty in %d' );
mtidTranscended := TRegMultiString.Create( 'mtidTransended', 'Transcended in %d' );
// Levels
mtidLevelAchieved := TRegMultiString.Create( 'mtidLevelAchieved', 'Achieved level %s in %d' );
mtidNotEnoughMoney := TRegMultiString.Create( 'mtidNotEnoughMoney', 'Could not upgrade level last year. You failed to pay $%.0n' );
mtidNotEnoughProfit := TRegMultiString.Create( 'mtidNotEnoughProfit', 'Could not upgrade level last year. You require an average profit ratio of $%.0n/h (last year you had $%.0n/h)' );
mtidMustHaveBeenMayor := TRegMultiString.Create( 'mtidMustHaveBeenMayor', 'You need to be elected Mayor at least once' );
mtidMustHaveBeenPresident := TRegMultiString.Create( 'mtidMustHaveBeenPresident', 'You need to be elected President at least once' );
mtidPrestigeRequired := TRegMultiString.Create( 'mtidPrestigeRequired', 'Could not upgrade level last year. You require %d prestige points' );
mtidNotEnoughPrestigeLostLevel := TRegMultiString.Create( 'mtidNotEnoughPrestigeLostLevel', 'Lost level %s in %d. You didn''t have the required %d prestige points' );
mtidNotEnoughProfitLostLevel := TRegMultiString.Create( 'mtidNotEnoughProfitLostLevel', 'Lost level %s in %d. You didn''t have the required average profit ratio of $%.0n/h (last year you had $%.0n/h)' );
mtidLevelLost := TRegMultiString.Create( 'mtidLevelLost', 'Lost level %s in %d.' );
// Misc
mtidJoinedWorld := TRegMultiString.Create( 'mtidJoinedWorld', 'Joined %s in %d' );
mtidAND := TRegMultiString.Create( 'mtidAND', 'and' );
// Events
mtidSetTaxes := TRegMultiString.Create( 'mtidSetTaxes', 'Mayor of %s set taxes for %s at %s%%.' );
mtidSubsidy := TRegMultiString.Create( 'mtidSubsidy', 'Mayor of %s set a subsidy for %s.' );
mtidLaunchedCampaign := TRegMultiString.Create( 'mtidLaunchedCampaign', '%s launched a campaign for %s.' );
mtidCancelledCampaign := TRegMultiString.Create( 'mtidCancelledCampaign', '%s withdrawed campaign for %s' );
mtidMayorElected := TRegMultiString.Create( 'mtidMayorElected', '%s was elected Mayor of %s.' );
mtidMayorReElected := TRegMultiString.Create( 'mtidMayorReElected', '%s was reelected Mayor of %s.' );
mtidCityHasNoMayor := TRegMultiString.Create( 'mtidCityHasNoMayor', '%s has no Mayor.' );
mtidMayorFired := TRegMultiString.Create( 'mtidMayorFired', '%s was fired from Mayor of %s.' );
mtidSubsidiesRemoved := TRegMultiString.Create( 'mtidSubsidiesRemoved', '%s removed its subsidies. Population is already greater than 9,000.' );
mtidTycoonBankrupt := TRegMultiString.Create( 'mtidTycoonBankrupt', '%s was declared bankrupt.' );
mtidFacBuilt := TRegMultiString.Create( 'mtidFacBuilt', '%s built %s near %s.' );
mtidAccountReset := TRegMultiString.Create( 'mtidAccountReset', '%s made an account reset.' );
mtidMsgJoinedWorld := TRegMultiString.Create( 'mtidMsgJoinedWorld', '%s joined %s.' );
mtidSatelliteUpdated := TRegMultiString.Create( 'mtidSatelliteUpdated', 'The satellite map of %s has been updated.' );
mtidMinisterElected := TRegMultiString.Create( 'mtidMinisterElected', '%s was appointed %s.' );
mtidPresidentElected := TRegMultiString.Create( 'mtidPresidentElected', '%s was elected President of %s' );
mtidPresidentReElected := TRegMultiString.Create( 'mtidPresidentReElected', '%s was reelected President of %s.' );
mtidNoPresident := TRegMultiString.Create( 'mtidNoPresident', '%s has no President.' );
mtidPresidenCampaignLaunched := TRegMultiString.Create( 'mtidPresidenCampaignLaunched', '%s launched a campaign for the Presidency of %s.' );
mtidPresidenCampaignCancelled := TRegMultiString.Create( 'mtidPresidenCampaignCancelled', '%s withdrawed campaign for Presidency of %s.' );
// Arrange later
mtidCiviHQPrest := TRegMultiString.Create( 'mtidCiviHQPrest', '%d prestige points from publicity.' );
mtidPubFacMain := TRegMultiString.Create( 'mtidPubFacMain', '%d%% operational.' );
mtidCapitolMain := TRegMultiString.Create( 'mtidCapitolMain', 'President: %s.' );
mtidCapitolWithPresSec := TRegMultiString.Create( 'mtidCapitolWithPresSec', 'President rated at %d%%. %d years to Elections.' );
mtidCapitolWithNoPresSec := TRegMultiString.Create( 'mtidCapitolWithNoPresSec', 'No President. %d years to Elections.' );
mtidCapitolHint := TRegMultiString.Create( 'mtidCapitolHint', 'Hint: If you have more than 1000 prestige points you can launch your campaign for the presidency of %s.' );
mtidTVMainOne := TRegMultiString.Create( 'mtidTVMainOne', '%d viewers' );
mtidTVMainTwo := TRegMultiString.Create( 'mtidTVMainTwo', '%d%% rating' );
mtidTVSec := TRegMultiString.Create( 'mtidTVSec', 'Broadcasting %d hours a day. %d%% of commercials. %d%% of commercials time sold. %d antennas worldwide. TV Station quality: %d%%, efficiency: %d%%' );
mtidHiringWorkForce := TRegMultiString.Create( 'mtidHiringWorkForce', 'Hiring workforce at %d%%' );
mtidHiringWorkForceSec := TRegMultiString.Create( 'mtidHiringWorkForceSec', '%s: %d of %d.' );
mtidTVWarning := TRegMultiString.Create( 'mtidTVWarning', 'WARNING: There are no antennas attached to this facility. Use the Connect button in the INSPECT panel to connect an antenna.' );
mtidAntenaAudience := TRegMultiString.Create( 'mtidAntenaAudience', 'Potential audience: %d.' );
mtidAntenaRating := TRegMultiString.Create( 'mtidAntenaRating', 'Channel rating: %d%%.' );
mtidAntenaHint := TRegMultiString.Create( 'mtidAntenaHint', 'HINT: Use the "Connect" button in the INSPECT panel to connect this antenna to a station.' );
mtidConstruction := TRegMultiString.Create( 'mtidConstruction', '%d%% completed.' );
mtidStoppedDueWeather := TRegMultiString.Create( 'mtidStoppedDueWeather', 'Stopped due to weather conditions.' );
mtidOfficeReport := TRegMultiString.Create( 'mtidOfficeReport', '%d offices rented. %d quality index. BAP: %d%%. Beauty: %d%%. Crime: %d%%. Pollution %d%%.' );
mtidOfficeTitle := TRegMultiString.Create( 'mtidOfficeTitle', 'Office Building' );
mtidOfficeOccup := TRegMultiString.Create( 'mtidOfficeOccup', '%d%% of offices rented' );
mtidWarehouseRepHead := TRegMultiString.Create( 'mtidWarehouseRepHead', 'Storing:' );
mtidWarehouseRepN := TRegMultiString.Create( 'mtidWarehouseRepN', '%s of %s at %d%% qualiy index.' );
mtidMinisterName := TRegMultiString.Create( 'mtidMinisterName', 'Minister of %s' );
mtidMinistryName := TRegMultiString.Create( 'mtidMinistryName', 'Ministry of %s' );
mtidCommerceMain := TRegMultiString.Create( 'mtidCommerceMain', '%s sales at %d%%' );
mtidOutputEvalFull := TRegMultiString.Create( 'mtidOutputEvalFull', '%s production: %d%%' );
mtidOutputEval := TRegMultiString.Create( 'mtidOutputEval', 'Producing: %d%%' );
mtidOutputSec := TRegMultiString.Create( 'mtidOutputSec', '%s of %s at %d%% quality index, %d%% efficiency' );
mtidInvPrice := TRegMultiString.Create( 'mtidInvPrice', 'Price: %s' );
mtidInvLicense := TRegMultiString.Create( 'mtidInvLicense', 'License: %s' );
mtidInvImpCostYear := TRegMultiString.Create( 'mtidInvImpCostYear', 'Implementation: %s a year/fac' );
mtidInvImpCostHour := TRegMultiString.Create( 'mtidInvImpCostHour', 'Implementation: %s/hour' );
mtidInvUsage := TRegMultiString.Create( 'mtidInvUsage', 'Facilities: %d' );
mtidInvNobPoints := TRegMultiString.Create( 'mtidInvNobPoints', 'Nobility: %s pts' );
mtidInvPrestige := TRegMultiString.Create( 'mtidInvPrestige', 'Prestige: %s pts' );
mtidInvLevel := TRegMultiString.Create( 'mtidInvLevel', 'Level: %s' );
mtidInvPayReduct := TRegMultiString.Create( 'mtidInvPayReduct', 'Payroll reduction: %s%%' );
mtidInvJobQ := TRegMultiString.Create( 'mtidInvJobQ', 'Job quality: %s%%' );
mtidInvBeauty := TRegMultiString.Create( 'mtidInvBeauty', 'Beauty: %s%%' );
mtidInvMaintenance := TRegMultiString.Create( 'mtidInvMaintenance', 'Maintenance: %s%%' );
mtidInvPrivacy := TRegMultiString.Create( 'mtidInvPrivacy', 'Privacy: %s%%' );
mtidInvCrimeRes := TRegMultiString.Create( 'mtidInvCrimeRes', 'Security: %s%%' );
mtidInvPollRes := TRegMultiString.Create( 'mtidInvPollRes', 'Environment: %s%%' );
mtidInvEff := TRegMultiString.Create( 'mtidInvEff', 'Efficiency: %s%%' );
mtidInvDesirability := TRegMultiString.Create( 'mtidInvDesirability', 'Desirability: %s pts' );
mtidInvQ := TRegMultiString.Create( 'mtidInvQ', 'Quality: %s pts' );
mtidOfficeClone := TRegMultiString.Create( 'mtidOfficeClone', 'Rent|%d|Maintenance|%d|' );
mtidPlayerWillTranscend := TRegMultiString.Create( 'mtidPlayerWillTranscend', 'Estimated date of Transcendence: %d days.' );
mtidBewareOfTranscend := TRegMultiString.Create( 'mtidBewareOfTranscend', 'WARNING! All facilities belonging to %s will disappear except this building. This may affect your facilities in this world.' );
mtidGrowingTrees := TRegMultiString.Create( 'mtidGrowingTrees', 'Growing trees at %d%%' );
mtidLicensingFilm := TRegMultiString.Create('mtidLicensingFilm', 'Licensing: "%s" Quality Index: %d%%.');
mtidFilmProject := TRegMultiString.Create('mtidFilmProject', 'Filming: "%s" Day %d of %d, %d%% done.');
mtidNowPlaying := TRegMultiString.Create('mtidNowPlaying', 'Now playing:');
mtidInvCatGeneral := TRegMultiString.Create('mtidInvCatGeneral', 'General');
mtidInvCatCommerce := TRegMultiString.Create('mtidInvCatCommerce', 'Commerce');
mtidInvCatIndustry := TRegMultiString.Create('mtidInvCatIndustry', 'Industry');
mtidInvCatRlEstate := TRegMultiString.Create('mtidInvCatRlEstate', 'Real Estate');
end;
initialization
InitMLS;
end.
|
unit ItemSkin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Menus, MGR32_Image,IdTypes,FastStream;
type
TFrmItemSkinEd = class(TForm)
LstItemSkin: TListBox;
Label1: TLabel;
MainMenu1: TMainMenu;
Files1: TMenuItem;
LoadItemSkins1: TMenuItem;
SaveItemSkins1: TMenuItem;
EdtSkinId: TEdit;
EdtSkinName: TEdit;
Label2: TLabel;
Label3: TLabel;
LstElem: TListBox;
Label4: TLabel;
ComboType: TComboBox;
ComboMouseCursor: TComboBox;
Label5: TLabel;
Label6: TLabel;
View: TMPaintBox32;
EdtSoundOpen: TEdit;
EdtSoundClose: TEdit;
Label7: TLabel;
Label8: TLabel;
PopupSkinList: TPopupMenu;
AddNewID1: TMenuItem;
N1: TMenuItem;
DuplicateID1: TMenuItem;
N2: TMenuItem;
DeleteID1: TMenuItem;
EdtColorMod: TEdit;
ComboColorFx: TComboBox;
Label9: TLabel;
Label10: TLabel;
EdtAnimDelay: TEdit;
Label11: TLabel;
Help1: TMenuItem;
DlgOpen: TOpenDialog;
DlgSave: TSaveDialog;
N3: TMenuItem;
ClearAll1: TMenuItem;
PopupElem: TPopupMenu;
DeleteSprite1: TMenuItem;
N4: TMenuItem;
ClearAllSprites1: TMenuItem;
GroupBox1: TGroupBox;
Label12: TLabel;
EdtOffX: TEdit;
Label13: TLabel;
EdtOffY: TEdit;
procedure FormResize(Sender: TObject);
procedure AddNewID1Click(Sender: TObject);
procedure LstItemSkinClick(Sender: TObject);
procedure EdtSkinIdChange(Sender: TObject);
procedure EdtSkinNameChange(Sender: TObject);
procedure ComboTypeChange(Sender: TObject);
procedure ComboMouseCursorChange(Sender: TObject);
procedure ComboColorFxChange(Sender: TObject);
procedure EdtAnimDelayChange(Sender: TObject);
procedure EdtSoundOpenChange(Sender: TObject);
procedure EdtSoundCloseChange(Sender: TObject);
procedure LoadItemSkins1Click(Sender: TObject);
procedure SaveItemSkins1Click(Sender: TObject);
PRocedure RefreshSkinList;
procedure DeleteID1Click(Sender: TObject);
procedure EdtColorModChange(Sender: TObject);
procedure LstElemDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
procedure LstElemDragDrop(Sender, Source: TObject; X, Y: Integer);
procedure LstElemClick(Sender: TObject);
Procedure FreeAllMemory;
procedure ClearAll1Click(Sender: TObject);
procedure DeleteSprite1Click(Sender: TObject);
procedure ClearAllSprites1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmItemSkinEd: TFrmItemSkinEd;
implementation
{$R *.dfm}
uses comctrls,udda,globals;
procedure TFrmItemSkinEd.FormResize(Sender: TObject);
begin
LstItemSkin.Height:=(FrmItemSkinEd.ClientHeight-LstItemSkin.Top)-4;
LstElem.Height:=(FrmItemSkinEd.ClientHeight-LstElem.Top)-4;
View.Width:= (FrmItemSkinEd.ClientWidth-View.Left)-4;
View.Height:= (FrmItemSkinEd.ClientHeight-View.Top)-4;
end;
procedure TFrmItemSkinEd.FreeAllMemory;
var Skin:PItemSkinInfo;
Frame:PFrame;
i,j:longint;
begin
for i:=0 to LstItemSkin.Count-1 do
begin
Skin:=PItemSkinInfo(LstItemSkin.Items.Objects[i]);
for j:=0 to Skin^.GraphInfo.Count-1 do
begin
Frame:=Skin^.GraphInfo.Items[j];
dispose(frame);
end;
Dispose(Skin);
end;
LstItemSkin.Clear;
LstElem.Clear;
end;
procedure TFrmItemSkinEd.LoadItemSkins1Click(Sender: TObject);
var Fst:TFastStream;
i,j,Count,Version:longint;
ItemSkin:PItemSkinInfo;
Frame:PFrame;
begin
If DlgOpen.Execute then
begin
LstItemSkin.Items.BeginUpdate;
FreeAllMemory;
Fst:=TFastStream.Create;
Fst.LoadFromFile(DlgOpen.FileName);
Version:=Fst.ReadLong;
Count:=Fst.ReadLong;
for i:=0 to Count-1 do
begin
new(ItemSkin);
ItemSkin.SkinName:=Fst.ReadWordString;
ItemSkin.SkinId:=fst.ReadWord;
ItemSkin.SkinType:=fst.ReadLong;
ItemSkin.MouseCursor:=Fst.ReadLong;
ItemSkin.ColorFx:=Fst.ReadLong;
ItemSkin.VertexColor:=Fst.ReadLong;
ItemSkin.AnimationDelay:=Fst.ReadSingle;
ItemSkin.OpenSound:=Fst.ReadWordString;
ItemSkin.CloseSound:=Fst.ReadWordString;
ItemSkin.GraphCount:=Fst.ReadLong;
ItemSkin.GraphInfo:=TList.create;
for j:=0 to ItemSkin.GraphCount-1 do
begin
new(Frame);
Frame.SpriteName:=Fst.ReadWordString;
Frame.Offx:=Fst.ReadWord;
Frame.Offy:=Fst.ReadWord;
ItemSkin.GraphInfo.Add(Frame);
end;
LstItemSkin.AddItem(ItemSkin^.SkinName+' : '+IntToStr(ItemSkin^.SkinId),TObject(ItemSkin));
end;
Fst.Free;
LstItemSkin.Items.EndUpdate;
end;
end;
procedure TFrmItemSkinEd.SaveItemSkins1Click(Sender: TObject);
var Fst:TFastStream;
i,j,Count,Version:longint;
ItemSkin:PItemSkinInfo;
Frame:PFrame;
begin
DlgSave.FileName:=DlgOpen.FileName;
If DlgSave.Execute then
begin
Fst:=TFastStream.Create;
Version:=1;
Fst.WriteLong(Version);
Count:=LstItemSkin.Count;
Fst.WriteLong(Count);
for i:=0 to Count-1 do
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[i]);
Fst.WriteWordString(ItemSkin.SkinName);
Fst.WriteWord(ItemSkin.SkinId);
Fst.WriteLong(ItemSkin.SkinType);
Fst.WriteLong(ItemSkin.MouseCursor);
Fst.WriteLong(ItemSkin.ColorFx);
Fst.WriteLong(ItemSkin.VertexColor);
Fst.WriteSingle(ItemSkin.AnimationDelay);
Fst.WriteWordString(ItemSkin.OpenSound);
Fst.WriteWordString(ItemSkin.CloseSound);
ItemSkin.GraphInfo.Pack;
ItemSkin.GraphCount:=ItemSkin.GraphInfo.Count;
Fst.WriteLong(ItemSkin.GraphCount);
for j:=0 to ItemSkin.GraphCount-1 do
begin
Frame:=PFrame(ItemSkin.GraphInfo.Items[j]);
Fst.WriteWordString(Frame.SpriteName);
Fst.WriteWord(Word(Frame.Offx));
Fst.WriteWord(Word(Frame.Offy));
end;
end;
Fst.WriteToFile(DlgSave.FileName);
Fst.Free;
end;
end;
procedure TFrmItemSkinEd.ClearAll1Click(Sender: TObject);
begin
FreeAllMemory;
end;
procedure TFrmItemSkinEd.AddNewID1Click(Sender: TObject);
var NewSkin:PItemSkinInfo;
begin
New(NewSkin);
NewSkin.SkinName:='New Skin';
NewSkin.SkinId:=0;
NewSkin.VertexColor:=$FFFFFFFF;
NewSkin.GraphCount:=0;
NewSkin.AnimationDelay:=0.066;
NewSkin.SkinType:=0;
NewSkin.MouseCursor:=0;
NewSkin.ColorFx:=0;
NewSkin.GraphCount:=0;
NewSkin.GraphInfo:=TList.Create;
LstItemSkin.AddItem('0 : New Skin',TOBject(NewSkin));
end;
procedure TFrmItemSkinEd.DeleteID1Click(Sender: TObject);
var Skin:PItemSkinInfo;
Frame:PFrame;
i:longint;
begin
if LstItemSkin.ItemIndex>=0 then
begin
Skin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
for i:=0 to Skin.GraphInfo.Count-1 do
begin
Frame:=Skin.GraphInfo.Items[i];
dispose(frame);
end;
LstItemSkin.DeleteSelected;
LstElem.Clear;
Skin.GraphInfo.Free;
Dispose(Skin);
end;
end;
procedure TFrmItemSkinEd.DeleteSprite1Click(Sender: TObject);
var Skin:PItemSkinInfo;
Frame:PFrame;
begin
if LstItemSkin.ItemIndex>=0 then
if LstElem.ItemIndex>=0 then
begin
Skin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
Frame:=PFrame(LstElem.Items.Objects[LstElem.ItemIndex]);
Skin.GraphInfo.Remove(Frame);
Skin.GraphInfo.Pack;
Dispose(Frame);
LstElem.DeleteSelected;
end;
end;
procedure TFrmItemSkinEd.ClearAllSprites1Click(Sender: TObject);
var Skin:PItemSkinInfo;
Frame:PFrame;
i:longint;
begin
if LstItemSkin.ItemIndex>=0 then
begin
Skin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
for i:=0 to Skin.GraphInfo.Count-1 do
begin
Frame:=PFrame(Skin.GraphInfo.Items[i]);
Dispose(Frame);
end;
LstElem.Clear;
Skin.GraphInfo.Clear;
end;
end;
procedure TFrmItemSkinEd.LstElemDragDrop(Sender, Source: TObject; X, Y: Integer);
var TempList:TList;
i:integer;
Tree:TTreeView;
Frame:PFrame;
Skin:PItemSkinInfo;
begin //drag a list of graph from the graph editor
Tree:=TTreeView(Source);
if (Tree.SelectionCount>0) and (LstItemSkin.ItemIndex>=0 )then //we got something selected (sanity check)
begin
Skin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
for i:=0 to Tree.SelectionCount-1 do
begin
if Tree.Selections[i].ImageIndex=1 then //reject directory
begin
new(Frame);
Frame^.SpriteName:=Tree.Selections[i].Text;
Frame^.Offx:=0;
Frame^.Offy:=0;
GetSpriteOffset(Frame^.SpriteName,Frame^.Offx,Frame^.Offy,0);
Skin.GraphInfo.Add(Frame);
inc(Skin.GraphCount);
end;
end;
LstItemSkinClick(nil);
end;
end;
procedure TFrmItemSkinEd.LstElemDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean);
var Tree:TTreeView;
begin
Accept:=false;
if Source is TTreeView then
begin
Tree:=TTreeView(Source);
if Tree.Tag=2 then
Accept:=true else
Accept:=false;
end;
end;
procedure TFrmItemSkinEd.LstItemSkinClick(Sender: TObject);
var ItemSkin:PItemSkinInfo;
Frame:PFrame;
i:longint;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
EdtSkinName.Text:=ItemSkin.SkinName;
EdtSkinId.Text:=IntToStr(ITemSkin.SkinId);
ComboType.ItemIndex:=ITemSkin.SkinType;
ComboMouseCursor.ItemIndex:=ITemSkin.MouseCursor;
ComboColorFx.ItemIndex:=ITemSkin.ColorFx;
EdtColorMod.Text:=IntToHex(ITemSkin.VertexColor,8);
EdtAnimDelay.Text:=IntToStr(round(ITemSkin.AnimationDelay*1000));
EdtSoundOpen.Text:=ITemSkin.OpenSound;
EdtSoundClose.Text:=ItemSkin.CloseSound;
LstElem.Clear;
for i:=0 to ItemSkin.GraphInfo.Count-1 do
begin
Frame:=PFrame(ItemSkin.GraphInfo.Items[i]);
LstElem.AddItem(Frame.SpriteName,TObject(Frame));
end;
end;
end;
procedure TFrmItemSkinEd.LstElemClick(Sender: TObject);
var Surface:PCardinal;
Sprite:PSprite;
ItemSkin:PItemSkinInfo;
Frame:PFrame;
begin
if LstItemSkin.ItemIndex>=0 then
if LstElem.ItemIndex>=0 then
begin
ItemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
Frame:=PFrame(LstElem.Items.Objects[LstElem.ItemIndex]);
EdtOffX.Text:=IntToStr(Frame^.Offx);
EdtOffy.Text:=IntToStr(Frame^.Offy);
Sprite:=Index.SpriteHash.SearchByName(Frame^.SpriteName);
if Sprite=nil then
exit;
Surface:=GetSpriteA8R8G8B8Surface(Sprite);
DrawA8R8G8B8(Surface,Sprite^.Width,Sprite^.Height,Frame^.Offx-16,Frame^.Offy-8,0,1,ItemSkin^.VertexColor,ItemSkin^.ColorFx,View);
FreeMem(Surface);
end;
end;
procedure TFrmItemSkinEd.RefreshSkinList;
var i:longint;
ItemSkin:PItemSkinInfo;
begin
LstItemSkin.Items.BeginUpdate;
LstItemSkin.Clear;
for i:=0 to LstItemSkin.Count-1 do
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[i]);
LstItemSkin.Items.AddObject(IntToStr(ITemSkin.SkinId)+' : '+ITemSkin.SkinName,TObject(ItemSkin));
end;
LstItemSkin.Items.EndUpdate;
end;
procedure TFrmItemSkinEd.ComboColorFxChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.ColorFx:=ComboColorFx.ItemIndex;
end;
end;
procedure TFrmItemSkinEd.ComboMouseCursorChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.MouseCursor:=ComboMouseCursor.ItemIndex;
end;
end;
procedure TFrmItemSkinEd.ComboTypeChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.SkinType:=ComboType.ItemIndex;
end;
end;
procedure TFrmItemSkinEd.EdtAnimDelayChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.AnimationDelay:=StrToInt(EdtAnimDelay.Text)/1000;
end;
end;
procedure TFrmItemSkinEd.EdtColorModChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.VertexColor:=HexToint(EdtColorMod.Text);
end;
end;
procedure TFrmItemSkinEd.EdtSkinIdChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if EdtSkinId.Text='' then exit;
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.SkinId:=StrToInt(EdtSkinId.Text);
LstItemSkin.Items[LstItemSkin.ItemIndex]:=ItemSkin^.SkinName+' : '+IntToStr(ItemSkin^.SkinId);
end;
end;
procedure TFrmItemSkinEd.EdtSkinNameChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.SkinName:=EdtSkinName.Text;
LstItemSkin.Items[LstItemSkin.ItemIndex]:=ItemSkin^.SkinName+' : '+IntToStr(ItemSkin^.SkinId);
end;
end;
procedure TFrmItemSkinEd.EdtSoundCloseChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.CloseSound:=EdtSoundClose.Text;
end;
end;
procedure TFrmItemSkinEd.EdtSoundOpenChange(Sender: TObject);
var ItemSkin:PItemSkinInfo;
begin
if LstItemSkin.ItemIndex>=0 then
begin
ITemSkin:=PItemSkinInfo(LstItemSkin.Items.Objects[LstItemSkin.ItemIndex]);
ITemSkin.OpenSound:=EdtSoundOpen.Text;
end;
end;
end.
|
unit G2Mobile.Model.Usuarios;
interface
uses
FMX.ListView,
uDmDados,
uRESTDWPoolerDB,
System.SysUtils,
IdSSLOpenSSLHeaders,
FireDAC.Comp.Client,
FMX.Dialogs,
FMX.ListView.Appearances,
FMX.ListView.Types,
System.Classes,
Datasnap.DBClient,
FireDAC.Comp.DataSet,
Data.DB,
G2Mobile.Controller.Usuarios,
FMX.Objects,
Form_Mensagem,
uFrmUtilFormate;
type
TModelUsuarios = class(TInterfacedObject, iModelUsuarios)
private
FUsuario: String;
FSenha : String;
public
constructor create;
destructor destroy; override;
class function new: iModelUsuarios;
function Usuario(value: String): iModelUsuarios;
function Senha(value: String): iModelUsuarios;
function BuscaUserServidor(ADataSet: TFDMemTable): iModelUsuarios;
function PopulaUserSqLite(ADataSet: TFDMemTable): iModelUsuarios;
function LimpaTabelaUser: iModelUsuarios;
function ValidaLogin: iModelUsuarios;
end;
implementation
{ TModelUsuarios }
class function TModelUsuarios.new: iModelUsuarios;
begin
result := self.create;
end;
constructor TModelUsuarios.create;
begin
end;
destructor TModelUsuarios.destroy;
begin
inherited;
end;
function TModelUsuarios.Senha(value: String): iModelUsuarios;
begin
result := self;
FSenha := value;
end;
function TModelUsuarios.Usuario(value: String): iModelUsuarios;
begin
result := self;
FUsuario := value;
end;
function TModelUsuarios.LimpaTabelaUser: iModelUsuarios;
var
qry: TFDQuery;
begin
result := self;
try
qry := TFDQuery.create(nil);
qry.Connection := DmDados.ConexaoInterna;
qry.FetchOptions.RowsetSize := 50000;
qry.Active := false;
qry.SQL.Clear;
qry.ExecSQL('DELETE FROM USUARIOS')
finally
FreeAndNil(qry);
end;
end;
function TModelUsuarios.BuscaUserServidor(ADataSet: TFDMemTable): iModelUsuarios;
var
rdwSQLTemp: TRESTDWClientSQL;
begin
result := self;
try
rdwSQLTemp := TRESTDWClientSQL.create(nil);
rdwSQLTemp.DataBase := DmDados.RESTDWDataBase1;
rdwSQLTemp.BinaryRequest := True;
rdwSQLTemp.FormatOptions.MaxStringSize := 10000;
rdwSQLTemp.Active := false;
rdwSQLTemp.SQL.Clear;
rdwSQLTemp.SQL.Add
('select cod_user, usuario, nome, senha, ISNULL(cod_vend, 0) as cod_vendedor, ISNULL(cod_camara, 0) as cod_camara, super from t_usuarios');
rdwSQLTemp.Active := True;
rdwSQLTemp.RecordCount;
ADataSet.CopyDataSet(rdwSQLTemp, [coStructure, coRestart, coAppend]);
finally
FreeAndNil(rdwSQLTemp);
end;
end;
function TModelUsuarios.PopulaUserSqLite(ADataSet: TFDMemTable): iModelUsuarios;
var
i : Integer;
qry: TFDQuery;
begin
result := self;
qry := TFDQuery.create(nil);
qry.Connection := DmDados.ConexaoInterna;
qry.FetchOptions.RowsetSize := 50000;
ADataSet.First;
try
qry.Active := false;
for i := 0 to ADataSet.RecordCount - 1 do
begin
qry.SQL.Clear;
qry.SQL.Add(' INSERT INTO USUARIOS ( COD_USER, USUARIO, NOME, SENHA, COD_VENDEDOR, SUPER, COD_CAMARA) VALUES ' +
'( :COD_USER, :USUARIO, :NOME, :SENHA, :COD_VENDEDOR, :SUPER, :COD_CAMARA)');
qry.ParamByName('COD_USER').AsInteger := ADataSet.FieldByName('COD_USER').AsInteger;
qry.ParamByName('USUARIO').AsString := ADataSet.FieldByName('USUARIO').AsString;
qry.ParamByName('NOME').AsString := ADataSet.FieldByName('NOME').AsString;
qry.ParamByName('SENHA').AsString := ADataSet.FieldByName('SENHA').AsString;
qry.ParamByName('COD_VENDEDOR').AsInteger := ADataSet.FieldByName('COD_VENDEDOR').AsInteger;
qry.ParamByName('SUPER').AsInteger := ADataSet.FieldByName('SUPER').AsInteger;
qry.ParamByName('COD_CAMARA').AsInteger := ADataSet.FieldByName('COD_CAMARA').AsInteger;
qry.ExecSQL;
ADataSet.Next;
end;
finally
FreeAndNil(qry);
end;
end;
function TModelUsuarios.ValidaLogin: iModelUsuarios;
var
qry: TFDQuery;
begin
result := self;
try
qry := TFDQuery.create(nil);
qry.Connection := DmDados.ConexaoInterna;
qry.FetchOptions.RowsetSize := 50000;
qry.Active := false;
qry.SQL.Clear;
qry.SQL.Add('SELECT * FROM USUARIOS WHERE USUARIO = :USUARIO AND SENHA = :SENHA');
qry.ParamByName('USUARIO').AsString := FUsuario;
qry.ParamByName('SENHA').AsString := FSenha;
qry.open;
CodVend := qry.FieldByName('COD_VENDEDOR').AsInteger;
codUser := qry.FieldByName('COD_USER').AsInteger;
SuperUser := qry.FieldByName('SUPER').AsInteger;
NomeUsuario := qry.FieldByName('NOME').AsString;
if qry.RecordCount = 0 then
begin
Exibir_Mensagem('ERRO', 'ALERTA', 'Erro', 'Usuario ou senha invalido!', 'OK', '', $FFDF5447, $FFDF5447);
Frm_Mensagem.Show;
abort;
end;
finally
FreeAndNil(qry);
end;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clNewsChecker;
interface
{$I clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, Windows, SysUtils,
{$ELSE}
System.Classes, Winapi.Windows, System.SysUtils,
{$ENDIF}
clDC, clMultiDC, clDownLoader, clDCUtils, clUtils, clResourceState;
type
TclOnIsNewsEvent = procedure (Sender: TObject; var IsNews, Handled: Boolean) of object;
TclNewsChecker = class;
TclNewsCheckerItem = class(TclSingleDownLoadItem)
private
FIsNewsExist: Boolean;
FIsNewsMode: Boolean;
function HasNews: Boolean;
function GetNewsChecker(): TclNewsChecker;
protected
procedure InternalStart(AIsGetResourceInfo: Boolean); override;
procedure ProcessCompleted(AThreader: TclCustomThreader); override;
procedure DoGetResourceInfo(AResourceInfo: TclResourceInfo); override;
procedure ControlChanged(); override;
procedure NewsExist(); virtual;
procedure IsNews(var IsNews, Handled: Boolean); virtual;
end;
TclNewsChecker = class(TclDownLoader)
private
FOnIsNews: TclOnIsNewsEvent;
FOnNewsExist: TNotifyEvent;
function GetIsNewsExist: Boolean;
protected
procedure DoIsNews(var IsNews, Handled: Boolean); dynamic;
procedure DoNewsExist; dynamic;
function GetInternetItemClass(): TclInternetItemClass; override;
public
constructor Create(AOwner: TComponent); override;
property IsNewsExist: Boolean read GetIsNewsExist;
published
property OnIsNews: TclOnIsNewsEvent read FOnIsNews write FOnIsNews;
property OnNewsExist: TNotifyEvent read FOnNewsExist write FOnNewsExist;
end;
implementation
{ TclNewsCheckerItem }
procedure TclNewsCheckerItem.ControlChanged();
begin
inherited ControlChanged();
if not IsBusy then
begin
FIsNewsExist := False;
end;
end;
procedure TclNewsCheckerItem.DoGetResourceInfo(AResourceInfo: TclResourceInfo);
begin
inherited DoGetResourceInfo(AResourceInfo);
FIsNewsExist := False;
if FIsNewsMode then
begin
FIsNewsExist := HasNews();
if not FIsNewsExist then
begin
Stop();
end;
end;
end;
procedure TclNewsCheckerItem.IsNews(var IsNews, Handled: Boolean);
begin
GetNewsChecker().DoIsNews(IsNews, Handled);
end;
function TclNewsCheckerItem.GetNewsChecker: TclNewsChecker;
begin
Result := (Control as TclNewsChecker);
end;
procedure TclNewsCheckerItem.InternalStart(AIsGetResourceInfo: Boolean);
begin
FIsNewsMode := not AIsGetResourceInfo;
inherited InternalStart(AIsGetResourceInfo);
end;
{$IFDEF DELPHI6}
{$WARNINGS OFF}
{$ENDIF}
function TclNewsCheckerItem.HasNews: Boolean;
var
h: THandle;
Handled: Boolean;
pTime: TFileTime;
p: DWORD;
hSize, pp: Int64;
begin
Result := False;
Handled := False;
IsNews(Result, Handled);
if (ResourceInfo = nil) or (Errors.Count > 0) or Handled then Exit;
h := CreateFile(PChar(LocalFile), GENERIC_READ, FILE_SHARE_READ, nil,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (h <> INVALID_HANDLE_VALUE);
if Result then
begin
hSize := GetFileSize(h, @p);
pp := p;
hSize := hSize or (pp shl 32);
Result := GetFileTime(h, nil, nil, @pTime) and (hSize > - 1);
if Result then
begin
Result := (Int(ConvertFileTimeToDateTime(pTime)) = Int(ResourceInfo.Date)) and (hSize = ResourceInfo.Size);
end;
end;
if (h <> INVALID_HANDLE_VALUE) then
begin
CloseHandle(h);
end;
Result := not Result;
end;
{$IFDEF DELPHI6}
{$WARNINGS ON}
{$ENDIF}
procedure TclNewsCheckerItem.NewsExist();
begin
GetNewsChecker().DoNewsExist();
end;
procedure TclNewsCheckerItem.ProcessCompleted(AThreader: TclCustomThreader);
begin
inherited ProcessCompleted(AThreader);
if not IsBusy and FIsNewsMode then
begin
FIsNewsMode := False;
if (ResourceState.LastStatus = psSuccess) and FIsNewsExist then
begin
NewsExist();
end;
end;
end;
{ TclNewsChecker }
function TclNewsChecker.GetInternetItemClass: TclInternetItemClass;
begin
Result := TclNewsCheckerItem;
end;
procedure TclNewsChecker.DoNewsExist;
begin
if Assigned(FOnNewsExist) then
begin
FOnNewsExist(Self);
end;
end;
procedure TclNewsChecker.DoIsNews(var IsNews, Handled: Boolean);
begin
if Assigned(FOnIsNews) then
begin
FOnIsNews(Self, IsNews, Handled);
end;
end;
function TclNewsChecker.GetIsNewsExist: Boolean;
begin
Result := (GetInternetItem() as TclNewsCheckerItem).FIsNewsExist;
end;
constructor TclNewsChecker.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
CorrectResourceTime := True;
end;
end.
|
unit Solid.Samples.OCP.Book.Ok;
interface
uses
System.SysUtils;
type
{ TBookEntity }
TBookEntity = class
private
FAuthor: string;
FPageCount: Integer;
FTitle: string;
procedure SetAuthor(const AValue: string);
procedure SetPageCount(const AValue: Integer);
procedure SetTitle(const AValue: string);
public
property Author: string read FAuthor write SetAuthor;
property PageCount: Integer read FPageCount write SetPageCount;
property Title: string read FTitle write SetTitle;
end;
{ IBookPrinter }
IBookPrinter = interface
['{3F64DE79-C32C-4940-BD86-099A6A1A404E}']
procedure Print(ABook: TBookEntity; APage: Integer = 0);
end;
{ IBookPersistor }
IBookPersistor = interface
['{41115130-5879-44A5-BA27-D87F338EE666}']
procedure Save(ABook: TBookEntity; APage: Integer = 0);
end;
{ TBookStand }
TBookStand = class
private
FCurrentBook: TBookEntity;
FCurrentPage: Integer;
procedure SetCurrentBook(AValue: TBookEntity);
procedure SetCurrentPage(AValue: Integer);
function HasBook: Boolean;
public
property CurrentBook: TBookEntity read FCurrentBook write SetCurrentBook;
property CurrentPage: Integer read FCurrentPage write SetCurrentPage;
procedure OpenNewBook(ABook: TBookEntity);
procedure CloseBook;
procedure NextPage();
procedure PriorPage();
procedure Print(APrinter: IBookPrinter; APage: Integer = 0);
procedure Save(APersistor: IBookPersistor; APage: Integer = 0);
end;
{ TBookPaperPrinter }
TBookPaperPrinter = class(TInterfacedObject, IBookPrinter)
public
procedure Print(ABook: TBookEntity; APage: Integer = 0);
end;
{ TBookHtmlPrinter }
TBookHtmlPrinter = class(TInterfacedObject, IBookPrinter)
public
procedure Print(ABook: TBookEntity; APage: Integer = 0);
end;
{ TBookDbPersistor }
TBookDbPersistor = class(TInterfacedObject, IBookPersistor)
private
FConnectionString: string;
public
constructor Create(const AConnectionString: string);
procedure Save(ABook: TBookEntity; APage: Integer = 0);
end;
{ TBookRestPersistor }
TBookRestPersistor = class(TInterfacedObject, IBookPersistor)
private
FEndpointUrl: string;
public
constructor Create(const AEndpointUrl: string);
procedure Save(ABook: TBookEntity; APage: Integer = 0);
end;
implementation
{ TBookEntity }
procedure TBookEntity.SetAuthor(const AValue: string);
begin
FAuthor := Trim(AValue);
end;
procedure TBookEntity.SetPageCount(const AValue: Integer);
begin
if FPageCount < 0 then
Exit;
FPageCount := AValue;
end;
procedure TBookEntity.SetTitle(const AValue: string);
begin
FTitle := Trim(AValue);
end;
{ TBookStand }
procedure TBookStand.CloseBook;
begin
SetCurrentBook(nil);
end;
function TBookStand.HasBook: Boolean;
begin
Result := FCurrentBook <> nil;
end;
procedure TBookStand.OpenNewBook(ABook: TBookEntity);
begin
SetCurrentBook(ABook);
end;
procedure TBookStand.Print(APrinter: IBookPrinter; APage: Integer = 0);
begin
if not HasBook then
raise Exception.Create('Book not opened');
if APrinter = nil then
raise Exception.Create('Printer is null');
APrinter.Print(FCurrentBook, APage);
end;
procedure TBookStand.PriorPage;
begin
if not HasBook then
Exit;
if FCurrentPage <= 1 then
Exit;
Dec(FCurrentPage);
end;
procedure TBookStand.Save(APersistor: IBookPersistor; APage: Integer = 0);
begin
if not HasBook then
raise Exception.Create('Book not opened');
if APersistor = nil then
raise Exception.Create('Persistor is null');
APersistor.Save(FCurrentBook, APage);
end;
procedure TBookStand.SetCurrentBook(AValue: TBookEntity);
begin
FCurrentBook := AValue;
if HasBook then
FCurrentPage := 1
else
FCurrentPage := 0;
end;
procedure TBookStand.SetCurrentPage(AValue: Integer);
begin
if AValue < 0 then
Exit;
if FCurrentBook = nil then
Exit;
if AValue > FCurrentBook.PageCount then
Exit;
FCurrentPage := AValue;
end;
procedure TBookStand.NextPage;
begin
if not HasBook then
Exit;
if FCurrentPage >= FCurrentBook.PageCount then
Exit;
Inc(FCurrentPage);
end;
{ TBookPaperPrinter }
procedure TBookPaperPrinter.Print(ABook: TBookEntity; APage: Integer);
begin
// TODO
end;
{ TBookHtmlPrinter }
procedure TBookHtmlPrinter.Print(ABook: TBookEntity; APage: Integer);
begin
// TODO
end;
{ TBookDbPersistor }
constructor TBookDbPersistor.Create(const AConnectionString: string);
begin
inherited Create;
FConnectionString := AConnectionString;
end;
procedure TBookDbPersistor.Save(ABook: TBookEntity; APage: Integer);
begin
// TODO
end;
{ TBookRestPersistor }
constructor TBookRestPersistor.Create(const AEndpointUrl: string);
begin
inherited Create;
FEndpointUrl := AEndpointUrl;
end;
procedure TBookRestPersistor.Save(ABook: TBookEntity; APage: Integer);
begin
// TODO
end;
end.
|
unit eInterestSimulator.Model.Simulador;
interface
uses
eInterestSimulator.Model.Interfaces;
type
TModelSimulador = class(TInterfacedObject, iSimulador)
private
FCapital: Real;
FTaxaJuros: Real;
FTotalParcelas: Integer;
FTipoSistema: TTypeSistema;
function Capital(Value: Real): iSimulador; overload;
function Capital: Real; overload;
function TaxaJuros(Value: Real): iSimulador; overload;
function TaxaJuros: Real; overload;
function TotalParcelas(Value: Integer): iSimulador; overload;
function TotalParcelas: Integer; overload;
function TipoSistema(Value: TTypeSistema): iSimulador; overload;
function TipoSistema: TTypeSistema; overload;
public
constructor Create;
destructor Destroy; override;
class function New: iSimulador;
end;
implementation
{ TModelSimulador }
function TModelSimulador.Capital: Real;
begin
Result := FCapital;
end;
function TModelSimulador.Capital(Value: Real): iSimulador;
begin
Result := Self;
FCapital := Value;
end;
constructor TModelSimulador.Create;
begin
end;
destructor TModelSimulador.Destroy;
begin
inherited;
end;
class function TModelSimulador.New: iSimulador;
begin
Result := Self.Create;
end;
function TModelSimulador.TaxaJuros: Real;
begin
Result := FTaxaJuros;
end;
function TModelSimulador.TipoSistema: TTypeSistema;
begin
Result := FTipoSistema;
end;
function TModelSimulador.TotalParcelas: Integer;
begin
Result := FTotalParcelas;
end;
function TModelSimulador.TotalParcelas(Value: Integer): iSimulador;
begin
Result := Self;
FTotalParcelas := Value;
end;
function TModelSimulador.TipoSistema(Value: TTypeSistema): iSimulador;
begin
Result := Self;
FTipoSistema := Value;
end;
function TModelSimulador.TaxaJuros(Value: Real): iSimulador;
begin
Result := Self;
FTaxaJuros := Value;
end;
end.
|
unit GX_ProofreaderKeyboard;
{$I GX_CondDefine.inc}
interface
function CharsAreNearOnKeyboard(const a, b: Char): Boolean;
var
KeysWithDistance1: array[1..50] of set of AnsiChar;
KeyboardChars, ShiftKeyboardChars, AltGrKeyboardChars: string;
implementation
uses
Windows, GX_GenericUtils, SysUtils;
function CharsAreNearOnKeyboard(const a, b: Char): Boolean;
var
p: ShortInt;
q: ShortInt;
begin
p := Pos(a, KeyboardChars);
if p = 0 then
p := Pos(a, ShiftKeyboardChars);
if p = 0 then
p := Pos(a, AltGrKeyboardChars); // FS: added
q := Pos(b, KeyboardChars);
if q = 0 then
q := Pos(b, ShiftKeyboardChars);
if q = 0 then
q := Pos(b, AltGrKeyboardChars); // FS: added
Result := (p > 0) and (q > 0) and CharInSet(KeyboardChars[q], KeysWithDistance1[p]);
end;
var
BarrierChars: set of AnsiChar;
Barriers, NextChars: string[6]; // FS: added
(*
InitKeySets builds a map of the user's keyboard in memory. It arranges
the key map such that is mirrors the keyboard device driver's picture of
the keyboard. Before adding this function, the key location map was
hardcoded and the calculations for keys that are "next to each other"
were off for many people.
> In particular, I am interested in the first half - that is that part/loop
> where
> j := VkKeyScan(Chr(i)); // char to virtual key
This loop builds a KeyBoardLayout array that mirrors the physical
location of keys on the keyboard. The first dimension in the array is
the shift state, and is one of (ksNormal, ksShift, ksAltGr). The second
dimension is the physical row of the key on the keyboard. The third and
last dimension is the physical column in that row for the key.
To perform the above, we need to find the locale specific virtual key
code for each of the printable ASCII characters from 33 to 254 that can
be "next to" other keys. The code then extracts the high and low order
bytes to get the shift state and the virtual key code to produce that
ASCII character. MapVirtualKey(lo(j), 0) is what maps the virtual key
code to the keyboard driver's scan code to determine the physical
position of that key on the keyboard. The case statement following
MapVirtualKey() checks the scan code and from that determines the "row"
the key is on for this keyboard, such that scan codes 1..13 are the
first row "QWERTYUIOP[]\" in most of our keyboards, 16..27 is row two,
or "ASDFGHJKL;'" on most keyboards, etc. Scan codes 41 (` and ~), 43 (\
and |) and 86 (?) have their locations set specially and I can only
assume they are special cases that don't follow standard scan code
ordering. The last if statement in the loop just makes sure we found a
useful mapping, and if we did, assign it to the KeyBoardLayout array if
the array spot isn't already filled.
*)
{$WARNINGS OFF}
procedure InitKeySets;
procedure IncludeInSet(iKeySet: Integer; Key: AnsiChar);
begin
if Key <> #32 then
KeysWithDistance1[iKeySet] := KeysWithDistance1[iKeySet] + [Key];
end;
const
ASCIIAlphaChars = ['A'..'Z', 'a'..'z'];
type
TKeyState = (ksNormal, ksShift, ksAltGr);
var
KeyBoardLayout: array[TKeyState] of array[1..4] of string[15];
i, j, Row, Column: Smallint;
aKeyState: TKeystate;
begin
Column := 0;
// Get layout as 4 rows of 11..13 keys in 3 states
// keyboard state could be Normal, Shift or AltGr (CTRL+ALT)
FillChar(KeyBoardLayout, SizeOf(KeyBoardLayout), #32);
for aKeyState := Low(TKeyState) to High(TKeyState) do
begin
KeyBoardLayout[aKeyState][1][0] := #13;
KeyBoardLayout[aKeyState][2][0] := #12;
KeyBoardLayout[aKeyState][3][0] := #12;
KeyBoardLayout[aKeyState][4][0] := #11;
end;
for i := 33 to 254 do
begin
j := VkKeyScan(Chr(i)); // char to virtual key
if Lo(j) > 0 then
begin
case Hi(j) of
0: aKeystate := ksNormal;
1: aKeystate := ksShift;
6: aKeystate := ksAltGr; // (CTRL+ALT)
else
Continue; // ignore other shift states
end;
begin
j := MapVirtualKey(lo(j), 0); // virtual key code to scan code
Row := 0;
case Lo(j) of
1..13:
begin
Row := 1;
Column := j;
end;
16..27:
begin
Row := 2;
Column := j - 15;
end;
30..40:
begin
Row := 3;
Column := j - 29;
end;
44..53:
begin
Row := 4;
Column := j - 42;
end;
41:
begin
Row := 1;
Column := 1;
end;
43:
begin
Row := 3;
Column := 12;
end;
86:
begin
Row := 4;
Column := 1;
end;
end;
if (Row > 0) and (KeyBoardLayout[aKeyState][Row][Column] = #32) then
KeyBoardLayout[aKeyState][Row][Column] := AnsiChar(i);
end;
end;
end;
KeyboardChars :=
KeyBoardLayout[ksNormal][1] +
KeyBoardLayout[ksNormal][2] +
KeyBoardLayout[ksNormal][3] +
KeyBoardLayout[ksNormal][4];
ShiftKeyboardChars :=
KeyBoardLayout[ksShift][1] +
KeyBoardLayout[ksShift][2] +
KeyBoardLayout[ksShift][3] +
KeyBoardLayout[ksShift][4];
AltGrKeyboardChars :=
KeyBoardLayout[ksAltgr][1] +
KeyBoardLayout[ksAltgr][2] +
KeyBoardLayout[ksAltgr][3] +
KeyBoardLayout[ksAltgr][4];
// Get keys with distance 1
for i := 1 to Length(KeyboardChars) do
begin
case i of
1:
begin
IncludeInSet(i, KeyBoardLayout[ksNormal][1][2]);
end;
2..13:
begin
IncludeInSet(i, KeyBoardLayout[ksNormal][1][i - 1]);
IncludeInSet(i, KeyBoardLayout[ksNormal][1][i + 1]);
IncludeInSet(i, KeyBoardLayout[ksNormal][2][i - 1]);
if i > 2 then
IncludeInSet(i, KeyBoardLayout[ksNormal][2][i - 2]);
end;
14..25:
begin
IncludeInSet(i, KeyBoardLayout[ksNormal][1][i + 1 - 13]);
IncludeInSet(i, KeyBoardLayout[ksNormal][1][i + 2 - 13]);
if i > 14 then
IncludeInSet(i, KeyBoardLayout[ksNormal][2][i - 1 - 13]);
IncludeInSet(i, KeyBoardLayout[ksNormal][2][i + 1 - 13]);
if i > 14 then
IncludeInSet(i, KeyBoardLayout[ksNormal][3][i - 1 - 13]);
IncludeInSet(i, KeyBoardLayout[ksNormal][3][i - 13]);
end;
26..37:
begin
IncludeInSet(i, KeyBoardLayout[ksNormal][2][i - 25]);
IncludeInSet(i, KeyBoardLayout[ksNormal][2][i + 1 - 25]);
if i > 26 then
IncludeInSet(i, KeyBoardLayout[ksNormal][3][i - 1 - 25]);
IncludeInSet(i, KeyBoardLayout[ksNormal][3][i + 1 - 25]);
if i > 26 then
IncludeInSet(i, KeyBoardLayout[ksNormal][4][i - 25]);
IncludeInSet(i, KeyBoardLayout[ksNormal][4][i + 1 - 25]);
end;
38..48:
begin
if i > 38 then
IncludeInSet(i, KeyBoardLayout[ksNormal][3][i - 38]);
IncludeInSet(i, KeyBoardLayout[ksNormal][3][i - 37]);
if i > 38 then
IncludeInSet(i, KeyBoardLayout[ksNormal][4][i - 1 - 37]);
IncludeInSet(i, KeyBoardLayout[ksNormal][4][i + 1 - 37]);
end;
end;
end;
// Get BarrierChars
BarrierChars := [];
Barriers := '';
NextChars := '';
for Row := 2 to 4 do
begin
for aKeyState := ksNormal to ksShift do
begin
Column := Length(KeyBoardLayout[aKeyState][Row]);
while (Column > 0) and not (KeyBoardLayout[aKeyState][Row][Column] in ASCIIAlphaChars) do
Dec(Column);
if (Column > 0) and (Column < Length(KeyBoardLayout[aKeyState][Row])) then
begin
BarrierChars := BarrierChars + [KeyBoardLayout[aKeyState][Row][Column]];
Barriers := Barriers + KeyBoardLayout[aKeyState][Row][Column];
NextChars := NextChars + KeyBoardLayout[aKeyState][Row][Column + 1];
end;
end;
end;
end;
{$WARNINGS ON}
initialization
InitKeySets;
end.
|
unit udmDadosNFSe;
interface
uses
Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient, DBAccess, IBC, MemDS, udmPadrao,
pnfsConversao, pcnConversao,
LibGeral, uMatVars, ACBrNFSeDANFSeClass, ACBrNFSeDANFSeFR, ACBrNFSe, ACBrCTe,ACBrDFeUtil,
ACBrBase, ACBrDFe, frxClass, ACBrDFeSSL;
type
TdmDadosNFSe = class(TdmPadrao)
qryManutencaoNRO_NF: TIntegerField;
qryManutencaoNRO_LOTE: TIntegerField;
qryManutencaoFILIAL: TStringField;
qryManutencaoCONVERTE: TIntegerField;
qryManutencaoSITUACAORPS: TStringField;
qryManutencaoTRIBUTACAO: TStringField;
qryManutencaoMOTIVOCANCELAMENTO: TStringField;
qryManutencaoCOD_CNAE: TStringField;
qryManutencaoCOD_SERVICO: TStringField;
qryManutencaoXML: TBlobField;
qryManutencaoSERIE: TStringField;
qryLocalizacaoNRO_NF: TIntegerField;
qryLocalizacaoNRO_LOTE: TIntegerField;
qryLocalizacaoSERIE: TStringField;
qryLocalizacaoFILIAL: TStringField;
qryLocalizacaoCONVERTE: TIntegerField;
qryLocalizacaoSITUACAORPS: TStringField;
qryLocalizacaoTRIBUTACAO: TStringField;
qryLocalizacaoMOTIVOCANCELAMENTO: TStringField;
qryLocalizacaoCOD_CNAE: TStringField;
qryLocalizacaoCOD_SERVICO: TStringField;
qryLocalizacaoXML: TBlobField;
qryManutencaoISSRETIDO: TStringField;
qryLocalizacaoISSRETIDO: TStringField;
qryManutencaoDESCRICAO_SERVICO: TStringField;
qryManutencaoDESCRICAO_CNAE: TStringField;
qryLocalizacaoDESCRICAO_SERVICO: TStringField;
qryLocalizacaoDESCRICAO_CNAE: TStringField;
qryFatura: TIBCQuery;
qryPrestador: TIBCQuery;
qryPrestadorNRO_NF: TIntegerField;
qryPrestadorNRO_LOTE: TIntegerField;
qryPrestadorSERIE: TStringField;
qryPrestadorFILIAL: TStringField;
qryPrestadorCONVERTE: TIntegerField;
qryPrestadorSITUACAORPS: TStringField;
qryPrestadorTRIBUTACAO: TStringField;
qryPrestadorMOTIVOCANCELAMENTO: TStringField;
qryPrestadorCOD_CNAE: TStringField;
qryPrestadorCOD_SERVICO: TStringField;
qryPrestadorXML: TMemoField;
qryPrestadorISSRETIDO: TStringField;
qryPrestadorDESCRICAO_SERVICO: TStringField;
qryPrestadorDESCRICAO_CNAE: TStringField;
ACBrNFSe1: TACBrNFSe;
ACBrNFSeDANFSeFR1: TACBrNFSeDANFSeFR;
CTe: TACBrCTe;
qryLocalizacaoNRO_RPS: TIntegerField;
qryManutencaoNRO_RPS: TIntegerField;
qryManutencaoCOD_CID_INCIDENCIA: TIntegerField;
qryLocalizacaoCOD_CID_INCIDENCIA: TIntegerField;
qryLocalizacaoNRO_PROTOCOLO: TStringField;
qryManutencaoNRO_PROTOCOLO: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure ACBrNFSe1StatusChange(Sender: TObject);
protected
procedure MontaSQLBusca(DataSet :TDataSet = Nil); override;
procedure MontaSQLRefresh; override;
private
FSQL_PADRAO: string;
FDigOperacao: Boolean;
FEmissora: string;
FNro_NF: Integer;
FDocFatura: string;
FFilFatura: string;
FAno: string;
FFatura: Real;
function GetSQL_PADRAO: string;
public
lstXML: TStrings;
// procedure SetarEmailDestino(AEmailDestinatario: string; lstEmailCC: TStrings);
procedure LerConfiguracao;
procedure LerConfiguracaoProdam;
procedure CarregarDadosPrestador;
procedure CarregarDadosTomador;
function LocalizarporFatura(FDocFatura,FFilFatura,FAno : string; FFatura: Real): Boolean;
function LocalizarVazio(DataSet: TDataSet = nil): Boolean;
function pegarSequencialRPS(AFilial: string): string;
property DigOperacao: Boolean read FDigOperacao write FDigOperacao;
property Emissora: string read FEmissora write FEmissora;
property Nro_NF: Integer read FNro_NF write FNro_NF;
property SQL_PADRAO: string read GetSQL_PADRAO;
end;
const
SQL_DAFAULT =
'SELECT ' +
' NFSE.NRO_NF, ' +
' NFSE.NRO_LOTE, ' +
' NFSE.SERIE, ' +
' NFSE.FILIAL, ' +
' NFSE.CONVERTE, ' +
' NFSE.SITUACAORPS, ' +
' NFSE.TRIBUTACAO, ' +
' NFSE.MOTIVOCANCELAMENTO, ' +
' NFSE.COD_CNAE, ' +
' NFSE.COD_SERVICO, ' +
' NFSE.XML, ' +
' NFSE.ISSRETIDO, ' +
' NFSE.NRO_RPS, ' +
' NFSE.COD_CID_INCIDENCIA, ' +
' NFSE.NRO_PROTOCOLO, ' + //UTILIZADO PARA PROVEDOR TINUS
' (SELECT FIRST (1) LS.DESCRICAO_SERVICO FROM TB_LISTASERVICO LS WHERE LS.COD_SERVICO = NFSE.COD_SERVICO) DESCRICAO_SERVICO, ' +
' (SELECT FIRST (1) CN.DESCRICAO_CNAE FROM TB_CNAE CN WHERE CN.COD_CNAE = NFSE.COD_CNAE) DESCRICAO_CNAE ' +
' FROM STWOPETNFSE NFSE ';
var
dmDadosNFSe: TdmDadosNFSe;
implementation
uses
udmPrincipal,
udmVariaveis,
udmCliente,
udmContatos,
udmConfigSMTP,
ufrmStatus;
{$R *.dfm}
function TdmDadosNFSe.LocalizarporFatura(FDocFatura, FFilFatura, FAno: string; FFatura: Real): Boolean;
begin
if qryFatura.Active then qryFatura.Close;
qryFatura.SQL.Text := '';
with qryFatura do
begin
SQL.Add('SELECT FIL_ORIG, NR_CTO FROM STWFATTFAT ');
SQL.Add('WHERE DOC_FATURA=:DOCFATURA AND FIL_FATURA=:FIL_FATURA ');
SQL.Add('AND FATURA=:FATURA AND ANO=:ANO AND TIPO_DOC=:TIPO_DOC');
Params[0].AsString := FDocFatura;
Params[1].AsString := FFilFatura;
Params[2].AsFloat := FFatura;
Params[3].AsString := FAno;
Params[4].AsString := 'NF';
Open;
end;
Result := not qryFatura.IsEmpty;
end;
function TdmDadosNFSe.LocalizarVazio(DataSet: TDataSet): Boolean;
begin
if DataSet = nil then
DataSet := qryLocalizacao;
with (DataSet as TIBCQuery) do
begin
Close;
SQL.Clear;
SQL.Add(SQL_DAFAULT);
SQL.Add(' WHERE 1 = 0');
Open;
Result := not IsEmpty;
end;
end;
procedure TdmDadosNFSe.DataModuleCreate(Sender: TObject);
var
str: TMemoryStream;
begin
inherited;
if not Assigned(dmConfigSMTP) then
dmConfigSMTP := TdmConfigSMTP.Create(Application);
lstXML := TStringList.Create;
str := TMemoryStream.Create;
RecuperarFR3('DANFSE_Tr2.fr3', str);
try
str.SaveToFile(ExtractFileDir(Application.ExeName)+'\Report\DANFSE_Tr2.fr3');
except
end;
str.Free;
str := nil;
end;
function TdmDadosNFSe.GetSQL_PADRAO: string;
begin
Result := SQL_DAFAULT;
end;
procedure TdmDadosNFSe.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do begin
SQL.Clear;
SQL.Add(SQL_DAFAULT);
SQL.Add('WHERE NFSE.FILIAL = :FILIAL AND NFSE.NRO_NF = :NRO_NF ');
SQL.Add('ORDER BY NFSE.FILIAL, NFSE.NRO_NF');
Params[0].AsString := FEmissora;
Params[1].AsInteger := FNro_NF;
end;
end;
procedure TdmDadosNFSe.MontaSQLRefresh;
begin
inherited;
with qryManutencao do
begin
SQL.Clear;
SQL.Add(SQL_DAFAULT);
SQL.Add('ORDER BY NFSE.FILIAL, NFSE.NRO_NF');
end;
end;
function TdmDadosNFSe.pegarSequencialRPS(AFilial: string): string;
begin
with qryManipulacao do
begin
SQL.Clear;
SQL.Add('SELECT COUNT (*) RPS_SEQUENCIAL FROM STWOPETNFSE WHERE FILIAL = :FILIAL AND ((CONVERTE = 1) or (NRO_LOTE > 0))');
ParamByName('FILIAL').AsString := AFilial;
Open;
result := IntToStr(qryManipulacao.FieldByName('RPS_SEQUENCIAL').asInteger + 1);
end;
end;
//teste
//procedure TdmDadosNFSe.SetarEmailDestino(AEmailDestinatario: string; lstEmailCC: TStrings);
//var
// I: Integer;
//begin
// with ProxyNFSe.ComponenteNFSe.EmailSettings do
// begin
// EmailDestinatario := AEmailDestinatario;
//
// for I := 0 to lstEmailCC.Count -1 do
// CC := CC + lstEmailCC[I] + ',';
// end;
//
// with NFSe.EmailSettings do
// begin
// EmailDestinatario := AEmailDestinatario;
//
// for I := 0 to lstEmailCC.Count -1 do
// CC := CC + lstEmailCC[I] + ',';
// end;
//end;
procedure TdmDadosNFSe.ACBrNFSe1StatusChange(Sender: TObject);
begin
inherited;
case ACBrNFSe1.Status of
stNFSeIdle : begin
if ( frmStatus <> nil ) then frmStatus.Hide;
end;
stNFSeRecepcao : begin
if ( frmStatus = nil )
then frmStatus := TfrmStatus.Create(Application);
frmStatus.lblStatus.Caption := 'Enviando dados da NFSe...';
frmStatus.Show;
frmStatus.BringToFront;
end;
stNFSeConsulta : begin
if ( frmStatus = nil )
then frmStatus := TfrmStatus.Create(Application);
frmStatus.lblStatus.Caption := 'Consultando...';
frmStatus.Show;
frmStatus.BringToFront;
end;
stNFSeCancelamento : begin
if ( frmStatus = nil )
then frmStatus := TfrmStatus.Create(Application);
frmStatus.lblStatus.Caption := 'Enviando cancelamento de NFSe...';
frmStatus.Show;
frmStatus.BringToFront;
end;
stNFSeEmail : begin
if ( frmStatus = nil )
then frmStatus := TfrmStatus.Create(Application);
frmStatus.lblStatus.Caption := 'Enviando Email...';
frmStatus.Show;
frmStatus.BringToFront;
end;
end;
Application.ProcessMessages;
end;
procedure TdmdadosNFSe.LerConfiguracao;
var
sPathPDF: String;
begin
if sCertDigitalCaminhoPFX <> '' then
begin
ACBrNFSe1.Configuracoes.Geral.SSLLib := libWinCrypt;
ACBrNFSe1.Configuracoes.Certificados.ArquivoPFX := sCertDigitalCaminhoPFX;
ACBrNFSe1.Configuracoes.Certificados.Senha := sCertDigitalSenha;
end;
ACBrNFSe1.Configuracoes.Certificados.NumeroSerie := sCertDigitalNumeroSerie;
ACBrNFSe1.Configuracoes.Arquivos.AdicionarLiteral := True;
ACBrNFSe1.Configuracoes.Arquivos.EmissaoPathNFSe := True;
ACBrNFSe1.Configuracoes.Arquivos.SepararPorMes := True;
ACBrNFSe1.Configuracoes.Arquivos.PathCan := sPathXML_NFSe;
ACBrNFSe1.Configuracoes.Arquivos.PathNFSe := sPathXML_NFSe;
ACBrNFSe1.Configuracoes.Arquivos.Salvar := True;
ACBrNFSe1.Configuracoes.Geral.PathIniCidades := sPathArqINI_NFSe;
ACBRNFSe1.Configuracoes.Geral.PathIniProvedor := sPathArqINI_NFSe;
ACBrNFSe1.Configuracoes.Geral.Salvar := True;
ACBrNFSe1.Configuracoes.Arquivos.PathSalvar := sPathXML_NFSe;
// PathMensal:=ACBrNFSe1.Configuracoes.Arquivos.GetPathNFSe(0);
ACBrNFSe1.Configuracoes.Geral.Emitente.CNPJ := LimpaString(dmVariaveis.qryManutencaoCGC.AsString, ' .-/');
ACBRNFSe1.Configuracoes.Geral.Emitente.InscMun := DesformataCNPJ(sNFSe_InscricaoMunicipal);
ACBrNFSe1.Configuracoes.Geral.CodigoMunicipio := dmVariaveis.qryManutencaoCOD_MUNICIPIO.AsInteger;
ACBrNFSe1.Configuracoes.Geral.Emitente.RazSocial := dmVariaveis.qryManutencaoNOME.AsString;
if lNFSeAmbienteTestes then
ACBrNFSe1.Configuracoes.WebServices.Ambiente := taHomologacao
else
ACBrNFSe1.Configuracoes.WebServices.Ambiente := taProducao;
// ACBrNFSe1.Configuracoes.WebServices.Visualizar := ckVisualizar.Checked;
// ACBrNFSe1.Configuracoes.WebServices.SenhaWeb := edtSenhaWeb.Text;
// ACBrNFSe1.Configuracoes.WebServices.UserWeb := edtUserWeb.Text;
// ACBrNFSe1.Configuracoes.WebServices.Salvar := ckSalvarSoap.Checked;
if sNFSeUsuarioWeb <> '' then
ACBrNFSe1.Configuracoes.Geral.UserWeb := sNFSeUsuarioWeb;
if sNFSeSenhaWeb <> '' then
ACBrNFSe1.Configuracoes.Geral.SenhaWeb := sNFSeSenhaWeb;
ACBrNFSe1.Configuracoes.WebServices.ProxyHost := sProxyServer;
ACBrNFSe1.Configuracoes.WebServices.ProxyPort := IntToStr(iProxyPort);
ACBrNFSe1.Configuracoes.WebServices.ProxyUser := sProxyUsername;
ACBrNFSe1.Configuracoes.WebServices.ProxyPass := sProxyPassword;
// ACBrNFSe1.Configuracoes.WebServices.Visualizar := True;
ACBrNFSe1.Configuracoes.Geral.SetConfigMunicipio();
ACBrNFSe1.Configuracoes.Arquivos.PathSchemas := PathWithDelim(sPathSchemas_NFSe) + ProvedorToStr(ACBrNFSe1.Configuracoes.Geral.Provedor);
sPathPDF := '';
sPathPDF := sPathPDF_NFSe;
ForceDirectories(PathWithDelim(sPathPDF) + FormatDateTime('yyyymm', Now));
sPathPDF := PathWithDelim(sPathPDF) + FormatDateTime('yyyymm', Now);
ACBrNFSe1.DANFSe.PathPDF := sPathPDF;
ACBrNFSe1.DANFSe.Usuario := sSnh_NmUsuario;
ACBrNFSe1.DANFSe.Sistema := 'www.americasoft.com.br';
ACBrNFSe1.DANFSe.NFSeCancelada := False;
ACBrNFSeDANFSeFR1.FastFile := PathWithDelim(ExtractFilePath(Application.ExeName)) + 'Report\DANFSE_Tr2.fr3';
if not lVisualizaNFSe then
ACBrNFSe1.DANFSe.MostrarPreview := false;
if FileExists(sPathLogo_Municipio) then
ACBrNFSeDANFSeFR1.Logo := sPathLogo_Municipio;//'C:\Componentes\XE3\acbr\Exemplos\ACBrNFSe\Delphi\Report\Brasao.jpg';
if FileExists(sCaminhoLogo_CTE) then
ACBrNFSeDANFSeFR1.PrestLogo := sCaminhoLogo_CTE; //'C:\Temp\America\Logo.JPG';
ACBrNFSeDANFSeFR1.Prefeitura := dmVariaveis.qryManutencaoCIDADE.AsString;
end;
procedure TdmDadosNFSe.LerConfiguracaoProdam;
var
PathMensal, sPathPDF: String;
begin
With dmDadosNFSe.ACBrNFSe1 do
Begin
Configuracoes.Arquivos.Salvar := True;
Configuracoes.WebServices.Salvar := True;
if sSnh_NmUsuario = 'AMERICA' then
Configuracoes.WebServices.Visualizar := True
else
Configuracoes.WebServices.Visualizar := False;
Configuracoes.WebServices.Tentativas := 5;
Configuracoes.Certificados.Senha := '';
end;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Certificados.NumeroSerie := sCertDigitalNumeroSerie;
sPathLog_NFSe := PathWithDelim(sPathSchemas_NFSe) + sSnh_Filial + '\LOG\';
sPathPDF := '';
sPathPDF := sPathPDF_NFSe;
ForceDirectories(PathWithDelim(sPathPDF) + FormatDateTime('yyyymm', Now));
sPathPDF := PathWithDelim(sPathPDF) + FormatDateTime('yyyymm', Now);
dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.CodigoMunicipio := dmVariaveis.qryManutencaoCOD_MUNICIPIO.AsInteger;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.AdicionarLiteral:=True;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.EmissaoPathNFSe:=True;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.SepararPorMes:=True;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.PathCan:=sPathXML_NFSe;;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.PathNFSe:=sPathXML_NFSe;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.Salvar:=True;
//PathMensal:=dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.GetPathNFSe(0);
dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.SetConfigMunicipio();
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.PathSchemas := PathWithDelim(sPathSchemas_NFSe) + ProvedorToStr(dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.Provedor);
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.Salvar := True;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Arquivos.PathSalvar := sPathXML_NFSe;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.CodigoMunicipio := StrToIntDef('3550308', 0);
//dmDadosNFSe.ACBrNFSe1.Configuracoes.WebServices.Ambiente := StrToTpAmb(Ok, IntToStr(rgTipoAmb.ItemIndex+1));
dmDadosNFSe.ACBrNFSe1.Configuracoes.WebServices.Ambiente := taproducao;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.SenhaWeb := '';//edtSenhaWeb.Text;
dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.UserWeb := '';//edtUserWeb.Text;
ACBrNFSe1.Configuracoes.WebServices.ProxyHost := sProxyServer;
ACBrNFSe1.Configuracoes.WebServices.ProxyPort := IntToStr(iProxyPort);
ACBrNFSe1.Configuracoes.WebServices.ProxyUser := sProxyUsername;
ACBrNFSe1.Configuracoes.WebServices.ProxyPass := sProxyPassword;
ACBrNFSe1.DANFSe.PathPDF := sPathPDF;
ACBrNFSe1.DANFSe.Usuario := sSnh_NmUsuario;
ACBrNFSe1.DANFSe.Sistema := 'www.americasoft.com.br';
ACBrNFSe1.DANFSe.NFSeCancelada := False;
if not lVisualizaNFSe then
ACBrNFSe1.DANFSe.MostrarPreview := false;
ACBrNFSeDANFSeFR1.FastFile := PathWithDelim(ExtractFilePath(Application.ExeName)) + 'Report\DANFSE_Tr2.fr3';
if FileExists(sPathLogo_Municipio) then
ACBrNFSeDANFSeFR1.Logo := sPathLogo_Municipio;//'C:\Componentes\XE3\acbr\Exemplos\ACBrNFSe\Delphi\Report\Brasao.jpg';
if FileExists(sCaminhoLogo_CTE) then
ACBrNFSeDANFSeFR1.PrestLogo := sCaminhoLogo_CTE; //'C:\Temp\America\Logo.JPG';
ACBrNFSeDANFSeFR1.Prefeitura := dmVariaveis.qryManutencaoCIDADE.AsString;
end;
procedure TdmDadosNFSe.CarregarDadosPrestador;
var
i: integer;
begin
if dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.Provedor = proIssDSF then
for I := 0 to ACBrNFSe1.NotasFiscais.Count - 1 do
with ACBrNFSe1.NotasFiscais.Items[i].NFSe do
begin
with PrestadorServico do
begin
IdentificacaoPrestador.Cnpj := dmVariaveis.qryManutencaoCGC.AsString;
IdentificacaoPrestador.InscricaoMunicipal := DesformataCNPJ(sNFSe_InscricaoMunicipal);
RazaoSocial := dmVariaveis.qryManutencaoNOME.AsString;
NomeFantasia := dmVariaveis.qryManutencaoNOME.AsString;
with Endereco do
begin
CodigoMunicipio := dmVariaveis.qryManutencaoCOD_MUNICIPIO.AsString;
Endereco := dmVariaveis.qryManutencaoENDERECO.AsString;
Numero := dmVariaveis.qryManutencaoEND_NRO.AsString;
Complemento := dmVariaveis.qryManutencaoEND_COMPL.AsString;
Bairro := dmVariaveis.qryManutencaoBAIRRO.AsString;
UF := dmVariaveis.qryManutencaoESTADO.AsString;
CEP := dmVariaveis.qryManutencaoCEP.AsString;
xMunicipio := dmVariaveis.qryManutencaoCIDADE.AsString;
CodigoPais := 1058;
end;
with Contato do
begin
Telefone := dmVariaveis.qryManutencaoTELEFONE_1.AsString;
Email := dmVariaveis.qryManutencaoEMAIL.AsString;
end;
end;
end;
if ACBrNFSe1.NotasFiscais.Count < 1 then
begin
if dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.Provedor = proSP then
begin
for I := 0 to dmDadosNFSe.ACBrNFSe1.WebServices.ConsLote.RetornoNFSe.ListaNfse.CompNFSe.Count - 1 do
begin
with dmDadosNFSe.ACBrNFSe1.WebServices.ConsLote.RetornoNFSe.ListaNfse.CompNfse.Items[i].Nfse do
begin
with PrestadorServico do
begin
IdentificacaoPrestador.Cnpj := dmVariaveis.qryManutencaoCGC.AsString;
IdentificacaoPrestador.InscricaoMunicipal := DesformataCNPJ(sNFSe_InscricaoMunicipal);
RazaoSocial := dmVariaveis.qryManutencaoNOME.AsString;
NomeFantasia := dmVariaveis.qryManutencaoNOME.AsString;
with Endereco do
begin
CodigoMunicipio := dmVariaveis.qryManutencaoCOD_MUNICIPIO.AsString;
Endereco := dmVariaveis.qryManutencaoENDERECO.AsString;
Numero := dmVariaveis.qryManutencaoEND_NRO.AsString;
Complemento := dmVariaveis.qryManutencaoEND_COMPL.AsString;
Bairro := dmVariaveis.qryManutencaoBAIRRO.AsString;
UF := dmVariaveis.qryManutencaoESTADO.AsString;
CEP := dmVariaveis.qryManutencaoCEP.AsString;
xMunicipio := dmVariaveis.qryManutencaoCIDADE.AsString;
CodigoPais := 1058;
end;
with Contato do
begin
Telefone := dmVariaveis.qryManutencaoTELEFONE_1.AsString;
Email := dmVariaveis.qryManutencaoEMAIL.AsString;
end;
end;
end;
end;
CarregarDadosTomador;
end;
end;
with dmDadosNFSe do
begin
Emissora := dmVariaveis.qryManutencaoFILIAL.AsString;
if (dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.Provedor = proSP) and (dmDadosNFSe.ACBrNFSe1.NotasFiscais.Count < 1) then
Nro_NF := StrToInt(dmDadosNFSe.ACBrNFSe1.WebServices.ConsLote.RetornoNFSe.ListaNfse.CompNfse.Items[0].Nfse.Numero)
else
Nro_NF := StrToInt(ACBrNFSe1.NotasFiscais.Items[0].NFSe.Numero);
Localizar(qryPrestador);
end;
//showMessage(intTostr(dmdadosNFse.qryLocalizacaoNro_NF.asInteger)+ #13 + ACBrNFSe1.NotasFiscais.Items[0].NFSe.Numero );
if ACBrNFSe1.NotasFiscais.Count < 1 then
begin
for I := 0 to dmDadosNFSe.ACBrNFSe1.WebServices.ConsLote.RetornoNFSe.ListaNfse.CompNFSe.Count - 1 do
begin
with dmDadosNFSe.ACBrNFSe1.WebServices.ConsLote.RetornoNFSe.ListaNfse.CompNfse.Items[i].Nfse do
begin
Servico.CodigoCnae := dmDadosNFSe.qryPrestadorDESCRICAO_CNAE.AsString;
if Servico.CodigoCnae = '' then
Servico.CodigoCnae := dmDadosNFSe.qryPrestadorDESCRICAO_SERVICO.AsString;
end;
end;
end;
for I := 0 to ACBrNFSe1.NotasFiscais.Count - 1 do
begin
with ACBrNFSe1.NotasFiscais.Items[i].NFSe do
begin
Servico.CodigoCnae := dmDadosNFSe.qryPrestadorDESCRICAO_CNAE.AsString;
if Servico.CodigoCnae = '' then
Servico.CodigoCnae := dmDadosNFSe.qryPrestadorDESCRICAO_SERVICO.AsString;
end;
end;
end;
procedure TdmDadosNFSe.CarregarDadosTomador;
var
I : integer;
begin
if dmDadosNFSe.ACBrNFSe1.Configuracoes.Geral.Provedor = proSP then
for I := 0 to dmDadosNFSe.ACBrNFSe1.WebServices.ConsLote.RetornoNFSe.ListaNfse.CompNFSe.Count - 1 do
with dmDadosNFSe.ACBrNFSe1.WebServices.ConsLote.RetornoNFSe.ListaNfse.CompNfse.Items[i].Nfse do
begin
with Tomador do
begin
with dmCliente do
begin
if length(IdentificacaoTomador.CpfCnpj) = 11 then
Cod_Cliente := FormataCPF(IdentificacaoTomador.CpfCnpj)
else
Cod_Cliente := FormataCNPJ(IdentificacaoTomador.CpfCnpj);
if Localizar then
begin
IdentificacaoTomador.CpfCnpj := dmCliente.qryLocalizacaoCGC.AsString;
RazaoSocial := dmCliente.qryLocalizacaoNOME.AsString;
with Endereco do
begin
Endereco := dmCliente.qryLocalizacaoENDERECO.AsString;
Numero := dmCliente.qryLocalizacaoEND_NRO.AsString;
Complemento := dmCliente.qryLocalizacaoEND_COMPL.AsString;
Bairro := dmCliente.qryLocalizacaoBAIRRO.AsString;
UF := dmCliente.qryLocalizacaoESTADO.AsString;
CEP := dmCliente.qryLocalizacaoCEP.AsString;
xMunicipio := dmCliente.qryLocalizacaoCIDADE.AsString;
end;
with Contato do
begin
Telefone := dmCliente.qryLocalizacaoTEL1.AsString;
with dmContatos do
begin
Cliente := dmCliente.qryLocalizacaoCGC.AsString;
Contato := 'NFS-E';
if Localizar then
Tomador.Contato.Email := dmContatos.qryLocalizacaoEMAIL.AsString
else
Tomador.Contato.Email := '';
end;
//Email := dmContatos.qryLocalizacaoEMAIL.AsString;
end;
end;
end;
end;
end;
end;
end.
|
unit FirebirdTools;
interface
uses IBX.IBDatabase, Data.DB, IBX.IBCustomDataSet, IBX.IBSQL, XSuperObject, Forms, SysUtils, IBX.IB;
type TFBTool = class(TObject)
public
FbDB : TIBDatabase;
FbDS : TIBDataSet;
FbDS2 : TIBDataSet;
FbSQL : TIBSQL;
ReadTrans : TIBTransaction;
UpdTrans : TIBTransaction;
Connected : boolean;
WrkMode : byte;
constructor Create(Params: ISuperObject = nil; WorkMode: Byte = 0; Log: Boolean = True);
function ConnectToDB(Log: Boolean = True): boolean;
procedure DisconnectFromDB(Log: Boolean = True);
function Select(Sql: string): TIBDataSet;
function Select2(Sql: string): TIBDataSet;
procedure Update(Sql: string);
procedure Drop(Log: Boolean = True);
function GetShutDownMode: Byte;
procedure StartTrans(Sql: string = '');
procedure CommitTrans;
procedure Execute;
function GetSQL: TIBSQL;
end;
const
fbSelect = 0;
fbUpdate = 1;
fbUpdateNotAuto = 2;
fbBooth = 3;
fbBoothNotAuto = 4;
implementation
uses Service;
function TFbTool.ConnectToDB(Log: Boolean = True): boolean;
begin
Result := False;
try
FbDB.Connected := True;
Result := True;
Connected := True;
if Log then
LogOut('Служба - Успешное подключение к базе данных - ' + FbDB.DatabaseName);
except
on E: Exception do
begin
LogOut('Ошибка подключения: ' + E.Message);
Application.ShowException(E);
LogOut('Служба - Не удалось подключиться к базе данных - ' + FbDB.DatabaseName);
end;
// MCore.StopService;
end;
end;
procedure TFbTool.DisconnectFromDB(Log: Boolean = True);
begin
FbDB.Connected := False;
Connected := False;
if Log then
LogOut('Служба - Отключение от базы данных - ' + FbDB.DatabaseName);
end;
constructor TFbTool.Create(Params: ISuperObject = nil; WorkMode: Byte = 0; Log: Boolean = True);
begin
Connected := False;
WrkMode := WorkMode;
if Params = nil then Params := DCore.DbParams;
FbDb := TIBDatabase.Create(nil);
FbDb.DatabaseName := Params.S['DB_NAME'];
FbDB.Connected := False;
FbDB.LoginPrompt := False;
FbDB.Params.Clear;
FbDB.Params.Add('user_name=' + Params.S['DB_USER']);
FbDB.Params.Add('password=' + Params.S['DB_PASS']);
FbDB.Params.Add('lc_ctype=win1251');
UpdTrans := nil;
ReadTrans := nil;
FbSQL := nil;
FbDS := nil;
FbDS2 := nil;
if WorkMode = fbUpdate then
begin
UpdTrans := TIBTransaction.Create(nil);
UpdTrans.DefaultDatabase := FbDB;
UpdTrans.Params.Add('isc_tpb_read_committed');
UpdTrans.Params.Add('isc_tpb_write'); // ??? Params.Add('isc_tpb_read');
UpdTrans.Params.Add('isc_tpb_rec_version');
UpdTrans.Params.Add('isc_tpb_nowait');
FbSQL := TIBSQL.Create(nil);
FbSQL.Transaction := UpdTrans;
FbSQL.Database := FbDB;
FbSQL.Close;
end;
if WorkMode = fbSelect then
begin
ReadTrans := TIBTransaction.Create(nil);
ReadTrans.DefaultDatabase := FbDB;
ReadTrans.Params.Add('isc_tpb_read_committed');
ReadTrans.Params.Add('isc_tpb_read'); // ??? Params.Add('isc_tpb_read');
ReadTrans.Params.Add('isc_tpb_rec_version');
ReadTrans.Params.Add('isc_tpb_nowait');
FbDS := TIBDataSet.Create(nil);
FbDS.Transaction := ReadTrans;
FbDS.Database := FbDB;
FbDS.Close;
FbDS2 := TIBDataSet.Create(nil);
FbDS2.Transaction := ReadTrans;
FbDS2.Database := FbDB;
FbDS2.Close;
end;
if (WorkMode = fbBooth) or (WorkMode = fbBoothNotAuto) then
begin
UpdTrans := TIBTransaction.Create(nil);
UpdTrans.DefaultDatabase := FbDB;
UpdTrans.Params.Add('isc_tpb_read_committed');
UpdTrans.Params.Add('isc_tpb_write'); // ??? Params.Add('isc_tpb_read');
UpdTrans.Params.Add('isc_tpb_rec_version');
UpdTrans.Params.Add('isc_tpb_nowait');
FbSQL := TIBSQL.Create(nil);
FbSQL.Transaction := UpdTrans;
FbSQL.Database := FbDB;
FbSQL.Close;
ReadTrans := TIBTransaction.Create(nil);
ReadTrans.DefaultDatabase := FbDB;
ReadTrans.Params.Add('isc_tpb_read_committed');
ReadTrans.Params.Add('isc_tpb_read'); // ??? Params.Add('isc_tpb_read');
ReadTrans.Params.Add('isc_tpb_rec_version');
ReadTrans.Params.Add('isc_tpb_nowait');
FbDS := TIBDataSet.Create(nil);
FbDS.Transaction := ReadTrans;
FbDS.Database := FbDB;
FbDS.Close;
FbDS2 := TIBDataSet.Create(nil);
FbDS2.Transaction := ReadTrans;
FbDS2.Database := FbDB;
FbDS2.Close;
end;
if ConnectToDB(Log) then Connected := True;
if GetShutDownMode = 1 then
begin
LogOut('Error connect to DB: DB is SHUTDOWN');
DisconnectFromDB(Log);
Connected := False;
end;
end;
function TFbTool.Select(Sql: string): TIBDataSet;
begin
Result := FbDS;
if Sql = '' then Exit;
try
FbDS.Close;
FbDS.SelectSQL.Text := Sql;
FbDS.Open;
Result := FbDS;
except
on E: Exception do
begin
LogOut('Ошибка при выполнении выборки: ' + E.Message);
if Pos('SHUTDOWN', AnsiUpperCase(E.Message)) > 0 then
begin
DCore.ShutDownMode := 1;
LogOut('ERROR DB in SHUTDOWN');
end;
end;
end;
end;
function TFbTool.GetShutDownMode: Byte;
var Sql: string;
begin
Result := 0;
Sql := 'select MON$SHUTDOWN_MODE from MON$DATABASE';
Select(Sql);
if FbDS.Eof then
Result := DCore.ShutDownMode
else
Result := FbDS.FieldValues['MON$SHUTDOWN_MODE'];
end;
function TFbTool.Select2(Sql: string): TIBDataSet;
begin
Result := FbDS2;
if Sql = '' then Exit;
try
FbDS2.Close;
FbDS2.SelectSQL.Text := Sql;
FbDS2.Open;
Result := FbDS2;
except
on E: Exception do
begin
LogOut(E.Message);
if Pos('SHUTDOWN', AnsiUpperCase(E.Message)) > 0 then
begin
DCore.ShutDownMode := 1;
LogOut('ERROR DB in SHUTDOWN');
end;
end;
end;
end;
procedure TFbTool.Update(Sql: string);
begin
if Sql = '' then Exit;
if (WrkMode = fbUpdate) or (WrkMode = fbBooth) then
begin
if UpdTrans.InTransaction then UpdTrans.Rollback;
UpdTrans.StartTransaction;
end;
try
FbSQL.Close;
FbSQL.SQL.Text := Sql;
FbSQL.ExecQuery;
if (WrkMode = fbUpdate) or (WrkMode = fbBooth) then
begin
UpdTrans.Commit;
end;
except
on E: Exception do
begin
LogOut(E.Message);
if Pos('SHUTDOWN', AnsiUpperCase(E.Message)) > 0 then
begin
DCore.ShutDownMode := 1;
LogOut('ERROR DB is SHUTDOWN');
end;
end;
end;
end;
procedure TFbTool.Drop(Log: Boolean = True);
begin
DisconnectFromDB(Log);
if UpdTrans <> nil then UpdTrans.Free;
if ReadTrans <> nil then ReadTrans.Free;
if FbDS <> nil then FbDS.Free;
if FbDS2 <> nil then FbDS2.Free;
if FbSQL <> nil then FbSQL.Free;
FbDB.Free;
Self.Free;
end;
procedure TFbTool.StartTrans(Sql: string = '');
begin
if UpdTrans.InTransaction then UpdTrans.Rollback;
UpdTrans.StartTransaction;
if Sql <> '' then
begin
FbSQL.Close;
FbSQL.SQL.Text := Sql;
end;
end;
procedure TFbTool.CommitTrans;
begin
UpdTrans.Commit;
end;
procedure TFbTool.Execute;
begin
FbSQL.ExecQuery;
end;
function TFbTool.GetSQL: TIBSQL;
begin
Result := FbSQL;
end;
end.
|
Program OrdenarMatriz;
Const
Max=30;
Type
matriz= array[1..Max, 1..Max] of integer;
Var
A:matriz;
filas,columnas:integer;
Procedure LlenarMatriz(var A:matriz; columnas,filas:integer);
var
i,j:integer;
begin
randomize;
for i:=1 to filas do
begin
for j:=1 to columnas do
begin
A[i,j]:=random(9)+1;
// writeln('A[',i,',',j,'] => ',A[i,j]);
end;
end;
writeln('');
end;
Procedure MostrarMatriz (A:matriz; columnas,filas:integer);
var
i,j:integer;
begin
for i:=1 to filas do
begin
for j:=1 to columnas do
begin
write(A[i,j], ' ');
end;
writeln('');
end;
end;
Procedure MostrarAlReves(A:matriz; columnas,filas:integer);
var
i,j:integer;
begin
writeln('Al reves');
writeln('');
for i:=1 to columnas do
begin
for j:=1 to filas do
begin
write(A[j,i], ' ');
end;
writeln('');
end;
end;
Function Minimo(A:matriz;inif,inic,columnas,filas:integer;var posf,posc:integer):integer;
var
i,j,min:integer;
begin
min:= A[inif,inic];
writeln('inic =>', inic);
writeln('inif =>', inif);
writeln('min inicial=>', min);
//terminar fila comenzada
for i:=inif to inif do
begin
for j:=inic to columnas do
begin
writeln('filas comenzadas');
writeln('A[i,j] es A[',i,',',j,'] => ',A[i,j]);
if ((A[i,j] < min)) then
begin
posc:=j;
posf:=i;
min:= A[i,j];
writeln('min en el if=>', min);
end;
end;
end;
for i:=inif+1 to filas do
begin
for j:=1 to columnas do
begin
writeln('filas nuevas');
writeln('A[i,j] es A[',i,',',j,'] => ',A[i,j]);
if ((A[i,j] < min)) then
begin
posc:=j;
posf:=i;
min:= A[i,j];
writeln('min en el if=>', min);
end;
end;
end;
Minimo:=min;
end;
Function MinimoFilas(A:matriz;inif,inic,columnas,filas:integer;var posf,posc:integer):integer;
var
i,j,min:integer;
begin
min:= A[inif,inic];
writeln('inic =>', inic);
writeln('inif =>', inif);
writeln('min inicial=>', min);
//terminar fila comenzada
for i:=inif to filas do
begin
for j:=inic to inic do
begin
writeln('columnas comenzadas');
writeln('A[j,i] es A[',i,',',j,'] => ',A[i,j]);
if ((A[i,j] < min)) then
begin
posc:=j;
posf:=i;
min:= A[i,j];
writeln('min en el if=>', min);
end;
end;
end;
for i:=1 to filas do
begin
for j:=inic+1 to columnas do
begin
writeln('columnas nuevas');
writeln('A[i,j] es A[',i,',',j,'] => ',A[i,j]);
if ((A[i,j] < min)) then
begin
posc:=j;
posf:=i;
min:= A[i,j];
writeln('min en el if=>', min);
end;
end;
end;
MinimoFilas:=min;
end;
Procedure OrdAscColum(var A:matriz;columnas,filas:integer);
var
f,c,min,posf,posc:integer;
begin
writeln('Ordenar Ascendente por Columnas usando seleccion directa');
writeln('');
posc:=1;
posf:=1;
for f:=1 to filas do
begin
for c:=1 to columnas do
begin
writeln('A[f,c] es A[',f,',',c,'] => ',A[f,c]);
min:= Minimo (A,f,c,columnas,filas,posf,posc);
writeln('min es =>', min);
A[posf,posc]:= A[f,c];
A[f,c]:=min;
MostrarMatriz(A,columnas,filas);
end;
end;
end;
Procedure OrdAscFilas(var A:matriz;columnas,filas:integer);
var
f,c,min,posf,posc:integer;
begin
writeln('Ordenar Ascendente por Columnas usando seleccion directa');
writeln('');
posc:=1;
posf:=1;
for c:=1 to columnas do
begin
for f:=1 to filas do
begin
writeln('A[f,c] es A[',f,',',c,'] => ',A[f,c]);
min:= MinimoFilas(A,f,c,columnas,filas,posf,posc);
writeln('min es =>', min);
A[posf,posc]:= A[f,c];
A[f,c]:=min;
MostrarMatriz(A,columnas,filas);
end;
end;
end;
Procedure RecorridoEspiral (A:matriz;columnas,filas:integer);
var
comienzofilas,comienzocolumnas,i,j:integer;
begin
comienzocolumnas:=1;
comienzofilas:=1;
while ((comienzofilas<filas) or (comienzocolumnas<columnas))do
begin
i:=comienzofilas;
j:=comienzocolumnas;
while (j<=columnas) do
begin
write (A[i,j], ' ');
j:=j+1;
end;
j:=j-1;
i:=i+1;
while (i<=filas) do
begin
write (A[i,j], ' ');
i:=i+1;
end;
i:=i-1;
j:=j-1;
while(j>comienzocolumnas) do
begin
write (A[i,j], ' ');
j:=j-1;
end;
while (i>comienzofilas) do
begin
write (A[i,j], ' ');
i:=i-1;
end;
comienzofilas:= comienzofilas+1;
comienzocolumnas:=comienzocolumnas+1;
columnas:=columnas-1;
filas:=filas-1;
end;
end;
Begin
Repeat
Write('Introduzca nro. de filas => '); Readln(filas);
Write('Introduzca nro. de columnas => '); Readln(columnas);
if((columnas>30) or (filas>30)) then
writeln('El numero de filas/columnas debe ser menor a 30');
until ((columnas<=30) and (filas<=30));
LlenarMatriz(A,columnas,filas);
writeln('La matriz creada es:');
MostrarMatriz(A,columnas,filas);
//writeln('La matriz al reves es:');
//MostrarAlReves(A,columnas,filas);
//OrdAscColum(A,columnas,filas);
OrdAscFilas(A,columnas,filas);
writeln('La matriz ordenada ascendentemente es:');
MostrarMatriz(A,columnas, filas);
//writeln('La matriz recorrida en espiral es');
//RecorridoEspiral(A,columnas,filas);
readln;
End.
|
program queueDataStructure;
(*
procedures:
1. init
2. enqueue
3. dequeue
functions:
1. isFull
2. isEmpty
*)
uses crt;
const size = 10;
type
queueType = record
front, rear : Integer;
data : array[1..size] of Integer;
end;
var q : queueType;
response : string;
x : Integer;
procedure init(var q : queueType);
var i : Integer;
begin
q.front := 1;
q.rear := 0;
for i := 1 to size do
q.data[i] := 0;
end;
function isFull(q : queueType):Boolean;
begin
isFull := q.rear = size;
end;
function isEmpty(q : queueType):Boolean;
begin
isEmpty := q.front > q.rear; //q.front = q.rear+1
end;
procedure enqueue(var q : queueType; x : Integer);
begin
if not isFull(q) then
begin
q.rear := q.rear + 1;
q.data[q.rear] := x;
end;
end;
procedure dequeue(var q : queueType; var x : Integer);
begin
if not isEmpty(q) then
begin
x := q.data[q.front]; // retrieve data
q.data[q.front] := 0; // zero means empty
q.front := q.front + 1;
end;
end;
procedure printQueue(q : queueType);
var i : Integer;
begin
for i := q.front to q.rear do
WriteLn('|':4, i, '| ', q.data[i]:5);
WriteLn('Front: ', q.front, ' Rear: ', q.rear);
end;
begin
writeln('Queue:');
init(q);
repeat
WriteLn;
writeln('1.Enqueue data') ;
writeln('2.Dequeue data');
write('> ');
readln(response);
if response = '1' then
begin
if not isFull(q) then
begin
write('Enter the data to enqueue > ');
readln(x);
enqueue(q, x);
end
else
begin
TextColor(Red);
writeln('Stack overflow may occur :)');
TextColor(lightgray);
end;
end
else if response = '2' then
begin
if not isEmpty(q) then
begin
dequeue(q, x);
writeln('Dequeued data is ', x);
end
else
begin
TextColor(Red);
WriteLn('Stack underflow may occur :/');
TextColor(lightgray);
end;
end;
printQueue(q);
until upcase(response) = 'EXIT';
end. |
unit ssImagePanel;
interface
uses
SysUtils, Classes, Controls, ExtCtrls, Graphics;
type
TssImagePanel = class(TPanel)
private
FPicture: TPicture;
procedure SetPicture(const Value: TPicture);
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Picture: TPicture read FPicture write SetPicture;
end;
implementation
uses Windows;
{ TssImagePanel }
constructor TssImagePanel.Create(AOwner: TComponent);
begin
inherited;
FPicture:=TPicture.Create;
end;
destructor TssImagePanel.Destroy;
begin
FPicture.Free;
inherited;
end;
procedure TssImagePanel.Paint;
const
Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER);
var
Rect: TRect;
TopColor, BottomColor: TColor;
FontHeight: Integer;
Flags: Longint;
procedure AdjustColors(Bevel: TPanelBevel);
begin
TopColor := clBtnHighlight;
if Bevel = bvLowered then TopColor := clBtnShadow;
BottomColor := clBtnShadow;
if Bevel = bvLowered then BottomColor := clBtnHighlight;
end;
begin
Rect := GetClientRect;
if BevelOuter <> bvNone then
begin
AdjustColors(BevelOuter);
Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth);
end;
Frame3D(Canvas, Rect, Color, Color, BorderWidth);
if BevelInner <> bvNone then
begin
AdjustColors(BevelInner);
Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth);
end;
with Canvas do
begin
// if not ThemeServices.ThemesEnabled or not ParentBackground then
// begin
Brush.Color := Color;
FillRect(Rect);
if Assigned(FPicture) then Canvas.StretchDraw(ClientRect, FPicture.Bitmap);
// end;
Brush.Style := bsClear;
Font := Self.Font;
FontHeight := TextHeight('W');
with Rect do
begin
Top := ((Bottom + Top) - FontHeight) div 2;
Bottom := Top + FontHeight;
end;
Flags := DT_EXPANDTABS or DT_VCENTER or Alignments[Alignment];
Flags := DrawTextBiDiModeFlags(Flags);
DrawText(Handle, PChar(Caption), -1, Rect, Flags);
end;
end;
procedure TssImagePanel.SetPicture(const Value: TPicture);
begin
FPicture.Assign(Value);
end;
end.
|
//
// MD5Managed.pas
//
// This file is ported from the Mono project
//
//Original File:
// System.Security.Cryptography.MD5CryptoServiceProvider.cs
//
//Original Authors:
// Matthew S. Ford (Matthew.S.Ford@Rose-Hulman.Edu)
// Sebastien Pouliot (sebastien@ximian.com)
//
// Copyright 2001 by Matthew S. Ford.
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Sugar.Cryptography;
interface
type
MD5Managed = public class (System.Security.Cryptography.HashAlgorithm)
private
_H: array of UInt32;
Buff: array of UInt32;
Count: UInt64;
_ProcessingBuffer: array of Byte; // Used to start data when passed less than a block worth.
_ProcessingBufferCount: Int32; // Counts how much data we have stored that still needs processed.
const BLOCK_SIZE_BYTES: Int32 = 64;
private
method ProcessBlock(InputBuffer: array of Byte; InputOffset: Integer);
method ProcessFinalBlock(InputBuffer: array of Byte; InputOffset: Integer; InputCount: Integer);
method AddLength(Length: UInt64; Buffer: array of Byte; Position: Integer);
class var K: array of UInt32 := [
$d76aa478, $e8c7b756, $242070db, $c1bdceee,
$f57c0faf, $4787c62a, $a8304613, $fd469501,
$698098d8, $8b44f7af, $ffff5bb1, $895cd7be,
$6b901122, $fd987193, $a679438e, $49b40821,
$f61e2562, $c040b340, $265e5a51, $e9b6c7aa,
$d62f105d, $02441453, $d8a1e681, $e7d3fbc8,
$21e1cde6, $c33707d6, $f4d50d87, $455a14ed,
$a9e3e905, $fcefa3f8, $676f02d9, $8d2a4c8a,
$fffa3942, $8771f681, $6d9d6122, $fde5380c,
$a4beea44, $4bdecfa9, $f6bb4b60, $bebfbc70,
$289b7ec6, $eaa127fa, $d4ef3085, $04881d05,
$d9d4d039, $e6db99e5, $1fa27cf8, $c4ac5665,
$f4292244, $432aff97, $ab9423a7, $fc93a039,
$655b59c3, $8f0ccc92, $ffeff47d, $85845dd1,
$6fa87e4f, $fe2ce6e0, $a3014314, $4e0811a1,
$f7537e82, $bd3af235, $2ad7d2bb, $eb86d391]; readonly;
public
constructor;
finalizer;
method Dispose(disposing: Boolean); override;
method HashCore(&array: array of Byte; ibStart: Integer; cbSize: Integer); override;
method HashFinal: array of Byte; override;
method Initialize; override;
end;
implementation
method MD5Managed.ProcessBlock(InputBuffer: array of Byte; InputOffset: Integer);
begin
var a, b, c, d: UInt32;
Count := Count + BLOCK_SIZE_BYTES;
for i: Integer := 0 to 15 do
Buff[i] := UInt32(InputBuffer[InputOffset + 4 * i]) or
(UInt32((InputBuffer[InputOffset + 4 * i + 1])) shl 8) or
(UInt32((InputBuffer[InputOffset + 4 * i + 2])) shl 16) or
(UInt32((InputBuffer[InputOffset + 4 * i + 3])) shl 24);
a := _H[0];
b := _H[1];
c := _H[2];
d := _H[3];
// This function was unrolled because it seems to be doubling our performance with current compiler/VM.
// Possibly roll up if this changes.
// ---- Round 1 --------
a := a + (((c xor d) and b) xor d) + UInt32(K[0] + buff[0]);
a := (a shl 7) or (a shr 25);
a := a + b;
d := d + (((b xor c) and a) xor c) + UInt32(K[1] + buff[1]);
d := (d shl 12) or (d shr 20);
d := d + a;
c := c + (((a xor b) and d) xor b) + UInt32(K[2] + buff[2]);
c := (c shl 17) or (c shr 15);
c := c + d;
b := b + (((d xor a) and c) xor a) + UInt32(K[3] + buff[3]);
b := (b shl 22) or (b shr 10);
b := b + c;
a := a + (((c xor d) and b) xor d) + UInt32(K[4] + buff[4]);
a := (a shl 7) or (a shr 25);
a := a + b;
d := d + (((b xor c) and a) xor c) + UInt32(K[5] + buff[5]);
d := (d shl 12) or (d shr 20);
d := d + a;
c := c + (((a xor b) and d) xor b) + UInt32(K[6] + buff[6]);
c := (c shl 17) or (c shr 15);
c := c + d;
b := b + (((d xor a) and c) xor a) + UInt32(K[7] + buff[7]);
b := (b shl 22) or (b shr 10);
b := b + c;
a := a + (((c xor d) and b) xor d) + UInt32(K[8] + buff[8]);
a := (a shl 7) or (a shr 25);
a := a + b;
d := d + (((b xor c) and a) xor c) + UInt32(K[9] + buff[9]);
d := (d shl 12) or (d shr 20);
d := d + a;
c := c + (((a xor b) and d) xor b) + UInt32(K[10] + buff[10]);
c := (c shl 17) or (c shr 15);
c := c + d;
b := b + (((d xor a) and c) xor a) + UInt32(K[11] + buff[11]);
b := (b shl 22) or (b shr 10);
b := b + c;
a := a + (((c xor d) and b) xor d) + UInt32(K[12] + buff[12]);
a := (a shl 7) or (a shr 25);
a := a + b;
d := d + (((b xor c) and a) xor c) + UInt32(K[13] + buff[13]);
d := (d shl 12) or (d shr 20);
d := d + a;
c := c + (((a xor b) and d) xor b) + UInt32(K[14] + buff[14]);
c := (c shl 17) or (c shr 15);
c := c + d;
b := b + (((d xor a) and c) xor a) + UInt32(K[15] + buff[15]);
b := (b shl 22) or (b shr 10);
b := b + c;
// ---- Round 2 --------
a := a + (((b xor c) and d) xor c) + UInt32(K[16] + buff[1]);
a := (a shl 5) or (a shr 27);
a := a + b;
d := d + (((a xor b) and c) xor b) + UInt32(K[17] + buff[6]);
d := (d shl 9) or (d shr 23);
d := d + a;
c := c + (((d xor a) and b) xor a) + UInt32(K[18] + buff[11]);
c := (c shl 14) or (c shr 18);
c := c + d;
b := b + (((c xor d) and a) xor d) + UInt32(K[19] + buff[0]);
b := (b shl 20) or (b shr 12);
b := b + c;
a := a + (((b xor c) and d) xor c) + UInt32(K[20] + buff[5]);
a := (a shl 5) or (a shr 27);
a := a + b;
d := d + (((a xor b) and c) xor b) + UInt32(K[21] + buff[10]);
d := (d shl 9) or (d shr 23);
d := d + a;
c := c + (((d xor a) and b) xor a) + UInt32(K[22] + buff[15]);
c := (c shl 14) or (c shr 18);
c := c + d;
b := b + (((c xor d) and a) xor d) + UInt32(K[23] + buff[4]);
b := (b shl 20) or (b shr 12);
b := b + c;
a := a + (((b xor c) and d) xor c) + UInt32(K[24] + buff[9]);
a := (a shl 5) or (a shr 27);
a := a + b;
d := d + (((a xor b) and c) xor b) + UInt32(K[25] + buff[14]);
d := (d shl 9) or (d shr 23);
d := d + a;
c := c + (((d xor a) and b) xor a) + UInt32(K[26] + buff[3]);
c := (c shl 14) or (c shr 18);
c := c + d;
b := b + (((c xor d) and a) xor d) + UInt32(K[27] + buff[8]);
b := (b shl 20) or (b shr 12);
b := b + c;
a := a + (((b xor c) and d) xor c) + UInt32(K[28] + buff[13]);
a := (a shl 5) or (a shr 27);
a := a + b;
d := d + (((a xor b) and c) xor b) + UInt32(K[29] + buff[2]);
d := (d shl 9) or (d shr 23);
d := d + a;
c := c + (((d xor a) and b) xor a) + UInt32(K[30] + buff[7]);
c := (c shl 14) or (c shr 18);
c := c + d;
b := b + (((c xor d) and a) xor d) + UInt32(K[31] + buff[12]);
b := (b shl 20) or (b shr 12);
b := b + c;
// ---- Round 3 --------
a := a + (b xor c xor d) + UInt32(K[32] + buff[5]);
a := (a shl 4) or (a shr 28);
a := a + b;
d := d + (a xor b xor c) + UInt32(K[33] + buff[8]);
d := (d shl 11) or (d shr 21);
d := d + a;
c := c + (d xor a xor b) + UInt32(K[34] + buff[11]);
c := (c shl 16) or (c shr 16);
c := c + d;
b := b + (c xor d xor a) + UInt32(K[35] + buff[14]);
b := (b shl 23) or (b shr 9);
b := b + c;
a := a + (b xor c xor d) + UInt32(K[36] + buff[1]);
a := (a shl 4) or (a shr 28);
a := a + b;
d := d + (a xor b xor c) + UInt32(K[37] + buff[4]);
d := (d shl 11) or (d shr 21);
d := d + a;
c := c + (d xor a xor b) + UInt32(K[38] + buff[7]);
c := (c shl 16) or (c shr 16);
c := c + d;
b := b + (c xor d xor a) + UInt32(K[39] + buff[10]);
b := (b shl 23) or (b shr 9);
b := b + c;
a := a + (b xor c xor d) + UInt32(K[40] + buff[13]);
a := (a shl 4) or (a shr 28);
a := a + b;
d := d + (a xor b xor c) + UInt32(K[41] + buff[0]);
d := (d shl 11) or (d shr 21);
d := d + a;
c := c + (d xor a xor b) + UInt32(K[42] + buff[3]);
c := (c shl 16) or (c shr 16);
c := c + d;
b := b + (c xor d xor a) + UInt32(K[43] + buff[6]);
b := (b shl 23) or (b shr 9);
b := b + c;
a := a + (b xor c xor d) + UInt32(K[44] + buff[9]);
a := (a shl 4) or (a shr 28);
a := a + b;
d := d + (a xor b xor c) + UInt32(K[45] + buff[12]);
d := (d shl 11) or (d shr 21);
d := d + a;
c := c + (d xor a xor b) + UInt32(K[46] + buff[15]);
c := (c shl 16) or (c shr 16);
c := c + d;
b := b + (c xor d xor a) + UInt32(K[47] + buff[2]);
b := (b shl 23) or (b shr 9);
b := b + c;
// ---- Round 4 --------
a := a + (((not d) or b) xor c) + UInt32(K[48] + buff[0]);
a := (a shl 6) or (a shr 26);
a := a + b;
d := d + (((not c) or a) xor b) + UInt32(K[49] + buff[7]);
d := (d shl 10) or (d shr 22);
d := d + a;
c := c + (((not b) or d) xor a) + UInt32(K[50] + buff[14]);
c := (c shl 15) or (c shr 17);
c := c + d;
b := b + (((not a) or c) xor d) + UInt32(K[51] + buff[5]);
b := (b shl 21) or (b shr 11);
b := b + c;
a := a + (((not d) or b) xor c) + UInt32(K[52] + buff[12]);
a := (a shl 6) or (a shr 26);
a := a + b;
d := d + (((not c) or a) xor b) + UInt32(K[53] + buff[3]);
d := (d shl 10) or (d shr 22);
d := d + a;
c := c + (((not b) or d) xor a) + UInt32(K[54] + buff[10]);
c := (c shl 15) or (c shr 17);
c := c + d;
b := b + (((not a) or c) xor d) + UInt32(K[55] + buff[1]);
b := (b shl 21) or (b shr 11);
b := b + c;
a := a + (((not d) or b) xor c) + UInt32(K[56] + buff[8]);
a := (a shl 6) or (a shr 26);
a := a + b;
d := d + (((not c) or a) xor b) + UInt32(K[57] + buff[15]);
d := (d shl 10) or (d shr 22);
d := d + a;
c := c + (((not b) or d) xor a) + UInt32(K[58] + buff[6]);
c := (c shl 15) or (c shr 17);
c := c + d;
b := b + (((not a) or c) xor d) + UInt32(K[59] + buff[13]);
b := (b shl 21) or (b shr 11);
b := b + c;
a := a + (((not d) or b) xor c) + UInt32(K[60] + buff[4]);
a := (a shl 6) or (a shr 26);
a := a + b;
d := d + (((not c) or a) xor b) + UInt32(K[61] + buff[11]);
d := (d shl 10) or (d shr 22);
d := d + a;
c := c + (((not b) or d) xor a) + UInt32(K[62] + buff[2]);
c := (c shl 15) or (c shr 17);
c := c + d;
b := b + (((not a) or c) xor d) + UInt32(K[63] + buff[9]);
b := (b shl 21) or (b shr 11);
b := b + c;
_H[0] := _H[0] + a;
_H[1] := _H[1] + b;
_H[2] := _H[2] + c;
_H[3] := _H[3] + d;
end;
method MD5Managed.ProcessFinalBlock(InputBuffer: array of Byte; InputOffset: Integer; InputCount: Integer);
begin
var Total: UInt64 := Count + UInt64(InputCount);
var PaddingSize: Int32 := Int32((56 - Total mod BLOCK_SIZE_BYTES));
if PaddingSize < 1 then
PaddingSize := PaddingSize + BLOCK_SIZE_BYTES;
var FooBuffer: array of Byte := new Byte[InputCount + PaddingSize + 8];
for i: Integer := 0 to InputCount - 1 do
FooBuffer[i] := InputBuffer[i + InputOffset];
FooBuffer[InputCount] := $80;
for i: Integer := InputCount + 1 to (InputCount + PaddingSize) - 1 do
FooBuffer[i] := $0;
// I deal in bytes. The algorithm deals in bits.
var Size: UInt64 := Total shl 3;
AddLength(Size, FooBuffer, InputCount + PaddingSize);
ProcessBlock(FooBuffer, 0);
if InputCount + PaddingSize + 8 = 128 then begin
ProcessBlock(FooBuffer, 64);
end;
end;
method MD5Managed.AddLength(Length: System.UInt64; Buffer: array of Byte; Position: Integer);
begin
buffer[Position] := Byte(Length);
inc(Position);
buffer[Position] := Byte(Length shr 8);
inc(Position);
buffer[Position] := Byte(Length shr 16);
inc(Position);
buffer[Position] := Byte(Length shr 24);
inc(Position);
buffer[Position] := Byte(Length shr 32);
inc(Position);
buffer[Position] := Byte(Length shr 40);
inc(Position);
buffer[Position] := Byte(Length shr 48);
inc(Position);
buffer[Position] := Byte(Length shr 56);
end;
constructor MD5Managed;
begin
HashSizeValue := 128;
_H := new UInt32[4];
Buff := new UInt32[16];
_ProcessingBuffer := new Byte[BLOCK_SIZE_BYTES];
Initialize;
end;
finalizer MD5Managed;
begin
Dispose(false);
end;
method MD5Managed.Dispose(disposing: Boolean);
begin
if _ProcessingBuffer <> nil then begin
Array.Clear(_ProcessingBuffer, 0, _ProcessingBuffer.Length);
_ProcessingBuffer := nil;
end;
if _H <> nil then begin
Array.Clear(_H, 0, _H.Length);
_H := nil
end;
if Buff <> nil then begin
Array.Clear(Buff, 0, Buff.Length);
Buff := nil
end;
end;
method MD5Managed.HashCore(&array: array of Byte; ibStart: Integer; cbSize: Integer);
begin
var i: Int32;
State := 1;
if _ProcessingBufferCount <> 0 then begin
if cbSize < (BLOCK_SIZE_BYTES - _ProcessingBufferCount) then begin
System.Buffer.BlockCopy(&array, ibStart, _ProcessingBuffer, _ProcessingBufferCount, cbSize);
_ProcessingBufferCount := _ProcessingBufferCount + cbSize;
exit;
end
else begin
i := BLOCK_SIZE_BYTES - _ProcessingBufferCount;
System.Buffer.BlockCopy(&array, ibStart, _ProcessingBuffer, _ProcessingBufferCount, i);
ProcessBlock(_ProcessingBuffer, 0);
_ProcessingBufferCount := 0;
ibStart := ibStart + i;
cbSize := cbSize - i;
end;
end;
i := 0;
while i < cbSize - cbSize mod BLOCK_SIZE_BYTES do begin
ProcessBlock(&array, ibStart + i);
i := i + BLOCK_SIZE_BYTES;
end;
if cbSize mod BLOCK_SIZE_BYTES <> 0 then begin
System.Buffer.BlockCopy(&array, cbSize - cbSize mod BLOCK_SIZE_BYTES + ibStart, _ProcessingBuffer, 0, cbSize mod BLOCK_SIZE_BYTES);
_ProcessingBufferCount := cbSize mod BLOCK_SIZE_BYTES;
end;
end;
method MD5Managed.HashFinal: array of Byte;
begin
var Hash := new Byte[16];
ProcessFinalBlock(_ProcessingBuffer, 0, _ProcessingBufferCount);
for i: Integer := 0 to 3 do
for j: Integer := 0 to 3 do
Hash[i * 4 + j] := Byte(_H[i] shr (j * 8));
exit Hash;
end;
method MD5Managed.Initialize;
begin
Count := 0;
_ProcessingBufferCount := 0;
_H[0] := $67452301;
_H[1] := $efcdab89;
_H[2] := $98badcfe;
_H[3] := $10325476;
end;
end. |
namespace Sugar.RegularExpressions;
interface
uses
Sugar.Collections;
type
Match = public class {$IF COOPER}mapped to java.util.regex.Matcher
{$ELSEIF ECHOES}mapped to System.Text.RegularExpressions.Match{$ENDIF}
protected
{$IF TOFFEE}
fInput: String;
fMatch: NSTextCheckingResult;
{$ENDIF}
method GetEnd: Integer;
method GetGroups: List<&Group>;
method GetLength: Integer;
method GetStart: Integer;
method GetText: String;
public
{$IF TOFFEE}
constructor(PlatformMatch: NSTextCheckingResult; Input: String);
{$ENDIF}
method FindNext: Match;
property &End: Integer read GetEnd;
property Groups: List<&Group> read GetGroups;
property Length: Integer read GetLength;
property Start: Integer read GetStart;
property Text: String read GetText;
end;
implementation
{$IF TOFFEE}
constructor Match(PlatformMatch: NSTextCheckingResult; Input: String);
begin
fMatch := PlatformMatch;
fInput := Input;
end;
{$ENDIF}
method Match.FindNext: Match;
begin
{$IF COOPER}
exit if mapped.find() then mapped else nil;
{$ELSEIF ECHOES}
var NextMatch: System.Text.RegularExpressions.Match := mapped.NextMatch();
exit if NextMatch.Success then NextMatch else nil;
{$ELSEIF TOFFEE}
var Offset: Integer := fMatch.range.location + fMatch.range.length;
var NextMatch: NSTextCheckingResult := fMatch.regularExpression.
firstMatchInString(fInput)
options(NSMatchingOptions(0))
range(NSMakeRange(Offset, fInput.length - Offset));
exit if NextMatch <> nil then new Match(NextMatch, fInput) else nil;
{$ENDIF}
end;
method Match.GetEnd: Integer;
begin
{$IF COOPER}
exit mapped.end() - 1;
{$ELSEIF ECHOES}
exit mapped.Index + mapped.Length - 1;
{$ELSEIF TOFFEE}
exit fMatch.range.location + fMatch.range.length - 1;
{$ENDIF}
end;
method Match.GetGroups: List<&Group>;
begin
var GroupCount: Integer;
var Results: List<&Group> := new List<&Group>();
{$IF COOPER}
GroupCount := mapped.groupCount() + 1;
{$ELSEIF ECHOES}
GroupCount := mapped.Groups.Count;
{$ELSEIF TOFFEE}
GroupCount := fMatch.numberOfRanges;
{$ENDIF}
for I: Integer := 1 to GroupCount - 1 do
Results.Add(
{$IF COOPER}
if mapped.group(I) <> nil then
new &Group(mapped.start(I), mapped.end(I) - mapped.start(I), mapped.group(I))
{$ELSEIF ECHOES}
if mapped.Groups.Item[I].Success then
new &Group(mapped.Groups.Item[I].Index, mapped.Groups.Item[I].Length, mapped.Groups.Item[I].Value)
{$ELSEIF TOFFEE}
if fMatch.rangeAtIndex(I).location <> NSNotFound then
new &Group(fMatch.rangeAtIndex(I).location,
fMatch.rangeAtIndex(I).length,
fInput.substringWithRange(fMatch.rangeAtIndex(I)))
{$ENDIF}
else nil
);
exit Results;
end;
method Match.GetLength: Integer;
begin
{$IF COOPER}
exit mapped.end() - mapped.start();
{$ELSEIF ECHOES}
exit mapped.Length;
{$ELSEIF TOFFEE}
exit fMatch.range.length;
{$ENDIF}
end;
method Match.GetStart: Integer;
begin
{$IF COOPER}
exit mapped.start();
{$ELSEIF ECHOES}
exit mapped.Index;
{$ELSEIF TOFFEE}
exit fMatch.range.location;
{$ENDIF}
end;
method Match.GetText: String;
begin
{$IF COOPER}
exit mapped.group();
{$ELSEIF ECHOES}
exit mapped.Value;
{$ELSEIF TOFFEE}
exit fInput.substringWithRange(fMatch.range);
{$ENDIF}
end;
end. |
unit URLParser;
interface
uses
VoyagerInterfaces, Controls;
type
TFramePositioning = (posRelative, posAbsolute);
TFrameAlign = TAlign;
type
TDimension =
record
value : integer;
relative : boolean;
end;
type
TVisibility = (visVisible, visHidden, visSwitch);
type
TAnchorData =
record
URL : string;
Action : string;
FrameId : string;
FrameClass : string;
Target : string;
Positioning : TFramePositioning;
Align : TFrameAlign;
Width : TDimension;
Height : TDimension;
Maximized : boolean;
CloseFrame : boolean;
VoidCache : boolean;
ToHistory : boolean;
Visibility : TVisibility;
end;
function ExtractURL( var URL : string ) : string;
function StrToPositioning( str : string ) : TFramePositioning;
function StrToAlign( str : string ) : TFrameAlign;
function StrToBoolean( str : string ) : boolean;
function StrToDimension( str : string ) : TDimension;
function GetURLAction( URL : TURL ) : string;
function GetParmValue( URL : TURL; ParmName : string ) : string;
function GetAnchorData( URL : TURL ) : TAnchorData;
function EncodeEscSequences( URL : string ) : string;
function DecodeEscSequences( URL : string ) : string;
// HTML strings
const
URLJoint = '::';
const
htmlParmName_Action = 'frame_Action';
htmlParmName_Id = 'frame_Id';
htmlParmName_Class = 'frame_Class';
htmlParmName_Positioning = 'frame_Positioning';
htmlParmName_Align = 'frame_Align';
htmlParmName_Width = 'frame_Width';
htmlParmName_Height = 'frame_Height';
htmlParmName_Maximized = 'frame_Maximized';
htmlParmName_Close = 'frame_Close';
htmlParmName_VoidCache = 'frame_VoidCache';
htmlParmName_Hidden = 'frame_Hidden';
htmlParmName_Target = 'frame_Target';
htmlParmName_Visibility = 'frame_Visibility';
htmlParmName_ToHistory = 'frame_ToHistory';
const
htmlValue_PosAbsolute = 'ABSOLUTE';
htmlValue_PosRelative = 'RELATIVE';
htmlValue_AlignClient = 'CLIENT';
htmlValue_AlignLeft = 'LEFT';
htmlValue_AlignTop = 'TOP';
htmlValue_AlignRight = 'RIGHT';
htmlValue_AlignBottom = 'BOTTOM';
htmlValue_VisVisible = 'VISIBLE';
htmlValue_VisHidden = 'HIDDEN';
htmlValue_VisSwitch = 'SWITCH';
implementation
uses
Windows, SysUtils, StrUtils, WinInet;
function ExtractURL( var URL : string ) : string;
var
p : integer;
begin
p := pos( URLJoint, URL, 1 );
if p = 0
then
begin
result := URL;
URL := '';
end
else
begin
result := copy( URL, 1, p - 1 );
delete( URL, 1, p + length(URLJoint) - 1 );
end;
end;
function StrToPositioning( str : string ) : TFramePositioning;
begin
str := uppercase( str );
if str = htmlValue_PosAbsolute
then result := posAbsolute
else result := posRelative;
end;
function StrToAlign( str : string ) : TFrameAlign;
begin
str := uppercase( str );
if str = htmlValue_AlignLeft
then result := alLeft
else
if str = htmlValue_AlignTop
then result := alTop
else
if str = htmlValue_AlignRight
then result := alRight
else
if str = htmlValue_AlignBottom
then result := alBottom
else
if str = htmlValue_AlignClient
then result := alClient
else result := alNone;
end;
function StrToBoolean( str : string ) : boolean;
begin
str := uppercase( str );
result := (str = 'TRUE') or (str = 'YES')
end;
function StrToDimension( str : string ) : TDimension;
begin
try
if str <> ''
then
if str[length(str)] = '%'
then
begin
result.value := StrToInt( copy( str, 1, pred(length(str)) ));
result.relative := true;
end
else
begin
result.value := StrToInt( str );
result.relative := false;
end
else
begin
result.value := -1;
result.relative := false;
end
except
result.value := -1;
result.relative := false;
end;
end;
function StrToVisibility( str : string ) : TVisibility;
begin
str := uppercase(str);
if str = htmlValue_VisSwitch
then result := visSwitch
else
if str = htmlValue_VisHidden
then result := visHidden
else result := visVisible;
end;
function GetURLAction( URL : TURL ) : string;
begin
URL := DecodeEscSequences( URL );
result := uppercase(GetParmValue( URL, htmlParmName_Action ));
end;
function GetParmValue( URL : TURL; ParmName : string ) : string;
var
p : integer;
UpperURL : string;
URLParm : boolean;
begin
URL := DecodeEscSequences( URL );
UpperURL := uppercase( URL );
ParmName := uppercase( ParmName );
p := strutils.pos( '&' + ParmName, UpperURL, 1 );
if p = 0
then p := strutils.pos( '?' + ParmName, UpperURL, 1 );
if p > 0
then
begin
p := strutils.pos( '=', UpperURL, p );
if p > 0
then
begin
inc( p );
result := '';
URLParm := false;
while (p <= length(URL)) and ((URL[p] <> '&') or URLParm) and (URL[p] <> '}') do
begin
if URL[p] = '{'
then URLParm := true
else result := result + URL[p];
inc( p );
end;
end
else result := '';
end
else result := '';
end;
function GetAnchorData( URL : TURL ) : TAnchorData;
var
hiddenParm : string;
begin
URL := DecodeEscSequences( URL );
result.URL := URL;
result.Action := GetURLAction( URL );
result.FrameId := GetParmValue( URL, htmlParmName_Id );
result.FrameClass := GetParmValue( URL, htmlParmName_Class );
result.Target := GetParmValue( URL, htmlParmName_Target );
result.Positioning := StrToPositioning(GetParmValue( URL, htmlParmName_Positioning ));
result.Align := StrToAlign(GetParmValue( URL, htmlParmName_Align ));
result.Width := StrToDimension(GetParmValue( URL, htmlParmName_Width ));
result.Height := StrToDimension(GetParmValue( URL, htmlParmName_Height ));
result.Maximized := StrToBoolean(GetParmValue( URL, htmlParmName_Maximized ));
result.CloseFrame := StrToBoolean(GetParmValue( URL, htmlParmName_Close ));
result.VoidCache := StrToBoolean(GetParmValue( URL, htmlParmName_VoidCache ));
result.ToHistory := StrToBoolean(GetParmValue( URL, htmlParmName_ToHistory ));
hiddenParm := GetParmValue( URL, htmlParmName_Hidden );
if hiddenParm = ''
then result.Visibility := StrToVisibility(GetParmValue( URL, htmlParmName_Visibility ))
else
if not StrToBoolean(hiddenParm)
then result.Visibility := visVisible
else result.Visibility := visHidden
end;
function EncodeEscSequences( URL : string ) : string;
var
buffer : pchar;
bufferlen : dword;
begin
bufferlen := 2*length(URL);
buffer := StrAlloc( bufferlen );
if InternetCanonicalizeUrlA( pchar(URL), buffer, bufferlen, ICU_ENCODE_SPACES_ONLY )
then result := buffer
else result := URL;
end;
function DecodeEscSequences( URL : string ) : string;
var
buffer : pchar;
bufferlen : dword;
begin
bufferlen := 2*length(URL);
buffer := StrAlloc( bufferlen );
if InternetCanonicalizeUrlA( pchar(URL), buffer, bufferlen, ICU_DECODE or ICU_NO_ENCODE )
then result := buffer
else result := URL;
end;
end.
|
module sst_func;
define sst_func_exp;
define sst_func_arg;
%include 'sst2.ins.pas';
{
********************************************************************************
*
* Function SST_FUNC_EXP (FUNC)
*
* Create the expression for the returned value of a function. FUNC is the
* function symbol. The function will not be passed any call arguments. These
* can be added later with SST_FUNC_ARG and related routines.
}
function sst_func_exp ( {make function value expression, no args}
in var func: sst_symbol_t) {function symbol}
:sst_exp_p_t; {pointer to new expression}
val_param;
var
proc_p: sst_proc_p_t; {pointer to called procedure descriptor}
var_p: sst_var_p_t; {pnt to "variable" descriptor for func ref}
exp_p: sst_exp_p_t; {pointer to expression being built}
begin
if func.symtype <> sst_symtype_proc_k then begin
writeln ('INTERNAL ERROR: FUNC argument to SST_EXP_FUNC not a function symbol.');
sys_bomb;
end;
{
* Create desciptor for the function call.
}
sst_mem_alloc_scope ( {create called routine descriptor}
sizeof(proc_p^), proc_p);
proc_p^ := func.proc; {initialize called function from template}
proc_p^.n_args := 0; {init to no call arguments}
proc_p^.first_arg_p := nil; {init call arguments list to empty}
{
* Create the "variable" reference to the function.
}
sst_mem_alloc_scope ( {create variable reference descriptor}
sizeof(var_p^), var_p);
var_p^.mod1.next_p := nil; {this is last modifier in chain}
var_p^.mod1.modtyp := sst_var_modtyp_top_k; {this is top level modifier}
var_p^.mod1.top_str_h.first_char.crange_p := nil;
var_p^.mod1.top_sym_p := addr(func); {symbol being referenced}
var_p^.dtype_p := func.proc.dtype_func_p; {resulting data type of the reference}
var_p^.rwflag := [sst_rwflag_read_k]; {reference is read-only}
var_p^.vtype := sst_vtype_rout_k; {reference is to called routine}
var_p^.rout_proc_p := addr(func.proc); {template for calling the routine}
{
* Create the expression for the value of the called function.
}
sst_mem_alloc_scope ( {create expression descriptor}
sizeof(exp_p^), exp_p);
exp_p^.str_h.first_char.crange_p := nil;
exp_p^.dtype_p := func.proc.dtype_func_p; {function return value data type}
exp_p^.dtype_hard := true; {data type is known and fixed}
exp_p^.val_eval := true; {attempted to resolve value}
exp_p^.val_fnd := false; {fixed value not found}
exp_p^.rwflag := [sst_rwflag_read_k]; {expression is read-only}
exp_p^.term1.next_p := nil; {there is no next term}
exp_p^.term1.op2 := sst_op2_none_k; {no operator with previous term}
exp_p^.term1.op1 := sst_op1_none_k; {no unary operator applying to this term}
exp_p^.term1.ttype := sst_term_func_k; {term is the value of a function}
exp_p^.term1.str_h.first_char.crange_p := nil;
exp_p^.term1.dtype_p := exp_p^.dtype_p; {same data type as whole expression}
exp_p^.term1.dtype_hard := true; {data type is known and fixed}
exp_p^.term1.val_eval := true; {tried to resolve value}
exp_p^.term1.val_fnd := false; {not a known fixed value}
exp_p^.term1.rwflag := [sst_rwflag_read_k]; {term is read-only}
exp_p^.term1.func_var_p := var_p; {"variable" reference for calling the function}
exp_p^.term1.func_proc_p := proc_p; {point to function call descriptor}
exp_p^.term1.func_proct_p := {point to the procedure template}
addr(func.proc);
sst_func_exp := exp_p; {return pointer to the new expression}
end;
{
********************************************************************************
*
* Subroutine SST_FUNC_ARG (EXP, ARG)
*
* Add an argument to the function call expression EXP. ARG is the argument
* value expression. EXP must be the expression for the result of calling a
* function, such as returned by SST_FUNC_EXP.
}
procedure sst_func_arg ( {add argument to function value expression}
in out exp: sst_exp_t; {function reference exp to add argument to}
in var arg: sst_exp_t); {argument expression}
val_param;
var
proc_p: sst_proc_p_t; {pointer to the called procedure descriptor}
narg: sys_int_machine_t; {number of arguments found}
argt_p: sst_proc_arg_p_t; {pointer to argument template}
arg_p: sst_proc_arg_p_t; {pointer to call argument}
arg_pp: ^sst_proc_arg_p_t; {pnt to where to link new arg descriptor}
label
notemplate;
begin
if exp.term1.ttype <> sst_term_func_k then begin
writeln ('INTERNAL ERROR: Expression is not a function call in SST_FUNC_ARG.');
sys_bomb;
end;
proc_p := exp.term1.func_proc_p; {get pointer to call descriptor}
{
* Find the end of the arguments chain. The following state is set:
*
* NARG - Number of existing arguments found.
*
* ARG_PP - Points to where to link new argument to end of arguments chain.
*
* ARGT_P - Pointer to the template for this argument in the function
* descriptor.
}
narg := 0; {init number of existing arguments found}
arg_pp := addr(proc_p^.first_arg_p); {init pointer to end of chain link}
arg_p := proc_p^.first_arg_p; {init to first argument}
argt_p := exp.term1.func_proct_p^.first_arg_p; {init to first argument template}
if argt_p = nil then goto notemplate; {no template exists for a new argument ?}
while arg_p <> nil do begin {loop until hit end of chain}
narg := narg + 1; {count one more existing argument}
arg_pp := addr(arg_p^.next_p); {update end of chain link pointer}
arg_p := arg_p^.next_p; {advance to next argument in chain}
argt_p := argt_p^.next_p; {advance to template for next argument}
if argt_p = nil then goto notemplate; {no template for new argument ?}
end;
{
* Create the new call argument descriptor.
}
sst_mem_alloc_scope ( {create the empty descriptor}
sizeof(arg_p^), arg_p);
arg_p^ := argt_p^; {init the new argument from the template}
arg_p^.next_p := nil; {this will be last argument in chain}
arg_p^.exp_p := addr(arg); {point to expression for this argument}
arg_p^.dtype_p := arg.dtype_p; {data type of this argument}
{
* Update the function call.
}
arg_pp^ := arg_p; {link new argument to end of chain}
proc_p^.n_args := narg + 1; {update number of args function called with}
return;
notemplate:
writeln ('INTERNAL ERROR: Attempt to add more arguments than allowed by function.');
writeln (' in SST_FUNC_ARG.');
sys_bomb;
end;
|
unit fmPieChart;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, TeEngine, Series, TeeProcs, Chart, uEventAgg, uEvents, uModel;
type
TfrmPieChart = class(TForm)
Chart1: TChart;
pnlFooter: TPanel;
btnClose: TButton;
CheckBox1: TCheckBox;
Series1: TPieSeries;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CheckBox1Click(Sender: TObject);
private
FAngle: Integer;
FCurrent: TReportCard;
procedure UpdateChart(const aPublisher: TObject; const anEvent: TEventClass);
public
{ Public declarations }
end;
var
frmPieChart: TfrmPieChart;
implementation
uses dmController;
{$R *.dfm}
{ TfrmPieChart }
procedure TfrmPieChart.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmPieChart.CheckBox1Click(Sender: TObject);
begin
EA.Unsubscribe(UpdateChart);
if CheckBox1.Checked then
EA.Subscribe(UpdateChart, TReportCardEvent)
else
EA.Subscribe(UpdateChart, TReportCardChange);
end;
procedure TfrmPieChart.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmPieChart.FormCreate(Sender: TObject);
begin
FCurrent := nil;
FAngle := 0;
UpdateChart(dtmController.Current, TReportCardNav);
EA.Subscribe(UpdateChart, TReportCardEvent);
end;
procedure TfrmPieChart.FormDestroy(Sender: TObject);
begin
EA.Unsubscribe(UpdateChart);
end;
procedure TfrmPieChart.UpdateChart(const aPublisher: TObject; const anEvent: TEventClass);
begin
// If it's a navigational event, make this object the 'Current' object.
if anEvent.InheritsFrom(TReportCardNav) then
begin
FCurrent := TReportCard(aPublisher);
Inc(FAngle,15);
FAngle := FAngle mod 360;
Series1.RotationAngle := FAngle;
end;
if aPublisher = FCurrent then
begin
Chart1.Title.Caption := FCurrent.Name;
Series1.Clear;
Series1.Add(FCurrent.ScoreA, 'A', clAqua);
Series1.Add(FCurrent.ScoreB, 'B', clPurple);
Series1.Add(FCurrent.ScoreC, 'C', clYellow);
end;
end;
end.
|
unit ColorTrans;
// Palette Transform Stuff. Copyright (c) 1997 Jorge Romero Gomez, Merchise.
interface
uses
Windows, GDI;
// Color Translation Stuff
type
PColorTransTable = ^TColorTransTable;
TColorTransTable = array[byte] of byte;
function TabPaletteConv( const SourceRgbEntries; SourceCount : integer;
const DestRgbEntries; DestCount : integer ) : PColorTransTable;
function TabPaletteReduce( const RgbEntries; Count, NewCount : integer ) : PColorTransTable;
//function TabPaletteTint( const RgbEntries; Count : integer; Color : TRgbQuad; Percent : integer ) : PColorTransTable;
// Color Mixing Stuff
type
PColorMixMatrix = ^TColorMixMatrix;
TColorMixMatrix = array[byte, byte] of byte;
const // Alpha constants
alphaBlend5050 = 128;
function MixColors( const SourceRgbEntries; Count : integer; Alpha : integer ) : PColorMixMatrix;
// Use these tables as CTTs to transfer 8-bit images to 16, 24 or 32-bit images
type
PColorTransTableHi = ^TColorTransTableHi;
TColorTransTableHi = array[byte] of word;
type
PColorTransTableTrue = ^TColorTransTableTrue;
TColorTransTableTrue = array[0..256] of dword;
function Tab8toHiColor( const SourceRgbEntries; Count : integer; rMask, gMask, bMask : integer ) : PColorTransTableHi;
function Tab8toHiColorUnpacked( const SourceRgbEntries; Count : integer; rMask, gMask, bMask : integer ) : PColorTransTableTrue;
function Tab8toTrueColor( const SourceRgbEntries; Count : integer; rMask, gMask, bMask : integer ) : PColorTransTableTrue;
procedure Tab8toHiColorInPlace( const SourceRgbEntries; Count : integer; var HiColorEntries; rMask, gMask, bMask : integer );
procedure Tab8toHiColorUnpackedInPlace( const SourceRgbEntries; Count : integer; var HiColorUnpackEntries; rMask, gMask, bMask : integer );
procedure Tab8toTrueColorInPlace( const SourceRgbEntries; Count : integer; var TrueColorEntries; rMask, gMask, bMask : integer );
implementation
uses
NumUtils;
function Tab8toHiColor( const SourceRgbEntries; Count : integer; rMask, gMask, bMask : integer ) : PColorTransTableHi;
begin
getmem( Result, sizeof( TColorTransTableHi ) );
Tab8toHiColorInPlace( SourceRgbEntries, Count, Result^, rMask, gMask, bMask );
end;
function Tab8toTrueColor( const SourceRgbEntries; Count : integer; rMask, gMask, bMask : integer ) : PColorTransTableTrue;
begin
getmem( Result, sizeof( TColorTransTableTrue ) );
Tab8toTrueColorInPlace( SourceRgbEntries, Count, Result^, rMask, gMask, bMask );
end;
function Tab8toHiColorUnpacked( const SourceRgbEntries; Count : integer; rMask, gMask, bMask : integer ) : PColorTransTableTrue;
begin
getmem( Result, sizeof( TColorTransTableTrue ) );
Tab8toHiColorUnpackedInPlace( SourceRgbEntries, Count, Result^, rMask, gMask, bMask );
end;
procedure Tab8toHiColorInPlace( const SourceRgbEntries; Count : integer; var HiColorEntries; rMask, gMask, bMask : integer );
var
i : integer;
rRight, gRight, bRight : integer;
rLeft, gLeft, bLeft : integer;
RgbEntries : TRgbPalette absolute SourceRgbEntries;
HiColorTable : TColorTransTableHi absolute HiColorEntries;
begin
if rMask = 0
then
begin
rMask := $7C00;
gMask := $03E0;
bMask := $001F;
end;
rRight := RightShiftCount( rMask );
gRight := RightShiftCount( gMask );
bRight := RightShiftCount( bMask );
rLeft := LeftShiftCount( rMask );
gLeft := LeftShiftCount( gMask );
bLeft := LeftShiftCount( bMask );
for i := 0 to Count - 1 do
with RgbEntries[i] do
begin
HiColorTable[i] := ( (rgbRed shr rLeft) shl rRight ) or
( (rgbGreen shr gLeft) shl gRight ) or
( (rgbBlue shr bLeft) shl bRight );
end;
end;
procedure Tab8toHiColorUnpackedInPlace( const SourceRgbEntries; Count : integer; var HiColorUnPackEntries; rMask, gMask, bMask : integer );
var
i : integer;
rRight, gRight, bRight : integer;
rLeft, gLeft, bLeft : integer;
RgbEntries : TRgbPalette absolute SourceRgbEntries;
HiColorUnpackTable : TColorTransTableTrue absolute HiColorUnPackEntries;
begin
if rMask = 0
then
begin
rMask := $ff0000;
gMask := $00ff00;
bMask := $0000ff;
end;
rRight := RightShiftCount( rMask );
gRight := RightShiftCount( gMask );
bRight := RightShiftCount( bMask );
rLeft := LeftShiftCount( rMask );
gLeft := LeftShiftCount( gMask );
bLeft := LeftShiftCount( bMask );
for i := 0 to Count - 1 do
with RgbEntries[i] do
begin
HiColorUnpackTable[i] := rgbRed shr ( rLeft + 3 ) shl rRight or
rgbGreen shr ( gLeft + 3 ) shl gRight or
rgbBlue shr ( bLeft + 3 ) shl bRight;
end;
end;
procedure Tab8toTrueColorInPlace( const SourceRgbEntries; Count : integer; var TrueColorEntries; rMask, gMask, bMask : integer );
var
i : integer;
rRight, gRight, bRight : integer;
rLeft, gLeft, bLeft : integer;
RgbEntries : TRgbPalette absolute SourceRgbEntries;
TrueColorTable : TColorTransTableTrue absolute TrueColorEntries;
begin
if rMask = 0
then
begin
rMask := $ff0000;
gMask := $00ff00;
bMask := $0000ff;
end;
rRight := RightShiftCount( rMask );
gRight := RightShiftCount( gMask );
bRight := RightShiftCount( bMask );
rLeft := LeftShiftCount( rMask );
gLeft := LeftShiftCount( gMask );
bLeft := LeftShiftCount( bMask );
for i := 0 to Count - 1 do
with RgbEntries[i] do
begin
TrueColorTable[i] := rgbRed shr rLeft shl rRight or
rgbGreen shr gLeft shl gRight or
rgbBlue shr bLeft shl bRight;
end;
end;
function MixColors( const SourceRgbEntries; Count : integer; Alpha : integer ) : PColorMixMatrix;
var
x, y, i : integer;
Dist, MinDist, Indx : integer;
Average : TColorRef;
var
RgbEntries : TRgbPalette absolute SourceRgbEntries;
AvgRgb : TColorRec absolute Average;
begin
new( Result );
with AvgRgb do
for y := 0 to 255 do
for x := 0 to 255 do
begin
with RgbEntries[x] do
begin
crRed := ( Alpha * rgbRed + ( 256 - Alpha ) * RgbEntries[y].rgbRed ) div 256;
crGreen := ( Alpha * rgbGreen + ( 256 - Alpha ) * RgbEntries[y].rgbGreen ) div 256;
crBlue := ( Alpha * rgbBlue + ( 256 - Alpha ) * RgbEntries[y].rgbBlue ) div 256;
end;
MinDist := MaxInt;
Indx := 0;
for i := 0 to 255 do
with RgbEntries[i] do
begin
Dist := Square[ crRed - rgbRed ] + Square[ crGreen - rgbGreen ] + Square[ crBlue - rgbBlue ];
if Dist < MinDist
then
begin
Indx := i;
if Dist > 0
then MinDist := Dist
else break;
end;
end;
Result[x, y] := Indx;
end;
end;
function TabPaletteConv( const SourceRgbEntries; SourceCount : integer;
const DestRgbEntries; DestCount : integer ) : PColorTransTable;
var
i : integer;
RgbEntries : TRgbPalette absolute SourceRgbEntries;
begin
assert( (SourceCount < 256) and (DestCount < 256), 'Invalid count in ColorTrans.TabPaletteConv!!' );
new( Result );
for i := 0 to SourceCount - 1 do
Result[i] := GetNearestEntry( DestRgbEntries, DestCount, dword( RgbEntries[i] ) );
end;
function TabPaletteReduce( const RgbEntries; Count, NewCount : integer ) : PColorTransTable;
var
i : integer;
Entries : TRgbPalette absolute RgbEntries;
begin
assert( (Count < 256) and (Count < 256), 'Invalid count in ColorTrans.TabPaletteConv!!' );
new( Result );
for i := 0 to NewCount - 1 do
Result[i] := GetNearestEntry( Entries, Count, dword( Entries[i] ) );
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
SEM shader : Spherical Environment Mapping
The main idea of SEM is to get the UV coordinates (which are used to lookup the matCap texture)
from the normal vector on the fragment instead of the original texture coordinates from the object.
A material using SEM is very useful to highlight variations in the mesh: creases, bumps, even slow ondulations.
It doesn't work that well on a cube, for instance. And does absolutely nothing on a sphere:
SEM on a sphere is exactly the same as a planar projection of the matCap texture.
At this time only one light source is supported
}
unit VXS.GLSLSemShader;
interface
{$I VXScene.inc}
uses
System.Classes,
VXS.Scene, VXS.CrossPlatform, VXS.BaseClasses, VXS.State, Winapi.OpenGL, Winapi.OpenGLext, VXS.OpenGL1x,
VXS.Context, VXS.RenderContextInfo, VXS.VectorGeometry, VXS.Coordinates, VXS.TextureFormat,
VXS.Color, VXS.Texture, VXS.Material, GLSL.Shader, VXS.CustomShader;
//TVXCustomGLSLSimpleSemShader
//
{ Custom class for GLSLSEMShader.
SEM Shader : Spherical Environment Mapping }
Type
TVXCustomGLSLSemShader = class(TVXCustomGLSLShader)
private
FAmbientColor: TVXColor;
// FDiffuseColor: TVXColor;
FSpecularColor: TVXColor;
FAmbientFactor : Single;
FDiffuseFactor : Single;
FSpecularFactor : Single;
FMaterialLibrary: TVXAbstractMaterialLibrary;
FMainTexture: TVXTexture;
FMainTexName : TVXLibMaterialName;
// FSpecularPower: Single;
// FLightPower: Single;
function GetMaterialLibrary: TVXAbstractMaterialLibrary;
procedure SetMainTexTexture(const Value: TVXTexture);
function GetMainTexName: TVXLibMaterialName;
procedure SetMainTexName(const Value: TVXLibMaterialName);
//procedure SetDiffuseColor(AValue: TVXColor);
procedure SetAmbientColor(AValue: TVXColor);
procedure SetSpecularColor(AValue: TVXColor);
protected
procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override;
procedure SetMaterialLibrary(const Value: TVXAbstractMaterialLibrary); virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
// property DiffuseColor : TVXColor read FDiffuseColor Write setDiffuseColor;
property SpecularColor : TVXColor Read FSpecularColor Write setSpecularColor;
property AmbientColor : TVXColor Read FAmbientColor Write setAmbientColor;
property AmbientFactor : Single Read FAmbientFactor Write FAmbientFactor;
property DiffuseFactor : Single Read FDiffuseFactor Write FDiffuseFactor;
property SpecularFactor : Single Read FSpecularFactor Write FSpecularFactor;
property MaterialLibrary: TVXAbstractMaterialLibrary read getMaterialLibrary write SetMaterialLibrary;
property MainTexture: TVXTexture read FMainTexture write SetMainTexTexture;
property MainTextureName: TVXLibMaterialName read GetMainTexName write SetMainTexName;
// property SpecularPower: Single read FSpecularPower write FSpecularPower;
// property LightPower: Single read FLightPower write FLightPower;
end;
TVXSLSemShader = class(TVXCustomGLSLSemShader)
published
property AmbientColor;
// property DiffuseColor;
property SpecularColor;
property AmbientFactor;
property DiffuseFactor;
property SpecularFactor;
property MaterialLibrary;
property MainTexture;
property MainTextureName;
end;
implementation
constructor TVXCustomGLSLSemShader.Create(AOwner: TComponent);
begin
inherited;
with VertexProgram.Code do
begin
clear;
Add('varying vec3 viewVec; ');
Add('varying vec3 normal; ');
Add('varying vec3 lightVec; ');
Add('void main() { ');
Add(' vec4 p = gl_ModelViewMatrix * gl_Vertex; ');
Add(' vec4 lightPos = gl_LightSource[0].position;');
Add(' lightVec = vec3(lightPos - p); ');
Add(' viewVec = -vec3(p); ');
Add(' normal = normalize(gl_NormalMatrix * gl_Normal ); ');
Add(' gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; ');
Add('} ');
end;
with FragmentProgram.Code do
begin
clear;
Add('uniform vec4 AmbientColor; ');
Add('uniform vec4 SpecularColor; ');
Add('uniform float DiffuseIntensity; ');
Add('uniform float AmbientIntensity; ');
Add('uniform float SpecularIntensity; ');
Add('uniform sampler2D MainTexture; ');
Add('varying vec3 viewVec; ');
Add('varying vec3 normal; ');
Add('varying vec3 lightVec; ');
Add('void main() { ');
Add(' vec3 V = normalize(viewVec); ');
Add(' vec3 r = reflect( V, normal ); ');
Add(' float m = 2.0 * sqrt( pow( r.x, 2.0 ) + pow( r.y, 2.0 ) + pow( r.z + 1.0, 2.0 ) ); ');
Add(' vec2 vN = r.xy / m + 0.5; ');
Add(' vec4 DiffuseColor; ');
Add(' DiffuseColor = texture2D( MainTexture, vN ); //.rgb; ');
// Simple Lighting
Add(' vec3 L = normalize(lightVec); ');
Add(' vec3 halfAngle = normalize(L + V); ');
Add(' float NdotL = dot(L, normal); ');
Add(' float NdotH = clamp(dot(halfAngle, normal), 0.0, 1.0); ');
Add(' // "Half-Lambert" technique for more pleasing diffuse term ');
Add(' float diffuse = DiffuseColor*(0.5 * NdotL + 0.5); ');
Add(' float specular = pow(NdotH, 64.0); ');
Add(' vec4 FinalColour = AmbientColor*AmbientIntensity + ');
Add(' DiffuseColor*diffuse*DiffuseIntensity + ');
Add(' SpecularColor*specular*SpecularIntensity; ');
Add(' gl_FragColor = FinalColour; //vec4( FinalColour, 1.0 ); ');
Add('} ');
end;
FAmbientColor := TVXColor.Create(Self);
//FDiffuseColor := TVXColor.Create(Self);
FSpecularColor := TVXColor.Create(Self);
//setup initial parameters
FAmbientColor.SetColor(0.15, 0.15, 0.15, 1.0);
//FDiffuseColor.SetColor(1, 1, 1, 1);
FSpecularColor.SetColor(1.0, 1.0, 1.0, 1.0);
FAmbientFactor := 0.8;
FDiffuseFactor :=0.9;
FSpecularFactor :=0.8;
end;
destructor TVXCustomGLSLSemShader.Destroy;
begin
FAmbientColor.Destroy;
// FDiffuseColor.Destroy;
FSpecularColor.Destroy;
inherited;
end;
procedure TVXCustomGLSLSemShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject);
begin
GetGLSLProg.UseProgramObject;
//Param['DiffuseColor'].AsVector4f := FDiffuseColor.Color;
param['AmbientColor'].AsVector4f := FAmbientColor.Color;
param['SpecularColor'].AsVector4f := FSpecularColor.Color;
param['AmbientIntensity'].AsVector1f := FAmbientFactor;
param['DiffuseIntensity'].AsVector1f := FDiffuseFactor;
param['SpecularIntensity'].AsVector1f := FSpecularFactor;
// Param['SpecPower'].AsVector1f := FSpecularPower;
// Param['LightIntensity'].AsVector1f := FLightPower;
Param['MainTexture'].AsTexture2D[0] := FMainTexture;
end;
function TVXCustomGLSLSemShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean;
begin
gl.ActiveTexture(GL_TEXTURE0_ARB);
GetGLSLProg.EndUseProgramObject;
Result := False;
end;
function TVXCustomGLSLSemShader.GetMaterialLibrary: TVXAbstractMaterialLibrary;
begin
Result := FMaterialLibrary;
end;
procedure TVXCustomGLSLSemShader.SetMaterialLibrary(const Value: TVXAbstractMaterialLibrary);
begin
if FMaterialLibrary <> nil then FMaterialLibrary.RemoveFreeNotification(Self);
FMaterialLibrary := Value;
if (FMaterialLibrary <> nil)
and (FMaterialLibrary is TVXAbstractMaterialLibrary) then
FMaterialLibrary.FreeNotification(Self);
end;
procedure TVXCustomGLSLSemShader.SetMainTexTexture(const Value: TVXTexture);
begin
if FMainTexture = Value then Exit;
FMainTexture := Value;
NotifyChange(Self)
end;
function TVXCustomGLSLSemShader.GetMainTexName: TVXLibMaterialName;
begin
Result := TVXMaterialLibrary(FMaterialLibrary).GetNameOfTexture(FMainTexture);
if Result = '' then Result := FMainTexName;
end;
procedure TVXCustomGLSLSemShader.SetMainTexName(const Value: TVXLibMaterialName);
begin
// Assert(not(assigned(FMaterialLibrary)),'You must set Material Library Before');
if FMainTexName = Value then Exit;
FMainTexName := Value;
FMainTexture := TVXMaterialLibrary(FMaterialLibrary).TextureByName(FMainTexName);
NotifyChange(Self);
end;
//procedure TVXCustomGLSLSemShader.SetDiffuseColor(AValue: TVXColor);
//begin
// FDiffuseColor.DirectColor := AValue.Color;
//end;
procedure TVXCustomGLSLSemShader.SetAmbientColor(AValue: TVXColor);
begin
FAmbientColor.DirectColor := AValue.Color;
end;
procedure TVXCustomGLSLSemShader.SetSpecularColor(AValue: TVXColor);
begin
FSpecularColor.DirectColor := AValue.Color;
end;
procedure TVXCustomGLSLSemShader.Notification(AComponent: TComponent; Operation: TOperation);
var
Index: Integer;
begin
inherited;
if Operation = opRemove then
if AComponent = FMaterialLibrary then
if FMaterialLibrary <> nil then
begin
if FMainTexture <> nil then
begin
Index := TVXMaterialLibrary(FMaterialLibrary).Materials.GetTextureIndex(FMainTexture);
if Index <> -1 then
SetMainTexTexture(nil);
end;
FMaterialLibrary := nil;
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20171018 - 170941
////////////////////////////////////////////////////////////////////////////////
unit android.media.MediaCodecInfo_CodecCapabilities;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.media.MediaCodecInfo_CodecProfileLevel,
android.media.MediaFormat,
android.media.MediaCodecInfo_AudioCapabilities,
android.media.MediaCodecInfo_EncoderCapabilities,
android.media.MediaCodecInfo_VideoCapabilities;
type
JMediaCodecInfo_CodecCapabilities = interface;
JMediaCodecInfo_CodecCapabilitiesClass = interface(JObjectClass)
['{901ADD16-E09E-4160-90E2-2BB6E3392682}']
function _GetCOLOR_Format12bitRGB444 : Integer; cdecl; // A: $19
function _GetCOLOR_Format16bitARGB1555 : Integer; cdecl; // A: $19
function _GetCOLOR_Format16bitARGB4444 : Integer; cdecl; // A: $19
function _GetCOLOR_Format16bitBGR565 : Integer; cdecl; // A: $19
function _GetCOLOR_Format16bitRGB565 : Integer; cdecl; // A: $19
function _GetCOLOR_Format18BitBGR666 : Integer; cdecl; // A: $19
function _GetCOLOR_Format18bitARGB1665 : Integer; cdecl; // A: $19
function _GetCOLOR_Format18bitRGB666 : Integer; cdecl; // A: $19
function _GetCOLOR_Format19bitARGB1666 : Integer; cdecl; // A: $19
function _GetCOLOR_Format24BitABGR6666 : Integer; cdecl; // A: $19
function _GetCOLOR_Format24BitARGB6666 : Integer; cdecl; // A: $19
function _GetCOLOR_Format24bitARGB1887 : Integer; cdecl; // A: $19
function _GetCOLOR_Format24bitBGR888 : Integer; cdecl; // A: $19
function _GetCOLOR_Format24bitRGB888 : Integer; cdecl; // A: $19
function _GetCOLOR_Format25bitARGB1888 : Integer; cdecl; // A: $19
function _GetCOLOR_Format32bitABGR8888 : Integer; cdecl; // A: $19
function _GetCOLOR_Format32bitARGB8888 : Integer; cdecl; // A: $19
function _GetCOLOR_Format32bitBGRA8888 : Integer; cdecl; // A: $19
function _GetCOLOR_Format8bitRGB332 : Integer; cdecl; // A: $19
function _GetCOLOR_FormatCbYCrY : Integer; cdecl; // A: $19
function _GetCOLOR_FormatCrYCbY : Integer; cdecl; // A: $19
function _GetCOLOR_FormatL16 : Integer; cdecl; // A: $19
function _GetCOLOR_FormatL2 : Integer; cdecl; // A: $19
function _GetCOLOR_FormatL24 : Integer; cdecl; // A: $19
function _GetCOLOR_FormatL32 : Integer; cdecl; // A: $19
function _GetCOLOR_FormatL4 : Integer; cdecl; // A: $19
function _GetCOLOR_FormatL8 : Integer; cdecl; // A: $19
function _GetCOLOR_FormatMonochrome : Integer; cdecl; // A: $19
function _GetCOLOR_FormatRGBAFlexible : Integer; cdecl; // A: $19
function _GetCOLOR_FormatRGBFlexible : Integer; cdecl; // A: $19
function _GetCOLOR_FormatRawBayer10bit : Integer; cdecl; // A: $19
function _GetCOLOR_FormatRawBayer8bit : Integer; cdecl; // A: $19
function _GetCOLOR_FormatRawBayer8bitcompressed : Integer; cdecl; // A: $19
function _GetCOLOR_FormatSurface : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYCbYCr : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYCrYCb : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV411PackedPlanar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV411Planar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV420Flexible : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV420PackedPlanar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV420PackedSemiPlanar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV420Planar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV420SemiPlanar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV422Flexible : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV422PackedPlanar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV422PackedSemiPlanar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV422Planar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV422SemiPlanar : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV444Flexible : Integer; cdecl; // A: $19
function _GetCOLOR_FormatYUV444Interleaved : Integer; cdecl; // A: $19
function _GetCOLOR_QCOM_FormatYUV420SemiPlanar : Integer; cdecl; // A: $19
function _GetCOLOR_TI_FormatYUV420PackedSemiPlanar : Integer; cdecl; // A: $19
function _GetFEATURE_AdaptivePlayback : JString; cdecl; // A: $19
function _GetFEATURE_IntraRefresh : JString; cdecl; // A: $19
function _GetFEATURE_SecurePlayback : JString; cdecl; // A: $19
function _GetFEATURE_TunneledPlayback : JString; cdecl; // A: $19
function _GetcolorFormats : TJavaArray<Integer>; cdecl; // A: $1
function _GetprofileLevels : TJavaArray<JMediaCodecInfo_CodecProfileLevel>; cdecl;// A: $1
function createFromProfileLevel(mime : JString; profile : Integer; level : Integer) : JMediaCodecInfo_CodecCapabilities; cdecl;// (Ljava/lang/String;II)Landroid/media/MediaCodecInfo$CodecCapabilities; A: $9
function getAudioCapabilities : JMediaCodecInfo_AudioCapabilities; cdecl; // ()Landroid/media/MediaCodecInfo$AudioCapabilities; A: $1
function getDefaultFormat : JMediaFormat; cdecl; // ()Landroid/media/MediaFormat; A: $1
function getEncoderCapabilities : JMediaCodecInfo_EncoderCapabilities; cdecl;// ()Landroid/media/MediaCodecInfo$EncoderCapabilities; A: $1
function getMaxSupportedInstances : Integer; cdecl; // ()I A: $1
function getMimeType : JString; cdecl; // ()Ljava/lang/String; A: $1
function getVideoCapabilities : JMediaCodecInfo_VideoCapabilities; cdecl; // ()Landroid/media/MediaCodecInfo$VideoCapabilities; A: $1
function init : JMediaCodecInfo_CodecCapabilities; cdecl; // ()V A: $1
function isFeatureRequired(&name : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $11
function isFeatureSupported(&name : JString) : boolean; cdecl; // (Ljava/lang/String;)Z A: $11
function isFormatSupported(format : JMediaFormat) : boolean; cdecl; // (Landroid/media/MediaFormat;)Z A: $11
procedure _SetcolorFormats(Value : TJavaArray<Integer>) ; cdecl; // A: $1
procedure _SetprofileLevels(Value : TJavaArray<JMediaCodecInfo_CodecProfileLevel>) ; cdecl;// A: $1
property COLOR_Format12bitRGB444 : Integer read _GetCOLOR_Format12bitRGB444;// I A: $19
property COLOR_Format16bitARGB1555 : Integer read _GetCOLOR_Format16bitARGB1555;// I A: $19
property COLOR_Format16bitARGB4444 : Integer read _GetCOLOR_Format16bitARGB4444;// I A: $19
property COLOR_Format16bitBGR565 : Integer read _GetCOLOR_Format16bitBGR565;// I A: $19
property COLOR_Format16bitRGB565 : Integer read _GetCOLOR_Format16bitRGB565;// I A: $19
property COLOR_Format18BitBGR666 : Integer read _GetCOLOR_Format18BitBGR666;// I A: $19
property COLOR_Format18bitARGB1665 : Integer read _GetCOLOR_Format18bitARGB1665;// I A: $19
property COLOR_Format18bitRGB666 : Integer read _GetCOLOR_Format18bitRGB666;// I A: $19
property COLOR_Format19bitARGB1666 : Integer read _GetCOLOR_Format19bitARGB1666;// I A: $19
property COLOR_Format24BitABGR6666 : Integer read _GetCOLOR_Format24BitABGR6666;// I A: $19
property COLOR_Format24BitARGB6666 : Integer read _GetCOLOR_Format24BitARGB6666;// I A: $19
property COLOR_Format24bitARGB1887 : Integer read _GetCOLOR_Format24bitARGB1887;// I A: $19
property COLOR_Format24bitBGR888 : Integer read _GetCOLOR_Format24bitBGR888;// I A: $19
property COLOR_Format24bitRGB888 : Integer read _GetCOLOR_Format24bitRGB888;// I A: $19
property COLOR_Format25bitARGB1888 : Integer read _GetCOLOR_Format25bitARGB1888;// I A: $19
property COLOR_Format32bitABGR8888 : Integer read _GetCOLOR_Format32bitABGR8888;// I A: $19
property COLOR_Format32bitARGB8888 : Integer read _GetCOLOR_Format32bitARGB8888;// I A: $19
property COLOR_Format32bitBGRA8888 : Integer read _GetCOLOR_Format32bitBGRA8888;// I A: $19
property COLOR_Format8bitRGB332 : Integer read _GetCOLOR_Format8bitRGB332; // I A: $19
property COLOR_FormatCbYCrY : Integer read _GetCOLOR_FormatCbYCrY; // I A: $19
property COLOR_FormatCrYCbY : Integer read _GetCOLOR_FormatCrYCbY; // I A: $19
property COLOR_FormatL16 : Integer read _GetCOLOR_FormatL16; // I A: $19
property COLOR_FormatL2 : Integer read _GetCOLOR_FormatL2; // I A: $19
property COLOR_FormatL24 : Integer read _GetCOLOR_FormatL24; // I A: $19
property COLOR_FormatL32 : Integer read _GetCOLOR_FormatL32; // I A: $19
property COLOR_FormatL4 : Integer read _GetCOLOR_FormatL4; // I A: $19
property COLOR_FormatL8 : Integer read _GetCOLOR_FormatL8; // I A: $19
property COLOR_FormatMonochrome : Integer read _GetCOLOR_FormatMonochrome; // I A: $19
property COLOR_FormatRGBAFlexible : Integer read _GetCOLOR_FormatRGBAFlexible;// I A: $19
property COLOR_FormatRGBFlexible : Integer read _GetCOLOR_FormatRGBFlexible;// I A: $19
property COLOR_FormatRawBayer10bit : Integer read _GetCOLOR_FormatRawBayer10bit;// I A: $19
property COLOR_FormatRawBayer8bit : Integer read _GetCOLOR_FormatRawBayer8bit;// I A: $19
property COLOR_FormatRawBayer8bitcompressed : Integer read _GetCOLOR_FormatRawBayer8bitcompressed;// I A: $19
property COLOR_FormatSurface : Integer read _GetCOLOR_FormatSurface; // I A: $19
property COLOR_FormatYCbYCr : Integer read _GetCOLOR_FormatYCbYCr; // I A: $19
property COLOR_FormatYCrYCb : Integer read _GetCOLOR_FormatYCrYCb; // I A: $19
property COLOR_FormatYUV411PackedPlanar : Integer read _GetCOLOR_FormatYUV411PackedPlanar;// I A: $19
property COLOR_FormatYUV411Planar : Integer read _GetCOLOR_FormatYUV411Planar;// I A: $19
property COLOR_FormatYUV420Flexible : Integer read _GetCOLOR_FormatYUV420Flexible;// I A: $19
property COLOR_FormatYUV420PackedPlanar : Integer read _GetCOLOR_FormatYUV420PackedPlanar;// I A: $19
property COLOR_FormatYUV420PackedSemiPlanar : Integer read _GetCOLOR_FormatYUV420PackedSemiPlanar;// I A: $19
property COLOR_FormatYUV420Planar : Integer read _GetCOLOR_FormatYUV420Planar;// I A: $19
property COLOR_FormatYUV420SemiPlanar : Integer read _GetCOLOR_FormatYUV420SemiPlanar;// I A: $19
property COLOR_FormatYUV422Flexible : Integer read _GetCOLOR_FormatYUV422Flexible;// I A: $19
property COLOR_FormatYUV422PackedPlanar : Integer read _GetCOLOR_FormatYUV422PackedPlanar;// I A: $19
property COLOR_FormatYUV422PackedSemiPlanar : Integer read _GetCOLOR_FormatYUV422PackedSemiPlanar;// I A: $19
property COLOR_FormatYUV422Planar : Integer read _GetCOLOR_FormatYUV422Planar;// I A: $19
property COLOR_FormatYUV422SemiPlanar : Integer read _GetCOLOR_FormatYUV422SemiPlanar;// I A: $19
property COLOR_FormatYUV444Flexible : Integer read _GetCOLOR_FormatYUV444Flexible;// I A: $19
property COLOR_FormatYUV444Interleaved : Integer read _GetCOLOR_FormatYUV444Interleaved;// I A: $19
property COLOR_QCOM_FormatYUV420SemiPlanar : Integer read _GetCOLOR_QCOM_FormatYUV420SemiPlanar;// I A: $19
property COLOR_TI_FormatYUV420PackedSemiPlanar : Integer read _GetCOLOR_TI_FormatYUV420PackedSemiPlanar;// I A: $19
property FEATURE_AdaptivePlayback : JString read _GetFEATURE_AdaptivePlayback;// Ljava/lang/String; A: $19
property FEATURE_IntraRefresh : JString read _GetFEATURE_IntraRefresh; // Ljava/lang/String; A: $19
property FEATURE_SecurePlayback : JString read _GetFEATURE_SecurePlayback; // Ljava/lang/String; A: $19
property FEATURE_TunneledPlayback : JString read _GetFEATURE_TunneledPlayback;// Ljava/lang/String; A: $19
property colorFormats : TJavaArray<Integer> read _GetcolorFormats write _SetcolorFormats;// [I A: $1
property profileLevels : TJavaArray<JMediaCodecInfo_CodecProfileLevel> read _GetprofileLevels write _SetprofileLevels;// [Landroid/media/MediaCodecInfo$CodecProfileLevel; A: $1
end;
[JavaSignature('android/media/MediaCodecInfo_CodecCapabilities')]
JMediaCodecInfo_CodecCapabilities = interface(JObject)
['{D1E67D54-19C1-4198-A202-8E11CA8D5BDD}']
function _GetcolorFormats : TJavaArray<Integer>; cdecl; // A: $1
function _GetprofileLevels : TJavaArray<JMediaCodecInfo_CodecProfileLevel>; cdecl;// A: $1
function getAudioCapabilities : JMediaCodecInfo_AudioCapabilities; cdecl; // ()Landroid/media/MediaCodecInfo$AudioCapabilities; A: $1
function getDefaultFormat : JMediaFormat; cdecl; // ()Landroid/media/MediaFormat; A: $1
function getEncoderCapabilities : JMediaCodecInfo_EncoderCapabilities; cdecl;// ()Landroid/media/MediaCodecInfo$EncoderCapabilities; A: $1
function getMaxSupportedInstances : Integer; cdecl; // ()I A: $1
function getMimeType : JString; cdecl; // ()Ljava/lang/String; A: $1
function getVideoCapabilities : JMediaCodecInfo_VideoCapabilities; cdecl; // ()Landroid/media/MediaCodecInfo$VideoCapabilities; A: $1
procedure _SetcolorFormats(Value : TJavaArray<Integer>) ; cdecl; // A: $1
procedure _SetprofileLevels(Value : TJavaArray<JMediaCodecInfo_CodecProfileLevel>) ; cdecl;// A: $1
property colorFormats : TJavaArray<Integer> read _GetcolorFormats write _SetcolorFormats;// [I A: $1
property profileLevels : TJavaArray<JMediaCodecInfo_CodecProfileLevel> read _GetprofileLevels write _SetprofileLevels;// [Landroid/media/MediaCodecInfo$CodecProfileLevel; A: $1
end;
TJMediaCodecInfo_CodecCapabilities = class(TJavaGenericImport<JMediaCodecInfo_CodecCapabilitiesClass, JMediaCodecInfo_CodecCapabilities>)
end;
const
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format12bitRGB444 = 3;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format16bitARGB1555 = 5;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format16bitARGB4444 = 4;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format16bitBGR565 = 7;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format16bitRGB565 = 6;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format18BitBGR666 = 41;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format18bitARGB1665 = 9;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format18bitRGB666 = 8;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format19bitARGB1666 = 10;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format24BitABGR6666 = 43;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format24BitARGB6666 = 42;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format24bitARGB1887 = 13;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format24bitBGR888 = 12;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format24bitRGB888 = 11;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format25bitARGB1888 = 14;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format32bitABGR8888 = 2130747392;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format32bitARGB8888 = 16;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format32bitBGRA8888 = 15;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_Format8bitRGB332 = 2;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatCbYCrY = 27;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatCrYCbY = 28;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatL16 = 36;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatL2 = 33;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatL24 = 37;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatL32 = 38;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatL4 = 34;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatL8 = 35;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatMonochrome = 1;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatRGBAFlexible = 2134288520;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatRGBFlexible = 2134292616;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatRawBayer10bit = 31;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatRawBayer8bit = 30;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatRawBayer8bitcompressed = 32;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatSurface = 2130708361;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYCbYCr = 25;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYCrYCb = 26;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV411PackedPlanar = 18;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV411Planar = 17;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV420Flexible = 2135033992;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV420PackedPlanar = 20;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV420PackedSemiPlanar = 39;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV420Planar = 19;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV420SemiPlanar = 21;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV422Flexible = 2135042184;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV422PackedPlanar = 23;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV422PackedSemiPlanar = 40;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV422Planar = 22;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV422SemiPlanar = 24;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV444Flexible = 2135181448;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_FormatYUV444Interleaved = 29;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_QCOM_FormatYUV420SemiPlanar = 2141391872;
TJMediaCodecInfo_CodecCapabilitiesCOLOR_TI_FormatYUV420PackedSemiPlanar = 2130706688;
TJMediaCodecInfo_CodecCapabilitiesFEATURE_AdaptivePlayback = 'adaptive-playback';
TJMediaCodecInfo_CodecCapabilitiesFEATURE_IntraRefresh = 'intra-refresh';
TJMediaCodecInfo_CodecCapabilitiesFEATURE_SecurePlayback = 'secure-playback';
TJMediaCodecInfo_CodecCapabilitiesFEATURE_TunneledPlayback = 'tunneled-playback';
implementation
end.
|
unit Demo.GanttChart.NoDependencies;
interface
uses
System.Classes, System.SysUtils, System.Variants, Demo.BaseFrame, cfs.GCharts;
type
TDemo_GanttChart_NoDependencies = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_GanttChart_NoDependencies.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_GANTT_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Task ID'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Task Name'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Resource'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Start Date'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'End Date'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Duration'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Percent Complete'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Dependencies')
]);
Chart.Data.AddRow(['2014Spring', 'Spring 2014', 'spring', EncodeDate(2014, 3, 22), EncodeDate(2014, 6, 20), null, 100, null]);
Chart.Data.AddRow(['2014Summer', 'Summer 2014', 'summer', EncodeDate(2014, 6, 21), EncodeDate(2014, 9, 20), null, 100, null]);
Chart.Data.AddRow(['2014Autumn', 'Autumn 2014', 'autumn', EncodeDate(2014, 9, 21), EncodeDate(2014, 12, 20), null, 100, null]);
Chart.Data.AddRow(['2014Winter', 'Winter 2014', 'winter', EncodeDate(2014, 12, 21), EncodeDate(2015, 3, 21), null, 100, null]);
Chart.Data.AddRow(['2015Spring', 'Spring 2015', 'spring', EncodeDate(2015, 3, 22), EncodeDate(2015, 6, 20), null, 50, null]);
Chart.Data.AddRow(['2015Summer', 'Summer 2015', 'summer', EncodeDate(2015, 6, 21), EncodeDate(2015, 9, 20), null, 0, null]);
Chart.Data.AddRow(['2015Autumn', 'Autumn 2015', 'autumn', EncodeDate(2015, 9, 21), EncodeDate(2015, 12, 20), null, 0, null]);
Chart.Data.AddRow(['2015Winter', 'Winter 2015', 'winter', EncodeDate(2015, 12, 21), EncodeDate(2016, 3, 21), null, 0, null]);
Chart.Data.AddRow(['Football', 'Football Season', 'sports', EncodeDate(2014, 9, 4), EncodeDate(2015, 2, 1), null, 100, null]);
Chart.Data.AddRow(['Baseball', 'Baseball Season', 'sports', EncodeDate(2015, 3, 31), EncodeDate(2015, 10, 20), null, 14, null]);
Chart.Data.AddRow(['Basketball', 'Basketball Season', 'sports', EncodeDate(2014, 10, 28), EncodeDate(2015, 6, 20), null, 86, null]);
Chart.Data.AddRow(['Hockey', 'Hockey Season', 'sports', EncodeDate(2014, 10, 8), EncodeDate(2015, 6, 21), null, 89, null]);
// Options
Chart.Options.Gantt('trackHeight', 30);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="margin: auto; width: 80%; height: 100%; padding: 100px;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_GanttChart_NoDependencies);
end.
|
unit MRpuppySettingCls;
interface
type
TMRPuppyGlobalSetting = class
private
FIdCategory
public
getPetCategoryList: TList;
getServiceCategoryList: TList;
getKitCategoryList: TList;
end;
implementation
end.
|
unit Time;{Модуль времени}
interface
function TimeF: word;{функция, в которую мы сохраняем нынешнее время системы}
implementation
uses
dos;{Подключаем dos, чтобы мы могли использоать процедуру gettime}
function TimeF;
var
h, min, sec, hsec: word;{Переменные, в которые процедура gettime записывает текущее количество
часов, минут, сикунд и милисекунд}
begin
gettime(h,min,sec,hsec); {Записываем текущее время системы}
TimeF := h * 3600000 + min * 6000 + sec * 100 + hsec; {Переводим текущее время в милисекунды}
end;
end. |
unit ClsDAOPrincipal;
interface
uses
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
Data.DB,
FireDAC.Comp.Client,
FireDAC.Phys.IBBase,
FireDAC.Phys.IB,
FireDAC.Phys.FB,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.VCLUI.Wait,
FireDAC.Comp.UI,
FireDAC.DApt;
type
TDAOPrincipal = class
private
FPathDataBase: string;
FConexao: TFDConnection;
FTransacao: TFDTransaction;
FEventosBD: TFDEventAlerter;
procedure DoAlert(ASender: TFDCustomEventAlerter; const AEventName: String; const AArgument: Variant);
function getStringConection: string;
public
constructor Create(const PathDataBase: string);
procedure Conectar;
procedure Desconectar;
procedure AssociaTransacao;
procedure ConfirmaTransacao;
procedure CancelaTransacao;
function getConsulta(const QueryStr: string): TFDQuery;
function getProcedimento(const NomeProc: string): TFDStoredProc;
function getComando: TFDCommand;
end;
implementation
uses
System.SysUtils;
{ TDAOPrincipal }
procedure TDAOPrincipal.AssociaTransacao;
begin
if not Assigned(FTransacao) then begin
self.FTransacao := TFDTransaction.Create(nil);
self.FTransacao.Connection := FConexao;
self.FTransacao.StartTransaction;
end;
end;
procedure TDAOPrincipal.CancelaTransacao;
begin
if Assigned(FTransacao) then begin
self.FTransacao.Rollback;
FreeAndNil(FTransacao);
end;
end;
procedure TDAOPrincipal.Conectar;
begin
if not Assigned(FConexao) then begin
FConexao := TFDConnection.Create(nil);
FConexao.Params.Clear;
FConexao.LoginPrompt := false;
FConexao.Open(self.getStringConection);
FEventosBD := TFDEventAlerter.Create(nil);
FEventosBD.Connection := FConexao;
FEventosBD.Options.Synchronize := True;
FEventosBD.Options.Timeout := 10000;
FEventosBD.OnAlert := DoAlert;
FEventosBD.Active := True;
FEventosBD.Names.Clear;
FEventosBD.Names.Add('TESTE');
end;
end;
procedure TDAOPrincipal.ConfirmaTransacao;
begin
if Assigned(FTransacao) then begin
self.FTransacao.Commit;
FreeAndNil(FTransacao);
end;
end;
constructor TDAOPrincipal.Create(const PathDataBase: string);
begin
FPathDataBase := PathDataBase;
end;
procedure TDAOPrincipal.Desconectar;
begin
self.FConexao.Connected := false;
self.FConexao.Close;
end;
procedure TDAOPrincipal.DoAlert(ASender: TFDCustomEventAlerter; const AEventName: String; const AArgument: Variant);
begin
// if CompareText(AEventName, 'Customers') = 0 then qryCustomers.Refresh;
end;
function TDAOPrincipal.getComando: TFDCommand;
begin
Result := TFDCommand.Create(nil);
Result.Connection := FConexao;
Result.Prepare();
end;
function TDAOPrincipal.getConsulta(const QueryStr: string): TFDQuery;
begin
Result := TFDQuery.Create(nil);
Result.Connection := FConexao;
if QueryStr <> EmptyStr then Result.SQL.Add(QueryStr);
end;
function TDAOPrincipal.getProcedimento(const NomeProc: string): TFDStoredProc;
begin
Result := TFDStoredProc.Create(nil);
Result.Connection := FConexao;
Result.StoredProcName := NomeProc;
Result.Prepare;
end;
function TDAOPrincipal.getStringConection: string;
begin
result := ' Database='+ FPathDataBase + ';' +
' User_Name=SYSDBA; '+
' Password=masterkey; '+
' CharacterSet=WIN1252; '+
' DriverID=IB; '+
' Protocol=TCPIP; '+
' Server=localhost;';
end;
end.
|
unit TestThItemRectangle;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, BaseTestUnit, FMX.Types, FMX.Forms, FMX.StdCtrls,
System.UITypes, System.Types, System.SysUtils, FMX.Controls, System.UIConsts;
type
// #18 캔버스에 사각형을 추가한다.
TestTThRectangle = class(TThCanvasBaseTestUnit)
private
FTestClick: Boolean;
procedure _Test(Sender: TObject);
published
procedure TestItemFactory;
// #36 마우스 드래그로 시작점과 끝점을 이용해 도형을 그린다.
procedure TestDrawRectangle;
// #56 사각형 영역을 클릭하면 사각형이 선택되어야 한다.
procedure TestRectangleSelect;
// #54 캔버스 트래킹 이후 마우스 드래그 시 드래그한 위치에 그려져야 한다.
procedure TestCanvasTrackingAndDrawRectangle;
// #53 캔버스 Tracking 시 Rectangle이 Canvas 영역 밖으로 나오지 않는다.
procedure TestRectangleOutOfCanvas;
{$IFDEF ON_HIGHLIGHT}
// #68 도형 선택 시 하이라이트 효과가 나타나야 한다.
procedure TestRectangleSelectionHighlight;
// #38 도형에 마우스 오버시 하이라이트 효과가 나타난다.
procedure TestRectangleMouseOverHighlight;
{$ENDIF}
// #37 끝점이 시작점 앞에 있어도 그려져야 한다.
procedure TestDrawRectangleEx;
// #42 최소 크기를 갖으며 그리거나 크기 조정시 반영된다.
procedure TestDrawRectangleMinSize;
// #72 캔버스 영역 밖으로 이동이 가능해야 한다.
procedure TestMoveRectangleOutOfCanvas;
{$IFDEF ON_HIGHLIGHT}
// #69 도형 선택 후 다른 도형 선택 시 이전 도형의 하이라이트 효과는 없어져야 한다.
procedure TestHideHighlightFromBeforeSelections;
{$ENDIF}
// #94 아이템 추가 후 바로 이동 시 TopLeft Spot의 잔상이 남음
procedure BugTestCreateAndMoveAfterPaint;
// #133 도형 그릴때에는 도형위에 중복하여 그린다.
procedure TestDrawOverItem;
end;
implementation
uses
FMX.TestLib, ThItem, ThShapeItem, ThItemFactory, ThConsts;
{ TestTThShape }
procedure TestTThRectangle._Test(Sender: TObject);
begin
FTestClick := True;
end;
procedure TestTThRectangle.TestItemFactory;
var
Item: TThItem;
begin
// Not assigned number 0
Item := ItemFactory.Get(0);
try
Check(not Assigned(Item));
finally
if Assigned(Item) then
Item.Free;
end;
// 1100 is Rectangle
Item := ItemFactory.Get(1100);
try
Check(Assigned(Item));
finally
if Assigned(Item) then
Item.Free;
end;
end;
procedure TestTThRectangle.TestDrawRectangle;
var
Item: TThItem;
begin
// Draw
DrawRectangle(50, 50, 200, 200);
// Select
TestLib.RunMouseClick(100, 100);
Item := FCanvas.SelectedItem;
Check(Assigned(Item), 'Check SelectedItem');
Check(Item.ClassType = TThRectangle, 'Check Class type');
Check(Item.Position.X = -100, Format('X = %f', [Item.Position.X]));
Check(Item.Width = 150, Format('Width = %f', [Item.Width]));
end;
// S1.100,50 으로 Canvas 이동 후 0,0 > 100, 100 Rectangle 그리면
// Rectangle의 좌표는 -100, -50 이어야 한다.
procedure TestTThRectangle.TestCanvasTrackingAndDrawRectangle;
var
Item: TThItem;
begin
FCanvas.TrackAnimated := False;
// Tracking
MousePath.New
.Add(0, 0)
.Add(10, 0)
.Add(100, 50);
TestLib.RunMousePath(MousePath.Path);
Check(FCanvas.ViewPortPosition.X = 250, Format('ViewPortPosition.X: %f', [FCanvas.ViewPortPosition.X]));
// Draw Rectangle
DrawRectangle(10, 10, 100, 100);
Check(FCanvas.ItemCount = 1);
// Select
TestLib.RunMouseClick(50, 50);
Item := FCanvas.SelectedItem;
Check(Assigned(Item), 'not assigned');
Check(Item.Position.X = -240, Format('Postion.X : %f', [Item.Position.X]));
Check(Item.Position.Y = -190, Format('Postion.Y : %f', [Item.Position.Y]));
end;
procedure TestTThRectangle.TestRectangleSelect;
begin
// Draw Rectangle
DrawRectangle(50, 50, 100, 100);
// Select
TestLib.RunMouseClick(60, 60);
Check(Assigned(FCanvas.SelectedItem));
end;
// S1.0,0에 Rectangle을 그리고 -100, -100 이동한 후
// -30, -30을 클릭하면 그영역에 있는 버튼이 클릭되야 한다.
procedure TestTThRectangle.TestRectangleOutOfCanvas;
var
Button: TButton;
begin
Button := TButton.Create(FForm);
Button.Parent := FForm;
Button.Position.Point := PointF(0,0);
Button.OnClick := _Test;
Button.Width := 50;
Button.Height := 100;
Button.SendToBack;
// Draw Rectangle
DrawRectangle(10, 10, 150, 150);
// Canvas Tracking
MousePath.New
.Add(160, 160)
.Add(80, 80)
.Add(60, 60);
TestLib.RunMousePath(MousePath.Path);
// Button Click
TestLib.RunMouseClick(-30, -30);
// Check(FCanvas.SelectedItem.LocalToAbsolute(PointF(0, 0)).X = -30, Format('Postion.X : %f', [FCanvas.SelectedItem.LocalToAbsolute(PointF(0, 0)).X]));
Check(FTestClick, '버튼이 클릭되지 않음');
end;
{$IFDEF ON_HIGHLIGHT}
procedure TestTThRectangle.TestRectangleSelectionHighlight;
var
AC: TAlphaColor;
begin
// 그리기
DrawRectangle(10, 10, 100, 100);
// 클릭 선택
TestLib.RunMouseClick(50, 50);
// 105.50 색상확인
AC := TestLib.GetControlPixelColor(FCanvas, 100 + (ItemHighlightSize - 1), 50);
Check(AC = ItemHighlightColor, 'Not matching Color');
end;
procedure TestTThRectangle.TestRectangleMouseOverHighlight;
var
AC: TAlphaColor;
begin
// 추가
DrawRectangle(10, 10, 100, 100);
// 선택
TestLib.RunMouseClick(50, 50);
FCanvas.BgColor := claPink;
// 선택해제
TestLib.RunMouseClick(150, 150);
AC := TestLib.GetControlPixelColor(FCanvas, 100 + (ItemHighlightSize - 1), 100 + (ItemHighlightSize - 1));
Check(AC <> ItemHighlightColor, 'Canvas color is not highlight color');
MousePath.New
.Add(150, 150)
.Add(50, 50);
TestLib.RunMouseMove(MousePath.Path);
// 그림자 확인
AC := TestLib.GetControlPixelColor(FCanvas, 100 + (ItemHighlightSize - 1), 100 + (ItemHighlightSize - 1));
Check(AC = ItemHighlightColor, 'Not matching Color');
// Check(AC = claGray, 'Not matching Color');
end;
{$ENDIF}
procedure TestTThRectangle.TestDrawRectangleEx;
begin
// BRToTL
DrawRectangle(200, 100, 110, 10);
TestLib.RunMouseClick(150, 50);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned BRToTL');
Check(FCanvas.SelectedItem.Position.X = -40, Format('BottomRight > TopLeft - X : %f', [FCanvas.SelectedItem.Position.X]));
// TRToBL
DrawRectangle(100, 110, 10, 200);
TestLib.RunMouseClick(50, 150);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned TRToBL');
Check(FCanvas.SelectedItem.Position.X = -140, Format('TopRight > BottomLeft - X : %f', [FCanvas.SelectedItem.Position.X]));
// BLToTR
DrawRectangle(110, 200, 200, 110);
TestLib.RunMouseClick(150, 150);
Check(Assigned(FCanvas.SelectedItem), 'Not assigned BLToTR');
Check(FCanvas.SelectedItem.Position.X = -40, Format('BottomLeft > TopRight - X : %f', [FCanvas.SelectedItem.Position.X]));
end;
procedure TestTThRectangle.TestDrawRectangleMinSize;
begin
DrawRectangle(10, 10, 10, 10);
TestLib.RunMouseClick(35, 35); // MinSize 30, 30 : 10,10 > 40, 40
Check(Assigned(FCanvas.SelectedItem), 'Empty Rect');
// TLToBR
DrawRectangle(10, 10, 30, 30);
TestLib.RunMouseClick(35, 35); // MinSize 30, 30 : 10,10 > 40, 40
Check(Assigned(FCanvas.SelectedItem), 'TLToBR');
// TRToBL
DrawRectangle(60, 30, 80, 10);
TestLib.RunMouseClick(85, 5); // MinSize 30, 30 : 10,0 > 40, 30
Check(Assigned(FCanvas.SelectedItem), 'TRToBL');
// BLToTR
DrawRectangle(30, 60, 10, 80);
TestLib.RunMouseClick(5, 85); // MinSize 30, 30 : 0,10 > 30, 40
Check(Assigned(FCanvas.SelectedItem), 'BLToTR');
// BRToTL
DrawRectangle(80, 80, 60, 60);
TestLib.RunMouseClick(55, 55); // MinSize 30, 30 : 0,0 > 30, 30
Check(Assigned(FCanvas.SelectedItem), 'BRToTL');
end;
procedure TestTThRectangle.TestMoveRectangleOutOfCanvas;
var
Item: TThItem;
begin
DrawRectangle(10, 10, 100, 100);
// 밖에서 안으로 드래그
MousePath.New
.Add(50, 50)
.Add(-100, 200)
.Add(200, 200);
TestLib.RunMousePath(MousePath.Path);
// 선택
TestLib.RunMouseClick(200, 200);
Item := FCanvas.SelectedItem;
Check(Assigned(Item), 'Not assigned');
end;
{$IFDEF ON_HIGHLIGHT}
procedure TestTThRectangle.TestHideHighlightFromBeforeSelections;
var
AC: TAlphaColor;
begin
// 2개 그리기
DrawRectangle(10, 10, 40, 40); // A
DrawRectangle(60, 60, 90, 90); // B
// 선택 B
TestLib.RunMouseClick(75, 75);
// B 선택 그림자 확인
AC := TestLib.GetControlPixelColor(FCanvas, 90 + (ItemHighlightSize - 1), 75);
Check(AC = ItemHighlightColor, 'Check Show Highlight(B)');
// 선택 A
TestLib.RunMouseClick(25, 25);
// B 그림자 없어짐
AC := TestLib.GetControlPixelColor(FCanvas, 90 + (ItemHighlightSize - 1), 75);
Check(AC <> ItemHighlightColor, 'Check Hide Highlight(B)');
// A 선택 그림자 확인
AC := TestLib.GetControlPixelColor(FCanvas, 40 + (ItemHighlightSize - 1), 25);
Check(AC = ItemHighlightColor, 'Check Show Highlight(A)');
end;
{$ENDIF}
procedure TestTThRectangle.BugTestCreateAndMoveAfterPaint;
var
ExceptL: Integer;
AC: TAlphaColor;
X, Y: Single;
P: TPointF;
begin
FCanvas.BgColor := claRed;
{ Screen shot을 위해 폼 활성화 체크 }
ExceptL := 0;
P := IControl(FCanvas).LocalToScreen(PointF(100, 100));
while TestLib.GetBitmapPixelColor(P.X, P.Y) <> claRed do
begin
// Application.ProcessMessages;
// Sleep(0);
Inc(ExceptL);
if ExceptL > 2 then
begin
Check(False, 'Checking Testcase - Activate Form');
end;
end;
{ Screen shot을 위해 폼 활성화 체크 }
DrawRectangle(10, 10, 100, 100);
MousePath.New
.Add(50, 50)
.Add(100, 100)
.Add(150, 150);
TestLib.RunMousePath(MousePath.Path);
X := 10-ItemHighlightSize+2;
Y := 10-ItemHighlightSize+2;
P := IControl(FCanvas).LocalToScreen(PointF(X, Y));
AC := TestLib.GetBitmapPixelColor(P.X, P.Y);
Check(AC = claRed, 'Showing Afterpaint');
end;
procedure TestTThRectangle.TestDrawOverItem;
begin
DrawRectangle(10, 10, 100, 100);
DrawRectangle(50, 50, 200, 200);
TestLib.RunMouseClick(150, 150);
Check(Assigned(FCanvas.SelectedItem), 'Drawing item over of item');
end;
initialization
RegisterTest(TestTThRectangle.Suite);
end.
|
unit UDSortFieldBuild;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeBuildSortFieldDlg = class(TForm)
pnlBuildSort: TPanel;
lblSummaryType: TLabel;
lblSummaryField: TLabel;
lblGroupField: TLabel;
lblLeftBracket: TLabel;
lblRightBracket: TLabel;
lblComma: TLabel;
cbSummaryType: TComboBox;
cbGroupField: TComboBox;
btnCancel: TButton;
btnOk: TButton;
cbSummaryField: TComboBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
rField : string;
end;
var
CrpeBuildSortFieldDlg: TCrpeBuildSortFieldDlg;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeBuildSortFieldDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeBuildSortFieldDlg.FormShow(Sender: TObject);
var
i : integer;
s1,s2 : string;
begin
{Check for Groups}
cbGroupField.Clear;
cbGroupField.Items.AddStrings(Cr.Groups.Names);
{Summary Fields}
cbSummaryField.Clear;
cbSummaryField.Items.AddStrings(Cr.Tables.FieldNames);
{If we are editing, parse the current GroupSortField}
if Caption = 'Edit GroupSortField' then
begin
{Summary Type}
i := Pos('(', Cr.GroupSortFields.Item.FieldName);
if i > 0 then
begin
s1 := Trim(Copy(Cr.GroupSortFields.Item.FieldName,0,i-1));
cbSummaryType.ItemIndex := cbSummaryType.Items.IndexOf(s1);
end;
{Summary Field}
s1 := Copy(Cr.GroupSortFields.Item.FieldName,i+1,Length(Cr.GroupSortFields.Item.FieldName));
i := Pos('}', s1);
if i > 0 then
begin
s2 := Trim(Copy(s1,0,i));
cbSummaryField.ItemIndex := cbSummaryField.Items.IndexOf(s2);
end;
{Group Field}
s1 := Copy(s1,i+1,Length(s1));
i := Pos('{', s1);
if i > 0 then
begin
s1 := Trim(Copy(s1,i,Length(s1)));
i := Pos('}', s1);
if i > 0 then
begin
s2 := Copy(s1,0,i);
cbGroupField.ItemIndex := cbGroupField.Items.IndexOf(s2);
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeBuildSortFieldDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
end;
{------------------------------------------------------------------------------}
{ btnCancelClick }
{------------------------------------------------------------------------------}
procedure TCrpeBuildSortFieldDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeBuildSortFieldDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
rField := '';
if ModalResult = mrOk then
rField := cbSummaryType.Text + '(' +
cbSummaryField.Text + ',' + cbGroupField.Text + ')';
Release;
end;
end.
|
program questao28;
{
Autor: Hugo Deiró Data: 23/06/2012
- Este programa recebe um tipo de carne
e a quantidade de carne comprada. Caso a
compra seja paga no cartão, há um desconto de 5%.
}
var
tipo_carne : string[10];
resposta : string[3];
KG : integer;
preco : real;
begin
writeln('OPÇÕES DE CARNE: ');
writeln;
writeln('- Filé Duplo');
writeln('- Alcatra');
writeln('- Picanha');
writeln;
writeln('Qual é o tipo desejado?');
readln(tipo_carne);
tipo_carne := upcase(tipo_carne);
if(tipo_carne = 'FILÉ DUPLO')then
tipo_carne := 'FILE DUPLO';
if(tipo_carne <> 'FILE DUPLO') and (tipo_carne <> 'ALCATRA') and (tipo_carne <> 'PICANHA')then
writeln('Tipo de carne não cadastrado!')
else
begin
write('Insira quantos KG de ',tipo_carne,' você deseja comprar: ');
readln(KG);
if(KG < 0)then
writeln('Valor Inválido!')
else
begin
if(tipo_carne = 'FILE DUPLO')then
if(KG <= 5)then
preco := 4.9
else
preco := 5.8;
if(tipo_carne = 'ALCATRA')then
if(KG <= 5)then
preco := 5.9
else
preco := 6.8;
if(tipo_carne = 'PICANHA')then
if(KG <= 5)then
preco := 6.9
else
preco := 7.8;
writeln('O pagamento será no cartão? Sim ou Não?');
read(resposta);
resposta := upcase(resposta);
if(resposta = 'SIM')then
preco := preco - (preco*0.05);
writeln;
writeln('KG de ',tipo_carne,' comprados: ',KG);
writeln('Pagamento no cartão: ',resposta);
writeln('Valor final: ',KG*preco:6:2);
end;
end;
end.
|
unit TITaxInvoicesEdit_AddInNakl;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, cxLookAndFeelPainters, cxButtons,
cxTextEdit, cxButtonEdit, cxControls, cxContainer, cxEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, Ibase,TiCommonProc,TICommonLoader,TiMessages,
cxCurrencyEdit,Registry,TITaxinvoicesEdit_DM, Spin;
type TTITaxInvoicesAddVidNaklDelivery=record
id_range_of_delivery : Integer;
Name_range_of_delivery : string;
Id_Measures : Integer;
Name_Measures : string;
id_kod_tovar : Integer;
Name_Kod_tovar : string;
Num_Kod_tovar : string;
end;
type
TTaxInvoicesEditAddInNaklForm = class(TForm)
Panel1: TPanel;
SummaGroupBox: TGroupBox;
ValueDeliveryExportLabel: TLabel;
ValueDelivery20Label: TLabel;
ValueDeliveryVATexemptionsLabel: TLabel;
PostavkaGroupBox: TGroupBox;
MeasuresLabel: TLabel;
PriceLabel: TLabel;
ValueDeliveryCustomsLabel: TLabel;
KolVoLabel: TLabel;
MeasuresButtonEdit: TcxButtonEdit;
YesButton: TcxButton;
CancelButton: TcxButton;
PriceCurrencyEdit: TcxCurrencyEdit;
ValueDelivery20CurrencyEdit: TcxCurrencyEdit;
ValueDeliveryExportCurrencyEdit: TcxCurrencyEdit;
ValueDeliveryCustomsCurrencyEdit: TcxCurrencyEdit;
ValueDeliveryVATexemptionsCurrencyEdit: TcxCurrencyEdit;
DataGroupBox: TGroupBox;
DateShipmentEdit: TcxDateEdit;
DateShipmentLabel: TLabel;
RangeOfDeliveryButtonEdit: TcxButtonEdit;
RangeOfDeliveryLabel: TLabel;
KolVoTextEdit: TcxTextEdit;
GroupBox1: TGroupBox;
KodTovarCheckBox: TCheckBox;
KodTovarButtonEdit: TcxButtonEdit;
MonthList: TComboBox;
YearSpinEdit: TSpinEdit;
ZaCheckBox: TCheckBox;
procedure cxButtonEdit2PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure CancelButtonClick(Sender: TObject);
procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure YesButtonClick(Sender: TObject);
procedure ValueDelivery20CurrencyEditExit(Sender: TObject);
procedure DateShipmentEditKeyPress(Sender: TObject; var Key: Char);
procedure RangeOfDeliveryButtonEditKeyPress(Sender: TObject;
var Key: Char);
procedure MeasuresButtonEditKeyPress(Sender: TObject; var Key: Char);
procedure KolVoTextEditKeyPress(Sender: TObject; var Key: Char);
procedure PriceCurrencyEditKeyPress(Sender: TObject; var Key: Char);
procedure ValueDelivery20CurrencyEditKeyPress(Sender: TObject;
var Key: Char);
procedure ValueDeliveryExportCurrencyEditKeyPress(Sender: TObject;
var Key: Char);
procedure ValueDeliveryVATexemptionsCurrencyEditKeyPress(
Sender: TObject; var Key: Char);
procedure FormActivate(Sender: TObject);
procedure ValueDeliveryCustomsCurrencyEditKeyPress(Sender: TObject;
var Key: Char);
procedure KodTovarButtonEditClick(Sender: TObject);
procedure KodTovarButtonEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure KodTovarCheckBoxClick(Sender: TObject);
procedure ZaCheckBoxClick(Sender: TObject);
private
PRes : Variant;
PDb_Handle : TISC_DB_HANDLE;
PParameter : TTITaxInvoicesAddVidNaklDelivery;
TaxInvoicesEditDM : TTaxInvoicesEditDM;
public
Kod_Setup : Integer;
procedure ReadReg;
procedure WriteReg;
constructor Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE;AddParametr:TTITaxInvoicesAddVidNaklDelivery);reintroduce;
property Parameter:TTITaxInvoicesAddVidNaklDelivery read PParameter;
property Res:Variant read PRes;
end;
var
TaxInvoicesEditAddInNaklForm: TTaxInvoicesEditAddInNaklForm;
implementation
{$R *.dfm}
constructor TTaxInvoicesEditAddInNaklForm.Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE;AddParametr:TTITaxInvoicesAddVidNaklDelivery);
begin
inherited Create(AOwner);
PDb_Handle := Db_Handle;
TaxInvoicesEditDM := TTaxInvoicesEditDM.Create(AOwner,Db_Handle);
PParameter := AddParametr;
end;
procedure TTaxInvoicesEditAddInNaklForm.cxButtonEdit2PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
measures:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
measures := DoFunctionFromPackage(Parameter,Measures_Const);
Parameter.Destroy;
If VarArrayDimCount(measures)>0 then
begin
MeasuresButtonEdit.Text := measures[1];
PParameter.Id_Measures := measures[0];
PParameter.Name_Measures := measures[2];
if ((MeasuresButtonEdit.Text = 'Грн') or (MeasuresButtonEdit.Text = 'Гривня') )then
begin
KolVoTextEdit.Text := 'послуги';
end
else
KolVoTextEdit.Text := '';
end;
end;
procedure TTaxInvoicesEditAddInNaklForm.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure TTaxInvoicesEditAddInNaklForm.cxButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
RangeOfDelivery:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
RangeOfDelivery := DoFunctionFromPackage(Parameter,RangeOfDelivery_Const);
Parameter.Destroy;
If VarArrayDimCount(RangeOfDelivery)>0 then
begin
RangeOfDeliveryButtonEdit.Text := RangeOfDelivery[1];
PParameter.id_range_of_delivery := RangeOfDelivery[0];
PParameter.Name_range_of_delivery := RangeOfDelivery[1];
end;
end;
procedure TTaxInvoicesEditAddInNaklForm.ReadReg;
var
reg : TRegistry;
begin
try
begin
reg := TRegistry.Create;
reg.RootKey := HKEY_CURRENT_USER;
if reg.OpenKey('\Software\TaxInvoices\VidNaklDeliveryIns\',False) then
begin
RangeOfDeliveryButtonEdit.Text := reg.ReadString('NAME_RANGE_OF_DELIVERY');
PParameter.id_range_of_delivery := StrToInt(reg.ReadString('id_range_of_delivery'));
PParameter.Name_range_of_delivery := reg.ReadString('Name_range_of_delivery');
MeasuresButtonEdit.Text := reg.ReadString('Name_Measures');
PParameter.Id_Measures := StrToInt(reg.ReadString('Id_Measures'));
PParameter.Name_Measures := reg.ReadString('Name_Measures');
end
else
begin
RangeOfDeliveryButtonEdit.Text := '';
MeasuresButtonEdit.Text := '';
end;
end
finally
reg.Free;
end;
end;
procedure TTaxInvoicesEditAddInNaklForm.WriteReg;
var
reg : TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if (reg.OpenKey('\Software\TaxInvoices\VidNaklDeliveryIns\',True)) then
begin
reg.WriteString('id_range_of_delivery',IntToStr(PParameter.id_range_of_delivery));
reg.WriteString('Name_range_of_delivery',PParameter.Name_range_of_delivery);
reg.WriteString('Id_Measures',IntToStr(PParameter.Id_Measures));
reg.WriteString('Name_Measures',PParameter.Name_Measures);
end;
finally
reg.Free;
end;
end;
procedure TTaxInvoicesEditAddInNaklForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
WriteReg;
end;
procedure TTaxInvoicesEditAddInNaklForm.YesButtonClick(Sender: TObject);
begin
if (DateShipmentLabel.Visible = True) then
begin
if (DateShipmentEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть дату відвантаження!',mtWarning,[mbOK]);
DateShipmentEdit.SetFocus;
Exit;
end;
end;
if (RangeOfDeliveryLabel.Visible = True) then
begin
if (RangeOfDeliveryButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть номенклатуру поставки!',mtWarning,[mbOK]);
RangeOfDeliveryButtonEdit.SetFocus;
Exit;
end;
end;
if (MeasuresButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть одиницю виміру!',mtWarning,[mbOK]);
MeasuresButtonEdit.SetFocus;
Exit;
end;
if (KolVoTextEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть кількість!',mtWarning,[mbOK]);
KolVoTextEdit.SetFocus;
Exit;
end;
if (PriceCurrencyEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть ціну!',mtWarning,[mbOK]);
PriceCurrencyEdit.SetFocus;
Exit;
end;
if (ValueDelivery20CurrencyEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть суму 20%!',mtWarning,[mbOK]);
ValueDelivery20CurrencyEdit.SetFocus;
Exit;
end;
if (ValueDeliveryExportCurrencyEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть 0% експорт!',mtWarning,[mbOK]);
ValueDeliveryExportCurrencyEdit.SetFocus;
Exit;
end;
if (ValueDeliveryCustomsCurrencyEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть 0%(реалізація на митній території)!',mtWarning,[mbOK]);
ValueDeliveryCustomsCurrencyEdit.SetFocus;
Exit;
end;
if (ValueDeliveryVATexemptionsCurrencyEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть звільнення від ПДВ!',mtWarning,[mbOK]);
ValueDeliveryVATexemptionsCurrencyEdit.SetFocus;
Exit;
end;
if (KodTovarCheckBox.Checked = True) then
begin
if (KodTovarButtonEdit.Text='') then
begin
TiShowMessage('Увага!','Заповніть код товару або зніміть галочку!',mtWarning,[mbOK]);
KodTovarButtonEdit.SetFocus;
Exit;
end;
end;
ModalResult := mrOk;
end;
procedure TTaxInvoicesEditAddInNaklForm.ValueDelivery20CurrencyEditExit(
Sender: TObject);
begin
//summa := (StrToFloat(PriceCurrencyEdit.EditValue))*(StrToFloat(KolVoCurrencyEdit.EditValue));
//ValueDelivery20CurrencyEdit.Text := FloatToStr(summa);
end;
procedure TTaxInvoicesEditAddInNaklForm.DateShipmentEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then RangeOfDeliveryButtonEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.RangeOfDeliveryButtonEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then MeasuresButtonEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.MeasuresButtonEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then KolVoTextEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.KolVoTextEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then PriceCurrencyEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.PriceCurrencyEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then ValueDelivery20CurrencyEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.ValueDelivery20CurrencyEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then ValueDeliveryExportCurrencyEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.ValueDeliveryExportCurrencyEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then ValueDeliveryCustomsCurrencyEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.ValueDeliveryVATexemptionsCurrencyEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then YesButton.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.FormActivate(Sender: TObject);
begin
DateShipmentEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.ValueDeliveryCustomsCurrencyEditKeyPress(
Sender: TObject; var Key: Char);
begin
if key = #13 then ValueDeliveryVATexemptionsCurrencyEdit.SetFocus;
end;
procedure TTaxInvoicesEditAddInNaklForm.KodTovarButtonEditClick(
Sender: TObject);
begin
KodTovarCheckBox.Checked := KodTovarButtonEdit.Enabled;
end;
procedure TTaxInvoicesEditAddInNaklForm.KodTovarButtonEditPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
Parameter:TTiSimpleParam;
KodTovar:Variant;
begin
Parameter := TTiSimpleParam.Create;
Parameter.DB_Handle := TaxInvoicesEditDM.DB.Handle;
Parameter.Owner := self;
KodTovar := DoFunctionFromPackage(Parameter,KodTovar_Const);
Parameter.Destroy;
If VarArrayDimCount(KodTovar)>0 then
begin
KodTovarButtonEdit.Text := KodTovar[1];
PParameter.id_kod_tovar := KodTovar[0];
PParameter.Name_Kod_tovar := KodTovar[1];
KodTovarButtonEdit.SetFocus;
end;
end;
procedure TTaxInvoicesEditAddInNaklForm.KodTovarCheckBoxClick(
Sender: TObject);
begin
if KodTovarCheckBox.Checked = True then
KodTovarButtonEdit.Enabled := True
else
KodTovarButtonEdit.Enabled := False;
end;
procedure TTaxInvoicesEditAddInNaklForm.ZaCheckBoxClick(Sender: TObject);
begin
MonthList.Enabled := ZaCheckBox.Checked;
YearSpinEdit.Enabled := ZaCheckBox.Checked;
end;
end.
|
unit VoxelDocument;
interface
uses Voxel, HVA, Palette, BasicDataTypes, BasicFunctions, SysUtils;
const
C_VXLTP_BODY = 0;
C_VXLTP_TURRET = 1;
C_VXLTP_BARREL = 2;
type
TVoxelDocument = class
private
// Misc
function GetHVAName(var _VoxelName: string): string;
function GetTurretName(var _VoxelName: string): string;
function GetBarrelName(var _VoxelName: string): string;
public
Voxels : array of PVoxel;
HVAs : array of PHVA;
VoxelType : array of byte;
Palette : PPalette;
ActiveVoxel: PVoxel;
ActiveHVA: PHVA;
ActiveSection : PVoxelSection;
// Constructors and Destructors
constructor Create; overload;
constructor Create(const _Filename: string); overload;
constructor Create(const _VoxelDocument: TVoxelDocument); overload;
constructor CreateFullUnit(const _Filename: string);
destructor Destroy; override;
procedure Clear;
procedure ClearVoxel;
// I/O
procedure LoadNew;
function Load(const _Filename: string): boolean;
function LoadFullUnit(const _Filename: string): boolean;
procedure SaveDocument(const _Filename: string);
// Gets
function GetNumVoxels: integer;
function GetBodyVoxel: PVoxel;
function GetTurretVoxel: PVoxel;
function GetBarrelVoxel: PVoxel;
function GetBodyHVA: PHVA;
function GetTurretHVA: PHVA;
function GetBarrelHVA: PHVA;
// Adds
function AddVoxel(const _Filename: string): boolean;
// Copies
procedure Assign(const _VoxelDocument: TVoxelDocument);
// Swicthes
function SwitchTurret(const _Filename: string): boolean;
end;
PVoxelDocument = ^TVoxelDocument;
implementation
uses GlobalVars;
constructor TVoxelDocument.Create;
begin
// Create new document.
New(Palette);
Palette^ := TPalette.Create(ExtractFileDir(ParamStr(0)) + '\palettes\TS\unittem.pal');
LoadNew;
end;
constructor TVoxelDocument.Create(const _Filename: string);
begin
// Load a single voxel.
New(Palette);
Palette^ := TPalette.Create(ExtractFileDir(ParamStr(0)) + '\palettes\TS\unittem.pal');
Load(_Filename);
end;
constructor TVoxelDocument.Create(const _VoxelDocument: TVoxelDocument);
begin
Assign(_VoxelDocument);
end;
constructor TVoxelDocument.CreateFullUnit(const _Filename: string);
begin
// Load a single voxel.
New(Palette);
Palette^ := TPalette.Create(ExtractFileDir(ParamStr(0)) + '\palettes\TS\unittem.pal');
LoadFullUnit(_Filename);
end;
destructor TVoxelDocument.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TVoxelDocument.Clear;
begin
ClearVoxel;
Palette^.Free;
end;
procedure TVoxelDocument.ClearVoxel;
var
i : integer;
begin
for i := Low(Voxels) to High(Voxels) do
begin
HVABank.Delete(HVAs[i]);
VoxelBank.Delete(Voxels[i]);
end;
SetLength(Voxels,0);
SetLength(HVAs,0);
SetLength(VoxelType,0);
ActiveVoxel := nil;
ActiveHVA := nil;
ActiveSection := nil;
end;
// I/O
procedure TVoxelDocument.LoadNew;
begin
ClearVoxel;
SetLength(Voxels,1);
SetLength(HVAs,1);
SetLength(VoxelType,1);
Voxels[0] := VoxelBank.LoadNew;
HVAs[0] := HVABank.LoadNew(Voxels[0]);
VoxelType[0] := C_VXLTP_BODY;
ActiveVoxel := Voxels[0];
ActiveHVA := HVAs[0];
ActiveSection := nil;
end;
function TVoxelDocument.Load(const _Filename: string): boolean;
begin
ClearVoxel;
Result := AddVoxel(_Filename);
end;
function TVoxelDocument.LoadFullUnit(const _Filename: string): boolean;
var
Filename : string;
begin
ClearVoxel;
// Add Body.
Result := AddVoxel(_Filename);
if Result then
begin
// Turret.
Filename := CopyString(_Filename);
if AddVoxel(GetTurretName(Filename)) then
VoxelType[High(VoxelType)] := C_VXLTP_TURRET;
// Barrel.
Filename := CopyString(_Filename);
if AddVoxel(GetBarrelName(Filename)) then
VoxelType[High(VoxelType)] := C_VXLTP_BARREL;
ActiveVoxel := Voxels[0];
ActiveHVA := HVAs[0];
ActiveSection := @(ActiveVoxel^.Section[0]);
end
else
begin
ActiveVoxel := nil;
ActiveHVA := nil;
ActiveSection := nil;
end;
end;
procedure TVoxelDocument.SaveDocument(const _Filename: string);
var
OriginalFilename,Filename : string;
i : integer;
begin
// If there are no voxels, there is nothing to save.
if High(Voxels) < 0 then
exit;
// Check if it saves all voxels in a different place.
if Length(_Filename) = 0 then
begin
OriginalFilename := CopyString(Voxels[0]^.Filename);
end
else
begin
OriginalFilename := CopyString(_Filename);
end;
// Save all voxels and HVAs
for i := Low(Voxels) to High(Voxels) do
begin
Filename := CopyString(OriginalFilename);
case (VoxelType[i]) of
C_VXLTP_BODY:
begin
VoxelBank.Save(Voxels[0],Filename);
HVABank.Save(HVAs[0],GetHVAName(Filename));
end;
C_VXLTP_TURRET:
begin
VoxelBank.Save(Voxels[0],GetTurretName(Filename));
HVABank.Save(HVAs[0],GetHVAName(Filename));
end;
C_VXLTP_BARREL:
begin
VoxelBank.Save(Voxels[0],GetBarrelName(Filename));
HVABank.Save(HVAs[0],GetHVAName(Filename));
end;
end;
end;
end;
// Gets
function TVoxelDocument.GetNumVoxels: integer;
begin
Result := High(Voxels)+1;
end;
function TVoxelDocument.GetBodyVoxel: PVoxel;
var
i : integer;
begin
Result := nil;
for i := Low(VoxelType) to High(VoxelType) do
begin
if (VoxelType[i] = C_VXLTP_BODY) then
begin
Result := Voxels[i];
exit;
end;
end;
end;
function TVoxelDocument.GetTurretVoxel: PVoxel;
var
i : integer;
begin
Result := nil;
for i := Low(VoxelType) to High(VoxelType) do
begin
if (VoxelType[i] = C_VXLTP_TURRET) then
begin
Result := Voxels[i];
exit;
end;
end;
end;
function TVoxelDocument.GetBarrelVoxel: PVoxel;
var
i : integer;
begin
Result := nil;
for i := Low(VoxelType) to High(VoxelType) do
begin
if (VoxelType[i] = C_VXLTP_BARREL) then
begin
Result := Voxels[i];
exit;
end;
end;
end;
function TVoxelDocument.GetBodyHVA: PHVA;
var
i : integer;
begin
Result := nil;
for i := Low(VoxelType) to High(VoxelType) do
begin
if (VoxelType[i] = C_VXLTP_BODY) then
begin
Result := HVAs[i];
exit;
end;
end;
end;
function TVoxelDocument.GetTurretHVA: PHVA;
var
i : integer;
begin
Result := nil;
for i := Low(VoxelType) to High(VoxelType) do
begin
if (VoxelType[i] = C_VXLTP_TURRET) then
begin
Result := HVAs[i];
exit;
end;
end;
end;
function TVoxelDocument.GetBarrelHVA: PHVA;
var
i : integer;
begin
Result := nil;
for i := Low(VoxelType) to High(VoxelType) do
begin
if (VoxelType[i] = C_VXLTP_BARREL) then
begin
Result := HVAs[i];
exit;
end;
end;
end;
// Adds
function TVoxelDocument.AddVoxel(const _Filename: string): boolean;
var
i: integer;
Filename: string;
begin
Result := false;
ActiveVoxel := nil;
ActiveHVA := nil;
ActiveSection := nil;
Filename := CopyString(_Filename);
if FileExists(Filename) then
begin
SetLength(Voxels,High(Voxels)+2);
SetLength(HVAs,High(HVAs)+2);
SetLength(VoxelType,High(VoxelType)+2);
i := High(Voxels);
Voxels[i] := VoxelBank.Load(Voxels[i],Filename);
// Did it open the voxel?
if Voxels[i] <> nil then
begin
HVAs[i] := HVABank.Load(HVAs[i],GetHVAName(Filename),Voxels[i]);
VoxelType[i] := C_VXLTP_BODY; // Default value.
ActiveVoxel := Voxels[i];
ActiveHVA := HVAs[i];
ActiveSection := @(ActiveVoxel^.Section[0]);
Result := true;
end
else // if Voxel couldn't be opened, abort operation
begin
SetLength(Voxels,High(Voxels));
SetLength(HVAs,High(HVAs));
SetLength(VoxelType,High(VoxelType));
end;
end;
end;
// Copies
procedure TVoxelDocument.Assign(const _VoxelDocument: TVoxelDocument);
var
NumItems, i: integer;
begin
NumItems := _VoxelDocument.GetNumVoxels;
SetLength(Voxels,NumItems);
SetLength(HVAs,NumItems);
SetLength(VoxelType,NumItems);
for i := Low(Voxels) to High(Voxels) do
begin
Voxels[i] := VoxelBank.CloneEditable(_VoxelDocument.Voxels[i]);
HVAs[i] := HVABank.CloneEditable(_VoxelDocument.HVAs[i]);
VoxelType[i] := _VoxelDocument.VoxelType[i];
end;
ActiveVoxel := GetBodyVoxel;
ActiveHVA := GetBodyHVA;
ActiveSection := @(ActiveVoxel^.Section[0]);
New(Palette);
Palette^ := TPalette.Create(_VoxelDocument.Palette^);
end;
// Misc
function TVoxelDocument.GetHVAName(var _VoxelName: string): string;
begin
if Length(_VoxelName) > 4 then
begin
_VoxelName := copy(_VoxelName,1,Length(_VoxelName)-3);
_VoxelName := _VoxelName + 'hva';
end;
Result := _VoxelName;
end;
function TVoxelDocument.GetTurretName(var _VoxelName: string): string;
begin
if Length(_VoxelName) > 4 then
begin
_VoxelName := copy(_VoxelName,1,Length(_VoxelName)-4);
_VoxelName := _VoxelName + 'tur.vxl';
end;
Result := _VoxelName;
end;
function TVoxelDocument.GetBarrelName(var _VoxelName: string): string;
begin
if Length(_VoxelName) > 4 then
begin
_VoxelName := copy(_VoxelName,1,Length(_VoxelName)-4);
_VoxelName := _VoxelName + 'bar.vxl';
end;
Result := _VoxelName;
end;
// Swicthes
function TVoxelDocument.SwitchTurret(const _Filename: string): boolean;
var
i : integer;
Filename: string;
MyVoxel : PVoxel;
begin
Result := false;
if FileExists(_Filename) then
begin
i := 0;
while i <= High(Voxels) do
begin
if VoxelType[i] = C_VXLTP_TURRET then
begin
MyVoxel := Voxels[i];
Voxels[i] := VoxelBank.Load(Voxels[i],_Filename);
Filename := CopyString(_Filename);
HVAs[i] := HVABank.Load(HVAs[i],GetHVAName(Filename),Voxels[i]);
if ActiveVoxel = MyVoxel then
begin
ActiveVoxel := Voxels[i];
ActiveHVA := HVAs[i];
ActiveSection := @(ActiveVoxel^.Section[0]);
end;
Result := true;
exit;
end;
inc(i);
end;
end;
end;
end.
|
program HowToDrawSomethingToTheScreen;
uses
SwinGame, sgTypes;
procedure Main();
begin
OpenGraphicsWindow('How To Draw Something To The Screen', 320, 240);
ClearScreen(); // clear the background canvas (black by default)
RefreshScreen(); // make it appear on screen...
Delay(2000); // wait for 2 seconds
ClearScreen(ColorYellow); // clear the background canvas
RefreshScreen(); // make it appear on screen...
//Start drawing the "next" screen to appear...
ClearScreen(ColorWhite); // clear the background canvas
Delay(2000); // wait for 2 seconds... notice the yellow screen!
RefreshScreen(); // make the white screen appear...
Delay(2000);
ReleaseAllResources();
end;
begin
Main();
end. |
unit uUninstall;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
System.Classes,
System.StrUtils,
System.SysUtils,
System.Win.Registry,
Winapi.Windows,
Vcl.Dialogs,
Dmitry.Utils.Files,
uActions,
uInstallTypes,
uMemory,
uConstants,
uUninstallTypes,
uShellUtils;
const
InstallPoints_UninstallShortcuts = 16 * 1024;
type
TUninstallPreviousShortcut = class
public
PathType: string;
RelativePath: string;
Directory: Boolean;
end;
TUninstallPreviousShortcutsAction = class(TInstallAction)
private
FUninstallShortcuts : TList;
procedure FillList;
procedure AddUninstallShortcut(APathType : string; ARelativePath : string; Directory: Boolean);
public
constructor Create; override;
destructor Destroy; override;
function CalculateTotalPoints : Int64; override;
procedure Execute(Callback : TActionCallback); override;
end;
implementation
{ TUninstallShortcutsAction }
procedure TUninstallPreviousShortcutsAction.AddUninstallShortcut(APathType,
ARelativePath: string; Directory: Boolean);
var
Shortcut : TUninstallPreviousShortcut;
begin
Shortcut := TUninstallPreviousShortcut.Create;
Shortcut.PathType := APathType;
Shortcut.RelativePath := ARelativePath;
Shortcut.Directory := Directory;
FUninstallShortcuts.Add(Shortcut);
end;
function TUninstallPreviousShortcutsAction.CalculateTotalPoints: Int64;
begin
Result := InstallPoints_UninstallShortcuts * FUninstallShortcuts.Count;
end;
constructor TUninstallPreviousShortcutsAction.Create;
begin
inherited;
FUninstallShortcuts := TList.Create;
FillList;
end;
destructor TUninstallPreviousShortcutsAction.Destroy;
begin
FreeList(FUninstallShortcuts);
inherited;
end;
procedure TUninstallPreviousShortcutsAction.Execute(Callback: TActionCallback);
var
I, P: Integer;
Shortcut: TUninstallPreviousShortcut;
Path, RemovePath, RemoveMask: string;
FCurrent, FTotal: Int64;
Terminate: Boolean;
begin
FTotal := CalculateTotalPoints;
FCurrent := 0;
Terminate := False;
for I := 0 to FUninstallShortcuts.Count - 1 do
begin
Shortcut := TUninstallPreviousShortcut(FUninstallShortcuts[I]);
if Shortcut.PathType = 'Desktop' then
Path := GetDesktopPath
else if Shortcut.PathType = 'Start Menu' then
Path := GetStartMenuPath
else
Path := GetProgramFilesPath;
Path := IncludeTrailingBackslash(Path) + Shortcut.RelativePath;
if EndsText('|', Path) then
begin
P := Pos('*', Path);
if P > 0 then
begin
RemovePath := Copy(Path, 1, P - 1);
RemoveMask := Copy(Path, P + 1, Length(Path) - 2);
DelDir(RemovePath, RemoveMask);
end;
end else if not Shortcut.Directory then
System.SysUtils.DeleteFile(Path)
else
System.SysUtils.RemoveDir(Path);
Inc(FCurrent, InstallPoints_UninstallShortcuts);
Callback(Self, FCurrent, FTotal, Terminate);
if Terminate then
Exit;
end;
end;
procedure TUninstallPreviousShortcutsAction.FillList;
begin
AddUninstallShortcut('Desktop', ProgramShortCutFile_1_75, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_75 + '\' + ProgramShortCutFile_1_75, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_75 + '\' + HelpShortCutFile_1_75, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_75, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_1_8, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_8 + '\' + ProgramShortCutFile_1_8, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_8 + '\' + HelpShortCutFile_1_8, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_8, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_1_9, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_9 + '\' + ProgramShortCutFile_1_9, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_9 + '\' + HelpShortCutFile_1_9, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_1_9, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_2_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_0 + '\' + ProgramShortCutFile_2_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_0 + '\' + HelpShortCutFile_2_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_0, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_2_1, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_1 + '\' + ProgramShortCutFile_2_1, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_1 + '\' + HelpShortCutFile_2_1, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_1, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_2_2, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_2 + '\' + ProgramShortCutFile_2_2, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_2 + '\' + HelpShortCutFile_2_2, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_2, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_2_3, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_3 + '\' + ProgramShortCutFile_2_3, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_3 + '\' + HelpShortCutFile_2_3, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_2_3, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_3_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_3_0 + '\' + ProgramShortCutFile_3_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_3_0 + '\' + HelpShortCutFile_3_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_3_0, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_3_1, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_3_1 + '\' + ProgramShortCutFile_3_1, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_3_1 + '\' + HelpShortCutFile_3_1, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_3_1, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_4_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_4_0 + '\' + ProgramShortCutFile_4_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_4_0 + '\' + HelpShortCutFile_4_0, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_4_0, True);
AddUninstallShortcut('Desktop', ProgramShortCutFile_4_5, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_4_5 + '\' + ProgramShortCutFile_4_5, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_4_5 + '\' + HelpShortCutFile_4_5, False);
AddUninstallShortcut('Start Menu', StartMenuProgramsPath_4_5, True);
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
An extention of TVXNavigator, which allows to move objects with inertia
Note: it is not completely FPS-independant. Only Moving code is, but
MoveAroundTarget, Turn[Vertical/Horizontal] and AdjustDistanceTo[..] is not.
Don't know why, but when I make their code identical, these function stop
working completely. So you probably have to call the AutoScaleParameters
procedure once in a while for it to adjust to the current framerate.
TODO:
1) Scale "Old values" too, when callin the Scale parameter procedure to
avoid the temporary "freeze" of controls.
2) AddImpulse procedures.
}
unit VXS.SmoothNavigator;
interface
{$I VXScene.inc}
uses
System.Types,
System.Classes,
VXS.VectorTypes,
VXS.Navigator,
VXS.VectorGeometry,
VXS.Scene,
VXS.CrossPlatform,
VXS.Coordinates,
VXS.Screen,
VXS.PersistentClasses,
VXS.XCollection;
type
{ Includes a basic set of parameters that control the smoothness of movement. }
TVXNavigatorAbstractParameters = class(TPersistent)
private
FOwner: TPersistent;
FInertia: Single;
FSpeed: Single;
FCutoff: Single;
function StoreCutoff: Boolean;
protected
function StoreInertia: Boolean; virtual;
function StoreSpeed: Boolean; virtual;
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
published
property Inertia: Single read FInertia write FInertia stored StoreInertia;
property Speed: Single read FSpeed write FSpeed stored StoreSpeed;
property Cutoff: Single read FCutoff write FCutoff stored StoreCutoff;
end;
TVXSmoothNavigator = class;
{ Includes a basic set of parameters that control the smoothness of movement }
TVXNavigatorSmoothChangeItem = class(TXCollectionItem)
private
FInertia: Single;
FSpeed: Single;
FEnabled: Boolean;
FSpeedLimit: Single;
FCutoff: Double;
function StoreInertia: Boolean;
function StoreSpeed: Boolean;
function StoreSpeedLimit: Boolean;
function StoreCutoff: Boolean;
protected
function GetNavigator: TVXSmoothNavigator;
public
{ Returns False if there was no change. }
function Proceed(ADeltaTime: Double): Boolean; virtual; abstract;
constructor Create(aOwner: TXCollection); override;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
procedure ResetTargetValue(); virtual; abstract;
published
property Inertia: Single read FInertia write FInertia stored StoreInertia;
property Speed: Single read FSpeed write FSpeed stored StoreSpeed;
property SpeedLimit: Single read FSpeedLimit write FSpeedLimit stored StoreSpeedLimit;
property Cutoff: Double read FCutoff write FCutoff stored StoreCutoff;
property Enabled: Boolean read FEnabled write FEnabled default True;
end;
TVXNavigatorSmoothChangeSingle = class;
TVXNavigatorSmoothChangeSingleGetEvent = function(const ASender: TVXNavigatorSmoothChangeSingle): Single of object;
TVXNavigatorSmoothChangeSingleSetEvent = procedure(const ASender: TVXNavigatorSmoothChangeSingle; const AValue: Single) of object;
{ Smoothly change any Single value, so it will become TargetValue in the end. }
TVXNavigatorSmoothChangeSingle = class(TVXNavigatorSmoothChangeItem)
private
FTargetValue: Single;
FOnGetCurrentValue: TVXNavigatorSmoothChangeSingleGetEvent;
FOnSetCurrentValue: TVXNavigatorSmoothChangeSingleSetEvent;
public
class function FriendlyName: string; override;
function Proceed(ADeltaTime: Double): Boolean; override;
procedure Assign(Source: TPersistent); override;
procedure ResetTargetValue(); override;
published
property TargetValue: Single read FTargetValue write FTargetValue;
property OnGetCurrentValue: TVXNavigatorSmoothChangeSingleGetEvent read FOnGetCurrentValue write FOnGetCurrentValue;
property OnSetCurrentValue: TVXNavigatorSmoothChangeSingleSetEvent read FOnSetCurrentValue write FOnSetCurrentValue;
end;
TVXNavigatorSmoothChangeVector = class;
TVXNavigatorSmoothChangeVectorGetEvent = function(const ASender: TVXNavigatorSmoothChangeVector): TVector of object;
TVXNavigatorSmoothChangeVectorSetEvent = procedure(const ASender: TVXNavigatorSmoothChangeVector; const AValue: TVector) of object;
{ Smoothly change any Vector4f value, so it will become TargetValue in the end. }
TVXNavigatorSmoothChangeVector = class(TVXNavigatorSmoothChangeItem)
private
FTargetValue: TVXCoordinates;
FOnGetCurrentValue: TVXNavigatorSmoothChangeVectorGetEvent;
FOnSetCurrentValue: TVXNavigatorSmoothChangeVectorSetEvent;
procedure SetTargetValue(const Value: TVXCoordinates);
public
class function FriendlyName: string; override;
function Proceed(ADeltaTime: Double): Boolean; override;
procedure Assign(Source: TPersistent); override;
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
procedure ResetTargetValue(); override;
published
property TargetValue: TVXCoordinates read FTargetValue write SetTargetValue;
property OnGetCurrentValue: TVXNavigatorSmoothChangeVectorGetEvent read FOnGetCurrentValue write FOnGetCurrentValue;
property OnSetCurrentValue: TVXNavigatorSmoothChangeVectorSetEvent read FOnSetCurrentValue write FOnSetCurrentValue;
end;
TVXNavigatorSmoothChangeItemClass = class of TVXNavigatorSmoothChangeItem;
{ XCollection of TVXNavigatorSmoothChangeItem. }
TVXNavigatorSmoothChangeItems = class(TXCollection)
private
function GetItems(const Index : Integer): TVXNavigatorSmoothChangeItem;
procedure SetItems(const Index : Integer; const Value: TVXNavigatorSmoothChangeItem);
protected
procedure DoProceed(ADeltaTime: Double);
public
function Add(AClass : TVXNavigatorSmoothChangeItemClass): TVXNavigatorSmoothChangeItem;
function CanAdd(AClass: TXCollectionItemClass): Boolean; override;
class function ItemsClass: TXCollectionItemClass; override;
property Items[const Index : Integer]: TVXNavigatorSmoothChangeItem read GetItems write
SetItems; default;
end;
{ This is wrapper for all parameters that affect how the AdjustDisanceTo[...] methods work }
TVXNavigatorAdjustDistanceParameters = class(TVXNavigatorAbstractParameters)
private
FOldDistanceRatio: Single;
FImpulseSpeed: Single;
function StoreImpulseSpeed: Boolean;
public
constructor Create(AOwner: TPersistent); override;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); override;
procedure AddImpulse(const Impulse: Single); virtual;
published
property ImpulseSpeed: Single read FImpulseSpeed write FImpulseSpeed stored StoreImpulseSpeed;
end;
{ This is a wrapper for all parameters that affect how the AdjustDisanceTo[...]Ex methods work
You need to set the TargetObject and desired distance to it,
then call AdjustDisanceTo[...]Ex() in your Cadencer.OnProgress code. }
TVXNavigatorAdjustDistanceParametersEx = class(TVXNavigatorAbstractParameters)
private
FSpeedLimit: Single;
FTargetDistance: Single;
function StoreSpeedLimit: Boolean;
function StoreTargetDistance: Boolean;
protected
function StoreSpeed: Boolean; override;
function StoreInertia: Boolean; override;
public
constructor Create(AOwner: TPersistent); override;
procedure Assign(Source: TPersistent); override;
published
property TargetDistance: Single read FTargetDistance write FTargetDistance stored StoreTargetDistance;
property SpeedLimit: Single read FSpeedLimit write FSpeedLimit stored StoreSpeedLimit;
end;
{ This is a wrapper for all parameters that affect the smoothness of movement }
TVXNavigatorInertiaParameters = class(TPersistent)
private
FOwner: TPersistent;
OldTurnHorizontalAngle: Single;
OldTurnVerticalAngle: Single;
OldMoveForwardDistance: Single;
OldStrafeHorizontalDistance: Single;
OldStrafeVerticalDistance: Single;
FTurnInertia: Single;
FTurnSpeed: Single;
FTurnMaxAngle: Single;
FMovementAcceleration: Single;
FMovementInertia: Single;
FMovementSpeed: Single;
function StoreTurnMaxAngle: Boolean;
function StoreMovementAcceleration: Boolean;
function StoreMovementInertia: Boolean;
function StoreMovementSpeed: Boolean;
function StoreTurnInertia: Boolean;
function StoreTurnSpeed: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
published
property MovementAcceleration: Single read FMovementAcceleration write FMovementAcceleration stored StoreMovementAcceleration;
property MovementInertia: Single read FMovementInertia write FMovementInertia stored StoreMovementInertia;
property MovementSpeed: Single read FMovementSpeed write FMovementSpeed stored StoreMovementSpeed;
property TurnMaxAngle: Single read FTurnMaxAngle write FTurnMaxAngle stored StoreTurnMaxAngle;
property TurnInertia: Single read FTurnInertia write FTurnInertia stored StoreTurnInertia;
property TurnSpeed: Single read FTurnSpeed write FTurnSpeed stored StoreTurnSpeed;
end;
{ This is a wrapper for all general inertia parameters.
These properties mean that if ExpectedMaxFPS is 100, FAutoScaleMin is 0.1,
FAutoScaleMax is 0.75 then the "safe range" for it to change is [10..75].
If these bounds are violated, then ExpectedMaxFPS is automaticly increased
or decreased by AutoScaleMult. }
TVXNavigatorGeneralParameters = class(TPersistent)
private
FOwner: TPersistent;
FAutoScaleMin: Single;
FAutoScaleMax: Single;
FAutoScaleMult: Single;
function StoreAutoScaleMax: Boolean;
function StoreAutoScaleMin: Boolean;
function StoreAutoScaleMult: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
published
property AutoScaleMin: Single read FAutoScaleMin write FAutoScaleMin stored StoreAutoScaleMin;
property AutoScaleMax: Single read FAutoScaleMax write FAutoScaleMax stored StoreAutoScaleMax;
property AutoScaleMult: Single read FAutoScaleMult write FAutoScaleMult stored StoreAutoScaleMult;
end;
{ This is a wrapper for all parameters that effect how the TVXBaseSceneObject.MoveObjectAround() procedure works}
TVXNavigatorMoveAroundParameters = class(TPersistent)
private
FOwner: TPersistent;
FTargetObject: TVXBaseSceneObject;
FOldPitchInertiaAngle : Single;
FOldTurnInertiaAngle : Single;
FPitchSpeed : Single;
FTurnSpeed : Single;
FInertia : Single;
FMaxAngle : Single;
FCutoff: Double;
function StoreInertia: Boolean;
function StoreMaxAngle: Boolean;
function StorePitchSpeed: Boolean;
function StoreTurnSpeed: Boolean;
procedure SetTargetObject(const Value: TVXBaseSceneObject);
function StoreCutoff: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
published
property Inertia: Single read FInertia write FInertia stored StoreInertia;
property MaxAngle: Single read FMaxAngle write FMaxAngle stored StoreMaxAngle;
property PitchSpeed: Single read FPitchSpeed write FPitchSpeed stored StorePitchSpeed;
property TurnSpeed: Single read FTurnSpeed write FTurnSpeed stored StoreTurnSpeed;
property TargetObject: TVXBaseSceneObject read FTargetObject write SetTargetObject;
property Cutoff: Double read FCutoff write FCutoff stored StoreCutoff;
end;
{ This is the component for moving a TVXBaseSceneObject, and all
classes based on it, this includes all the objects from the Scene Editor.
It uses complex smoothing algorithms, most of which are FPS-dependant.
Make sure your limit your FPS and set MaxExpectedDeltaTime to a value
that is aproximatly 5 times less than your usual deltatime. }
TVXSmoothNavigator = class(TVXNavigator)
private
FMaxExpectedDeltaTime: Double;
FInertiaParams: TVXNavigatorInertiaParameters;
FGeneralParams: TVXNavigatorGeneralParameters;
FMoveAroundParams: TVXNavigatorMoveAroundParameters;
FAdjustDistanceParams: TVXNavigatorAdjustDistanceParameters;
FAdjustDistanceParamsEx: TVXNavigatorAdjustDistanceParametersEx;
FCustomAnimatedItems: TVXNavigatorSmoothChangeItems;
procedure SetInertiaParams(const Value: TVXNavigatorInertiaParameters);
function StoreMaxExpectedDeltaTime: Boolean;
procedure SetGeneralParams(const Value: TVXNavigatorGeneralParameters);
procedure SetMoveAroundParams(const Value: TVXNavigatorMoveAroundParameters);
procedure SetAdjustDistanceParams(const Value: TVXNavigatorAdjustDistanceParameters);
procedure SetAdjustDistanceParamsEx(
const Value: TVXNavigatorAdjustDistanceParametersEx);
procedure SetCustomAnimatedItems(
const Value: TVXNavigatorSmoothChangeItems);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
// Constructors-destructors.
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// From TVXNavigator. Probably, should not be public.
procedure SetObject(Value: TVXBaseSceneObject); override;
// Uses InertiaParams.
procedure TurnHorizontal(Angle: Single; ADeltaTime: Double); virtual;
procedure TurnVertical(Angle: Single; ADeltaTime: Double); virtual;
procedure FlyForward(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False); virtual;
procedure MoveForward(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False); virtual;
procedure StrafeHorizontal(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False); virtual;
procedure StrafeVertical(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False); virtual;
// Uses MoveAroundParams. Returns True, if object was actually moved.
function MoveAroundTarget(const PitchDelta, TurnDelta : Single; const ADeltaTime: Double): Boolean; virtual;
function MoveObjectAround(const AObject: TVXBaseSceneObject; PitchDelta, TurnDelta : Single; ADeltaTime: Double): Boolean; virtual;
// Uses AdjustDistanceParams.
function AdjustDistanceToPoint(const APoint: TVector; const DistanceRatio : Single; ADeltaTime: Double): Boolean; virtual;
function AdjustDistanceToTarget(const DistanceRatio : Single; const ADeltaTime: Double): Boolean; virtual;
// Uses AdjustDistanceParamsEx.
function AdjustDistanceToPointEx(const APoint: TVector; ADeltaTime: Double): Boolean; virtual;
function AdjustDistanceToTargetEx(const ADeltaTime: Double): Boolean; virtual;
// Uses CustomAnimatedItems.
procedure AnimateCustomItems(const ADeltaTime: Double); virtual;
// Uses GeneralParams.
{ In ScaleParameters, Value should be around 1. }
procedure ScaleParameters(const Value: Single); virtual;
procedure AutoScaleParameters(const FPS: Single); virtual;
procedure AutoScaleParametersUp(const FPS: Single); virtual;
published
property MaxExpectedDeltaTime: Double read FMaxExpectedDeltaTime write FMaxExpectedDeltaTime stored StoreMaxExpectedDeltaTime;
property InertiaParams: TVXNavigatorInertiaParameters read FInertiaParams write SetInertiaParams;
property GeneralParams: TVXNavigatorGeneralParameters read FGeneralParams write SetGeneralParams;
property MoveAroundParams: TVXNavigatorMoveAroundParameters read FMoveAroundParams write SetMoveAroundParams;
property AdjustDistanceParams: TVXNavigatorAdjustDistanceParameters read FAdjustDistanceParams write SetAdjustDistanceParams;
property AdjustDistanceParamsEx: TVXNavigatorAdjustDistanceParametersEx read FAdjustDistanceParamsEx write SetAdjustDistanceParamsEx;
property CustomAnimatedItems: TVXNavigatorSmoothChangeItems read FCustomAnimatedItems write SetCustomAnimatedItems;
end;
{ This is the component which reads the userinput and transform it into action.
Mouselook(ADeltaTime: double) : handles mouse look... Should be called
in the Cadencer event. (Though it works everywhere!)
The four properties to get you started are:
InvertMouse : Inverts the mouse Y axis.
AutoUpdateMouse : If enabled (by defaul), than handles all mouse updates.
GLNavigator : The Navigator which receives the user movement.
GLVertNavigator : The Navigator which if set receives the vertical user
movement. Used mostly for cameras.... }
TVXSmoothUserInterface = class(TComponent)
private
FAutoUpdateMouse: Boolean;
FMouseLookActive: Boolean;
FSmoothNavigator: TVXSmoothNavigator;
FSmoothVertNavigator: TVXSmoothNavigator;
FInvertMouse: Boolean;
FOriginalMousePos: TVXCoordinates2;
procedure SetSmoothNavigator(const Value: TVXSmoothNavigator); virtual;
procedure SetOriginalMousePos(const Value: TVXCoordinates2); virtual;
procedure SetSmoothVertNavigator(const Value: TVXSmoothNavigator); virtual;
procedure SetMouseLookActive(const Value: Boolean); virtual;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure TurnHorizontal(const Angle : Single; const ADeltaTime: Double); virtual;
procedure TurnVertical(const Angle : Single; const ADeltaTime: Double); virtual;
procedure MouseLookActiveToggle; virtual;
function MouseLook(const ADeltaTime: Double): Boolean; overload;
function MouseLook(const NewXY: TPoint; const ADeltaTime: Double): Boolean; overload;
function MouseLook(const NewX, NewY: Integer; const ADeltaTime: Double): Boolean; overload;
published
property AutoUpdateMouse: Boolean read FAutoUpdateMouse write FAutoUpdateMouse default True;
property MouseLookActive: Boolean read FMouseLookActive write SetMouseLookActive default False;
property SmoothVertNavigator: TVXSmoothNavigator read FSmoothVertNavigator write SetSmoothVertNavigator;
property SmoothNavigator: TVXSmoothNavigator read FSmoothNavigator write SetSmoothNavigator;
property InvertMouse: Boolean read FInvertMouse write FInvertMouse default False;
property OriginalMousePos: TVXCoordinates2 read FOriginalMousePos write SetOriginalMousePos;
end;
//-----------------------------------------------------------
implementation
//-----------------------------------------------------------
const
EPS = 0.001;
EPS2 = 0.0001;
EPS8 = 0.00000001;
{ TVXSmoothNavigator }
constructor TVXSmoothNavigator.Create(AOwner: TComponent);
begin
inherited;
FMaxExpectedDeltaTime := 0.001;
FInertiaParams := TVXNavigatorInertiaParameters.Create(Self);
FGeneralParams := TVXNavigatorGeneralParameters.Create(Self);
FMoveAroundParams := TVXNavigatorMoveAroundParameters.Create(Self);
FAdjustDistanceParams := TVXNavigatorAdjustDistanceParameters.Create(Self);
FAdjustDistanceParamsEx := TVXNavigatorAdjustDistanceParametersEx.Create(Self);
FCustomAnimatedItems := TVXNavigatorSmoothChangeItems.Create(Self);
end;
destructor TVXSmoothNavigator.Destroy;
begin
FInertiaParams.Free;
FGeneralParams.Free;
FMoveAroundParams.Free;
FAdjustDistanceParams.Free;
FAdjustDistanceParamsEx.Free;
FCustomAnimatedItems.Free;
inherited;
end;
procedure TVXSmoothNavigator.SetInertiaParams(
const Value: TVXNavigatorInertiaParameters);
begin
FInertiaParams.Assign(Value);
end;
procedure TVXSmoothNavigator.TurnHorizontal(Angle: Single; ADeltaTime: Double);
var
FinalAngle: Single;
begin
with FInertiaParams do
begin
FinalAngle := 0;
Angle := Angle * FTurnSpeed;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
Angle := ClampValue((Angle * FMaxExpectedDeltaTime + OldTurnHorizontalAngle * FTurnInertia) / (FTurnInertia + 1), -FTurnMaxAngle, FTurnMaxAngle);
OldTurnHorizontalAngle := Angle;
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalAngle := FinalAngle + Angle;
end;
end;
if (Abs(FinalAngle) > EPS) then
inherited TurnHorizontal(FinalAngle);
end;
procedure TVXSmoothNavigator.TurnVertical(Angle: Single; ADeltaTime: Double);
var
FinalAngle: Single;
begin
with FInertiaParams do
begin
FinalAngle := 0;
Angle := Angle * FTurnSpeed;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
Angle := ClampValue((Angle * FMaxExpectedDeltaTime + OldTurnVerticalAngle * FTurnInertia) / (FTurnInertia + 1), -FTurnMaxAngle, FTurnMaxAngle);
OldTurnVerticalAngle := Angle;
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalAngle := FinalAngle + Angle;
end;
end;
if (Abs(FinalAngle) > EPS) then
inherited TurnVertical(FinalAngle);
end;
procedure TVXSmoothNavigator.MoveForward(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
OldMoveForwardDistance := (Distance * FMaxExpectedDeltaTime + OldMoveForwardDistance * FMovementInertia) / (FMovementInertia + 1);
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldMoveForwardDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited MoveForward(FinalDistance);
end;
procedure TVXSmoothNavigator.FlyForward(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
OldMoveForwardDistance := (Distance * FMaxExpectedDeltaTime + OldMoveForwardDistance * FMovementInertia) / (FMovementInertia + 1);
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldMoveForwardDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited FlyForward(FinalDistance);
end;
procedure TVXSmoothNavigator.StrafeHorizontal(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
OldStrafeHorizontalDistance := (Distance * FMaxExpectedDeltaTime + OldStrafeHorizontalDistance * FMovementInertia) / (FMovementInertia + 1);
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldStrafeHorizontalDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited StrafeHorizontal(FinalDistance);
end;
procedure TVXSmoothNavigator.StrafeVertical(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
OldStrafeVerticalDistance := (Distance * FMaxExpectedDeltaTime + OldStrafeVerticalDistance * FMovementInertia) / (FMovementInertia + 1);
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldStrafeVerticalDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited StrafeVertical(FinalDistance);
end;
procedure TVXSmoothNavigator.AutoScaleParameters(const FPS: Single);
begin
with FGeneralParams do
begin
if FPS > FAutoScaleMax / FMaxExpectedDeltatime then
ScaleParameters(FAutoScaleMult)
else if FPS < FAutoScaleMin / FMaxExpectedDeltatime then
ScaleParameters(1/FAutoScaleMult);
end;
end;
procedure TVXSmoothNavigator.AutoScaleParametersUp(const FPS: Single);
begin
with FGeneralParams do
begin
if FPS > FAutoScaleMax / FMaxExpectedDeltatime then
ScaleParameters(FAutoScaleMult)
end;
end;
procedure TVXSmoothNavigator.ScaleParameters(const Value: Single);
begin
Assert(Value > 0);
FMaxExpectedDeltatime := FMaxExpectedDeltatime / Value;
FInertiaParams.ScaleParameters(Value);
FMoveAroundParams.ScaleParameters(Value);
FAdjustDistanceParams.ScaleParameters(Value);
end;
function TVXSmoothNavigator.StoreMaxExpectedDeltaTime: Boolean;
begin
Result := Abs(FMaxExpectedDeltaTime - 0.001) > EPS2;
end;
procedure TVXSmoothNavigator.SetGeneralParams(
const Value: TVXNavigatorGeneralParameters);
begin
FGeneralParams.Assign(Value);
end;
procedure TVXSmoothNavigator.SetMoveAroundParams(
const Value: TVXNavigatorMoveAroundParameters);
begin
FMoveAroundParams.Assign(Value);
end;
procedure TVXSmoothNavigator.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = FMoveAroundParams.FTargetObject then
FMoveAroundParams.FTargetObject := nil;
end;
end;
procedure TVXSmoothNavigator.SetObject(Value: TVXBaseSceneObject);
var
I: Integer;
begin
inherited;
// Try to detect a TargetObject.
if Value <> nil then
if FMoveAroundParams.TargetObject = nil then
begin
// May be it is a camera...
if Value is TVXCamera then
FMoveAroundParams.TargetObject := TVXCamera(Value).TargetObject
else
begin
// May be it has camera children...
if Value.Count <> 0 then
for I := 0 to Value.Count - 1 do
if Value.Children[I] is TVXCamera then
begin
FMoveAroundParams.TargetObject := TVXCamera(Value.Children[I]).TargetObject;
Exit;
end;
end;
end;
end;
function TVXSmoothNavigator.MoveAroundTarget(const PitchDelta, TurnDelta: Single;
const ADeltaTime: Double): Boolean;
begin
Result := MoveObjectAround(FMoveAroundParams.FTargetObject, PitchDelta, TurnDelta, ADeltaTime);
end;
function TVXSmoothNavigator.MoveObjectAround(
const AObject: TVXBaseSceneObject; PitchDelta, TurnDelta: Single;
ADeltaTime: Double): Boolean;
var
FinalPitch: Single;
FinalTurn: Single;
lUp: TVector;
begin
Result := False;
FinalPitch := 0;
FinalTurn := 0;
with FMoveAroundParams do
begin
PitchDelta := PitchDelta * FPitchSpeed;
TurnDelta := TurnDelta * FTurnSpeed;
while ADeltaTime > FMaxExpectedDeltatime do
begin
PitchDelta := ClampValue((PitchDelta * FMaxExpectedDeltatime + FOldPitchInertiaAngle * FInertia) / (FInertia + 1), - FMaxAngle, FMaxAngle);
FOldPitchInertiaAngle := PitchDelta;
FinalPitch := FinalPitch + PitchDelta;
TurnDelta := ClampValue((TurnDelta * FMaxExpectedDeltatime + FOldTurnInertiaAngle * FInertia) / (FInertia + 1), - FMaxAngle, FMaxAngle);
FOldTurnInertiaAngle := TurnDelta;
FinalTurn := FinalTurn + TurnDelta;
ADeltaTime := ADeltaTime - FMaxExpectedDeltatime;
end;
if UseVirtualUp then
lUp := VirtualUp.AsVector
else
lUp := MovingObject.AbsoluteUp;
if (Abs(FinalPitch) > FCutOff) or (Abs(FinalTurn) > FCutOff) then
begin
MovingObject.AbsolutePosition := VXS.VectorGeometry.MoveObjectAround(
MovingObject.AbsolutePosition, lUp, AObject.AbsolutePosition, FinalPitch, FinalTurn);
Result := True;
end;
end;
end;
function TVXSmoothNavigator.AdjustDistanceToPoint(const APoint: TVector;
const DistanceRatio: Single; ADeltaTime: Double): Boolean;
// Based on TVXCamera.AdjustDistanceToTarget
procedure DoAdjustDistanceToPoint(const DistanceRatio: Single);
var
vect: TVector;
begin
vect := VectorSubtract(MovingObject.AbsolutePosition, APoint);
ScaleVector(vect, (distanceRatio - 1));
AddVector(vect, MovingObject.AbsolutePosition);
if Assigned(MovingObject.Parent) then
vect := MovingObject.Parent.AbsoluteToLocal(vect);
MovingObject.Position.AsVector := vect;
Result := True;
end;
var
FinalDistanceRatio: Single;
TempDistanceRatio: Single;
begin
with FAdjustDistanceParams do
begin
TempDistanceRatio := DistanceRatio * FSpeed;
FinalDistanceRatio := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
TempDistanceRatio := (TempDistanceRatio * FMaxExpectedDeltaTime + FOldDistanceRatio * FInertia) / (FInertia + 1);
FOldDistanceRatio := TempDistanceRatio;
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistanceRatio := FinalDistanceRatio + FOldDistanceRatio / FMaxExpectedDeltaTime;
end;
if Abs(FinalDistanceRatio) > FCutoff then
begin
if FinalDistanceRatio > 0 then
DoAdjustDistanceToPoint(1 / (1 + FinalDistanceRatio))
else
DoAdjustDistanceToPoint(1 * (1 - FinalDistanceRatio))
end
else
Result := False;
end;
end;
function TVXSmoothNavigator.AdjustDistanceToTarget(const DistanceRatio: Single;
const ADeltaTime: Double): Boolean;
begin
Assert(FMoveAroundParams.FTargetObject <> nil);
Result := AdjustDistanceToPoint(FMoveAroundParams.FTargetObject.AbsolutePosition,
DistanceRatio, ADeltaTime);
end;
procedure TVXSmoothNavigator.SetAdjustDistanceParams(
const Value: TVXNavigatorAdjustDistanceParameters);
begin
FAdjustDistanceParams.Assign(Value);
end;
function TVXSmoothNavigator.AdjustDistanceToPointEx(const APoint: TVector;
ADeltaTime: Double): Boolean;
var
lAbsolutePosition: TVector;
lCurrentDistance: Single;
lDistanceDifference, lTempCurrentDistance: Single;
procedure DoAdjustDistanceToPoint(const DistanceValue: Single);
var
vect: TVector;
begin
vect := VectorSubtract(APoint, lAbsolutePosition);
NormalizeVector(vect);
ScaleVector(vect, DistanceValue);
MovingObject.AbsolutePosition := VectorAdd(lAbsolutePosition, vect);
Result := True;
end;
begin
lAbsolutePosition := MovingObject.AbsolutePosition;
lCurrentDistance := VectorDistance(lAbsolutePosition, APoint);
lDistanceDifference := lCurrentDistance - FAdjustDistanceParamsEx.FTargetDistance;
with FAdjustDistanceParamsEx do
begin
lTempCurrentDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
lTempCurrentDistance := (FSpeed * FMaxExpectedDeltaTime * lDistanceDifference * FInertia) / (FInertia + 1);
// lTempCurrentDistance := (FSpeed * FMaxExpectedDeltaTime + lDistanceDifference * FInertia) / (FInertia + 1);- this also works, but a bit different.
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
end;
lTempCurrentDistance := ClampValue(lTempCurrentDistance, -FSpeedLimit * ADeltaTime, FSpeedLimit * ADeltaTime);
if Abs(lTempCurrentDistance) > FCutoff then
DoAdjustDistanceToPoint(lTempCurrentDistance)
else
Result := False;
end;
end;
function TVXSmoothNavigator.AdjustDistanceToTargetEx(
const ADeltaTime: Double): Boolean;
begin
Assert(FMoveAroundParams.FTargetObject <> nil);
Result := AdjustDistanceToPointEx(FMoveAroundParams.FTargetObject.AbsolutePosition,
ADeltaTime);
end;
procedure TVXSmoothNavigator.SetAdjustDistanceParamsEx(
const Value: TVXNavigatorAdjustDistanceParametersEx);
begin
FAdjustDistanceParamsEx.Assign(Value);
end;
procedure TVXSmoothNavigator.AnimateCustomItems(const ADeltaTime: Double);
begin
FCustomAnimatedItems.DoProceed(ADeltaTime);
end;
procedure TVXSmoothNavigator.SetCustomAnimatedItems(
const Value: TVXNavigatorSmoothChangeItems);
begin
FCustomAnimatedItems.Assign(Value);
end;
{ TVXSmoothUserInterface }
function TVXSmoothUserInterface.MouseLook(
const ADeltaTime: Double): Boolean;
var
MousePos: TPoint;
begin
Assert(FAutoUpdateMouse, 'AutoUpdateMouse must be True to use this function');
if FMouseLookActive then
begin
GLGetCursorPos(MousePos);
Result := Mouselook(MousePos.X, MousePos.Y, ADeltaTime);
GLSetCursorPos(Round(OriginalMousePos.X), Round(OriginalMousePos.Y));
end
else
Result := False;
end;
function TVXSmoothUserInterface.Mouselook(const NewX, NewY: Integer; const ADeltaTime: Double): Boolean;
var
DeltaX, DeltaY: Single;
begin
Result := False;
if FMouseLookActive then
begin
Deltax := (NewX - FOriginalMousePos.X);
Deltay := (FOriginalMousePos.Y - NewY);
if InvertMouse then
DeltaY := -DeltaY;
SmoothNavigator.TurnHorizontal(DeltaX, ADeltaTime);
SmoothNavigator.TurnVertical(DeltaY, ADeltaTime);
Result := (DeltaX <> 0) or (DeltaY <> 0);
end;
end;
function TVXSmoothUserInterface.MouseLook(const NewXY: TPoint; const ADeltaTime: Double): Boolean;
begin
Result := Mouselook(NewXY.X, NewXY.Y, ADeltaTime);
end;
constructor TVXSmoothUserInterface.Create(AOwner: TComponent);
begin
inherited;
FMouseLookActive := False;
FAutoUpdateMouse := True;
FOriginalMousePos := TVXCoordinates2.CreateInitialized(Self,
VectorMake(GLGetScreenWidth div 2,
GLGetScreenHeight div 2, 0, 0), csPoint2D);
end;
procedure TVXSmoothUserInterface.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
begin
if AComponent = FSmoothNavigator then
FSmoothNavigator := nil;
if AComponent = FSmoothVertNavigator then
FSmoothNavigator := nil;
end;
end;
procedure TVXSmoothUserInterface.SetSmoothNavigator(
const Value: TVXSmoothNavigator);
begin
if FSmoothNavigator <> nil then
FSmoothNavigator.RemoveFreeNotification(Self);
FSmoothNavigator := Value;
if FSmoothNavigator <> nil then
FSmoothNavigator.FreeNotification(Self);
end;
destructor TVXSmoothUserInterface.Destroy;
begin
FOriginalMousePos.Destroy;
inherited;
end;
procedure TVXSmoothUserInterface.SetOriginalMousePos(
const Value: TVXCoordinates2);
begin
FOriginalMousePos.Assign(Value);
end;
procedure TVXSmoothUserInterface.SetSmoothVertNavigator(
const Value: TVXSmoothNavigator);
begin
if FSmoothVertNavigator <> nil then
FSmoothVertNavigator.RemoveFreeNotification(Self);
FSmoothVertNavigator := Value;
if FSmoothVertNavigator <> nil then
FSmoothVertNavigator.FreeNotification(Self);
end;
procedure TVXSmoothUserInterface.MouseLookActiveToggle;
begin
if FMouseLookActive then
SetMouseLookActive(False)
else
SetMouseLookActive(True)
end;
procedure TVXSmoothUserInterface.SetMouseLookActive(const Value: Boolean);
var
MousePos: TPoint;
begin
if FMouseLookActive = Value then Exit;
FMouseLookActive := Value;
if FMouseLookActive then
begin
if FAutoUpdateMouse then
begin
GLGetCursorPos(MousePos);
FOriginalMousePos.SetPoint2D(MousePos.X, MousePos.Y);
GLShowCursor(False);
end;
end
else
begin
if FAutoUpdateMouse then
GLShowCursor(True);
end;
end;
procedure TVXSmoothUserInterface.TurnHorizontal(const Angle: Single;
const ADeltaTime: Double);
begin
FSmoothNavigator.TurnHorizontal(Angle, ADeltaTime);
end;
procedure TVXSmoothUserInterface.TurnVertical(const Angle: Single;
const ADeltaTime: Double);
begin
if Assigned(FSmoothNavigator) then
FSmoothNavigator.TurnVertical(Angle, ADeltaTime)
else
FSmoothVertNavigator.TurnVertical(Angle, ADeltaTime);
end;
{ TVXNavigatorInertiaParameters }
procedure TVXNavigatorInertiaParameters.Assign(Source: TPersistent);
begin
if Source is TVXNavigatorInertiaParameters then
begin
FMovementAcceleration := TVXNavigatorInertiaParameters(Source).FMovementAcceleration;
FMovementInertia := TVXNavigatorInertiaParameters(Source).FMovementInertia;
FMovementSpeed := TVXNavigatorInertiaParameters(Source).FMovementSpeed;
FTurnMaxAngle := TVXNavigatorInertiaParameters(Source).FTurnMaxAngle;
FTurnInertia := TVXNavigatorInertiaParameters(Source).FTurnInertia;
FTurnSpeed := TVXNavigatorInertiaParameters(Source).FTurnSpeed;
end
else
inherited; //to the pit of doom ;)
end;
constructor TVXNavigatorInertiaParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FTurnInertia := 150;
FTurnSpeed := 50;
FTurnMaxAngle := 0.5;
FMovementAcceleration := 7;
FMovementInertia := 200;
FMovementSpeed := 200;
end;
function TVXNavigatorInertiaParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TVXNavigatorInertiaParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value > 1 then
begin
FMovementInertia := FMovementInertia * PowerSingle(2, 1 / Value);
FTurnInertia := FTurnInertia * PowerSingle(2, 1 / Value);
end
else
begin
FMovementInertia := FMovementInertia / PowerSingle(2, Value);
FTurnInertia := FTurnInertia / PowerSingle(2, Value);
end;
FTurnMaxAngle := FTurnMaxAngle / Value;
FTurnSpeed := FTurnSpeed * Value;
end;
function TVXNavigatorInertiaParameters.StoreTurnMaxAngle: Boolean;
begin
Result := Abs(FTurnMaxAngle - 0.5) > EPS;
end;
function TVXNavigatorInertiaParameters.StoreMovementAcceleration: Boolean;
begin
Result := Abs(FMovementAcceleration - 7) > EPS;
end;
function TVXNavigatorInertiaParameters.StoreMovementInertia: Boolean;
begin
Result := Abs(FMovementInertia - 200) > EPS;
end;
function TVXNavigatorInertiaParameters.StoreMovementSpeed: Boolean;
begin
Result := Abs(FMovementSpeed - 200) > EPS;
end;
function TVXNavigatorInertiaParameters.StoreTurnInertia: Boolean;
begin
Result := Abs(FTurnInertia - 150) > EPS;
end;
function TVXNavigatorInertiaParameters.StoreTurnSpeed: Boolean;
begin
Result := Abs(FTurnSpeed - 50) > EPS;
end;
{ TVXNavigatorGeneralParameters }
procedure TVXNavigatorGeneralParameters.Assign(Source: TPersistent);
begin
if Source is TVXNavigatorGeneralParameters then
begin
FAutoScaleMin := TVXNavigatorGeneralParameters(Source).FAutoScaleMin;
FAutoScaleMax := TVXNavigatorGeneralParameters(Source).FAutoScaleMax;
FAutoScaleMult := TVXNavigatorGeneralParameters(Source).FAutoScaleMult;
end
else
inherited; //die!
end;
constructor TVXNavigatorGeneralParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FAutoScaleMin := 0.1;
FAutoScaleMax := 0.75;
FAutoScaleMult := 2;
end;
function TVXNavigatorGeneralParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TVXNavigatorGeneralParameters.StoreAutoScaleMax: Boolean;
begin
Result := Abs(FAutoScaleMax - 0.75) > EPS;
end;
function TVXNavigatorGeneralParameters.StoreAutoScaleMin: Boolean;
begin
Result := Abs(FAutoScaleMin - 0.1) > EPS;
end;
function TVXNavigatorGeneralParameters.StoreAutoScaleMult: Boolean;
begin
Result := Abs(FAutoScaleMult - 2) > EPS;
end;
{ TVXNavigatorMoveAroundParameters }
procedure TVXNavigatorMoveAroundParameters.Assign(Source: TPersistent);
begin
if Source is TVXNavigatorMoveAroundParameters then
begin
FMaxAngle := TVXNavigatorMoveAroundParameters(Source).FMaxAngle;
FInertia := TVXNavigatorMoveAroundParameters(Source).FInertia;
FPitchSpeed := TVXNavigatorMoveAroundParameters(Source).FPitchSpeed;
FTurnSpeed := TVXNavigatorMoveAroundParameters(Source).FTurnSpeed;
FCutoff := TVXNavigatorMoveAroundParameters(Source).FCutoff;
SetTargetObject(TVXNavigatorMoveAroundParameters(Source).FTargetObject);
end
else
inherited; //die
end;
constructor TVXNavigatorMoveAroundParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FPitchSpeed := 500;
FTurnSpeed := 500;
FInertia := 65;
FMaxAngle := 1.5;
FCutoff := EPS2;
end;
function TVXNavigatorMoveAroundParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TVXNavigatorMoveAroundParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value < 1 then
FInertia := FInertia / PowerSingle(2, Value)
else
FInertia := FInertia * PowerSingle(2, 1 / Value);
FMaxAngle := FMaxAngle / Value;
FPitchSpeed := FPitchSpeed * Value;
FTurnSpeed := FTurnSpeed * Value;
end;
procedure TVXNavigatorMoveAroundParameters.SetTargetObject(
const Value: TVXBaseSceneObject);
begin
if FTargetObject <> nil then
if FOwner is TVXSmoothNavigator then
FTargetObject.RemoveFreeNotification(TVXSmoothNavigator(FOwner));
FTargetObject := Value;
if FTargetObject <> nil then
if FOwner is TVXSmoothNavigator then
FTargetObject.FreeNotification(TVXSmoothNavigator(FOwner));
end;
function TVXNavigatorMoveAroundParameters.StoreCutoff: Boolean;
begin
Result := Abs(FCutoff - EPS2) > EPS8;
end;
function TVXNavigatorMoveAroundParameters.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 65) > EPS;
end;
function TVXNavigatorMoveAroundParameters.StoreMaxAngle: Boolean;
begin
Result := Abs(FMaxAngle - 1.5) > EPS;
end;
function TVXNavigatorMoveAroundParameters.StorePitchSpeed: Boolean;
begin
Result := Abs(FPitchSpeed - 500) > EPS;
end;
function TVXNavigatorMoveAroundParameters.StoreTurnSpeed: Boolean;
begin
Result := Abs(FTurnSpeed - 500) > EPS;
end;
{ TVXNavigatorAdjustDistanceParameters }
procedure TVXNavigatorAdjustDistanceParameters.AddImpulse(
const Impulse: Single);
begin
FOldDistanceRatio := FOldDistanceRatio + Impulse * FSpeed / FInertia * FImpulseSpeed;
end;
procedure TVXNavigatorAdjustDistanceParameters.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TVXNavigatorAdjustDistanceParameters then
begin
FImpulseSpeed := TVXNavigatorAdjustDistanceParameters(Source).FImpulseSpeed;
end;
end;
constructor TVXNavigatorAdjustDistanceParameters.Create(
AOwner: TPersistent);
begin
inherited;
FImpulseSpeed := 0.02;
end;
procedure TVXNavigatorAdjustDistanceParameters.ScaleParameters(
const Value: Single);
begin
inherited;
FImpulseSpeed := FImpulseSpeed / Value;
end;
function TVXNavigatorAdjustDistanceParameters.StoreImpulseSpeed: Boolean;
begin
Result := Abs(FImpulseSpeed - 0.02) > EPS;
end;
{ TVXNavigatorAbstractParameters }
procedure TVXNavigatorAbstractParameters.Assign(Source: TPersistent);
begin
if Source is TVXNavigatorAbstractParameters then
begin
FInertia := TVXNavigatorAbstractParameters(Source).FInertia;
FSpeed := TVXNavigatorAbstractParameters(Source).FSpeed;
FCutoff := TVXNavigatorAbstractParameters(Source).FCutoff;
end
else
inherited; //to the pit of doom ;)
end;
constructor TVXNavigatorAbstractParameters.Create(
AOwner: TPersistent);
begin
FOwner := AOwner;
FInertia := 100;
FSpeed := 0.005;
FCutoff := EPS;
end;
function TVXNavigatorAbstractParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TVXNavigatorAbstractParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value < 1 then
FInertia := FInertia / PowerSingle(2, Value)
else
FInertia := FInertia * PowerSingle(2, 1 / Value);
end;
function TVXNavigatorAbstractParameters.StoreCutoff: Boolean;
begin
Result := Abs(FCutoff - EPS) > EPS2;
end;
function TVXNavigatorAbstractParameters.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 100) > EPS;
end;
function TVXNavigatorAbstractParameters.StoreSpeed: Boolean;
begin
Result := Abs(FSpeed - 0.005) > EPS2;
end;
{ TVXNavigatorAdjustDistanceParametersEx }
procedure TVXNavigatorAdjustDistanceParametersEx.Assign(
Source: TPersistent);
begin
if Source is TVXNavigatorAdjustDistanceParametersEx then
begin
FTargetDistance := TVXNavigatorAdjustDistanceParametersEx(Source).FTargetDistance;
FSpeedLimit := TVXNavigatorAdjustDistanceParametersEx(Source).FSpeedLimit;
end
else
inherited;
end;
constructor TVXNavigatorAdjustDistanceParametersEx.Create(
AOwner: TPersistent);
begin
inherited;
FInertia := 0.5;
FTargetDistance := 100;
FSpeed := 100;
FSpeedLimit := 20000;
end;
function TVXNavigatorAdjustDistanceParametersEx.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 0.5) > EPS2;
end;
function TVXNavigatorAdjustDistanceParametersEx.StoreSpeed: Boolean;
begin
Result := Abs(FSpeed - 100) > EPS2;
end;
function TVXNavigatorAdjustDistanceParametersEx.StoreSpeedLimit: Boolean;
begin
Result := Abs(FSpeedLimit - 20000) > EPS2;
end;
function TVXNavigatorAdjustDistanceParametersEx.StoreTargetDistance: Boolean;
begin
Result := Abs(FTargetDistance - 100) > EPS2;
end;
{ TVXNavigatorSmoothChangeItem }
procedure TVXNavigatorSmoothChangeItem.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TVXNavigatorSmoothChangeItem then
begin
FInertia := TVXNavigatorSmoothChangeItem(Source).FInertia;
FSpeed := TVXNavigatorSmoothChangeItem(Source).FSpeed;
FSpeedLimit := TVXNavigatorSmoothChangeItem(Source).FSpeedLimit;
FCutoff := TVXNavigatorSmoothChangeItem(Source).FCutoff;
FEnabled := TVXNavigatorSmoothChangeItem(Source).FEnabled;
end;
end;
constructor TVXNavigatorSmoothChangeItem.Create(aOwner: TXCollection);
begin
inherited;
FInertia := 1;
FSpeed := 5.5;
FSpeedLimit := 20000;
FCutoff := EPS;
FEnabled := True;
end;
function TVXNavigatorSmoothChangeItem.GetNavigator: TVXSmoothNavigator;
begin
Result := TVXSmoothNavigator(TVXNavigatorSmoothChangeItems(GetOwner).Owner);
end;
procedure TVXNavigatorSmoothChangeItem.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value < 1 then
FInertia := FInertia / PowerSingle(2, Value)
else
FInertia := FInertia * PowerSingle(2, 1 / Value);
end;
function TVXNavigatorSmoothChangeItem.StoreCutoff: Boolean;
begin
Result := Abs(FCutoff - EPS) > EPS8;
end;
function TVXNavigatorSmoothChangeItem.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 1) > EPS;
end;
function TVXNavigatorSmoothChangeItem.StoreSpeed: Boolean;
begin
Result := Abs(FSpeed - 5.5) > EPS2;
end;
function TVXNavigatorSmoothChangeItem.StoreSpeedLimit: Boolean;
begin
Result := Abs(FSpeedLimit - 20000) > EPS2;
end;
{ TVXNavigatorSmoothChangeItems }
function TVXNavigatorSmoothChangeItems.Add(AClass : TVXNavigatorSmoothChangeItemClass): TVXNavigatorSmoothChangeItem;
begin
Result := AClass.Create(Self);
end;
function TVXNavigatorSmoothChangeItems.CanAdd(AClass: TXCollectionItemClass): Boolean;
begin
Result := AClass.InheritsFrom(TVXNavigatorSmoothChangeItem);
end;
procedure TVXNavigatorSmoothChangeItems.DoProceed(ADeltaTime: Double);
var
I: Integer;
begin
for I := 0 to Count - 1 do
GetItems(I).Proceed(ADeltaTime);
end;
function TVXNavigatorSmoothChangeItems.GetItems(const Index : Integer): TVXNavigatorSmoothChangeItem;
begin
Result := TVXNavigatorSmoothChangeItem(inherited GetItems(Index));
end;
class function TVXNavigatorSmoothChangeItems.ItemsClass: TXCollectionItemClass;
begin
Result := TVXNavigatorSmoothChangeItem;
end;
procedure TVXNavigatorSmoothChangeItems.SetItems(const Index : Integer; const Value:
TVXNavigatorSmoothChangeItem);
begin
GetItems(Index).Assign(Value);
end;
{ TVXNavigatorSmoothChangeSingle }
procedure TVXNavigatorSmoothChangeSingle.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TVXNavigatorSmoothChangeVector then
begin
FTargetValue := TVXNavigatorSmoothChangeSingle(Source).TargetValue;
FOnGetCurrentValue := TVXNavigatorSmoothChangeSingle(Source).FOnGetCurrentValue;
FOnSetCurrentValue := TVXNavigatorSmoothChangeSingle(Source).FOnSetCurrentValue;
end;
end;
class function TVXNavigatorSmoothChangeSingle.FriendlyName: string;
begin
Result := 'Navigator SmoothChange Single';
end;
function TVXNavigatorSmoothChangeSingle.Proceed(ADeltaTime: Double): Boolean;
var
lCurrentValue: Single;
lCurrentDifference: Single;
lTotalDistanceToTravelThisTime, lDistanceToTravelThisTime: Single;
lMaxExpectedDeltaTime: Double;
begin
Result := False;
if not FEnabled then Exit;
if not Assigned(FOnGetCurrentValue) then Exit;
if not Assigned(FOnSetCurrentValue) then Exit;
lMaxExpectedDeltaTime := GetNavigator.FMaxExpectedDeltaTime;
lCurrentValue := FOnGetCurrentValue(Self);
lCurrentDifference := FTargetValue - lCurrentValue;
lTotalDistanceToTravelThisTime := 0;
while ADeltaTime > lMaxExpectedDeltaTime do
begin
lDistanceToTravelThisTime := MinFloat((lCurrentDifference * ADeltaTime * FSpeed * FInertia) / (FInertia + 1), FSpeedLimit);
// lDistanceToTravelThisTime := (lCurrentDistance * ADeltaTime + FSpeed * FInertia) / (FInertia + 1);- this also works, but a bit different.
lCurrentDifference := lCurrentDifference - lDistanceToTravelThisTime;
lTotalDistanceToTravelThisTime := lTotalDistanceToTravelThisTime + lDistanceToTravelThisTime;
ADeltaTime := ADeltaTime - lMaxExpectedDeltaTime;
end;
if Abs(lTotalDistanceToTravelThisTime) > FCutoff then
begin
FOnSetCurrentValue(Self, lCurrentValue + lTotalDistanceToTravelThisTime);
Result := True;
end;
end;
procedure TVXNavigatorSmoothChangeSingle.ResetTargetValue;
begin
FTargetValue := FOnGetCurrentValue(Self);
end;
{ TVXNavigatorSmoothChangeVector }
procedure TVXNavigatorSmoothChangeVector.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TVXNavigatorSmoothChangeVector then
begin
FTargetValue.Assign(TVXNavigatorSmoothChangeVector(Source).TargetValue);
FOnGetCurrentValue := TVXNavigatorSmoothChangeVector(Source).FOnGetCurrentValue;
FOnSetCurrentValue := TVXNavigatorSmoothChangeVector(Source).FOnSetCurrentValue;
end;
end;
constructor TVXNavigatorSmoothChangeVector.Create(aOwner: TXCollection);
begin
inherited;
FTargetValue := TVXCoordinates.CreateInitialized(Self, NullHmgVector, csVector);
end;
destructor TVXNavigatorSmoothChangeVector.Destroy;
begin
FTargetValue.Free;
inherited;
end;
class function TVXNavigatorSmoothChangeVector.FriendlyName: string;
begin
Result := 'Navigator SmoothChange Vector';
end;
function TVXNavigatorSmoothChangeVector.Proceed(ADeltaTime: Double): Boolean;
var
lAbsolutePosition: TVector;
lCurrentDistance: Single;
lTotalDistanceToTravelThisTime, lDistanceToTravelThisTime: Single;
lMaxExpectedDeltaTime: Double;
procedure DoAdjustDistanceToPoint();
var
vect: TVector;
begin
vect := VectorScale(VectorNormalize(VectorSubtract(FTargetValue.DirectVector, lAbsolutePosition)), lTotalDistanceToTravelThisTime);
AddVector(vect, lAbsolutePosition);
// Did we go too far?
if VectorDistance(vect, FTargetValue.DirectVector) > VectorDistance(lAbsolutePosition, FTargetValue.DirectVector) then
vect := FTargetValue.DirectVector;
FOnSetCurrentValue(Self, vect);
Result := True;
end;
begin
Result := False;
if not FEnabled then Exit;
if not Assigned(FOnGetCurrentValue) then Exit;
if not Assigned(FOnSetCurrentValue) then Exit;
lMaxExpectedDeltaTime := GetNavigator.FMaxExpectedDeltaTime;
lAbsolutePosition := FOnGetCurrentValue(Self);
lCurrentDistance := VectorDistance(lAbsolutePosition, FTargetValue.DirectVector);
lTotalDistanceToTravelThisTime := 0;
while ADeltaTime > lMaxExpectedDeltaTime do
begin
lDistanceToTravelThisTime := MinFloat((lCurrentDistance * ADeltaTime * FSpeed * FInertia) / (FInertia + 1), FSpeedLimit);
// lDistanceToTravelThisTime := (lCurrentDistance * ADeltaTime + FSpeed * FInertia) / (FInertia + 1);- this also works, but a bit different.
lCurrentDistance := lCurrentDistance - lDistanceToTravelThisTime;
lTotalDistanceToTravelThisTime := lTotalDistanceToTravelThisTime + lDistanceToTravelThisTime;
ADeltaTime := ADeltaTime - lMaxExpectedDeltaTime;
end;
if Abs(lTotalDistanceToTravelThisTime) > FCutoff then
DoAdjustDistanceToPoint();
end;
procedure TVXNavigatorSmoothChangeVector.ResetTargetValue;
begin
FTargetValue.DirectVector := FOnGetCurrentValue(Self);
end;
procedure TVXNavigatorSmoothChangeVector.SetTargetValue(
const Value: TVXCoordinates);
begin
FTargetValue.Assign(Value);
end;
initialization
RegisterClasses([
TVXSmoothNavigator, TVXSmoothUserInterface,
TVXNavigatorInertiaParameters, TVXNavigatorGeneralParameters,
TVXNavigatorMoveAroundParameters,
TVXNavigatorAdjustDistanceParameters, TVXNavigatorAdjustDistanceParametersEx
]);
RegisterXCollectionItemClass(TVXNavigatorSmoothChangeSingle);
RegisterXCollectionItemClass(TVXNavigatorSmoothChangeVector);
end.
|
{* euclid.pas *}
program euclid;
var a,b,result:integer;
{* Greatest Common Divisor Function*}
function GCD(a, b : integer) : integer;
var t, r : integer;
begin
if (a < b) then
begin
t := a; a := b; b := t
end;
repeat
r := a mod b; {* modulus *}
a := b;
b := r
until r = 0;
GCD := a;
end;
{* Main Function *}
begin
writeln('Greatest Common Divisor (GCD)');
writeln('using Euclid Algorithm');
write('Enter number A:'); readln(a);
write('Enter number B:'); readln(b);
result:= GCD(a,b);
writeln(' GCD = ', result);
end.
|
unit GamePoints;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, math;
type
{ TGamePoint }
TGamePoint = object
public
X, Y: Double;
procedure Assign(AX, AY: Double);
end;
function GamePoint(X, Y: Double): TGamePoint;
operator + (A, B: TGamePoint) C: TGamePoint;
operator - (A, B: TGamePoint) C: TGamePoint;
operator*(A: TGamePoint; X: Double)C: TGamePoint;
function abs(A: TGamePoint): Double;
function EnsureAbs(A: TGamePoint; MinAbs, MaxAbs: Double): TGamePoint;
implementation
function GamePoint(X, Y: Double): TGamePoint;
begin
Result.X := X;
Result.Y := Y;
end;
operator+(A, B: TGamePoint)C: TGamePoint;
begin
C.X := A.X + B.X;
C.Y := A.Y + B.Y;
end;
operator-(A, B: TGamePoint)C: TGamePoint;
begin
C.X := A.X - B.X;
C.Y := A.Y - B.Y;
end;
operator*(A: TGamePoint; X: Double)C: TGamePoint;
begin
C.X := A.X * X;
C.Y := A.Y * X;
end;
function abs(A: TGamePoint): Double;
begin
Result := hypot(A.X, A.Y);
end;
function EnsureAbs(A: TGamePoint; MinAbs, MaxAbs: Double): TGamePoint;
begin
if abs(A) < MinAbs then
exit(A * (MinAbs / abs(A)));
if abs(A) > MaxAbs then
exit(A * (MaxAbs / abs(A)));
exit(A);
end;
{ TGamePoint }
procedure TGamePoint.Assign(AX, AY: Double);
begin
X := AX;
Y := AY;
end;
end.
|
unit UnitListarProcessos;
interface
uses
Windows,
TLhelp32,
PsAPI;
function ListaDeProcessos: String;
function TerminarProceso(PID: cardinal): Boolean;
function RutaProcesos(PID: DWORD): string;
procedure SetTokenPrivileges;
implementation
uses
UnitServerUtils;
function GetProcessMemoryUsage(PID: cardinal): Cardinal;
var
l_nWndHandle, l_nProcID, l_nTmpHandle: HWND;
l_pPMC: PPROCESS_MEMORY_COUNTERS;
l_pPMCSize: Cardinal;
begin
result := 0;
l_pPMCSize := SizeOf(PROCESS_MEMORY_COUNTERS);
GetMem(l_pPMC, l_pPMCSize);
l_pPMC^.cb := l_pPMCSize;
l_nTmpHandle := OpenProcess(PROCESS_ALL_ACCESS, False, PID);
try
if (GetProcessMemoryInfo(l_nTmpHandle, l_pPMC, l_pPMCSize)) then
Result := l_pPMC^.WorkingSetSize else Result := 0;
except
end;
FreeMem(l_pPMC);
end;
function ListaDeProcessos: String;
var
Proceso : TProcessEntry32;
ProcessHandle : THandle;
HayOtroProceso : Boolean;
begin
SetTokenPrivileges;
Result := '';
Proceso.dwSize := SizeOf(TProcessEntry32);
ProcessHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if Process32First(ProcessHandle, Proceso) then
begin
Result:= String(Proceso.szExeFile) + '|' +
IntToStr(Proceso.th32ProcessID) + '|' +
inttostr(GetProcessMemoryUsage(Proceso.th32ProcessID)) + '|' +
string(RutaProcesos(Proceso.th32ProcessID)) + '|' + #13#10;
repeat
HayOtroProceso := Process32Next(ProcessHandle, Proceso);
if HayOtroProceso then
Result:= result + String(Proceso.szExeFile) + '|' +
IntToStr(Proceso.th32ProcessID) + '|' +
inttostr(GetProcessMemoryUsage(Proceso.th32ProcessID)) + '|' +
string(RutaProcesos(Proceso.th32ProcessID)) + '|' + #13#10;
until not HayOtroProceso;
end;
CloseHandle(ProcessHandle);
end;
procedure SetTokenPrivileges;
var
hToken1, hToken2, hToken3: THandle;
TokenPrivileges: TTokenPrivileges;
Version: OSVERSIONINFO;
begin
Version.dwOSVersionInfoSize := SizeOf(OSVERSIONINFO);
GetVersionEx(Version);
if Version.dwPlatformId <> VER_PLATFORM_WIN32_WINDOWS then
begin
try
OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken1);
hToken2 := hToken1;
LookupPrivilegeValue(nil, 'SeDebugPrivilege', TokenPrivileges.Privileges[0].luid);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
hToken3 := 0;
AdjustTokenPrivileges(hToken1, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
hToken3 := 0;
AdjustTokenPrivileges(hToken2, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3);
CloseHandle(hToken1);
except;
end;
end;
end;
function TerminarProceso(PID: cardinal): Boolean;
var
ProcessHandle : THandle;
begin
SetTokenPrivileges;
try
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, TRUE, PID);
if TerminateProcess(ProcessHandle ,0) then
Result := True
except
Result := False;
end;
end;
function StrLen(tStr:PChar):integer;
begin
result := 0;
while tStr[Result] <> #0 do
inc(Result);
end;
function RutaProcesos(PID: DWORD): string;
var
Handle: THandle;
begin
Result := ' ';
Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID);
if Handle <> 0 then
try
SetLength(Result, MAX_PATH);
begin
if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
SetLength(Result, StrLen(PChar(Result)))
else
Result := ' ';
end
finally
CloseHandle(Handle);
end;
end;
end.
|
unit BsEditRegion;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, DB, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxLabel, cxControls,
cxContainer, cxEdit, cxTextEdit, ActnList, FIBDataSet, pFIBDataSet,
FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, StdCtrls,
cxButtons, AdrEdit, BaseTypes, BsAdrConsts, BsAdrSpr, cxCheckBox;
type
TfrmEditRegion = class(TEditForm)
btnOk: TcxButton;
btnCancel: TcxButton;
EditDB: TpFIBDatabase;
eTrRead: TpFIBTransaction;
eTrWrite: TpFIBTransaction;
eStoredProc: TpFIBStoredProc;
EDSet: TpFIBDataSet;
ActionList1: TActionList;
ActOk: TAction;
ActCancel: TAction;
RegionEdit: TcxTextEdit;
lblRegion: TcxLabel;
lblTypeRegion: TcxLabel;
lblCountry: TcxLabel;
TypeRegionBox: TcxLookupComboBox;
CountryBox: TcxLookupComboBox;
btnTypeRegion: TcxButton;
btnCountry: TcxButton;
TypeRegionDSet: TpFIBDataSet;
CountryDSet: TpFIBDataSet;
TypeRegionDS: TDataSource;
CountryDS: TDataSource;
ZipEndEdit: TcxTextEdit;
cxLabel1: TcxLabel;
ZipBegEdit: TcxTextEdit;
lblZip: TcxLabel;
chZipEqual: TcxCheckBox;
procedure FormShow(Sender: TObject);
procedure ActOkExecute(Sender: TObject);
procedure ActCancelExecute(Sender: TObject);
procedure TypeRegionBoxPropertiesChange(Sender: TObject);
procedure CountryBoxPropertiesChange(Sender: TObject);
procedure btnTypeRegionClick(Sender: TObject);
procedure btnCountryClick(Sender: TObject);
procedure chZipEqualPropertiesChange(Sender: TObject);
procedure ZipBegEditPropertiesChange(Sender: TObject);
procedure ZipBegEditKeyPress(Sender: TObject; var Key: Char);
procedure ZipEndEditKeyPress(Sender: TObject; var Key: Char);
private
function CheckData:Boolean;
public
{ Public declarations }
end;
var
frmEditRegion: TfrmEditRegion;
implementation
{$R *.dfm}
procedure TfrmEditRegion.FormShow(Sender: TObject);
begin
try
TypeRegionDSet.Close;
TypeRegionDSet.SQLs.SelectSQL.Text:=ReqionTypeSqlText;
TypeRegionDSet.Open;
CountryDSet.Close;
CountryDSet.SQLs.SelectSQL.Text:=CountrySqlText;
CountryDSet.Open;
if not VarIsNull(KeyField) then
begin
EDSet.Close;
EDSet.SQLs.SelectSQL.Text:=frmRegionSqlText+'('+IntToStr(KeyField)+')';
EDSet.Open;
TypeRegionBox.EditValue:=EDSet['ID_REGION_TYPE'];
CountryBox.EditValue:=EDSet['ID_COUNTRY'];
RegionEdit.Text:=EDSet['NAME_REGION'];
if not VarIsNull(EDSet['ZIP_BEG']) then ZipBegEdit.Text:=IntToStr(EDSet['ZIP_BEG']);
if not VarIsNull(EDSet['ZIP_END']) then ZipEndEdit.Text:=IntToStr(EDSet['ZIP_END']);
Self.Caption:='Змінити область';
end
else
begin
CountryBox.EditValue:=AddInfo;
Self.Caption:='Додати область';
end;
except on E:Exception
do agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
end;
end;
procedure TfrmEditRegion.ActOkExecute(Sender: TObject);
begin
if CheckData then
begin
try
eStoredProc.StoredProcName:='ADR_REGION_IU';
eTrWrite.StartTransaction;
// eStoredProc.Transaction.StartTransaction;
eStoredProc.Prepare;
eStoredProc.ParamByName('ID_R').AsVariant:=KeyField;
eStoredProc.ParamByName('NAME_REGION').AsString:=RegionEdit.Text;
eStoredProc.ParamByName('ID_COUNTRY').AsInteger:=CountryBox.EditValue;
eStoredProc.ParamByName('ID_REGION_TYPE').AsInteger:=TypeRegionBox.EditValue;
eStoredProc.ExecProc;
ReturnId:=eStoredProc.FieldByName('ID_REGION').AsInteger;
if ((ZipBegEdit.Text<>'') and (ZipEndEdit.Text<>'')) then
begin
eStoredProc.StoredProcName:='ADR_ZIP_REGION_IU';
eStoredProc.Prepare;
eStoredProc.ParamByName('ID_REGION').AsInteger:=ReturnId;
eStoredProc.ParamByName('ZIP_BEG').AsInteger:=StrToInt(ZipBegEdit.Text);
eStoredProc.ParamByName('ZIP_END').AsInteger:=StrToInt(ZipEndEdit.Text);
eStoredProc.ExecProc;
end;
eTrWrite.Commit;
ModalResult:=mrOk;
except on E:Exception
do begin
agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
eTrWrite.Rollback;
end;
end;
end;
end;
procedure TfrmEditRegion.ActCancelExecute(Sender: TObject);
begin
CloseConnect;
ModalResult:=mrCancel;
end;
procedure TfrmEditRegion.TypeRegionBoxPropertiesChange(Sender: TObject);
begin
GlobalBoxFilter(TypeRegionBox, 'NAME_FULL');
end;
procedure TfrmEditRegion.CountryBoxPropertiesChange(Sender: TObject);
begin
GlobalBoxFilter(CountryBox, 'NAME_COUNTRY');
end;
function TfrmEditRegion.CheckData:Boolean;
begin
Result:=True;
if RegionEdit.Text='' then
begin
RegionEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не заповнили поле "Область"!', mtInformation, [mbOK]);
Result:=False;
end;
if VarIsNull(TypeRegionBox.EditValue) then
begin
TypeRegionBox.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не обрали тип області!', mtInformation, [mbOK]);
Result:=False;
end;
if VarIsNull(CountryBox.EditValue) then
begin
CountryBox.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не обрали країну!', mtInformation, [mbOK]);
Result:=False;
end;
if (((ZipBegEdit.Text='') and (ZipEndEdit.Text<>'')) or
((ZipBegEdit.Text<>'') and (ZipEndEdit.Text=''))) then
begin
ZipBegEdit.Style.Color:=clRed;
ZipEndEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Вкажіть повністю діапозон!', mtInformation, [mbOK]);
Result:=False;
end;
if (((ZipBegEdit.Text<>'') and (ZipEndEdit.Text<>'')) and
(StrToInt(ZipBegEdit.Text)>StrToInt(ZipEndEdit.Text))) then
begin
ZipBegEdit.Style.Color:=clRed;
ZipEndEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Початок діапозону не можу перевищувати кінець!', mtInformation, [mbOK]);
Result:=False;
end;
end;
procedure TfrmEditRegion.btnTypeRegionClick(Sender: TObject);
var sParam:TSpravParams;
frm:TfrmSprav;
begin
sParam.FormCaption := 'Довідник типів областей';
sParam.SelectText := TypeRegionDSet.SQLs.SelectSQL.Text;
sParam.NameFields := 'Name_Full,ID_REGION_TYPE';
sParam.FieldsCaption := 'Тип області';
sParam.KeyField := 'ID_REGION_TYPE';
sParam.ReturnFields := 'ID_REGION_TYPE,Name_Full';
sParam.FilterFields:='Name_Full';
sParam.FilterCaptions:='Тип області';
sParam.DbHandle:=EditDB.Handle;
sParam.frmButtons:=[fbRefresh,fbSelect,fbExit];
frm:=TfrmSprav.Create(Self, sParam);
if frm.ShowModal=mrOk then
begin
if TypeRegionDSet.Active then TypeRegionDSet.Close;
TypeRegionDSet.Open;
TypeRegionBox.EditValue:=frm.Res[0];
end;
frm.Free;
end;
procedure TfrmEditRegion.btnCountryClick(Sender: TObject);
var sParam:TSpravParams;
frm:TfrmSprav;
begin
sParam.FormCaption := 'Довідник країн';
sParam.SelectText := CountryDSet.SQLs.SelectSQL.Text;
sParam.NameFields := 'Name_Country,Id_Country';
sParam.FieldsCaption := 'Країна';
sParam.KeyField := 'Id_Country';
sParam.ReturnFields := 'Id_Country,Name_Country';
sParam.FilterFields:='Name_Country';
sParam.FilterCaptions:='Назва країни';
sParam.DbHandle:=EditDB.Handle;
sParam.NameClass:='TfrmEditCountry';
sParam.DeleteProcName:='ADR_COUNTRY_D';
sParam.frmButtons:=[fbAdd,fbModif,fbDelete,fbRefresh,fbSelect,fbExit];
frm:=TfrmSprav.Create(Self, sParam);
if frm.ShowModal=mrOk then
begin
if CountryDSet.Active then CountryDSet.Close;
CountryDSet.Open;
CountryBox.EditValue:=frm.Res[0];
end;
frm.Free;
end;
procedure TfrmEditRegion.chZipEqualPropertiesChange(Sender: TObject);
begin
ZipEndEdit.Enabled:=not chZipEqual.Checked;
if chZipEqual.Checked then ZipEndEdit.Text:=ZipBegEdit.Text;
end;
procedure TfrmEditRegion.ZipBegEditPropertiesChange(Sender: TObject);
begin
if chZipEqual.Checked then ZipEndEdit.Text:=ZipBegEdit.EditingText;
end;
procedure TfrmEditRegion.ZipBegEditKeyPress(Sender: TObject;
var Key: Char);
begin
if ((Key in ['0'..'9']) or (Key=#8)) then ZipBegEdit.Properties.ReadOnly:=False
else ZipBegEdit.Properties.ReadOnly:=True;
end;
procedure TfrmEditRegion.ZipEndEditKeyPress(Sender: TObject;
var Key: Char);
begin
if ((Key in ['0'..'9']) or (Key=#8)) then ZipEndEdit.Properties.ReadOnly:=False
else ZipEndEdit.Properties.ReadOnly:=True;
end;
initialization
RegisterClass(TfrmEditRegion);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1997-1999 Borland Software Corporation }
{ }
{*******************************************************}
unit IdZLibConst;
interface
{$I IdCompilerDefines.inc}
{$UNDEF STATICLOAD_ZLIB}
{$IFNDEF FPC}
{$IFDEF WINDOWS}
{$IFNDEF BCB5_DUMMY_BUILD}
{$DEFINE STATICLOAD_ZLIB}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$IFNDEF STATICLOAD_ZLIB}
uses
IdException;
{$ENDIF}
resourcestring
sTargetBufferTooSmall = 'ZLib エラー : ターゲットバッファが足りません。';
sInvalidStreamOp = 'ストリーム操作が無効です';
sZLibError = 'ZLib エラー (%d)';
{$IFNDEF STATICLOAD_ZLIB}
RSZLibCallError = 'ZLib ライブラリ関数 %s の呼び出しでエラーが発生しました';
{$ENDIF}
implementation
end.
|
unit uDMImportInventoryTextFile;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDMImportTextFile, DB, ADODB, uContentClasses, uDMCalcPrice,
uDMImportInventory, uSystemConst;
type
TDMImportInventoryTextFile = class(TDMImportTextFile)
procedure DataModuleDestroy(Sender: TObject);
private
FDMImportInventory: TDMImportInventory;
FDMCalcPrice : TDMCalcPrice;
FImportQty: Boolean;
FUpdateQty: Boolean;
FIDStore: Variant;
lstBarcodes: TList;
function GetNewBarcode: TBarCode;
function GetNewModel(Model, Description, IDUserLastSellingPrice: Variant; Qty, CaseQty: Double; SellingPrice, VendorCost: Currency): TModel;
function GetNewCategory(Category: variant): TCategory;
function GetNewModelGroup(ModelGroup: variant): TModelGroup;
function GetNewModelSubGroup(ModelSubGroup: variant): TModelSubGroup;
function GetNewVendor(Vendor: Variant): TVendor;
function GetNewManufacturer(Manufacturer: Variant): TManufacturer;
function GetNewVendorModelCode(VendorModelCode: Variant): TVendorModelCode;
protected
procedure BeforeImport; override;
procedure ImportLine; override;
procedure AfterImport; override;
procedure ConfigureCalcPrice(SQLConnection: TADOConnection);
end;
implementation
uses uNumericFunctions, uDMGlobal;
{$R *.dfm}
{ TDMImportInventoryTextFile }
procedure TDMImportInventoryTextFile.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(FDMImportInventory);
inherited;
end;
function TDMImportInventoryTextFile.GetNewModel(Model, Description, IDUserLastSellingPrice: Variant; Qty, CaseQty: Double;SellingPrice, VendorCost: Currency): TModel;
begin
Result := TModel.Create;
Result.IDModel := Null;
Result.Model := Model;
Result.Description := VarToStr(Description);
Result.Qty := Qty;
Result.CaseQty := CaseQty;
Result.VendorCost := VendorCost;
Result.IDUserLastSellingPrice := IDUserLastSellingPrice;
if not DMGlobal.IsClientServer(SQLConnection) then
Result.SellingPrice := SellingPrice
else
Result.SellingPrice := 0;
end;
function TDMImportInventoryTextFile.GetNewBarcode: TBarcode;
var
varSellingPrice, varVendorCost: Variant;
DecimalPoint: String;
CaseQty: Double;
begin
Result := TBarcode.Create;
if FImportQty then
begin
Result.Qty := StrToFloatDef(VarToStr(GetParamValue('Qty')), 0);
CaseQty := StrToFloatDef(VarToStr(GetParamValue('CaseQty')), 0);
end
else
begin
Result.Qty := 0;
CaseQty := 0;
end;
DecimalPoint := ImpExpConfig.Values['DecimalDelimiter'];
varSellingPrice := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(GetParamValue('SellingPrice')), DecimalPoint[1]));
varVendorCost := FDMCalcPrice.FormatPrice(MyStrToDouble(VarToStr(GetParamValue('VendorCost')), DecimalPoint[1]));
Result.Model := GetNewModel(GetParamValue('Model'), GetParamValue('Description'), ImpExpConfig.Values['IDUser'], Result.Qty, CaseQty, varSellingPrice, varVendorCost);
Result.Model.Category := GetNewCategory(GetParamValue('Category'));
Result.Model.ModelGroup := GetNewModelGroup(GetParamValue('Sub-Category'));
Result.Model.ModelSubGroup := GetNewModelSubGroup(GetParamValue('Group'));
Result.Model.Vendor := GetNewVendor(GetParamValue('Vendor'));
Result.Model.Manufacturer := GetNewManufacturer(GetParamValue('Manufacturer'));
Result.Model.VendorModelCode := GetNewVendorModelCode(GetParamValue('VendorModelCode'));
Result.IDBarcode := GetParamValue('Barcode');
end;
function TDMImportInventoryTextFile.GetNewCategory(Category: variant): TCategory;
var
I: Integer;
begin
if (Category = null) or (VarToStr(Category) = '') then
Result := nil
else
begin
Result := TCategory.Create;
Result.IDGroup := null;
Result.TabGroup := Category;
end;
end;
function TDMImportInventoryTextFile.GetNewVendorModelCode(VendorModelCode: Variant): TVendorModelCode;
var
I: Integer;
begin
if (VendorModelCode = null) or (VendorModelCode = '') then
Result := nil
else
begin
Result := TVendorModelCode.Create;
Result.IDVendorModelCode := null;
Result.IDVendor := null;
Result.IDModel := null;
Result.VendorCode := VendorModelCode;
end;
end;
function TDMImportInventoryTextFile.GetNewVendor(Vendor: Variant): TVendor;
var
I : Integer;
begin
if (Vendor = null) or (Vendor = '') then
Result := nil
else
begin
Result := TVendor.Create;
Result.IDVendor := null;
Result.Vendor := Vendor;
end;
end;
function TDMImportInventoryTextFile.GetNewManufacturer(Manufacturer: Variant): TManufacturer;
var
I : Integer;
begin
if (Manufacturer = null) or (Manufacturer = '') then
Result := nil
else
begin
Result := TManufacturer.Create;
Result.IDManufacturer := null;
Result.Manufacturer := Manufacturer;
end;
end;
procedure TDMImportInventoryTextFile.BeforeImport;
begin
inherited;
FDMImportInventory := TDMImportInventory.Create(Self);
FDMImportInventory.SQLConnection := Self.SQLConnection;
ConfigureCalcPrice( Self.SQLConnection );
lstBarcodes := TList.Create;
FImportQty := ImpExpConfig.Values['UseQty'] = 'Y';
FUpdateQty := ImpExpConfig.Values['QtyActionType'] = 'R';
FIDStore := ImpExpConfig.Values['IDStore'];
end;
procedure TDMImportInventoryTextFile.ImportLine;
var
aBarcode : TBarcode;
begin
inherited;
try
lstBarcodes.Add(GetNewBarcode);
FDMImportInventory.ImportBarcodes(lstBarcodes, FImportQty, FUpdateQty, FIDStore);
finally
while lstBarcodes.Count > 0 do
begin
aBarcode := TBarcode(lstBarcodes[0]);
FreeAndNil(aBarcode);
lstBarcodes.Delete(0);
end;
lstBarcodes.Clear;
end;
end;
function TDMImportInventoryTextFile.GetNewModelGroup(
ModelGroup: variant): TModelGroup;
var
I: Integer;
begin
if (ModelGroup = null) or (ModelGroup = '') then
Result := nil
else
begin
Result := TModelGroup.Create;
Result.IDModelGroup := null;
Result.ModelGroup := ModelGroup;
end;
end;
function TDMImportInventoryTextFile.GetNewModelSubGroup(
ModelSubGroup: variant): TModelSubGroup;
var
I: Integer;
begin
if (ModelSubGroup = null) or (ModelSubGroup = '') then
Result := nil
else
begin
Result := TModelSubGroup.Create;
Result.IDModelSubGroup := null;
Result.ModelSubGroup := ModelSubGroup;
end;
end;
procedure TDMImportInventoryTextFile.AfterImport;
begin
inherited;
if Assigned(FDMCalcPrice) then
FreeAndNil(FDMCalcPrice);
FreeAndNil(lstBarcodes);
end;
procedure TDMImportInventoryTextFile.ConfigureCalcPrice(
SQLConnection: TADOConnection);
begin
if not Assigned(FDMCalcPrice) then
FDMCalcPrice := TDMCalcPrice.Create(Self);
FDMCalcPrice.SetConnection(SQLConnection);
FDMCalcPrice.UseMargin := DMGlobal.GetSvrParam(PARAM_CALC_MARGIN ,SQLConnection);
FDMCalcPrice.UseRound := DMGlobal.GetSvrParam(PARAM_CALC_ROUNDING, SQLConnection);
end;
end.
|
{ NAME: Jordan Millett
CLASS: Comp Sci 1
DATE: 10/3/2016
PURPOSE: To create a guessing game
}
Program guess;
uses
crt;
Procedure getInt(ask:string;var num : integer);
var
numStr : string;
code : integer;
begin
repeat
write(ask);
readln(numstr);
val(numStr, num, code);
if code <> 0 then
begin
writeln('Please enter a number ');
writeln('Press any key to continue');
readkey;
clrscr;
end;
until (code = 0);
end;
Procedure Rolldice(var dice:integer);
var
die1, die2:integer;
begin
die1:=random(6)+1;
die2:=random(6)+1;
dice:=die1+die2;
end;
Procedure GuessHL(var choice:char);
begin
Write('Will the next roll be (H)igher,(L)ower or (E)qual? ');
readln(choice);
choice:=upcase(choice);
end;
Procedure Decide(var Roll1,Roll2,Bet,Bank:integer;choice:char);
begin
if (choice='M') then
begin
delay(200);
writeln(' ______ _ ______ ');
delay(200);
writeln(' | ____| | | | ____| ');
delay(200);
writeln(' | |__ __ _ ___| |_ ___ _ __ | |__ __ _ __ _ ');
delay(200);
writeln(' | __| / _` / __| __/ _ \ __| | __| / _ |/ _ |');
delay(200);
writeln(' | |___| (_| \__ \ || __/ | | |___| (_| | (_| |');
delay(200);
writeln(' |______\__,_|___/\__\___|_| |______\__, |\__, |');
delay(200);
writeln(' __/ | __/ |');
delay(200);
writeln(' |___/ |___/ ');
end
else if (choice = 'H') and (roll2 > roll1) then
begin
writeln('You win');
bank:=bank+bet*2;
writeln('you have ',bank,' dollars in the bank');
end
else if (choice = 'H') and (roll2 < roll1) then
begin
writeln('You lose');
bank:=bank-bet;
writeln('you have ',bank,' dollars in the bank');
end
else if (choice = 'L') and (roll2 > roll1) then
begin
writeln('You lose');
bank:=bank-bet;
writeln('you have ',bank,' dollars in the bank');
end
else if (choice = 'L') and (roll2 < roll1) then
begin
writeln('You win');
bank:=bank+bet*2;
writeln('you have ',bank,' dollars in the bank');
end
else if (choice = 'E') and (roll2=roll1) then
begin
writeln('You win');
bank:=bank+bet*5;
writeln('you have ',bank,' dollars in the bank');
end
else if (choice = 'E') and (roll2<>roll1) then
begin
writeln('You lose');
bank:=bank-bet;
writeln('you have ',bank,' dollars in the bank');
end
else if (choice = 'H') and (roll2 = roll1) then
begin
writeln('You lose');
bank:=bank-bet;
writeln('you have ',bank,' dollars in the bank');
end
else if (choice = 'L') and (roll2 = roll1) then
begin
writeln('You lose');
bank:=bank-bet;
writeln('you have ',bank,' dollars in the bank');
end else
begin
writeln('Incorrect Answer');
readkey;
end;
end;
Procedure Placebet(var bet,bank:integer);
begin
repeat
Writeln('You have ',bank,' dollars in your bank');
Getint('How much do you want to bet? ',Bet);
if (bet<0) then
begin
writeln('You cant bet a negative');
readkey;
end
else if (bank<bet) then
begin
writeln('You dont have enough money ');
readkey;
end;
clrscr;
until (bet<=bank) and (bet>=0);
end;
Procedure intro(
var bank,save,shopb:integer;
var name:string;
var shop,game:char;
var myfile:text);
begin
repeat
repeat
clrscr;
if (save = 0) then
begin
Write('(L)oad game or (N)ew game? ');
readln(game);
game:=upcase(game);
if (game = 'N') then
begin
write('Enter your name ');
readln(name);
insert('.txt',name,100);
assign(myfile, name);
end
else if (game = 'L') then
begin
writeln('Enter your name the exact way you did when you made this account');
readln(name);
insert('.txt',name,100);
assign(myfile, name);
reset(myfile);
readln(myfile, bank);
writeln('You have ',bank,' dollars in this save file');
closefile(myfile);
end
end;
until (game = 'L') or (game = 'N');
save:=1;
Write('Do you want to go to the shop? (Y/N) ');
readln(shop);
shop:=upcase(shop);
clrscr;
until (shop = 'Y') or (shop = 'N');
if (shop ='Y') then
begin
writeln('What do you want to buy?');
writeln('(1)Blue Background text color $500');
writeln('(2)Red text color $1000');
writeln('(3)Red Background text color $500');
writeln('(4)Yellow Background text color $500');
writeln('(5)Yellow text color $1000');
writeln('(6)Exit');
readln(shopb);
if (shopB = 1) and (bank >= 500) then
begin
TextBackground(Blue);
bank:=bank-500;
end
else if (shopB = 2) and (bank >= 1000) then
begin
Textcolor(lightred);
bank:=bank-1000;
end
else if (shopB = 3) and (bank >= 500) then
begin
TextBackground(Red);
bank:=bank-500;
end
else if (shopB = 4) and (bank >= 500) then
begin
TextBackground(Yellow);
bank:=bank-500;
end
else if (shopB = 5) and (bank >= 1000) then
begin
Textcolor(Yellow);
bank:=bank-1000;
end;
end;
end;
var
Bank,save, Bet, roll1, roll2,ShopB:integer;
choice,quit,shop,game:char;
name:string;
myfile:text;
begin {main}
Bank:=100;
repeat
Bet:=0;
randomize;
Intro(bank,shopb,save,name,game,shop,myfile);
clrscr;
Placebet(bet,bank);
RollDice(Roll1);
writeln('You rolled a ',Roll1);
GuessHL(choice);
RollDice(Roll2);
writeln('You rolled a ',Roll2);
Decide(Roll1,Roll2,Bet,Bank,Choice);
repeat
write('Do you want to cash out? (Y/N) ' );
readln(quit);
clrscr;
quit:=upcase(quit);
until (quit = 'Y') or (quit = 'N');
until (quit = 'Y') or (bank<=0);
if (bank<=0) and (quit = 'Y') then
begin
Writeln('You cashed out with zero dollars');
readkey;
end
else if (bank<=0) then
begin
writeln('You ran out of money');
readkey;
end;
begin
rewrite(myfile);
writeln(myfile, bank);
close(myfile);
writeln('You cashed out with ',bank,' dollars');
readkey;
writeln('This application was made by Jordan Millett');
readkey;
end;
end. {main}
|
{******************************************************************************}
{ }
{ Delphi OPENSSL Library }
{ Copyright (c) 2021 Lsuper }
{ https://github.com/delphilite/DelphiOpenSSL }
{ }
{******************************************************************************}
{ }
{ 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 OpenSSL.DSAUtils;
// https://www.openssl.org/docs/man1.1.1/man3/DSA_sign.html
// https://www.openssl.org/docs/man1.1.1/man3/DSA_verify.html
interface
uses
System.SysUtils, System.Classes, OpenSSL.Core, OpenSSL.Api_11;
type
// DSA base key
TDSAKey = class(TOpenSSLBase)
private
FBuffer: TBytes;
FDSA: PDSA;
private
function GetDSA: PDSA;
procedure FreeDSA;
public
constructor Create; override;
destructor Destroy; override;
function IsValid: Boolean;
function Print: string;
procedure LoadFromBuffer(const AData: TBytes); virtual; abstract;
procedure LoadFromFile(const FileName: string);
procedure LoadFromStream(AStream: TStream);
end;
// DSA public key
TDSAPublicKey = class(TDSAKey)
public
procedure LoadFromBuffer(const AData: TBytes); override;
end;
// DSA private key
TDSAPrivateKey = class(TDSAKey)
public
procedure LoadFromBuffer(const AData: TBytes); override;
end;
// DSA sign/verify
TDSAUtil = class(TOpenSSLBase)
private
FPublicKey: TDSAPublicKey;
FPrivateKey: TDSAPrivateKey;
public
constructor Create; override;
destructor Destroy; override;
function PublicVerify(const Input, Output: TBytes): Boolean; overload;
function PrivateSign(const Input: TBytes): TBytes; overload;
function PublicVerify(InputStream: TStream; OutputStream: TStream): Boolean; overload;
procedure PrivateSign(InputStream: TStream; OutputStream: TStream); overload;
function PublicVerify(const InputFileName, OutputFileName: TFileName): Boolean; overload;
procedure PrivateSign(const InputFileName, OutputFileName: TFileName); overload;
property PublicKey: TDSAPublicKey read FPublicKey;
property PrivateKey: TDSAPrivateKey read FPrivateKey;
end;
implementation
{ TDSAUtil }
constructor TDSAUtil.Create;
begin
inherited;
FPublicKey := TDSAPublicKey.Create;
FPrivateKey := TDSAPrivateKey.Create;
end;
destructor TDSAUtil.Destroy;
begin
FPublicKey.Free;
FPrivateKey.Free;
inherited;
end;
function TDSAUtil.PrivateSign(const Input: TBytes): TBytes;
var
Output: TBytes;
OutLen, Ret: Integer;
begin
if not PrivateKey.IsValid then
raise Exception.Create('Private key not assigned');
if (Input = nil) or (Length(Input) = 0) then
begin
Result := nil;
Exit;
end;
OutLen := 1024; { DSA_size(FPrivateKey.GetDSA) }
SetLength(Output, OutLen);
Ret := DSA_sign(0, PByte(Input), Length(Input), PByte(Output), @OutLen, FPrivateKey.GetDSA);
if Ret <> 1 then
RaiseOpenSSLError('DSA sign error');
if OutLen <= 0 then
RaiseOpenSSLError('DSA operation error');
Result := Copy(Output, 0, OutLen);
end;
procedure TDSAUtil.PrivateSign(const InputFileName, OutputFileName: TFileName);
var
InputFile, OutputFile: TStream;
begin
InputFile := TFileStream.Create(InputFileName, fmOpenRead or fmShareDenyWrite);
try
OutputFile := TFileStream.Create(OutputFileName, fmCreate);
try
Self.PrivateSign(InputFile, OutputFile);
finally
OutputFile.Free;
end;
finally
InputFile.Free;
end;
end;
procedure TDSAUtil.PrivateSign(InputStream, OutputStream: TStream);
var
InputBuffer: TBytes;
OutputBuffer: TBytes;
Ret, DSAOutLen: Integer;
begin
if not PrivateKey.IsValid then
raise Exception.Create('Private key not assigned');
SetLength(InputBuffer, InputStream.Size);
InputStream.ReadBuffer(InputBuffer[0], InputStream.Size);
DSAOutLen := 1024; { DSA_size(FPrivateKey.GetDSA) }
SetLength(OutputBuffer, DSAOutLen);
Ret := DSA_sign(0, PByte(InputBuffer), Length(InputBuffer), PByte(OutputBuffer), @DSAOutLen, FPrivateKey.GetDSA);
if Ret <> 1 then
RaiseOpenSSLError('DSA sign error');
SetLength(OutputBuffer, DSAOutLen);
if DSAOutLen <= 0 then
RaiseOpenSSLError('DSA operation error');
OutputStream.Write(OutputBuffer[0], DSAOutLen);
end;
function TDSAUtil.PublicVerify(const Input, Output: TBytes): Boolean;
var
Ret: Integer;
begin
if not PublicKey.IsValid then
raise Exception.Create('Public key not assigned');
if (Input = nil) or (Length(Input) = 0) then
begin
Result := Length(Output) = 0;
Exit;
end;
Ret := DSA_verify(0, PByte(Input), Length(Input), PByte(Output), Length(Output), FPublicKey.GetDSA);
Result := Ret = 1;
if Ret <= 0 then
RaiseOpenSSLError('DSA operation error');
end;
function TDSAUtil.PublicVerify(const InputFileName, OutputFileName: TFileName): Boolean;
var
InputFile, OutputFile: TStream;
begin
InputFile := TFileStream.Create(InputFileName, fmOpenRead or fmShareDenyWrite);
try
OutputFile := TFileStream.Create(OutputFileName, fmOpenRead or fmShareDenyWrite);
try
Result := Self.PublicVerify(InputFile, OutputFile);
finally
OutputFile.Free;
end;
finally
InputFile.Free;
end;
end;
function TDSAUtil.PublicVerify(InputStream, OutputStream: TStream): Boolean;
var
InputBuffer: TBytes;
OutputBuffer: TBytes;
Ret: Integer;
begin
if not PublicKey.IsValid then
raise Exception.Create('Public key not assigned');
SetLength(InputBuffer, InputStream.Size);
InputStream.ReadBuffer(InputBuffer[0], InputStream.Size);
SetLength(OutputBuffer, OutputStream.Size);
OutputStream.ReadBuffer(OutputBuffer[0], OutputStream.Size);
Ret := DSA_verify(0, PByte(InputBuffer), Length(InputBuffer), PByte(OutputBuffer), Length(OutputBuffer), FPublicKey.GetDSA);
Result := Ret = 1;
if Ret <= 0 then
RaiseOpenSSLError('DSA operation error');
end;
{ TDSAKey }
constructor TDSAKey.Create;
begin
inherited;
FDSA := nil;
end;
destructor TDSAKey.Destroy;
begin
FreeDSA;
inherited;
end;
procedure TDSAKey.FreeDSA;
begin
if FDSA <> nil then
begin
DSA_free(FDSA);
FDSA := nil;
end;
end;
function TDSAKey.GetDSA: PDSA;
begin
Result := FDSA;
end;
function TDSAKey.IsValid: Boolean;
begin
Result := GetDSA <> nil;
end;
procedure TDSAKey.LoadFromFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Self.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TDSAKey.LoadFromStream(AStream: TStream);
var
B: TBytes;
begin
SetLength(B, AStream.Size);
AStream.ReadBuffer(Pointer(B)^, AStream.Size);
Self.LoadFromBuffer(B);
end;
function TDSAKey.Print: string;
var
bp: PBIO;
begin
bp := BIO_new(BIO_s_mem());
try
if DSA_print(bp, FDSA, 0) = 0 then
RaiseOpenSSLError('DSA_print');
Result := BIO_to_string(bp);
finally
BIO_free(bp);
end;
end;
{ TDSAPrivateKey }
procedure TDSAPrivateKey.LoadFromBuffer(const AData: TBytes);
var
KeyBuffer: pBIO;
begin
FBuffer := AData;
KeyBuffer := BIO_new_mem_buf(FBuffer, Length(FBuffer));
if KeyBuffer = nil then
RaiseOpenSSLError('DSA load stream error');
try
FDSA := PEM_read_bio_DSAPrivateKey(KeyBuffer, nil, nil, nil);
if not Assigned(FDSA) then
RaiseOpenSSLError('DSA load private key error');
finally
BIO_free(KeyBuffer);
end;
end;
{ TDSAPublicKey }
procedure TDSAPublicKey.LoadFromBuffer(const AData: TBytes);
var
KeyBuffer: pBIO;
begin
FBuffer := AData;
KeyBuffer := BIO_new_mem_buf(FBuffer, Length(FBuffer));
if KeyBuffer = nil then
RaiseOpenSSLError('DSA load stream error');
try
FDSA := PEM_read_bio_DSA_PUBKEY(KeyBuffer, nil, nil, nil);
if not Assigned(FDSA) then
RaiseOpenSSLError('DSA load public key error');
finally
BIO_free(KeyBuffer);
end;
end;
end.
|
unit Action;
interface
uses Windows, Messages, SysUtils, Classes, IBQuery, IBSQL,
IBDatabase, Db, IBStoredProc, Dbun, Variants;
type
TObjectAction = class(TDbunObject)
private
FActionName: string;
FActionFullName: string;
FActionID: Integer;
FNewInObject: Boolean;
public
property NewInObject: Boolean read FNewInObject write FNewInObject;
property ActionName: string read FActionName write FActionName;
property ActionFullName: string read FActionFullName write FActionFullName;
property ActionID: Integer read FActionID write FActionID;
function FillDataBy(KeyValue: Variant): Boolean; override;
function FillDataByName(KeyValue: string): Boolean;
function Insert: Boolean; override;
function Update: Boolean; override;
function Delete: Boolean; override;
procedure NewAction(Name, FullName: string; ID: Integer = -1);
function IsInObject(ObjectID: Integer): Boolean;
function DeleteFromObject(ObjectID: Integer): Boolean;
function InsertActionInObject(ObjectID: Integer): Boolean;
function AddPermission(ObjectID, RoleID: Integer): Boolean;
constructor Create(AOwner: TComponent; AConnection: TIBDatabase; Query: TIBQuery = nil); override;
end;
implementation
{ TObjectAction }
constructor TObjectAction.Create(AOwner: TComponent; AConnection: TIBDatabase; Query: TIBQuery = nil);
begin
inherited;
FActionID := -1;
FNewInObject := false;
FActionName := '';
FActionFullName := '';
end;
function TObjectAction.Insert: Boolean;
var
stprInsAction: TIBStoredProc;
begin
Result := false;
stprInsAction := TIBStoredProc.Create(nil);
stprInsAction.Database := FConnection;
stprInsAction.Transaction := FInputTransaction;
stprInsAction.StoredProcName := 'INSERT_ACTION';
StartInputTransaction;
try
stprInsAction.Prepare;
stprInsAction.ParamByName('pname').AsString := FActionName;
stprInsAction.ParamByName('pfull_name').AsString := FActionFullName;
stprInsAction.ExecProc;
CommitInputTransaction;
except
on Exception do
begin
RollbackInputTransaction;
Exit;
end;
end;
FActionID := stprInsAction.ParamByName('pid_action').AsInteger;
stprInsAction.Free;
Result := true;
end;
function TObjectAction.Update: Boolean;
var
sqlUpdAction: TIBSQL;
sql: string;
begin
Result := false;
sqlUpdAction := TIBSQL.Create(nil);
sqlUpdAction.Database := FConnection;
sqlUpdAction.Transaction := FInputTransaction;
sql := 'update actions set ' +
'name = ''' + FActionName + ''', ' +
'full_name = ''' + FActionFullName + ''' ' +
'where id_action = ' + IntToStr(FActionID);
sqlUpdAction.SQL.Text := sql;
StartInputTransaction;
try
sqlUpdAction.ExecQuery;
CommitInputTransaction;
except
on Exception do
begin
RollbackInputTransaction;
Exit;
end;
end;
sqlUpdAction.Free;
Result := true;
end;
function TObjectAction.FillDataBy(KeyValue: Variant): Boolean;
var
sql: string;
queryRes: TIBQuery;
begin
Result := false;
if not Assigned(FDataQuery) then
begin
FDataQuery := TIBQuery.Create(nil);
FDataQuery.Transaction := FConnection.DefaultTransaction;
sql := 'select *';
sql := sql + ' from actions';
sql := sql + ' where actions.id_action = ' + VarToStr(KeyValue);
FDataQuery.SQL.Text := sql;
try
FDataQuery.Open;
except
on Exception do
begin
// !
Exit;
end;
end;
queryRes := FDataQuery;
end else begin
queryRes := FDataQuery;
FDataQuery := nil;
end;
if queryRes.RecordCount <= 0 then
begin
if Assigned(FDataQuery) then
begin
FDataQuery.Free;
FDataQuery := nil;
end;
Exit;
end;
FActionID := KeyValue;
FActionName := queryRes.FieldByName('name').AsString;
FActionFullName := queryRes.FieldByName('full_name').AsString;
// Если отбор был самостоятельный
if Assigned(FDataQuery) then
begin
FDataQuery.Free;
FDataQuery := nil;
end;
Result := true;
end;
procedure TObjectAction.NewAction(Name, FullName: string; ID: Integer = -1);
begin
FActionID := ID;
FActionName := Name;
FActionFullName := FullName;
end;
function TObjectAction.InsertActionInObject(ObjectID: Integer): Boolean;
var
sqlInsActionInObj: TIBSQL;
sql: string;
begin
Result := false;
sqlInsActionInObj := TIBSQL.Create(nil);
sqlInsActionInObj.Database := FConnection;
sqlInsActionInObj.Transaction := FInputTransaction;
sql := 'insert into objects_actions (id_object, id_action) values (' +
IntToStr(ObjectID) + ', ' + IntToStr(FActionID) + ')';
sqlInsActionInObj.SQL.Text := sql;
StartInputTransaction;
try
sqlInsActionInObj.ExecQuery;
CommitInputTransaction;
except
on Exception do
begin
RollbackInputTransaction;
Exit;
end;
end;
sqlInsActionInObj.Free;
Result := true;
end;
function TObjectAction.IsInObject(ObjectID: Integer): Boolean;
var
queryInObj: TIBQuery;
sql: string;
begin
Result := false;
queryInObj := TIBQuery.Create(nil);
queryInObj.Database := FConnection;
queryInObj.Transaction := FConnection.DefaultTransaction;
sql := 'select * from objects_actions where id_object = ' + IntToStr(ObjectID) +
' and id_action = ' + IntToStr(FActionID);
queryInObj.SQL.Text := sql;
try
queryInObj.Open;
except
on Exception do
begin
//!
Exit;
end;
end;
if queryInObj.RecordCount > 0 then Result := true;
queryInObj.Free;
end;
function TObjectAction.DeleteFromObject(ObjectID: Integer): Boolean;
var
sqlDelActionFromObj: TIBSQL;
sql: string;
begin
Result := false;
sqlDelActionFromObj := TIBSQL.Create(nil);
sqlDelActionFromObj.Database := FConnection;
sqlDelActionFromObj.Transaction := FInputTransaction;
sql := 'delete from objects_actions where id_object = ' + IntToStr(ObjectID) +
' and id_action = ' + IntToStr(FActionID);
sqlDelActionFromObj.SQL.Text := sql;
StartInputTransaction;
try
// Удаляем действие из объекта
sqlDelActionFromObj.ExecQuery;
// Удаляем права для данного объекта и действия
sql := 'delete from permissions where id_object = ' + IntToStr(ObjectID) +
' and id_action = ' + IntToStr(FActionID);
sqlDelActionFromObj.SQL.Text := sql;
sqlDelActionFromObj.ExecQuery;
CommitInputTransaction;
except
on Exception do
begin
RollbackInputTransaction;
Exit;
end;
end;
sqlDelActionFromObj.Free;
Result := true;
end;
function TObjectAction.AddPermission(ObjectID, RoleID: Integer): Boolean;
var
sqlInsPermission: TIBSQL;
sql: string;
begin
Result := false;
sqlInsPermission := TIBSQL.Create(nil);
sqlInsPermission.Database := FConnection;
sqlInsPermission.Transaction := FInputTransaction;
sql := 'insert into permissions (id_role, id_object, id_action) values (' +
IntToStr(RoleID) + ', ' + IntToStr(ObjectID) + ', ' + IntToStr(FActionID) + ')';
sqlInsPermission.SQL.Text := sql;
StartInputTransaction;
try
sqlInsPermission.ExecQuery;
CommitInputTransaction;
except
on Exception do
begin
RollbackInputTransaction;
Exit;
end;
end;
sqlInsPermission.Free;
Result := true;
end;
function TObjectAction.Delete: Boolean;
begin
Result := false;
end;
function TObjectAction.FillDataByName(KeyValue: string): Boolean;
var
sql: string;
queryRes: TIBQuery;
begin
Result := false;
if not Assigned(FDataQuery) then
begin
FDataQuery := TIBQuery.Create(nil);
FDataQuery.Transaction := FConnection.DefaultTransaction;
sql := 'select *';
sql := sql + ' from actions';
sql := sql + ' where actions.name = ''' + Trim(KeyValue) + '''';
FDataQuery.SQL.Text := sql;
try
FDataQuery.Open;
except
on Exception do
begin
// !
Exit;
end;
end;
queryRes := FDataQuery;
end else begin
queryRes := FDataQuery;
FDataQuery := nil;
end;
if queryRes.RecordCount <= 0 then
begin
if Assigned(FDataQuery) then
begin
FDataQuery.Free;
FDataQuery := nil;
end;
Exit;
end;
FActionID := queryRes.FieldByName('id_action').AsInteger;
FActionName := queryRes.FieldByName('name').AsString;
FActionFullName := queryRes.FieldByName('full_name').AsString;
// Если отбор был самостоятельный
if Assigned(FDataQuery) then
begin
FDataQuery.Free;
FDataQuery := nil;
end;
Result := true;
end;
end.
|
unit sgDriverTextSDL2;
interface
procedure LoadSDL2TextDriver();
implementation
uses sgTypes, sgDriverSDL2Types, sgDriverText, sgShared, sgBackendTypes;
function LoadFontProcedure(const fontName, fileName : String; size : Longint) : FontPtr;
var
fdata: psg_font_data;
begin
New(result);
result^.id := FONT_PTR;
New(fdata);
if (result = nil) or (fdata = nil) then
begin
RaiseException('LoadFont to allocate space.');
exit;
end;
fdata^ := _sg_functions^.text.load_font(PChar(fileName), size);
result^.fptr := fdata;
if result^.fptr = nil then
begin
Dispose(result);
result := nil;
RaiseWarning('LoadFont failed: ' + fontName + ' (' + fileName + ')');
exit;
end;
result^.name := fontName;
end;
procedure CloseFontProcedure(fontToClose : FontPtr);
var
fdata: psg_font_data;
begin
fdata := fontToClose^.fptr;
_sg_functions^.text.close_font(fdata);
Dispose(fdata);
fontToClose^.fptr := nil;
end;
//TODO: move most of this to sgText
procedure PrintStringsProcedure(dest: Bitmap; font: FontPtr; const str: String; rc: Rectangle; clrFg, clrBg:Color; flags:FontAlignment);
var
clr: sg_color;
pts: array [0..4] of Single;
begin
clr := _ToSGColor(clrBg);
if clr.a > 0 then
begin
pts[0] := rc.x;
pts[1] := rc.y;
pts[2] := rc.width;
pts[3] := rc.height;
_sg_functions^.graphics.fill_aabb_rect(ToSurfacePtr(dest), clr, @pts[0], 4);
end;
_sg_functions^.text.draw_text(ToSurfacePtr(dest), font^.fptr, rc.x, rc.y, PChar(str), _ToSGColor(clrFg));
end;
procedure PrintWideStringsProcedure(dest: Bitmap; font: FontPtr; str: WideString; rc: Rectangle; clrFg, clrBg:Color; flags:FontAlignment) ;
begin
WriteLn('PrintWideStringsProcedure!!!');
end;
procedure SetFontStyleProcedure(fontToSet : FontPtr; value : FontStyle);
begin
_sg_functions^.text.set_font_style(fontToSet^.fptr, Longint(value));
end;
function GetFontStyleProcedure(font : FontPtr) : FontStyle;
begin
result := FontStyle(_sg_functions^.text.get_font_style(font^.fptr));
end;
function SizeOfTextProcedure(font : FontPtr ;const theText : String; var w : Longint ; var h : Longint) : Integer;
begin
result := _sg_functions^.text.text_size(font^.fptr, PChar(theText), @w, @h);
end;
function SizeOfUnicodeProcedure(font : FontPtr; theText : WideString; var w : Longint; var h : Longint) : Integer;
begin
result := 0;
end;
procedure QuitProcedure();
begin
//do nothing - now in general quit code
end;
function GetErrorProcedure() : String;
begin
result := 'TODO: ERRORS';
end;
function InitProcedure(): integer;
begin
// do nothing - now in standard startup
result := 0;
end;
procedure StringColorProcedure(dest : Bitmap; x,y : Single; const theText : String; theColor : Color);
begin
_sg_functions^.text.draw_text(ToSurfacePtr(dest), nil, x, y, PChar(theText), _ToSGColor(theColor));
end;
function LineSkipFunction(fnt: FontPtr): Integer;
begin
result := _sg_functions^.text.text_line_skip(fnt^.fptr);
end;
//=============================================================================
procedure LoadSDL2TextDriver();
begin
TextDriver.LoadFont := @LoadFontProcedure;
TextDriver.CloseFont := @CloseFontProcedure;
TextDriver.PrintStrings := @PrintStringsProcedure;
TextDriver.PrintWideStrings := @PrintWideStringsProcedure;
TextDriver.SetFontStyle := @SetFontStyleProcedure;
TextDriver.GetFontStyle := @GetFontStyleProcedure;
TextDriver.SizeOfText := @SizeOfTextProcedure;
TextDriver.SizeOfUnicode := @SizeOfUnicodeProcedure;
TextDriver.Quit := @QuitProcedure;
TextDriver.GetError := @GetErrorProcedure;
TextDriver.Init := @InitProcedure;
TextDriver.StringColor := @StringColorProcedure;
TextDriver.LineSkip := @LineSkipFunction;
end;
end. |
{ *********************************************************************** }
{ }
{ The Siam Developer Runtime Library }
{ DevCore Library }
{ }
{ Copyright (c) 2014 Siam Developer Co.,Ltd. }
{ }
{ *********************************************************************** }
unit DevCoreLIB;
interface
uses
SysUtils,
Forms,
Dialogs,
Classes,
DB,
DBXpress,
FMTBcd,
SqlExpr,
StdCtrls,
DBClient,
Provider,
Windows,jvUIb,IdIPWatch,MyAccess;
type
TShowWindowType = (swNone, swModal, swNomal);
function SAMInitConnection(conn:TSQLConnection):boolean;stdcall;
function SAMGetDataSet(const SQL: string): Variant;stdcall;
function SAMUpdateDataset(dataset:Tclientdataset; SQLText: string): Integer;stdcall;
procedure SAMExecuteSQL(SQL: string);stdcall;
implementation
const
DevCoreDLL = 'DevCore.dll';
function SAMInitConnection(conn:TSQLConnection):boolean; external DevCoreDLL name 'SamInitConnection';
function SAMGetDataSet(const SQL: string): Variant; external DevCoreDLL name 'SamGetDataSet';
function SAMUpdateDataset(dataset:Tclientdataset; SQLText: string): Integer; external DevCoreDLL name 'SamUpdateDataset';
procedure SAMExecuteSQL(SQL: string);external DevCoreDLL name 'SamExecuteSQL';
end.
|
unit rtti_idebinder_uBehavioralBinder;
{$mode objfpc}{$H+}
interface
uses
SysUtils, rtti_idebinder_iBindings, rtti_idebinder_uBehaveBinders,
Controls, ComCtrls, fgl;
type
{ TRBBehavioralBinder }
TRBBehavioralBinder = class(TInterfacedObject, IRBBehavioralBinder)
private type
TBehaveBinderItems = specialize TFPGObjectList<TBehaveBinder>;
private
fBinders: TBehaveBinderItems;
fContainer: TWinControl;
protected
// IRBBehavioralBinder
procedure Bind(AContainer: TWinControl);
protected
procedure ActualizeItems;
procedure MakeBinders(AContainer: TWinControl);
procedure AddBinderForControl(AControl: TWinControl);
public
constructor Create;
destructor Destroy; override;
end;
implementation
{ TRBBehavioralBinder }
procedure TRBBehavioralBinder.Bind(AContainer: TWinControl);
begin
fContainer := AContainer;
ActualizeItems;
end;
procedure TRBBehavioralBinder.ActualizeItems;
begin
fBinders.Clear;
MakeBinders(fContainer);
end;
procedure TRBBehavioralBinder.MakeBinders(AContainer: TWinControl);
var
i: integer;
begin
for i := 0 to AContainer.ControlCount - 1 do
begin
if not (AContainer.Controls[i] is TWinControl) then
Continue;
AddBinderForControl(AContainer.Controls[i] as TWinControl);
end;
end;
procedure TRBBehavioralBinder.AddBinderForControl(AControl: TWinControl);
var
mBinder: TBehaveBinder;
begin
if AControl is TCustomTabControl then begin
mBinder := TPageControlBehaveBinder.Create;
fBinders.Add(mBinder);
mBinder.Bind(AControl);
end;
end;
constructor TRBBehavioralBinder.Create;
begin
fBinders := TBehaveBinderItems.Create;
end;
destructor TRBBehavioralBinder.Destroy;
begin
FreeAndNil(fBinders);
inherited Destroy;
end;
end.
|
unit Class3DPointList;
interface
type
P3DPosition = ^T3DPosition;
T3DPosition = record
x,y,z : integer;
Next : P3DPosition;
end;
C3DPointList = class
private
Start,Last,Active : P3DPosition;
procedure Reset;
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// Add
procedure Add (x,y,z : integer);
procedure Delete;
// Delete
procedure Clear;
// Gets
function GetPosition (var x,y,z : integer): boolean;
function GetX: integer;
function GetY: integer;
function GetZ: integer;
// Misc
procedure GoToNextElement;
end;
implementation
constructor C3DPointList.Create;
begin
Reset;
end;
destructor C3DPointList.Destroy;
begin
Clear;
Reset;
end;
procedure C3DPointList.Reset;
begin
Start := nil;
Last := nil;
Active := nil;
end;
// Add
procedure C3DPointList.Add (x,y,z : integer);
var
NewPosition : P3DPosition;
begin
New(NewPosition);
NewPosition^.x := x;
NewPosition^.y := y;
NewPosition^.z := z;
NewPosition^.Next := nil;
if Start <> nil then
begin
Last^.Next := NewPosition;
end
else
begin
Start := NewPosition;
Active := Start;
end;
Last := NewPosition;
end;
// Delete
procedure C3DPointList.Delete;
var
Previous : P3DPosition;
begin
if Active <> nil then
begin
Previous := Start;
if Active = Start then
begin
Start := Start^.Next;
end
else
begin
while Previous^.Next <> Active do
begin
Previous := Previous^.Next;
end;
Previous^.Next := Active^.Next;
if Active = Last then
begin
Last := Previous;
end;
end;
Dispose(Active);
end;
end;
procedure C3DPointList.Clear;
var
Garbage : P3DPosition;
begin
Active := Start;
while Active <> nil do
begin
Garbage := Active;
Active := Active^.Next;
dispose(Garbage);
end;
end;
// Gets
function C3DPointList.GetPosition (var x,y,z : integer): boolean;
begin
if Active <> nil then
begin
x := Active^.x;
y := Active^.y;
z := Active^.z;
Result := true;
end
else
begin
Result := false;
end;
end;
function C3DPointList.GetX: integer;
begin
if Active <> nil then
begin
Result := Active^.x;
end;
end;
function C3DPointList.GetY: integer;
begin
if Active <> nil then
begin
Result := Active^.y;
end;
end;
function C3DPointList.GetZ: integer;
begin
if Active <> nil then
begin
Result := Active^.z;
end;
end;
// Misc
procedure C3DPointList.GoToNextElement;
begin
if Active <> nil then
begin
Active := Active^.Next;
end
end;
end.
|
(*
@abstract Implements a class thats injects a hidden id into a string.
*)
unit NtHiddenId;
{$I NtVer.inc}
interface
uses
System.Generics.Collections;
const
REQUIRED_ZERO_WIDTH_CHARACTER_COUNT_C = 4;
type
TZeroWidthCharacter =
(
zwSpace, //< 200B
zwNonJoiner, //< 200C
zwJoiner, //< 200D
zwLeftToRightMark, //< 200E
zwLeftToRightEmbedding, //< 202A
zwPopDirectionalFormatting, //< 202C
zwLeftToRightOverwrite, //< 202D
zwWordJoiner, //< 2060
zwInvisibleTimes, //< 2062
zwInvisibleSeparator, //< 2063
zwNoBreakSpace //< FEFF
);
TZeroWidthCharacters = set of TZeroWidthCharacter;
{ @abstract Class that contains one decoded string that is the string id and the string value. }
TDecodedString = record
Id: Integer; //< String id.
Value: String; //< String value.
end;
{ @abstract Class that provided the API methods. }
THiddenId = class
private
FChars: array[0..REQUIRED_ZERO_WIDTH_CHARACTER_COUNT_C - 1] of Char;
FValue: TZeroWidthCharacters;
procedure SetValue(thisValue: TZeroWidthCharacters);
function IsZeroWidthChar(c: Char): Boolean;
function GetZeroWidthIndex(c: Char): Integer;
public
constructor Create;
{ @abstract. Encode an id.
@param value Id to be encoded.
@return Encoded id as a string. }
function Encode(value: Integer): String;
{ @abstract. Decode an encoded id.
@param value Encoded id to be decoded.
@return Decoded id. }
function Decode(value: String): Integer;
{ @abstract. Injects an id into a string.
@param value String where the id will be injected.
@param id Id to be injected.
@return String with injected id. }
function Inject(const value: String; id: Integer): String;
{ @abstract. Parse a string that may contain injected id(s).
@param str String that may contain injected id.
@return Array of decoded strings. }
function Parse(const str: String; list: TList<TDecodedString>): Integer; overload;
{ @abstract. Parse a string that may contain injected id. If the string contains multiple strings return the first one.
@param str String that may contain injected id.
@return First decoded string. }
function Parse(const str: String): TDecodedString; overload;
class function GetCount(value: TZeroWidthCharacters): Integer; static;
class function GetChar(value: TZeroWidthCharacter): Char; static;
class function GetName(value: TZeroWidthCharacter; includeCode: Boolean = False): String; static;
property Value: TZeroWidthCharacters read FValue write SetValue;
end;
const
DEFAULT_ZERO_WIDTH_CHARACTERS_C = [zwNonJoiner, zwJoiner, zwPopDirectionalFormatting, zwLeftToRightOverwrite];
implementation
uses
SysUtils;
const
CHARS: array[TZeroWidthCharacter] of Char =
(
#$200B,
#$200C,
#$200D,
#$200E,
#$202A,
#$202C,
#$202D,
#$2060,
#$2062,
#$2063,
#$FEFF
);
constructor THiddenId.Create;
begin
inherited;
Value := DEFAULT_ZERO_WIDTH_CHARACTERS_C;
end;
procedure THiddenId.SetValue(thisValue: TZeroWidthCharacters);
var
index: Integer;
c: TZeroWidthCharacter;
begin
if GetCount(thisValue) <> REQUIRED_ZERO_WIDTH_CHARACTER_COUNT_C then
thisValue := DEFAULT_ZERO_WIDTH_CHARACTERS_C;
FValue := thisValue;
index := 0;
for c := Low(c) to High(c) do
begin
if c in FValue then
begin
FChars[index] := GetChar(c);
Inc(index);
end;
if index >= 4 then
Break;
end;
end;
function THiddenId.IsZeroWidthChar(c: Char): Boolean;
var
zc: Char;
begin
for zc in FChars do
begin
if c = zc then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
function THiddenId.GetZeroWidthIndex(c: Char): Integer;
var
i: Integer;
begin
for i := 0 to High(FChars) do
begin
if FChars[i] = c then
begin
Result := i;
Exit;
end;
end;
Result := 0;
end;
function THiddenId.Encode(value: Integer): String;
var
digit: Integer;
begin
if value = 0 then
begin
Result := FChars[0] + FChars[0]; //FI:W510
Exit;
end;
Result := '';
while value > 0 do
begin
digit := value mod 16;
if digit < 4 then
Result := FChars[0] + FChars[digit] + Result
else if digit < 8 then
Result := FChars[1] + FChars[digit - 4] + Result
else if digit < 12 then
Result := FChars[2] + FChars[digit - 8] + Result
else
Result := FChars[3] + FChars[digit - 12] + Result;
value := value div 16;
end;
end;
function THiddenId.Decode(value: String): Integer;
var
digit: Integer;
begin
if (value = '') or ((Length(value) mod 2) <> 0) then
begin
Result := -1;
Exit;
end;
Result := 0;
while value <> '' do
begin
digit := GetZeroWidthIndex(value[2]);
if value[1] = FChars[1] then
Inc(digit, 4)
else if value[1] = FChars[2] then
Inc(digit, 8)
else if value[1] = FChars[3] then
Inc(digit, 12);
Result := 16*Result + digit;
Delete(value, 1, 2);
end;
end;
function THiddenId.Inject(const value: String; id: Integer): String;
begin
Result := value + Encode(id);
end;
function THiddenId.Parse(const str: String; list: TList<TDecodedString>): Integer;
var
id, thisValue: String;
procedure Add;
var
decodedString: TDecodedString;
begin
decodedString.Value := thisValue;
decodedString.Id := Decode(id);
list.Add(decodedString);
Inc(Result);
id := '';
thisValue := '';
end;
var
i, len: Integer;
c: Char;
begin
Result := 0;
id := '';
thisValue := '';
len := Length(str);
i := 1;
while i <= len do
begin
c := str[i];
if IsZeroWidthChar(c) then
id := id + c
else
begin
if id <> '' then
Add;
thisValue := thisValue + c;
end;
Inc(i);
end;
if thisValue <> '' then
Add;
end;
function THiddenId.Parse(const str: String): TDecodedString;
var
list: TList<TDecodedString>;
begin
list := TList<TDecodedString>.Create;
try
if Parse(str, list) > 0 then
Result := list[0]
else
begin
Result.Value := str;
Result.Id := 0;
end;
finally
list.Free;
end;
end;
class function THiddenId.GetCount(value: TZeroWidthCharacters): Integer;
var
c: TZeroWidthCharacter;
begin
Result := 0;
for c := Low(c) to High(c) do
if c in value then
Inc(Result);
end;
class function THiddenId.GetChar(value: TZeroWidthCharacter): Char;
begin
Result := CHARS[value];
end;
class function THiddenId.GetName(value: TZeroWidthCharacter; includeCode: Boolean): String;
resourcestring
SZeroWidthSpace = 'Zero width space';
SZeroWidthNonJoiner = 'Zero width non joiner';
SZeroWidthJoiner = 'Zero width joiner';
SLeftToRightMark = 'Left to right mark';
SLeftToRightEmbedding = 'Left to right embedding';
SPopDirectionalFormatting = 'Pop directional formatting';
SLeftToRightOverwrite = 'Left to right overwrite';
SWordJoiner = 'Word joiner';
SInvisibleTimes = 'Invisible times';
SInvisibleSeparator = 'Invisible separator';
SNoBreakSpace = 'Zero width no-break space';
var
code: Integer;
begin
case value of
zwSpace: Result := SZeroWidthSpace;
zwNonJoiner: Result := SZeroWidthNonJoiner;
zwJoiner: Result := SZeroWidthJoiner;
zwLeftToRightMark: Result := SLeftToRightMark;
zwLeftToRightEmbedding: Result := SLeftToRightEmbedding;
zwPopDirectionalFormatting: Result := SPopDirectionalFormatting;
zwLeftToRightOverwrite: Result := SLeftToRightOverwrite;
zwWordJoiner: Result := SWordJoiner;
zwInvisibleTimes: Result := SInvisibleTimes;
zwInvisibleSeparator: Result := SInvisibleSeparator;
zwNoBreakSpace: Result := SNoBreakSpace;
else
raise Exception.Create('Not implemented');
end;
if includeCode then
begin
code := Integer(GetChar(value));
Result := Format('%s (0x%s, %s)', [Result, IntToHex(code, 4), IntToStr(code)]);
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.Cache;
interface
uses
VSoft.Awaitable,
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Package.Interfaces,
DPM.Core.Cache.Interfaces,
DPM.Core.Spec.Interfaces;
type
TPackageCache = class(TInterfacedObject, IPackageCache)
private
FLogger : ILogger;
FSpecReader : IPackageSpecReader;
FLocation : string;
protected
procedure SetLocation(const value : string);
function GetLocation : string;
function GetPackagesFolder : string;
function CachePackage(const packageId : IPackageId; const saveFile : Boolean) : Boolean;
function Clean : Boolean;
function CreatePackagePath(const packageId : IPackageId) : string;
function GetPackagePath(const packageId : IPackageId) : string; overload;
function GetPackagePath(const id : string; const version : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : string;overload;
function EnsurePackage(const packageId : IPackageId) : Boolean;
function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
function GetPackageMetadata(const packageId : IPackageId) : IPackageMetadata;
function GetPackageSpec(const packageId : IPackageId) : IPackageSpec;
// function InstallPackage(const packageId : IPackageId; const saveFile : boolean; const source : string = '') : boolean;
function InstallPackageFromFile(const packageFileName : string; const saveFile : boolean) : boolean;
public
constructor Create(const logger : ILogger; const specReader : IPackageSpecReader);
end;
implementation
uses
System.SysUtils,
System.IOUtils,
System.Zip,
System.RegularExpressions,
DPM.Core.Constants,
DPM.Core.Package.Metadata,
DPM.Core.Utils.Strings;
{ TPackageCache }
function TPackageCache.CachePackage(const packageId : IPackageId; const saveFile : Boolean) : Boolean;
begin
result := false;
end;
function TPackageCache.Clean : Boolean;
begin
result := false;
end;
constructor TPackageCache.Create(const logger : ILogger; const specReader : IPackageSpecReader);
begin
FLogger := logger;
FSpecReader := specReader;
end;
function TPackageCache.CreatePackagePath(const packageId : IPackageId) : string;
begin
result := GetPackagePath(packageId);
if not ForceDirectories(result) then
begin
FLogger.Error('Error creating package folder [' + result + ']');
exit;
end;
end;
function TPackageCache.GetLocation : string;
begin
result := FLocation;
end;
function TPackageCache.GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
var
packageFolder : string;
metaDataFile : string;
spec : IPackageSpec;
begin
result := nil;
packageFolder := GetPackagePath(packageId);
if not DirectoryExists(packageFolder) then
exit;
metaDataFile := IncludeTrailingPathDelimiter(packageFolder) + cPackageMetaFile;
if not FileExists(metaDataFile) then
begin
FLogger.Debug('Package metadata file [' + metaDataFile + '] not found in cache.');
exit;
end;
spec := FSpecReader.ReadSpec(metaDataFile);
if spec = nil then
exit;
Result := TPackageInfo.CreateFromSpec('', spec);
end;
function TPackageCache.GetPackageMetadata(const packageId : IPackageId) : IPackageMetadata;
var
spec : IPackageSpec;
begin
spec := GetPackageSpec(packageId);
if spec = nil then
exit;
Result := TPackageMetadata.CreateFromSpec('', spec);
end;
function TPackageCache.GetPackagePath(const id: string; const version: string; const compilerVersion : TCompilerVersion;const platform: TDPMPlatform): string;
begin
result := GetPackagesFolder + PathDelim + CompilerToString(compilerVersion) + PathDelim + DPMPlatformToString(platform) + PathDelim + Id + PathDelim + Version;
end;
function TPackageCache.GetPackagePath(const packageId : IPackageId) : string;
begin
result := GetPackagesFolder + PathDelim + CompilerToString(packageId.CompilerVersion) + PathDelim + DPMPlatformToString(packageId.platform) + PathDelim + packageId.Id + PathDelim + packageId.Version.ToStringNoMeta;
end;
function TPackageCache.GetPackagesFolder : string;
begin
// result := IncludeTrailingPathDelimiter(FLocation);
result := TPath.GetFullPath(FLocation)
end;
function TPackageCache.GetPackageSpec(const packageId: IPackageId): IPackageSpec;
var
packageFolder : string;
metaDataFile : string;
begin
result := nil;
if not EnsurePackage(packageId) then
begin
FLogger.Error('Package metadata file [' + packageId.ToString + '] not found in cache.');
exit;
end;
packageFolder := GetPackagePath(packageId);
if not DirectoryExists(packageFolder) then
exit;
metaDataFile := IncludeTrailingPathDelimiter(packageFolder) + cPackageMetaFile;
if not FileExists(metaDataFile) then
begin
FLogger.Debug('Package metadata file [' + metaDataFile + '] not found in cache.');
exit;
end;
result := FSpecReader.ReadSpec(metaDataFile);
end;
function TPackageCache.EnsurePackage(const packageId : IPackageId) : Boolean;
var
packageFileName : string;
packagesFolder : string;
begin
//check if we have a package folder and manifest.
packageFileName := GetPackagePath(packageId);
result := DirectoryExists(packageFileName) and FileExists(IncludeTrailingPathDelimiter(packageFileName) + cPackageMetaFile);
if not result then
begin
packagesFolder := GetPackagesFolder;
//ok, if we still have the file, try install it again.
packageFileName := IncludeTrailingPathDelimiter(packagesFolder) + packageId.ToString + cPackageFileExt;
if FileExists(packageFileName) then
result := InstallPackageFromFile(packageFileName, true)
end;
end;
function TPackageCache.InstallPackageFromFile(const packageFileName : string; const saveFile : boolean) : boolean;
var
packageFilePath : string;
fileName : string;
packageIndentity : IPackageIdentity;
packageFolder : string;
begin
result := false;
// FLogger.Debug('[PackageCache] installing from file : ' + packageFileName);
if not FileExists(packageFileName) then
begin
FLogger.Error('Package File [' + packageFileName + '] does not exist');
exit;
end;
if ExtractFileExt(packageFileName) <> '.dpkg' then
begin
FLogger.Error('Package File [' + packageFileName + '] is not a valid package file.');
exit;
end;
fileName := ChangeFileExt(ExtractFileName(packageFileName), '');
//if savefile, copy to cache folder.
if not TPackageIdentity.TryCreateFromString(FLogger, fileName, '', packageIndentity) then
exit;
//creates the folder
packageFolder := CreatePackagePath(packageIndentity);
if saveFile then
begin
if (not TStringUtils.StartsWith(packageFileName, GetPackagesFolder)) then
begin
packageFilePath := GetPackagesFolder + PathDelim + ExtractFileName(packageFileName);
try
TFile.Copy(packageFileName, packageFilePath, true);
except
on e : Exception do
begin
FLogger.Error('Unable to copy file [' + packageFileName + '] to the package cache');
FLogger.Error(e.Message);
exit;
end;
end;
end
else
packageFilePath := packageFileName;
end
else
packageFilePath := packageFileName;
//work with packageFilePath now.
try
TZipFile.ExtractZipFile(packageFilePath, packageFolder);
result := FileExists(IncludeTrailingPathDelimiter(packageFolder) + cPackageMetaFile);
if result then
FLogger.Verbose('Package [' + packageFilePath + '] added to cache.');
//TODO : extract icon and readme
except
on e : exception do
begin
TDirectory.Delete(packageFolder, true); //just empties it but doesn't delete?
if not RemoveDir(packageFolder) then
begin
FLogger.Error('Unable to cleanup directory : ' + packageFolder);
FLogger.Error(SysErrorMessage(GetLastError));
end;
//raising here, if we don't we end up here again!
raise Exception.Create('Unable to extract file [' + packageFilePath + '] into the package cache : ' + e.Message);
end;
end;
end;
procedure TPackageCache.SetLocation(const value : string);
begin
FLocation := value;
end;
end.
|
Program PL0;
{带有代码生成的PL0编译程序}
Const
norw = 11; {保留字的个数}
txmax = 100; {标识符表长度}
nmax = 14; {数字的最大位数}
al = 10; {标识符的长度}
amax = 2047; {最大地址}
levmax = 3; {程序体嵌套的最大深度}
cxmax = 200; {代码数组的大小}
Type
symbol = (nul, ident, number, plus, minus, times, slash, oddsym,
eql, neq, lss, leq, gtr, geq, lparen, rparen, comma, semicolon,
period, becomes, beginsym, endsym, ifsym, thensym,
whilesym, dosym, callsym, constsym, varsym, procsym);
alfa = packed array [1..al] Of char;
objecttype = (constant, variable, procedures);
symset = set Of symbol;
fct = (lit, opr, lod, sto, cal, int, jmp, jpc); {functions}
instruction = packed Record
f : fct; {功能码}
l : 0..levmax; {相对层数}
a : 0..amax; {相对地址}
End;
{LIT 0,a : 取常数a}
{OPR 0,a : 执行运算a}
{LOD l,a : 取层差为l的层﹑相对地址为a的变量}
{STO l,a : 存到层差为l的层﹑相对地址为a的变量}
{CAL l,a : 调用层差为l的过程}
{INT 0,a : t寄存器增加a}
{JMP 0,a : 转移到指令地址a处}
{JPC 0,a : 条件转移到指令地址a处}
Var
ch: char; {最近读到的字符}
sym: symbol; {最近读到的符号}
id: alfa; {最近读到的标识符}
num: integer; {最近读到的数}
cc: integer; {当前行的字符计数}
ll: integer; {当前行的长度}
kk, err: integer;
cx: integer; {代码数组的当前下标}
line: array [1..81] Of char; {当前行}
a: alfa; {当前标识符的字符串}
code: array [0..cxmax] Of instruction; {中间代码数组}
word: array [1..norw] Of alfa; {存放保留字的字符串}
wsym: array [1..norw] Of symbol; {存放保留字的记号}
ssym: array [char] Of symbol; {存放算符和标点符号的记号}
mnemonic: array [fct] Of packed array [1..3] Of char;
{中间代码算符的字符串}
declbegsys, statbegsys, facbegsys: symset;
table: array [0..txmax] Of {符号表}
Record
name: alfa;
Case kind: objecttype Of
constant: (val: integer);
variable, procedures: (level, adr: integer)
End;
fin, fout, foutStack, foutAsm: textfile;
{结束程序处理}
Procedure programExit;
Begin
close(fin);
close(fout);
close(foutStack);
close(foutAsm);
exit;
End; {programExit}
{错误处理}
Procedure error(n: integer);
Begin
writeln(fout, '*****', ' ':cc-1, '^', n:2);
err := err + 1
{cc为当前行已读的字符数, n为错误号, 错误数err加1}
End; {error}
{词法分析}
Procedure getsym;
Var i, j, k: integer;
{获取下一个字符}
Procedure getch;
Begin
If cc = ll Then {如果cc指向行末}
Begin
If eof(fin) Then
Begin
writeln('Program Incomplete');
programExit;
End;
{读新的一行}
ll := 0;
cc := 0;
write(fout, cx:5, ' ');
While Not eoln(fin) Do
Begin
ll := ll + 1;
read(fin, ch);
write(fout, ch);
line[ll] := ch;
End;
writeln(fout);
ll := ll + 1;
readln(fin, line[ll]); {line[ll]中是行末符}
End;
cc := cc + 1;
ch := line[cc] {ch取line中下一个字符}
End; {getch}
Begin {getsym}
While (ch = ' ') Or (ord(ch) = 10) Or (ord(ch) = 13) Do
getch; {跳过无用空白}
If ch In ['A'..'Z', 'a'..'z'] Then
Begin {标识符或保留字}
k := 0;
Repeat
If k < al Then
Begin
k := k + 1;
a[k] := ch
End;
getch
Until Not (ch In ['A'..'Z', 'a'..'z', '0'..'9']);
If k >= kk Then kk := k
Else
Repeat {如果标识符长度不是最大长度, 后面补空白}
a[kk] := ' ';
kk := kk - 1
Until kk = k;
id := a; {id中存放当前标识符或保留字的字符串}
i := 1;
j := norw;
Repeat {用二分查找法在保留字表中找当前的标识符id}
k := (i + j) Div 2;
If id <= word[k] Then j := k - 1;
If id >= word[k] Then i := k + 1
Until i > j;
{如果找到, 当前记号sym为保留字, 否则sym为标识符}
If i - 1 > j Then sym := wsym[k]
Else sym := ident
End
Else If ch In ['0'..'9'] Then
Begin {数字}
k := 0;
num := 0;
sym := number; {当前记号sym为数字}
Repeat {计算数字串的值}
num := 10 * num + (ord(ch) - ord('0'));
k := k + 1;
getch;
Until Not (ch In ['0'..'9']);
If k > nmax Then error(30)
{当前数字串的长度超过上界,则报告错误}
End
Else If ch = ':' Then {处理赋值号}
Begin
getch;
If ch = '=' Then
Begin
sym := becomes;
getch;
End
Else sym := nul;
End
Else If ch = '<' Then {处理不等号、小于号、小于等于号}
Begin
getch;
If ch = '=' Then
Begin
sym := leq;
getch;
End
Else If ch = '>' Then
Begin
sym := neq;
getch;
End
Else sym := lss;
End
Else If ch = '>' Then {处理大于号、大于等于号}
Begin
getch;
If ch = '=' Then
Begin
sym := geq;
getch;
End
Else sym := gtr;
End
Else {处理其它算符或标点符号}
Begin
sym := ssym[ch];
getch;
End
End; {getsym}
{生成汇编}
Procedure gen(x: fct; y, z: integer);
Begin
If cx > cxmax Then {如果当前指令序号>代码的最大长度}
Begin
writeln('Program Too Long');
programExit;
End;
With code[cx] Do {在代码数组cx位置生成一条新代码}
Begin
f := x; {功能码}
l := y; {层号}
a := z {地址}
End;
cx := cx + 1;
End; {gen}
Procedure test(s1, s2: symset; n: integer);
Begin
If Not (sym In s1) Then
{如果当前记号不属于集合S1,则报告错误n}
Begin
error(n);
s1 := s1 + s2;
While Not (sym In s1) Do getsym;
{跳过一些记号, 直到当前记号属于S1∪S2}
End
End; {test}
Procedure block(lev, tx: integer; fsys: symset);
Var
dx: integer; {本过程数据空间分配下标}
tx0: integer; {本过程标识表起始下标}
cx0: integer; {本过程代码起始下标}
Procedure enter(k: objecttype);
Begin {把object填入符号表中}
tx := tx + 1; {符号表指针加1}
With table[tx] Do {在符号表中增加新的一个条目}
Begin
name := id; {当前标识符的名字}
kind := k; {当前标识符的种类}
Case k Of
constant:
Begin {当前标识符是常数名}
If num > amax Then
Begin
error(30);
num := 0
End;
val := num;
End;
variable:
Begin {当前标识符是变量名}
level := lev;
adr := dx;
dx := dx +1;
End;
procedures: level := lev {本过程的嵌套层数}
End
End
End; {enter}
Function position(id: alfa) : integer; {返回id在符号表的入口}
Var i: integer;
Begin {在标识符表中查标识符id}
table[0].name := id; {在符号表栈的最下方预填标识符id}
i := tx; {符号表栈顶指针}
While table[i].name <> id Do
i := i - 1; {从符号表栈顶往下查标识符id}
position := i; {若查到,i为id的入口,否则i=0 }
End; {position}
Procedure constdeclaration;
Begin
If sym = ident Then {当前记号是常数名}
Begin
getsym;
If sym In [eql, becomes] Then {当前记号是等号或赋值号}
Begin
If sym = becomes Then error(1);
getsym;
If sym = number Then {等号后面是常数}
Begin
enter(constant);
getsym;
End
Else error(2) {等号后面不是常数出错}
End
Else error(3) {标识符后不是等号或赋值号出错}
End
Else error(4) {常数说明中没有常数名标识符}
End; {constdeclaration}
Procedure vardeclaration;
Begin
If sym = ident Then {如果当前记号是标识符}
Begin
enter(variable);
getsym;
End
Else error(4) {如果变量说明未出现标识符,则出错}
End; {vardeclaration}
Procedure listcode;
Var i: integer;
Begin {列出本程序体生成的代码}
For i := cx0 To cx - 1 Do
With code[i] Do {打印第i条代码}
writeln(foutAsm, i:5, mnemonic[f]:6, l:3, a:5)
{i: 代码序号}
{mnemonic[f]: 功能码的字符串}
{l: 相对层号(层差)}
{a: 相对地址或运算号码}
End; {listcode}
Procedure statement(fsys: symset);
Var i, cx1, cx2: integer;
Procedure expression(fsys: symset);
Var addop: symbol;
Procedure term(fsys: symset);
Var mulop: symbol;
Procedure factor(fsys: symset);
Var i : integer;
Begin {factor}
test(facbegsys, fsys, 24);
While sym In facbegsys Do
{如果当前的记号是否因子的开始符号}
Begin
If sym = ident Then {当前记号是标识符}
Begin
i := position(id);
If i = 0 Then error(11)
Else
With table[i] Do
Case kind Of
{若id是常数, 生成指令,将常数val取到栈顶}
constant: gen(lit, 0, val);
{若id是变量, 生成指令,将该变量取到栈顶;}
{lev: 当前语句所在过程的层号;}
{level: 定义该变量的过程层号;}
{adr: 变量在其过程的数据空间的相对地址}
variable: gen(lod, lev-level, adr);
{若id是过程名, 则出错}
procedures: error(21);
End;
getsym;
End
Else If sym = number Then {当前记号是数字}
Begin
If num > amax Then
Begin
error(30);
num := 0
End;
gen(lit, 0, num);
getsym;
End
Else If sym = lparen Then {如果当前记号是左括号}
Begin
getsym;
expression([rparen]+fsys);
If sym = rparen Then getsym
Else error(22)
End;
{测试当前记号是否同步, 否则出错, 跳过一些记号}
test(fsys, [lparen], 23)
End {while}
End; {factor}
Begin {term}
factor(fsys+[times, slash]); {处理项中第一个因子}
While sym In [times, slash] Do
Begin
mulop := sym;
getsym;
factor(fsys+[times, slash]);
If mulop = times Then gen(opr, 0, 4)
Else gen(opr, 0, 5)
End
End; {term}
Begin {expression}
If sym In [plus, minus] Then {若第一个记号是加号或减号}
Begin
addop := sym;
getsym;
term(fsys+[plus, minus]);
If addop = minus Then gen(opr, 0, 1)
End
Else term(fsys+[plus, minus]);
{第一个记号不是加号或减号, 则处理一个项}
While sym In [plus, minus] Do {若当前记号是加号或减号}
Begin
addop := sym;
getsym;
term(fsys+[plus, minus]);
If addop = plus Then gen(opr, 0, 2)
Else gen(opr, 0, 3)
End
End; {expression}
Procedure condition(fsys: symset);
Var relop: symbol;
Begin
If sym = oddsym Then {如果当前记号是“odd”}
Begin
getsym;
expression(fsys);
gen(opr, 0, 6)
End
Else {如果当前记号不是“odd”}
Begin
expression([eql, neq, lss, gtr, leq, geq] + fsys);
If Not (sym In [eql, neq, lss, leq, gtr, geq]) Then
error(20)
Else
Begin
relop := sym;
getsym;
expression(fsys); {处理关系符右边的算术表达式}
Case relop Of
eql: gen(opr, 0, 8);
neq: gen(opr, 0, 9);
lss: gen(opr, 0, 10);
geq: gen(opr, 0, 11);
gtr: gen(opr, 0, 12);
leq: gen(opr, 0, 13);
End
End
End
End; {condition}
Begin {statement}
If sym = ident Then {处理赋值语句}
Begin
i := position(id);
If i = 0 Then error(11)
Else If table[i].kind <> variable Then
Begin {对非变量赋值}
error(12);
i := 0;
End;
getsym;
If sym = becomes Then getsym
Else error(13);
expression(fsys);
If i <> 0 Then {若赋值号左边的变量id有定义}
With table[i] Do
gen(sto, lev-level, adr)
{生成一条存数指令, 将栈顶(表达式)的值存入变量id中}
{lev: 当前语句所在过程的层号}
{level: 定义变量id的过程的层号}
{adr: 变量id在其过程的数据空间的相对地址}
End
Else If sym = callsym Then {处理过程调用语句}
Begin
getsym;
If sym <> ident Then error(14)
Else
Begin
i := position(id);
If i = 0 Then error(11)
Else
With table[i] Do
If kind = procedures Then
{如果在符号表中id是过程名}
gen(cal, lev-level, adr)
{生成一条过程调用指令}
{lev: 当前语句所在过程的层号}
{level: 定义过程名id的层号}
{adr: 过程id的代码中第一条指令的地址}
Else error(15);
getsym
End
End
Else If sym = ifsym Then {处理条件语句}
Begin
getsym;
condition([thensym, dosym]+fsys);
If sym = thensym Then getsym
Else error(16);
cx1 := cx;
gen(jpc, 0, 0);
{生成指令,表达式为“假”转到某地址(待填), 否则顺序执行}
statement(fsys);
code[cx1].a := cx;
{将下一个指令的地址回填到上面的jpc指令地址栏}
End
Else If sym = beginsym Then {处理语句序列}
Begin
getsym;
statement([semicolon, endsym]+fsys);
While sym In [semicolon]+statbegsys Do
Begin
If sym = semicolon Then getsym
Else error(10);
statement([semicolon, endsym]+fsys)
End;
If sym = endsym Then getsym
Else error(17);
End
Else If sym = whilesym Then {处理循环语句}
Begin
cx1 := cx;
getsym;
condition([dosym]+fsys);
cx2 := cx;
gen(jpc, 0, 0);
{生成一条指令,表达式为“假”转到某地址(待回填), 否则顺序执行}
If sym = dosym Then getsym
Else error(18);
statement(fsys);
gen(jmp, 0, cx1);
{生成无条件转移指令, 转移到“while”后的条件表达式的代码的第一条指令处}
code[cx2].a := cx
{把下一指令地址回填到前面生成的jpc指令的地址栏}
End;
test(fsys, [], 19);
End; {statement}
Begin {block}
dx := 3; {本过程数据空间栈顶指针}
tx0 := tx; {标识符表的长度(当前指针)}
table[tx].adr := cx; {本过程名的地址, 即下一条指令的序号}
gen(jmp, 0, 0); {生成一条转移指令}
If lev > levmax Then error(32);
Repeat
If sym = constsym Then {处理常数说明语句}
Begin
getsym;
Repeat
constdeclaration; {处理一个常数说明}
While sym = comma Do
Begin
getsym;
constdeclaration
End;
If sym = semicolon Then getsym
Else error(5)
Until sym <> ident
End;
If sym = varsym Then {当前记号是变量说明语句开始符号}
Begin
getsym;
Repeat
vardeclaration; {处理一个变量说明}
While sym = comma Do
Begin
getsym;
vardeclaration
End;
If sym = semicolon Then getsym
Else error(5)
Until sym <> ident;
End;
While sym = procsym Do {处理过程说明}
Begin
getsym;
If sym = ident Then
Begin
enter(procedures);
getsym
End
Else error(4);
If sym = semicolon Then getsym
Else error(5);
block(lev+1, tx, [semicolon]+fsys); {处理过程体}
{lev+1: 过程嵌套层数加1}
{tx: 符号表当前栈顶指针,也是新过程符号表起始位置}
{[semicolon]+fsys: 过程体开始和末尾符号集}
If sym = semicolon Then {如果当前记号是分号}
Begin
getsym;
test(statbegsys+[ident, procsym], fsys, 6)
End
Else error(5)
End; {while}
test(statbegsys+[ident], declbegsys, 7)
Until Not (sym In declbegsys);
code[table[tx0].adr].a := cx;
With table[tx0] Do
Begin
adr := cx;
End;
cx0 := cx;
gen(int, 0, dx);
statement([semicolon, endsym]+fsys);
gen(opr, 0, 0);
test(fsys, [], 8);
listcode;
End; {block}
Procedure interpret;
Const stacksize = 500; {运行时数据空间(栈)的上界}
Var
p, b, t: integer; {程序地址寄存器, 基地址寄存器,栈顶地址寄存器}
i: instruction; {指令寄存器}
s: array [1..stacksize] Of integer; {数据存储栈}
Function base(l: integer): integer;
Var b1: integer;
Begin
b1 := b; {顺静态链求层差为l的外层的基地址}
While l > 0 Do
Begin
b1 := s[b1];
l := l-1
End;
base := b1
End; {base}
Begin
writeln(foutStack, 'START PL/0:');
t := 0; {栈顶地址寄存器}
b := 1; {基地址寄存器}
p := 0; {程序地址寄存器}
s[1] := 0;
s[2] := 0;
s[3] := 0;
{最外层主程序数据空间栈最下面预留三个单元}
{每个过程运行时的数据空间的前三个单元是:SL, DL, RA;}
{SL: 指向本过程静态直接外层过程的SL单元;}
{DL: 指向调用本过程的过程的最新数据空间的第一个单元;}
{RA: 返回地址 }
Repeat
i := code[p];
p := p + 1;
With i Do
Case f Of
lit: {当前指令是取常数指令(lit, 0, a)}
Begin
t := t+1;
s[t] := a
End;
opr: Case a Of {当前指令是运算指令(opr, 0, a)}
0: {返回调用过程指令}
Begin
t := b-1;
p := s[t+3];
b := s[t+2];
End;
1: s[t] := -s[t]; {一元负运算, 栈顶元素的值反号}
2: {加法}
Begin
t := t-1;
s[t] := s[t] + s[t+1]
End;
3: {减法}
Begin
t := t-1;
s[t] := s[t]-s[t+1]
End;
4: {乘法}
Begin
t := t-1;
s[t] := s[t] * s[t+1]
End;
5: {整数除法}
Begin
t := t-1;
s[t] := s[t] Div s[t+1]
End;
6: s[t] := ord(odd(s[t])); {s[t]是否奇数}
8: {判两个表达式的值是否相等}
Begin
t := t-1;
s[t] := ord(s[t] = s[t+1])
End;
9: {判两个表达式的值是否不等}
Begin
t := t-1;
s[t] := ord(s[t] <> s[t+1])
End;
10: {判前一表达式是否小于后一表达式}
Begin
t := t-1;
s[t] := ord(s[t] < s[t+1])
End;
11: {判前一表达式是否大于或等于后一表达式}
Begin
t := t-1;
s[t] := ord(s[t] >= s[t+1])
End;
12: {判前一表达式是否大于后一表达式}
Begin
t := t-1;
s[t] := ord(s[t] > s[t+1])
End;
13: {判前一表达式是否小于或等于后一表达式}
Begin
t := t-1;
s[t] := ord(s[t] <= s[t+1])
End;
End;
lod: {当前指令是取变量指令(lod, l, a)}
Begin
t := t + 1;
s[t] := s[base(l) + a]
End;
sto: {当前指令是保存变量值(sto, l, a)指令}
Begin
s[base(l) + a] := s[t];
writeln(foutStack, s[t]);
t := t-1
End;
cal: {当前指令是(cal, l, a)}
Begin
s[t+1] := base(l);
s[t+2] := b;
s[t+3] := p;
b := t+1;
p := a
End;
int: t := t + a; {若当前指令是(int, 0, a)}
jmp: p := a; {若当前指令是(jmp, 0, a)}
jpc: {当前指令是(jpc, 0, a)}
Begin
If s[t] = 0 Then p := a;
t := t-1
End
End {with, case}
Until p = 0;
writeln(foutStack, 'End PL/0');
End; {interpret}
Begin {主程序}
If ParamCount <> 4 Then
Begin
writeln('Please input filenames.');
writeln('Format: pl0 [source_file] [output_src_file] [output_stack_file] [output_asm_file]');
exit;
End;
assign(fin, ParamStr(1));
assign(fout, ParamStr(2));
assign(foutStack, ParamStr(3));
assign(foutAsm, ParamStr(4));
writeln('Input File: ' + ParamStr(1));
writeln('Output File: ' + ParamStr(2));
writeln('Stack File: ' + ParamStr(3));
writeln('Asm File: ' + ParamStr(4));
writeln('Compile...');
reset(fin);
rewrite(fout);
rewrite(foutStack);
rewrite(foutAsm);
For ch := 'A' To ';' Do
ssym[ch] := nul;
{ASCII码的顺序}
word[1] := 'Begin ';
word[2] := 'Call ';
word[3] := 'Const ';
word[4] := 'Do ';
word[5] := 'End ';
word[6] := 'If ';
word[7] := 'Odd ';
word[8] := 'Procedure ';
word[9] := 'Then ';
word[10] := 'Var ';
word[11] := 'While ';
wsym[1] := beginsym;
wsym[2] := callsym;
wsym[3] := constsym;
wsym[4] := dosym;
wsym[5] := endsym;
wsym[6] := ifsym;
wsym[7] := oddsym;
wsym[8] := procsym;
wsym[9] := thensym;
wsym[10] := varsym;
wsym[11] := whilesym;
ssym['+'] := plus;
ssym['-'] := minus;
ssym['*'] := times;
ssym['/'] := slash;
ssym['('] := lparen;
ssym[')'] := rparen;
ssym['='] := eql;
ssym[','] := comma;
ssym['.'] := period;
{ssym['<>'] := neq;}
{ssym['<'] := lss;}
{ssym['>'] := gtr;}
{ssym['<='] := leq;}
{ssym['>='] := geq;}
ssym[';'] := semicolon;
{算符和标点符号的记号}
mnemonic[lit] := 'LIT';
mnemonic[opr] := 'OPR';
mnemonic[lod] := 'LOD';
mnemonic[sto] := 'STO';
mnemonic[cal] := 'CAL';
mnemonic[int] := 'INT';
mnemonic[jmp] := 'JMP';
mnemonic[jpc] := 'JPC';
{中间代码指令的字符串}
declbegsys := [constsym, varsym, procsym];
{说明语句的开始符号}
statbegsys := [beginsym, callsym, ifsym, whilesym];
{语句的开始符号}
facbegsys := [ident, number, lparen];
{因子的开始符号}
{page(output);}
err := 0; {发现错误的个数}
cc := 0; {当前行中输入字符的指针}
cx := 0; {代码数组的当前指针}
ll := 0; {输入当前行的长度}
ch := ' '; {当前输入的字符}
kk := al; {标识符的长度}
getsym; {取下一个记号}
block(0, 0, [period]+declbegsys+statbegsys); {处理程序体}
If sym <> period Then error(9);
{如果当前记号不是句号, 则出错}
If err = 0 Then interpret
{如果编译无错误, 则解释执行中间代码}
Else write('ERRORS In PL/0 Program');
programExit;
End.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.