text stringlengths 14 6.51M |
|---|
unit Utils;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Zip,
System.IniFiles, Winapi.ShlObj, System.IOUtils, Generics.Collections, Winapi.TlHelp32;
var
OldWow64RedirectionValue: LongBool = True;
/// <summary>
/// 判断系统是否为64位
/// </summary>
/// <returns></returns>
function IsWin64: Boolean;
function DisableWowRedirection: Boolean;
function RevertWowRedirection: Boolean;
/// <summary>
/// 检测XX进程是否存在函数
/// </summary>
/// <param name="ExeFileName"></param>
/// <returns></returns>
function CheckTask(ExeFileName: string): Boolean;
implementation
function IsWin64: Boolean;
var
Kernel32Handle: THandle;
IsWow64Process: function(Handle: THandle; var Res: BOOL): BOOL; stdcall;
GetNativeSystemInfo: procedure(var lpSystemInfo: TSystemInfo); stdcall;
isWoW64: Bool;
SystemInfo: TSystemInfo;
const
PROCESSOR_ARCHITECTURE_AMD64 = 9;
PROCESSOR_ARCHITECTURE_IA64 = 6;
begin
Kernel32Handle := GetModuleHandle('KERNEL32.DLL');
if Kernel32Handle = 0 then
Kernel32Handle := LoadLibrary('KERNEL32.DLL');
if Kernel32Handle <> 0 then
begin
IsWOW64Process := GetProcAddress(Kernel32Handle, 'IsWow64Process');
GetNativeSystemInfo := GetProcAddress(Kernel32Handle, 'GetNativeSystemInfo');
if Assigned(IsWow64Process) then
begin
IsWow64Process(GetCurrentProcess, isWoW64);
Result := isWoW64 and Assigned(GetNativeSystemInfo);
if Result then
begin
GetNativeSystemInfo(SystemInfo);
Result := (SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64) or (SystemInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_IA64);
end;
end
else
Result := False;
end
else
Result := False;
end;
function DisableWowRedirection: Boolean;
type
TWow64DisableWow64FsRedirection = function(var b: LongBool): LongBool; stdcall;
var
hHandle: THandle;
Wow64DisableWow64FsRedirection: TWow64DisableWow64FsRedirection;
begin
Result := true;
try
hHandle := GetModuleHandle('kernel32.dll');
@Wow64DisableWow64FsRedirection := GetProcAddress(hHandle, 'Wow64DisableWow64FsRedirection');
if ((hHandle <> 0) and (@Wow64DisableWow64FsRedirection <> nil)) then
Wow64DisableWow64FsRedirection(OldWow64RedirectionValue);
except
Result := False;
end;
end;
function RevertWowRedirection: Boolean;
type
TWow64RevertWow64FsRedirection = function(var b: LongBool): LongBool; stdcall;
var
hHandle: THandle;
Wow64RevertWow64FsRedirection: TWow64RevertWow64FsRedirection;
begin
Result := true;
try
hHandle := GetModuleHandle('kernel32.dll');
@Wow64RevertWow64FsRedirection := GetProcAddress(hHandle, 'Wow64RevertWow64FsRedirection');
if ((hHandle <> 0) and (@Wow64RevertWow64FsRedirection <> nil)) then
Wow64RevertWow64FsRedirection(OldWow64RedirectionValue);
except
Result := False;
end;
end;
function CheckTask(ExeFileName: string): Boolean; //检测XX进程是否存在函数
const
PROCESS_TERMINATE = $0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
result := False;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(ExeFileName))) then
result := True;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
end;
end.
|
unit UExtraMethodsIntf;
interface
uses InvokeRegistry, Types, XSBuiltIns;
type
IExtraMethods = interface(IInvokable)
['{5DF1C06B-C897-48FC-9011-7E5E2AC4AA9B}']
function GetConstraintsFor(const aProviderName: WideString; aDataSetName: WideString; const aSessionID: String): String; stdcall;
function GetPermissions(const aSessionID: String): OleVariant; stdcall;
end;
implementation
initialization
InvRegistry.RegisterInterface(TypeInfo(IExtraMethods),'','','Interface que expõe métodos adicionais que podem ser usados por clientes autenticados');
end.
|
unit FormUtils;
{**********************************************
Kingstar Delphi Library
Copyright (C) Kingstar Corporation
<Unit> FormUtils
<What> 有关Form的工具
调整Form的大小位置等等
<Written By> Huang YanLai
<History>
**********************************************}
interface
uses Windows, Messages, SysUtils, Classes,Controls,Forms;
{ Form Size/position Utilities.
How to use them:
Example : in OnFormCreate handler, write
SetFormSize(self,0.5,0,5);
or SetFormPos(self,true,false,false,false);
or both
}
type
TFormPosition = (atLeft,atRight,atTop,atBottom);
TFormPositions = set of TFormPosition;
// set form size relative of Screen
procedure SetFormSize(Form : TCustomForm; WidthPersent, HeightPersent : real);
// set form position relative of Screen
procedure SetFormPos(Form : TCustomForm; poss : TFormPositions);
// set form at Screen center
procedure PlaceScreenCenter(Form: TCustomForm);
// set form position relative of another form
procedure SetFormRelatePos(Form,RelateForm : TCustomForm;
pos : TFormPosition; distance : integer);
// set form position relative of another form, and change form's size.
procedure SetFormRelatePos2(Form,RelateForm : TCustomForm;
pos : TFormPosition; distance : integer; ChangeSize : boolean);
// set form position relative of another form, and change form's size.
// use offset relative to RelateForm's left or right or top or bottom.
// offset + rightward,downward, - leftward,upward
procedure SetFormRelatePos3(Form,RelateForm : TCustomForm;
pos : TFormPosition; offset : integer; ChangeSize : boolean);
procedure ShowDockableCtrl(Ctrl : TControl);
implementation
procedure SetFormSize(Form : TCustomForm; WidthPersent, HeightPersent : real);
var
width,height : integer;
begin
width := round(Screen.width * WidthPersent);
height := round(Screen.height * HeightPersent);
Form.SetBounds(Form.left,Form.top,width,height);
end;
procedure SetFormPos(Form : TCustomForm; poss : TFormPositions);
var
left,width,top,height : integer;
begin
left := Form.left;
width := Form.width;
top := Form.top;
height := Form.height;
if [atleft,atright] <= poss then
begin
left:=0;
width := screen.width;
end
else // not change width
begin
if atLeft in poss then left:=0
else if atRight in poss then left:=screen.width-width;
end;
if [attop,atbottom]<=poss then
begin
top:=0;
height := screen.height;
end
else // not change height
begin
if attop in poss then top:=0
else if atbottom in poss then top:=screen.height-height;
end;
Form.SetBounds(left,top,width,height);
end;
procedure PlaceScreenCenter(Form: TCustomForm);
var
Left,top : integer;
begin
Left := (screen.width - form.width) div 2;
Top := (screen.Height - form.Height) div 2;
Form.SetBounds(left,top,form.width,form.Height);
end;
procedure SetFormRelatePos(Form,RelateForm : TCustomForm;
pos : TFormPosition; distance : integer);
{var
left,top,width,height : integer;}
begin
{ left := Form.left;
width := Form.width;
top := Form.top;
height := Form.height;
case pos of
atLeft: left := RelateForm.Left - distance - width;
atRight: left := RelateForm.Left + RelateForm.width + distance;
atTop: top := RelateForm.Top - distance - Height;
atBottom: top := RelateForm.top + RelateForm.height + distance;
end;
Form.SetBounds(left,top,width,height);}
SetFormRelatePos2(Form,RelateForm,
pos,distance,false);
end;
procedure SetFormRelatePos2(Form,RelateForm : TCustomForm;
pos : TFormPosition; distance : integer; ChangeSize : boolean);
var
left,top,width,height : integer;
begin
left := Form.left;
width := Form.width;
top := Form.top;
height := Form.height;
case pos of
atLeft: left := RelateForm.Left - distance - width;
atRight: left := RelateForm.Left + RelateForm.width + distance;
atTop: top := RelateForm.Top - distance - Height;
atBottom: top := RelateForm.top + RelateForm.height + distance;
end;
if changeSize then
begin
width := width + (Form.left-left);
Height := Height + (Form.top-top);
end;
Form.SetBounds(left,top,width,height);
end;
// set form position relative of another form, and change form's size.
// use offset
procedure SetFormRelatePos3(Form,RelateForm : TCustomForm;
pos : TFormPosition; offset : integer; ChangeSize : boolean);
var
left,top,width,height : integer;
begin
left := Form.left;
width := Form.width;
top := Form.top;
height := Form.height;
case pos of
atLeft: left := RelateForm.Left + offset;
atRight: left := RelateForm.Left + RelateForm.width + offset;
atTop: top := RelateForm.Top + offset;
atBottom: top := RelateForm.top + RelateForm.height + offset;
end;
if changeSize then
begin
width := width + (Form.left-left);
Height := Height + (Form.top-top);
end;
Form.SetBounds(left,top,width,height);
end;
procedure ShowDockableCtrl(Ctrl : TControl);
begin
repeat
while Ctrl.HostDockSite<>nil do
Ctrl:=Ctrl.HostDockSite;
while Ctrl.parent<>nil do
Ctrl := Ctrl.parent;
until (Ctrl.parent=nil) and (Ctrl.HostDockSite=nil);
if Ctrl is TCustomForm then
with TCustomForm(Ctrl) do
if WindowState = wsMinimized then
WindowState := wsNormal;
Ctrl.show;
end;
end.
|
{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{}
{ $Log: 23934: EncoderBox.pas
{
{ Rev 1.1 04/10/2003 15:22:18 CCostelloe
{ Emails generated now have the same date
}
{
{ Rev 1.0 26/09/2003 00:04:08 CCostelloe
{ Initial
}
unit EncoderBox;
interface
{$I IdCompilerDefines.inc}
uses
IndyBox,
Classes,
IdComponent, IdGlobal, IdSocketHandle, IdIntercept, IdMessage, IdMessageClient,
SysUtils;
type
TEncoderBox = class(TIndyBox)
protected
FExtractPath: string;
FMsg: TIdMessage;
FGeneratedStream: TMemoryStream;
FTestMessageName: string;
public
procedure Test; override;
procedure TestMessage(const APathname: string; const AVerify: Boolean = False;
const AEmit: Boolean = False);
//
property ExtractPath: string read FExtractPath;
property Msg: TIdMessage read FMsg;
property GeneratedStream: TMemoryStream read FGeneratedStream;
property TestMessageName: string read FTestMessageName;
end;
implementation
uses
IdMessageCoderMIME, IdMessageCoderUUE, IdPOP3,
IniFiles, IdText, IdAttachmentFile{$IFDEF VER130},FileCtrl{$ENDIF};
{ TEncoderBox }
procedure TEncoderBox.Test;
var
i: integer;
LRec: TSearchRec;
LPathToSearch: string;
begin
LPathToSearch := GetDataDir + '*.ini';
i := FindFirst(LPathToSearch, faAnyFile, LRec); try
while i = 0 do begin
TestMessage(GetDataDir + LRec.Name, True);
i := FindNext(LRec);
end;
finally FindClose(LRec); end;
end;
procedure TEncoderBox.TestMessage(const APathname: string; const AVerify: Boolean = False;
const AEmit: Boolean = False);
var
IniParams: TStringList;
CorrectStream: TFileStream;
//GeneratedStreamToFile: TFileStream;
i: Integer;
sTemp: string;
sParentPart, sContentType, sType, sEncoding, sFile: string;
nParentPart: Integer;
nPos: integer;
TheTextPart: TIdText;
{$IFDEF INDY100}
TheAttachment: TIdAttachmentFile;
{$ELSE}
TheAttachment: TIdAttachment;
{$ENDIF}
sr: TSearchRec;
FileAttrs: Integer;
procedure CompareStream(const AStream1: TStream; const AStream2: TStream; const AMsg: string);
//var
//i: integer;
//LByte1, LByte2: byte;
begin
Check(AStream1.Size = AStream2.Size, 'File size mismatch with ' + AMsg);
//The following always fails for MIME because the random boundary is always different !!!
{
for i := 1 to AStream1.Size do begin
AStream1.ReadBuffer(LByte1, 1);
AStream2.ReadBuffer(LByte2, 1);
Check(LByte1 = LByte2, 'Mismatch at byte ' + IntToStr(i) + ', '
+ AMsg);
end;
}
end;
begin
FTestMessageName := '';
Status('Testing message ' + ExtractFilename(APathname));
//Set up path to test directory...
FExtractPath := ChangeFileExt(APathname, '') + GPathSep;
ForceDirectories(ExtractPath);
//Set up the filename of the correct (test) message...
FTestMessageName := ExtractPath+ChangeFileExt(ExtractFilename(APathname), '.msg');
//If it is Emit, make sure we will be able to delete the message...
FileAttrs := 0; //Stop compiler whining it might not have been initialized
if AEmit then begin
if FindFirst(FTestMessageName, FileAttrs, sr) = 0 then begin
if (sr.Attr and faReadOnly) = faReadOnly then begin
raise EBXCheck.Create('The reference file exists and is read-only, Emit not valid: '+FTestMessageName);
end;
FindClose(sr);
end;
end;
FMsg := TIdMessage.Create(Self);
//Read in the INI settings that define the email we are to generate...
IniParams := TStringList.Create;
IniParams.LoadFromFile(APathname);
//Make sure the date will always be the same, else get different
//outputs for the Date header...
FMsg.UseNowForDate := False;
FMsg.Date := EncodeDate(2011, 11, 11);
i := 0;
while IniParams.Values['Body'+IntToStr(i)] <> '' do begin
FMsg.Body.Add(IniParams.Values['Body'+IntToStr(i)]);
Inc(i);
end;
FMsg.ContentTransferEncoding := IniParams.Values['ContentTransferEncoding'];
if IniParams.Values['ConvertPreamble'] = 'True' then begin
FMsg.ConvertPreamble := True;
end else if IniParams.Values['ConvertPreamble'] = 'False' then begin
FMsg.ConvertPreamble := False;
end;
if IniParams.Values['Encoding'] = 'meMIME' then begin
FMsg.Encoding := meMIME;
end else if IniParams.Values['Encoding'] = 'meUU' then begin
FMsg.Encoding := meUU;
end else if IniParams.Values['Encoding'] = 'meXX' then begin
FMsg.Encoding := meXX;
end;
if IniParams.Values['ContentType'] <> '' then begin
FMsg.ContentType := IniParams.Values['ContentType'];
end;
i := 0;
while IniParams.Values['Part'+IntToStr(i)] <> '' do begin
sTemp := IniParams.Values['Part'+IntToStr(i)];
nPos := Pos(',', sTemp);
sType := Copy(sTemp, 1, nPos-1);
sTemp := Copy(sTemp, nPos+1, MAXINT);
nPos := Pos(',', sTemp);
sEncoding := Copy(sTemp, 1, nPos-1);
sFile := Copy(sTemp, nPos+1, MAXINT);
nParentPart := -999;
nPos := Pos(',', sFile);
if nPos > 0 then begin //ParentPart, ContentType optional
sTemp := Copy(sFile, nPos+1, MAXINT);
sFile := Copy(sFile, 1, nPos-1);
nPos := Pos(',', sTemp);
sContentType := Copy(sTemp, nPos+1, MAXINT);
sParentPart := Copy(sTemp, 1, nPos-1);
nParentPart := StrToInt(sParentPart);
end;
if sType = 'TIdText' then begin
TheTextPart := TIdText.Create(FMsg.MessageParts);
TheTextPart.Body.LoadFromFile(sFile);
if sEncoding <> 'Default' then TheTextPart.ContentTransfer := sEncoding;
if ((sContentType <> '') and (sContentType <> 'Default')) then TheTextPart.ContentType := sContentType;
{$IFDEF INDY100}
if nParentPart <> -999 then TheTextPart.ParentPart := nParentPart;
{$ENDIF}
end else begin
{$IFDEF INDY100}
TheAttachment := TIdAttachmentFile.Create(FMsg.MessageParts, sFile);
{$ELSE}
TheAttachment := TIdAttachment.Create(FMsg.MessageParts, sFile);
{$ENDIF}
if sEncoding <> 'Default' then TheAttachment.ContentTransfer := sEncoding;
if ((sContentType <> '') and (sContentType <> 'Default')) then TheAttachment.ContentType := sContentType;
{$IFDEF INDY100}
if nParentPart <> -999 then TheAttachment.ParentPart := nParentPart;
{$ENDIF}
end;
Inc(i);
end;
//Do the test...
FGeneratedStream := TMemoryStream.Create;
FMsg.SaveToStream(FGeneratedStream);
//Compare the results...
try
if AEmit then begin
GeneratedStream.Seek(0, soFromBeginning);
GeneratedStream.SaveToFile(TestMessageName);
end else if AVerify then begin
Check(FileExists(TestMessageName) = True, 'Missing correct result file '+TestMessageName);
CorrectStream := TFileStream.Create(TestMessageName, fmOpenRead);
GeneratedStream.Seek(0, soFromBeginning);
CompareStream(GeneratedStream, CorrectStream, ExtractFilename(APathname));
end;
finally FreeAndNil(CorrectStream); end;
Status('Message encoded.');
end;
initialization
TIndyBox.RegisterBox(TEncoderBox, 'Emails', 'Encoders');
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Ported to Delphi by Michal Wojcik.
//
{$H+}
unit FixtureName;
interface
uses
Classes,
StrUtils,
SysUtils;
type
TFixtureName = class
private
nameAsString : string;
procedure addBlahAndBlahFixture(qualifiedBy : string; candidateClassNames : TStringList);
public
constructor Create(tableName : string);
function toString() : string;
function getPotentialFixtureClassNames(fixturePathElements : TStringList) : TStringList;
function fixtureNameHasPackageSpecified(fixtureName : string) : boolean;
function isFullyQualified() : boolean;
end;
implementation
uses
GracefulNamer;
{ TFixtureName }
constructor TFixtureName.Create(tableName : string);
begin
inherited Create;
if (TGracefulNamer.isGracefulName(tableName)) then
begin
self.nameAsString := TGracefulNamer.disgrace(tableName);
end
else
begin
self.nameAsString := tableName;
end;
end;
function TFixtureName.toString() : string;
begin
result := nameAsString;
end;
function TFixtureName.isFullyQualified() : boolean;
begin
result := Pos('.', nameAsString) <> 0;
end;
function TFixtureName.fixtureNameHasPackageSpecified(fixtureName : string) : boolean;
begin
result := TFixtureName.Create(fixtureName).isFullyQualified();
end;
function TFixtureName.getPotentialFixtureClassNames(fixturePathElements : TStringList) : TStringList;
var
packageName : string;
i : Integer;
candidateClassNames : TStringList;
begin
candidateClassNames := TStringList.Create;
if (not isFullyQualified()) then
begin
for i := 0 to fixturePathElements.Count - 1 do
begin
packageName := fixturePathElements[i];
addBlahAndBlahFixture(packageName + '.', candidateClassNames);
end;
end;
addBlahAndBlahFixture('', candidateClassNames);
result := candidateClassNames;
end;
procedure TFixtureName.addBlahAndBlahFixture(qualifiedBy : string; candidateClassNames : TStringList);
begin
candidateClassNames.add(qualifiedBy + nameAsString);
candidateClassNames.add(qualifiedBy + nameAsString + 'Fixture');
candidateClassNames.add(qualifiedBy + StringReplace(nameAsString, '.', '.T', [rfReplaceAll]));
candidateClassNames.add(qualifiedBy + StringReplace(nameAsString, '.', '.T', [rfReplaceAll]) + 'Fixture');
if not ((nameAsString[1] = 'T') and (nameAsString[2] in ['A'..'Z'])) then // Delphi specific - convert to notation TSomeClass
begin
candidateClassNames.add(qualifiedBy + 'T' + nameAsString);
candidateClassNames.add(qualifiedBy + 'T' + nameAsString + 'Fixture');
end;
end;
end.
|
unit Unit2;
interface
uses System.SysUtils,System.Types,System.UITypes,System.Generics.Collections,FMX.Types,FMX.Dialogs, FMX.Graphics;
type
TPoints = TList<TPointF>;
TBrokenLine = class
Points: TPoints;
Name: string;
constructor Create(Arr: TPoints; inName: string);
procedure Draw(canvas: TCanvas); virtual;
procedure relocate(direction: word);
procedure zoom(a: byte);
procedure turn(a: byte);
function testRange(w,h: single): boolean;
end;
TPolygon = class(TBrokenLine)
procedure Draw(canvas: TCanvas); override;
end;
TFiguresList = TObjectList<TBrokenLine>;
const
WORK_WITH_FIGURES = 1; //режимы работы
BROKEN_LINE = 2;
POLYGON = 3;
UP = 1; //направления перемещения
DOWN = 3;
LEFT =4;
RIGHT = 2;
MIN_ANGLE = 0.01; //элементароный угол поворота
MIN_RELOC = 1; //элементаронео перемещение
INCREASE = 1.01; //коэффициент увеличения
DECREASE = 0.99; //коэффициент уменьшения
var
currentMode: integer = 0;
FiguresList: TFiguresList;
drawFigure: TPoints;
currentFigure: TBrokenLine;
curPoint: TPointF;
implementation
uses Math;
constructor TBrokenLine.Create;
var i: integer;
begin
Points := TPoints.Create;
for i := 0 to Arr.Count-1 do Points.Add(Arr[i]);
name := InName;
end;
procedure TBrokenLine.Draw;
var i: integer;
begin
canvas.BeginScene;
for i := 0 to Points.Count-2 do
canvas.DrawLine(Points[i],Points[i+1],1);
canvas.EndScene;
end;
{ TPolygon }
procedure TPolygon.Draw;
begin
inherited;
with canvas do
begin
BeginScene;
DrawLine(Points[Points.Count-1],Points[0],1);
EndScene;
end;
end;
procedure TBrokenLine.relocate(direction: word);
var i: integer;
p: TPointF;
begin
p:= TPointF.Create(0,0);
case direction of
UP: for i := 0 to Points.Count-1 do begin p.X := Points[i].X; p.Y := Points[i].y - MIN_RELOC; Points[i] := p; end;
RIGHT: for i := 0 to Points.Count-1 do begin p.X := Points[i].X + MIN_RELOC; p.Y := Points[i].y; Points[i] := p; end;
DOWN: for i := 0 to Points.Count-1 do begin p.X := Points[i].X; p.Y := Points[i].y + MIN_RELOC; Points[i] := p; end;
LEFT: for i := 0 to Points.Count-1 do begin p.X := Points[i].X-MIN_RELOC; p.Y := Points[i].y; Points[i] := p; end;
end;
end;
procedure TBrokenLine.zoom(a: byte);
var i: integer;
x,y: single;
centr,p: TPointF;
begin
x := 0;
y := 0;
for i := 0 to Points.Count-1 do
begin
x := x + Points[i].X;
y := y + Points[i].y;
end;
x := x/Points.Count;
y := y/Points.Count;
centr := TpointF.Create(x,y);
for i := 0 to Points.Count-1 do
begin
case a of
1: begin x := (Points[i].X - centr.X) * INCREASE + centr.X;
y := (Points[i].Y - centr.Y) * INCREASE + centr.Y;
end;
0: begin x := (Points[i].X - centr.X) * DECREASE + centr.X;
y := (Points[i].Y - centr.Y) * DECREASE + centr.Y;
end;
end;
p := TPointF.Create(x,y);
Points[i] := p;
end;
end;
procedure TBrokenLine.turn(a: byte);
var i: integer;
x,y: single;
centr,p: TPointF;
begin
try
x := 0;
y := 0;
for i := 0 to Points.Count-1 do
begin
x := x + Points[i].X;
y := y + Points[i].y;
end;
x := x/Points.Count;
y := y/Points.Count;
centr := TpointF.Create(x,y);
for i := 0 to Points.Count-1 do
begin
case a of
1: begin x := (Points[i].X - centr.X) * cos(MIN_ANGLE) - (Points[i].Y - centr.Y)* sin(MIN_ANGLE) + centr.X;
y := (Points[i].X - centr.X) * sin(MIN_ANGLE) + (Points[i].Y - centr.Y) * cos(MIN_ANGLE) + centr.Y;
end;
0: begin x := (Points[i].X - centr.X) * cos(-MIN_ANGLE) - (Points[i].Y - centr.Y)* sin(-MIN_ANGLE) + centr.X;
y := (Points[i].X - centr.X) * sin(-MIN_ANGLE) + (Points[i].Y - centr.Y) * cos(-MIN_ANGLE) + centr.Y;
end;
end;
p := TPointF.Create(x,y);
Points[i] := p;
end;
except
on EAccessViolation do ShowMessage('Нет объектов');
end;
end;
function TBrokenLine.testRange(w,h: single): boolean;
var i,j: integer;
p: boolean;
t: TPointF;
begin
i := 0;
p:=true;
t:=TPointF.Create(0,0);
while (i < Points.Count) and p do
begin
if (Points[i].X >= w-5) then
begin
p:=false;
for j := 0 to Points.Count - 1 do
begin
t.X := Points[j].X-5;
t.Y := Points[j].y;
Points[j] := t;
end;
end;
if (Points[i].X <= 5) then begin p:=false; for j := 0 to Points.Count - 1 do begin t.X := Points[j].X+5; t.Y := Points[j].y; Points[j] := t; end; end;
if (Points[i].y >= h-5) then begin p:=false; for j := 0 to Points.Count - 1 do begin t.y := Points[j].y-5; t.x := Points[j].x; Points[j] := t; end; end;
if (Points[i].y <= 5) then begin p:=false; for j := 0 to Points.Count - 1 do begin t.y := Points[j].y+5; t.x := Points[j].x; Points[j] := t; end; end;
inc(i);
end;
if not p then result := true
else result := false;
end;
initialization
FiguresList := TFiguresList.Create;
FiguresList.Count := 0;
drawFigure := TPoints.Create;
drawFigure.Count := 0;
curPoint := TPointF.Create(0,0);
end.
|
unit UtilsHttp_WinInet;
interface
uses
WinInet, Classes, Sysutils, UtilsHttp;
type
PWinInetSession = ^TWinInetSession;
TWinInetSession = record
Session : HINTERNET;
Connect : HINTERNET;
Request : HINTERNET;
end;
function Http_GetString(AURL: string): string;
function GetHTTPStream(AHttpUrlInfo: PHttpUrlInfo; AWinInetSession: PWinInetSession;
AStream: TStream; APost: TStrings): Boolean;
function IsUrlValid(AUrl: AnsiString): boolean;
implementation
//uses
// CnInetUtils;
function GetStreamFromHandle(ARequestHandle: HINTERNET; ATotalSize: Integer; AStream: TStream): Boolean;
const
csBufferSize = 4096;
var
tmpCurrSize: Cardinal;
tmpReaded: Cardinal;
tmpBuf: array[0..csBufferSize - 1] of Byte;
begin
Result := False;
tmpCurrSize := 0;
tmpReaded := 0;
repeat
if not InternetReadFile(ARequestHandle, @tmpBuf, csBufferSize, tmpReaded) then
Exit;
if tmpReaded > 0 then
begin
AStream.Write(tmpBuf, tmpReaded);
Inc(tmpCurrSize, tmpReaded);
//DoProgress(TotalSize, CurrSize);
//if Aborted then
// Exit;
end;
until tmpReaded = 0;
Result := True;
end;
function GetHTTPStream(AHttpUrlInfo: PHttpUrlInfo;
AWinInetSession: PWinInetSession;
AStream: TStream; APost: TStrings): Boolean;
var
tmpIsHttps: Boolean;
tmpPathName: string;
tmpSizeStr: array[0..63] of Char;
tmpBufLen: Cardinal;
tmpIndex: Cardinal;
i: Integer;
tmpPort: Word;
tmpFlag: Cardinal;
tmpVerb: string;
tmpOpt: string;
tmpPOpt: PChar;
tmpOptLen: Integer;
begin
Result := False;
try
tmpIsHttps := SameText(AHttpUrlInfo.Protocol, 'https');
if tmpIsHttps then
begin
tmpPort := StrToIntDef(AHttpUrlInfo.Port, INTERNET_DEFAULT_HTTPS_PORT);
tmpFlag := INTERNET_FLAG_RELOAD or INTERNET_FLAG_SECURE or
INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
end
else
begin
tmpPort := StrToIntDef(AHttpUrlInfo.Port, INTERNET_DEFAULT_HTTP_PORT);
tmpFlag := INTERNET_FLAG_RELOAD;
end;
//if NoCookie then
// Flag := Flag + INTERNET_FLAG_NO_COOKIES;
AWinInetSession.Connect :=
InternetConnect(AWinInetSession.Session, PChar(AHttpUrlInfo.Host), tmpPort, nil, nil, INTERNET_SERVICE_HTTP, 0, 0);
if (nil = AWinInetSession.Connect) {or FAborted } then
Exit;
if APost <> nil then
begin
tmpVerb := 'POST';
tmpOpt := '';
for i := 0 to APost.Count - 1 do
if tmpOpt = '' then
tmpOpt := EncodeURL(APost[i])
else
tmpOpt := tmpOpt + '&' + EncodeURL(APost[i]);
tmpPOpt := PChar(tmpOpt);
tmpOptLen := Length(tmpOpt);
end
else
begin
tmpVerb := 'GET';
tmpPOpt := nil;
tmpOptLen := 0;
end;
tmpPathName := AHttpUrlInfo.PathName;
//if EncodeUrlPath then
tmpPathName := EncodeURL(tmpPathName);
AWinInetSession.Request := HttpOpenRequest(AWinInetSession.Connect,
PChar(tmpVerb), PChar(tmpPathName), HTTP_VERSION, nil, nil, tmpFlag, 0);
if (nil = AWinInetSession.Request) {or FAborted} then
Exit;
//if FDecoding and FDecodingValid then
begin
HttpAddRequestHeaders(AWinInetSession.Request,
PChar(SAcceptEncoding),
Length(SAcceptEncoding),
HTTP_ADDREQ_FLAG_REPLACE or HTTP_ADDREQ_FLAG_ADD);
end;
// for i := 0 to FHttpRequestHeaders.Count - 1 do
// begin
// HttpAddRequestHeaders(AWinInetSession.Request,
// PChar(FHttpRequestHeaders[i]),
// Length(FHttpRequestHeaders[i]),
// HTTP_ADDREQ_FLAG_REPLACE or HTTP_ADDREQ_FLAG_ADD);
// end;
if HttpSendRequest(AWinInetSession.Request, nil, 0, tmpPOpt, tmpOptLen) then
begin
//if FAborted then
// Exit;
FillChar(tmpSizeStr, SizeOf(tmpSizeStr), 0);
tmpBufLen := SizeOf(tmpSizeStr);
tmpIndex := 0;
HttpQueryInfo(AWinInetSession.Request, HTTP_QUERY_CONTENT_LENGTH, @tmpSizeStr, tmpBufLen, tmpIndex);
//if Aborted then
// Exit;
Result := GetStreamFromHandle(AWinInetSession.Request, StrToIntDef(tmpSizeStr, -1), AStream);
end;
finally
if nil <> AWinInetSession.Request then
InternetCloseHandle(AWinInetSession.Request);
if nil <> AWinInetSession.Connect then
InternetCloseHandle(AWinInetSession.Connect);
end;
end;
function Http_GetString(AURL: string): string;
begin
// Result := CnInet_GetString(AURL);
end;
// 检查URL是否有效的函数
function IsUrlValid(AUrl: AnsiString): boolean;
var
tmpWinInet: TWinInetSession;
dwindex: dword;
dwcodelen: dword;
dwcode: array[1..20] of AnsiChar;
res: PAnsiChar;
tmpAgent: AnsiString;
begin
Result := false;
if Pos('://', lowercase(AUrl)) < 1 then
AUrl := 'http://' + AUrl;
tmpAgent := 'InetURL:/1.0';
tmpWinInet.Session := InternetOpenA(PAnsiChar(tmpAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(tmpWinInet.Session) then
begin
try
tmpWinInet.Request := InternetOpenUrlA(tmpWinInet.Session, PAnsiChar(AUrl), nil, 0, INTERNET_FLAG_RELOAD, 0);
try
dwIndex := 0;
dwCodeLen := 10;
if HttpQueryInfoA(tmpWinInet.Request, HTTP_QUERY_STATUS_CODE, @dwcode, dwcodeLen, dwIndex) then
begin
res := PAnsiChar(@dwcode);
result := (res = '200') or (res = '302');
end;
finally
InternetCloseHandle(tmpWinInet.Request);
end;
finally
InternetCloseHandle(tmpWinInet.Session);
end;
end;
end;
end.
|
(*
ENUNCIADO
Fazer um programa em Pascal para ler do teclado um número inteiro m e em seguida ler uma sequência de m pares de números
(N1, P1), (N2, P2), ... (Nm, Pm), onde Ni, 1 <= i <= m são números reais e Pi, 1 <= i <= m são números inteiros,
imprimir o cálculo da média ponderada deles. Isto é, calcular:
// MP= (N1*P1 + N2*P2 + ... + Nm*Pm)/(P1 + P2 + ... + Pm)
Seu programa deve imprimir a mensagem "divisao por zero" caso o denominador seja zero.
Caso isso não ocorra seu programa irá abortar neste caso, o que não é correto.
Exemplos de entrada e saída:
Exemplo de entrada 1:
3
0 1
3 2
10 3
Saída esperada :
6.0000000000000000E+000
Exemplo de entrada 2:
3
0 0
3 2
10 -2
Saída esperada :
divisao por zero
Exemplo de entrada 3:
0
Saída esperada :
divisao por zero
*)
program 2mediaponderada;
var
m,i:integer;
num,den:real;
p: real;
n: real;
begin
i:=0;
m:=0;
read(m);
while (i<m) do
begin
read(n);
read(p);
num:=num+(n*p);
den:=den+p;
i:=i+1;
end;
if (den = 0) then
writeln('divisao por zero')
else
begin
writeln(num/den);
end;
end.
|
function MastermindCodeToString(a, b, c, d: integer): string;
var strA, strB, strC, strD: string;
begin
str(a, strA);
str(b, strB);
str(c, strC);
str(d, strD);
MastermindCodetoString := concat(strA, strB, strC, strD);
end;
|
unit main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, wclBluetooth, wclWeDoWatcher, wclWeDoHub, Vcl.ComCtrls;
type
TfmMain = class(TForm)
btConnect: TButton;
btDisconnect: TButton;
laStatus: TLabel;
laCurrentTitle: TLabel;
laCurrent: TLabel;
laMA: TLabel;
laVoltageTitle: TLabel;
laVoltage: TLabel;
laMV: TLabel;
laHighCurrent: TLabel;
laLowVoltage: TLabel;
PageControl: TPageControl;
tsMotor1: TTabSheet;
laIoState1: TLabel;
laDirection1: TLabel;
laPower1: TLabel;
cbDirection1: TComboBox;
edPower1: TEdit;
btStart1: TButton;
btBrake1: TButton;
btDrift1: TButton;
tsMotor2: TTabSheet;
laIoState2: TLabel;
laDirection2: TLabel;
cbDirection2: TComboBox;
laPower2: TLabel;
edPower2: TEdit;
btStart2: TButton;
btDrift2: TButton;
btBrake2: TButton;
procedure FormCreate(Sender: TObject);
procedure btDisconnectClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btConnectClick(Sender: TObject);
procedure btStart1Click(Sender: TObject);
procedure btBrake1Click(Sender: TObject);
procedure btDrift1Click(Sender: TObject);
procedure btBrake2Click(Sender: TObject);
procedure btDrift2Click(Sender: TObject);
procedure btStart2Click(Sender: TObject);
private
FManager: TwclBluetoothManager;
FWatcher: TwclWeDoWatcher;
FHub: TwclWeDoHub;
FMotor1: TwclWeDoMotor;
FMotor2: TwclWeDoMotor;
FCurrent: TwclWeDoCurrentSensor;
FVoltage: TwclWeDoVoltageSensor;
procedure FHub_OnLowVoltageAlert(Sender: TObject; Alert: Boolean);
procedure FHub_OnHighCurrentAlert(Sender: TObject; Alert: Boolean);
procedure FHub_OnDeviceDetached(Sender: TObject; Device: TwclWeDoIo);
procedure FHub_OnDeviceAttached(Sender: TObject; Device: TwclWeDoIo);
procedure FHub_OnDisconnected(Sender: TObject; Reason: Integer);
procedure FHub_OnConnected(Sender: TObject; Error: Integer);
procedure FVoltage_OnVoltageChanged(Sender: TObject);
procedure FCurrent_OnCurrentChanged(Sender: TObject);
procedure FWatcher_OnHubFound(Sender: TObject; Address: Int64;
Name: string);
procedure EnablePlay;
procedure EnablePlay1(Attached: Boolean);
procedure EnablePlay2(Attached: Boolean);
procedure EnableConnect(Connected: Boolean);
procedure Disconnect;
end;
var
fmMain: TfmMain;
implementation
uses
wclErrors;
{$R *.dfm}
procedure TfmMain.btBrake1Click(Sender: TObject);
var
Res: Integer;
begin
if FMotor1 = nil then
ShowMessage('Device is not attached')
else begin
Res := FMotor1.Brake;
if Res <> WCL_E_SUCCESS then
ShowMessage('Brake motor failed: 0x' + IntToHex(Res, 8));
end;
end;
procedure TfmMain.btConnectClick(Sender: TObject);
var
Res: Integer;
Radio: TwclBluetoothRadio;
begin
// The very first thing we have to do is to open Bluetooth Manager.
// That initializes the underlying drivers and allows us to work with
// Bluetooth.
// Always check result!
Res := FManager.Open;
if Res <> WCL_E_SUCCESS then
// It should never happen but if it does notify user.
ShowMessage('Unable to open Bluetooth Manager: 0x' + IntToHex(Res, 8))
else begin
// Assume that no one Bluetooth Radio available.
Radio := nil;
Res := FManager.GetLeRadio(Radio);
if Res <> WCL_E_SUCCESS then
// If not, let user know that he has no Bluetooth.
ShowMessage('No available Bluetooth Radio found')
else begin
// If found, try to start discovering.
Res := FWatcher.Start(Radio);
if Res <> WCL_E_SUCCESS then
// It is something wrong with discovering starting. Notify user about
// the error.
ShowMessage('Unable to start discovering: 0x' + IntToHex(Res, 8))
else begin
btConnect.Enabled := False;
btDisconnect.Enabled := True;
laStatus.Caption := 'Searching...';
end;
end;
// Again, check the found Radio.
if Res <> WCL_E_SUCCESS then begin
// And if it is null (not found or discovering was not started
// close the Bluetooth Manager to release all the allocated resources.
FManager.Close;
// Also clean up found Radio variable so we can check it later.
Radio := nil;
end;
end;
end;
procedure TfmMain.btDisconnectClick(Sender: TObject);
begin
Disconnect;
end;
procedure TfmMain.btDrift1Click(Sender: TObject);
var
Res: Integer;
begin
if FMotor1 = nil then
ShowMessage('Device is not attached')
else begin
Res := FMotor1.Drift;
if Res <> WCL_E_SUCCESS then
ShowMessage('Drift motor failed: 0x' + IntToHex(Res, 8));
end;
end;
procedure TfmMain.btStart1Click(Sender: TObject);
var
Dir: TwclWeDoMotorDirection;
Res: Integer;
begin
if FMotor1 = nil then
ShowMessage('Device is not attached')
else begin
case cbDirection1.ItemIndex of
0: Dir := mdRight;
1: Dir := mdLeft;
else Dir := mdUnknown;
end;
Res := FMotor1.Run(Dir, StrToInt(edPower1.Text));
if Res <> WCL_E_SUCCESS then
ShowMessage('Start motor failed: 0x' + IntToHex(Res, 8));
end;
end;
procedure TfmMain.btStart2Click(Sender: TObject);
var
Dir: TwclWeDoMotorDirection;
Res: Integer;
begin
if FMotor2 = nil then
ShowMessage('Device is not attached')
else begin
case cbDirection2.ItemIndex of
0: Dir := mdRight;
1: Dir := mdLeft;
else Dir := mdUnknown;
end;
Res := FMotor2.Run(Dir, StrToInt(edPower2.Text));
if Res <> WCL_E_SUCCESS then
ShowMessage('Start motor failed: 0x' + IntToHex(Res, 8));
end;
end;
procedure TfmMain.Disconnect;
begin
FWatcher.Stop;
FHub.Disconnect;
FManager.Close;
btConnect.Enabled := True;
btDisconnect.Enabled := False;
end;
procedure TfmMain.EnableConnect(Connected: Boolean);
begin
if Connected then begin
btConnect.Enabled := False;
btDisconnect.Enabled := True;
laStatus.Caption := 'Connected';
end else begin
btConnect.Enabled := True;
btDisconnect.Enabled := False;
laStatus.Caption := 'Disconnected';
end;
end;
procedure TfmMain.EnablePlay;
var
Attached: Boolean;
begin
Attached := (FMotor1 <> nil) or (FMotor2 <> nil);
laCurrentTitle.Enabled := Attached;
laCurrent.Enabled := Attached;
laMA.Enabled := Attached;
laVoltageTitle.Enabled := Attached;
laVoltage.Enabled := Attached;
laMV.Enabled := Attached;
if not Attached then begin
laCurrent.Caption := '0';
laVoltage.Caption := '0';
laHighCurrent.Visible := False;
laLowVoltage.Visible := False;
end;
end;
procedure TfmMain.EnablePlay1(Attached: Boolean);
begin
if Attached then
laIoState1.Caption := 'Attached'
else
laIoState1.Caption := 'Dectahed';
laDirection1.Enabled := Attached;
cbDirection1.Enabled := Attached;
laPower1.Enabled := Attached;
edPower1.Enabled := Attached;
btStart1.Enabled := Attached;
btBrake1.Enabled := Attached;
btDrift1.Enabled := Attached;
EnablePlay;
end;
procedure TfmMain.EnablePlay2(Attached: Boolean);
begin
if Attached then
laIoState2.Caption := 'Attached'
else
laIoState2.Caption := 'Dectahed';
laDirection2.Enabled := Attached;
cbDirection2.Enabled := Attached;
laPower2.Enabled := Attached;
edPower2.Enabled := Attached;
btStart2.Enabled := Attached;
btBrake2.Enabled := Attached;
btDrift2.Enabled := Attached;
EnablePlay;
end;
procedure TfmMain.FCurrent_OnCurrentChanged(Sender: TObject);
begin
if FCurrent <> nil then
laCurrent.Caption := FloatToStr(FCurrent.Current);
end;
procedure TfmMain.FHub_OnConnected(Sender: TObject; Error: Integer);
begin
if Error <> WCL_E_SUCCESS then begin
ShowMessage('Connect failed: 0x' + IntToHex(Error, 8));
EnableConnect(False);
FManager.Close;
end else
EnableConnect(True);
end;
procedure TfmMain.FHub_OnDeviceAttached(Sender: TObject; Device: TwclWeDoIo);
begin
// This demo supports only single motor.
if Device.DeviceType = iodMotor then begin
if FMotor1 = nil then begin
FMotor1 := TwclWeDoMotor(Device);
EnablePlay1(True);
end else begin
if FMotor2 = nil then begin
FMotor2 := TwclWeDoMotor(Device);
EnablePlay2(True);
end
end;
end;
if FCurrent = nil then begin
if Device.DeviceType = iodCurrentSensor then begin
FCurrent := TwclWeDoCurrentSensor(Device);
FCurrent.OnCurrentChanged := FCurrent_OnCurrentChanged;
end;
end;
if FVoltage = nil then begin
if Device.DeviceType = iodVoltageSensor then begin
FVoltage := TwclWeDoVoltageSensor(Device);
FVoltage.OnVoltageChanged := FVoltage_OnVoltageChanged;
end;
end;
end;
procedure TfmMain.FHub_OnDeviceDetached(Sender: TObject; Device: TwclWeDoIo);
begin
if (Device.DeviceType = iodMotor) then begin
if (FMotor1 <> nil) and (Device.ConnectionId = FMotor1.ConnectionId) then begin
FMotor1 := nil;
EnablePlay1(False);
end;
if (FMotor2 <> nil) and (Device.ConnectionId = FMotor2.ConnectionId) then begin
FMotor2 := nil;
EnablePlay2(False);
end;
end;
if Device.DeviceType = iodCurrentSensor then
FCurrent := nil;
if Device.DeviceType = iodVoltageSensor then
FVoltage := nil;
end;
procedure TfmMain.FHub_OnDisconnected(Sender: TObject; Reason: Integer);
begin
EnableConnect(False);
FManager.Close;
end;
procedure TfmMain.FHub_OnHighCurrentAlert(Sender: TObject; Alert: Boolean);
begin
laHighCurrent.Visible := Alert;
end;
procedure TfmMain.FHub_OnLowVoltageAlert(Sender: TObject; Alert: Boolean);
begin
laLowVoltage.Visible := Alert;
end;
procedure TfmMain.FormCreate(Sender: TObject);
begin
cbDirection1.ItemIndex := 0;
cbDirection2.ItemIndex := 0;
FManager := TwclBluetoothManager.Create(nil);
FWatcher := TwclWeDoWatcher.Create(nil);
FWatcher.OnHubFound := FWatcher_OnHubFound;
FHub := TwclWeDoHub.Create(nil);
FHub.OnConnected := FHub_OnConnected;
FHub.OnDisconnected := FHub_OnDisconnected;
FHub.OnDeviceAttached := FHub_OnDeviceAttached;
FHub.OnDeviceDetached := FHub_OnDeviceDetached;
FHub.OnHighCurrentAlert := FHub_OnHighCurrentAlert;
FHub.OnLowVoltageAlert := FHub_OnLowVoltageAlert;
FMotor1 := nil;
FMotor2 := nil;
FCurrent := nil;
FVoltage := nil;
PageControl.ActivePageIndex := 0;
end;
procedure TfmMain.FormDestroy(Sender: TObject);
begin
Disconnect;
FManager.Free;
FWatcher.Free;
FHub.Free;
end;
procedure TfmMain.FVoltage_OnVoltageChanged(Sender: TObject);
begin
if FVoltage <> nil then
laVoltage.Caption := FloatToStr(FVoltage.Voltage);
end;
procedure TfmMain.FWatcher_OnHubFound(Sender: TObject; Address: Int64;
Name: string);
var
Radio: TwclBluetoothRadio;
Res: Integer;
begin
Radio := FWatcher.Radio;
FWatcher.Stop;
Res := FHub.Connect(Radio, Address);
if Res <> WCL_E_SUCCESS then begin
ShowMessage('Connect failed: 0x' + IntToHex(Res, 8));
EnableConnect(False);
end else
laStatus.Caption := 'Connecting';
end;
procedure TfmMain.btBrake2Click(Sender: TObject);
var
Res: Integer;
begin
if FMotor2 = nil then
ShowMessage('Device is not attached')
else begin
Res := FMotor2.Brake;
if Res <> WCL_E_SUCCESS then
ShowMessage('Brake motor failed: 0x' + IntToHex(Res, 8));
end;
end;
procedure TfmMain.btDrift2Click(Sender: TObject);
var
Res: Integer;
begin
if FMotor2 = nil then
ShowMessage('Device is not attached')
else begin
Res := FMotor2.Drift;
if Res <> WCL_E_SUCCESS then
ShowMessage('Drift motor failed: 0x' + IntToHex(Res, 8));
end;
end;
end.
|
unit UCC_Utils_Chart;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted 2006-2012 by Bradford Technologies, Inc. }
{ This unit has objects for creating histograms of property features, such as}
{ the distribution of sale prices, bedrooms, GLA and Site area. The values}
{ come form a list of properties in a grid, but they can be added in using }
{ the Add function. If the subject is going to be shown in the histogram, it}
{ needs to be set initially so that ranges and distribution can be calculated}
{correctly.}
interface
uses
Windows, Classes, ExtCtrls, Contnrs,
Grids_ts, TSGrid, osAdvDbGrid, Graphics,
TeEngine, Series, TeeProcs, Chart,
UFileUtils;
type
TIntegerRange = class(TObject)
private
FVal: array of integer;
FBarVal: array of integer;
FBarTitle: array of string;
FCount: Integer;
FHigh: Integer;
FLow: Integer;
FPred: Integer;
FRangeLow: Integer;
FRangeHigh: Integer;
FDelta: Real;
FSpread: Real;
FBarCount: Integer;
FAllowZero: Boolean;
FShowBarTitle: Boolean;
FShowSubject: Boolean;
FSubjectValue: Integer;
FSubjectPosition: Integer;
procedure ReadFromStream(AStream: TStream);
procedure WriteToStream(AStream: TStream);
procedure SetSubjectValue(Value: Integer); virtual;
public
constructor Create(itemCount: Integer);
destructor Destroy; override;
procedure Add(value: Integer);
procedure CalcRange;
procedure CalcSpread; virtual;
procedure CalcDistribution; virtual;
procedure CalcPredominant; virtual;
procedure CalcSubjectPosition; virtual;
procedure DoCalcs;
procedure LoadValues(AGrid: TosAdvDbgrid; valueCol, includeCol, typeCol: Integer; typeStr: String);
procedure SetChartSeries(ASeries: TBarSeries; AColor: TColor);
procedure SetChartSeries2(ASeries: TBarSeries; AColor, SubjectColor: TColor);
procedure SetSubjectChartSeries(SubjectBar: TBarSeries; AColor: TColor);
procedure GetHighLowValues(var valLo, valHi: Integer);
// procedure GetHighLowPredValues(var valLo, valHi, valPred: Integer; useThousands: Boolean=False);
procedure GetHighLowPredValues(var valLo, valHi, valPred: Integer; useThousands: Boolean=False; useHundred: Boolean = False);
property Count: Integer read FCount write FCount;
property High: Integer read FHigh write FHigh;
property Low: Integer read FLow write FLow;
property Pred: Integer read FPred write FPred;
property AllowZero: Boolean read FAllowZero write FAllowZero;
property ShowBarCount: Boolean read FShowBarTitle write FShowBarTitle;
property BarCount: Integer read FBarCount write FBarCount;
property SubjectValue: Integer read FSubjectValue write SetSubjectValue;
end;
TItemPriceChart = class(TIntegerRange)
procedure CalcSpread; override;
procedure CalcDistribution; override;
end;
TItemCountChart = class(TIntegerRange)
procedure CalcSpread; override;
procedure CalcDistribution; override;
procedure CalcSubjectPosition; override;
end;
TItemAreaChart = class(TItemPriceChart)
procedure CalcDistribution; override;
end;
TItemAgeChart = class(TIntegerRange)
procedure CalcDistribution; override;
procedure CalcSpread; override;
procedure CalcSubjectPosition; override;
end;
TDoubleRange = class(TObject)
private
FVal: array of double;
// FBarVal: array of integer;
FBarVal: array of Double;
FBarTitle: array of string;
FCount: Integer;
FHigh: double;
FLow: double;
FPred: double;
FRangeLow: double;
FRangeHigh: double;
FDelta: double;
FSpread: double;
FBarCount: Integer;
FAllowZero: Boolean;
FShowBarTitle: Boolean;
FShowSubject: Boolean;
FSubjectValue: double;
FSubjectPosition: Integer;
procedure ReadFromStream(AStream: TStream);
procedure WriteToStream(AStream: TStream);
procedure SetSubjectValue(Value: Double); virtual;
public
constructor Create(itemCount: Integer);
destructor Destroy; override;
procedure Add(value: Double);
procedure CalcRange; virtual;
procedure CalcSpread; virtual;
procedure CalcDistribution; virtual;
procedure CalcSubjectPosition; virtual;
procedure CalcPredominant; virtual;
procedure DoCalcs;
procedure LoadValues(AGrid: TosAdvDbgrid; valueCol, includeCol, typeCol: Integer; typeStr: String);
procedure SetChartSeries(ASeries: TBarSeries; AColor: TColor); virtual;
procedure SetChartSeries2(ASeries: TBarSeries; AColor, SubjectColor: TColor); virtual;
procedure SetSubjectChartSeries(SubjectBar: TBarSeries; AColor: TColor);
procedure GetHighLowValues(var valLo, valHi: Double);
procedure GetHighLowPredValues(var valLo, valHi, valPred: Double);
property Count: Integer read FCount write FCount;
property High: double read FHigh write FHigh;
property Low: double read FLow write FLow;
property AllowZero: Boolean read FAllowZero write FAllowZero;
property ShowBarTitle: Boolean read FShowBarTitle write FShowBarTitle;
property BarCount: Integer read FBarCount write FBarCount;
property SubjectValue: double read FSubjectValue write SetSubjectValue;
end;
TBathCountChart = class(TDoubleRange)
procedure SetSubjectValue(Value: Double); override;
procedure CalcRange; override;
procedure CalcSpread; override;
procedure CalcDistribution; override;
procedure CalcSubjectPosition; override;
end;
TBellCurveChart = class(TDoubleRange)
procedure CalcSpread; override;
procedure CalcDistribution; override;
end;
TDateRange = class(TObject)
private
FVal: array of TDateTime;
FCount: Integer;
FHigh: TDateTime;
FLow: TDateTime;
function GetHighDate: String;
function GetLowDate: String;
// procedure ReadFromStream(AStream: TStream);
// procedure WriteToStream(AStream: TStream);
public
constructor Create(itemCount: Integer);
destructor Destroy; override;
procedure Add(dateStr: String);
procedure LoadValues(AGrid: TosAdvDbgrid; valueCol, includeCol, typeCol: Integer; typeStr: String);
procedure CalcRange;
property Count: Integer read FCount write FCount;
property High: String read GetHighDate;
property Low: String read GetLowDate;
end;
TSimpleChart = class(TObject)
private
FXVal: array of integer;
FYVal: array of integer;
FTitle: array of string;
FCount: Integer;
FAllowZero: Boolean;
FShowTitle: Boolean;
public
constructor Create(itemCount: Integer);
destructor Destroy; override;
procedure SetBarSeries(ASeries: TBarSeries; AColor: TColor);
procedure SetLineSeries(ASeries: TLineSeries; AColor: TColor);
procedure LoadValues(xList, yList: String);
procedure GetMarkText(Sender: TChartSeries;ValueIndex: Integer; var MarkText: String);
property ShowTitle: Boolean read FShowTitle write FShowTitle;
property Count: Integer read FCount write FCount;
end;
{------------------------------------------------------------------}
{ IMPLEMENTATION BEGINS HERE }
{------------------------------------------------------------------}
implementation
uses
SysUtils,DateUtils,Math,
UGlobals, UUtil1, UStatus, UCC_Utils;
{ TIntegerRange }
constructor TIntegerRange.Create(itemCount: Integer);
begin
inherited create;
FShowBarTitle := True;
FShowSubject := False;
FSubjectPosition := -1;
FCount := 0;
FBarCount := 10; //undo github #522
if itemCount > 0 then
SetLength(FVal, itemCount);
end;
destructor TIntegerRange.Destroy;
begin
FVal := nil;
FBarVal := nil;
FBarTitle := nil;
inherited;
end;
procedure TIntegerRange.ReadFromStream(AStream: TStream);
begin
FHigh := ReadLongFromStream(AStream);
FLow := ReadLongFromStream(AStream);
FPred := ReadLongFromStream(AStream);
end;
procedure TIntegerRange.WriteToStream(AStream: TStream);
begin
WriteLongToStream(FHigh, AStream);
WriteLongToStream(FLow, AStream);
WriteLongToStream(FPred, AStream);
end;
procedure TIntegerRange.SetSubjectValue(Value: Integer);
begin
FShowSubject := True;
FSubjectValue := Value;
end;
procedure TIntegerRange.Add(value: Integer);
begin
if (value = 0) and not FAllowZero then
exit;
FCount := FCount + 1;
if FCount > length(FVal) then
SetLength(FVal, FCount);
FVal[FCount-1] := Value;
end;
procedure TIntegerRange.CalcRange;
var
mx,mn: integer;
begin
if FCount = 0 then //Handle 0 count
begin
FHigh := 0;
FLow := 0;
Exit;
end;
FHigh := -99999999;
for mx := 0 to FCount-1 do
if FVal[mx] > FHigh then
FHigh := FVal[mx];
FLow := FHigh;
for mn := 0 to FCount-1 do
if (FVal[mn] < FLow) then
FLow:= FVal[mn];
if FShowSubject then //make sure subject is in range
begin
if FSubjectValue < FLow then
FLow := FSubjectValue;
if FSubjectValue > FHigh then
FHigh := FSubjectValue;
end;
end;
procedure TIntegerRange.CalcSpread;
begin
// FDelta := (FHigh - FLow)/FBarCount;
FDelta := Round((FHigh - FLow)/FBarCount);
// FRangeLow := round((FLow - (0.5 * FDelta))/10)*10; //github #504
FRangeLow := FLow - round(((0.5 * FDelta)/10)*10);
// FRangeHigh := round((FHigh + (0.5 * FDelta))/10)*10;
FRangeHigh := FHigh + Round(((0.5 * FDelta)/10)*10);
FSpread := (FRangeHigh - FRangeLow)/FBarCount;
SetLength(FBarVal, FBarCount);
SetLength(FBarTitle, FBarCount);
end;
procedure TIntegerRange.CalcDistribution;
var
i, n, bCount: Integer;
aVal, totalVal: Integer;
Level1, Level2: Real;
begin
Level2 := FRangeLow;
if FCount = 0 then Exit; //Handle 0 count
for i := 1 to FBarCount do
begin
Level1 := Level2;
Level2 := Level2 + FSpread;
totalVal := 0;
bCount := 0;
for n := 0 to FCount-1 do
begin
aVal := FVal[n];
// shownotice(floattostr(Level1) + ' --- '+ IntTostr(aVal)+ ' --- '+ floattostr(Level2));
if (Level1 <= aVal) and (aVal < Level2) then
begin
// beep;
bCount := bCount + 1;
totalVal := totalVal + aVal;
end
end;
//create the bar column values and title
if bCount > 0 then
begin
FBarVal[i-1] := bCount;
FBarTitle[i-1] := IntToStr(Round(totalVal/bCount));
end
else //could be no ages in this bracket
begin
FBarVal[i-1] := 0;
FBarTitle[i-1] := IntToStr(Trunc((Level1 + Level2)/2));
end;
end;
end;
procedure TIntegerRange.CalcPredominant;
var
n,nCount,idx: Integer;
HiBar: Integer;
begin
idx := 0;
HiBar := -99999;
nCount := Length(FBarVal);
for n := 0 to nCount-1 do
if FBarVal[n] > HiBar then
begin
HiBar := FBarVal[n]; //get bar with most counts
idx := n;
end;
FPred := 0;
if idx < nCount then
FPred := StrToIntDef(FBarTitle[idx], 0);
end;
//in what histogram bar is the subject located
procedure TIntegerRange.CalcSubjectPosition;
var
n: Integer;
Level1, Level2: Real;
begin
if FShowSubject then
begin
Level2 := FRangeLow;
for n := 1 to FBarCount do
begin
Level1 := Level2;
Level2 := Level2 + FSpread;
if (Level1 <= FSubjectValue) and (FSubjectValue < Level2) then
begin
FSubjectPosition := n-1;
break;
end;
end;
end;
end;
procedure TIntegerRange.DoCalcs;
begin
if FCount > 0 then
begin
CalcRange;
CalcSpread;
CalcDistribution;
CalcPredominant;
CalcSubjectPosition;
end;
end;
procedure TIntegerRange.LoadValues(AGrid: TosAdvDbgrid; valueCol, includeCol, typeCol: Integer; typeStr: String);
var
n, rowCount: integer;
value: Integer;
countIt: Boolean;
begin
FCount := 0;
rowCount := AGrid.rows;
Setlength(FVal, rowCount);
for n := 0 to rowCount-1 do
if (AGrid.Cell[includeCol, n+1] = 1) then //only add if its included (need to test for this column)
begin
countIt := typeStr = ''; //there no data type separator
if not countIt then //if there is one...
countIt := (CompareText(AGrid.Cell[typeCol, n+1], typeStr) = 0); //countIt only if there is a match
if countIt then
begin
value := GetValidInteger(AGrid.Cell[valueCol, n+1]);
if (value = 0) and not FAllowZero then
continue;
FVal[FCount] := Value; //FCount is zero based
FCount := FCount + 1;
end;
end;
end;
procedure TIntegerRange.SetChartSeries(ASeries: TBarSeries; AColor: TColor);
var
n: integer;
begin
ASeries.Clear;
for n := 0 to FBarCount-1 do
if FShowBarTitle then
ASeries.AddY(FBarVal[n], FBarTitle[n], AColor)
else
ASeries.AddY(FBarVal[n], '', AColor);
end;
procedure TIntegerRange.SetChartSeries2(ASeries: TBarSeries; AColor, SubjectColor: TColor);
var
n: integer;
begin
ASeries.Clear;
for n := 0 to FBarCount-1 do
begin
if n = FSubjectPosition then
begin
if FShowBarTitle then
ASeries.AddY(FBarVal[n], FBarTitle[n], SubjectColor)
else
ASeries.AddY(FBarVal[n], '', SubjectColor);
end
else
begin
if FShowBarTitle then
ASeries.AddY(FBarVal[n], FBarTitle[n], AColor)
else
ASeries.AddY(FBarVal[n], '', AColor);
end;
end;
end;
procedure TIntegerRange.SetSubjectChartSeries(SubjectBar: TBarSeries; AColor: TColor);
var
n: integer;
begin
SubjectBar.Clear;
for n := 0 to FBarCount-1 do
if n = FSubjectPosition then
begin
if FBarVal[n] = 0 then //if the subject value is 0, raise it up a bit
FBarVal[n] := Max(3, Round(FHigh * 0.25));
SubjectBar.AddY(FBarVal[n],'', AColor);
end
else
SubjectBar.AddY(0,'', AColor);
end;
procedure TIntegerRange.GetHighLowValues(var valLo, valHi: Integer);
begin
valLo := Low;
valHi := High;
end;
procedure TIntegerRange.GetHighLowPredValues(var valLo, valHi, valPred: Integer; useThousands: Boolean=False; useHundred: Boolean=False);
begin
valLo := Low;
valHi := High;
valPred := Pred;
if useThousands then
valPred := Pred * 1000
else if useHundred then //github #212
valPred := Pred * 100;
end;
{ TDoubleRange }
constructor TDoubleRange.Create(itemCount: Integer);
begin
inherited create;
FShowBarTitle := True;
FShowSubject := False;
FSubjectPosition := -1;
FCount := 0;
FBarCount := 10;
SetLength(FVal, itemCount);
end;
destructor TDoubleRange.Destroy;
begin
FVal := nil;
inherited;
end;
procedure TDoubleRange.ReadFromStream(AStream: TStream);
begin
FHigh := ReadDoubleFromStream(AStream);
FLow := ReadDoubleFromStream(AStream);
FPred := ReadDoubleFromStream(AStream);
end;
procedure TDoubleRange.WriteToStream(AStream: TStream);
begin
WriteDoubleToStream(FHigh, AStream);
WriteDoubleToStream(FLow, AStream);
WriteDoubleToStream(FPred, AStream);
end;
procedure TDoubleRange.Add(value: Double);
begin
if (value = 0) and not AllowZero then
exit;
FCount := FCount + 1;
if FCount > length(FVal) then
SetLength(FVal, FCount);
FVal[FCount-1] := Value;
end;
procedure TDoubleRange.CalcRange;
var
mx,mn: integer;
begin
if FCount = 0 then
begin
FHigh := 0;
FLow := 0;
Exit;
end;
FHigh := -99999999;
for mx := 0 to FCount-1 do
if FVal[mx] > FHigh then
FHigh := FVal[mx];
FLow := FHigh;
for mn := 0 to FCount-1 do
if (FVal[mn] < FLow) then
FLow:= FVal[mn];
if FShowSubject then //make sure subject is in range
begin
if FSubjectValue < FLow then
FLow := FSubjectValue;
if FSubjectValue > FHigh then
FHigh := FSubjectValue;
end;
end;
procedure TDoubleRange.CalcPredominant;
var
n,nCount,idx: Integer;
HiBar: Double;
begin
idx := 0;
HiBar := -99999;
nCount := Length(FBarVal);
for n := 0 to nCount-1 do
if FBarVal[n] > HiBar then
begin
HiBar := FBarVal[n]; //get bar with most counts
idx := n;
end;
FPred := 0;
if idx < nCount then
FPred := StrToFloatDef(FBarTitle[idx], 0);
end;
procedure TDoubleRange.CalcSpread;
begin
// FDelta := (FHigh - FLow)/FBarCount;
FDelta := Round((FHigh - FLow)/FBarCount);
// FRangeLow := round((FLow - (0.5 * FDelta))/10)*10;
FRangeLow := FLow - Round(((0.5 * FDelta)/10)*10); //github #504
// FRangeHigh := round((FHigh + (0.5 * FDelta))/10)*10;
FRangeHigh := FHigh + Round(((0.5 * FDelta)/10)*10);
FSpread := (FRangeHigh - FRangeLow)/FBarCount;
SetLength(FBarVal, FBarCount);
SetLength(FBarTitle, FBarCount);
end;
procedure TDoubleRange.CalcDistribution;
var
i, n, bCount: Integer;
aVal, totalVal: Double;
Level1, Level2: Double;
begin
Level2 := FRangeLow;
for i := 1 to FBarCount do
begin
Level1 := Level2;
Level2 := Level2 + FSpread;
totalVal := 0;
bCount := 0;
for n := 0 to FCount-1 do
begin
aVal := FVal[n];
if (Level1 <= aVal) and (aVal < Level2) then
begin
bCount := bCount + 1;
totalVal := totalVal + aVal;
end
end;
//create the bar column values and title
if bCount > 0 then
begin
FBarVal[i-1] := bCount;
FBarTitle[i-1] := IntToStr(Round(totalVal/bCount));
end
else //could be no ages in this bracket
begin
FBarVal[i-1] := 0;
FBarTitle[i-1] := IntToStr(Trunc((Level1 + Level2)/2));
end;
end;
end;
procedure TDoubleRange.SetSubjectValue(Value: Double);
begin
FShowSubject := True;
FSubjectValue := Value;
end;
procedure TDoubleRange.CalcSubjectPosition;
var
n: Integer;
Level1, Level2: Real;
begin
if FShowSubject then
begin
Level2 := FRangeLow;
for n := 1 to FBarCount do
begin
Level1 := Level2;
Level2 := Level2 + FSpread;
if (Level1 <= FSubjectValue) and (FSubjectValue < Level2) then
begin
FSubjectPosition := n-1;
break;
end;
end;
if FSubjectPosition = -1 then
FSubjectPosition := 0;
end;
end;
procedure TDoubleRange.DoCalcs;
begin
if FCount > 0 then
begin
CalcRange;
CalcSpread;
CalcDistribution;
CalcPredominant; //need to calculate predom for double
CalcSubjectPosition;
end;
end;
procedure TDoubleRange.LoadValues(AGrid: TosAdvDbgrid; valueCol, includeCol, typeCol: Integer; typeStr: String);
var
n, rowCount: integer;
value: Double;
countIt: Boolean;
begin
FCount := 0;
rowCount := AGrid.rows;
Setlength(FVal, rowCount);
for n := 0 to rowCount-1 do
if (AGrid.Cell[includeCol, n+1] = 1) then
begin
countIt := typeStr = ''; //count it if there no data type identifier
if not countIt then //if there is one...
countIt := (CompareText(AGrid.Cell[typeCol, n+1], typeStr) = 0); //countIt only if there is a match
if countIt then
begin
value := GetValidNumber(AGrid.Cell[valueCol, n+1]);
if (value = 0) and not FAllowZero then
continue;
FVal[FCount] := Value; //FCount is zero based
FCount := FCount + 1;
end;
end;
end;
procedure TDoubleRange.SetChartSeries(ASeries: TBarSeries; AColor: TColor);
var
n: integer;
begin
ASeries.Clear;
for n := 0 to FBarCount-1 do
if FShowBarTitle then
ASeries.AddY(FBarVal[n], FBarTitle[n], AColor)
else
ASeries.AddY(FBarVal[n], '', AColor);
end;
procedure TDoubleRange.SetChartSeries2(ASeries: TBarSeries; AColor, SubjectColor: TColor);
var
n: integer;
begin
ASeries.Clear;
for n := 0 to FBarCount-1 do
begin
if n = FSubjectPosition then
begin
if FShowBarTitle then
ASeries.AddY(FBarVal[n], FBarTitle[n], SubjectColor)
else
ASeries.AddY(FBarVal[n], '', SubjectColor);
end
else
begin
if FShowBarTitle then
ASeries.AddY(FBarVal[n], FBarTitle[n], AColor)
else
ASeries.AddY(FBarVal[n], '', AColor);
end;
end;
end;
procedure TDoubleRange.SetSubjectChartSeries(SubjectBar: TBarSeries; AColor: TColor);
var
n:integer;
begin
SubjectBar.Clear;
for n := 0 to FBarCount-1 do
if n = FSubjectPosition then
begin
if FBarVal[n] = 0 then //if the subject value is 0, raise it up a bit
FBarVal[n] := Max(5, Round(FHigh * 0.25)); //10;
SubjectBar.AddY(FBarVal[n],'', AColor);
end
else
SubjectBar.AddY(0,'', AColor);
end;
procedure TDoubleRange.GetHighLowValues(var valLo, valHi: Double);
begin
valLo := Low;
valHi := High;
end;
procedure TDoubleRange.GetHighLowPredValues(var valLo, valHi, valPred: Double);
begin
valLo := FLow;
valHi := FHigh;
valPred := FPred;
end;
{ TItemPriceChart }
procedure TItemPriceChart.CalcDistribution;
var
i, n, bCount: Integer;
aVal, totalVal: Integer;
Level1, Level2: Real;
begin
if FCount = 0 then exit;
Level2 := FRangeLow;
for i := 1 to FBarCount do
begin
Level1 := Level2;
Level2 := Level2 + FSpread;
totalVal := 0;
bCount := 0;
for n := 0 to FCount-1 do
begin
aVal := FVal[n];
if (Level1 <= aVal) and (aVal < Level2) then
begin
bCount := bCount + 1;
totalVal := totalVal + aVal;
end
end;
//create the bar column values and title
if bCount > 0 then
begin
FBarVal[i-1] := bCount;
FBarTitle[i-1] := IntToStr(Trunc((totalVal/bCount)/1000));
end
else //could be no ages in this bracket
begin
FBarVal[i-1] := 0;
FBarTitle[i-1] := IntToStr(Trunc((Level1 + Level2)/2000)); //divide by 1000 for price, divide by 2 for average
end;
end;
end;
procedure TItemPriceChart.CalcSpread;
begin
// FDelta := (FHigh - FLow)/FBarCount; //github #504
FDelta := Round((FHigh - FLow)/FBarCount);
// FRangeLow := round((FLow - (0.5 * FDelta))/100)*100;
FRangeLow := FLow - Round(((0.5 * FDelta)/100)*100); //github #504
// FRangeHigh := Round(FHigh + (0.5 * FDelta))/100)*100;
FRangeHigh := FHigh + round(((0.5 * FDelta)/100)*100);
FSpread := (FRangeHigh - FRangeLow)/FBarCount;
SetLength(FBarVal, FBarCount);
SetLength(FBarTitle, FBarCount);
end;
{ TBedRoomCountChart }
procedure TItemCountChart.CalcDistribution;
var
i, n, bCount, numBeds: Integer;
begin
FBarCount := (FHigh - FLow) + 1;
numBeds := FLow;
SetLength(FBarVal, FBarCount);
SetLength(FBarTitle, FBarCount);
for i := 1 to FBarCount do
begin
bCount := 0;
for n := 0 to FCount-1 do
if FVal[n] = numBeds then
bCount := bCount + 1;
//create the bar column values and title
if bCount > 0 then
begin
FBarVal[i-1] := bCount;
FBarTitle[i-1] := IntToStr(numBeds);
end
else //could be no ages in this bracket
begin
FBarVal[i-1] := 0;
FBarTitle[i-1] := IntToStr(numBeds);
end;
numBeds := numBeds + 1;
end;
end;
procedure TItemCountChart.CalcSubjectPosition;
var
n, aItemVal: Integer;
begin
if FShowSubject then
begin
for n := 1 to FBarCount do
begin
aItemVal := StrToInt(FBarTitle[n-1]);
if FSubjectValue = aItemVal then
begin
FSubjectPosition := n-1;
break;
end;
end;
end;
end;
procedure TItemCountChart.CalcSpread;
begin
//do nothing for simple items
end;
{ TItemAreaChart }
procedure TItemAreaChart.CalcDistribution;
var
i, n, bCount: Integer;
aVal, totalVal: Integer;
Level1, Level2: Real;
begin
Level2 := FRangeLow;
for i := 1 to FBarCount do
begin
Level1 := Level2;
Level2 := Level2 + FSpread;
totalVal := 0;
bCount := 0;
for n := 0 to FCount-1 do
begin
aVal := FVal[n];
if (Level1 <= aVal) and (aVal < Level2) then
begin
bCount := bCount + 1;
totalVal := totalVal + aVal;
end
end;
//create the bar column values and title
if bCount > 0 then
begin
FBarVal[i-1] := bCount;
FBarTitle[i-1] := IntToStr(Trunc((totalVal/bCount)/100)); //average of all values in this column
end
else //could be no ages in this bracket
begin
FBarVal[i-1] := 0;
FBarTitle[i-1] := IntToStr(Trunc((Level1 + Level2)/200)); //divide by 100 for area, divide by 2 for average
end;
end;
end;
{ TBathCountChart }
procedure TBathCountChart.SetSubjectValue(Value: Double);
begin
FShowSubject := True;
FSubjectValue := RoundBathCount(Value);
end;
procedure TBathCountChart.CalcRange;
begin
inherited;
FHigh := RoundBathCount(FHigh);
FLow := RoundBathCount(FLow);
end;
procedure TBathCountChart.CalcDistribution;
var
i, n, bCount: Integer;
numBaths: Double;
begin
FBarCount := round((FHigh - FLow)/0.5) + 1;
numBaths := FLow;
SetLength(FBarVal, FBarCount);
SetLength(FBarTitle, FBarCount);
for i := 1 to FBarCount do
begin
bCount := 0;
for n := 0 to FCount-1 do
if FVal[n] = numBaths then
bCount := bCount + 1;
//create the bar column values and title
if bCount > 0 then
begin
FBarVal[i-1] := bCount;
FBarTitle[i-1] := FormatValue2(numBaths, bRnd1P1, True);
end
else //could be no baths in this bracket
begin
FBarVal[i-1] := 0;
FBarTitle[i-1] := FormatValue2(numBaths, bRnd1P2, True);
end;
numBaths := numBaths + 0.5;
end;
end;
procedure TBathCountChart.CalcSubjectPosition;
var
n: Integer;
aItemVal : Double;
begin
if FShowSubject then
begin
for n := 1 to FBarCount do
begin
aItemVal := StrToFloat(FBarTitle[n-1]);
if FSubjectValue = aItemVal then
begin
FSubjectPosition := n-1;
break;
end;
end;
end;
end;
procedure TBathCountChart.CalcSpread;
begin
//do nothing for baths
end;
{ TItemAgeChart }
procedure TItemAgeChart.CalcDistribution;
var
i, n, bCount, thisAge: Integer;
begin
if (FHigh - FLow) > 9 then
inherited
else
begin
FBarCount := (FHigh - FLow) + 1;
thisAge := FLow;
SetLength(FBarVal, FBarCount);
SetLength(FBarTitle, FBarCount);
for i := 1 to FBarCount do
begin
bCount := 0;
for n := 0 to FCount-1 do
if FVal[n] = thisAge then
bCount := bCount + 1;
//create the bar column values and title
if bCount > 0 then
begin
FBarVal[i-1] := bCount;
FBarTitle[i-1] := IntToStr(thisAge);
end
else //could be no ages in this bracket
begin
FBarVal[i-1] := 0;
FBarTitle[i-1] := IntToStr(thisAge);
end;
thisAge := thisAge + 1;
end;
end;
end;
procedure TItemAgeChart.CalcSpread;
begin
if (FHigh - FLow) > 9 then //spread needs to be 10 or more
begin
// FDelta := (FHigh - FLow)/FBarCount;
FDelta := Round((FHigh - FLow)/FBarCount);
// FRangeLow := Round(FLow - (0.5 * FDelta));
FRangeLow := FLow - Round(0.5 * FDelta); //github #504
// FRangeHigh := Round(FHigh + (0.5 * FDelta));
FRangeHigh := FHigh + Round(0.5 * FDelta);
FSpread := (FRangeHigh - FRangeLow)/FBarCount;
SetLength(FBarVal, FBarCount);
SetLength(FBarTitle, FBarCount);
end;
// inherited; //to use inherited Spread Calcs
{else do nothing, we have less than 10 yr spread}
end;
procedure TItemAgeChart.CalcSubjectPosition;
var
n, thisAge: Integer;
begin
if (FHigh - FLow) > 9 then
inherited
else if FShowSubject then
for n := 1 to FBarCount do
begin
thisAge := StrToInt(FBarTitle[n-1]);
if FSubjectValue = thisAge then
begin
FSubjectPosition := n-1;
break;
end;
end;
end;
{ TDateRange }
constructor TDateRange.Create(itemCount: Integer);
begin
inherited create;
FCount := 0;
SetLength(FVal, itemCount); //set the storage
end;
destructor TDateRange.Destroy;
begin
FVal := nil; //delete the storage
inherited;
end;
procedure TDateRange.Add(dateStr: String);
var
ADate: TDateTime;
begin
if IsValidDateTime(dateStr, ADate) then
begin
FCount := FCount + 1;
if FCount > length(FVal) then
SetLength(FVal, FCount);
FVal[FCount-1] := ADate;
end;
end;
procedure TDateRange.CalcRange;
var
mx,mn: integer;
begin
FHigh := StrToDate('1/1/1600');
for mx := 0 to FCount-1 do
if (CompareDate(FVal[mx], FHigh) = 1) then //greater than
FHigh := FVal[mx];
FLow := FHigh;
for mn := 0 to FCount-1 do
if (CompareDate(FVal[mn], FLow) <> 1) then //equal or less than
FLow:= FVal[mn];
end;
procedure TDateRange.LoadValues(AGrid: TosAdvDbgrid; valueCol, includeCol,
typeCol: Integer; typeStr: String);
var
n, rowCount: integer;
ADate: TDateTime;
countIt: Boolean;
begin
FCount := 0;
rowCount := AGrid.rows;
Setlength(FVal, rowCount);
for n := 0 to rowCount-1 do
if (AGrid.Cell[includeCol, n+1] = 1) then //only add if its included (need to test for this column)
begin
countIt := typeStr = ''; //there no data type separator
if not countIt then //if there is one...
countIt := (CompareText(AGrid.Cell[typeCol, n+1], typeStr) = 0); //countIt only if there is a match
if countIt then
if IsValidDateTime(AGrid.Cell[valueCol, n+1], ADate) then
begin
FVal[FCount] := ADate; //FCount is zero based
FCount := FCount + 1;
end;
end;
end;
function TDateRange.GetHighDate: String;
begin
result := DateToStr(FHigh);
end;
function TDateRange.GetLowDate: String;
begin
result := DateToStr(FLow);
end;
{ TBellCurveChart }
procedure TBellCurveChart.CalcSpread;
begin
FDelta := (FHigh - FLow)/FBarCount;
FRangeLow := 0.0;
FRangeHigh := 1.0;
FSpread := 1.0/(FBarCount/2); //this is increments
SetLength(FBarVal, FBarCount);
SetLength(FBarTitle, FBarCount);
end;
//calc distribution on one side then the other
procedure TBellCurveChart.CalcDistribution;
var
i, n, bCount, iCount: Integer;
aVal, totalVal: Double;
Level1, Level2: Double;
begin
iCount := Round(FBarCount/2);
//distribution on the left side of curve (negatives)
Level2 := FRangeLow;
for i := 1 to iCount do
begin
Level1 := Level2;
Level2 := Level2 - FSpread;
totalVal := 0;
bCount := 0;
for n := 0 to FCount-1 do
begin
aVal := FVal[n];
if (Level2 < aVal) and (aVal <= Level1) then
begin
bCount := bCount + 1;
totalVal := totalVal + aVal;
end
end;
//create the bar column values and title
FBarVal[i-1] := bCount;
FBarTitle[i-1] := IntToStr(bCount);
end;
//distribution on the right side of curve (positives)
Level2 := FRangeHigh;
iCount := iCount + 1;
for i := iCount to FBarCount-1 do
begin
Level1 := Level2;
Level2 := Level2 - FSpread;
totalVal := 0;
bCount := 0;
for n := 0 to FCount-1 do
begin
aVal := FVal[n];
if (Level1 >= aVal) and (aVal > Level2) then
begin
bCount := bCount + 1;
totalVal := totalVal + aVal;
end
end;
//create the bar column values and title
FBarVal[i-1] := bCount;
FBarTitle[i-1] := IntToStr(bCount);
end;
end;
constructor TSimpleChart.Create(itemCount: Integer);
begin
inherited create;
FShowTitle := True;
FCount := 0;
if itemCount > 0 then
begin
SetLength(FXVal, itemCount);
SetLength(FYVal, itemCount);
SetLength(FTitle, itemCount);
end;
end;
destructor TSimpleChart.Destroy;
begin
FXVal := nil;
FYVal := nil;
FTitle := nil;
inherited;
end;
procedure TSimpleChart.LoadValues(xList, yList: String);
var
rowCount: integer;
xValue, yValue: Integer;
sl1, sl2: TStringList;
i, j: Integer;
begin
sl1 := TStringList.Create;
sl2 := TStringList.Create;
try
sl1.commaText := xList;
sl2.CommaText := yList;
rowCount := sl1.count;
Setlength(FXVal, sl1.Count);
SetLength(FYVal, sl2.Count);
SetLength(FTitle, sl1.Count);
FCount := 0;
j := sl1.count;
for i:= 0 to rowCount-1 do
begin
xValue := GetValidInteger(sl1[i]);
yValue := GetValidInteger(sl2[i]);
FXVal[i] := xValue;
FYVal[i] := yValue;
if j = 1 then
FTitle[i] := 'Current Month'
else
FTitle[i] := Format('%d',[j]);
dec(j);
inc(FCount);
end;
finally
sl1.Free;
sl2.Free;
end;
end;
procedure TSimpleChart.GetMarkText(Sender: TChartSeries;ValueIndex: Integer; var MarkText: String);
begin
MarkText := Format('%d%%',[Round(Sender.YValue[ValueIndex])]);
end;
procedure TSimpleChart.SetBarSeries(ASeries: TBarSeries; AColor: TColor);
var
n: integer;
begin
ASeries.Clear;
for n := 0 to FCount-1 do
if FShowTitle then
begin
ASeries.AddXY(FXVal[n], FYVal[n],FTitle[n],aColor)
end
else
begin
ASeries.AddXY(FXVal[n], FYVal[n],'',aColor)
end;
end;
procedure TSimpleChart.SetLineSeries(ASeries: TLineSeries; AColor: TColor);
var
n: integer;
begin
ASeries.Clear;
for n := 0 to FCount-1 do
if FShowTitle then
begin
ASeries.AddXY(FXVal[n], FYVal[n],FTitle[n],aColor)
end
else
begin
ASeries.AddXY(FXVal[n], FYVal[n],'',aColor)
end;
end;
end.
|
unit uFormOSVersion;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.Memo,
FMX.Objects;
type
TFormOSVersion = class(TForm)
ButtonGetOSInfo: TButton;
PanelTop: TPanel;
MemoLog: TMemo;
Image1: TImage;
procedure ButtonGetOSInfoClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormOSVersion: TFormOSVersion;
implementation
{$R *.fmx}
uses
uOSVersionUtils;
procedure TFormOSVersion.ButtonGetOSInfoClick(Sender: TObject);
begin
with MemoLog.Lines do
begin
Clear;
Add(TOSVersion.ToString);
Add('');
Add('Architecture: ' + OSArchitectureToStr(TOSVersion.Architecture));
Add('Platform: ' + OSPlatformToStr(TOSVersion.Platform));
Add('Build: ' + IntToStr(TOSVersion.Build));
Add('Major: ' + IntToStr(TOSVersion.Major));
Add('Minor: ' + IntToStr(TOSVersion.Minor));
Add('Name: ' + TOSVersion.Name);
Add('Service Pack - Major: ' + IntToStr(TOSVersion.ServicePackMajor));
Add('Service Pack - Minor: ' + IntToStr(TOSVersion.ServicePackMinor));
end;
end;
end.
|
unit TSTOSbtp.Xml;
Interface
Uses Windows, Classes, SysUtils, RTLConsts, HsXmlDocEx;
Type
IXmlSbtpSubVariable = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-9424-7C6AF115804C}']
Function GetVariableName() : String;
Procedure SetVariableName(Const AVariableName : String);
Function GetVariableData() : String;
Procedure SetVariableData(Const AVariableData : String);
Procedure Assign(ASource : IInterface);
Property VariableName : String Read GetVariableName Write SetVariableName;
Property VariableData : String Read GetVariableData Write SetVariableData;
End;
IXmlSbtpSubVariables = Interface(IXmlNodeCollectionEx)
['{4B61686E-29A0-2112-93FA-B915A74141AC}']
Function GetItem(Const Index : Integer) : IXmlSbtpSubVariable;
Function Add() : IXmlSbtpSubVariable;
Function Insert(Const Index: Integer) : IXmlSbtpSubVariable;
Procedure Assign(ASource : IInterface);
Property Items[Const Index: Integer] : IXmlSbtpSubVariable Read GetItem; Default;
End;
IXmlSbtpVariable = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-B27B-D35DBB202C96}']
Function GetVariableType() : String;
Procedure SetVariableType(Const AVariableType : String);
Function GetNbSubItems() : DWord;
Function GetSubItem() : IXmlSbtpSubVariables;
Procedure Assign(ASource : IInterface);
Property VariableType : String Read GetVariableType Write SetVariableType;
Property NbSubItems : DWord Read GetNbSubItems;
Property SubItem : IXmlSbtpSubVariables Read GetSubItem;
End;
IXmlSbtpVariables = Interface(IXmlNodeCollectionEx)
['{4B61686E-29A0-2112-BDA3-20871446F8A7}']
Function GetItem(Const Index : Integer) : IXmlSbtpVariable;
Function Add() : IXmlSbtpVariable;
Function Insert(Const Index: Integer) : IXmlSbtpVariable;
Procedure Assign(ASource : IInterface);
Property Items[Const Index: Integer] : IXmlSbtpVariable Read GetItem; Default;
End;
IXmlSbtpHeader = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-8E56-71D8253578A1}']
Function GetHeader() : String;
Procedure SetHeader(Const AHeader : String);
Function GetHeaderPadding() : Word;
Procedure SetHeaderPadding(Const AHeaderPadding : Word);
Procedure Assign(ASource : IInterface);
Property Header : String Read GetHeader Write SetHeader;
Property HeaderPadding : Word Read GetHeaderPadding Write SetHeaderPadding;
End;
IXmlSbtpFile = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-A167-F6FB9F504096}']
Function GetHeader() : IXmlSbtpHeader;
Function GetItem() : IXmlSbtpVariables;
Procedure Assign(ASource : IInterface);
Property Header : IXmlSbtpHeader Read GetHeader;
Property Item : IXmlSbtpVariables Read GetItem;
End;
IXmlSbtpFiles = Interface(IXmlNodeCollectionEx)
['{4B61686E-29A0-2112-9A75-E9F85554694E}']
Function GetItem(Const Index : Integer) : IXmlSbtpFile;
Function Add() : IXmlSbtpFile;
Function Insert(Const Index: Integer) : IXmlSbtpFile;
Procedure Assign(ASource : IInterface);
Property Items[Const Index: Integer] : IXmlSbtpFile Read GetItem; Default;
End;
(******************************************************************************)
TXmlSbtpFile = Class(TObject)
Public
Class Function CreateSbtpFile() : IXmlSbtpFile; OverLoad;
Class Function CreateSbtpFile(Const AXmlString : String) : IXmlSbtpFile; OverLoad;
Class Function CreateSbtpFiles() : IXmlSbtpFiles; OverLoad;
Class Function CreateSbtpFiles(Const AXmlString : String) : IXmlSbtpFiles; OverLoad;
End;
Implementation
Uses Dialogs, TypInfo,
Variants, Forms, XmlIntf, XmlDom, OXmlDOMVendor,
HsInterfaceEx, TSTOSbtpIntf;
Type
TXmlSbtpSubVariable = Class(TXmlNodeEx, ISbtpSubVariable, IXmlSbtpSubVariable)
Private
FSubVariableImpl : Pointer;
Function GetImplementor() : ISbtpSubVariable;
Protected
Property SubVariableImpl : ISbtpSubVariable Read GetImplementor;
Function GetVariableName() : String;
Procedure SetVariableName(Const AVariableName : String);
Function GetVariableData() : String;
Procedure SetVariableData(Const AVariableData : String);
Procedure Clear();
Procedure Assign(ASource : IInterface); ReIntroduce;
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlSbtpSubVariables = Class(TXMLNodeCollectionEx, ISbtpSubVariables, IXmlSbtpSubVariables)
Private
FSubVariablesImpl : Pointer;
Function GetImplementor() : ISbtpSubVariables;
Protected
Property SubVariablesImpl : ISbtpSubVariables Read GetImplementor Implements ISbtpSubVariables;
Function GetItem(Const Index : Integer) : IXmlSbtpSubVariable;
Function Add() : IXmlSbtpSubVariable;
Function Insert(Const Index : Integer) : IXmlSbtpSubVariable;
Procedure Assign(ASource : IInterface); ReIntroduce;
Procedure AssignTo(ATarget : ISbtpSubVariables);
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlSbtpVariable = Class(TXmlNodeEx, ISbtpVariable, IXmlSbtpVariable)
Private
FVariableImpl : Pointer;
Function GetImplementor() : ISbtpVariable;
Protected
Property VariableImpl : ISbtpVariable Read GetImplementor;
Function GetVariableType() : String;
Procedure SetVariableType(Const AVariableType : String);
Function GetNbSubItems() : DWord;
Function GetSubItem() : IXmlSbtpSubVariables;
Function GetISubItem() : ISbtpSubVariables;
Function ISbtpVariable.GetSubItem = GetISubItem;
Procedure Clear();
Procedure Assign(ASource : IInterface); ReIntroduce;
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlSbtpVariables = Class(TXMLNodeCollectionEx, ISbtpVariables, IXmlSbtpVariables)
Private
FVariablesImpl : Pointer;
Function GetImplementor() : ISbtpVariables;
Protected
Property VariablesImpl : ISbtpVariables Read GetImplementor Implements ISbtpVariables;
Function GetItem(Const Index : Integer) : IXmlSbtpVariable;
Function Add() : IXmlSbtpVariable;
Function Insert(Const Index : Integer) : IXmlSbtpVariable;
Procedure Assign(ASource : IInterface); ReIntroduce;
Procedure AssignTo(ASource : ISbtpVariables);
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlSbtpHeader = Class(TXmlNodeEx, ISbtpHeader, IXmlSbtpHeader)
Private
FHeaderImpl : Pointer;
Function GetImplementor() : ISbtpHeader;
Protected
Property HeaderImpl : ISbtpHeader Read GetImplementor;
Function GetHeader() : String;
Procedure SetHeader(Const AHeader : String);
Function GetHeaderPadding() : Word;
Procedure SetHeaderPadding(Const AHeaderPadding : Word);
Procedure Clear();
Procedure Assign(ASource : IInterface); ReIntroduce;
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlSbtpFileImpl = Class(TXmlNodeEx, ISbtpFile, IXmlSbtpFile)
Private
FFileImpl : Pointer;
Function GetImplementor() : ISbtpFile;
Protected
Property FileImpl : ISbtpFile Read GetImplementor;
Function GetHeader() : IXmlSbtpHeader;
Function GetIHeader() : ISbtpHeader;
Function GetItem() : IXmlSbtpVariables;
Function GetIItem() : ISbtpVariables;
Function ISbtpFile.GetHeader = GetIHeader;
Function ISbtpFile.GetItem = GetIItem;
Procedure Clear();
Procedure Assign(ASource : IInterface); ReIntroduce;
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlSbtpFiles = Class(TXMLNodeCollectionEx, ISbtpFiles, IXmlSbtpFiles)
Private
FFilesImpl : Pointer;
Function GetImplementor() : ISbtpFiles;
Protected
Property FilesImpl : ISbtpFiles Read GetImplementor Implements ISbtpFiles;
Function GetItem(Const Index : Integer) : IXmlSbtpFile;
Function Add() : IXmlSbtpFile;
Function Insert(Const Index : Integer) : IXmlSbtpFile;
Procedure Assign(ASource : IInterface); ReIntroduce;
Procedure AssignTo(ATarget : ISbtpFiles);
Public
Procedure AfterConstruction(); OverRide;
End;
Class Function TXmlSbtpFile.CreateSbtpFile() : IXmlSbtpFile;
Var lXml : TXmlDocumentEx;
Begin
lXml := TXmlDocumentEx.Create(Nil);
lXml.DOMVendor := GetDOMVendor(sOXmlDOMVendor);
lXml.Options := lXml.Options + [doNodeAutoIndent];
Result := lXml.GetDocBinding('SBTPFile', TXmlSbtpFileImpl) As IXmlSbtpFile;
End;
Class Function TXmlSbtpFile.CreateSbtpFile(Const AXmlString : String) : IXmlSbtpFile;
Var lXml : TXmlDocumentEx;
Begin
lXml := TXmlDocumentEx.Create(Nil);
lXml.DOMVendor := GetDOMVendor(sOXmlDOMVendor);
lXml.Options := lXml.Options + [doNodeAutoIndent];
lXml.LoadFromXML(AXmlString);
Result := lXml.GetDocBinding('SBTPFile', TXmlSbtpFileImpl) As IXmlSbtpFile;
End;
Class Function TXmlSbtpFile.CreateSbtpFiles() : IXmlSbtpFiles;
Begin
Result := NewXmlDocument().GetDocBinding('SBTPFiles', TXmlSbtpFiles) As IXmlSbtpFiles;
End;
Class Function TXmlSbtpFile.CreateSbtpFiles(Const AXmlString : String) : IXmlSbtpFiles;
Begin
Result := LoadXmlData(AXmlString).GetDocBinding('SBTPFiles', TXmlSbtpFiles) As IXmlSbtpFiles;
End;
(******************************************************************************)
Procedure TXmlSbtpSubVariable.AfterConstruction();
Begin
FSubVariableImpl := Pointer(ISbtpSubVariable(Self));
InHerited AfterConstruction();
End;
Function TXmlSbtpSubVariable.GetImplementor() : ISbtpSubVariable;
Begin
Result := ISbtpSubVariable(FSubVariableImpl);
End;
Procedure TXmlSbtpSubVariable.Clear();
Begin
ChildNodes['VariableName'].NodeValue := Null;
ChildNodes['VariableData'].NodeValue := Null;
End;
Procedure TXmlSbtpSubVariable.Assign(ASource : IInterface);
Var lXmlSrc : IXmlSbtpSubVariable;
lSrc : ISbtpSubVariable;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlSbtpSubVariable, lXmlSrc) Then
Begin
ChildNodes['VariableName'].NodeValue := lXmlSrc.VariableName;
ChildNodes['VariableData'].NodeValue := lXmlSrc.VariableData;
End
Else If Supports(ASource, ISbtpSubVariable, lSrc) Then
Begin
FSubVariableImpl := Pointer(lSrc);
ChildNodes['VariableName'].NodeValue := lSrc.VariableName;
ChildNodes['VariableData'].NodeValue := lSrc.VariableData;
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlSbtpSubVariable.GetVariableName() : String;
Begin
Result := ChildNodes['VariableName'].AsString;
End;
Procedure TXmlSbtpSubVariable.SetVariableName(Const AVariableName : String);
Begin
ChildNodes['VariableName'].AsString := AVariableName;
If Not IsImplementorOf(SubVariableImpl) Then
SubVariableImpl.VariableName := AVariableName;
End;
Function TXmlSbtpSubVariable.GetVariableData() : String;
Begin
Result := ChildNodes['VariableData'].AsString;
End;
Procedure TXmlSbtpSubVariable.SetVariableData(Const AVariableData : String);
Begin
ChildNodes['VariableData'].AsString := AVariableData;
If Not IsImplementorOf(SubVariableImpl) Then
SubVariableImpl.VariableData := AVariableData;
End;
Procedure TXmlSbtpSubVariables.AfterConstruction();
Begin
RegisterChildNode('SbtpSubVariable', TXmlSbtpSubVariable);
ItemTag := 'SbtpSubVariable';
ItemInterface := IXmlSbtpSubVariable;
FSubVariablesImpl := Nil;
InHerited AfterConstruction();
End;
Function TXmlSbtpSubVariables.GetImplementor() : ISbtpSubVariables;
Begin
If Not Assigned(FSubVariablesImpl) Then
Begin
Result := TSbtpFile.CreateSbtpSubVariables();
AssignTo(Result);
FSubVariablesImpl := Pointer(Result);
End
Else
Result := ISbtpSubVariables(FSubVariablesImpl);
End;
Function TXmlSbtpSubVariables.GetItem(Const Index : Integer) : IXmlSbtpSubVariable;
Begin
Result := List[Index] As IXmlSbtpSubVariable;
End;
Function TXmlSbtpSubVariables.Add() : IXmlSbtpSubVariable;
Begin
Result := AddItem(-1) As IXmlSbtpSubVariable;
If Assigned(FSubVariablesImpl) Then
SubVariablesImpl.Add(Result As ISbtpSubVariable);
End;
Function TXmlSbtpSubVariables.Insert(Const Index : Integer) : IXmlSbtpSubVariable;
Begin
Result := AddItem(Index) As IXmlSbtpSubVariable;
End;
Procedure TXmlSbtpSubVariables.Assign(ASource : IInterface);
Var lXmlSrc : IXmlSbtpSubVariables;
lSrc : ISbtpSubVariables;
X : Integer;
Begin
If Supports(ASource, IXMLNodeCollectionEx) And
Supports(ASource, IXmlSbtpSubVariables, lXmlSrc) Then
Begin
Clear();
For X := 0 To lXmlSrc.Count - 1 Do
Begin
Add().Assign(lXmlSrc[X]);
Application.ProcessMessages();
End;
End
Else If Supports(ASource, ISbtpSubVariables, lSrc) Then
Begin
FSubVariablesImpl := Pointer(lSrc);
Clear();
For X := 0 To lSrc.Count - 1 Do
Begin
Add().Assign(lSrc[X]);
Application.ProcessMessages();
End;
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Procedure TXmlSbtpSubVariables.AssignTo(ATarget : ISbtpSubVariables);
Var X : Integer;
lItem : ISbtpSubVariable;
Begin
ATarget.Clear();
For X := 0 To Count - 1 Do
Begin
If Supports(List[X], ISbtpSubVariable, lItem) Then
ATarget.Add().Assign(lItem);
End;
End;
Procedure TXmlSbtpVariable.AfterConstruction();
Begin
RegisterChildNode('SubItem', TXmlSbtpSubVariables);
FVariableImpl := Pointer(ISbtpVariable(Self));
InHerited AfterConstruction();
End;
Function TXmlSbtpVariable.GetImplementor() : ISbtpVariable;
Begin
Result := ISbtpVariable(FVariableImpl);
End;
Procedure TXmlSbtpVariable.Clear();
Begin
ChildNodes['VariableType'].NodeValue := Null;
ChildNodes['SubItem'].NodeValue := Null;
End;
Procedure TXmlSbtpVariable.Assign(ASource : IInterface);
Var lXmlSrc : IXmlSbtpVariable;
lSrc : ISbtpVariable;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlSbtpVariable, lXmlSrc) Then
Begin
ChildNodes['VariableType'].NodeValue := lXmlSrc.VariableType;
GetSubItem().Assign(lXmlSrc.SubItem);
End
Else If Supports(ASource, ISbtpVariable, lSrc) Then
Begin
FVariableImpl := Pointer(lSrc);
ChildNodes['VariableType'].NodeValue := lSrc.VariableType;
GetSubItem().Assign(lSrc.SubItem);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlSbtpVariable.GetVariableType() : String;
Begin
Result := ChildNodes['VariableType'].AsString;
End;
Procedure TXmlSbtpVariable.SetVariableType(Const AVariableType : String);
Begin
ChildNodes['VariableType'].AsString := AVariableType;
If Not IsImplementorOf(VariableImpl) Then
VariableImpl.VariableType := AVariableType;
End;
Function TXmlSbtpVariable.GetNbSubItems() : DWord;
Begin
Result := GetSubItem().Count;
End;
Function TXmlSbtpVariable.GetSubItem() : IXmlSbtpSubVariables;
Begin
Result := ChildNodes['SubItem'] As IXmlSbtpSubVariables;
End;
Function TXmlSbtpVariable.GetISubItem() : ISbtpSubVariables;
Begin
Result := ChildNodes['SubItem'] As ISbtpSubVariables;
End;
Procedure TXmlSbtpVariables.AfterConstruction();
Begin
RegisterChildNode('SbtpVariable', TXmlSbtpVariable);
ItemTag := 'SbtpVariable';
ItemInterface := IXmlSbtpVariable;
FVariablesImpl := Nil;
InHerited AfterConstruction();
End;
Function TXmlSbtpVariables.GetImplementor() : ISbtpVariables;
Begin
If Not Assigned(FVariablesImpl) Then
Begin
Result := TSbtpFile.CreateSbtpVariables();
AssignTo(Result);
FVariablesImpl := Pointer(Result);
End
Else
Result := ISbtpVariables(FVariablesImpl);
End;
Function TXmlSbtpVariables.GetItem(Const Index : Integer) : IXmlSbtpVariable;
Begin
Result := List[Index] As IXmlSbtpVariable;
End;
Function TXmlSbtpVariables.Add() : IXmlSbtpVariable;
Begin
Result := AddItem(-1) As IXmlSbtpVariable;
If Assigned(FVariablesImpl) Then
// VariablesImpl.Add().Assign(Result);
VariablesImpl.Add(Result As ISbtpVariable);
End;
Function TXmlSbtpVariables.Insert(Const Index : Integer) : IXmlSbtpVariable;
Begin
Result := AddItem(Index) As IXmlSbtpVariable;
End;
Procedure TXmlSbtpVariables.Assign(ASource : IInterface);
Var lXmlSrc : IXmlSbtpVariables;
lSrc : ISbtpVariables;
X : Integer;
Begin
If Supports(ASource, IXMLNodeCollectionEx) And
Supports(ASource, IXmlSbtpVariables, lXmlSrc) Then
Begin
Clear();
For X := 0 To lXmlSrc.Count - 1 Do
Add().Assign(lXmlSrc[X]);
End
Else If Supports(ASource, ISbtpVariables, lSrc) Then
Begin
FVariablesImpl := Pointer(lSrc);
Clear();
For X := 0 To lSrc.Count - 1 Do
Add().Assign(lSrc[X]);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Procedure TXmlSbtpVariables.AssignTo(ASource : ISbtpVariables);
Var X : Integer;
lItem : ISbtpVariable;
Begin
ASource.Clear();
For X := 0 To Count - 1 Do
If Supports(List[X], ISbtpVariable, lItem) Then
ASource.Add().Assign(lItem);
End;
Procedure TXmlSbtpHeader.AfterConstruction();
Begin
FHeaderImpl := Pointer(ISbtpHeader(Self));
InHerited AfterConstruction();
End;
Function TXmlSbtpHeader.GetImplementor() : ISbtpHeader;
Begin
Result := ISbtpHeader(FHeaderImpl);
End;
Procedure TXmlSbtpHeader.Clear();
Begin
ChildNodes['Header'].NodeValue := Null;
ChildNodes['HeaderPadding'].NodeValue := Null;
End;
Procedure TXmlSbtpHeader.Assign(ASource : IInterface);
Var lXmlSrc : IXmlSbtpHeader;
lSrc : ISbtpHeader;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlSbtpHeader, lXmlSrc) Then
Begin
ChildNodes['Header'].NodeValue := lXmlSrc.Header;
ChildNodes['HeaderPadding'].NodeValue := lXmlSrc.HeaderPadding;
End
Else If Supports(ASource, ISbtpHeader, lSrc) Then
Begin
FHeaderImpl := Pointer(lSrc);
ChildNodes['Header'].NodeValue := lSrc.Header;
ChildNodes['HeaderPadding'].NodeValue := lSrc.HeaderPadding;
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlSbtpHeader.GetHeader() : String;
Begin
Result := ChildNodes['Header'].AsString;
End;
Procedure TXmlSbtpHeader.SetHeader(Const AHeader : String);
Begin
ChildNodes['Header'].AsString := AHeader;
If Not IsImplementorOf(HeaderImpl) Then
HeaderImpl.Header := AHeader;
End;
Function TXmlSbtpHeader.GetHeaderPadding() : Word;
Begin
Result := ChildNodes['HeaderPadding'].AsInteger;
End;
Procedure TXmlSbtpHeader.SetHeaderPadding(Const AHeaderPadding : Word);
Begin
ChildNodes['HeaderPadding'].AsInteger := AHeaderPadding;
If Not IsImplementorOf(HeaderImpl) Then
HeaderImpl.HeaderPadding := AHeaderPadding;
End;
Procedure TXmlSbtpFileImpl.AfterConstruction();
Begin
RegisterChildNode('Header', TXmlSbtpHeader);
RegisterChildNode('Item', TXmlSbtpVariables);
FFileImpl := Pointer(ISbtpFile(Self));
InHerited AfterConstruction();
End;
Function TXmlSbtpFileImpl.GetImplementor() : ISbtpFile;
Begin
Result := ISbtpFile(FFileImpl);
End;
Procedure TXmlSbtpFileImpl.Clear();
Begin
ChildNodes['Header'].NodeValue := Null;
ChildNodes['Item'].NodeValue := Null;
End;
Procedure TXmlSbtpFileImpl.Assign(ASource : IInterface);
Var lXmlSrc : IXmlSbtpFile;
lSrc : ISbtpFile;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlSbtpFile, lXmlSrc) Then
Begin
GetHeader().Assign(lXmlSrc.Header);
GetItem().Assign(lXmlSrc.Item);
End
Else If Supports(ASource, ISbtpFile, lSrc) Then
Begin
FFileImpl := Pointer(lSrc);
GetHeader().Assign(lSrc.Header);
GetItem().Assign(lSrc.Item);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlSbtpFileImpl.GetHeader() : IXmlSbtpHeader;
Begin
Result := ChildNodes['Header'] As IXmlSbtpHeader;
End;
Function TXmlSbtpFileImpl.GetIHeader() : ISbtpHeader;
Begin
Result := GetHeader() As ISbtpHeader;
End;
Function TXmlSbtpFileImpl.GetItem() : IXmlSbtpVariables;
Begin
Result := ChildNodes['Item'] As IXmlSbtpVariables;
End;
Function TXmlSbtpFileImpl.GetIItem() : ISbtpVariables;
Begin
Result := GetItem() As ISbtpVariables;
End;
Procedure TXmlSbtpFiles.AfterConstruction();
Begin
RegisterChildNode('SBTPFile', TXmlSbtpFileImpl);
ItemTag := 'SBTPFile';
ItemInterface := IXmlSbtpFile;
InHerited AfterConstruction();
End;
Function TXmlSbtpFiles.GetImplementor() : ISbtpFiles;
Begin
If Not Assigned(FFilesImpl) Then
Begin
Result := TSbtpFile.CreateSbtpFiles();
AssignTo(Result);
FFilesImpl := Pointer(Result);
End
Else
Result := ISbtpFiles(FFilesImpl);
End;
Procedure TXmlSbtpFiles.Assign(ASource : IInterface);
Var lXmlSrc : IXmlSbtpFiles;
lSrc : ISbtpFiles;
X : Integer;
Begin
If Supports(ASource, IXMLNodeCollectionEx) And
Supports(ASource, IXmlSbtpFiles, lXmlSrc) Then
Begin
Clear();
For X := 0 To lXmlSrc.Count - 1 Do
Add().Assign(lXmlSrc[X]);
End
Else If Supports(ASource, ISbtpFiles, lSrc) Then
Begin
FFilesImpl := Pointer(lSrc);
Clear();
For X := 0 To lSrc.Count - 1 Do
Add().Assign(lSrc[X]);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Procedure TXmlSbtpFiles.AssignTo(ATarget : ISbtpFiles);
Var X : Integer;
Begin
ATarget.Clear();
For X := 0 To List.Count - 1 Do
ATarget.Add().Assign(List[X]);
End;
Function TXmlSbtpFiles.GetItem(Const Index : Integer) : IXmlSbtpFile;
Begin
Result := List[Index] As IXmlSbtpFile;
End;
Function TXmlSbtpFiles.Add() : IXmlSbtpFile;
Begin
Result := AddItem(-1) As IXmlSbtpFile;
If Assigned(FFilesImpl) Then
FilesImpl.Add(Result As ISbtpFile);
End;
Function TXmlSbtpFiles.Insert(Const Index : Integer) : IXmlSbtpFile;
Begin
Result := AddItem(Index) As IXmlSbtpFile;
End;
End.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ Copyright(c) 2012-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.PixelFormats;
{
General description of all pixel formats supported by HRH, along with the
conversion between different formats. In addition, it simplifies matching
of one or more pixel formats so that a closest alternative can be found
within a list of available formats.
}
interface
uses
System.Generics.Collections, System.Types;
type
{ Native pixel format that describes how color and data are encoded for each
pixel in bitmap and/or texture. }
TPixelFormat = (pfUnknown,
{ 64-bit format with 16 bits per channel. }
pfA16B16G16R16,
{ 32-bit format with 10 bits for color channels and 2 bits for alpha channel. }
pfA2R10G10B10,
{ 32-bit format with 10 bits for color channels and 2 bits for alpha channel. }
pfA2B10G10R10,
{ 32-bit format with 8 bits per channel. }
pfA8R8G8B8,
{ 32-bit format with 8 bits for color channels. }
pfX8R8G8B8,
{ 32-bit format with 8 bits per channel. }
pfA8B8G8R8,
{ 32-bit format with 8 bits for color channels. }
pfX8B8G8R8,
{ 16-bit format with 5 bits for red and blue channels and 6 bits for
green channel. }
pfR5G6B5,
{ 16-bit format with 4 bits per channel. }
pfA4R4G4B4,
{ 16-bit format with 5 bits for color channels and 1 bit for alpha channel. }
pfA1R5G5B5,
{ 16-bit format with 5 bits for color channels. }
pfX1R5G5B5,
{ 32-bit format with 16 bits for red and green channels. }
pfG16R16,
{ 16-bit format with 8 bits for alpha and luminance channels. }
pfA8L8,
{ 8-bit format with 4 bits for alpha and luminance channels. }
pfA4L4,
{ 16-bit format for luminance channel. }
pfL16,
{ 8-bit format for luminance channel. }
pfL8,
{ 16-bit floating-point format for red channel. }
pfR16F,
{ 32-bit floating-point format for green and red channels. }
pfG16R16F,
{ 64-bit floating-point format with 16 bits per channel. }
pfA16B16G16R16F,
{ 32-bit floating-point format for red channel. }
pfR32F,
{ 64-bit floating-point format with 32 bits for green and red channels. }
pfG32R32F,
{ 128-bit floating-point format with 32 bits per channel. }
pfA32B32G32R32F,
{ 8-bit format for alpha channel. }
pfA8,
{ 16-bit bump-map format. }
pfV8U8,
{ 16-bit bump-map format. }
pfL6V5U5,
{ 32-bit bump-map format. }
pfX8L8V8U8,
{ 32-bit bump-map format. }
pfQ8W8V8U8,
{ 32-bit bump-map format. }
pfV16U16,
{ 32-bit bump-map format. }
pfA2W10V10U10,
{ 32-bit FourCC packed format U8Y8_V8Y8 describing a pair of YUV pixels
(first Y8, U8, V8) and (second Y8, U8, V8). }
pfU8Y8_V8Y8,
{ 32-bit packed format describing a pair of pixels (R8, first G8, B8)
and (R8, second G8, B8). }
pfR8G8_B8G8,
{ 32-bit FourCC packed format Y8U8_Y8V8 describing a pair of YUV pixels
(first Y8, U8, V8) and (second Y8, U8, V8). }
pfY8U8_Y8V8,
{ 32-bit packed format describing a pair of pixels (R8, first G8, B8)
and (R8, second G8, B8). }
pfG8R8_G8B8,
{ 64-bit bumo-map format with 16 bits for QWVU channels. }
pfQ16W16V16U16,
{ 16-bit normal compression format. }
pfCxV8U8,
{ block compression 1: stores 16 pixels into 64 bits consisting of
two 16 bits RGB(R5G6B5) and a 4x4 2 bits lookup table. }
pfDXT1,
{ block compression 2: stores 16 pixels into 128 bits consisting of
64 bits of alpha channel (4 bits per pixel) and a 64 bits of color channels
premultiplied by alpha. }
pfDXT2,
{ block compression 2: stores 16 pixels into 128 bits consisting of
64 bits of alpha channel (4 bits per pixel) and a 64 bits of color channels
without being premultiplied by alpha. }
pfDXT3,
{ block compression 3: stores 16 pixels into 128 bits consisting of
64 bits of alpha channel (two 8-bit alpha values and a 4x4 3-bit
lookup table) and a 64 bits of color channels premultiplied by alpha. }
pfDXT4,
{ block compression 3: stores 16 pixels into 128 bits consisting of
64 bits of alpha channel (two 8-bit alpha values and a 4x4 3-bit
lookup table) and a 64 bits of color channels without being premultiplied
by alpha. }
pfDXT5,
{ 128-bit BGRA pixel format with 32 bits per channel. }
pfA32B32G32R32,
{ 32-bit BGR pixel format with 11 bits for Red and Green channels, and
10 bits for Blue channel. }
pfB10G11R11F);
type
{ The list of available pixel formats that can be used for matching
using FindClosestPixelFormat() function. }
TPixelFormatList = TList<TPixelFormat>;
{ Returns the number of bytes that each pixel occupies in the specified format. }
function GetPixelFormatBytes(Format: TPixelFormat): Integer;
{ Converts pixel refenced by the given pointer from its native format into
4-component floating-point vector (XYZW coordinates correspond to RGBA). }
function PixelToFloat4(Source: Pointer; SrcFormat: TPixelFormat): TVector3D;
{ Converts pixel refenced by the given pointer from its native format into
32-bit A8R8G8B8 value. }
function PixelToAlphaColor(Source: Pointer; SrcFormat: TPixelFormat): Cardinal;
{ Converts 4-component floating-point vector (XYZW coordinates corresponding
to RGBA) of one pixel into the native pixel format. The destination pixel
is referenced by the given pointer. }
procedure Float4ToPixel(const Source: TVector3D; Dest: Pointer; DestFormat: TPixelFormat);
{ Converts 32-bit A8R8G8B8 value of one pixel into the native pixel format.
The destination pixel is referenced by the given pointer. }
procedure AlphaColorToPixel(Source: Cardinal; Dest: Pointer; DestFormat: TPixelFormat);
{ Converts an array of contiguous pixels from their native format into 32-bit
A8R8G8B8 pixel format; Source points to the first pixel in the input array,
while Dest points to the first pixel in the output array. }
procedure ScanlineToAlphaColor(Source, Dest: Pointer; PixelCount: Integer; SrcFormat: TPixelFormat);
{ Converts an array of contiguous pixels in 32-bit A8R8G8B8 format into a
different pixel format; Source points to the first pixel in the input array,
while Dest points to the first pixel in the output array. }
procedure AlphaColorToScanline(Source, Dest: Pointer; PixelCount: Integer; DestFormat: TPixelFormat);
{ Converts the specified pixel format into a readable string describing each
of the channels, for example "A8R8G8B8". }
function PixelFormatToString(Format: TPixelFormat): string;
{ Given the specified pixel format and a list of available pixel formats, this
function tries to find a format contained in the list that closely
resembles the specified format (if no exact match exists). }
function FindClosestPixelFormat(Format: TPixelFormat; const FormatList: TPixelFormatList): TPixelFormat;
implementation
uses
System.Character, System.SysUtils, System.Generics.Defaults, System.UIConsts, FMX.Types3D;
const
MaxPixelFormatChannels = 4;
type
TPixelFormatType = (ftRGB, ftRGBf, ftLuminance, ftBump, ftSpecial);
TPixelFormatChannel = record
Letter: Char;
Start: Integer;
Size: Integer;
end;
TPixelFormatDesc = record
Channels: array [0 .. MaxPixelFormatChannels - 1] of TPixelFormatChannel;
BitCount: Integer;
FormType: TPixelFormatType;
function AddChannel(Letter: Char; Start, Size: Integer): Integer;
function IsChannelMeaningful(Index: Integer): Boolean;
function IndexOfLetter(Letter: Char): Integer;
function GetMeaningfulChannelCount(): Integer;
end;
TPixelFormatComparer = class(TComparer<TPixelFormat>)
private
FPivot: TPixelFormat;
public
property Pivot: TPixelFormat read FPivot write FPivot;
function Compare(const Left, Right: TPixelFormat): Integer; override;
end;
function TPixelFormatDesc.AddChannel(Letter: Char; Start, Size: Integer): Integer;
var
Index: Integer;
begin
Result := -1;
for Index := 0 to MaxPixelFormatChannels - 1 do
if (Channels[Index].Letter = #0) or (Channels[Index].Size < 1) then
begin
Result := Index;
Break;
end;
if (Result = -1) then
Exit;
Channels[Result].Letter := Letter;
Channels[Result].Start := Start;
Channels[Result].Size := Size;
end;
function TPixelFormatDesc.IsChannelMeaningful(Index: Integer): Boolean;
begin
Result := (Index >= 0) and (Index <= MaxPixelFormatChannels) and (Channels[Index].Size > 0);
if (not Result) then
Exit;
Result := Channels[Index].Letter.ToUpper.IsInArray(['R', 'G', 'B', 'A', 'L', 'U', 'V', 'W', 'Q']);
end;
function TPixelFormatDesc.IndexOfLetter(Letter: Char): Integer;
var
Index: Integer;
begin
Result := -1;
for Index := 0 to MaxPixelFormatChannels - 1 do
if (Channels[Index].Size > 0) and (UpCase(Channels[Index].Letter) = UpCase(Letter)) then
begin
Result := Index;
Break;
end;
end;
function TPixelFormatDesc.GetMeaningfulChannelCount(): Integer;
var
Index: Integer;
begin
Result := 0;
for Index := 0 to MaxPixelFormatChannels - 1 do
if (IsChannelMeaningful(Index)) then
Inc(Result);
end;
function GetPixelFormatDesc(Format: TPixelFormat): TPixelFormatDesc;
begin
FillChar(Result, SizeOf(TPixelFormatDesc), 0);
case Format of
pfA16B16G16R16:
begin
Result.BitCount := 64;
Result.FormType := ftRGB;
Result.AddChannel('R', 0, 16);
Result.AddChannel('G', 16, 16);
Result.AddChannel('B', 32, 16);
Result.AddChannel('A', 48, 16);
end;
pfA2R10G10B10:
begin
Result.BitCount := 32;
Result.FormType := ftRGB;
Result.AddChannel('B', 0, 10);
Result.AddChannel('G', 10, 10);
Result.AddChannel('R', 20, 10);
Result.AddChannel('A', 30, 2);
end;
pfA2B10G10R10:
begin
Result.BitCount := 32;
Result.FormType := ftRGB;
Result.AddChannel('R', 0, 10);
Result.AddChannel('G', 10, 10);
Result.AddChannel('B', 20, 10);
Result.AddChannel('A', 30, 2);
end;
pfA8R8G8B8:
begin
Result.BitCount := 32;
Result.FormType := ftRGB;
Result.AddChannel('B', 0, 8);
Result.AddChannel('G', 8, 8);
Result.AddChannel('R', 16, 8);
Result.AddChannel('A', 24, 8);
end;
pfX8R8G8B8:
begin
Result.BitCount := 32;
Result.FormType := ftRGB;
Result.AddChannel('B', 0, 8);
Result.AddChannel('G', 8, 8);
Result.AddChannel('R', 16, 8);
Result.AddChannel('X', 24, 8);
end;
pfA8B8G8R8:
begin
Result.BitCount := 32;
Result.FormType := ftRGB;
Result.AddChannel('R', 0, 8);
Result.AddChannel('G', 8, 8);
Result.AddChannel('B', 16, 8);
Result.AddChannel('A', 24, 8);
end;
pfX8B8G8R8:
begin
Result.BitCount := 32;
Result.FormType := ftRGB;
Result.AddChannel('R', 0, 8);
Result.AddChannel('G', 8, 8);
Result.AddChannel('B', 16, 8);
Result.AddChannel('X', 24, 8);
end;
pfR5G6B5:
begin
Result.BitCount := 16;
Result.FormType := ftRGB;
Result.AddChannel('B', 0, 5);
Result.AddChannel('G', 5, 6);
Result.AddChannel('R', 11, 5);
end;
pfA4R4G4B4:
begin
Result.BitCount := 16;
Result.FormType := ftRGB;
Result.AddChannel('B', 0, 4);
Result.AddChannel('G', 4, 4);
Result.AddChannel('R', 8, 4);
Result.AddChannel('A', 12, 4);
end;
pfA1R5G5B5:
begin
Result.BitCount := 16;
Result.FormType := ftRGB;
Result.AddChannel('B', 0, 5);
Result.AddChannel('G', 5, 5);
Result.AddChannel('R', 10, 5);
Result.AddChannel('A', 15, 1);
end;
pfX1R5G5B5:
begin
Result.BitCount := 16;
Result.FormType := ftRGB;
Result.AddChannel('B', 0, 5);
Result.AddChannel('G', 5, 5);
Result.AddChannel('R', 10, 5);
Result.AddChannel('X', 15, 1);
end;
pfG16R16:
begin
Result.BitCount := 32;
Result.FormType := ftRGB;
Result.AddChannel('R', 0, 16);
Result.AddChannel('G', 16, 16);
end;
pfA8L8:
begin
Result.BitCount := 16;
Result.FormType := ftLuminance;
Result.AddChannel('L', 0, 8);
Result.AddChannel('A', 8, 8);
end;
pfA4L4:
begin
Result.BitCount := 8;
Result.FormType := ftLuminance;
Result.AddChannel('L', 0, 4);
Result.AddChannel('A', 4, 4);
end;
pfL16:
begin
Result.BitCount := 16;
Result.FormType := ftLuminance;
Result.AddChannel('L', 0, 16);
end;
pfL8:
begin
Result.BitCount := 8;
Result.FormType := ftLuminance;
Result.AddChannel('L', 0, 8);
end;
pfR16F:
begin
Result.BitCount := 16;
Result.FormType := ftRGBf;
Result.AddChannel('R', 0, 16);
end;
pfG16R16F:
begin
Result.BitCount := 32;
Result.FormType := ftRGBf;
Result.AddChannel('R', 0, 16);
Result.AddChannel('G', 16, 16);
end;
pfA16B16G16R16F:
begin
Result.BitCount := 64;
Result.FormType := ftRGBf;
Result.AddChannel('R', 0, 16);
Result.AddChannel('G', 16, 16);
Result.AddChannel('B', 32, 16);
Result.AddChannel('A', 48, 16);
end;
pfR32F:
begin
Result.BitCount := 32;
Result.FormType := ftRGBf;
Result.AddChannel('R', 0, 32);
end;
pfG32R32F:
begin
Result.BitCount := 64;
Result.FormType := ftRGBf;
Result.AddChannel('R', 0, 32);
Result.AddChannel('G', 32, 32);
end;
pfA32B32G32R32F:
begin
Result.BitCount := 128;
Result.FormType := ftRGBf;
Result.AddChannel('R', 0, 32);
Result.AddChannel('G', 32, 32);
Result.AddChannel('B', 64, 32);
Result.AddChannel('A', 96, 32);
end;
pfA8:
begin
Result.BitCount := 8;
Result.FormType := ftRGB;
Result.AddChannel('A', 0, 8);
end;
pfV8U8:
begin
Result.BitCount := 16;
Result.FormType := ftBump;
Result.AddChannel('U', 0, 8);
Result.AddChannel('V', 8, 8);
end;
pfL6V5U5:
begin
Result.BitCount := 16;
Result.FormType := ftBump;
Result.AddChannel('U', 0, 5);
Result.AddChannel('V', 5, 5);
Result.AddChannel('L', 10, 6);
end;
pfX8L8V8U8:
begin
Result.BitCount := 32;
Result.FormType := ftBump;
Result.AddChannel('U', 0, 8);
Result.AddChannel('V', 8, 8);
Result.AddChannel('L', 16, 8);
Result.AddChannel('X', 24, 8);
end;
pfQ8W8V8U8:
begin
Result.BitCount := 32;
Result.FormType := ftBump;
Result.AddChannel('U', 0, 8);
Result.AddChannel('V', 8, 8);
Result.AddChannel('W', 16, 8);
Result.AddChannel('Q', 24, 8);
end;
pfV16U16:
begin
Result.BitCount := 32;
Result.FormType := ftBump;
Result.AddChannel('U', 0, 16);
Result.AddChannel('V', 16, 16);
end;
pfA2W10V10U10:
begin
Result.BitCount := 32;
Result.FormType := ftBump;
Result.AddChannel('U', 0, 10);
Result.AddChannel('V', 10, 10);
Result.AddChannel('W', 20, 10);
Result.AddChannel('A', 30, 2);
end;
pfU8Y8_V8Y8:
begin
Result.BitCount := 16;
Result.FormType := ftSpecial;
Result.AddChannel('U', 0, 1);
Result.AddChannel('Y', 1, 1);
Result.AddChannel('V', 2, 1);
Result.AddChannel('Y', 3, 1);
end;
pfR8G8_B8G8:
begin
Result.BitCount := 32;
Result.FormType := ftSpecial;
Result.AddChannel('G', 0, 8);
Result.AddChannel('B', 8, 8);
Result.AddChannel('G', 16, 8);
Result.AddChannel('R', 24, 8);
end;
pfY8U8_Y8V8:
begin
Result.BitCount := 16;
Result.FormType := ftSpecial;
Result.AddChannel('2', 0, 1);
Result.AddChannel('Y', 1, 1);
Result.AddChannel('U', 2, 1);
Result.AddChannel('Y', 3, 1);
end;
pfG8R8_G8B8:
begin
Result.BitCount := 32;
Result.FormType := ftSpecial;
Result.AddChannel('B', 0, 8);
Result.AddChannel('G', 8, 8);
Result.AddChannel('R', 16, 8);
Result.AddChannel('G', 24, 8);
end;
pfQ16W16V16U16:
begin
Result.BitCount := 64;
Result.FormType := ftBump;
Result.AddChannel('U', 0, 16);
Result.AddChannel('V', 16, 16);
Result.AddChannel('W', 32, 16);
Result.AddChannel('Q', 48, 16);
end;
pfCxV8U8:
begin
Result.BitCount := 16;
Result.FormType := ftSpecial;
Result.AddChannel('U', 0, 1);
Result.AddChannel('V', 1, 1);
Result.AddChannel('X', 2, 1);
Result.AddChannel('C', 3, 1);
end;
pfDXT1:
begin
Result.BitCount := 4;
Result.FormType := ftSpecial;
Result.AddChannel('1', 0, 1);
Result.AddChannel('T', 1, 1);
Result.AddChannel('X', 2, 1);
Result.AddChannel('D', 3, 1);
end;
pfDXT2:
begin
Result.BitCount := 8;
Result.FormType := ftSpecial;
Result.AddChannel('2', 0, 1);
Result.AddChannel('T', 1, 1);
Result.AddChannel('X', 2, 1);
Result.AddChannel('D', 3, 1);
end;
pfDXT3:
begin
Result.BitCount := 8;
Result.FormType := ftSpecial;
Result.AddChannel('3', 0, 1);
Result.AddChannel('T', 1, 1);
Result.AddChannel('X', 2, 1);
Result.AddChannel('D', 3, 1);
end;
pfDXT4:
begin
Result.BitCount := 8;
Result.FormType := ftSpecial;
Result.AddChannel('4', 0, 1);
Result.AddChannel('T', 1, 1);
Result.AddChannel('X', 2, 1);
Result.AddChannel('D', 3, 1);
end;
pfDXT5:
begin
Result.BitCount := 8;
Result.FormType := ftSpecial;
Result.AddChannel('5', 0, 1);
Result.AddChannel('T', 1, 1);
Result.AddChannel('X', 2, 1);
Result.AddChannel('D', 3, 1);
end;
pfA32B32G32R32:
begin
Result.BitCount := 128;
Result.FormType := ftRGB;
Result.AddChannel('B', 0, 32);
Result.AddChannel('G', 32, 32);
Result.AddChannel('R', 64, 32);
Result.AddChannel('A', 96, 32);
end;
pfB10G11R11F:
begin
Result.BitCount := 32;
Result.FormType := ftRGBf;
Result.AddChannel('R', 0, 11);
Result.AddChannel('G', 11, 11);
Result.AddChannel('B', 22, 10);
end;
end;
end;
function GetPixelFormatBytes(Format: TPixelFormat): Integer;
begin
Result := 0;
case Format of
pfA32B32G32R32F, pfA32B32G32R32:
Result := 16;
pfA16B16G16R16, pfA16B16G16R16F, pfG32R32F, pfQ16W16V16U16:
Result := 8;
pfA2R10G10B10, pfA2B10G10R10, pfA8R8G8B8, pfX8R8G8B8, pfA8B8G8R8, pfX8B8G8R8, pfG16R16, pfG16R16F, pfR32F,
pfX8L8V8U8, pfQ8W8V8U8, pfV16U16, pfA2W10V10U10, pfR8G8_B8G8, pfG8R8_G8B8, pfB10G11R11F:
Result := 4;
pfR5G6B5, pfA4R4G4B4, pfA1R5G5B5, pfX1R5G5B5, pfA8L8, pfL16, pfR16F, pfV8U8, pfL6V5U5:
Result := 2;
pfA4L4, pfL8, pfA8:
Result := 1;
end;
end;
function IsFormatConvertible(Source, Dest: TPixelFormat): Boolean;
var
SourceDesc, DestDesc: TPixelFormatDesc;
Index, DestIndex: Integer;
OneElement: Boolean;
begin
SourceDesc := GetPixelFormatDesc(Source);
DestDesc := GetPixelFormatDesc(Dest);
Result := (SourceDesc.FormType = DestDesc.FormType) and (SourceDesc.BitCount > 0) and (DestDesc.BitCount > 0);
if (not Result) then
Exit;
OneElement := False;
for Index := 0 to MaxPixelFormatChannels - 1 do
begin
if (not SourceDesc.IsChannelMeaningful(Index)) then
Continue;
DestIndex := DestDesc.IndexOfLetter(SourceDesc.Channels[Index].Letter);
if (DestIndex = -1) then
begin
Result := False;
Exit;
end;
OneElement := True;
end;
Result := OneElement;
end;
function GetChannelSizeDifference(Source, Dest: TPixelFormat): Integer;
var
SourceDesc, DestDesc: TPixelFormatDesc;
SrcIndex, DestIndex: Integer;
begin
SourceDesc := GetPixelFormatDesc(Source);
DestDesc := GetPixelFormatDesc(Dest);
Result := 0;
for SrcIndex := 0 to MaxPixelFormatChannels - 1 do
begin
if (not SourceDesc.IsChannelMeaningful(SrcIndex)) then
Continue;
DestIndex := DestDesc.IndexOfLetter(SourceDesc.Channels[SrcIndex].Letter);
if (DestIndex = -1) then
Continue;
Inc(Result, Sqr(SourceDesc.Channels[SrcIndex].Size - DestDesc.Channels[DestIndex].Size));
end;
Result := Round(Sqrt(Result));
end;
function GetChannelWastedBits(Source, Dest: TPixelFormat): Integer;
var
SourceDesc, DestDesc: TPixelFormatDesc;
Index: Integer;
begin
SourceDesc := GetPixelFormatDesc(Source);
DestDesc := GetPixelFormatDesc(Dest);
Result := 0;
for Index := 0 to MaxPixelFormatChannels - 1 do
begin
if (DestDesc.Channels[Index].Size < 1) then
Continue;
if (not DestDesc.IsChannelMeaningful(Index)) or (SourceDesc.IndexOfLetter(DestDesc.Channels[Index].Letter) = -1)
then
Inc(Result, DestDesc.Channels[Index].Size);
end;
end;
function GetChannelLocationDifference(Source, Dest: TPixelFormat): Integer;
var
SourceDesc, DestDesc: TPixelFormatDesc;
SrcIndex, DestIndex: Integer;
begin
SourceDesc := GetPixelFormatDesc(Source);
DestDesc := GetPixelFormatDesc(Dest);
Result := 0;
for SrcIndex := 0 to MaxPixelFormatChannels - 1 do
begin
if (not SourceDesc.IsChannelMeaningful(SrcIndex)) then
Continue;
DestIndex := DestDesc.IndexOfLetter(SourceDesc.Channels[SrcIndex].Letter);
if (DestIndex = -1) then
Continue;
Inc(Result, Sqr(SourceDesc.Channels[SrcIndex].Start - DestDesc.Channels[DestIndex].Start));
end;
Result := Round(Sqrt(Result));
end;
function PixelToAlphaColor(Source: Pointer; SrcFormat: TPixelFormat): Cardinal;
begin
case SrcFormat of
pfA8R8G8B8: Result := PLongWord(Source)^;
pfA8B8G8R8: Result := RGBtoBGR(PLongWord(Source)^);
else
Result := Vector3DToColor(PixelToFloat4(Source, SrcFormat));
end;
end;
function PixelToFloat4(Source: Pointer; SrcFormat: TPixelFormat): TVector3D;
begin
Result := Vector3D(1.0, 1.0, 1.0, 1.0);
case SrcFormat of
pfA16B16G16R16:
begin
Result.X := (PLongWord(Source)^ and $FFFF) / 65535.0;
Result.Y := ((PLongWord(Source)^ shr 16) and $FFFF) / 65535.0;
Result.Z := (PLongWord(NativeInt(Source) + 4)^ and $FFFF) / 65535.0;
Result.W := ((PLongWord(NativeInt(Source) + 4)^ shr 16) and $FFFF) / 65535.0;
end;
pfA2R10G10B10:
begin
Result.X := ((PLongWord(Source)^ shr 20) and $3FF) / 1023.0;
Result.Y := ((PLongWord(Source)^ shr 10) and $3FF) / 1023.0;
Result.Z := (PLongWord(Source)^ and $3FF) / 1023.0;
Result.W := ((PLongWord(Source)^ shr 30) and $03) / 3.0;
end;
pfA2B10G10R10:
begin
Result.X := (PLongWord(Source)^ and $3FF) / 1023.0;
Result.Y := ((PLongWord(Source)^ shr 10) and $3FF) / 1023.0;
Result.Z := ((PLongWord(Source)^ shr 20) and $3FF) / 1023.0;
Result.W := ((PLongWord(Source)^ shr 30) and $03) / 3.0;
end;
pfA8R8G8B8:
begin
Result.X := ((PLongWord(Source)^ shr 16) and $FF) / 255.0;
Result.Y := ((PLongWord(Source)^ shr 8) and $FF) / 255.0;
Result.Z := (PLongWord(Source)^ and $FF) / 255.0;
Result.W := ((PLongWord(Source)^ shr 24) and $FF) / 255.0;
end;
pfX8R8G8B8:
begin
Result.X := ((PLongWord(Source)^ shr 16) and $FF) / 255.0;
Result.Y := ((PLongWord(Source)^ shr 8) and $FF) / 255.0;
Result.Z := (PLongWord(Source)^ and $FF) / 255.0;
Result.W := 1.0;
end;
pfA8B8G8R8:
begin
Result.X := (PLongWord(Source)^ and $FF) / 255.0;
Result.Y := ((PLongWord(Source)^ shr 8) and $FF) / 255.0;
Result.Z := ((PLongWord(Source)^ shr 16) and $FF) / 255.0;
Result.W := ((PLongWord(Source)^ shr 24) and $FF) / 255.0;
end;
pfX8B8G8R8:
begin
Result.X := (PLongWord(Source)^ and $FF) / 255.0;
Result.Y := ((PLongWord(Source)^ shr 8) and $FF) / 255.0;
Result.Z := ((PLongWord(Source)^ shr 16) and $FF) / 255.0;
end;
pfR5G6B5:
begin
Result.X := ((PWord(Source)^ shr 11) and $1F) / 31.0;
Result.Y := ((PWord(Source)^ shr 5) and $3F) / 63.0;
Result.Z := (PWord(Source)^ and $1F) / 31.0;
end;
pfA4R4G4B4:
begin
Result.X := ((PWord(Source)^ shr 8) and $0F) / 15.0;
Result.Y := ((PWord(Source)^ shr 4) and $0F) / 15.0;
Result.Z := (PWord(Source)^ and $0F) / 15.0;
Result.W := ((PLongWord(Source)^ shr 12) and $0F) / 15.0;
end;
pfA1R5G5B5:
begin
Result.X := ((PWord(Source)^ shr 10) and $1F) / 31.0;
Result.Y := ((PWord(Source)^ shr 5) and $1F) / 31.0;
Result.Z := (PWord(Source)^ and $1F) / 31.0;
Result.W := (PLongWord(Source)^ shr 15) and $01;
end;
pfX1R5G5B5:
begin
Result.X := ((PWord(Source)^ shr 10) and $1F) / 31.0;
Result.Y := ((PWord(Source)^ shr 5) and $1F) / 31.0;
Result.Z := (PWord(Source)^ and $1F) / 31.0;
end;
pfG16R16:
begin
Result.Y := (PLongWord(Source)^ and $FFFF) / 65535.0;
Result.X := ((PLongWord(Source)^ shr 16) and $FFFF) / 65535.0;
end;
pfA8L8:
begin
Result.X := (PWord(Source)^ and $FF) / 255.0;
Result.Y := Result.X;
Result.Z := Result.X;
Result.W := ((PWord(Source)^ shr 16) and $FF) / 255.0;
end;
pfA4L4:
begin
Result.X := (PByte(Source)^ and $0F) / 15.0;
Result.Y := Result.X;
Result.Z := Result.X;
Result.W := ((PByte(Source)^ shr 8) and $0F) / 15.0;
end;
pfL16:
begin
Result.X := PWord(Source)^ / 65535.0;
Result.Y := Result.X;
Result.Z := Result.X;
end;
pfL8:
begin
Result.X := PByte(Source)^ / 255.0;
Result.Y := Result.X;
Result.Z := Result.X;
end;
pfA8:
begin
Result.X := 0.0;
Result.Y := 0.0;
Result.Z := 0.0;
Result.W := PByte(Source)^ / 255.0;
end;
pfR32F:
begin
Result.X := PSingle(Source)^;
Result.Y := Result.X;
Result.Z := Result.X;
end;
pfA32B32G32R32:
begin
Result.X := PLongWord(Source)^ / High(LongWord);
Result.Y := PLongWord(NativeInt(Source) + 4)^ / High(LongWord);
Result.Z := PLongWord(NativeInt(Source) + 8)^ / High(LongWord);
Result.W := PLongWord(NativeInt(Source) + 12)^ / High(LongWord);
end;
end;
end;
procedure Float4ToPixel(const Source: TVector3D; Dest: Pointer; DestFormat: TPixelFormat);
begin
case DestFormat of
pfA16B16G16R16:
begin
PLongWord(Dest)^ := Round(Source.X * 65535.0) or (Round(Source.Y * 65535.0) shl 16);
PLongWord(NativeInt(Dest) + 4)^ := Round(Source.Z * 65535.0) or (Round(Source.W * 65535.0) shl 16);
end;
pfA2R10G10B10:
PLongWord(Dest)^ := Round(Source.Z * 1023.0) or (Round(Source.Y * 1023.0) shl 10) or
(Round(Source.X * 1023.0) shl 20) or (Round(Source.W * 3.0) shl 30);
pfA2B10G10R10:
PLongWord(Dest)^ := Round(Source.X * 1023.0) or (Round(Source.Y * 1023.0) shl 10) or
(Round(Source.Z * 1023.0) shl 20) or (Round(Source.W * 3.0) shl 30);
pfA8R8G8B8:
PLongWord(Dest)^ := Round(Source.Z * 255.0) or (Round(Source.Y * 255.0) shl 8) or (Round(Source.X * 255.0) shl 16)
or (Round(Source.W * 255.0) shl 24);
pfX8R8G8B8:
PLongWord(Dest)^ := Round(Source.Z * 255.0) or (Round(Source.Y * 255.0) shl 8) or
(Round(Source.X * 255.0) shl 16);
pfA8B8G8R8:
PLongWord(Dest)^ := Round(Source.X * 255.0) or (Round(Source.Y * 255.0) shl 8) or (Round(Source.Z * 255.0) shl 16)
or (Round(Source.W * 255.0) shl 24);
pfX8B8G8R8:
PLongWord(Dest)^ := Round(Source.X * 255.0) or (Round(Source.Y * 255.0) shl 8) or
(Round(Source.Z * 255.0) shl 16);
pfR5G6B5:
PWord(Dest)^ := Round(Source.X * 31.0) or (Round(Source.Y * 63.0) shl 5) or (Round(Source.Z * 31.0) shl 11);
pfA4R4G4B4:
PWord(Dest)^ := Round(Source.Z * 15.0) or (Round(Source.Y * 15.0) shl 4) or (Round(Source.X * 15.0) shl 8) or
(Round(Source.W * 15.0) shl 12);
pfA1R5G5B5:
PWord(Dest)^ := Round(Source.Z * 31.0) or (Round(Source.Y * 31.0) shl 5) or (Round(Source.X * 31.0) shl 10) or
(Round(Source.W) shl 15);
pfX1R5G5B5:
PWord(Dest)^ := Round(Source.Z * 31.0) or (Round(Source.Y * 31.0) shl 5) or (Round(Source.X * 31.0) shl 10);
pfG16R16:
PLongWord(Dest)^ := Round(Source.X * 65535.0) or (Round(Source.Y * 65535.0) shl 16);
pfA8L8:
PWord(Dest)^ := Round((Source.X * 0.3 + Source.Y * 0.59 + Source.Z * 0.11) * 255.0) or
(Round(Source.W * 255.0) shl 8);
pfA4L4:
PByte(Dest)^ := Round((Source.X * 0.3 + Source.Y * 0.59 + Source.Z * 0.11) * 15.0) or
(Round(Source.W * 15.0) shl 4);
pfL16:
PWord(Dest)^ := Round((Source.X * 0.3 + Source.Y * 0.59 + Source.Z * 0.11) * 65535.0);
pfL8:
PByte(Dest)^ := Round((Source.X * 0.3 + Source.Y * 0.59 + Source.Z * 0.11) * 255.0);
pfA8:
PByte(Dest)^ := Round(Source.W * 255.0);
pfR32F:
PSingle(Dest)^ := (Source.X * 0.3 + Source.Y * 0.59 + Source.Z * 0.11);
pfA32B32G32R32:
begin
PLongWord(Dest)^ := Round(Source.X * High(LongWord));
PLongWord(NativeInt(Dest) + 4)^ := Round(Source.Y * High(LongWord));
PLongWord(NativeInt(Dest) + 8)^ := Round(Source.Z * High(LongWord));
PLongWord(NativeInt(Dest) + 12)^ := Round(Source.W * High(LongWord));
end;
end;
end;
procedure AlphaColorToPixel(Source: Cardinal; Dest: Pointer; DestFormat: TPixelFormat);
begin
case DestFormat of
pfA8R8G8B8: PLongWord(Dest)^ := Source;
pfA8B8G8R8: PLongWord(Dest)^ := RGBtoBGR(Source);
else
Float4ToPixel(ColorToVector3D(Source), Dest, DestFormat);
end;
end;
procedure ScanlineToAlphaColor(Source, Dest: Pointer; PixelCount: Integer; SrcFormat: TPixelFormat);
var
InpData: Pointer;
OutData: PLongWord;
Index, SrcPitch: Integer;
begin
SrcPitch := GetPixelFormatBytes(SrcFormat);
if (SrcPitch < 1) then
Exit;
InpData := Source;
OutData := Dest;
for Index := 0 to PixelCount - 1 do
begin
OutData^ := PixelToAlphaColor(InpData, SrcFormat);
Inc(NativeInt(InpData), SrcPitch);
Inc(OutData);
end;
end;
procedure AlphaColorToScanline(Source, Dest: Pointer; PixelCount: Integer; DestFormat: TPixelFormat);
var
InpData: PLongWord;
OutData: Pointer;
Index, DestPitch: Integer;
begin
DestPitch := GetPixelFormatBytes(DestFormat);
if (DestPitch < 1) then
Exit;
InpData := Source;
OutData := Dest;
for Index := 0 to PixelCount - 1 do
begin
AlphaColorToPixel(InpData^, OutData, DestFormat);
Inc(InpData);
Inc(NativeInt(OutData), DestPitch);
end;
end;
function PixelFormatToString(Format: TPixelFormat): string;
var
Desc: TPixelFormatDesc;
Index: Integer;
begin
Desc := GetPixelFormatDesc(Format);
Result := '';
case Desc.FormType of
ftRGB, ftRGBf, ftLuminance, ftBump:
begin
for Index := MaxPixelFormatChannels - 1 downto 0 do
begin
if (Desc.Channels[Index].Size < 1) then
Continue;
Result := Result + Desc.Channels[Index].Letter + IntToStr(Desc.Channels[Index].Size);
end;
if (Desc.FormType = ftRGBf) then
Result := Result + 'F';
end;
ftSpecial:
begin
case Format of
pfR8G8_B8G8:
Result := 'R8G8_B8G8';
pfG8R8_G8B8:
Result := 'G8R8_G8B8';
pfCxV8U8:
Result := 'CxV8U8';
else
begin
for Index := MaxPixelFormatChannels - 1 downto 0 do
begin
if (Desc.Channels[Index].Size < 1) then
Continue;
Result := Result + Desc.Channels[Index].Letter;
end;
end;
end;
end;
end;
if (Result = '') then
Result := 'pfUnknown'
else
Result := 'pf' + Result;
end;
function FindClosestPixelFormat(Format: TPixelFormat; const FormatList: TPixelFormatList): TPixelFormat;
var
Possibilities: TPixelFormatList;
Index: Integer;
Comparer: TPixelFormatComparer;
begin
if (FormatList.IndexOf(Format) <> -1) then
begin
Result := Format;
Exit;
end;
Comparer := TPixelFormatComparer.Create();
Comparer.Pivot := Format;
Possibilities := TPixelFormatList.Create(Comparer);
for Index := 0 to FormatList.Count - 1 do
if (IsFormatConvertible(Format, FormatList[Index])) then
Possibilities.Add(FormatList[Index]);
Possibilities.Sort();
if (Possibilities.Count > 0) then
Result := Possibilities[0]
else
Result := pfUnknown;
FreeAndNil(Possibilities);
end;
function TPixelFormatComparer.Compare(const Left, Right: TPixelFormat): Integer;
var
Diff1, Diff2: Integer;
Desc1, Desc2, SortDesc: TPixelFormatDesc;
begin
Diff1 := GetChannelSizeDifference(FPivot, Left);
Diff2 := GetChannelSizeDifference(FPivot, Right);
if (Diff1 = Diff2) then
begin
Diff1 := GetChannelWastedBits(FPivot, Left);
Diff2 := GetChannelWastedBits(FPivot, Right);
end;
if (Diff1 = Diff2) then
begin
Diff1 := GetChannelLocationDifference(FPivot, Left);
Diff2 := GetChannelLocationDifference(FPivot, Right);
end;
if (Diff1 = Diff2) then
begin
Desc1 := GetPixelFormatDesc(Left);
Desc2 := GetPixelFormatDesc(Left);
Diff1 := Desc1.GetMeaningfulChannelCount();
Diff2 := Desc2.GetMeaningfulChannelCount();
if (Diff1 = Diff2) then
begin
SortDesc := GetPixelFormatDesc(FPivot);
Diff1 := Abs(Desc1.BitCount - SortDesc.BitCount);
Diff2 := Abs(Desc2.BitCount - SortDesc.BitCount);
end;
end;
Result := 0;
if (Diff1 > Diff2) then
Result := 1;
if (Diff1 < Diff2) then
Result := -1;
end;
end.
|
unit uFileProcessing;
interface
uses
System.IOUtils, System.Threading, System.Types,
System.Classes, System.SysUtils, System.SyncObjs,
System.Generics.Collections, IdHashMessageDigest,
Winapi.Windows;
type TDirectoryHash = class
private
FDirname: string;
FFileList: TStringList;
function GetHash(Filename: string): string;
function GetThreadCount: integer;
procedure DirectoryProcessing;
public
constructor Create;
destructor Destroy; override;
function GetHashFileList(Dirname: string): TStringLIst;
end;
implementation
// функция сортировки TStringLIst - сравниваем по значениям, а не
// по ключу - чтобы сортировать по имени файла, а не по хэшу
function CompareValues(List: TStringList; Index1, Index2: Integer): Integer;
begin
result := CompareText(List.ValueFromIndex[Index1], List.ValueFromIndex[Index2]);
end;
constructor TDirectoryHash.Create;
begin
FFileList := TStringList.Create;
end;
destructor TDirectoryHash.Destroy;
begin
FreeAndNil(FFileList);
inherited;
end;
// возвращает кол-во виртуальных ядер ЦП
function TDirectoryHash.GetThreadCount: integer;
var
SysInfo: _SYSTEM_INFO;
begin
GetSysteminfo(SysInfo);
result := SysInfo.dwNumberOfProcessors;
end;
// вычисляем хэш для всех файлов в каталоге FDirname
procedure TDirectoryHash.DirectoryProcessing;
var Attr: integer;
FoundedFile: TSearchRec;
Task: ITask;
TaskList: array of ITask;
Count: integer;
Filename: string;
// используем замыкание для "захвата" значения переменной в
// каждой задаче
function CaptureValue(Value: string): TProc;
begin
result := procedure
begin
MonitorEnter(FFileList);
FFileList.AddPair(GetHash(Value), Value);
MonitorExit(FFileList);
end;
end;
begin
// устанавливаем максимальное кол-во потоков равному кол-ву виртуальных ядер
// так максимально распараллеливаем процесс и не тратим процессорное время
// на лишние переключения между потоками
TThreadPool.Default.SetMaxWorkerThreads(GetThreadCount);
SetLength(TaskList, TThreadPool.Default.MaxWorkerThreads);
// Добавить к полному имени каталога конечный слэш, если он отсутствует
FDirname := TPath.GetFullPath(IncludeTrailingPathDelimiter(FDirname));
// обрабатываем все файлы, кроме каталогов
Attr := faAnyFile - faDirectory;
// FL := TList<string>.Create;
Count := 0;
try
if FindFirst(FDirname + '*', Attr, FoundedFile) = 0 then
repeat
Filename := FDirname + FoundedFile.Name;
// тут обработка каждого файла
Task := TTask.Create(CaptureValue(Filename));
TaskList[Count] := Task;
Inc(Count);
if Count > Length(TaskList)-1 then
SetLength(TaskList, Length(TaskList)*2);
until FindNext(FoundedFile) <> 0;
finally
System.SysUtils.FindClose(FoundedFile);
SetLength(TaskList, Count);
end;
// запускаем задачи на выполнение
for Task in TaskList do
begin
Task.Start;
end;
// ждем выполнения всех задач
try
TTask.WaitForAll(TaskList);
except
on E: EAggregateException do
end;
end;
// возвращает MD5 для файла filename
function TDirectoryHash.GetHash(Filename: string): string;
var FileStream: TFileStream;
IdHashMD5: TIdHashMessageDigest5;
begin
result := '';
IdHashMD5 := TIdHashMessageDigest5.Create;
try
FileStream := TFileStream.Create(Filename, fmOpenRead, fmShareDenyNone);
except on E: EFOpenError do
begin
FreeAndNil(IdHashMD5);
Exit('');
end;
end;
Result := IdhashMD5.HashStreamAsHex(FileStream);
FreeAndNil(FileStream);
end;
// возвращает отсортированный по именам файлов TStringList
// <hashMD5> <имя файла>
function TDirectoryHash.GetHashFileList(Dirname: string): TStringLIst;
begin
FFileList.Clear;
FDirname := Dirname;
FFileList.NameValueSeparator := ' ';
DirectoryProcessing;
FFileLIst.CustomSort(CompareValues);
result := FFileList;
end;
end.
|
//Виды расходов
unit fCostType;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, DB, RxMemDS, Grids, DBGridEh, RXSplit, DBCtrlsEh,
StdCtrls, Mask, ExtCtrls, uChild;
type
TfrmCostType = class(TForm)
GridCostType: TDBGridEh;
mdCostType: TRxMemoryData;
dsCostType: TDataSource;
pmCostType: TPopupMenu;
pmCostTypeAdd: TMenuItem;
pmCostTypeEdit: TMenuItem;
pmCostTypeDelete: TMenuItem;
N1: TMenuItem;
pmCostTypeRefresh: TMenuItem;
mdCostTypeCOST_TYPE_ID: TIntegerField;
mdCostTypeNAME: TStringField;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure AcAddExecute(Sender: TObject);
procedure AcEditExecute(Sender: TObject);
procedure AcDeleteExecute(Sender: TObject);
procedure AcRefreshExecute(Sender: TObject);
procedure GridCostTypeSortMarkingChanged(Sender: TObject);
procedure mdCostTypeAfterScroll(DataSet: TDataSet);
private
fChildInfo: PChildInfo;
//получение списка видов расходов
procedure GetCostTypeList;
//запрос в FireBird
function QueryFromFireBird: boolean;
//копирование данных во временную таблицу
procedure CopyToMemoryData;
public
{ Public declarations }
end;
var
frmCostType: TfrmCostType;
implementation
uses
dmHomeAudit,
fCostTypeEd,
uCommon;
{$R *.dfm}
procedure TfrmCostType.FormCreate(Sender: TObject);
begin
//cтруктуру для обслуживания из главной формы
NewChildInfo(fChildInfo, self);
fChildInfo.Actions[childFilterPanel] := nil;
fChildInfo.Actions[childAdd] := AcAddExecute;
fChildInfo.Actions[childEdit] := AcEditExecute;
fChildInfo.Actions[childDelete] := AcDeleteExecute;
fChildInfo.Actions[childRefresh] := AcRefreshExecute;
fChildInfo.haAdd := true;
fChildInfo.haAddPattern := false;
fChildInfo.haRefresh := true;
mdCostType.Active := true;
end;
procedure TfrmCostType.FormShow(Sender: TObject);
begin
GetCostTypeList;
end;
procedure TfrmCostType.FormClose(Sender: TObject; var Action: TCloseAction);
begin
mdCostType.Active := false;
Action := caFree;
end;
//------------------------------------------------------------------------------
//
// Управление записями
//
//------------------------------------------------------------------------------
//добавить запись
procedure TfrmCostType.AcAddExecute(Sender: TObject);
var
CostTypeEd: TfrmCostTypeEd;
begin
CostTypeEd := TfrmCostTypeEd.Create(Application);
if CostTypeEd = nil then
exit;
CostTypeEd.Add(dsCostType);
CostTypeEd.Free;
end;
//редактировать запись
procedure TfrmCostType.AcEditExecute(Sender: TObject);
var
CostTypeEd: TfrmCostTypeEd;
begin
//редактирование недоступно
if (mdCostType.IsEmpty) then
exit;
CostTypeEd := TfrmCostTypeEd.Create(Application);
if CostTypeEd = nil then
exit;
CostTypeEd.Edit(dsCostType, mdCostType.FieldByName('COST_TYPE_ID').AsInteger);
CostTypeEd.Free;
end;
//удалить запись
procedure TfrmCostType.AcDeleteExecute(Sender: TObject);
begin
//удаление недоступно
if (mdCostType.IsEmpty) then
exit;
//диалог подтверждения удаления
if (YesNoBox(format('Удалить вид расхода (ID #%d)?', [mdCostType.FieldByName('COST_TYPE_ID').AsInteger])) = IDYES) then
begin
//удаление
DataMod.IB_Cursor.SQL.Text := 'DELETE FROM COST_TYPE WHERE COST_TYPE_ID = ' + mdCostType.FieldByName('COST_TYPE_ID').AsString;
//MsgBox(DataMod.IB_Cursor.SQL.Text);
//запуск запроса
try
DataMod.IB_Cursor.Open;
except
ErrorBox('Не удалось удалить запись таблицы.' + #13 +
'Возможно, запись используется в других таблицах.');
exit;
end;
DataMod.IB_Cursor.Close;
DataMod.IB_Transaction.Commit;
mdCostType.Delete;
end;
end;
//обновить данные
procedure TfrmCostType.AcRefreshExecute(Sender: TObject);
var
i: word;
begin
//обновление недоступно
if (mdCostType.IsEmpty) then
exit;
for i := 0 to GridCostType.Columns.Count - 1 do
GridCostType.Columns[i].Title.SortMarker := smNoneEh;
GetCostTypeList;
end;
//------------------------------------------------------------------------------
//получение списка видов расходов
procedure TfrmCostType.GetCostTypeList;
begin
//MsgBox('GetCostTypeList');
if (QueryFromFireBird) then
CopyToMemoryData;
end;
//запрос в FireBird
function TfrmCostType.QueryFromFireBird: boolean;
begin
result := false;
DataMod.IB_Cursor.SQL.Text := 'SELECT COST_TYPE_ID'
+ ', NAME'
+ ' FROM COST_TYPE'
+ ' ORDER BY COST_TYPE_ID';
//MsgBox(DataMod.IB_Cursor.SQL.Text);
//запуск запроса
try
DataMod.IB_Cursor.Open;
except
WarningBox('Ошибка при заполнении таблицы видов расходов.');
exit;
end;
result := true;
end;
//копирование данных во временную таблицу
procedure TfrmCostType.CopyToMemoryData;
begin
GridCostType.DataSource.DataSet.DisableControls;
GridCostType.SumList.ClearSumValues;
mdCostType.EmptyTable;
while (not (DataMod.IB_Cursor.Eof)) do
begin
mdCostType.Append;
mdCostType.FieldByName('COST_TYPE_ID').AsInteger := DataMod.IB_Cursor.FieldByName('COST_TYPE_ID').AsInteger;
mdCostType.FieldByName('NAME').AsString := DataMod.IB_Cursor.FieldByName('NAME').AsString;
mdCostType.Post;
DataMod.IB_Cursor.Next;
end;
DataMod.IB_Cursor.Close;
mdCostType.First;
GridCostType.DataSource.DataSet.EnableControls;
end;
procedure TfrmCostType.GridCostTypeSortMarkingChanged(Sender: TObject);
var
fields: String;
i, count: Integer;
desc: Boolean;
begin
if GridCostType = nil then
exit;
desc := false;
fields := '';
count := GridCostType.SortMarkedColumns.Count;
for i := 0 to count - 1 do
begin
if Length(fields) > 0 then
fields := fields + '; ';
fields := fields + GridCostType.SortMarkedColumns.Items[i].FieldName;
if (i = 0) then
desc := smUpEh = GridCostType.SortMarkedColumns.Items[i].Title.SortMarker;
end;
mdCostType.SortOnFields(fields, false, desc);
end;
procedure TfrmCostType.mdCostTypeAfterScroll(DataSet: TDataSet);
begin
fChildInfo.haEdit := not mdCostType.IsEmpty;
fChildInfo.haDelete := not mdCostType.IsEmpty;
end;
end.
|
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
unit dll_sqlite3;
{ $DEFINE SQLITE_DEPRECATED} // Enable deprecated functions
{ $DEFINE SQLITE_EXPERIMENTAL} // Enable experimental functions
{$DEFINE SQLITE_ENABLE_COLUMN_METADATA} // Enable functions to work with
// column metadata:
// table name, DB name, etc.
{$DEFINE SQLITE_ENABLE_UNLOCK_NOTIFY} // Enable sqlite3_unlock_notify()
// function to receive DB unlock
// notification
{ $DEFINE SQLITE_DEBUG} // Enable sqlite3_mutex_held() and
// sqlite3_mutex_notheld() functions
interface
uses
atmcmbaseconst, winconst, wintype;
const
SQLITE_OK = 0;
SQLITE_ERROR = 1;
SQLITE_INTERNAL = 2;
SQLITE_PERM = 3;
SQLITE_ABORT = 4;
SQLITE_BUSY = 5;
SQLITE_LOCKED = 6;
SQLITE_NOMEM = 7;
SQLITE_READONLY = 8;
SQLITE_INTERRUPT = 9;
SQLITE_IOERR = 10;
SQLITE_CORRUPT = 11;
SQLITE_NOTFOUND = 12;
SQLITE_FULL = 13;
SQLITE_CANTOPEN = 14;
SQLITE_PROTOCOL = 15;
SQLITE_EMPTY = 16;
SQLITE_SCHEMA = 17;
SQLITE_TOOBIG = 18;
SQLITE_CONSTRAINT = 19;
SQLITE_MISMATCH = 20;
SQLITE_MISUSE = 21;
SQLITE_NOLFS = 22;
SQLITE_AUTH = 23;
SQLITE_FORMAT = 24;
SQLITE_RANGE = 25;
SQLITE_NOTADB = 26;
SQLITE_ROW = 100;
SQLITE_DONE = 101;
SQLITE_IOERR_READ = SQLITE_IOERR or (1 shl 8);
SQLITE_IOERR_SHORT_READ = SQLITE_IOERR or (2 shl 8);
SQLITE_IOERR_WRITE = SQLITE_IOERR or (3 shl 8);
SQLITE_IOERR_FSYNC = SQLITE_IOERR or (4 shl 8);
SQLITE_IOERR_DIR_FSYNC = SQLITE_IOERR or (5 shl 8);
SQLITE_IOERR_TRUNCATE = SQLITE_IOERR or (6 shl 8);
SQLITE_IOERR_FSTAT = SQLITE_IOERR or (7 shl 8);
SQLITE_IOERR_UNLOCK = SQLITE_IOERR or (8 shl 8);
SQLITE_IOERR_RDLOCK = SQLITE_IOERR or (9 shl 8);
SQLITE_IOERR_DELETE = SQLITE_IOERR or (10 shl 8);
SQLITE_IOERR_BLOCKED = SQLITE_IOERR or (11 shl 8);
SQLITE_IOERR_NOMEM = SQLITE_IOERR or (12 shl 8);
SQLITE_IOERR_ACCESS = SQLITE_IOERR or (13 shl 8);
SQLITE_IOERR_CHECKRESERVEDLOCK = SQLITE_IOERR or (14 shl 8);
SQLITE_IOERR_LOCK = SQLITE_IOERR or (15 shl 8);
SQLITE_IOERR_CLOSE = SQLITE_IOERR or (16 shl 8);
SQLITE_IOERR_DIR_CLOSE = SQLITE_IOERR or (17 shl 8);
SQLITE_LOCKED_SHAREDCACHE = SQLITE_LOCKED or (1 shl 8);
SQLITE_OPEN_READONLY = $00000001;
SQLITE_OPEN_READWRITE = $00000002;
SQLITE_OPEN_CREATE = $00000004;
SQLITE_OPEN_DELETEONCLOSE = $00000008;
SQLITE_OPEN_EXCLUSIVE = $00000010;
SQLITE_OPEN_MAIN_DB = $00000100;
SQLITE_OPEN_TEMP_DB = $00000200;
SQLITE_OPEN_TRANSIENT_DB = $00000400;
SQLITE_OPEN_MAIN_JOURNAL = $00000800;
SQLITE_OPEN_TEMP_JOURNAL = $00001000;
SQLITE_OPEN_SUBJOURNAL = $00002000;
SQLITE_OPEN_MASTER_JOURNAL = $00004000;
SQLITE_OPEN_NOMUTEX = $00008000;
SQLITE_OPEN_FULLMUTEX = $00010000;
SQLITE_OPEN_SHAREDCACHE = $00020000;
SQLITE_OPEN_PRIVATECACHE = $00040000;
SQLITE_IOCAP_ATOMIC = $00000001;
SQLITE_IOCAP_ATOMIC512 = $00000002;
SQLITE_IOCAP_ATOMIC1K = $00000004;
SQLITE_IOCAP_ATOMIC2K = $00000008;
SQLITE_IOCAP_ATOMIC4K = $00000010;
SQLITE_IOCAP_ATOMIC8K = $00000020;
SQLITE_IOCAP_ATOMIC16K = $00000040;
SQLITE_IOCAP_ATOMIC32K = $00000080;
SQLITE_IOCAP_ATOMIC64K = $00000100;
SQLITE_IOCAP_SAFE_APPEND = $00000200;
SQLITE_IOCAP_SEQUENTIAL = $00000400;
SQLITE_LOCK_NONE = 0;
SQLITE_LOCK_SHARED = 1;
SQLITE_LOCK_RESERVED = 2;
SQLITE_LOCK_PENDING = 3;
SQLITE_LOCK_EXCLUSIVE = 4;
SQLITE_SYNC_NORMAL = $00002;
SQLITE_SYNC_FULL = $00003;
SQLITE_SYNC_DATAONLY = $00010;
SQLITE_FCNTL_LOCKSTATE = 1;
SQLITE_GET_LOCKPROXYFILE = 2;
SQLITE_SET_LOCKPROXYFILE = 3;
SQLITE_LAST_ERRNO = 4;
SQLITE_ACCESS_EXISTS = 0;
SQLITE_ACCESS_READWRITE = 1;
SQLITE_ACCESS_READ = 2;
{$IFDEF SQLITE_EXPERIMENTAL}
SQLITE_CONFIG_SINGLETHREAD = 1;
SQLITE_CONFIG_MULTITHREAD = 2;
SQLITE_CONFIG_SERIALIZED = 3;
SQLITE_CONFIG_MALLOC = 4;
SQLITE_CONFIG_GETMALLOC = 5;
SQLITE_CONFIG_SCRATCH = 6;
SQLITE_CONFIG_PAGECACHE = 7;
SQLITE_CONFIG_HEAP = 8;
SQLITE_CONFIG_MEMSTATUS = 9;
SQLITE_CONFIG_MUTEX = 10;
SQLITE_CONFIG_GETMUTEX = 11;
//SQLITE_CONFIG_CHUNKALLOC = 12;
SQLITE_CONFIG_LOOKASIDE = 13;
SQLITE_CONFIG_PCACHE = 14;
SQLITE_CONFIG_GETPCACHE = 15;
SQLITE_DBCONFIG_LOOKASIDE = 1001;
{$ENDIF}
SQLITE_DENY = 1;
SQLITE_IGNORE = 2;
SQLITE_CREATE_INDEX = 1;
SQLITE_CREATE_TABLE = 2;
SQLITE_CREATE_TEMP_INDEX = 3;
SQLITE_CREATE_TEMP_TABLE = 4;
SQLITE_CREATE_TEMP_TRIGGER = 5;
SQLITE_CREATE_TEMP_VIEW = 6;
SQLITE_CREATE_TRIGGER = 7;
SQLITE_CREATE_VIEW = 8;
SQLITE_DELETE = 9;
SQLITE_DROP_INDEX = 10;
SQLITE_DROP_TABLE = 11;
SQLITE_DROP_TEMP_INDEX = 12;
SQLITE_DROP_TEMP_TABLE = 13;
SQLITE_DROP_TEMP_TRIGGER = 14;
SQLITE_DROP_TEMP_VIEW = 15;
SQLITE_DROP_TRIGGER = 16;
SQLITE_DROP_VIEW = 17;
SQLITE_INSERT = 18;
SQLITE_PRAGMA = 19;
SQLITE_READ = 20;
SQLITE_SELECT = 21;
SQLITE_TRANSACTION = 22;
SQLITE_UPDATE = 23;
SQLITE_ATTACH = 24;
SQLITE_DETACH = 25;
SQLITE_ALTER_TABLE = 26;
SQLITE_REINDEX = 27;
SQLITE_ANALYZE = 28;
SQLITE_CREATE_VTABLE = 29;
SQLITE_DROP_VTABLE = 30;
SQLITE_FUNCTION = 31;
SQLITE_SAVEPOINT = 32;
SQLITE_COPY = 0;
SQLITE_LIMIT_LENGTH = 0;
SQLITE_LIMIT_SQL_LENGTH = 1;
SQLITE_LIMIT_COLUMN = 2;
SQLITE_LIMIT_EXPR_DEPTH = 3;
SQLITE_LIMIT_COMPOUND_SELECT = 4;
SQLITE_LIMIT_VDBE_OP = 5;
SQLITE_LIMIT_FUNCTION_ARG = 6;
SQLITE_LIMIT_ATTACHED = 7;
SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8;
SQLITE_LIMIT_VARIABLE_NUMBER = 9;
SQLITE_LIMIT_TRIGGER_DEPTH = 10;
SQLITE_STATIC = Pointer(0);
SQLITE_TRANSIENT = Pointer(-1);
SQLITE_INTEGER = 1;
SQLITE_FLOAT = 2;
SQLITE_TEXT = 3;
SQLITE_BLOB = 4;
SQLITE_NULL = 5;
SQLITE_UTF8 = 1;
SQLITE_UTF16LE = 2;
SQLITE_UTF16BE = 3;
SQLITE_UTF16 = 4;
SQLITE_ANY = 5;
SQLITE_UTF16_ALIGNED = 8;
SQLITE_INDEX_CONSTRAINT_EQ = 2;
SQLITE_INDEX_CONSTRAINT_GT = 4;
SQLITE_INDEX_CONSTRAINT_LE = 8;
SQLITE_INDEX_CONSTRAINT_LT = 16;
SQLITE_INDEX_CONSTRAINT_GE = 32;
SQLITE_INDEX_CONSTRAINT_MATCH = 64;
SQLITE_MUTEX_FAST = 0;
SQLITE_MUTEX_RECURSIVE = 1;
SQLITE_MUTEX_STATIC_MASTER = 2;
SQLITE_MUTEX_STATIC_MEM = 3;
SQLITE_MUTEX_STATIC_MEM2 = 4;
SQLITE_MUTEX_STATIC_OPEN = 4;
SQLITE_MUTEX_STATIC_PRNG = 5;
SQLITE_MUTEX_STATIC_LRU = 6;
SQLITE_MUTEX_STATIC_LRU2 = 7;
SQLITE_TESTCTRL_FIRST = 5;
SQLITE_TESTCTRL_PRNG_SAVE = 5;
SQLITE_TESTCTRL_PRNG_RESTORE = 6;
SQLITE_TESTCTRL_PRNG_RESET = 7;
SQLITE_TESTCTRL_BITVEC_TEST = 8;
SQLITE_TESTCTRL_FAULT_INSTALL = 9;
SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS = 10;
SQLITE_TESTCTRL_PENDING_BYTE = 11;
SQLITE_TESTCTRL_ASSERT = 12;
SQLITE_TESTCTRL_ALWAYS = 13;
SQLITE_TESTCTRL_RESERVE = 14;
SQLITE_TESTCTRL_OPTIMIZATIONS = 15;
SQLITE_TESTCTRL_ISKEYWORD = 16;
SQLITE_TESTCTRL_LAST = 16;
SQLITE_STATUS_MEMORY_USED = 0;
SQLITE_STATUS_PAGECACHE_USED = 1;
SQLITE_STATUS_PAGECACHE_OVERFLOW = 2;
SQLITE_STATUS_SCRATCH_USED = 3;
SQLITE_STATUS_SCRATCH_OVERFLOW = 4;
SQLITE_STATUS_MALLOC_SIZE = 5;
SQLITE_STATUS_PARSER_STACK = 6;
SQLITE_STATUS_PAGECACHE_SIZE = 7;
SQLITE_STATUS_SCRATCH_SIZE = 8;
SQLITE_DBSTATUS_LOOKASIDE_USED = 0;
SQLITE_STMTSTATUS_FULLSCAN_STEP = 1;
SQLITE_STMTSTATUS_SORT = 2;
type
PPAnsiCharArray = ^TPAnsiCharArray;
TPAnsiCharArray = array[0..MaxInt div SizeOf(PAnsiChar) - 1] of PAnsiChar;
//
//const
// sqlite3_lib = 'sqlite3.dll';
//var sqlite3_version: PAnsiChar;
Tsq3_libversion = function : PAnsiChar; cdecl;
Tsq3_sourceid = function : PAnsiChar; cdecl;
Tsq3_libversion_number = function : Integer; cdecl;
Tsq3_threadsafe = function : Integer; cdecl;
PSQLite3 = type Pointer;
Tsq3_close = function (db: PSQLite3): Integer; cdecl;
Tsqlite3Callback = function(pArg: Pointer; nCol: Integer; argv: PPAnsiCharArray; colv: PPAnsiCharArray): Integer; cdecl;
Tsq3_exec = function (db: PSQLite3; const sql: PAnsiChar; callback: Tsqlite3Callback;
pArg: Pointer; errmsg: PPAnsiChar): Integer; cdecl;
PSQLite3File = ^Tsqlite3File;
PSQLite3IOMethods = ^Tsqlite3IOMethods;
sqlite3_file = record
pMethods : PSQLite3IOMethods;
end;
Tsqlite3File = sqlite3_file;
sqlite3_io_methods = record
iVersion : Integer;
xClose : function(id: PSQLite3File): Integer; cdecl;
xRead : function(id: PSQLite3File; pBuf: Pointer; iAmt: Integer; iOfst: Int64): Integer; cdecl;
xWrite : function(id: PSQLite3File; const pBuf: Pointer; iAmt: Integer; iOfst: Int64): Integer; cdecl;
xTruncate : function(id: PSQLite3File; size: Int64): Integer; cdecl;
xSync : function(id: PSQLite3File; flags: Integer): Integer; cdecl;
xFileSize : function(id: PSQLite3File; var pSize: Int64): Integer; cdecl;
xLock : function(id: PSQLite3File; locktype: Integer): Integer; cdecl;
xUnlock : function(id: PSQLite3File; locktype: Integer): Integer; cdecl;
xCheckReservedLock: function(f: PSQLite3File; var pResOut: Integer): Integer; cdecl;
xFileControl : function(id: PSQLite3File; op: Integer; pArg: Pointer): Integer; cdecl;
xSectorSize : function(id: PSQLite3File): Integer; cdecl;
xDeviceCharacteristics: function(id: PSQLite3File): Integer; cdecl;
end;
Tsqlite3IOMethods = sqlite3_io_methods;
PSQLite3Mutex = type Pointer;
PSQLite3VFS = ^Tsqlite3VFS;
sqlite3_vfs = record
iVersion : Integer;
szOsFile : Integer;
mxPathname : Integer;
pNext : PSQLite3VFS;
zName : PAnsiChar;
pAppData : Pointer;
xOpen : function(pVfs: PSQLite3VFS; const zName: PAnsiChar; id: PSQLite3File; flags: Integer; pOutFlags: PInteger): Integer; cdecl;
xDelete : function(pVfs: PSQLite3VFS; const zName: PAnsiChar; syncDir: Integer): Integer; cdecl;
xAccess : function(pVfs: PSQLite3VFS; const zName: PAnsiChar; flags: Integer; var pResOut: Integer): Integer; cdecl;
xFullPathname : function(pVfs: PSQLite3VFS; const zName: PAnsiChar; nOut: Integer; zOut: PAnsiChar): Integer; cdecl;
xDlOpen : function(pVfs: PSQLite3VFS; const zFilename: PAnsiChar): Pointer; cdecl;
xDlError : procedure(pVfs: PSQLite3VFS; nByte: Integer; zErrMsg: PAnsiChar); cdecl;
xDlSym : function(pVfs: PSQLite3VFS; pHandle: Pointer; const zSymbol: PAnsiChar): Pointer; cdecl;
xDlClose : procedure(pVfs: PSQLite3VFS; pHandle: Pointer); cdecl;
xRandomness : function(pVfs: PSQLite3VFS; nByte: Integer; zOut: PAnsiChar): Integer; cdecl;
xSleep : function(pVfs: PSQLite3VFS; microseconds: Integer): Integer; cdecl;
xCurrentTime : function(pVfs: PSQLite3VFS; var prNow: Double): Integer; cdecl;
xGetLastError : function(pVfs: PSQLite3VFS; nBuf: Integer; zBuf: PAnsiChar): Integer; cdecl;
end;
Tsqlite3VFS = sqlite3_vfs;
Tsq3_initialize = function : Integer; cdecl;
Tsq3_shutdown = function : Integer; cdecl;
Tsq3_os_init = function : Integer; cdecl;
Tsq3_os_end = function : Integer; cdecl;
{$IFDEF SQLITE_EXPERIMENTAL}
Tsq3_config = function (op: Integer{; ...}): Integer; cdecl;
Tsq3_db_config = function (db: PSQLite3; op: Integer{; ...}): Integer; cdecl;
sqlite3_mem_methods = record
xMalloc : function(nByte: Integer): Pointer; cdecl;
xFree : procedure(pPrior: Pointer); cdecl;
xRealloc : function(pPrior: Pointer; nByte: Integer): Pointer; cdecl;
xSize : function(pPrior: Pointer): Integer; cdecl;
xRoundup : function(n: Integer): Integer; cdecl;
xInit : function(NotUsed: Pointer): Integer; cdecl;
xShutdown : procedure(NotUsed: Pointer); cdecl;
pAppData : Pointer;
end;
Tsqlite3MemMethods = sqlite3_mem_methods;
{$ENDIF}
Tsq3_extended_result_codes = function (db: PSQLite3; onoff: Integer): Integer; cdecl;
Tsq3_last_insert_rowid = function (db: PSQLite3): Int64; cdecl;
Tsq3_changes = function (db: PSQLite3): Integer; cdecl;
Tsq3_total_changes = function (db: PSQLite3): Integer; cdecl;
Tsq3_interrupt = procedure (db: PSQLite3); cdecl;
Tsq3_complete = function (const sql: PAnsiChar): Integer; cdecl;
Tsq3_complete16 = function (const sql: PWideChar): Integer; cdecl;
Tsqlite3BusyCallback = function(ptr: Pointer; count: Integer): Integer; cdecl;
Tsq3_busy_handler = function (db: PSQLite3; xBusy: Tsqlite3BusyCallback; pArg: Pointer): Integer; cdecl;
Tsq3_busy_timeout = function (db: PSQLite3; ms: Integer): Integer; cdecl;
Tsq3_get_table = function (db: PSQLite3; const zSql: PAnsiChar; var pazResult: PPAnsiCharArray; pnRow: PInteger; pnColumn: PInteger; pzErrmsg: PPAnsiChar): Integer; cdecl;
Tsq3_free_table = procedure (result: PPAnsiCharArray); cdecl;
Tsq3_mprintf = function (const zFormat: PAnsiChar{; ...}): PAnsiChar; cdecl;
Tsq3_vmprintf = function (const zFormat: PAnsiChar; ap: Pointer{va_list}): PAnsiChar; cdecl;
Tsq3_snprintf = function (n: Integer; zBuf: PAnsiChar; const zFormat: PAnsiChar{; ...}): PAnsiChar; cdecl;
Tsq3_malloc = function (n: Integer): Pointer; cdecl;
Tsq3_realloc = function (pOld: Pointer; n: Integer): Pointer; cdecl;
Tsq3_free = procedure (p: Pointer); cdecl;
Tsq3_memory_used = function : Int64; cdecl;
Tsq3_memory_highwater = function (resetFlag: Integer): Int64; cdecl;
Tsq3_randomness = procedure (N: Integer; P: Pointer); cdecl;
Tsqlite3AuthorizerCallback = function(pAuthArg: Pointer; code: Integer; const zTab: PAnsiChar; const zCol: PAnsiChar; const zDb: PAnsiChar; const zAuthContext: PAnsiChar): Integer; cdecl;
Tsq3_set_authorizer = function (db: PSQLite3; xAuth: Tsqlite3AuthorizerCallback; pUserData: Pointer): Integer; cdecl;
{$IFDEF SQLITE_EXPERIMENTAL}
Tsqlite3TraceCallback = procedure(pTraceArg: Pointer; const zTrace: PAnsiChar); cdecl;
Tsqlite3ProfileCallback = procedure(pProfileArg: Pointer; const zSql: PAnsiChar; elapseTime: UInt64); cdecl;
Tsq3_trace = function (db: PSQLite3; xTrace: Tsqlite3TraceCallback; pArg: Pointer): Pointer; cdecl;
Tsq3_profile = function (db: PSQLite3; xProfile: Tsqlite3ProfileCallback; pArg: Pointer): Pointer; cdecl;
{$ENDIF}
Tsqlite3ProgressCallback = function(pProgressArg: Pointer): Integer; cdecl;
Tsq3_progress_handler = procedure (db: PSQLite3; nOps: Integer; xProgress: Tsqlite3ProgressCallback; pArg: Pointer); cdecl;
Tsq3_open = function (const filename: PAnsiChar; var ppDb: PSQLite3): Integer; cdecl;
Tsq3_open16 = function (const filename: PWideChar; var ppDb: PSQLite3): Integer; cdecl;
Tsq3_open_v2 = function (const filename: PAnsiChar; var ppDb: PSQLite3; flags: Integer; const zVfs: PAnsiChar): Integer; cdecl;
Tsq3_errcode = function (db: PSQLite3): Integer; cdecl;
Tsq3_extended_errcode = function (db: PSQLite3): Integer; cdecl;
Tsq3_errmsg = function (db: PSQLite3): PAnsiChar; cdecl;
Tsq3_errmsg16 = function (db: PSQLite3): PWideChar; cdecl;
PSQLite3Stmt = type Pointer;
Tsq3_limit = function (db: PSQLite3; limitId: Integer; newLimit: Integer): Integer; cdecl;
Tsq3_prepare = function (db: PSQLite3; const zSql: PAnsiChar; nByte: Integer; var ppStmt: PSQLite3Stmt; const pzTail: PPAnsiChar): Integer; cdecl;
Tsq3_prepare_v2 = function (db: PSQLite3; const zSql: PAnsiChar; nByte: Integer; var ppStmt: PSQLite3Stmt; const pzTail: PPAnsiChar): Integer; cdecl;
Tsq3_prepare16 = function (db: PSQLite3; const zSql: PWideChar; nByte: Integer; var ppStmt: PSQLite3Stmt; const pzTail: PPWideChar): Integer; cdecl;
Tsq3_prepare16_v2 = function (db: PSQLite3; const zSql: PWideChar; nByte: Integer; var ppStmt: PSQLite3Stmt; const pzTail: PPWideChar): Integer; cdecl;
Tsq3_sql = function (pStmt: PSQLite3Stmt): PAnsiChar; cdecl;
PSQLite3Value = ^Tsqlite3Value;
sqlite3_value = type Pointer;
Tsqlite3Value = sqlite3_value;
PPSQLite3ValueArray = ^TPSQLite3ValueArray;
TPSQLite3ValueArray = array[0..MaxInt div SizeOf(PSQLite3Value) - 1] of PSQLite3Value;
PSQLite3Context = type Pointer;
Tsqlite3DestructorType = procedure(p: Pointer); cdecl;
Tsq3_bind_blob = function (pStmt: PSQLite3Stmt; i: Integer; const zData: Pointer; n: Integer; xDel: Tsqlite3DestructorType): Integer; cdecl;
Tsq3_bind_double = function (pStmt: PSQLite3Stmt; i: Integer; rValue: Double): Integer; cdecl;
Tsq3_bind_int = function (p: PSQLite3Stmt; i: Integer; iValue: Integer): Integer; cdecl;
Tsq3_bind_int64 = function (pStmt: PSQLite3Stmt; i: Integer; iValue: Int64): Integer; cdecl;
Tsq3_bind_null = function (pStmt: PSQLite3Stmt; i: Integer): Integer; cdecl;
Tsq3_bind_text = function (pStmt: PSQLite3Stmt; i: Integer; const zData: PAnsiChar; n: Integer; xDel: Tsqlite3DestructorType): Integer; cdecl;
Tsq3_bind_text16 = function (pStmt: PSQLite3Stmt; i: Integer; const zData: PWideChar; nData: Integer; xDel: Tsqlite3DestructorType): Integer; cdecl;
Tsq3_bind_value = function (pStmt: PSQLite3Stmt; i: Integer; const pValue: PSQLite3Value): Integer; cdecl;
Tsq3_bind_zeroblob = function (pStmt: PSQLite3Stmt; i: Integer; n: Integer): Integer; cdecl;
Tsq3_bind_parameter_count = function (pStmt: PSQLite3Stmt): Integer; cdecl;
Tsq3_bind_parameter_name = function (pStmt: PSQLite3Stmt; i: Integer): PAnsiChar; cdecl;
Tsq3_bind_parameter_index = function (pStmt: PSQLite3Stmt; const zName: PAnsiChar): Integer; cdecl;
Tsq3_clear_bindings = function (pStmt: PSQLite3Stmt): Integer; cdecl;
Tsq3_column_count = function (pStmt: PSQLite3Stmt): Integer; cdecl;
Tsq3_column_name = function (pStmt: PSQLite3Stmt; N: Integer): PAnsiChar; cdecl;
Tsq3_column_name16 = function (pStmt: PSQLite3Stmt; N: Integer): PWideChar; cdecl;
{$IFDEF SQLITE_ENABLE_COLUMN_METADATA}
Tsq3_column_database_name = function (pStmt: PSQLite3Stmt; N: Integer): PAnsiChar; cdecl;
Tsq3_column_database_name16 = function (pStmt: PSQLite3Stmt; N: Integer): PWideChar; cdecl;
Tsq3_column_table_name = function (pStmt: PSQLite3Stmt; N: Integer): PAnsiChar; cdecl;
Tsq3_column_table_name16 = function (pStmt: PSQLite3Stmt; N: Integer): PWideChar; cdecl;
Tsq3_column_origin_name = function (pStmt: PSQLite3Stmt; N: Integer): PAnsiChar; cdecl;
Tsq3_column_origin_name16 = function (pStmt: PSQLite3Stmt; N: Integer): PWideChar; cdecl;
{$ENDIF}
Tsq3_column_decltype = function (pStmt: PSQLite3Stmt; N: Integer): PAnsiChar; cdecl;
Tsq3_column_decltype16 = function (pStmt: PSQLite3Stmt; N: Integer): PWideChar; cdecl;
Tsq3_step = function (pStmt: PSQLite3Stmt): Integer; cdecl;
Tsq3_data_count = function (pStmt: PSQLite3Stmt): Integer; cdecl;
Tsq3_column_blob = function (pStmt: PSQLite3Stmt; iCol: Integer): Pointer; cdecl;
Tsq3_column_bytes = function (pStmt: PSQLite3Stmt; iCol: Integer): Integer; cdecl;
Tsq3_column_bytes16 = function (pStmt: PSQLite3Stmt; iCol: Integer): Integer; cdecl;
Tsq3_column_double = function (pStmt: PSQLite3Stmt; iCol: Integer): Double; cdecl;
Tsq3_column_int = function (pStmt: PSQLite3Stmt; iCol: Integer): Integer; cdecl;
Tsq3_column_int64 = function (pStmt: PSQLite3Stmt; iCol: Integer): Int64; cdecl;
Tsq3_column_text = function (pStmt: PSQLite3Stmt; iCol: Integer): PAnsiChar; cdecl;
Tsq3_column_text16 = function (pStmt: PSQLite3Stmt; iCol: Integer): PWideChar; cdecl;
Tsq3_column_type = function (pStmt: PSQLite3Stmt; iCol: Integer): Integer; cdecl;
Tsq3_column_value = function (pStmt: PSQLite3Stmt; iCol: Integer): PSQLite3Value; cdecl;
Tsq3_finalize = function (pStmt: PSQLite3Stmt): Integer; cdecl;
Tsq3_reset = function (pStmt: PSQLite3Stmt): Integer; cdecl;
Tsqlite3RegularFunction = procedure(ctx: PSQLite3Context; n: Integer; apVal: PPSQLite3ValueArray); cdecl;
Tsqlite3AggregateStep = procedure(ctx: PSQLite3Context; n: Integer; apVal: PPSQLite3ValueArray); cdecl;
Tsqlite3AggregateFinalize = procedure(ctx: PSQLite3Context); cdecl;
Tsq3_create_function = function (db: PSQLite3; const zFunctionName: PAnsiChar; nArg: Integer; eTextRep: Integer; pApp: Pointer; xFunc: Tsqlite3RegularFunction; xStep: Tsqlite3AggregateStep; xFinal: Tsqlite3AggregateFinalize): Integer; cdecl;
Tsq3_create_function16 = function (db: PSQLite3; const zFunctionName: PWideChar; nArg: Integer; eTextRep: Integer; pApp: Pointer; xFunc: Tsqlite3RegularFunction; xStep: Tsqlite3AggregateStep; xFinal: Tsqlite3AggregateFinalize): Integer; cdecl;
{$IFDEF SQLITE_DEPRECATED}
Tsqlite3MemoryAlarmCallback = procedure(pArg: Pointer; used: Int64; N: Integer); cdecl;
Tsq3_aggregate_count = function (p: PSQLite3Context): Integer; cdecl;
Tsq3_expired = function (pStmt: PSQLite3Stmt): Integer; cdecl;
Tsq3_transfer_bindings = function (pFromStmt: PSQLite3Stmt; pToStmt: PSQLite3Stmt): Integer; cdecl;
Tsq3_global_recover = function : Integer; cdecl;
Tsq3_thread_cleanup = procedure ; cdecl;
Tsq3_memory_alarm = function (xCallback: Tsqlite3MemoryAlarmCallback; pArg: Pointer; iThreshold: Int64): Integer; cdecl;
{$ENDIF}
Tsq3_value_blob = function (pVal: PSQLite3Value): Pointer; cdecl;
Tsq3_value_bytes = function (pVal: PSQLite3Value): Integer; cdecl;
Tsq3_value_bytes16 = function (pVal: PSQLite3Value): Integer; cdecl;
Tsq3_value_double = function (pVal: PSQLite3Value): Double; cdecl;
Tsq3_value_int = function (pVal: PSQLite3Value): Integer; cdecl;
Tsq3_value_int64 = function (pVal: PSQLite3Value): Int64; cdecl;
Tsq3_value_text = function (pVal: PSQLite3Value): PAnsiChar; cdecl;
Tsq3_value_text16 = function (pVal: PSQLite3Value): PWideChar; cdecl;
Tsq3_value_text16le = function (pVal: PSQLite3Value): Pointer; cdecl;
Tsq3_value_text16be = function (pVal: PSQLite3Value): Pointer; cdecl;
Tsq3_value_type = function (pVal: PSQLite3Value): Integer; cdecl;
Tsq3_value_numeric_type = function (pVal: PSQLite3Value): Integer; cdecl;
Tsq3_aggregate_context = function (p: PSQLite3Context; nBytes: Integer): Pointer; cdecl;
Tsq3_user_data = function (p: PSQLite3Context): Pointer; cdecl;
Tsq3_context_db_handle = function (p: PSQLite3Context): PSQLite3; cdecl;
Tsqlite3AuxDataDestructor = procedure(pAux: Pointer); cdecl;
Tsq3_get_auxdata = function (pCtx: PSQLite3Context; N: Integer): Pointer; cdecl;
Tsq3_set_auxdata = procedure (pCtx: PSQLite3Context; N: Integer; pAux: Pointer; xDelete: Tsqlite3AuxDataDestructor); cdecl;
Tsq3_result_blob = procedure (pCtx: PSQLite3Context; const z: Pointer; n: Integer; xDel: Tsqlite3DestructorType); cdecl;
Tsq3_result_double = procedure (pCtx: PSQLite3Context; rVal: Double); cdecl;
Tsq3_result_error = procedure (pCtx: PSQLite3Context; const z: PAnsiChar; n: Integer); cdecl;
Tsq3_result_error16 = procedure (pCtx: PSQLite3Context; const z: PWideChar; n: Integer); cdecl;
Tsq3_result_error_toobig = procedure (pCtx: PSQLite3Context); cdecl;
Tsq3_result_error_nomem = procedure (pCtx: PSQLite3Context); cdecl;
Tsq3_result_error_code = procedure (pCtx: PSQLite3Context; errCode: Integer); cdecl;Tsq3_result_int = procedure (pCtx: PSQLite3Context; iVal: Integer); cdecl;
Tsq3_result_int64 = procedure (pCtx: PSQLite3Context; iVal: Int64); cdecl;
Tsq3_result_null = procedure (pCtx: PSQLite3Context); cdecl;
Tsq3_result_text = procedure (pCtx: PSQLite3Context; const z: PAnsiChar; n: Integer; xDel: Tsqlite3DestructorType); cdecl;
Tsq3_result_text16 = procedure (pCtx: PSQLite3Context; const z: PWideChar; n: Integer; xDel: Tsqlite3DestructorType); cdecl;
Tsq3_result_text16le = procedure (pCtx: PSQLite3Context; const z: Pointer; n: Integer; xDel: Tsqlite3DestructorType); cdecl;
Tsq3_result_text16be = procedure (pCtx: PSQLite3Context; const z: Pointer; n: Integer; xDel: Tsqlite3DestructorType); cdecl;
Tsq3_result_value = procedure (pCtx: PSQLite3Context; pValue: PSQLite3Value); cdecl;
Tsq3_result_zeroblob = procedure (pCtx: PSQLite3Context; n: Integer); cdecl;
Tsqlite3CollationCompare = procedure(pUser: Pointer; n1: Integer; const z1: Pointer; n2: Integer; const z2: Pointer); cdecl;
Tsqlite3CollationDestructor = procedure(pUser: Pointer); cdecl;
Tsq3_create_collation = function (db: PSQLite3; const zName: PAnsiChar; eTextRep: Integer; pUser: Pointer; xCompare: Tsqlite3CollationCompare): Integer; cdecl;
Tsq3_create_collation_v2 = function (db: PSQLite3; const zName: PAnsiChar; eTextRep: Integer; pUser: Pointer; xCompare: Tsqlite3CollationCompare; xDestroy: Tsqlite3CollationDestructor): Integer; cdecl;
Tsq3_create_collation16 = function (db: PSQLite3; const zName: PWideChar; eTextRep: Integer; pUser: Pointer; xCompare: Tsqlite3CollationCompare): Integer; cdecl;
Tsqlite3CollationNeededCallback = procedure(pCollNeededArg: Pointer; db: PSQLite3; eTextRep: Integer; const zExternal: PAnsiChar); cdecl;
Tsqlite3CollationNeededCallback16 = procedure(pCollNeededArg: Pointer; db: PSQLite3; eTextRep: Integer; const zExternal: PWideChar); cdecl;
Tsq3_collation_needed = function (db: PSQLite3; pCollNeededArg: Pointer; xCollNeeded: Tsqlite3CollationNeededCallback): Integer; cdecl;
Tsq3_collation_needed16 = function (db: PSQLite3; pCollNeededArg: Pointer; xCollNeeded16: Tsqlite3CollationNeededCallback16): Integer; cdecl;
//function sqlite3_key(db: PSQLite3; const pKey: Pointer; nKey: Integer): Integer; cdecl;
//function sqlite3_rekey(db: PSQLite3; const pKey: Pointer; nKey: Integer): Integer; cdecl;
Tsq3_sleep = function (ms: Integer): Integer; cdecl;
//var sqlite3_temp_directory: PAnsiChar;
Tsq3_get_autocommit = function (db: PSQLite3): Integer; cdecl;
Tsq3_db_handle = function (pStmt: PSQLite3Stmt): PSQLite3; cdecl;
Tsq3_next_stmt = function (pDb: PSQLite3; pStmt: PSQLite3Stmt): PSQLite3Stmt; cdecl;
Tsqlite3CommitCallback = function(pCommitArg: Pointer): Integer; cdecl;
Tsqlite3RollbackCallback = procedure(pRollbackArg: Pointer); cdecl;
Tsq3_commit_hook = function (db: PSQLite3; xCallback: Tsqlite3CommitCallback; pArg: Pointer): Pointer; cdecl;
Tsq3_rollback_hook = function (db: PSQLite3; xCallback: Tsqlite3RollbackCallback; pArg: Pointer): Pointer; cdecl;
Tsqlite3UpdateCallback = procedure(pUpdateArg: Pointer; op: Integer; const zDb: PAnsiChar; const zTbl: PAnsiChar; iKey: Int64); cdecl;
Tsq3_update_hook = function (db: PSQLite3; xCallback: Tsqlite3UpdateCallback; pArg: Pointer): Pointer; cdecl;
Tsq3_enable_shared_cache = function (enable: Integer): Integer; cdecl;
Tsq3_release_memory = function (n: Integer): Integer; cdecl;
Tsq3_soft_heap_limit = procedure (n: Integer); cdecl;
{$IFDEF SQLITE_ENABLE_COLUMN_METADATA}
Tsq3_table_column_metadata = function (db: PSQLite3; const zDbName: PAnsiChar; const zTableName: PAnsiChar; const zColumnName: PAnsiChar; const pzDataType: PPAnsiChar; const pzCollSeq: PPAnsiChar; pNotNull: PInteger; pPrimaryKey: PInteger; pAutoinc: PInteger): Integer; cdecl;
{$ENDIF}
Tsq3_load_extension = function (db: PSQLite3; const zFile: PAnsiChar; const zProc: PAnsiChar; pzErrMsg: PPAnsiChar): Integer; cdecl;
Tsq3_enable_load_extension = function (db: PSQLite3; onoff: Integer): Integer; cdecl;
TSQLiteAutoExtensionEntryPoint = procedure; cdecl;
Tsq3_auto_extension = function (xEntryPoint: TSQLiteAutoExtensionEntryPoint): Integer; cdecl;
Tsq3_reset_auto_extension = procedure ; cdecl;
{$IFDEF SQLITE_EXPERIMENTAL}
Tsqlite3FTS3Func = procedure(pContext: PSQLite3Context; argc: Integer; argv: PPSQLite3ValueArray); cdecl;
PSQLite3VTab = ^Tsqlite3VTab;
PSQLite3IndexInfo = ^Tsqlite3IndexInfo;
PSQLite3VTabCursor = ^Tsqlite3VTabCursor;
PSQLite3Module = ^Tsqlite3Module;
sqlite3_module = record
iVersion: Integer;
xCreate: function(db: PSQLite3; pAux: Pointer; argc: Integer; const argv: PPAnsiCharArray; var ppVTab: PSQLite3VTab; var pzErr: PAnsiChar): Integer; cdecl;
xConnect: function(db: PSQLite3; pAux: Pointer; argc: Integer; const argv: PPAnsiCharArray; var ppVTab: PSQLite3VTab; var pzErr: PAnsiChar): Integer; cdecl;
xBestIndex: function(pVTab: PSQLite3VTab; pInfo: PSQLite3IndexInfo): Integer; cdecl;
xDisconnect: function(pVTab: PSQLite3VTab): Integer; cdecl;
xDestroy: function(pVTab: PSQLite3VTab): Integer; cdecl;
xOpen: function(pVTab: PSQLite3VTab; var ppCursor: PSQLite3VTabCursor): Integer; cdecl;
xClose: function(pVtabCursor: PSQLite3VTabCursor): Integer; cdecl;
xFilter: function(pVtabCursor: PSQLite3VTabCursor; idxNum: Integer; const idxStr: PAnsiChar; argc: Integer; argv: PPSQLite3ValueArray): Integer; cdecl;
xNext: function(pVtabCursor: PSQLite3VTabCursor): Integer; cdecl;
xEof: function(pVtabCursor: PSQLite3VTabCursor): Integer; cdecl;
xColumn: function(pVtabCursor: PSQLite3VTabCursor; sContext: PSQLite3Context; p2: Integer): Integer; cdecl;
xRowid: function(pVtabCursor: PSQLite3VTabCursor; var pRowid: Int64): Integer; cdecl;
xUpdate: function(pVtab: PSQLite3VTab; nArg: Integer; ppArg: PPSQLite3ValueArray; var pRowid: Int64): Integer; cdecl;
xBegin: function(pVTab: PSQLite3VTab): Integer; cdecl;
xSync: function(pVTab: PSQLite3VTab): Integer; cdecl;
xCommit: function(pVTab: PSQLite3VTab): Integer; cdecl;
xRollback: function(pVTab: PSQLite3VTab): Integer; cdecl;
xFindFunction: function(pVtab: PSQLite3VTab; nArg: Integer; const zName: PAnsiChar; var pxFunc: Tsqlite3FTS3Func; var ppArg: Pointer): Integer; cdecl;
xRename: function(pVtab: PSQLite3VTab; const zNew: PAnsiChar): Integer; cdecl;
end;
Tsqlite3Module = sqlite3_module;
sqlite3_index_constraint = record
iColumn: Integer;
op: Byte;
usable: Byte;
iTermOffset: Integer;
end;
Tsqlite3IndexConstraint = sqlite3_index_constraint;
PSQLite3IndexConstraintArray = ^Tsqlite3IndexConstraintArray;
Tsqlite3IndexConstraintArray = array[0..MaxInt div SizeOf(Tsqlite3IndexConstraint) - 1] of Tsqlite3IndexConstraint;
sqlite3_index_orderby = record
iColumn: Integer;
desc: Byte;
end;
Tsqlite3IndexOrderBy = sqlite3_index_orderby;
PSQLite3IndexOrderByArray = ^Tsqlite3IndexOrderByArray;
Tsqlite3IndexOrderByArray = array[0..MaxInt div SizeOf(Tsqlite3IndexOrderBy) - 1] of Tsqlite3IndexOrderBy;
sqlite3_index_constraint_usage = record
argvIndex: Integer;
omit: Byte;
end;
Tsqlite3IndexConstraintUsage = sqlite3_index_constraint_usage;
PSQLite3IndexConstraintUsageArray = ^Tsqlite3IndexConstraintUsageArray;
Tsqlite3IndexConstraintUsageArray = array[0..MaxInt div SizeOf(Tsqlite3IndexConstraintUsage) - 1] of Tsqlite3IndexConstraintUsage;
sqlite3_index_info = record
nConstraint: Integer;
aConstraint: PSQLite3IndexConstraintArray;
nOrderBy: Integer;
aOrderBy: PSQLite3IndexOrderByArray;
aConstraintUsage: PSQLite3IndexConstraintUsageArray;
idxNum: Integer;
idxStr: PAnsiChar;
needToFreeIdxStr: Integer;
orderByConsumed: Integer;
estimatedCost: Double;
end;
Tsqlite3IndexInfo = sqlite3_index_info;
sqlite3_vtab = record
pModule: PSQLite3Module;
nRef: Integer;
zErrMsg: PAnsiChar;
end;
Tsqlite3VTab = sqlite3_vtab;
sqlite3_vtab_cursor = record
pVtab: PSQLite3VTab;
end;
Tsqlite3VTabCursor = sqlite3_vtab_cursor;
Tsq3_create_module = function (db: PSQLite3; const zName: PAnsiChar; const p: PSQLite3Module; pClientData: Pointer): Integer; cdecl;
Tsqlite3ModuleDestructor = procedure(pAux: Pointer); cdecl;
Tsq3_create_module_v2 = function (db: PSQLite3; const zName: PAnsiChar; const p: PSQLite3Module; pClientData: Pointer; xDestroy: Tsqlite3ModuleDestructor): Integer; cdecl;
Tsq3_declare_vtab = function (db: PSQLite3; const zSQL: PAnsiChar): Integer; cdecl;
Tsq3_overload_function = function (db: PSQLite3; const zFuncName: PAnsiChar; nArg: Integer): Integer; cdecl;
{$ENDIF}
PSQLite3BlobData = type Pointer;
Tsq3_blob_open = function (db: PSQLite3; const zDb: PAnsiChar; const zTable: PAnsiChar;
const zColumn: PAnsiChar; iRow: Int64; flags: Integer;
var ppBlob: PSQLite3BlobData): Integer; cdecl;
Tsq3_blob_close = function (pBlob: PSQLite3BlobData): Integer; cdecl;
Tsq3_blob_bytes = function (pBlob: PSQLite3BlobData): Integer; cdecl;
Tsq3_blob_read = function (pBlob: PSQLite3BlobData; Z: Pointer; N: Integer; iOffset: Integer): Integer; cdecl;
Tsq3_blob_write = function (pBlob: PSQLite3BlobData; const z: Pointer; n: Integer; iOffset: Integer): Integer; cdecl;
Tsq3_vfs_find = function (const zVfsName: PAnsiChar): PSQLite3VFS; cdecl;
Tsq3_vfs_register = function (pVfs: PSQLite3VFS; makeDflt: Integer): Integer; cdecl;
Tsq3_vfs_unregister = function (pVfs: PSQLite3VFS): Integer; cdecl;
Tsq3_mutex_alloc = function (id: Integer): PSQLite3Mutex; cdecl;
Tsq3_mutex_free = procedure (p: PSQLite3Mutex); cdecl;
Tsq3_mutex_enter = procedure (p: PSQLite3Mutex); cdecl;
Tsq3_mutex_try = function (p: PSQLite3Mutex): Integer; cdecl;
Tsq3_mutex_leave = procedure (p: PSQLite3Mutex); cdecl;
{$IFDEF SQLITE_EXPERIMENTAL}
sqlite3_mutex_methods = record
xMutexInit: function: Integer; cdecl;
xMutexEnd: function: Integer; cdecl;
xMutexAlloc: function(id: Integer): PSQLite3Mutex; cdecl;
xMutexFree: procedure(p: PSQLite3Mutex); cdecl;
xMutexEnter: procedure(p: PSQLite3Mutex); cdecl;
xMutexTry: function(p: PSQLite3Mutex): Integer; cdecl;
xMutexLeave: procedure(p: PSQLite3Mutex); cdecl;
xMutexHeld: function(p: PSQLite3Mutex): Integer; cdecl;
xMutexNotheld: function(p: PSQLite3Mutex): Integer; cdecl;
end;
Tsqlite3MutexMethods = sqlite3_mutex_methods;
{$ENDIF}
{$IFDEF SQLITE_DEBUG}
Tsq3_mutex_held = function (p: PSQLite3Mutex): Integer; cdecl;
Tsq3_mutex_notheld = function (p: PSQLite3Mutex): Integer; cdecl;
{$ENDIF}
Tsq3_db_mutex = function (db: PSQLite3): PSQLite3Mutex; cdecl;
Tsq3_file_control = function (db: PSQLite3; const zDbName: PAnsiChar; op: Integer; pArg: Pointer): Integer; cdecl;
Tsq3_test_control = function (op: Integer{; ...}): Integer; cdecl;
{$IFDEF SQLITE_EXPERIMENTAL}
Tsq3_status = function (op: Integer; var pCurrent: Integer; var pHighwater: Integer; resetFlag: Integer): Integer; cdecl;
Tsq3_db_status = function (db: PSQLite3; op: Integer; var pCur: Integer; var pHiwtr: Integer; resetFlg: Integer): Integer; cdecl;
Tsq3_stmt_status = function (pStmt: PSQLite3Stmt; op: Integer; resetFlg: Integer): Integer; cdecl;
PSQLite3PCache = type Pointer;
sqlite3_pcache_methods = record
pArg : Pointer;
xInit : function(pArg: Pointer): Integer; cdecl;
xShutdown : procedure(pArg: Pointer); cdecl;
xCreate : function(szPage: Integer; bPurgeable: Integer): PSQLite3PCache; cdecl;
xCachesize: procedure(pCache: PSQLite3PCache; nCachesize: Integer); cdecl;
xPagecount: function(pCache: PSQLite3PCache): Integer; cdecl;
xFetch : function(pCache: PSQLite3PCache; key: Cardinal; createFlag: Integer): Pointer; cdecl;
xUnpin : procedure(pCache: PSQLite3PCache; pPg: Pointer; discard: Integer); cdecl;
xRekey : procedure(pCache: PSQLite3PCache; pPg: Pointer; oldKey: Cardinal; newKey: Cardinal); cdecl;
xTruncate : procedure(pCache: PSQLite3PCache; iLimit: Cardinal); cdecl;
xDestroy : procedure(pCache: PSQLite3PCache); cdecl;
end;
Tsqlite3PCacheMethods = sqlite3_pcache_methods;
PSQLite3Backup = type Pointer;
Tsq3_backup_init = function (pDest: PSQLite3; const zDestName: PAnsiChar; pSource: PSQLite3; const zSourceName: PAnsiChar): PSQLite3Backup; cdecl;
Tsq3_backup_step = function (p: PSQLite3Backup; nPage: Integer): Integer; cdecl;
Tsq3_backup_finish = function (p: PSQLite3Backup): Integer; cdecl;
Tsq3_backup_remaining = function (p: PSQLite3Backup): Integer; cdecl;
Tsq3_backup_pagecount = function (p: PSQLite3Backup): Integer; cdecl;
{$IFDEF SQLITE_ENABLE_UNLOCK_NOTIFY}
Tsqlite3UnlockNotifyCallback = procedure(apArg: PPointerArray; nArg: Integer); cdecl;
Tsq3_unlock_notify = function (pBlocked: PSQLite3; xNotify: Tsqlite3UnlockNotifyCallback; pNotifyArg: Pointer): Integer; cdecl;
{$ENDIF}
Tsq3_strnicmp = function (const zLeft: PAnsiChar; const zRight: PAnsiChar; N: Integer): Integer; cdecl;
{$ENDIF}
//function sqlite3_win32_mbcs_to_utf8(const S: PAnsiChar): PAnsiChar; cdecl;
type
PSqlite3Module = ^TSqlite3Module;
TSqlite3Module = record
Handle : HModule;
// RollBackStr : string; //PStr; // 'ROLLBACK;'
// BeginTransStr : string; //PStr; // 'BEGIN TRANSACTION;'
// CommitStr : string; //PStr; // 'COMMIT;'
libversion : Tsq3_libversion;
sourceid : Tsq3_sourceid;
libversion_number : Tsq3_libversion_number;
threadsafe : Tsq3_threadsafe;
close : Tsq3_close;
exec : Tsq3_exec;
initialize : Tsq3_initialize;
shutdown : Tsq3_shutdown;
os_init : Tsq3_os_init;
os_end : Tsq3_os_end;
{$IFDEF SQLITE_EXPERIMENTAL}
config : Tsq3_config;
db_config : Tsq3_db_config;
{$ENDIF}
extended_result_codes: Tsq3_extended_result_codes;
last_insert_rowid : Tsq3_last_insert_rowid;
changes : Tsq3_changes;
total_changes : Tsq3_total_changes;
interrupt : Tsq3_interrupt;
complete : Tsq3_complete;
complete16 : Tsq3_complete16;
busy_handler : Tsq3_busy_handler;
busy_timeout : Tsq3_busy_timeout;
get_table : Tsq3_get_table;
free_table : Tsq3_free_table;
mprintf : Tsq3_mprintf;
vmprintf : Tsq3_vmprintf;
snprintf : Tsq3_snprintf;
malloc : Tsq3_malloc;
realloc : Tsq3_realloc;
free : Tsq3_free;
memory_used : Tsq3_memory_used;
memory_highwater : Tsq3_memory_highwater;
randomness : Tsq3_randomness;
set_authorizer : Tsq3_set_authorizer;
{$IFDEF SQLITE_EXPERIMENTAL}
trace : Tsq3_trace;
profile : Tsq3_profile;
{$ENDIF}
progress_handler : Tsq3_progress_handler;
open : Tsq3_open;
open16 : Tsq3_open16;
open_v2 : Tsq3_open_v2;
errcode : Tsq3_errcode;
extended_errcode : Tsq3_extended_errcode;
errmsg : Tsq3_errmsg;
errmsg16 : Tsq3_errmsg16;
limit : Tsq3_limit;
prepare : Tsq3_prepare;
prepare_v2 : Tsq3_prepare_v2;
prepare16 : Tsq3_prepare16;
prepare16_v2 : Tsq3_prepare16_v2;
sql : Tsq3_sql;
bind_blob : Tsq3_bind_blob;
bind_double : Tsq3_bind_double;
bind_int : Tsq3_bind_int;
bind_int64 : Tsq3_bind_int64;
bind_null : Tsq3_bind_null;
bind_text : Tsq3_bind_text;
bind_text16 : Tsq3_bind_text16;
bind_value : Tsq3_bind_value;
bind_zeroblob : Tsq3_bind_zeroblob;
bind_param_count : Tsq3_bind_parameter_count;
bind_param_name : Tsq3_bind_parameter_name;
bind_param_index : Tsq3_bind_parameter_index;
clear_bindings : Tsq3_clear_bindings;
column_count : Tsq3_column_count;
column_name : Tsq3_column_name;
column_name16 : Tsq3_column_name16;
{$IFDEF SQLITE_ENABLE_COLUMN_METADATA}
column_db_name : Tsq3_column_database_name;
column_db_name16 : Tsq3_column_database_name16;
column_table_name : Tsq3_column_table_name;
column_table_name16: Tsq3_column_table_name16;
column_origin_name: Tsq3_column_origin_name;
column_origin_name16: Tsq3_column_origin_name16;
{$ENDIF}
column_decltype : Tsq3_column_decltype;
column_decltype16 : Tsq3_column_decltype16;
step : Tsq3_step;
data_count : Tsq3_data_count;
column_blob : Tsq3_column_blob;
column_bytes : Tsq3_column_bytes;
column_bytes16 : Tsq3_column_bytes16;
column_double : Tsq3_column_double;
column_int : Tsq3_column_int;
column_int64 : Tsq3_column_int64;
column_text : Tsq3_column_text;
column_text16 : Tsq3_column_text16;
column_type : Tsq3_column_type;
column_value : Tsq3_column_value;
finalize : Tsq3_finalize;
reset : Tsq3_reset;
create_function : Tsq3_create_function;
create_function16 : Tsq3_create_function16;
{$IFDEF SQLITE_DEPRECATED}
aggregate_count : Tsq3_aggregate_count;
expired : Tsq3_expired;
transfer_bindings : Tsq3_transfer_bindings;
global_recover : Tsq3_global_recover;
thread_cleanup : Tsq3_thread_cleanup;
memory_alarm : Tsq3_memory_alarm;
{$ENDIF}
value_blob : Tsq3_value_blob;
value_bytes : Tsq3_value_bytes;
value_bytes16 : Tsq3_value_bytes16;
value_double : Tsq3_value_double;
value_int : Tsq3_value_int;
value_int64 : Tsq3_value_int64;
value_text : Tsq3_value_text;
value_text16 : Tsq3_value_text16;
value_text16le : Tsq3_value_text16le;
value_text16be : Tsq3_value_text16be;
value_type : Tsq3_value_type;
value_numeric_type: Tsq3_value_numeric_type;
aggregate_context : Tsq3_aggregate_context;
user_data : Tsq3_user_data;
context_db_handle : Tsq3_context_db_handle;
get_auxdata : Tsq3_get_auxdata;
set_auxdata : Tsq3_set_auxdata;
result_blob : Tsq3_result_blob;
result_double : Tsq3_result_double;
result_error : Tsq3_result_error;
result_error16 : Tsq3_result_error16;
result_error_toobig: Tsq3_result_error_toobig;
result_error_nomem: Tsq3_result_error_nomem;
result_error_code : Tsq3_result_error_code;
result_int : Tsq3_result_int;
result_int64 : Tsq3_result_int64;
result_null : Tsq3_result_null;
result_text : Tsq3_result_text;
result_text16 : Tsq3_result_text16;
result_text16le : Tsq3_result_text16le;
result_text16be : Tsq3_result_text16be;
result_value : Tsq3_result_value;
result_zeroblob : Tsq3_result_zeroblob;
create_collation : Tsq3_create_collation;
create_collation_v2: Tsq3_create_collation_v2;
create_collation16: Tsq3_create_collation16;
collation_needed : Tsq3_collation_needed;
collation_needed16: Tsq3_collation_needed16;
sleep : Tsq3_sleep;
//var temp_directory: PAnsiChar;
get_autocommit : Tsq3_get_autocommit;
db_handle : Tsq3_db_handle;
next_stmt : Tsq3_next_stmt;
commit_hook : Tsq3_commit_hook;
rollback_hook : Tsq3_rollback_hook;
update_hook : Tsq3_update_hook;
enable_shared_cache: Tsq3_enable_shared_cache;
release_memory : Tsq3_release_memory;
soft_heap_limit : Tsq3_soft_heap_limit;
{$IFDEF SQLITE_ENABLE_COLUMN_METADATA}
table_column_metadata: Tsq3_table_column_metadata;
{$ENDIF}
load_extension : Tsq3_load_extension;
enable_load_extension: Tsq3_enable_load_extension;
auto_extension : Tsq3_auto_extension;
reset_auto_extension: Tsq3_reset_auto_extension;
{$IFDEF SQLITE_EXPERIMENTAL}
create_module : Tsq3_create_module;
create_module_v2 : Tsq3_create_module_v2;
declare_vtab : Tsq3_declare_vtab;
overload_function : Tsq3_overload_function;
{$ENDIF}
blob_open : Tsq3_blob_open;
blob_close : Tsq3_blob_close;
blob_bytes : Tsq3_blob_bytes;
blob_read : Tsq3_blob_read;
blob_write : Tsq3_blob_write;
vfs_find : Tsq3_vfs_find;
vfs_register : Tsq3_vfs_register;
vfs_unregister : Tsq3_vfs_unregister;
mutex_alloc : Tsq3_mutex_alloc;
mutex_free : Tsq3_mutex_free;
mutex_enter : Tsq3_mutex_enter;
mutex_try : Tsq3_mutex_try;
mutex_leave : Tsq3_mutex_leave;
{$IFDEF SQLITE_DEBUG}
mutex_held : Tsq3_mutex_held;
mutex_notheld : Tsq3_mutex_notheld;
{$ENDIF}
db_mutex : Tsq3_db_mutex;
file_control : Tsq3_file_control;
test_control : Tsq3_test_control;
{$IFDEF SQLITE_EXPERIMENTAL}
status : Tsq3_status;
db_status : Tsq3_db_status;
stmt_status : Tsq3_stmt_status;
backup_init : Tsq3_backup_init;
backup_step : Tsq3_backup_step;
backup_finish : Tsq3_backup_finish;
backup_remaining : Tsq3_backup_remaining;
backup_pagecount : Tsq3_backup_pagecount;
{$IFDEF SQLITE_ENABLE_UNLOCK_NOTIFY}
unlock_notify : Tsq3_unlock_notify;
{$ENDIF}
strnicmp : Tsq3_strnicmp;
{$ENDIF}
end;
function InitSqliteModule(ASqlite3: PSqlite3Module): Boolean;
implementation
uses
dll_kernel;
function InitSqliteModule(ASqlite3: PSqlite3Module): Boolean;
begin
Result := false;
if ASqlite3^.Handle = 0 then
exit;
// ASqlite3^.RollBackStr := 'ROLLBACK;';//CheckOutStr();
// ASqlite3^.CommitStr := 'COMMIT;';
// ASqlite3^.BeginTransStr := 'BEGIN TRANSACTION;';
ASqlite3^.libversion := GetProcAddress(ASqlite3^.Handle, 'sqlite3_libversion');
ASqlite3^.sourceid:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_sourceid');
ASqlite3^.libversion_number:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_libversion_number');
ASqlite3^.threadsafe:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_threadsafe');
ASqlite3^.close:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_close');
ASqlite3^.exec:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_exec');
ASqlite3^.initialize:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_initialize');
ASqlite3^.shutdown:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_shutdown');
ASqlite3^.os_init:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_os_init');
ASqlite3^.os_end:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_os_end');
{$IFDEF SQLITE_EXPERIMENTAL}
ASqlite3^.config:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_config');
ASqlite3^.db_config:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_db_config');
{$ENDIF}
ASqlite3^.extended_result_codes:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_extended_result_codes');
ASqlite3^.last_insert_rowid:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_last_insert_rowid');
ASqlite3^.changes:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_changes');
ASqlite3^.total_changes:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_total_changes');
ASqlite3^.interrupt:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_interrupt');
ASqlite3^.complete:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_complete');
ASqlite3^.complete16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_complete16');
ASqlite3^.busy_handler:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_busy_handler');
ASqlite3^.busy_timeout:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_busy_timeout');
ASqlite3^.get_table:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_get_table');
ASqlite3^.free_table:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_free_table');
ASqlite3^.mprintf:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_mprintf');
ASqlite3^.vmprintf:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_vmprintf');
ASqlite3^.snprintf:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_snprintf');
ASqlite3^.malloc:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_malloc');
ASqlite3^.realloc:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_realloc');
ASqlite3^.free:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_free');
ASqlite3^.memory_used:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_memory_used');
ASqlite3^.memory_highwater:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_memory_highwater');
ASqlite3^.randomness:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_randomness');
ASqlite3^.set_authorizer:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_set_authorizer');
{$IFDEF SQLITE_EXPERIMENTAL}
ASqlite3^.trace:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_trace');
ASqlite3^.profile:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_profile');
{$ENDIF}
ASqlite3^.progress_handler:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_progress_handler');
ASqlite3^.open:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_open');
ASqlite3^.open16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_open16');
ASqlite3^.open_v2:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_open_v2');
ASqlite3^.errcode:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_errcode');
ASqlite3^.extended_errcode:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_extended_errcode');
ASqlite3^.errmsg:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_errmsg');
ASqlite3^.errmsg16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_errmsg16');
ASqlite3^.limit:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_limit');
ASqlite3^.prepare:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_prepare');
ASqlite3^.prepare_v2:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_prepare_v2');
ASqlite3^.prepare16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_prepare16');
ASqlite3^.prepare16_v2:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_prepare16_v2');
ASqlite3^.sql:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_sql');
ASqlite3^.bind_blob:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_blob');
ASqlite3^.bind_double:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_double');
ASqlite3^.bind_int:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_int');
ASqlite3^.bind_int64:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_int64');
ASqlite3^.bind_null:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_null');
ASqlite3^.bind_text:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_text');
ASqlite3^.bind_text16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_text16');
ASqlite3^.bind_value:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_value');
ASqlite3^.bind_zeroblob:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_zeroblob');
ASqlite3^.bind_param_count:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_parameter_count');
ASqlite3^.bind_param_name:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_parameter_name');
ASqlite3^.bind_param_index:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_bind_parameter_index');
ASqlite3^.clear_bindings:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_clear_bindings');
ASqlite3^.column_count:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_count');
ASqlite3^.column_name:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_name');
ASqlite3^.column_name16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_name16');
{$IFDEF SQLITE_ENABLE_COLUMN_METADATA}
ASqlite3^.column_db_name:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_database_name');
ASqlite3^.column_db_name16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_database_name16');
ASqlite3^.column_table_name:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_table_name');
ASqlite3^.column_table_name16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_table_name16');
ASqlite3^.column_origin_name:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_origin_name');
ASqlite3^.column_origin_name16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_origin_name16');
{$ENDIF}
ASqlite3^.column_decltype:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_decltype');
ASqlite3^.column_decltype16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_decltype16');
ASqlite3^.step:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_step');
ASqlite3^.data_count:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_data_count');
ASqlite3^.column_blob:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_blob');
ASqlite3^.column_bytes:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_bytes');
ASqlite3^.column_bytes16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_bytes16');
ASqlite3^.column_double:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_double');
ASqlite3^.column_int:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_int');
ASqlite3^.column_int64:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_int64');
ASqlite3^.column_text:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_text');
ASqlite3^.column_text16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_text16');
ASqlite3^.column_type:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_type');
ASqlite3^.column_value:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_column_value');
ASqlite3^.finalize:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_finalize');
ASqlite3^.reset:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_reset');
ASqlite3^.create_function:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_create_function');
ASqlite3^.create_function16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_create_function16');
{$IFDEF SQLITE_DEPRECATED}
ASqlite3^.aggregate_count:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_aggregate_count');
ASqlite3^.expired:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_expired');
ASqlite3^.transfer_bindings:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_transfer_bindings');
ASqlite3^.global_recover:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_global_recover');
ASqlite3^.thread_cleanup:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_thread_cleanup');
ASqlite3^.memory_alarm:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_memory_alarm');
{$ENDIF}
ASqlite3^.value_blob:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_blob');
ASqlite3^.value_bytes:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_bytes');
ASqlite3^.value_bytes16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_bytes16');
ASqlite3^.value_double:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_double');
ASqlite3^.value_int:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_int');
ASqlite3^.value_int64:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_int64');
ASqlite3^.value_text:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_text');
ASqlite3^.value_text16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_text16');
ASqlite3^.value_text16le:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_text16le');
ASqlite3^.value_text16be:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_text16be');
ASqlite3^.value_type:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_type');
ASqlite3^.value_numeric_type:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_value_numeric_type');
ASqlite3^.aggregate_context:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_aggregate_context');
ASqlite3^.user_data:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_user_data');
ASqlite3^.context_db_handle:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_context_db_handle');
ASqlite3^.get_auxdata:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_get_auxdata');
ASqlite3^.set_auxdata:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_set_auxdata');
ASqlite3^.result_blob:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_blob');
ASqlite3^.result_double:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_double');
ASqlite3^.result_error:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_error');
ASqlite3^.result_error16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_error16');
ASqlite3^.result_error_toobig:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_error_toobig');
ASqlite3^.result_error_nomem:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_error_nomem');
ASqlite3^.result_error_code:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_error_code');
ASqlite3^.result_int:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_int');
ASqlite3^.result_int64:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_int64');
ASqlite3^.result_null:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_null');
ASqlite3^.result_text:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_text');
ASqlite3^.result_text16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_text16');
ASqlite3^.result_text16le:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_text16le');
ASqlite3^.result_text16be:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_text16be');
ASqlite3^.result_value:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_value');
ASqlite3^.result_zeroblob:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_result_zeroblob');
ASqlite3^.create_collation:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_create_collation');
ASqlite3^.create_collation_v2:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_create_collation_v2');
ASqlite3^.create_collation16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_create_collation16');
ASqlite3^.collation_needed:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_collation_needed');
ASqlite3^.collation_needed16:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_collation_needed16');
ASqlite3^.sleep:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_sleep');
//var sqlite3_temp_directory: PAnsiChar');
ASqlite3^.get_autocommit:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_get_autocommit');
ASqlite3^.db_handle:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_db_handle');
ASqlite3^.next_stmt:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_next_stmt');
ASqlite3^.commit_hook:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_commit_hook');
ASqlite3^.rollback_hook:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_rollback_hook');
ASqlite3^.update_hook:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_update_hook');
ASqlite3^.enable_shared_cache:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_enable_shared_cache');
ASqlite3^.release_memory:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_release_memory');
ASqlite3^.soft_heap_limit:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_soft_heap_limit');
{$IFDEF SQLITE_ENABLE_COLUMN_METADATA}
ASqlite3^.table_column_metadata:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_table_column_metadata');
{$ENDIF}
ASqlite3^.load_extension:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_load_extension');
ASqlite3^.enable_load_extension:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_enable_load_extension');
ASqlite3^.auto_extension:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_auto_extension');
ASqlite3^.reset_auto_extension:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_reset_auto_extension');
{$IFDEF SQLITE_EXPERIMENTAL}
ASqlite3^.create_module:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_create_module');
ASqlite3^.create_module_v2:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_create_module_v2');
ASqlite3^.declare_vtab:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_declare_vtab');
ASqlite3^.overload_function:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_overload_function');
{$ENDIF}
ASqlite3^.blob_open:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_blob_open');
ASqlite3^.blob_close:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_blob_close');
ASqlite3^.blob_bytes:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_blob_bytes');
ASqlite3^.blob_read:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_blob_read');
ASqlite3^.blob_write:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_blob_write');
ASqlite3^.vfs_find:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_vfs_find');
ASqlite3^.vfs_register:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_vfs_register');
ASqlite3^.vfs_unregister:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_vfs_unregister');
ASqlite3^.mutex_alloc:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_mutex_alloc');
ASqlite3^.mutex_free:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_mutex_free');
ASqlite3^.mutex_enter:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_mutex_enter');
ASqlite3^.mutex_try:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_mutex_try');
ASqlite3^.mutex_leave:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_mutex_leave');
{$IFDEF SQLITE_DEBUG}
ASqlite3^.mutex_held:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_mutex_held');
ASqlite3^.mutex_notheld:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_mutex_notheld');
{$ENDIF}
ASqlite3^.db_mutex:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_db_mutex');
ASqlite3^.file_control:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_file_control');
ASqlite3^.test_control:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_test_control');
{$IFDEF SQLITE_EXPERIMENTAL}
ASqlite3^.status:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_status');
ASqlite3^.db_status:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_db_status');
ASqlite3^.stmt_status:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_stmt_status');
ASqlite3^.backup_init:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_backup_init');
ASqlite3^.backup_step:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_backup_step');
ASqlite3^.backup_finish:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_backup_finish');
ASqlite3^.backup_remaining:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_backup_remaining');
ASqlite3^.backup_pagecount:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_backup_pagecount');
{$IFDEF SQLITE_ENABLE_UNLOCK_NOTIFY}
ASqlite3^.unlock_notify:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_unlock_notify');
{$ENDIF}
ASqlite3^.strnicmp:= GetProcAddress(ASqlite3^.Handle, 'sqlite3_strnicmp');
{$ENDIF}
Result := true;
end;
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Ported to Delphi by Michal Wojcik.
{$H+}
unit Method;
interface
uses
TypInfo;
type
TMethod = class
private
FMethodName : string;
FReturnType : TTypeKind;
function getMethodName : string;
function getReturnType : TTypeKind;
public
function invoke(theInstance : TObject; inParams : array of Variant) : variant;
constructor Create(theClass : TClass; const aMethod : string); overload;
constructor Create(const theName : string; retType : TTypeKind); overload;
property Name : string read getMethodName;
property ReturnType : TTypeKind read getReturnType;
end;
implementation
uses
DetailedRTTI,
ObjAuto,
SysUtils,
InvocationTargetException;
constructor TMethod.Create(const theName : string; retType : TTypeKind);
begin
FMethodName := theName;
FReturnType := retType;
end;
constructor TMethod.Create(theClass : TClass; const aMethod : string);
var
Instance : TObject;
ReturnInfo : PReturnInfo;
begin
Instance := theClass.NewInstance;
try
ReturnInfo := GetMethodReturnInfo(Instance, aMethod);
finally
Instance.FreeInstance;
end;
if (ReturnInfo = nil) or (ReturnInfo.ReturnType = nil) then
Self.Create(aMethod, tkUnknown)
else
Self.Create(aMethod, ReturnInfo.ReturnType^.Kind)
end;
function TMethod.invoke(theInstance : TObject; inParams : array of Variant) : variant;
var
ParamIndexes : array of Integer;
Params : array of Variant;
i, ArgCount : integer;
MethodInfo : PMethodInfoHeader;
ReturnInfo : PReturnInfo;
begin
ArgCount := Length(inParams);
SetLength(ParamIndexes, 0);
SetLength(Params, ArgCount);
// Params should contain arguments in reverse order!
for i := 0 to ArgCount - 1 do
Params[i] := inParams[ArgCount - i - 1];
MethodInfo := GetMethodInfo(theInstance, Name);
if not Assigned(MethodInfo) then
raise Exception.CreateFmt('There is no method named "%s"', [Name]);
try
ReturnInfo := GetMethodReturnInfo(theInstance, Name);
if (ReturnInfo = nil) or (ReturnInfo.ReturnType = nil) then
ObjectInvoke(theInstance, MethodInfo, ParamIndexes, Params)
else
Result := ObjectInvoke(theInstance, MethodInfo, ParamIndexes, Params);
except
on e : Exception do
raise TInvocationTargetException.Create(MethodInfo, e);
end;
end;
function TMethod.getMethodName : string;
begin
result := FMethodName;
end;
function TMethod.getReturnType : TTypeKind;
begin
result := FReturnType;
end;
end.
|
{==============================================================================*
* Copyright © 2020, Pukhkiy Igor *
* All rights reserved. *
*==============================================================================*
* This Source Code Form is subject to the terms of the Mozilla *
* Public License, v. 2.0. If a copy of the MPL was not distributed *
* with this file, You can obtain one at http://mozilla.org/MPL/2.0/. *
*==============================================================================*
* The Initial Developer of the Original Code is Pukhkiy Igor (Ukraine). *
* Contacts: nspytnik-programming@yahoo.com *
*==============================================================================*
* DESCRIPTION: *
* FrameTable.pas - unit print tables *
* *
* Last modified: 29.07.2020 17:49:30 *
* Author : Pukhkiy Igor *
* Email : nspytnik-programming@yahoo.com *
* www : *
* *
* File version: 0.0.0.1d *
*==============================================================================}
unit FrameTable;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FrameList, Vcl.StdCtrls, Vcl.Grids,
Vcl.ExtCtrls, RDBClass, RDBGridProvider, RDBGrid;
type
TTableFrame = class(TListFrame)
private
{ Private declarations }
function GetTableList(Kind: TMapKind): TMetaTableList;
procedure SetTableList(Kind: TMapKind; const Value: TMetaTableList);
protected
function GetProviderClass: TMetaListProviderClass; override;
public
{ Public declarations }
property TableList[Kind: TMapKind]: TMetaTableList read GetTableList write SetTableList;
end;
var
TableFrame: TTableFrame;
implementation
{$R *.dfm}
{ TTableFrame }
function TTableFrame.GetProviderClass: TMetaListProviderClass;
begin
Result := TMetaTablesProvider
end;
function TTableFrame.GetTableList(Kind: TMapKind): TMetaTableList;
begin
Result := TMetaTableList(TMetaListProvider(GetProvider(Kind)).list);
end;
procedure TTableFrame.SetTableList(Kind: TMapKind; const Value: TMetaTableList);
begin
TMetaListProvider(GetProvider(Kind)).list := Value;
end;
end.
|
unit PrimePool;
interface
uses
SysUtils, Classes, Generics.Collections, SyncObjs, ThreadPool, Types;
type
TPrimeTask = class(TPoolTask)
{**
* Input related
*}
protected
FFromNumber:Cardinal;
FToNumber:Cardinal;
{**
* Output related
*}
protected
FPrimesOutput:TCardinalDynArray;
procedure AddPrime(Prime:Cardinal);
{**
* Overriden stuff
*}
protected
procedure Assign(Source:TPoolTask); override;
function IsTheSame(Compare:TPoolTask):Boolean; override;
{**
* Public input
*}
public
property FromNumber:Cardinal read FFromNumber write FFromNumber;
property ToNumber:Cardinal read FToNumber write FToNumber;
{**
* Public output
*}
public
property PrimesOutput:TCardinalDynArray read FPrimesOutput;
end;
TPrimeWorker = class(TPoolWorker)
protected
procedure ExecuteTask; override;
end;
TPrimeManager = class(TPoolManager)
protected
class function WorkerClass:TPoolWorkerClass; override;
public
class function Singleton:TPrimeManager; reintroduce;
end;
implementation
{** TPrimeTask **}
procedure TPrimeTask.AddPrime(Prime:Cardinal);
var
InsertIndex:Integer;
begin
InsertIndex:=Length(FPrimesOutput);
SetLength(FPrimesOutput, InsertIndex + 1);
FPrimesOutput[InsertIndex]:=Prime;
end;
{**
* Assign only data which is required for do the job (no calculated data)
*}
procedure TPrimeTask.Assign(Source:TPoolTask);
var
PT:TPrimeTask;
begin
inherited Assign(Source);
PT:=TPrimeTask(Source);
FromNumber:=PT.FromNumber;
ToNumber:=PT.ToNumber;
end;
function TPrimeTask.IsTheSame(Compare:TPoolTask):Boolean;
var
PT:TPrimeTask;
begin
Result:=Compare is TPrimeTask;
if not Result then
Exit;
PT:=TPrimeTask(Compare);
Result:=(PT.FromNumber = FromNumber) and (PT.ToNumber = ToNumber);
end;
{** TPrimeWorker **}
procedure TPrimeWorker.ExecuteTask;
var
cc:Cardinal;
{**
* Local representation of the property Task, because it's expensive to get it often.
*}
Task:TPrimeTask;
function IsPrime(Test:Cardinal):Boolean;
var
h:Cardinal;
begin
Result:=Test > 1;
if not Result then
Exit;
for h:=2 to Trunc(Test/2) do
if Test mod h = 0 then
begin
Result:=FALSE;
Exit;
end;
end;
begin
Task:=TPrimeTask(ContextTask);
cc:=Task.FromNumber;
while not Canceled and (cc < Task.ToNumber) do
begin
if IsPrime(cc) then
Task.AddPrime(cc);
Inc(cc);
end;
DoneTask(TRUE);
end;
{** TPrimeManager **}
class function TPrimeManager.Singleton:TPrimeManager;
begin
Result:=TPrimeManager(inherited Singleton);
end;
class function TPrimeManager.WorkerClass:TPoolWorkerClass;
begin
Result:=TPrimeWorker;
end;
end.
|
unit Menus.View.Clientes;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Layouts, Menus.Controller.Entity.Interfaces,
Data.DB, System.Rtti, FMX.Grid.Style,
FMX.ScrollBox, FMX.Grid, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Fmx.Bind.Grid,
System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Components,
Data.Bind.Grid, Data.Bind.DBScope, Menus.Controller.Facade;
type
TFrmCliente = class(TForm)
ToolBar1: TToolBar;
Label1: TLabel;
Layout1: TLayout;
dsListaDados: TDataSource;
StringGrid1: TStringGrid;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FEntity : iControllerEntity;
procedure PreencherDados;
public
{ Public declarations }
end;
var
FrmCliente: TFrmCliente;
implementation
{$R *.fmx}
procedure TFrmCliente.FormCreate(Sender: TObject);
begin
{TControllerListaBoxFactory.New.Clientes(Layout1).Exibir;
FEntity := TControllerEntityFactory.New.Cliente;
FEntity.Lista(dsListaDados);}
FEntity := TControllerFacade.New.Entity.Entity.Cliente.Lista(dsListaDados);
TControllerFacade.New.Menu.ListBox.Clientes(Layout1).Exibir;
end;
procedure TFrmCliente.PreencherDados;
begin
///
end;
initialization
RegisterFmxClasses([TFrmCliente]);
end.
|
Unit RunThread;
// Поток, проверяющий кол-во запущенных потоков и разрешающий
// или запрещающий создание новых потоков
Interface
Uses
Classes, Main, Common, GlobVar;
Type
TRunThread = Class(TThread)
Private
{ Private declarations }
Protected
Procedure Execute; Override;
End;
Var
thRunThread : TRunThread ;
Implementation
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TRunThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end; }
{ TRunThread }
Procedure TRunThread.Execute;
Begin
{ Place thread code here }
While Not Terminated Do
Begin
Try
CriticalSection.Enter ;
If gCountAll < GlobalSetting.CurrentMultiThreadingBackLinks
Then gRunNewThread := True
Else gRunNewThread := False ;
Finally
CriticalSection.Leave ;
End ;
End ;
End;
End.
|
unit Procesor.Currency;
interface
uses
System.SysUtils,
System.Classes,
System.JSON,
System.Generics.Collections,
System.Net.HttpClient,
Procesor.Currency.Intf;
type
ECurrencyProcessorError = class(Exception);
TCurrencyProcessor = class(TInterfacedObject, ICurrencyProcessor)
private
fCurrencyRates: TArray<TCurrencyRate>;
function GetCurrencyRate(const aCode: string): Currency;
public
constructor Create;
function IsInitialiased: boolean;
procedure Download(const aURL: string);
function IsCurrencySupported(const aCode: string): boolean;
function Convert(aValue: Currency; const aFromCurrency: string;
const aToCurrency: string): Currency;
end;
implementation
constructor TCurrencyProcessor.Create;
begin
fCurrencyRates := nil;
end;
function TCurrencyProcessor.IsInitialiased: boolean;
begin
Result := (fCurrencyRates <> nil);
end;
procedure TCurrencyProcessor.Download(const aURL: string);
var
aStringStream: TStringStream;
aHTTPClient: THTTPClient;
jsResult: TJSONObject;
jsRates: TJSONObject;
idx: integer;
begin
aStringStream := TStringStream.Create('', TEncoding.UTF8);
try
aHTTPClient := THTTPClient.Create;
try
aHTTPClient.Get(aURL, aStringStream);
jsResult := TJSONObject.ParseJSONValue(aStringStream.DataString)
as TJSONObject;
try
jsRates := jsResult.GetValue('rates') as TJSONObject;
SetLength(fCurrencyRates, jsRates.Count + 1);
fCurrencyRates[0].Code := 'EUR';
fCurrencyRates[0].Rate := 1.0000;
for idx := 0 to jsRates.Count - 1 do
begin
fCurrencyRates[idx + 1].Code := jsRates.Pairs[idx].JsonString.Value;
fCurrencyRates[idx + 1].Rate := jsRates.Pairs[idx]
.JsonValue.AsType<double>;
end;
finally
jsResult.Free;
end;
finally
aHTTPClient.Free;
end;
finally
aStringStream.Free;
end;
end;
function TCurrencyProcessor.IsCurrencySupported(const aCode: string): boolean;
var
idx: integer;
begin
for idx := 0 to High(fCurrencyRates) do
if fCurrencyRates[idx].Code = aCode then
Exit(True);
Result := False;
end;
function TCurrencyProcessor.GetCurrencyRate(const aCode: string): Currency;
var
idx: integer;
begin
for idx := 0 to High(fCurrencyRates) do
if fCurrencyRates[idx].Code = aCode then
Exit(fCurrencyRates[idx].Rate);
raise ECurrencyProcessorError.Create('Unregistered currency code: ' + aCode);
end;
function TCurrencyProcessor.Convert(aValue: Currency;
const aFromCurrency, aToCurrency: string): Currency;
begin
Result := aValue / GetCurrencyRate(aFromCurrency) *
GetCurrencyRate(aToCurrency);
end;
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Ported to Delphi by Michal Wojcik.
//
// Modified or written by Object Mentor, Inc. for inclusion with FitNesse.
// Copyright (c) 2002 Cunningham & Cunningham, Inc.
// Released under the terms of the GNU General Public License version 2 or later.
// Derived from ColumnFixture.java by Martin Chernenkoff, CHI Software Design
// Ported to Delphi by Salim Nair.
{$H+}
unit ColumnFixture;
interface
uses
Field,
Method,
Classes,
TypInfo,
Parse,
Fixture,
SysUtils,
TypeAdapter,
Contnrs,
Binding;
type
TColumnFixture = class(TFixture)
private
procedure setupColumnBindings(theSize : integer);
function getColumnBinding(idx : integer) : TBinding;
procedure setColumnBinding(idx : integer; const Value : TBinding);
function createBinding(column : Integer; heads : TParse) : TBinding;
protected
FColumnBindings : TObjectList;
hasExecuted : Boolean;
procedure execute; virtual;
function bindMethod(const theName : string) : TTypeAdapter;
function bindField(const theName : string) : TTypeAdapter;
public
property ColumnBindings[idx : integer] : TBinding read getColumnBinding write setColumnBinding;
procedure bind(heads : TParse);
procedure doCell(cell : TParse; column : integer); override;
procedure doRows(Rows : TParse); override;
procedure doRow(row : TParse); override;
procedure checkCell(cell : TParse; a : TObject {TTypeAdapter}); override;
procedure reset; virtual;
procedure executeIfNeeded;
constructor Create; override;
destructor Destroy; override;
end;
implementation
{ TColumnFixture }
procedure TColumnFixture.setupColumnBindings(theSize : integer);
var
i : integer;
begin
FColumnBindings.Clear;
for i := 0 to theSize - 1 do
FColumnBindings.add(nil);
end;
procedure TColumnFixture.bind(heads : TParse);
(*
protected void bind(Parse heads)
{
try
{
columnBindings = new Binding[heads.size()];
for(int i = 0; heads != null; i++, heads = heads.more)
{
columnBindings[i] = createBinding(i, heads);
}
}
catch(Throwable throwable)
{
exception(heads, throwable);
}
}
*)
var
i : Integer;
begin
try
setupColumnBindings(heads.size);
i := 0;
while heads <> nil do
begin
columnBindings[i] := createBinding(i, heads);
Inc(i);
heads := heads.more;
end;
except
on throwable : Exception do
doException(heads, throwable);
end;
end;
function TColumnFixture.createBinding(column : Integer; heads : TParse) : TBinding;
begin
Result := TBinding.doCreate(self, heads.text());
end;
(*
protected Binding createBinding(int column, Parse heads) throws Throwable
{
return Binding.create(this, heads.text());
}
*)
procedure TColumnFixture.doCell(cell : TParse; column : integer);
(*
public void doCell(Parse cell, int column)
{
try
{
columnBindings[column].doCell(this, cell);
}
catch(Throwable e)
{
exception(cell, e);
}
}
*)
begin
try
columnBindings[column].doCell(self, cell);
except
on e : Exception do
doException(cell, e);
end;
end;
procedure TColumnFixture.doRows(Rows : TParse);
begin
(*
public void doRows(Parse rows) {
bind(rows.parts);
super.doRows(rows.more);
}
*)
bind(rows.parts);
inherited doRows(rows.more);
end;
procedure TColumnFixture.doRow(row : TParse);
begin
(*
public void doRow(Parse row)
{
hasExecuted = false;
try
{
reset();
super.doRow(row);
if(!hasExecuted)
{
execute();
}
}
catch(Exception e)
{
exception(row.leaf(), e);
}
}
*)
hasExecuted := false;
try
reset();
inherited doRow(row);
if (not hasExecuted) then
execute();
except
on e : Exception do
doException(row.leaf(), e);
end;
end;
procedure TColumnFixture.reset();
begin
// about to process first cell of row
end;
procedure TColumnFixture.execute();
begin
// about to process first method call of row
end;
procedure TColumnFixture.checkCell(cell : TParse; a : TObject {TTypeAdapter});
begin
(*
public void check(Parse cell, TypeAdapter a)
{
try
{
executeIfNeeded();
}
catch(Exception e)
{
exception(cell, e);
}
super.check(cell, a);
}
*)
try
executeIfNeeded();
except
on e : Exception do
doException(cell, e);
end;
inherited checkCell(cell, a);
end;
procedure TColumnFixture.executeIfNeeded();
begin
(*
protected void executeIfNeeded() throws Exception
{
if(!hasExecuted)
{
hasExecuted = true;
execute();
}
}
*)
if (not hasExecuted) then
begin
hasExecuted := true;
execute();
end;
end;
function TColumnFixture.getColumnBinding(idx : integer) : TBinding;
begin
result := TBinding(FColumnBindings[idx]);
end;
procedure TColumnFixture.setColumnBinding(idx : integer;
const Value : TBinding);
begin
FColumnBindings[idx] := Value;
end;
function TColumnFixture.bindField(const theName : string) : TTypeAdapter;
begin
result := TTypeAdapter.AdapterOn(self,
TField.Create(getTargetClass, theName));
end;
function TColumnFixture.bindMethod(const theName : string) : TTypeAdapter;
begin
result := TTypeAdapter.AdapterOn(self, TMethod.Create(getTargetClass, theName));
end;
constructor TColumnFixture.Create;
begin
inherited Create;
FColumnBindings := TObjectList.Create;
end;
destructor TColumnFixture.Destroy;
begin
FColumnBindings.Free;
inherited;
end;
end.
|
unit FModelPreview;
interface
uses
FDisplay, FUnit;
procedure ModelPreview_SetModel(attr : PUnitAttributes);
procedure ModelPreview_UpdateView();
procedure ModelPreview_Draw(id : integer);
var
ModelPreview_Model : TModel = nil;
implementation
uses
Windows, FOpenGl, FBase, FRedirect, FEditorModelView, FPlayer;
procedure ModelPreview_SetModel(attr : PUnitAttributes);
begin
if ModelPreview_Model = nil then begin
ModelPreview_Model := TModel.Create();
ModelPreview_Model.RealPos.X := 0;
ModelPreview_Model.RealPos.Y := 0;
ModelPreview_Model.RealPos.Z := 0;
ModelPreview_Model.ModelScale := attr.ModelScale;
ModelPreview_Model.TeamColor := TeamColor[2];
end;
ModelPreview_Model.SetPath(attr.Model);
end;
procedure ModelPreview_UpdateView();
begin
glViewport(0, 0, EditorModelView.Width, EditorModelView.Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(40, EditorModelView.Width / EditorModelView.Height, 1, 10000);
gluLookAt(0, -1000, 250,
0, 0, 250,
0, 0, 1);
glMatrixMode(GL_MODELVIEW);
end;
procedure ModelPreview_Draw(id : integer);
begin
SetGLFrame(id);
glClear(GL_DEPTH_BUFFER_BIT or GL_COLOR_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
ModelPreview_UpdateView();
glClearColor(0, 0, 0, 0);
if ModelPreview_Model <> nil then begin
glPushMatrix();
glTranslatef(EditorView.transx, 0, EditorView.transy);
glrotatef(EditorView.rotat, 0, 0, 1);
glscalef(EditorView.zoom, EditorView.zoom, EditorView.zoom);
ModelPreview_Model.UpdateAnim();
ModelPreview_Model.Display();
glPopMatrix();
end;
glFlush();
SwapBuffers(GLFrames[id].dc);
end;
end.
|
unit AqDrop.Core.Bindings;
interface
uses
System.Classes,
System.Rtti,
Data.Bind.ObjectScope,
AqDrop.Core.Collections.Intf;
type
TAqSetListBindSource<T: class; I: IAqReadableList<T>> = procedure(pSender: TBindSourceAdapter; pList: I);
TAqBaseListBindSourceAdapter<T: class; I: IAqReadableList<T>> = class(TBaseListBindSourceAdapter)
strict private
FList: I;
FOnBeforeSetList: TAqSetListBindSource<T, I>;
FOnAfterSetList: TAqSetListBindSource<T, I>;
strict protected
procedure CheckList;
function GetObjectType: TRttiType; override;
function GetCurrent: TObject; override;
function GetCount: Int32; override;
function GetCanActivate: Boolean; override;
function SupportsNestedFields: Boolean; override;
procedure AddFields; virtual;
procedure DoOnBeforeSetList(pList: I); virtual;
procedure DoOnAfterSetList; virtual;
function GetCurrentObject: T;
public
constructor Create(AOwner: TComponent; pList: I); reintroduce; overload; virtual;
procedure SetList(pList: I);
property List: I read FList;
property OnBeforeSetList: TAqSetListBindSource<T, I> read FOnBeforeSetList write FOnBeforeSetList;
property OnAfterSetList: TAqSetListBindSource<T, I> read FOnAfterSetList write FOnAfterSetList;
property CurrentObject: T read GetCurrentObject;
end;
TAqReadListBindSourceAdapter<T: class> = class(TAqBaseListBindSourceAdapter<T, IAqReadableList<T>>)
strict protected
function GetCanDelete: Boolean; override;
function GetCanInsert: Boolean; override;
function GetCanModify: Boolean; override;
function GetCanApplyUpdates: Boolean; override;
function GetCanCancelUpdates: Boolean; override;
end;
TAqListBindSourceAdapter<T: class> = class(TAqBaseListBindSourceAdapter<T, IAqList<T>>)
strict private
FInstanceFactory: TBindSourceAdapterInstanceFactory;
function GetItemInstanceFactory: TBindSourceAdapterInstanceFactory;
strict protected
function CreateItemInstance: T; virtual;
procedure InitItemInstance(const pIntance: T); virtual;
function DeleteAt(AIndex: Int32): Boolean; override;
function AppendAt: Int32; override;
function InsertAt(AIndex: Int32): Int32; override;
function GetCanDelete: Boolean; override;
function GetCanInsert: Boolean; override;
function GetCanModify: Boolean; override;
function GetCanApplyUpdates: Boolean; override;
function GetCanCancelUpdates: Boolean; override;
procedure InternalCancelUpdates; override;
procedure InternalApplyUpdates; override;
public
destructor Destroy; override;
end;
resourcestring
StrListIsNotAssigned = 'List is not Assigned';
StrNewInstanceOfTypeObjectClassNameDoesNotMatchExpectedTypeTClassName =
'New instance of type %s does not match expected type %s.';
implementation
uses
AqDrop.Core.Exceptions;
{ TAqBaseListBindSourceAdapter<T, I> }
procedure TAqBaseListBindSourceAdapter<T, I>.AddFields;
var
lType: TRttiType;
lGetMemberObject: IGetMemberObject;
begin
lType := GetObjectType;
lGetMemberObject := TBindSourceAdapterGetMemberObject.Create(Self);
AddFieldsToList(lType, Self, Self.Fields, lGetMemberObject);
AddPropertiesToList(lType, Self, Self.Fields, lGetMemberObject);
end;
procedure TAqBaseListBindSourceAdapter<T, I>.CheckList;
begin
if not Assigned(FList) then
begin
raise EAqInternal.Create(StrListIsNotAssigned);
end;
end;
constructor TAqBaseListBindSourceAdapter<T, I>.Create(AOwner: TComponent; pList: I);
begin
Create(AOwner);
SetList(pList);
end;
procedure TAqBaseListBindSourceAdapter<T, I>.DoOnAfterSetList;
begin
if Assigned(FOnAfterSetList) then
begin
FOnAfterSetList(Self, FList);
end;
end;
procedure TAqBaseListBindSourceAdapter<T, I>.DoOnBeforeSetList(pList: I);
begin
if Assigned(FOnBeforeSetList) then
begin
FOnBeforeSetList(Self, pList);
end;
end;
function TAqBaseListBindSourceAdapter<T, I>.GetCanActivate: Boolean;
begin
Result := Assigned(FList);
end;
function TAqBaseListBindSourceAdapter<T, I>.GetCount: Int32;
begin
if Assigned(FList) then
begin
Result := FList.Count;
end else begin
Result := 0;
end;
end;
function TAqBaseListBindSourceAdapter<T, I>.GetCurrent: TObject;
begin
Result := GetCurrentObject;
end;
function TAqBaseListBindSourceAdapter<T, I>.GetCurrentObject: T;
var
lIndex: Int32;
begin
lIndex := ItemIndex + ItemIndexOffset;
if Assigned(FList) and (lIndex >= 0) and (lIndex < FList.Count) then
begin
Result := FList.Items[lIndex];
end else begin
Result := nil;
end;
end;
function TAqBaseListBindSourceAdapter<T, I>.GetObjectType: TRttiType;
begin
Result := TRttiContext.Create.GetType(T.ClassInfo);
end;
procedure TAqBaseListBindSourceAdapter<T, I>.SetList(pList: I);
begin
DoOnBeforeSetList(pList);
Active := False;
if Assigned(FList) then
begin
ClearFields;
end;
FList := pList;
if Assigned(FList) then
begin
AddFields;
end;
DoOnAfterSetList;
end;
function TAqBaseListBindSourceAdapter<T, I>.SupportsNestedFields: Boolean;
begin
Result := True;
end;
{ TAqReadListBindSourceAdapter<T> }
function TAqReadListBindSourceAdapter<T>.GetCanApplyUpdates: Boolean;
begin
Result := False;
end;
function TAqReadListBindSourceAdapter<T>.GetCanCancelUpdates: Boolean;
begin
Result := False;
end;
function TAqReadListBindSourceAdapter<T>.GetCanDelete: Boolean;
begin
Result := False;
end;
function TAqReadListBindSourceAdapter<T>.GetCanInsert: Boolean;
begin
Result := False;
end;
function TAqReadListBindSourceAdapter<T>.GetCanModify: Boolean;
begin
Result := False;
end;
{ TAqListBindSourceAdapter<T> }
function TAqListBindSourceAdapter<T>.AppendAt: Int32;
var
lNewItem: T;
lIndex: Int32;
lHandled: Boolean;
lAppended: Boolean;
begin
CheckList;
DoListAppend(lHandled, lAppended);
if lHandled then
begin
if lAppended then
begin
Result := List.Count - 1;
end else begin
Result := -1;
end;
end else begin
Result := -1;
lNewItem := CreateItemInstance;
if Assigned(lNewItem) then
begin
InitItemInstance(lNewItem);
List.Add(lNewItem);
Result := List.Count - 1;
end;
end;
end;
function TAqListBindSourceAdapter<T>.CreateItemInstance: T;
var
lObject: TObject;
begin
CheckList;
Result := nil;
Assert(GetItemInstanceFactory.CanConstructInstance);
if GetItemInstanceFactory.CanConstructInstance then
begin
lObject := GetItemInstanceFactory.ConstructInstance;
try
if not (lObject is T) then
begin
raise EAqInternal.CreateFmt(StrNewInstanceOfTypeObjectClassNameDoesNotMatchExpectedTypeTClassName,
[lObject.QualifiedClassName, T.QualifiedClassName]);
end;
Result := lObject as T;
except
lObject.Free;
raise;
end;
end;
end;
function TAqListBindSourceAdapter<T>.DeleteAt(AIndex: Int32): Boolean;
var
lHandled: Boolean;
begin
CheckList;
DoListDelete(AIndex, lHandled, Result);
if not lHandled then
begin
Result := (AIndex >= 0) and (AIndex < List.Count);
if Result then
begin
List.Delete(AIndex);
end;
end;
end;
destructor TAqListBindSourceAdapter<T>.Destroy;
begin
FInstanceFactory.Free;
inherited;
end;
function TAqListBindSourceAdapter<T>.GetCanApplyUpdates: Boolean;
var
lHasUpdates: Boolean;
begin
Result := (loptAllowApplyUpdates in Options) and Assigned(OnApplyUpdates);
if Result and Assigned(OnHasUpdates) then
begin
lHasUpdates := False;
OnHasUpdates(Self, lHasUpdates);
Result := lHasUpdates;
end;
end;
function TAqListBindSourceAdapter<T>.GetCanCancelUpdates: Boolean;
var
lHasUpdates: Boolean;
begin
Result := (loptAllowCancelUpdates in Options) and Assigned(OnCancelUpdates);
if Result and Assigned(OnHasUpdates) then
begin
lHasUpdates := False;
OnHasUpdates(Self, lHasUpdates);
Result := lHasUpdates;
end;
end;
function TAqListBindSourceAdapter<T>.GetCanDelete: Boolean;
begin
Result := loptAllowDelete in Options;
end;
function TAqListBindSourceAdapter<T>.GetCanInsert: Boolean;
begin
Result := (loptAllowInsert in Options);
if Result then
begin
Result := Assigned(OnCreateItemInstance) or GetItemInstanceFactory.CheckConstructor;
end;
end;
function TAqListBindSourceAdapter<T>.GetCanModify: Boolean;
begin
Result := (loptAllowModify in Options);
end;
function TAqListBindSourceAdapter<T>.GetItemInstanceFactory: TBindSourceAdapterInstanceFactory;
begin
if not Assigned(FInstanceFactory) then
begin
FInstanceFactory := TBindSourceAdapterInstanceFactory.Create(GetObjectType);
end;
Result := FInstanceFactory;
end;
procedure TAqListBindSourceAdapter<T>.InitItemInstance(const pIntance: T);
begin
DoInitItemInstance(pIntance);
end;
function TAqListBindSourceAdapter<T>.InsertAt(AIndex: Int32): Int32;
var
lNewItem: T;
lHandled: Boolean;
begin
DoListInsert(AIndex, lHandled, Result);
if not lHandled then
begin
Result := -1;
lNewItem := CreateItemInstance;
if Assigned(lNewItem) then
begin
InitItemInstance(lNewItem);
List.Insert(AIndex, lNewItem);
Result := AIndex;
end;
end;
end;
procedure TAqListBindSourceAdapter<T>.InternalApplyUpdates;
begin
if Assigned(OnApplyUpdates) then
begin
OnApplyUpdates(Self);
end;
end;
procedure TAqListBindSourceAdapter<T>.InternalCancelUpdates;
begin
if Assigned(OnCancelUpdates) then
begin
OnCancelUpdates(Self);
end;
end;
end.
|
unit uCliente;
interface
type
TCliente = class
private
FNome: string;
FEndereco: string;
procedure SetEndereco(const Value: string);
procedure SetNome(const Value: string);
public
procedure Salvar;
property Nome: string read FNome write SetNome;
property Endereco: string read FEndereco write SetEndereco;
end;
TClientePF = class(TCliente)
private
FCPF: Int64;
procedure SetCPF(const Value: Int64);
public
property CPF: Int64 read FCPF write SetCPF;
end;
implementation
uses uConexao, System.SysUtils;
{ TCliente }
procedure TCliente.Salvar;
begin
try
TConexao.ExecutarSQL('insert into CLIENTE ( /* CAMPOS */ ) values ( /* VALORES */ )');
except
on E: Exception do
begin
E.RaiseOuterException(Exception.Create('Aconteceu um erro ao salvar o cliente.'));
end;
end;
end;
procedure TCliente.SetEndereco(const Value: string);
begin
FEndereco := Value;
end;
procedure TCliente.SetNome(const Value: string);
begin
FNome := Value;
end;
{ TClientePF }
procedure TClientePF.SetCPF(const Value: Int64);
begin
FCPF := Value;
end;
end.
|
unit uFinFluxo;
interface
uses
Classes, SysUtils,
mCollection, mCollectionItem,
uFinConta;
type
TFin_Fluxo = class;
TFin_FluxoClass = class of TFin_Fluxo;
TFin_FluxoList = class;
TFin_FluxoListClass = class of TFin_FluxoList;
TFin_Fluxo = class(TmCollectionItem)
private
fCd_Conta: String;
fU_Version: String;
fCd_Operador: Real;
fDt_Cadastro: TDateTime;
fDs_Conta: String;
fTp_Conta: String;
fDs_Formula: String;
fVl_Total: Real;
fVl_Media: Real;
fVl_Janeiro: Real;
fVl_Fevereiro: Real;
fVl_Marco: Real;
fVl_Abril: Real;
fVl_Maio: Real;
fVl_Junho: Real;
fVl_Julho: Real;
fVl_Agosto: Real;
fVl_Setembro: Real;
fVl_Outubro: Real;
fVl_Novembro: Real;
fVl_Dezembro: Real;
fIn_Pago: String;
fObj_Conta: TFin_Conta;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
function Limpar() : TFin_Fluxo;
function Totalizar() : TFin_Fluxo;
function Setar(AObj_Fluxo : TFin_Fluxo) : TFin_Fluxo;
function Adicionar(AObj_Fluxo : TFin_Fluxo) : TFin_Fluxo;
published
property Cd_Conta: String read fCd_Conta write fCd_Conta;
property U_Version: String read fU_Version write fU_Version;
property Cd_Operador: Real read fCd_Operador write fCd_Operador;
property Dt_Cadastro: TDateTime read fDt_Cadastro write fDt_Cadastro;
property Ds_Conta: String read fDs_Conta write fDs_Conta;
property Ds_Formula: String read fDs_Formula write fDs_Formula;
property Tp_Conta: String read fTp_Conta write fTp_Conta;
property Vl_Total: Real read fVl_Total write fVl_Total;
property Vl_Media: Real read fVl_Media write fVl_Media;
property Vl_Janeiro: Real read fVl_Janeiro write fVl_Janeiro;
property Vl_Fevereiro: Real read fVl_Fevereiro write fVl_Fevereiro;
property Vl_Marco: Real read fVl_Marco write fVl_Marco;
property Vl_Abril: Real read fVl_Abril write fVl_Abril;
property Vl_Maio: Real read fVl_Maio write fVl_Maio;
property Vl_Junho: Real read fVl_Junho write fVl_Junho;
property Vl_Julho: Real read fVl_Julho write fVl_Julho;
property Vl_Agosto: Real read fVl_Agosto write fVl_Agosto;
property Vl_Setembro: Real read fVl_Setembro write fVl_Setembro;
property Vl_Outubro: Real read fVl_Outubro write fVl_Outubro;
property Vl_Novembro: Real read fVl_Novembro write fVl_Novembro;
property Vl_Dezembro: Real read fVl_Dezembro write fVl_Dezembro;
property In_Pago: String read fIn_Pago write fIn_Pago;
property Obj_Conta: TFin_Conta read fObj_Conta write fObj_Conta;
end;
TFin_FluxoList = class(TmCollection)
private
function GetItem(Index: Integer): TFin_Fluxo;
procedure SetItem(Index: Integer; Value: TFin_Fluxo);
public
constructor Create(AOwner: TPersistent);
function Add: TFin_Fluxo;
property Items[Index: Integer]: TFin_Fluxo read GetItem write SetItem; default;
end;
implementation
uses
mFloat;
{ TFin_Fluxo }
constructor TFin_Fluxo.Create(Collection: TCollection);
begin
inherited;
fObj_Conta:= TFin_Conta.Create(nil);
end;
destructor TFin_Fluxo.Destroy;
begin
inherited;
end;
//--
function TFin_Fluxo.Limpar : TFin_Fluxo;
begin
Vl_Janeiro := 0;
Vl_Fevereiro := 0;
Vl_Marco := 0;
Vl_Abril := 0;
Vl_Maio := 0;
Vl_Junho := 0;
Vl_Julho := 0;
Vl_Agosto := 0;
Vl_Setembro := 0;
Vl_Outubro := 0;
Vl_Novembro := 0;
Vl_Dezembro := 0;
Vl_Total := 0;
Vl_Media := 0;
Result := Self;
end;
function TFin_Fluxo.Totalizar : TFin_Fluxo;
begin
Vl_Total := Vl_Janeiro + Vl_Fevereiro + Vl_Marco + Vl_Abril + Vl_Maio +
Vl_Junho + Vl_Julho + Vl_Agosto + Vl_Setembro + Vl_Outubro + Vl_Novembro +
Vl_Dezembro;
Vl_Media := TmFloat.Rounded( Vl_Total / 12, 2);
Result := Self;
end;
function TFin_Fluxo.Setar(AObj_Fluxo : TFin_Fluxo) : TFin_Fluxo;
begin
Limpar();
Adicionar(AObj_Fluxo);
end;
function TFin_Fluxo.Adicionar(AObj_Fluxo : TFin_Fluxo) : TFin_Fluxo;
begin
Vl_Janeiro := Vl_Janeiro + AObj_Fluxo.fVl_Janeiro;
Vl_Fevereiro := Vl_Fevereiro + AObj_Fluxo.Vl_Fevereiro;
Vl_Marco := Vl_Marco + AObj_Fluxo.Vl_Marco;
Vl_Abril := Vl_Abril + AObj_Fluxo.Vl_Abril;
Vl_Maio := Vl_Maio + AObj_Fluxo.Vl_Maio;
Vl_Junho := Vl_Junho + AObj_Fluxo.Vl_Junho;
Vl_Julho := Vl_Julho + AObj_Fluxo.Vl_Julho;
Vl_Agosto := Vl_Agosto + AObj_Fluxo.Vl_Agosto;
Vl_Setembro := Vl_Setembro + AObj_Fluxo.Vl_Setembro;
Vl_Outubro := Vl_Outubro + AObj_Fluxo.Vl_Outubro;
Vl_Novembro := Vl_Novembro + AObj_Fluxo.Vl_Novembro;
Vl_Dezembro := Vl_Dezembro + AObj_Fluxo.Vl_Dezembro;
Totalizar();
end;
{ TFin_FluxoList }
constructor TFin_FluxoList.Create(AOwner: TPersistent);
begin
inherited Create(TFin_Fluxo);
end;
function TFin_FluxoList.Add: TFin_Fluxo;
begin
Result := TFin_Fluxo(inherited Add);
Result.create(Self);
end;
function TFin_FluxoList.GetItem(Index: Integer): TFin_Fluxo;
begin
Result := TFin_Fluxo(inherited GetItem(Index));
end;
procedure TFin_FluxoList.SetItem(Index: Integer; Value: TFin_Fluxo);
begin
inherited SetItem(Index, Value);
end;
end.
|
unit mnWaitDialogTestCase;
{
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, mnWaitDialog;
type
TmnWaitDialogTestCase = class(TTestCase)
strict private
WaitDialog: mnTWaitDialog;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure testWorkload;
procedure testProgress;
procedure testAddProgress;
procedure testCancelSeries;
end;
implementation
uses mnDebug, SysUtils;
{ TmnWaitDialogTestCase }
procedure TmnWaitDialogTestCase.SetUp;
begin
WaitDialog := mnTWaitDialog.Create(nil);
end;
procedure TmnWaitDialogTestCase.TearDown;
begin
WaitDialog.Free;
end;
procedure TmnWaitDialogTestCase.testWorkload;
begin
CheckEquals(WaitDialog.Workload, 0);
WaitDialog.Progress := 10;
WaitDialog.Workload := 100;
CheckEquals(WaitDialog.Workload, 100);
CheckEquals(WaitDialog.Progress, 0);
end;
procedure TmnWaitDialogTestCase.testProgress;
begin
CheckEquals(WaitDialog.Progress, 0);
WaitDialog.Workload := 100;
WaitDialog.Progress := 10;
CheckEquals(WaitDialog.Progress, 10);
end;
procedure TmnWaitDialogTestCase.testAddProgress;
begin
CheckEquals(WaitDialog.Progress, 0);
WaitDialog.AddProgress(10);
CheckEquals(WaitDialog.Progress, 10);
WaitDialog.AddProgress;
CheckEquals(WaitDialog.Progress, 11);
end;
procedure TmnWaitDialogTestCase.testCancelSeries;
begin
CheckFalse(WaitDialog.Cancelled);
WaitDialog.Cancel;
Check(WaitDialog.Cancelled);
try
WaitDialog.CheckCancelled;
mnNeverGoesHere;
except
on E: Exception do CheckEquals(E.ClassType, EWaitDialogCancelledException);
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TmnWaitDialogTestCase.Suite);
end. |
unit VirtualKeyTable;
{$mode objfpc}{$H+}
interface
const
vk_table: array [0..255] of string = (
'0x00 ',
'VK_LBUTTON ',
'VK_RBUTTON ',
'VK_CANCEL ',
'VK_MBUTTON ',
'VK_XBUTTON1 ',
'VK_XBUTTON2 ',
'0x07 ',
'VK_BACK ',
'VK_TAB ',
'0x0A ',
'0x0B ',
'VK_CLEAR ',
'VK_RETURN ',
'0x0E ',
'0x0F ',
'VK_SHIFT ',
'VK_CONTROL ',
'VK_MENU ',
'VK_PAUSE ',
'VK_CAPITAL ',
'VK_KANA ',
'0x16 ',
'VK_JUNJA ',
'VK_FINAL ',
'VK_KANJI ',
'0x1A ',
'VK_ESCAPE ',
'VK_CONVERT ',
'VK_NONCONVERT ',
'VK_ACCEPT ',
'VK_MODECHANGE ',
'VK_SPACE ',
'VK_PRIOR ',
'VK_NEXT ',
'VK_END ',
'VK_HOME ',
'VK_LEFT ',
'VK_UP ',
'VK_RIGHT ',
'VK_DOWN ',
'VK_SELECT ',
'VK_PRINT ',
'VK_EXECUTE ',
'VK_SNAPSHOT ',
'VK_INSERT ',
'VK_DELETE ',
'VK_HELP ',
'"0" ',
'"1" ',
'"2" ',
'"3" ',
'"4" ',
'"5" ',
'"6" ',
'"7" ',
'"8" ',
'"9" ',
'0x3A ',
'0x3B ',
'0x3C ',
'0x3D ',
'0x3E ',
'0x3F ',
'0x40 ',
'"A" ',
'"B" ',
'"C" ',
'"D" ',
'"E" ',
'"F" ',
'"G" ',
'"H" ',
'"I" ',
'"J" ',
'"K" ',
'"L" ',
'"M" ',
'"N" ',
'"O" ',
'"P" ',
'"Q" ',
'"R" ',
'"S" ',
'"T" ',
'"U" ',
'"V" ',
'"W" ',
'"X" ',
'"Y" ',
'"Z" ',
'VK_LWIN ',
'VK_RWIN ',
'VK_APPS ',
'0x5E ',
'VK_SLEEP ',
'VK_NUMPAD0 ',
'VK_NUMPAD1 ',
'VK_NUMPAD2 ',
'VK_NUMPAD3 ',
'VK_NUMPAD4 ',
'VK_NUMPAD5 ',
'VK_NUMPAD6 ',
'VK_NUMPAD7 ',
'VK_NUMPAD8 ',
'VK_NUMPAD9 ',
'VK_MULTIPLY ',
'VK_ADD ',
'VK_SEPARATOR ',
'VK_SUBTRACT ',
'VK_DECIMAL ',
'VK_DIVIDE ',
'VK_F1 ',
'VK_F2 ',
'VK_F3 ',
'VK_F4 ',
'VK_F5 ',
'VK_F6 ',
'VK_F7 ',
'VK_F8 ',
'VK_F9 ',
'VK_F10 ',
'VK_F11 ',
'VK_F12 ',
'VK_F13 ',
'VK_F14 ',
'VK_F15 ',
'VK_F16 ',
'VK_F17 ',
'VK_F18 ',
'VK_F19 ',
'VK_F20 ',
'VK_F21 ',
'VK_F22 ',
'VK_F23 ',
'VK_F24 ',
'0x88 ',
'0x89 ',
'0x8A ',
'0x8B ',
'0x8C ',
'0x8D ',
'0x8E ',
'0x8F ',
'VK_NUMLOCK ',
'VK_SCROLL ',
'0x92 ',
'0x93 ',
'0x94 ',
'0x95 ',
'0x96 ',
'0x97 ',
'0x98 ',
'0x99 ',
'0x9A ',
'0x9B ',
'0x9C ',
'0x9D ',
'0x9E ',
'0x9F ',
'VK_LSHIFT ',
'VK_RSHIFT ',
'VK_LCONTROL ',
'VK_RCONTROL ',
'VK_LMENU ',
'VK_RMENU ',
'VK_BROWSER_BACK ',
'VK_BROWSER_FORWARD ',
'VK_BROWSER_REFRESH ',
'VK_BROWSER_STOP ',
'VK_BROWSER_SEARCH ',
'VK_BROWSER_FAVORITES ',
'VK_BROWSER_HOME ',
'VK_VOLUME_MUTE ',
'VK_VOLUME_DOWN ',
'VK_VOLUME_UP ',
'VK_MEDIA_NEXT_TRACK ',
'VK_MEDIA_PREV_TRACK ',
'VK_MEDIA_STOP ',
'VK_MEDIA_PLAY_PAUSE ',
'VK_LAUNCH_MAIL ',
'VK_LAUNCH_MEDIA_SELECT ',
'VK_LAUNCH_APP1 ',
'VK_LAUNCH_APP2 ',
'0xB8 ',
'0xB9 ',
'VK_OEM_1 ',
'VK_OEM_PLUS ',
'VK_OEM_COMMA ',
'VK_OEM_MINUS ',
'VK_OEM_PERIOD ',
'VK_OEM_2 ',
'VK_OEM_3 ',
'0xC1 ',
'0xC2 ',
'0xC3 ',
'0xC4 ',
'0xC5 ',
'0xC6 ',
'0xC7 ',
'0xC8 ',
'0xC9 ',
'0xCA ',
'0xCB ',
'0xCC ',
'0xCD ',
'0xCE ',
'0xCF ',
'0xD0 ',
'0xD1 ',
'0xD2 ',
'0xD3 ',
'0xD4 ',
'0xD5 ',
'0xD6 ',
'0xD7 ',
'0xD8 ',
'0xD9 ',
'0xDA ',
'VK_OEM_4 ',
'VK_OEM_5 ',
'VK_OEM_6 ',
'VK_OEM_7 ',
'VK_OEM_8 ',
'0xE0 ',
'0xE1 ',
'VK_OEM_102 ',
'0xE3 ',
'0xE4 ',
'VK_PROCESSKEY ',
'0xE6 ',
'VK_PACKET ',
'0xE8 ',
'0xE9 ',
'0xEA ',
'0xEB ',
'0xEC ',
'0xED ',
'0xEE ',
'0xEF ',
'0xF0 ',
'0xF1 ',
'0xF2 ',
'0xF3 ',
'0xF4 ',
'0xF5 ',
'VK_ATTN ',
'VK_CRSEL ',
'VK_EXSEL ',
'VK_EREOF ',
'VK_PLAY ',
'VK_ZOOM ',
'VK_NONAME ',
'VK_PA1 ',
'VK_OEM_CLEAR ',
'0xFF '
);
implementation
end.
|
unit uMachineStack;
// Ths source is distributed under Apache 2.0
// Copyright (C) 2019-2020 Herbert M Sauro
// Author Contact Information:
// email: hsauro@gmail.com
interface
Uses Classes, SysUtils, uListObject, uStringObject;
type
TStackType = (stNone, stInteger, stDouble, stBoolean, stString, stList, stObject);
TMachineStackRecord = record
stackType : TStackType; // 1 byte
case TStackType of // Max 8 bytes
stInteger: (iValue : integer);
stBoolean: (bValue : boolean);
stDouble : (dValue : double);
stString : (sValue : TStringObject);
stList : (lValue : TListObject);
end;
PMachineStackRecord = ^TMachineStackRecord;
TMachineStack = array of TMachineStackRecord;
var memCount : integer;
noneStackType : TMachineStackRecord;
function stToStr (st : TStackType) : string;
implementation
function stToStr (st : TStackType) : string;
begin
case st of
stInteger: result := 'integer';
stBoolean: result := 'boolean';
stDouble : result := 'double';
stString : result := 'string';
stList : result := 'list';
end;
end;
initialization
noneStackType.stackType := stNone;
end.
|
unit UnitDealershipRegistration;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls,StrUtils,
Buttons;
type
{ TfrmDealership }
TfrmDealership = class(TForm)
btnShowValues: TBitBtn;
btnExitApp: TBitBtn;
cmbBrandSelector: TComboBox;
edtInputOdometer: TEdit;
edtInputNumberPlate: TEdit;
edtInputModelYear: TEdit;
Image1: TImage;
lblBrand: TLabel;
lblModelYear: TLabel;
lblOdometer: TLabel;
lblAddOns: TLabel;
lblType: TLabel;
lblNumberPlate: TLabel;
lsbAddOnsSelector: TListBox;
rdbTypeVehicleCar: TRadioButton;
rdbTypeVehicleVan: TRadioButton;
rdbTypeVehicleUtility: TRadioButton;
procedure btnShowValuesClick(Sender: TObject);
procedure cmbBrandSelectorChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lblBrandClick(Sender: TObject);
procedure rdbTypeVehicleCarChange(Sender: TObject);
private
public
end;
var
frmDealership: TfrmDealership;
implementation
{$R *.lfm}
{ TfrmDealership }
function CheckRequiredFields():boolean;
begin
CheckRequiredFields:= (frmDealership.cmbBrandSelector.ItemIndex = -1) or ((frmDealership.rdbTypeVehicleCar.Checked = false) and (frmDealership.rdbTypeVehicleVan.Checked = false) and (frmDealership.rdbTypeVehicleUtility.Checked = false)) or (string(frmDealership.edtInputNumberPlate.Text).IsEmpty) or string(frmDealership.edtInputOdometer.Text).IsEmpty or string(frmDealership.edtInputModelYear.Text).IsEmpty;
end;
function TypeVehicleToString():string;
begin
TypeVehicleToString:= IfThen(frmDealership.rdbTypeVehicleCar.Checked, 'Auto', '');
TypeVehicleToString:= IfThen(frmDealership.rdbTypeVehicleVan.Checked, 'Camioneta', TypeVehicleToString);
TypeVehicleToString:= IfThen(frmDealership.rdbTypeVehicleUtility.Checked, 'Utilitario', TypeVehicleToString);
end;
function AddOnsToString(): string;
var
i:integer;
begin
AddOnsToString:= '';
for i:= 0 to frmDealership.lsbAddOnsSelector.Count-1 do
begin
AddOnsToString+= IfThen(frmDealership.lsbAddOnsSelector.Selected[i], sLineBreak+ '-'+ frmDealership.lsbAddOnsSelector.Items[i], '');
end;
end;
function RegisterToString(): string;
begin
RegisterToString:='Marca: '+ frmDealership.cmbBrandSelector.Text + sLineBreak + 'Tipo: ' + TypeVehicleToString() + sLineBreak + 'Dominio: ' + frmDealership.edtInputNumberPlate.Text + sLineBreak + 'Modelo: ' + frmDealership.edtInputModelYear.Text+ sLineBreak + 'Kilometraje'+
frmDealership.edtInputOdometer.Text + sLineBreak + 'Adicionales:' + AddOnsToString();
end;
procedure TfrmDealership.FormCreate(Sender: TObject);
begin
end;
procedure TfrmDealership.btnShowValuesClick(Sender: TObject);
begin
if(CheckRequiredFields()) then ShowMessage('Revise los campos obligatorios a cargar.')
else ShowMessage(RegisterToString());
end;
procedure TfrmDealership.cmbBrandSelectorChange(Sender: TObject);
begin
end;
procedure TfrmDealership.lblBrandClick(Sender: TObject);
begin
end;
procedure TfrmDealership.rdbTypeVehicleCarChange(Sender: TObject);
begin
end;
end.
|
unit TestValues;
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is DUnitLite.
//
// The Initial Developer of the Original Code is Joe White.
// Portions created by Joe White are Copyright (C) 2007
// Joe White. All Rights Reserved.
//
// Contributor(s):
//
// Alternatively, the contents of this file may be used under the terms
// of the LGPL license (the "LGPL License"), in which case the
// provisions of LGPL License are applicable instead of those
// above. If you wish to allow use of your version of this file only
// under the terms of the LGPL License and not to allow others to use
// your version of this file under the MPL, indicate your decision by
// deleting the provisions above and replace them with the notice and
// other provisions required by the LGPL License. If you do not delete
// the provisions above, a recipient may use your version of this file
// under either the MPL or the LGPL License.
interface
uses
Specifications;
type
IFoo = interface
['{2D8CD618-C413-4926-AA3E-325C45812AC0}']
end;
IBar = interface
['{5157E28C-B514-4811-AAB9-DE06D63B5CC1}']
end;
TFooBar = class(TInterfacedObject, IFoo, IBar)
end;
TBase = class
end;
TSub = class(TBase)
end;
EpsilonTestValues = class
const
BaseValue = 42.0;
SameAtDefaultEpsilon = 42.00000000001;
DifferentAtDefaultEpsilon = 42.0000000001;
BarelyDifferent = 42.00000000000000001;
end;
TestEpsilonTestValues = class(TRegisterableSpecification)
strict private
FComparisonValue: Extended;
procedure CheckBaseIsEqualAsDouble;
procedure CheckBaseIsSameValueAsDouble;
procedure CheckBaseIsSameValueAsExtended;
procedure CheckBaseNotEqualAsDouble;
procedure CheckBaseNotEqualAsExtended;
procedure CheckBaseNotSameValueAsDouble;
procedure CheckBaseNotSameValueAsExtended;
published
procedure TestSameAtDefaultEpsilon;
procedure TestDifferentAtDefaultEpsilon;
procedure TestBarelyDifferent;
end;
implementation
uses
Math;
{ TestInterestingEpsilons }
procedure TestEpsilonTestValues.CheckBaseIsEqualAsDouble;
var
Base: Double;
Comparison: Double;
begin
Base := EpsilonTestValues.BaseValue;
Comparison := FComparisonValue;
CheckTrue(Base = Comparison, 'Should be equal at Double precision');
end;
procedure TestEpsilonTestValues.CheckBaseIsSameValueAsDouble;
var
Base: Double;
Comparison: Double;
begin
Base := EpsilonTestValues.BaseValue;
Comparison := FComparisonValue;
CheckTrue(SameValue(Base, Comparison), 'Should be SameValue at Double precision');
end;
procedure TestEpsilonTestValues.CheckBaseIsSameValueAsExtended;
begin
CheckTrue(SameValue(EpsilonTestValues.BaseValue, FComparisonValue),
'Should be SameValue at Extended precision');
end;
procedure TestEpsilonTestValues.CheckBaseNotEqualAsDouble;
var
Base: Double;
Comparison: Double;
begin
Base := EpsilonTestValues.BaseValue;
Comparison := FComparisonValue;
CheckFalse(Base = Comparison, 'Should not be equal at Double precision');
end;
procedure TestEpsilonTestValues.CheckBaseNotEqualAsExtended;
begin
CheckFalse(EpsilonTestValues.BaseValue = FComparisonValue,
'Should not be equal at Extended precision');
end;
procedure TestEpsilonTestValues.CheckBaseNotSameValueAsDouble;
var
Base: Double;
Comparison: Double;
begin
Base := EpsilonTestValues.BaseValue;
Comparison := FComparisonValue;
CheckFalse(SameValue(Base, Comparison), 'Should not be SameValue at Double precision');
end;
procedure TestEpsilonTestValues.CheckBaseNotSameValueAsExtended;
begin
CheckFalse(SameValue(EpsilonTestValues.BaseValue, FComparisonValue),
'Should not be SameValue at Extended precision');
end;
procedure TestEpsilonTestValues.TestBarelyDifferent;
begin
FComparisonValue := EpsilonTestValues.BarelyDifferent;
CheckBaseIsEqualAsDouble;
CheckBaseNotEqualAsExtended;
CheckBaseIsSameValueAsDouble;
CheckBaseIsSameValueAsExtended;
end;
procedure TestEpsilonTestValues.TestDifferentAtDefaultEpsilon;
begin
FComparisonValue := EpsilonTestValues.DifferentAtDefaultEpsilon;
CheckBaseNotEqualAsDouble;
CheckBaseNotSameValueAsDouble;
end;
procedure TestEpsilonTestValues.TestSameAtDefaultEpsilon;
begin
FComparisonValue := EpsilonTestValues.SameAtDefaultEpsilon;
CheckBaseNotEqualAsDouble;
CheckBaseIsSameValueAsDouble;
CheckBaseNotSameValueAsExtended;
end;
initialization
TestEpsilonTestValues.Register;
end.
|
unit DW.NotificationReceiver;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
// Unit associated with workaround for: https://quality.embarcadero.com/browse/RSP-20565
// You should probably not use this unit for anything else
interface
uses
// Android
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes,
// DW
DW.MultiReceiver.Android;
type
TNotificationReceiver = class(TMultiReceiver)
protected
procedure Receive(context: JContext; intent: JIntent); override;
procedure ConfigureActions; override;
public
class function ACTION_NOTIFICATION: JString;
class function EXTRA_NOTIFICATION: JString;
class function EXTRA_NOTIFICATION_ID: JString;
end;
implementation
uses
// RTL
System.SysUtils,
// Android
Androidapi.Helpers, Androidapi.JNIBridge, Androidapi.JNI.App;
function NotificationManager: JNotificationManager;
var
LObject: JObject;
begin
LObject := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.NOTIFICATION_SERVICE);
Result := TJNotificationManager.Wrap((LObject as ILocalObject).GetObjectID);
end;
{ TNotificationReceiver }
class function TNotificationReceiver.ACTION_NOTIFICATION: JString;
begin
Result := StringToJString('ACTION_NOTIFICATION_EX');
end;
class function TNotificationReceiver.EXTRA_NOTIFICATION: JString;
begin
Result := StringToJString('EXTRA_NOTIFICATION');
end;
class function TNotificationReceiver.EXTRA_NOTIFICATION_ID: JString;
begin
Result := StringToJString('EXTRA_NOTIFICATION_ID');
end;
procedure TNotificationReceiver.ConfigureActions;
begin
IntentFilter.addAction(ACTION_NOTIFICATION);
end;
procedure TNotificationReceiver.Receive(context: JContext; intent: JIntent);
var
LNotification: JNotification;
begin
LNotification := TJNotification.Wrap(intent.getParcelableExtra(EXTRA_NOTIFICATION));
NotificationManager.notify(intent.getIntExtra(EXTRA_NOTIFICATION_ID, 0), LNotification);
end;
end.
|
unit SaveStartFile;
interface
uses
Winapi.Windows, vcl.Forms, system.SysUtils, system.Classes,
FIBQuery, pFIBQuery, FIBDatabase, pFIBDatabase, vcl.ExtCtrls;
type
TMutexObj = class( TObject )
protected
FHandle: THandle;
private
//
public
constructor Create(const Name: string);
destructor Destroy; override;
function GetSignal: Boolean;
function Release: Boolean;
property Handle: THandle read FHandle;
end;
TSaveStart = class
private
Query: TFIBQuery;
IBDB: TpFIBDatabase;
IBTr: TpFIBTransaction;
Mutex: TMutexObj;
procedure WriteToFile(FIleName: String);
function GetMutexName: String;
public
constructor Create;
destructor Destroy; override;
class procedure SaveExecute;
end;
{$WARN SYMBOL_PLATFORM OFF}
implementation
{ TMutex }
constructor TMutexObj.Create(const Name: string);
var
MutexName : array[ 0..MAX_PATH ] of Char;
L, N: Integer;
begin
try
L := GetModuleFileName( MainInstance, MutexName, SizeOf( MutexName ));
except
Raise;
end;
For N := 0 to L - 1 do
if MutexName[ N ] = '\' then
MutexName[ N ] := '_';
StrCat( MutexName, PChar( '_' + Name ));
FHandle := CreateMutex( nil, False, MutexName );
if FHandle = 0 then
Abort;
end;
destructor TMutexObj.Destroy;
begin
if FHandle <> 0 then
CloseHandle(FHandle);
inherited;
end;
function TMutexObj.GetSignal: Boolean;
const
TimeOut = 600000; // ∆дем 10 минут 60 * 10 * 1000
begin
Result := WaitForSingleObject(FHandle, LongWord( TimeOut )) = WAIT_OBJECT_0;
end;
function TMutexObj.Release: Boolean;
begin
Result := ReleaseMutex( FHandle );
end;
{ TSaveStart }
procedure TSaveStart.WriteToFile( FIleName: String );
var
F: TFileStream;
File_New: Integer;
UpdateDate: Integer;
begin
UpdateDate := -1;
try
F := TFileStream.Create( FileName, fmCreate );
except
Exit;
end;
try
F.Position := 0;
try
Query.FieldByName( 'EXE' ).SaveToStream( F );
UpdateDate := DateTimeToFileDate( Query.FieldByName( 'DATE_UPDATE' ).AsDateTime );
except
raise;
end;
finally
F.Free;
end;
If UpdateDate = -1 then
Exit;
SetFileAttributes( PChar( FileName ), FILE_ATTRIBUTE_NORMAL );
File_New := FileOpen( FileName, fmOpenReadWrite );
try
try
FileSetDate( File_New, UpdateDate );
except
Raise;
end;
finally
FileClose( File_New );
end;
end;
{ TSaveStart }
constructor TSaveStart.Create;
const
sqlValue =
'SELECT EXE, DATE_UPDATE FROM EXE_FILES_LIST ' +
' WHERE EXE_FILES_LIST_ID = :EXE_FILES_LIST_ID';
begin
inherited;
Mutex := TMutexObj.Create( GetMutexName );
IBDB := TpFIBDatabase.Create( nil );
IBDB.DBName := ParamStr( 3 );
IBDB.ConnectParams.UserName := ParamStr( 4 );
IBDB.ConnectParams.Password := ParamStr( 5 );
IBDB.ConnectParams.RoleName := ParamStr( 6 );
IBDB.ConnectParams.CharSet := 'WIN1251';
IBDB.LibraryName := 'fbclient.dll';
IBTr := TpFIBTransaction.Create( IBDB );
IBTr.DefaultDatabase := IBDB;
Query := TpFIBQuery.Create( IBDB );
Query.Database := IBDB;
Query.Transaction := IBTr;
Query.SQL.Text := sqlValue;
end;
destructor TSaveStart.Destroy;
begin
If Assigned( Query ) then begin
Query.Close;
Query.Free;
end;
If Assigned( IBTr ) then
IBTr.Free;
If Assigned( IBDB ) then
IBDB.Free;
If Assigned( Mutex ) then
Mutex.Free;
inherited;
end;
function TSaveStart.GetMutexName: String;
begin
Result := ParamStr( 0 );
Result := StringReplace( Result, '\', '/', [ rfReplaceAll ]);
end;
class procedure TSaveStart.SaveExecute;
var
SS: TSaveStart;
ExeID: Integer;
FileName: String;
begin
SS := TSaveStart.Create;
with SS do
If Mutex.GetSignal then
try
try
ExeID := StrToIntDef( ParamStr( 1 ), -1 );
FileName := ParamStr( 2 );
SetFileAttributes( PChar( FileName ), FILE_ATTRIBUTE_NORMAL );
try
IBDB.Open;
IBTr.StartTransaction;
Query.Close;
Query.ParamByName( 'EXE_FILES_LIST_ID' ).AsInteger := ExeID;
Query.ExecQuery;
WriteToFile( FileName );
except
raise;
end;
Query.Close;
finally
Mutex.Release;
end;
finally
SS.Free;
end;
end;
end.
|
{
ClickForms
(C) Copyright 1998 - 2009, Bradford Technologies, Inc.
All Rights Reserved.
}
unit UFonts;
interface
uses
Controls,
Graphics;
type
TAdvancedFont = class(TFont)
public
procedure AssignToControls(const Control: TControl; const Override: Boolean);
class function UIFont: TAdvancedFont;
end;
TCellFont = class(TAdvancedFont)
protected
FMaxSize: Integer;
FMinSize: Integer;
private
function GetStyleBits: Integer;
procedure SetStyleBits(const Value: Integer);
protected
procedure SetSize(Value: Integer);
public
constructor Create;
property MaxSize: Integer read FMaxSize;
property MinSize: Integer read FMinSize;
published
property Size: Integer read GetSize write SetSize stored False;
property StyleBits: Integer read GetStyleBits write SetStyleBits;
end;
implementation
uses
Windows,
SysUtils,
UGlobals,
UVersion;
type
TControlFriend = class(TControl)
public
property Font;
end;
var
GUIFont: TAdvancedFont;
// --- TAdvancedFont --------------------------------------------------------------
procedure TAdvancedFont.AssignToControls(const Control: TControl; const Override: Boolean);
const
CDefaultFont = 'MS Sans Serif';
var
cfont: TFont;
index: Integer;
wincontrol: TWinControl;
begin
cfont := TControlFriend(Control).Font; // technically an unsafe typecast, but therein lies the secret
// set the control's font
if SameText(cfont.Name, CDefaultFont) or Override then
begin
cfont.Name := Name;
if (cfont.Size = 8) then
cfont.Size := Size;
end;
// set child control fonts
if (Control is TWinControl) then
begin
wincontrol := (Control as TWinControl);
for index := 0 to wincontrol.ControlCount - 1 do
AssignToControls(wincontrol.Controls[index], Override);
end;
end;
class function TAdvancedFont.UIFont: TAdvancedFont;
var
metrics: NONCLIENTMETRICS;
version: TWindowsVersion;
begin
if not Assigned(GUIFont) then
begin
version := TWindowsVersion.Create(nil);
try
GUIFont := TAdvancedFont.Create;
case version.Product of
wpWin95..wpWin2000:
begin
GUIFont.Name := 'MS Sans Serif';
GUIFont.Size := 8;
end;
wpWinXP:
begin
GUIFont.Name := 'Tahoma';
GUIFont.Size := 8;
end;
wpWinVista..wpWinFuture:
begin
GUIFont.Name := 'Segoe UI';
GUIFont.Size := 9;
end;
else
begin
FillChar(metrics, sizeof(metrics), #0);
metrics.cbSize := sizeof(metrics);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @metrics, 0);
GUIFont.Handle := CreateFontIndirect(metrics.lfCaptionFont);
end;
end;
finally
FreeAndNil(version);
end;
end;
Result := GUIFont;
end;
// --- TCellFont --------------------------------------------------------------
function TCellFont.GetStyleBits: Integer;
var
bits: Integer;
begin
bits := tsPlain;
if (fsBold in Style) then
bits := bits or tsBold;
if (fsItalic in Style) then
bits := bits or tsItalic;
if (fsUnderline in Style) then
bits := bits or tsUnderline;
Result := bits ;
end;
procedure TCellFont.SetStyleBits(const Value: Integer);
var
newStyle: TFontStyles; // prevents OnFontChange events from firing on every assignment
begin
newStyle := [];
if (Value and tsBold = tsBold) then
newStyle := newStyle + [fsBold];
if (Value and tsItalic = tsItalic) then
newStyle := newStyle + [fsItalic];
if (Value and tsUnderLine = tsUnderline) then
newStyle := newStyle + [fsUnderline];
Style := newStyle;
end;
procedure TCellFont.SetSize(Value: Integer);
begin
if (Value >= FMinSize) or (Value <= FMaxSize) then
inherited;
end;
constructor TCellFont.Create;
begin
FMaxSize := 14;
FMinSize := 2;
inherited;
end;
// --- Unit -------------------------------------------------------------------
initialization
GUIFont := nil;
finalization
FreeAndNil(GUIFont);
end.
|
unit URepositorioTurno;
interface
uses
UTurno
, UEntidade
, URepositorioDB
, SqlExpr
;
type
TRepositorioTurno = class(TRepositorioDB<TTURNO>)
protected
procedure AtribuiDBParaEntidade(const coTURNO: TTURNO); override;
procedure AtribuiEntidadeParaDB(const coTURNO: TTURNO;
const coSQLQuery: TSQLQuery); override;
public
constructor Create;
function RetornaPorNomeTurno(const csNomeTurno: String): TTURNO;
end;
implementation
uses
UDM
, SysUtils
, UUtilitarios
;
const
CNT_SELECT_TURNO_NOME = 'select * from turno where nome = :nome';
{ TRepositorioTurno }
procedure TRepositorioTurno.AtribuiDBParaEntidade(const coTURNO: TTURNO);
begin
inherited;
with dmProway.SQLSelect do
begin
coTURNO.NOME := FieldByName(FLD_TURNO_NOME).AsString;
coTURNO.HORA_INICIO := FieldByName(FLD_TURNO_HORA_INICIO).AsDateTime;
coTURNO.HORA_TERMINO:= FieldByName(FLD_TURNO_HORA_TERMINO).AsDateTime;
end;
end;
procedure TRepositorioTurno.AtribuiEntidadeParaDB(const coTURNO: TTURNO;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
FieldByName(FLD_TURNO_NOME).AsString := coTURNO.NOME;
FieldByName(FLD_TURNO_HORA_INICIO).AsDateTime := coTURNO.HORA_INICIO;
FieldByName(FLD_TURNO_HORA_TERMINO).AsDateTime := coTURNO.HORA_TERMINO;
end;
end;
constructor TRepositorioTurno.Create;
begin
inherited Create(TTURNO, TBL_TURNO, FLD_ENTIDADE_CODIGO, STR_TURNO);
end;
function TRepositorioTurno.RetornaPorNomeTurno(const csNomeTurno: String): TTURNO;
begin
UDM.dmProway.SQLSelect.Close;
UDM.dmProway.SQLSelect.CommandText := CNT_SELECT_TURNO_NOME;
UDM.dmProway.SQLSelect.ParamByName(FLD_TURNO_NOME).AsString := csNomeTurno;
UDM.dmProway.SQLSelect.Open;
Result := TTURNO.Create;
AtribuiDBParaEntidade(Result);
end;
end.
|
unit DIOTA.Utils.IotaUnitConverter;
interface
uses
DIOTA.Utils.IotaUnits;
type
TIotaUnitConverter = class
private
class function ConvertUnits(amount: Int64; toUnit: IIotaUnit): Int64; overload;
class function CreateAmountWithUnitDisplayText(amountInUnit: Double; iotaUnit: IIotaUnit; extended: Boolean): String;
public
class function ConvertUnits(amount: Int64; fromUnit: IIotaUnit; toUnit: IIotaUnit): Int64; overload;
class function ConvertRawIotaAmountToDisplayText(amount: Int64; extended: Boolean): String;
class function ConvertAmountTo(amount: Int64; target: IIotaUnit): Double;
class function CreateAmountDisplayText(amountInUnit: Double; iotaUnit: IIotaUnit; extended: Boolean): String;
class function FindOptimalIotaUnitToDisplay(amount: Int64): IIotaUnit;
end;
implementation
uses
System.Math,
System.SysUtils;
{ TIotaUnitConverter }
class function TIotaUnitConverter.ConvertUnits(amount: Int64; toUnit: IIotaUnit): Int64;
begin
Result := amount div Round(Power(10, toUnit.GetValue));
end;
class function TIotaUnitConverter.ConvertUnits(amount: Int64; fromUnit: IIotaUnit; toUnit: IIotaUnit): Int64;
begin
Result := ConvertUnits(amount * Round(Power(10, fromUnit.GetValue)), toUnit);
end;
class function TIotaUnitConverter.ConvertRawIotaAmountToDisplayText(amount: Int64; extended: Boolean): String;
var
AUnit: IIotaUnit;
begin
AUnit := FindOptimalIotaUnitToDisplay(amount);
Result := CreateAmountWithUnitDisplayText(ConvertAmountTo(amount, AUnit), AUnit, extended);
end;
class function TIotaUnitConverter.ConvertAmountTo(amount: Int64; target: IIotaUnit): Double;
begin
Result := amount / Power(10, target.GetValue);
end;
class function TIotaUnitConverter.CreateAmountWithUnitDisplayText(amountInUnit: Double; iotaUnit: IIotaUnit; extended: Boolean): String;
begin
Result := CreateAmountDisplayText(amountInUnit, iotaUnit, extended) + ' ' + iotaUnit.GetUnit;
end;
class function TIotaUnitConverter.CreateAmountDisplayText(amountInUnit: Double; iotaUnit: IIotaUnit; extended: Boolean): String;
var
AFormat: String;
begin
if extended then
AFormat := '##0.##################'
else
AFormat := '##0.##';
if iotaUnit.EqualTo(TIotaUnits.IOTA) then
Result := IntToStr(Round(amountInUnit))
else
Result := FormatFloat(AFormat, amountInUnit);
end;
class function TIotaUnitConverter.FindOptimalIotaUnitToDisplay(amount: Int64): IIotaUnit;
var
ALength: Integer;
begin
ALength := Length(IntToStr(Abs(amount)));
if (ALength >= 1) and (ALength <= 3) then
Result := TIotaUnits.IOTA
else
if (ALength > 3) and (ALength <= 6) then
Result := TIotaUnits.KILO_IOTA
else
if (ALength > 6) and (ALength <= 9) then
Result := TIotaUnits.MEGA_IOTA
else
if (ALength > 9) and (ALength <= 12) then
Result := TIotaUnits.GIGA_IOTA
else
if (ALength > 12) and (ALength <= 15) then
Result := TIotaUnits.TERA_IOTA
else
if (ALength > 15) and (ALength <= 18) then
Result := TIotaUnits.PETA_IOTA
else
Result := TIotaUnits.IOTA;
end;
end.
|
unit zProcessMemory;
interface
uses Windows, Classes, SysUtils, registry, PSAPI;
type
TMemoryRegionInfo = record
MemoryBasicInformation : TMemoryBasicInformation;
end;
TMemoryRegionInfoArray = array of TMemoryRegionInfo;
TProcessMemoryInfo = class
MemoryRegionInfoArray : TMemoryRegionInfoArray;
MemAllocGran : DWord; // Гранулярность заполнения памяти
constructor Create;
// Обновление информации
function ResreshInfo(hProcess : THandle) : boolean;
function GetMappedFileName(hProcess: THandle; lpv: Pointer) : string;
end;
implementation
{ TProcessMemoryInfo }
constructor TProcessMemoryInfo.Create;
var
SI : TSystemInfo;
begin
MemoryRegionInfoArray := nil;
// Определение гранулярности заполнения памяти
GetSystemInfo(SI);
MemAllocGran := SI.dwAllocationGranularity;
end;
function TProcessMemoryInfo.GetMappedFileName(hProcess: THandle; lpv: Pointer): string;
var
Res : integer;
begin
SetLength(Result, 300);
Res := PSAPI.GetMappedFileName(hProcess, lpv, @Result[1], 300);
Result := copy(Result, 1, Res);
end;
function TProcessMemoryInfo.ResreshInfo(hProcess : THandle): boolean;
var
MemoryBasicInformation : TMemoryBasicInformation;
lpAddress : Pointer;
Res : DWORD;
begin
MemoryRegionInfoArray := nil;
// Первый запрос
lpAddress := nil;
Res := VirtualQueryEx(hProcess, lpAddress, MemoryBasicInformation, sizeof(MemoryBasicInformation));
while Res > 0 do begin
// Добавление региона
SetLength(MemoryRegionInfoArray, length(MemoryRegionInfoArray)+1);
MemoryRegionInfoArray[Length(MemoryRegionInfoArray)-1].MemoryBasicInformation := MemoryBasicInformation;
// Переход на новый регион
lpAddress := pointer(dword(MemoryBasicInformation.BaseAddress) + MemoryBasicInformation.RegionSize);
Res := VirtualQueryEx(hProcess, lpAddress, MemoryBasicInformation, sizeof(MemoryBasicInformation));
end;
end;
end.
|
unit LayoutManager;
interface
uses
Classes, CommunicationObj;
type
TLayoutManager = class
public
function LoadTemplate(Name : string ) : TTemplateInfo;
function InitTemplate(Name : string ) : TTemplateInfo;
function CloneTemplate(Name: string; Source: TTemplateInfo) : TTemplateInfo;
procedure SaveTemplate(template : TTemplateInfo);
procedure KillTemplate(Name : string);
function TemplateExists( TemplateName : string ) : boolean;
end;
procedure InitLayouts;
function EnumTemplates : TStrings;
function TemplateExists( Name : string ) : boolean;
implementation
uses
Users, RDAReg, Angle, Speed, Parameters, SysUtils;
const
TemplateKey = RDARootKey + '\Templates';
const
NameValue = 'Name';
FlagValue = 'Flag';
AddressValue = 'Address';
FTPSettingsValue = 'FTPSettings';
PeriodValue = 'Period';
DelayValue = 'Delay';
KindValue = 'Kind';
StartValue = 'Start';
FinishValue = 'Finish';
SpeedValue = 'Speed';
AnglesValue = 'Angles';
FormatsValue = 'Formats';
AngleListValue = 'AngleList';
FormatListValue = 'FormatList';
AutomaticValue = 'Automatic';
FTPValue = 'SentFTP';
LastTimeValue = 'LastTime';
NextTimeValue = 'NextTime';
ADRateValue = 'ADRate';
SectorsValue = 'Sectors';
TR1Value = 'TR1';
TR2Value = 'TR2';
PulseValue = 'Pulse';
CH10cm_B0Value = 'CH10cm_B0';
CH10cm_B1Value = 'CH10cm_B1';
CH10cm_B2Value = 'CH10cm_B2';
CH10cm_A1Value = 'CH10cm_A1';
CH10cm_A2Value = 'CH10cm_A2';
CH3cm_B0Value = 'CH3cm_B0';
CH3cm_B1Value = 'CH3cm_B1';
CH3cm_B2Value = 'CH3cm_B2';
CH3cm_A1Value = 'CH3cm_A1';
CH3cm_A2Value = 'CH3cm_A2';
FilterValue = 'Filter';
SaveFilterValue = 'SaveFilter';
ApplyFilterValue = 'ApplyFilter';
CH10cm_ThresholdValue = 'CH10cm_Threshold';
CH3cm_ThresholdValue = 'CH3cm_Threshold';
MaxAngleEchoFilterValue = 'MaxAngleEchoFilter';
MaxHeightEchoFilterValue = 'MaxHeightEchoFilter';
MaxDistanceEchoFilterValue = 'MaxDistanceEchoFilter';
const
ADay = 1;
AnHour = ADay/24;
AMinute = AnHour/60;
ASecond = AMinute/60;
type
_FormatData = packed record
Onda: Integer;
Celdas: Integer;
Long: Integer;
PotMet: Single;
end;
_TxRxData = packed record
CRT: LongWord;
CMG: LongWord;
CMS: LongWord;
end;
PAngleList = ^TAngleList;
TAngleList = array[0..0] of integer;
PFormatList = ^TFormatList;
TFormatList = array[0..0] of _FormatData;
// Public procedures & functions
procedure InitLayouts;
var
I : integer;
LayoutManager : TLayoutManager;
begin
with EnumTemplates do
try
LayoutManager := TLayoutManager.Create;
try
for I := 0 to Count - 1 do
with LayoutManager.LoadTemplate(Strings[I]) do
try
if Automatic
then Automatic := true;
finally
Free;
end;
finally
LayoutManager.Free;
end;
finally
Free;
end;
end;
function EnumTemplates : TStrings;
begin
Result := TStringList.Create;
with TRDAReg.Create do
try
if OpenKey(TemplateKey, true)
then GetKeyNames(Result);
finally
Free;
end;
end;
function TemplateExists( Name : string ) : boolean;
begin
if Name <> ''
then
with TRDAReg.Create do
try
Result := OpenKey(TemplateKey + '\' + Name, false);
finally
Free;
end
else Result := false;
end;
{ TLayoutManager }
function TLayoutManager.CloneTemplate(Name: string; Source: TTemplateInfo) : TTemplateInfo;
var
i : integer;
TemplateInfo: TTemplateInfo;
begin
TemplateInfo := TTemplateInfo.Create;
TemplateInfo.Name := Name;
TemplateInfo.Flags := Source.Flags;
TemplateInfo.Period := Source.Period;
TemplateInfo.Kind := Source.Kind;
TemplateInfo.Start := Source.Start;
TemplateInfo.Finish := Source.Finish;
TemplateInfo.Speed := Source.Speed;
TemplateInfo.Angles := Source.Angles;
TemplateInfo.Formats := Source.Formats;
TemplateInfo.ADRate := Source.ADRate;
TemplateInfo.Sectors := Source.Sectors;
for i := 0 to TemplateInfo.Angles-1 do
TemplateInfo.AngleList[i] := Source.AngleList[i];
TemplateInfo.FTPSettings := Source.FTPSettings;
TemplateInfo.SentFTP := Source.SentFTP;
for i := 0 to TemplateInfo.Formats-1 do
begin
TemplateInfo.FormatList[i].Onda := Source.FormatList[i].Onda;
TemplateInfo.FormatList[i].Celdas := Source.FormatList[i].Celdas;
TemplateInfo.FormatList[i].Long := Source.FormatList[i].Long;
TemplateInfo.FormatList[i].PotMet := Source.FormatList[i].PotMet;
end;
TemplateInfo.Pulse := Source.Pulse;
TemplateInfo.TR1.CRT := Source.TR1.CRT;
TemplateInfo.TR1.CMG := Source.TR1.CMG;
TemplateInfo.TR1.CMS := Source.TR1.CMS;
TemplateInfo.TR2.CRT := Source.TR2.CRT;
TemplateInfo.TR2.CMG := Source.TR2.CMG;
TemplateInfo.TR2.CMS := Source.TR2.CMS;
//Filter
TemplateInfo.CH10cm_B0 := Source.CH10cm_B0;
TemplateInfo.CH10cm_B1 := Source.CH10cm_B1;
TemplateInfo.CH10cm_B2 := Source.CH10cm_B2;
TemplateInfo.CH10cm_A1 := Source.CH10cm_A1;
TemplateInfo.CH10cm_A2 := Source.CH10cm_A2;
TemplateInfo.CH10cm_Threshold := Source.CH10cm_Threshold;
TemplateInfo.CH3cm_B0 := Source.CH3cm_B0;
TemplateInfo.CH3cm_B1 := Source.CH3cm_B1;
TemplateInfo.CH3cm_B2 := Source.CH3cm_B2;
TemplateInfo.CH3cm_A1 := Source.CH3cm_A1;
TemplateInfo.CH3cm_A2 := Source.CH3cm_A2;
TemplateInfo.CH3cm_Threshold := Source.CH3cm_Threshold;
TemplateInfo.Filter := Source.Filter;
TemplateInfo.SaveFilter := Source.SaveFilter;
TemplateInfo.ApplyFilter := Source.ApplyFilter;
TemplateInfo.MaxAngleEchoFilter := Source.MaxAngleEchoFilter;
TemplateInfo.MaxHeightEchoFilter := Source.MaxHeightEchoFilter;
TemplateInfo.MaxDistanceEchoFilter := Source.MaxDistanceEchoFilter;
SaveTemplate(TemplateInfo);
result := TemplateInfo;
end;
function TLayoutManager.InitTemplate(Name: string): TTemplateInfo;
begin
result := TTemplateInfo.Create;
result.Name := Name;
result.Flags := tf_Create_Dir or tf_Include_Year or tf_Include_Month;
result.Period := AnHour;
result.Kind := dk_PPI;
result.Start := ang_0;
result.Finish := ang_360;
result.Speed := spd_4;
result.Angles := 1;
result.Formats := 1;
result.ADRate := LoadSampleRate;
result.Sectors := 256;
result.AngleList[0] := ang_0;
result.FormatList[0].Onda := wl_10cm;
result.FormatList[0].Celdas := 100;
result.FormatList[0].Long := 1000;
result.FTPSettings := '';
result.SentFTP := false;
result.Pulse := tx_Pulse_Long;
result.TR1.CRT := xo_Nevermind;
result.TR1.CMG := xo_Nevermind;
result.TR1.CMS := xo_Nevermind;
result.TR2.CRT := xo_Nevermind;
result.TR2.CMG := xo_Nevermind;
result.TR2.CMS := xo_Nevermind;
//Filter
result.CH10cm_B0 := 0;
result.CH10cm_B1 := 0;
result.CH10cm_B2 := 0;
result.CH10cm_A1 := 0;
result.CH10cm_A2 := 0;
result.CH10cm_Threshold := 0;
result.CH3cm_B0 := 0;
result.CH3cm_B1 := 0;
result.CH3cm_B2 := 0;
result.CH3cm_A1 := 0;
result.CH3cm_A2 := 0;
result.CH3cm_Threshold := 0;
result.Filter := false;
result.SaveFilter := false;
result.ApplyFilter := false;
result.MaxAngleEchoFilter := 5;
result.MaxHeightEchoFilter := 1000;
result.MaxDistanceEchoFilter := 50000;
SaveTemplate(result);
end;
procedure TLayoutManager.KillTemplate(Name: string);
begin
with TRDAReg.Create do
try
if OpenKey(TemplateKey, false)
then DeleteKey(Name);
finally
Free;
end;
end;
function TLayoutManager.LoadTemplate(Name: string): TTemplateInfo;
var
Size : integer;
AngleList : pointer;
FormatList : pointer;
fTR1, fTR2 : _TxRxData;
i : integer;
begin
result := nil;
with TRDAReg.Create do
try
if OpenKey(TemplateKey + '\' + Name, false)
then
begin
result := TTemplateInfo.Create;
result.Name := ReadString(NameValue);
result.Flags := ReadInteger(FlagValue);
result.Address := ReadString(AddressValue);
result.FTPSettings := ReadString(FTPSettingsValue);
result.Period := ReadDateTime(PeriodValue);
result.Delay := ReadDateTime(DelayValue);
result.Kind := DesignKindEnum(ReadInteger(KindValue));
result.Start := ReadInteger(StartValue);
result.Finish := ReadInteger(FinishValue);
result.Speed := ReadInteger(SpeedValue);
result.Angles := ReadInteger(AnglesValue);
result.Formats := ReadInteger(FormatsValue);
result.Automatic := ReadBool(AutomaticValue);
result.SentFTP := ReadBool(FTPValue);
result.LastTime := ReadDateTime(LastTimeValue);
result.NextTime := ReadDateTime(NextTimeValue);
result.ADRate := ReadInteger(ADRateValue);
result.Sectors := ReadInteger(SectorsValue);
result.Pulse := TxPulseEnum( ReadInteger(PulseValue) );
//filter
result.CH10cm_B0 := ReadFloat(CH10cm_B0Value);
result.CH10cm_B1 := ReadFloat(CH10cm_B1Value);
result.CH10cm_B2 := ReadFloat(CH10cm_B2Value);
result.CH10cm_A1 := ReadFloat(CH10cm_A1Value);
result.CH10cm_A2 := ReadFloat(CH10cm_A2Value);
result.CH3cm_B0 := ReadFloat(CH3cm_B0Value);
result.CH3cm_B1 := ReadFloat(CH3cm_B1Value);
result.CH3cm_B2 := ReadFloat(CH3cm_B2Value);
result.CH3cm_A1 := ReadFloat(CH3cm_A1Value);
result.CH3cm_A2 := ReadFloat(CH3cm_A2Value);
result.Filter := ReadBool(FilterValue);
result.SaveFilter := ReadBool(SaveFilterValue);
result.ApplyFilter := ReadBool(ApplyFilterValue);
result.CH10cm_Threshold := ReadFloat(CH10cm_ThresholdValue);
result.CH3cm_Threshold := ReadFloat(CH3cm_ThresholdValue);
result.MaxAngleEchoFilter := ReadFloat(MaxAngleEchoFilterValue);
result.MaxHeightEchoFilter := ReadInteger(MaxHeightEchoFilterValue);
result.MaxDistanceEchoFilter := ReadInteger(MaxDistanceEchoFilterValue);
ReadBinaryData(TR1Value, fTR1, sizeof(fTR1));
ReadBinaryData(TR2Value, fTR2, sizeof(fTR2));
result.TR1.CRT := TxRxOptionsEnum(fTR1.CRT);
result.TR1.CMG := TxRxOptionsEnum(fTR1.CMG);
result.TR1.CMS := TxRxOptionsEnum(fTR1.CMS);
result.TR2.CRT := TxRxOptionsEnum(fTR2.CRT);
result.TR2.CMG := TxRxOptionsEnum(fTR2.CMG);
result.TR2.CMS := TxRxOptionsEnum(fTR2.CMS);
Size := result.Angles * sizeof(integer);
AngleList := AllocMem(Size);
ReadBinaryData(AngleListValue, AngleList^, Size);
for i := 0 to result.Angles-1 do
result.AngleList[i] := PAngleList(AngleList)^[i];
FreeMem(AngleList, Size);
Size := result.Formats * sizeof(_FormatData);
FormatList := AllocMem(Size);
ReadBinaryData(FormatListValue, FormatList^, Size);
for i := 0 to result.Formats-1 do
begin
result.FormatList[i] := FormatData.Create;
with PFormatList(FormatList)^[i] do
begin
result.FormatList[i].Onda := TWaveLengthEnum(Onda);
result.FormatList[i].Celdas := Celdas;
result.FormatList[i].Long := Long;
result.FormatList[i].PotMet := PotMet;
end;
end;
FreeMem(FormatList, Size);
end;
finally
Free;
end;
end;
procedure TLayoutManager.SaveTemplate(template: TTemplateInfo);
var
Size, i : integer;
AngleList : pointer;
FormatList : pointer;
fTR1, fTR2 : _TxRxData;
begin
if template.Name <> ''
then
with TRDAReg.Create do
try
if OpenKey(TemplateKey + '\' + template.Name, true)
then
begin
WriteString(NameValue, template.Name);
WriteInteger(FlagValue, template.Flags);
WriteString(AddressValue, template.Address);
WriteString(FTPSettingsValue, template.FTPSettings);
WriteDateTime(PeriodValue, template.Period);
WriteDateTime(DelayValue, template.Delay);
WriteInteger(KindValue, Ord(template.Kind));
WriteInteger(StartValue, template.Start);
WriteInteger(FinishValue, template.Finish);
WriteInteger(SpeedValue, template.Speed);
WriteInteger(AnglesValue, template.Angles);
WriteInteger(ADRateValue, template.ADRate);
WriteInteger(SectorsValue, template.Sectors);
WriteInteger(FormatsValue, template.Formats);
Size := template.Angles * sizeof(integer);
AngleList := AllocMem(Size);
for i := 0 to template.Angles-1 do
PAngleList(AngleList)^[i] := template.AngleList[i];
WriteBinaryData(AngleListValue, AngleList^, Size);
FreeMem(AngleList, Size);
Size := template.Formats * sizeof(_FormatData);
FormatList := AllocMem(Size);
for i := 0 to template.Formats-1 do
with PFormatList(FormatList)^[i] do
begin
Onda := Ord(template.FormatList[i].Onda);
Celdas := template.FormatList[i].Celdas;
Long := template.FormatList[i].Long;
PotMet := template.FormatList[i].PotMet;
end;
WriteBinaryData(FormatListValue, FormatList^, Size);
FreeMem(FormatList, Size);
WriteBool(AutomaticValue, template.Automatic);
WriteBool(FTPValue, template.SentFTP);
WriteDateTime(LastTimeValue, template.LastTime);
WriteDateTime(NextTimeValue, template.NextTime);
fTR1.CRT := Ord(template.TR1.CRT);
fTR1.CMG := Ord(template.TR1.CMG);
fTR1.CMS := Ord(template.TR1.CMS);
fTR2.CRT := Ord(template.TR2.CRT);
fTR2.CMG := Ord(template.TR2.CMG);
fTR2.CMS := Ord(template.TR2.CMS);
WriteBinaryData(TR1Value, fTR1, sizeof(fTR1));
WriteBinaryData(TR2Value, fTR2, sizeof(fTR2));
WriteInteger(PulseValue, Ord(template.Pulse));
//filter
WriteFloat(CH10cm_ThresholdValue, template.CH10cm_Threshold);
WriteFloat(CH3cm_ThresholdValue, template.CH3cm_Threshold);
WriteFloat(CH10cm_B0Value, template.CH10cm_B0);
WriteFloat(CH10cm_B1Value, template.CH10cm_B1);
WriteFloat(CH10cm_B2Value, template.CH10cm_B2);
WriteFloat(CH10cm_A1Value, template.CH10cm_A1);
WriteFloat(CH10cm_A2Value, template.CH10cm_A2);
WriteFloat(CH3cm_B0Value, template.CH3cm_B0);
WriteFloat(CH3cm_B1Value, template.CH3cm_B1);
WriteFloat(CH3cm_B2Value, template.CH3cm_B2);
WriteFloat(CH3cm_A1Value, template.CH3cm_A1);
WriteFloat(CH3cm_A2Value, template.CH3cm_A2);
WriteBool(FilterValue, template.Filter);
WriteBool(SaveFilterValue, template.SaveFilter);
WriteBool(ApplyFilterValue, template.ApplyFilter);
WriteFloat(MaxAngleEchoFilterValue, template.MaxAngleEchoFilter);
WriteInteger(MaxHeightEchoFilterValue, template.MaxHeightEchoFilter);
WriteInteger(MaxDistanceEchoFilterValue, template.MaxDistanceEchoFilter);
end;
finally
Free;
end;
end;
function TLayoutManager.TemplateExists(TemplateName: string): boolean;
begin
with TRDAReg.Create do
try
result := OpenKey(TemplateKey + '\' + TemplateName, false)
finally
Free;
end;
end;
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Ported to Delphi by Michal Wojcik.
{$H+}
unit InvocationTargetException;
interface
uses
SysUtils,
ObjAuto;
type
TInvocationTargetException = class(Exception)
private
targetException : Exception;
public
constructor Create(MethodInfo : PMethodInfoHeader; e : Exception);
function getTargetException() : Exception;
end;
implementation
{ TInvocationTargetException }
constructor TInvocationTargetException.Create(MethodInfo : PMethodInfoHeader; e : Exception);
begin
inherited CreateFmt('"%s" called with invalid arguments: %s', [MethodInfo.Name, e.Message]);
targetException := e.ClassType.Create as Exception;
targetException.Message := e.Message;
if (targetException is TInvocationTargetException) then
(targetException as TInvocationTargetException).targetException := (e as
TInvocationTargetException).targetException;
end;
function TInvocationTargetException.getTargetException : Exception;
begin
Result := targetException;
end;
end.
|
unit uTravelerDao;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs,
Variants, Contnrs, SqlExpr, DBXpress ,StrUtils, inifiles,UConnectBank,uTraveler,uPersonDao,DB,DBClient;
type
TTravelerDao = class(TPersonDao)
private
procedure insertTraveler(poObj:TTraveler);
public
constructor Create;
destructor Destroy; override;
procedure save(poObj:TTraveler);
function ListPerson(obj:TTraveler):string;
function PesquisarPessoa(obj:TTraveler):OleVariant;
procedure DeleteTraveler(poObj:TTraveler);
function ListCombo:string;
procedure saveService(psService:string);
end;
implementation
{ TTravelerDao }
constructor TTravelerDao.Create;
begin
inherited Create;
end;
procedure TTravelerDao.DeleteTraveler(poObj: TTraveler);
begin
sqlGeral.Close;
sqlGeral.SQL.Clear;
sqlGeral.SQL.Add('DELETE FROM Person WHERE IdentNr = ' + QuotedStr(poObj.IdentNr) + ' AND idpersonTypes = ' + IntToStr(poObj.typePerson));
sqlGeral.ExecSQL;
end;
destructor TTravelerDao.Destroy;
begin
inherited;
end;
procedure TTravelerDao.insertTraveler(poObj: TTraveler);
var
Trans: TTransactionDesc;
idPessoa:Integer;
begin
Conexao.GetConexao.StartTransaction(Trans);
try
insert(poObj,poObj.firstName,poObj.surename);
idPessoa := selectUltimoId;
sqlGeral.Close;
sqlGeral.SQL.Clear;
sqlGeral.SQL.Add('INSERT INTO Traveler ');
sqlGeral.SQL.Add(' VALUES (:Country_idCountry, :Person_idPerson)');
sqlGeral.ParamByName('Country_idCountry').AsInteger := poObj.country;
sqlGeral.ParamByName('Person_idPerson').AsInteger := idPessoa;
sqlGeral.ExecSQL;
Conexao.GetConexao.Commit(Trans);
Except
Conexao.GetConexao.Rollback(Trans);
Raise;
end;
end;
function TTravelerDao.ListCombo: string;
begin
sqlGeral.Close;
sqlGeral.SQL.Clear;
sqlGeral.SQL.Add('select * from Country');
Result := sqlGeral.SQL.GetText;
end;
function TTravelerDao.ListPerson(obj: TTraveler): string;
begin
sqlGeral.Close;
sqlGeral.SQL.Clear;
sqlGeral.SQL.Add('select P.idPerson, P.IdentNr, P.namePerson,P.firstName,P.surename, C.country,P.idpersonTypes from Traveler T ');
sqlGeral.SQL.Add('left join Person P ON T.Person_idPerson = P.idPerson ');
sqlGeral.SQL.Add('Left join Country C ON C.idCountry = T.Country_idCountry ');
sqlGeral.SQL.Add('where p.idpersonTypes = ' + IntToStr(obj.typePerson));
Result := sqlGeral.SQL.GetText;
end;
function TTravelerDao.PesquisarPessoa(obj: TTraveler): OleVariant;
begin
end;
procedure TTravelerDao.save(poObj: TTraveler);
var
oDataset:TDataSet;
begin
oDataset := SelectPersonId(poObj);
if oDataset.IsEmpty then
begin
insertTraveler(poObj);
Exit;
end;
UpdatePersonId(poObj,poObj.firstName,poObj.surename);
end;
procedure TTravelerDao.saveService(psService: string);
begin
end;
end.
|
unit Bargauge;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls;
type
TBarStyle = (bsLeftRight, bsRightLeft, bsBottomUp, bsTopDown);
TNotify = procedure ( aProgress : integer ) of object;
TBarGauge = class(TGraphicControl)
public
constructor Create( anOwner : TComponent ); override;
protected
procedure Paint; override;
private
fValue : integer;
fMax : integer;
fMin : integer;
fMargin : integer;
fStep : integer;
fGap : integer;
fBevel : TPanelBevel;
fColor : TColor;
fStyle : TBarStyle;
procedure SetValue ( aValue : integer );
procedure SetMax ( aMax : integer );
procedure SetMin ( aMin : integer );
procedure SetMargin( aMargin : integer );
procedure SetStep ( aStep : integer );
procedure SetGap ( aGap : integer );
procedure SetBevel ( aBevel : TPanelBevel );
procedure SetColor ( aColor : TColor );
procedure SetStyle ( aStyle : TBarStyle );
published
property Value : integer read fValue write SetValue;
property Min : integer read fMin write SetMin;
property Max : integer read fMax write SetMax;
property Margin : integer read fMargin write SetMargin;
property Step : integer read fStep write SetStep;
property Gap : integer read fGap write SetGap;
property Bevel : TPanelBevel read fBevel write SetBevel;
property BarColor : TColor read fColor write SetColor;
property Style : TBarStyle read fStyle write SetStyle;
property Align;
property Caption;
property Color;
property Font;
property ParentFont;
property Visible;
property Anchors;
private { Events }
fOnChange : TNotifyEvent;
function GetNotify : TNotify;
published
property OnChange : TNotifyEvent read fOnChange write fOnChange;
property Notify : TNotify read GetNotify;
private
procedure DrawBevel;
procedure DrawGauge;
end;
procedure Register;
implementation
{ TBarGauge methods }
constructor TBarGauge.Create( anOwner : TComponent );
begin
inherited;
fValue := 0; { Value }
fMin := 0; { Min }
fMax := 100; { Max }
fMargin := 2; { Margin }
fStep := 10; { Step }
fGap := 1; { Gap }
fBevel := bvLowered; { Bevel }
fColor := clHighLight; { BarColor }
fOnChange := nil;
end;
procedure TBarGauge.DrawBevel;
begin
with Canvas do
begin
Brush.Style := bsSolid;
Brush.Color := Color;
case Bevel of
bvRaised:
begin
MoveTo( 0, Height - 1 );
Pen.Color := clWhite;
LineTo( 0, 0 );
LineTo( Width - 1, 0 );
Pen.Color := clGray;
LineTo( Width - 1, Height - 1 );
LineTo( 0, Height - 1 );
end;
bvLowered:
begin
MoveTo( 0, Height - 1 );
Pen.Color := clGray;
LineTo( 0, 0 );
LineTo( Width - 1, 0 );
Pen.Color := clWhite;
LineTo( Width - 1, Height - 1 );
LineTo( 0, Height - 1 );
end;
end;
end;
end;
procedure TBarGauge.DrawGauge;
var
S, F : integer;
Last : integer;
begin
with Canvas do
begin
Pen.Color := BarColor;
Brush.Color := BarColor;
case fStyle of
bsLeftRight, bsRightLeft : Last := ((Width - 2 * fMargin) * fValue) div (fMax - fMin);
bsBottomUp, bsTopDown : Last := ((Height - 2 * fMargin) * fValue) div (fMax - fMin);
else raise Exception.Create( 'Invalid Bargauge style' );
end;
S := fMargin;
F := S + fStep;
while F < Last do
begin
case fStyle of
bsLeftRight : Rectangle( S, fMargin, F, Height - fMargin );
bsRightLeft : Rectangle( Width - F, fMargin, Width - S, Height - fMargin );
bsBottomUp : Rectangle( fMargin, Height - F, Width - fMargin, Height - S );
bsTopDown : Rectangle( fMargin, S, Width - fMargin, F );
end;
inc( S, fStep + fGap );
inc( F, fStep + fGap );
end;
if fValue >= 100
then
case fStyle of
bsLeftRight : Rectangle( S, fMargin, Width - fMargin, Height - fMargin );
bsRightLeft : Rectangle( fMargin, fMargin, Width - S, Height - fMargin );
bsBottomUp : Rectangle( fMargin, fMargin, Width - fMargin, Height - S );
bsTopDown : Rectangle( fMargin, S, Width - fMargin, Height - fMargin );
end
else
begin
Pen.Color := Color;
Brush.Color := Color;
case fStyle of
bsLeftRight : Rectangle( S, fMargin, Width - fMargin, Height - fMargin );
bsRightLeft : Rectangle( fMargin, fMargin, Width - S, Height - fMargin );
bsBottomUp : Rectangle( fMargin, fMargin, Width - fMargin, Height - S );
bsTopDown : Rectangle( fMargin, S, Width - fMargin, Height - fMargin );
end;
end;
Pen.Color := Color;
Brush.Style := bsClear;
Font := Self.Font;
S := Width div 2 - TextWidth ( Caption ) div 2;
F := Height div 2 - TextHeight( Caption ) div 2;
TextRect( Rect( fMargin, fMargin, Width - fMargin, Height - fMargin ), S, F, Caption );
end;
end;
procedure TBarGauge.Paint;
begin
DrawBevel;
DrawGauge;
end;
procedure TBarGauge.SetValue( aValue : integer );
begin
if aValue <> fValue
then
begin
if aValue < Min
then fValue := Min
else
if aValue > Max
then fValue := Max
else fValue := aValue;
Paint;
if assigned( fOnChange )
then fOnChange( Self );
end;
end;
procedure TBarGauge.SetMin( aMin : integer );
begin
if aMin < fMax
then
begin
fMin := aMin;
Repaint;
end;
end;
procedure TBarGauge.SetMax( aMax : integer );
begin
if aMax > fMin
then
begin
fMax := aMax;
Repaint;
end;
end;
procedure TBarGauge.SetStep( aStep : integer );
begin
if aStep > 0
then fStep := aStep
else fStep := 1;
Repaint;
end;
procedure TBarGauge.SetGap( aGap : integer );
begin
fGap := aGap;
Repaint;
end;
procedure TBarGauge.SetMargin( aMargin : integer );
begin
fMargin := aMargin;
Repaint;
end;
procedure TBarGauge.SetBevel( aBevel : TPanelBevel );
begin
fBevel := aBevel;
Repaint;
end;
procedure TBarGauge.SetColor( aColor : TColor );
begin
fColor := aColor;
Repaint;
end;
procedure TBarGauge.SetStyle( aStyle : TBarStyle );
begin
fStyle := aStyle;
Repaint;
end;
function TBarGauge.GetNotify : TNotify;
begin
GetNotify := Self.SetValue;
end;
{ Public procedures & functions }
procedure Register;
begin
RegisterComponents('Vesta', [TBarGauge]);
end;
end.
|
{
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
}
// Copyright (c) 2010 - J. Aldo G. de Freitas Junior
Unit
ExprNodes;
Interface
Uses
Classes,
SysUtils,
Tree,
Stacks;
Type
TVariantStack = Specialize TStack<Variant>;
TVariantStackStack = Specialize TStack<TVariantStack>;
TWindownedStack = Class(TVariantStackStack)
Public
Constructor Create;
Destructor Destroy; Override;
Procedure Enter(Const aCount : Integer);
Procedure Leave(Const aCount : Integer);
Procedure Purge;
End;
TArithmeticalStack = Class(TWindownedStack)
Public
Procedure DoDup;
Procedure DoDrop;
Procedure DoRot;
Procedure DoSwap;
Procedure DoPushTrue;
Procedure DoPushFalse;
Procedure DoAdd;
Procedure DoSub;
Procedure DoMul;
Procedure DoDiv;
Procedure DoIDiv;
Procedure DoMod;
Procedure DoPow;
Procedure DoNot;
Procedure DoAnd;
Procedure DoOr;
Procedure DoXOr;
Procedure DoCmpEq;
Procedure DoCmpSm;
Procedure DoCmpGt;
Procedure DoCmpDif;
Procedure DoCmpEqSm;
Procedure DoCmpGtSm;
End;
EVirtualMachineStack = Class(Exception);
TVirtualMachineStack = Class(TArithmeticalStack)
Public
Procedure DoCall(Const aFunctionName : String);
Procedure DefaultHandlerStr(Var aMessage); Override;
Procedure FunctionTrue(Var aMessage); Message 'true';
Procedure FunctionFalse(Var aMessage); Message 'false';
End;
TExprNode = Class;
TExprNodeClass = Class Of TExprNode;
EExprNode = Class(Exception);
TExprNodeList = Array Of TExprNode;
TExprNode = Class(TTreeNode)
Private
fRow, fCol : Integer;
fStack : TVirtualMachineStack;
Public
Procedure RaiseError(Const aMsg : String);
Procedure EvaluateChilds; Virtual;
Procedure Evaluate; Virtual; Abstract;
Procedure PropagateStack(Const aStack : TVirtualMachineStack); Virtual;
Property Row : Integer Read fRow Write fRow;
Property Col : Integer Read fCol Write fCol;
Property Stack : TVirtualMachineStack Read fStack;
End;
TUnaryMinusNode = Class(TExprNode)
Public
Procedure Evaluate; Override;
End;
TUnaryNotNode = Class(TExprNode)
Public
Procedure Evaluate; Override;
End;
TExpressionListNode = Class;
TFunctionCallNode = Class(TExprNode)
Private
fName : String;
fParameters : TExpressionListNode;
Public
Procedure Evaluate; Override;
Property Name : String Read fName Write fName;
Property Parameters : TExpressionListNode Read fParameters Write fParameters;
End;
TStringLiteralNode = Class(TExprNode)
Private
fValue : String;
Public
Procedure Evaluate; Override;
Property Value : String Read fValue Write fValue;
End;
TNumberLiteralNode = Class(TExprNode)
Private
fValue : Real;
Public
Procedure Evaluate; Override;
Property Value : Real Read fValue Write fValue;
End;
TMulExpressionNode = Class(TExprNode)
Private
fOperation : String;
Public
Procedure Evaluate; Override;
Property Operation : String Read fOperation Write fOperation;
End;
TAddExpressionNode = Class(TExprNode)
Private
fOperation : String;
Public
Procedure Evaluate; Override;
Property Operation : String Read fOperation Write fOperation;
End;
TExpressionNode = Class(TExprNode)
Private
fOperation : String;
Public
Procedure Evaluate; Override;
Property Operation : String Read fOperation Write fOperation;
End;
TExpressionListNode = Class(TExprNode)
Public
Procedure Evaluate; Override;
End;
TSourceNode = Class(TExprNode)
Public
Procedure Evaluate; Override;
End;
Implementation
Type
TVirtualMachineMessage = Record
MsgStr : String[255];
Data : Pointer;
End;
{ TWindownedStack }
Constructor TWindownedStack.Create;
Begin
Inherited Create;
Push(TVariantStack.Create);
End;
Destructor TWindownedStack.Destroy;
Begin
While AtLeast(1) Do
Pop.Free;
Inherited Destroy;
End;
Procedure TWindownedStack.Enter(Const aCount : Integer);
Var
lCtrl : Integer;
Begin
Push(TVariantStack.Create);
For lCtrl := 1 To aCount Do
Top.Push(Previous.Pop);
End;
Procedure TWindownedStack.Leave(Const aCount : Integer);
Var
lCtrl : Integer;
Begin
For lCtrl := 1 To aCount Do
Previous.Push(Top.Pop);
Top.Free;
Pop;
End;
Procedure TWindownedStack.Purge;
Begin
While AtLeast(1) Do
Pop.Free;
Push(TVariantStack.Create);
End;
{ TArithmeticalStack }
Procedure TArithmeticalStack.DoDup;
Var
lTmp : Variant;
Begin
lTmp := Top.Pop;
Top.Push(lTmp);
Top.Push(lTmp);
End;
Procedure TArithmeticalStack.DoDrop;
Begin
Top.Pop;
End;
Procedure TArithmeticalStack.DoRot;
Var
lTmp1,
lTmp2,
lTmp3 : Variant;
Begin
lTmp1 := Top.Pop;
lTmp2 := Top.Pop;
lTmp3 := Top.Pop;
Top.Push(lTmp1);
Top.Push(lTmp2);
Top.Push(lTmp3);
End;
Procedure TArithmeticalStack.DoSwap;
Var
lTmp1,
lTmp2 : Variant;
Begin
lTmp1 := Top.Pop;
lTmp2 := Top.Pop;
Top.Push(lTmp1);
Top.Push(lTmp2);
End;
Procedure TArithmeticalStack.DoPushTrue;
Begin
Top.Push(True);
End;
Procedure TArithmeticalStack.DoPushFalse;
Begin
Top.Push(False);
End;
Procedure TArithmeticalStack.DoAdd;
Begin
Top.Push(Top.Pop + Top.Pop);
End;
Procedure TArithmeticalStack.DoSub;
Begin
Top.Push(Top.Pop - Top.Pop);
End;
Procedure TArithmeticalStack.DoMul;
Begin
Top.Push(Top.Pop * Top.Pop);
End;
Procedure TArithmeticalStack.DoDiv;
Begin
Top.Push(Top.Pop / Top.Pop);
End;
Procedure TArithmeticalStack.DoIDiv;
Begin
Top.Push(Top.Pop Div Top.Pop);
End;
Procedure TArithmeticalStack.DoMod;
Begin
Top.Push(Top.Pop Mod Top.Pop);
End;
Procedure TArithmeticalStack.DoPow;
Begin
Top.Push(Top.Pop ** Top.Pop);
End;
Procedure TArithmeticalStack.DoNot;
Begin
Top.Push(Not(Top.Pop));
End;
Procedure TArithmeticalStack.DoAnd;
Begin
Top.Push(Top.Pop And Top.Pop);
End;
Procedure TArithmeticalStack.DoOr;
Begin
Top.Push(Top.Pop Or Top.Pop);
End;
Procedure TArithmeticalStack.DoXOr;
Begin
Top.Push(Top.Pop XOr Top.Pop);
End;
Procedure TArithmeticalStack.DoCmpEq;
Begin
Top.Push(Top.Pop = Top.Pop);
End;
Procedure TArithmeticalStack.DoCmpSm;
Begin
Top.Push(Top.Pop < Top.Pop);
End;
Procedure TArithmeticalStack.DoCmpGt;
Begin
Top.Push(Top.Pop > Top.Pop);
End;
Procedure TArithmeticalStack.DoCmpDif;
Begin
Top.Push(Top.Pop <> Top.Pop);
End;
Procedure TArithmeticalStack.DoCmpEqSm;
Begin
Top.Push(Top.Pop <= Top.Pop);
End;
Procedure TArithmeticalStack.DoCmpGtSm;
Begin
Top.Push(Top.Pop >= Top.Pop);
End;
{ TVirtualMachineStack }
Procedure TVirtualMachineStack.DoCall(Const aFunctionName : String);
Var
lMsg : TVirtualMachineMessage;
Begin
lMsg.MsgStr := LowerCase(aFunctionName);
lMsg.Data := Nil;
DispatchStr(lMsg);
End;
Procedure TVirtualMachineStack.DefaultHandlerStr(Var aMessage);
Begin
Raise EVirtualMachineStack.Create('Unknown identifier "' + TVirtualMachineMessage(aMessage).MsgStr + '".');
End;
Procedure TVirtualMachineStack.FunctionTrue(Var aMessage);
Begin
DoPushTrue;
End;
Procedure TVirtualMachineStack.FunctionFalse(Var aMessage);
Begin
DoPushFalse;
End;
{ TExprNode }
Procedure TExprNode.RaiseError(Const aMsg : String);
Begin
Raise EExprNode.Create(IntToStr(fRow) + ',' + IntToStr(fCol) + ',' + aMsg);
End;
Procedure TExprNode.EvaluateChilds;
Begin
First;
While Not(IsAfterLast) Do
Begin
(GetCurrent As TExprNode).Evaluate;
Next;
End;
End;
Procedure TExprNode.PropagateStack(Const aStack : TVirtualMachineStack);
Begin
fStack := aStack;
First;
While Not(IsAfterLast) Do
Begin
(GetCurrent As TExprNode).PropagateStack(aStack);
Next;
End;
End;
{ TUnaryMinusNode }
Procedure TUnaryMinusNode.Evaluate;
Begin
EvaluateChilds;
Stack.Top.Push(-1);
Try
Stack.DoMul;
Except
On E: Exception Do
RaiseError(E.Message);
End;
End;
{ TUnaryNotNode }
Procedure TUnaryNotNode.Evaluate;
Begin
Stack.DoNot;
End;
{ TFunctionCallNode }
Procedure TFunctionCallNode.Evaluate;
Begin
EvaluateChilds;
Try
If Assigned(fParameters) Then
Stack.Enter(Length(fParameters.Childs))
Else
Stack.Enter(0);
Stack.DoCall(fName);
Stack.Leave(1);
Except
On E: Exception Do
RaiseError(E.Message);
End;
End;
{ TStringLiteralNode }
Procedure TStringLiteralNode.Evaluate;
Begin
Stack.Top.Push(fValue);
End;
{ TNumberLiteralNode }
Procedure TNumberLiteralNode.Evaluate;
Begin
Stack.Top.Push(fValue);
End;
{ TMulExpressionNode }
Procedure TMulExpressionNode.Evaluate;
Begin
EvaluateChilds;
If fOperation = '*' Then
Try
Stack.DoMul;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = '/' Then
Try
Stack.DoDiv;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = 'div' Then
Try
Stack.DoIDiv;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = 'mod' Then
Try
Stack.DoMod;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = 'and' Then
Try
Stack.DoAnd;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = '^' Then
Try
Stack.DoPow;
Except
On E: Exception Do
RaiseError(E.Message);
End;
End;
{ TAddExpressionNode }
Procedure TAddExpressionNode.Evaluate;
Begin
EvaluateChilds;
If fOperation = '+' Then
Try
Stack.DoAdd;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = '-' Then
Try
Stack.DoSub;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = 'or' Then
Try
Stack.DoOr;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = 'xor' Then
Try
Stack.DoXOr;
Except
On E: Exception Do
RaiseError(E.Message);
End;
End;
{ TExpressionNode }
Procedure TExpressionNode.Evaluate;
Begin
EvaluateChilds;
If fOperation = '=' Then
Try
Stack.DoCmpEq;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = '<' Then
Try
Stack.DoCmpSm;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = '>' Then
Try
Stack.DoCmpGt;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = '<>' Then
Try
Stack.DoCmpDif;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = '<=' Then
Try
Stack.DoCmpEqSm;
Except
On E: Exception Do
RaiseError(E.Message);
End
Else If fOperation = '>=' Then
Try
Stack.DoCmpGtSm;
Except
On E: Exception Do
RaiseError(E.Message);
End;
End;
{ TExpressionListNode }
Procedure TExpressionListNode.Evaluate;
Begin
EvaluateChilds;
End;
{ TSourceNode }
Procedure TSourceNode.Evaluate;
Begin
EvaluateChilds;
End;
End. |
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ Copyright(c) 2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.WebBrowser.Android;
interface
procedure RegisterWebBrowserService;
procedure UnRegisterWebBrowserService;
implementation
uses
System.Classes, System.Types, System.StrUtils, System.SysUtils,
System.IOUtils, System.RTLConsts, FMX.Platform, FMX.Platform.Android, FMX.WebBrowser,
FMX.Types, FMX.Forms, Androidapi.JNI.Webkit, Androidapi.JNI.Embarcadero,
Androidapi.JNI.Widget, FMX.Helpers.Android, Androidapi.JNI.JavaTypes,
Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.Os,
Androidapi.JNI.Net, Androidapi.NativeActivity, Androidapi.IOUtils;
type
TAndroidWebBrowserService = class;
TAndroidWBService = class(TWBFactoryService)
protected
function DoCreateWebBrowser: ICustomBrowser; override;
end;
{ TAndroidWebBrowserService }
TAndroidWebBrowserService = class(TInterfacedObject, ICustomBrowser)
private
type
TWebBrowserListener = class(TJavaLocal,JOnWebViewListener)
private
FWBService : TAndroidWebBrowserService;
public
constructor Create(AWBService : TAndroidWebBrowserService);
procedure doUpdateVisitedHistory(P1: JWebView; P2: JString; P3: Boolean); cdecl;
procedure onFormResubmission(P1: JWebView; P2: JMessage; P3: JMessage); cdecl;
procedure onLoadResource(P1: JWebView; P2: JString); cdecl;
procedure onPageFinished(P1: JWebView; P2: JString); cdecl;
procedure onPageStarted(P1: JWebView; P2: JString; P3: JBitmap); cdecl;
procedure onReceivedError(P1: JWebView; P2: Integer; P3: JString; P4: JString); cdecl;
procedure onReceivedHttpAuthRequest(P1: JWebView; P2: JHttpAuthHandler; P3: JString; P4: JString); cdecl;
procedure onReceivedSslError(P1: JWebView; P2: JSslErrorHandler; P3: JSslError); cdecl;
procedure onScaleChanged(P1: JWebView; P2: Single; P3: Single); cdecl;
procedure onUnhandledKeyEvent(P1: JWebView; P2: JKeyEvent); cdecl;
function shouldOverrideKeyEvent(P1: JWebView; P2: JKeyEvent): Boolean; cdecl;
function shouldOverrideUrlLoading(P1: JWebView; P2: JString): Boolean; cdecl;
end;
private
FListener : TWebBrowserListener;
FScale : Single;
FJNativeLayout: JNativeLayout;
FJWebBrowser : JWebBrowser;
FURL: string;
FWebControl: TCustomWebBrowser;
FNeedUpdateBounds: Boolean;
FBounds: TRect;
FRealBounds : TRect;
procedure InitUIThread;
procedure SetPositionUIThread;
procedure CalcRealBorder;
procedure SetFocus(AFocus : Boolean);
procedure FocusEnable(Sender: TObject);
procedure FocusDisable(Sender: TObject);
protected
function GetParent : TFmxObject;
function GetVisible : Boolean;
procedure Show;
procedure Hide;
procedure UpdateContentFromControl;
procedure DoNavigate(const URL: string);
procedure DoGoBack;
procedure DoGoForward;
{ IFMXWebBrowserService }
function GetURL: string;
function GetCanGoBack: Boolean;
function GetCanGoForward: Boolean;
procedure SetURL(const AValue: string);
procedure SetWebBrowserControl(const AValue: TCustomWebBrowser);
procedure Navigate;
procedure GoBack;
procedure GoForward;
procedure GoHome;
procedure StartLoading;
procedure FinishLoading;
procedure FailLoadingWithError;
procedure ShouldStartLoading(const URL: string);
public
constructor Create;
destructor Free;
property URL: string read GetURL write SetURL;
property CanGoBack: Boolean read GetCanGoBack;
property CanGoForward: Boolean read GetCanGoForward;
end;
var
WBService : TAndroidWBService;
procedure RegisterWebBrowserService;
begin
WBService := TAndroidWBService.Create;
TPlatformServices.Current.AddPlatformService(IFMXWBService, WBService);
end;
procedure UnregisterWebBrowserService;
begin
TPlatformServices.Current.RemovePlatformService(IFMXWBService);
end;
function TAndroidWebBrowserService.GetCanGoBack: Boolean;
var
CanGoBack: Boolean;
begin
CallInUIThreadAndWaitFinishing(procedure begin
CanGoBack := FJWebBrowser.canGoBack;
end);
Result := CanGoBack;
end;
function TAndroidWebBrowserService.GetCanGoForward: Boolean;
var
CanGoForward: Boolean;
begin
CallInUIThreadAndWaitFinishing(procedure begin
CanGoForward := FJWebBrowser.canGoForward;
end);
Result := CanGoForward;
end;
function TAndroidWebBrowserService.GetParent: TFmxObject;
begin
Result := FWebControl.Parent;
end;
function TAndroidWebBrowserService.GetURL: string;
begin
Result := FURL;
end;
function TAndroidWebBrowserService.GetVisible: Boolean;
begin
Result := False;
if Assigned(FWebControl) then
Result := FWebControl.Visible;
end;
procedure TAndroidWebBrowserService.GoBack;
begin
CallInUIThread(DoGoBack);
end;
procedure TAndroidWebBrowserService.GoForward;
begin
CallInUIThread(DoGoForward);
end;
procedure TAndroidWebBrowserService.GoHome;
begin
end;
procedure TAndroidWebBrowserService.Hide;
begin
CallInUIThread(
procedure
begin
if FJWebBrowser.getVisibility <> TJView.JavaClass.INVISIBLE then
begin
FJWebBrowser.setVisibility(TJView.JavaClass.INVISIBLE);
FJNativeLayout.SetPosition(FRealBounds.Right * 2 , FRealBounds.Height * 2);
end;
end);
end;
procedure TAndroidWebBrowserService.InitUIThread;
begin
FJWebBrowser := TJWebBrowser.JavaClass.init(SharedActivity);
FJWebBrowser.getSettings.setJavaScriptEnabled(True);
FListener := TWebBrowserListener.Create(Self);
FJWebBrowser.SetWebViewListener(FListener);
FJNativeLayout := TJNativeLayout.JavaClass.init(SharedActivity,
MainActivity.getTextEditorProxy.getWindowToken);
FJNativeLayout.SetPosition(100,100);
FJNativeLayout.SetSize(300,300);
FJNativeLayout.SetControl(FJWebBrowser);
FJNativeLayout.SetFocus(False);
end;
procedure TAndroidWebBrowserService.Navigate;
begin
DoNavigate(URL);
end;
procedure TAndroidWebBrowserService.SetFocus(AFocus: Boolean);
begin
if Assigned(FJNativeLayout) then
CallInUIThreadAndWaitFinishing(
procedure
begin
FJNativeLayout.SetFocus(AFocus);
end);
end;
procedure TAndroidWebBrowserService.SetPositionUIThread;
begin
FJNativeLayout.SetPosition(FBounds.Left, FBounds.Top);
FJNativeLayout.SetSize(FBounds.Right, FBounds.Bottom);
end;
procedure TAndroidWebBrowserService.SetURL(const AValue: string);
begin
if FURL <> AValue then
FURL:= AValue;
end;
procedure TAndroidWebBrowserService.SetWebBrowserControl(const AValue: TCustomWebBrowser);
begin
FWebControl := AValue;
FWebControl.OnEnter := FocusEnable;
FWebControl.OnExit := FocusDisable;
end;
procedure TAndroidWebBrowserService.ShouldStartLoading(const URL: string);
begin
if Assigned(FWebControl) then
FWebControl.ShouldStartLoading(URL);
end;
procedure TAndroidWebBrowserService.Show;
begin
CallInUIThread(SetPositionUIThread );
CallInUIThread(
procedure
begin
if FJWebBrowser.getVisibility <> TJView.JavaClass.VISIBLE then
begin
FJWebBrowser.setVisibility(TJView.JavaClass.VISIBLE);
end;
end);
end;
procedure TAndroidWebBrowserService.StartLoading;
begin
if Assigned(FWebControl) then
FWebControl.StartLoading;
end;
procedure TAndroidWebBrowserService.CalcRealBorder;
var
NativeWin: JWindow;
DecorView: JView;
ContentRect: JRect;
begin
NativeWin := SharedActivity.getWindow;
if Assigned(NativeWin) then
begin
ContentRect := TJRect.Create;
DecorView := NativeWin.getDecorView;
DecorView.getWindowVisibleDisplayFrame(ContentRect);
FRealBounds := Rect(ContentRect.left,ContentRect.top, ContentRect.right,ContentRect.bottom);
end;
end;
constructor TAndroidWebBrowserService.Create;
var
ScreenSrv: IFMXScreenService;
begin
CalcRealBorder;
if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(ScreenSrv)) then
FScale := ScreenSrv.GetScreenScale
else
FScale := 1;
CallInUIThreadAndWaitFinishing(InitUIThread);
end;
procedure TAndroidWebBrowserService.DoGoBack;
begin
inherited;
FJWebBrowser.goBack;
end;
procedure TAndroidWebBrowserService.DoGoForward;
begin
inherited;
FJWebBrowser.goForward;
end;
procedure TAndroidWebBrowserService.DoNavigate(const URL: string);
var
NewURL: string;
begin
NewURL := URL;
if Pos('file://', URL) <> 0 then
begin
NewURL := ReplaceStr(NewURL,'file://','file:///');
FJWebBrowser.loadUrl(StringToJString(NewURL));
end
else
begin
if Pos('http', URL) = 0 then
Insert('http://', NewURL, 0);
FJWebBrowser.loadUrl(StringToJString(NewURL));
end;
UpdateContentFromControl;
end;
procedure TAndroidWebBrowserService.FailLoadingWithError;
begin
if Assigned(FWebControl) then
FWebControl.FailLoadingWithError;
end;
procedure TAndroidWebBrowserService.FinishLoading;
begin
if Assigned(FWebControl) then
FWebControl.FinishLoading;
end;
procedure TAndroidWebBrowserService.FocusDisable(Sender: TObject);
begin
SetFocus(False);
end;
procedure TAndroidWebBrowserService.FocusEnable(Sender: TObject);
begin
SetFocus(True);
end;
destructor TAndroidWebBrowserService.Free;
begin
end;
procedure TAndroidWebBrowserService.UpdateContentFromControl;
var
Pos : TPointF;
begin
while not Assigned(FJNativeLayout) do Application.ProcessMessages;
if Assigned(FJNativeLayout) then
begin
if (FWebControl <> nil)
and not (csDesigning in FWebControl.ComponentState)
and (FWebControl.Root <> nil)
and (FWebControl.Root.GetObject is TCommonCustomForm) then
begin
if FWebControl.Parent is TCommonCustomForm then
Pos := FRealBounds.TopLeft + FWebControl.Position.Point
else
Pos := FWebControl.Parent.AsIControl.LocalToScreen(FWebControl.Position.Point);
FNeedUpdateBounds := True;
FBounds := Rect(Round(Pos.X * FScale),Round(Pos.Y * FScale),
Round(FWebControl.Width * FScale), Round(FWebControl.Height * FScale));
if FWebControl.Visible and FWebControl.ParentedVisible
and (FWebControl.Root.GetObject as TCommonCustomForm).Visible
and (FWebControl.Root.GetObject as TCommonCustomForm).Active
then
begin
Show;
end
else
Hide;
end
else
Hide;
end;
end;
{ TAndroidWBService }
function TAndroidWBService.DoCreateWebBrowser: ICustomBrowser;
var
Browser : TAndroidWebBrowserService;
begin
Browser := TAndroidWebBrowserService.Create;
Result := Browser;
end;
{ TAndroidWebBrowserService.TWebBrowserListener }
constructor TAndroidWebBrowserService.TWebBrowserListener.Create(
AWBService: TAndroidWebBrowserService);
begin
inherited Create;
FWBService := AWBService;
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.doUpdateVisitedHistory(
P1: JWebView; P2: JString; P3: Boolean);
begin
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onFormResubmission(
P1: JWebView; P2, P3: JMessage);
begin
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onLoadResource(
P1: JWebView; P2: JString);
begin
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onPageFinished(
P1: JWebView; P2: JString);
begin
FWBService.FURL := JStringToString(P2);
FWBService.FinishLoading;
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onPageStarted(
P1: JWebView; P2: JString; P3: JBitmap);
begin
FWBService.StartLoading;
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onReceivedError(
P1: JWebView; P2: Integer; P3, P4: JString);
begin
FWBService.FailLoadingWithError;
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onReceivedHttpAuthRequest(
P1: JWebView; P2: JHttpAuthHandler; P3, P4: JString);
begin
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onReceivedSslError(
P1: JWebView; P2: JSslErrorHandler; P3: JSslError);
begin
FWBService.FailLoadingWithError;
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onScaleChanged(
P1: JWebView; P2, P3: Single);
begin
end;
procedure TAndroidWebBrowserService.TWebBrowserListener.onUnhandledKeyEvent(
P1: JWebView; P2: JKeyEvent);
begin
end;
function TAndroidWebBrowserService.TWebBrowserListener.shouldOverrideKeyEvent(
P1: JWebView; P2: JKeyEvent): Boolean;
begin
Result := False;
end;
function TAndroidWebBrowserService.TWebBrowserListener.shouldOverrideUrlLoading(
P1: JWebView; P2: JString): Boolean;
begin
Result := False;
end;
end.
|
unit jclass_enum;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils;
type
TJConstantType = (
ctUtf8 = 1,
ctInteger = 3,
ctFloat = 4,
ctLong = 5,
ctDouble = 6,
ctClass = 7,
ctString = 8,
ctFieldref = 9,
ctMethodref = 10,
ctInterfaceMethodref = 11,
ctNameAndType = 12,
ctMethodHandle = 15,
ctMethodType = 16,
ctDynamic = 17,
ctInvokeDynamic = 18,
ctModule = 19,
ctPackage = 20
);
TJAttributeLocation = (
alClassFile,
alFieldInfo,
alMethodInfo,
alCode
);
TJStackFrameType = (
sftSameFirst = 0,
sftSameLast = 63,
sftLocals1First = 64,
sftLocals1Last = 127,
sftLocals1Ext = 247,
sftChopFirst = 248,
sftChopLast = 250,
sftFrameExt = 251,
sftAppendFirst = 252,
sftAppendLast = 254,
sftFull = 255
);
TJClassAccessFlag = (
cafPublic = $0001,
cafPrivate = $0002,
cafProtected = $0004,
cafStatic = $0008,
cafFinal = $0010,
cafSuper = $0020,
cafInterface = $0200,
cafAbstract = $0400,
cafSynthetic = $1000,
cafAnnotation = $2000,
cafEnum = $4000,
cafModule = $8000
);
TJClassFieldAccessFlag = (
fafPublic = $0001,
fafPrivate = $0002,
fafProtected = $0004,
fafStatic = $0008,
fafFinal = $0010,
fafVolatile = $0040,
fafTransient = $0080,
fafSynthetic = $1000,
fafEnum = $4000
);
TJClassMethodAccessFlag = (
mafPublic = $0001,
mafPrivate = $0002,
mafProtected = $0004,
mafStatic = $0008,
mafFinal = $0010,
mafSynchronized = $0020,
mafBridge = $0040,
mafVarArgs = $0080,
mafNative = $0100,
mafAbstract = $0400,
mafStrict = $0800,
mafSynthetic = $1000
);
function ClassAccessFlagsToString(AAccessFlags: UInt16): string;
implementation
const
TJClassAccessFlagNames: array of string = (
'Public',
'Private',
'Protected',
'Static',
'Final',
'Super',
'Interface',
'Abstract',
'Synthetic',
'Annotation',
'Enum',
'Module'
);
TJClassAccessFlagValues: array of TJClassAccessFlag = (
cafPublic,
cafPrivate,
cafProtected,
cafStatic,
cafFinal,
cafSuper,
cafInterface,
cafAbstract,
cafSynthetic,
cafAnnotation,
cafEnum,
cafModule
);
function ClassAccessFlagsToString(AAccessFlags: UInt16): string;
var
i: integer;
begin
Result := '';
for i := 0 to High(TJClassAccessFlagValues) do
if Ord(TJClassAccessFlagValues[i]) and AAccessFlags > 0 then
Result := Result + ' ' + TJClassAccessFlagNames[i];
Result := trim(Result);
end;
end.
|
unit fDataMapping;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.ValEdit, Vcl.ExtCtrls,
Vcl.StdCtrls, Data.DB;
type
TFrmDataMapping = class(TForm)
panLeft: TPanel;
vleOffMapping: TValueListEditor;
panRigth: TPanel;
vleOnMapping: TValueListEditor;
btnMappingOff: TButton;
btnMappingOn: TButton;
procedure btnMappingOffClick(Sender: TObject);
procedure btnMappingOnClick(Sender: TObject);
private
function GetFieldType(Value: TFieldType): String;
procedure GetFieldsProperties(List: TValueListEditor);
procedure ClearMapRules;
procedure SetMapRules;
{ Private declarations }
public
{ Public declarations }
end;
var
FrmDataMapping: TFrmDataMapping;
implementation
{$R *.dfm}
uses dDataMapping, FireDAC.Stan.Intf;
procedure TFrmDataMapping.btnMappingOffClick(Sender: TObject);
begin
vleOffMapping.Strings.Clear;
DMDataMapping.Connection.Connected := False;
ClearMapRules;
DMDataMapping.Connection.Connected := True;
GetFieldsProperties(vleOffMapping);
end;
function TFrmDataMapping.GetFieldType(Value: TFieldType): String;
begin
case Value of
ftSmallint: Result := 'ftSmallint';
ftInteger: Result := 'ftInteger';
ftFloat: Result := 'ftFloat';
ftCurrency: Result := 'ftCurrency';
ftBCD: Result := 'ftBCD';
ftLargeint: Result := 'ftLargeint';
ftFMTBcd: Result := 'ftFMTBcd';
ftShortint: Result := 'ftShortint';
ftByte: Result := 'ftByte';
ftExtended: Result := 'ftExtended';
end;
end;
procedure TFrmDataMapping.btnMappingOnClick(Sender: TObject);
begin
vleOnMapping.Strings.Clear;
DMDataMapping.Connection.Connected := False;
SetMapRules;
DMDataMapping.Connection.Connected := True;
GetFieldsProperties(vleOnMapping);
end;
procedure TFrmDataMapping.GetFieldsProperties(List: TValueListEditor);
var
I: Integer;
begin
DMDataMapping.Query.Open;
for I := 0 to DMDataMapping.Query.FieldCount - 1 do
List.Strings.Add(DMDataMapping.Query.Fields[I].FieldName + '=' +
GetFieldType(DMDataMapping.Query.Fields[I].DataType));
end;
procedure TFrmDataMapping.ClearMapRules;
begin
DMDataMapping.Connection.FormatOptions.MapRules.Clear;
end;
procedure TFrmDataMapping.SetMapRules;
begin
ClearMapRules;
with DMDataMapping.Connection.FormatOptions do
begin
with MapRules.Add do begin
SourceDataType := dtInt16;
TargetDataType := dtInt64;
end;
with MapRules.Add do begin
SourceDataType := dtInt32;
TargetDataType := dtInt64;
end;
with MapRules.Add do begin
ScaleMin := 4;
ScaleMax := 4;
PrecMin := 18;
PrecMax := 18;
SourceDataType := dtBcd;
TargetDataType := dtCurrency;
end;
with MapRules.Add do begin
ScaleMin := 6;
ScaleMax := 6;
PrecMin := 18;
PrecMax := 18;
SourceDataType := dtFmtBCD;
TargetDataType := dtCurrency;
end;
end;
end;
end.
|
unit AbstractFactory.Concretes.ConcreteProductB1;
interface
uses
AbstractFactory.Interfaces.IAbstractProductB,
AbstractFactory.Interfaces.IAbstractProductA;
// Concrete Products are created by corresponding Concrete Factories.
// Produtos concretos são criados por correspondentes fabricas concretas
type
TConcreteProductB1 = class(TInterfacedObject, IAbstractProductB)
public
function UsefulFunctionB: string;
// The variant, Product B1, is only able to work correctly with the
// variant, Product A1. Nevertheless, it accepts any instance of
// AbstractProductA as an argument.
// A variação, Produto B1, é somente capaz de trabalhar corretamente com a variant, Produto A1.
// Mesmo assim, aceita qualquer instancia de AbstractProductA como argumento
function AnotherUsefulFunctionB(ACollaborator: IAbstractProductA): string;
end;
implementation
{ TConcreteProductB1 }
function TConcreteProductB1.AnotherUsefulFunctionB(ACollaborator
: IAbstractProductA): string;
begin
Result := 'The result of the B1 collaborating with the ' +
ACollaborator.UsefulFunctionA;
end;
function TConcreteProductB1.UsefulFunctionB: string;
begin
Result := 'The result of the product B1';
end;
end.
|
unit CadastroBomba;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ToolWin, Util, Bomba, BombaBO,
Vcl.Buttons;
type
TFormCadastroBomba = class(TForm)
ToolBar: TToolBar;
ToolButtonNovo: TToolButton;
ToolButton01: TToolButton;
ToolButtonSalvar: TToolButton;
ToolButtonCancelar: TToolButton;
ToolButton02: TToolButton;
ToolButtonPesquisar: TToolButton;
ToolButton03: TToolButton;
ToolButtonExcluir: TToolButton;
LabelCodigo: TLabel;
EditCodigo: TEdit;
LabelDescricao: TLabel;
EditDescricao: TEdit;
StatusBar: TStatusBar;
LabelTanque: TLabel;
EditCodigoTanque: TEdit;
EditDescricaoTanque: TEdit;
BitBtnConsultarTanque: TBitBtn;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormShow(Sender: TObject);
procedure ToolButtonNovoClick(Sender: TObject);
procedure ToolButtonSalvarClick(Sender: TObject);
procedure ToolButtonCancelarClick(Sender: TObject);
procedure ToolButtonPesquisarClick(Sender: TObject);
procedure ToolButtonExcluirClick(Sender: TObject);
procedure BitBtnConsultarTanqueClick(Sender: TObject);
private
UltimoIdVisualizado :Integer;
procedure ExibirUltimoRegistro;
procedure ExibirRegistro(Bomba: TBomba);
procedure SalvarBomba;
function ValidarGravacao:Boolean;
public
{ Public declarations }
end;
var
FormCadastroBomba: TFormCadastroBomba;
implementation
{$R *.dfm}
uses TanqueBO, ConsultaPadrao, Principal;
procedure TFormCadastroBomba.BitBtnConsultarTanqueClick(Sender: TObject);
begin
try
if (FormConsultaPadrao = nil) then
begin
Application.CreateForm(TFormConsultaPadrao, FormConsultaPadrao);
end;
FormConsultaPadrao.TipoConsulta := ConsultaTanque;
FormConsultaPadrao.ShowModal();
if (Trim(IdSelecionado) <> '') then
begin
EditCodigoTanque.Text := Trim(IdSelecionado);
EditDescricaoTanque.Text := Trim(DescricaoSelecionada);
end;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.ExibirRegistro(Bomba: TBomba);
begin
try
if (Bomba <> nil) then
begin
UltimoIdVisualizado := Bomba.Id;
EditCodigo.Text := IntToStr(Bomba.Id);
EditDescricao.Text := Bomba.Descricao;
EditCodigoTanque.Text := IntToStr(Bomba.Tanque.Id);
EditDescricaoTanque.Text := Bomba.Tanque.Descricao;
end
else
begin
ToolButtonNovo.Click();
end;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.ExibirUltimoRegistro;
var
BombaBO: TBombaBO;
Bomba: TBomba;
begin
try
BombaBO := TBombaBO.Create();
Bomba := BombaBO.UltimaBomba();
ExibirRegistro(Bomba);
FreeAndNil(Bomba);
FreeAndNil(BombaBO);
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.FormClose(Sender: TObject; var Action: TCloseAction);
begin
try
Action := caFree;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.FormDestroy(Sender: TObject);
begin
try
FormCadastroBomba := nil;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
try
case (Key) of
VK_F2 : ToolButtonNovo.Click();
VK_F3 : ToolButtonSalvar.Click();
VK_F4 : ToolButtonCancelar.Click();
VK_F5 : ToolButtonPesquisar.Click();
VK_F6 : ToolButtonExcluir.Click();
VK_ESCAPE : Close;
end;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.FormShow(Sender: TObject);
begin
try
ExibirUltimoRegistro();
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.SalvarBomba;
var
TanqueBO: TTanqueBO;
BombaBO: TBombaBO;
Bomba: TBomba;
begin
try
Bomba := TBomba.Create;
if (Trim(EditCodigo.Text) = '') then
begin
Bomba.Id := 0;
end
else
begin
Bomba.Id := StrToInt(Trim(EditCodigo.Text));
end;
Bomba.Descricao := Trim(EditDescricao.Text);
TanqueBO := TTanqueBO.Create;
Bomba.Tanque := TanqueBO.ObterTanquePorId(StrToInt(Trim(EditCodigoTanque.Text)));
FreeAndNil(TanqueBO);
BombaBO := TBombaBO.Create;
BombaBO.Salvar(Bomba);
FreeAndNil(BombaBO);
FreeAndNil(Bomba);
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.ToolButtonCancelarClick(Sender: TObject);
var
BombaBO: TBombaBO;
Bomba: TBomba;
begin
try
BombaBO := TBombaBO.Create();
Bomba := BombaBO.ObterBombaPorId(UltimoIdVisualizado);
ExibirRegistro(Bomba);
FreeAndNil(Bomba);
FreeAndNil(BombaBO);
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.ToolButtonExcluirClick(Sender: TObject);
var
BombaBO: TBombaBO;
Bomba: TBomba;
begin
try
if (Trim(EditCodigo.Text) = '') then
begin
TUtil.Mensagem('Selecione um bomba para poder realizar a exclusão');
Exit;
end;
if not(TUtil.Confirmacao('Tem certeza que deseja excluir a bomba?')) then
begin
Exit;
end;
BombaBO := TBombaBO.Create();
Bomba := TBomba.Create();
Bomba.Id := StrToInt(Trim(EditCodigo.Text));
BombaBO.Excluir(Bomba);
FreeAndNil(Bomba);
FreeAndNil(BombaBO);
ExibirUltimoRegistro();
TUtil.Mensagem('Bomba excluida com sucesso.');
except on E: Exception do
begin
if (Pos('FK',UpperCase(E.Message)) > 0) then
begin
TUtil.Mensagem('A bomba não pode ser excluída pois a mesma possui referencias.');
end
else
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
end;
procedure TFormCadastroBomba.ToolButtonNovoClick(Sender: TObject);
begin
try
EditCodigo.Clear();
EditDescricao.Clear();
EditCodigoTanque.Clear();
EditDescricaoTanque.Clear();
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.ToolButtonPesquisarClick(Sender: TObject);
var
BombaBO: TBombaBO;
Bomba: TBomba;
begin
try
if (FormConsultaPadrao = nil) then
begin
Application.CreateForm(TFormConsultaPadrao, FormConsultaPadrao);
end;
FormConsultaPadrao.TipoConsulta := ConsultaBomba;
FormConsultaPadrao.ShowModal();
if (Trim(IdSelecionado) <> '') then
begin
BombaBO := TBombaBO.Create();
Bomba := BombaBO.ObterBombaPorId(StrToInt(IdSelecionado));
ExibirRegistro(Bomba);
FreeAndNil(Bomba);
FreeAndNil(BombaBO);
end;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
procedure TFormCadastroBomba.ToolButtonSalvarClick(Sender: TObject);
begin
try
if not(ValidarGravacao()) then
begin
Exit;
end;
SalvarBomba();
if (Trim(EditCodigo.Text) = '') then
begin
ExibirUltimoRegistro();
end;
TUtil.Mensagem('Bomba gravada com sucesso.');
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
function TFormCadastroBomba.ValidarGravacao: Boolean;
begin
try
Result := False;
if (Trim(EditDescricao.Text) = '') then
begin
TUtil.Mensagem('Informe a descrição da bomba.');
EditDescricao.SetFocus;
Exit;
end;
if (Trim(EditCodigoTanque.Text) = '') then
begin
TUtil.Mensagem('Selecione o tanque de combustível da bomba.');
BitBtnConsultarTanque.SetFocus;
Exit;
end;
Result := True;
except on E: Exception do
begin
TUtil.Mensagem(e.Message);
end;
end;
end;
end.
|
unit ServerMethodsUnit1;
interface
uses
System.SysUtils,
System.Classes,
System.Json,
Datasnap.DSServer,
Datasnap.DSAuth,
DataSnap.DSProviderDataModuleAdapter,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
FireDAC.Phys.IB,
FireDAC.Phys.IBDef,
FireDAC.VCLUI.Wait,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.DApt,
Data.DB,
FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
frxClass,
frxExportPDF,
frxDBSet,
FireDAC.Phys.FB,
FireDAC.Phys.FBDef,
FireDAC.Phys.IBBase, FireDAC.Comp.UI, FireDAC.Stan.StorageJSON,
FireDAC.Stan.StorageBin, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef,
FireDAC.Stan.ExprFuncs;
type
TServerMethods1 = class(TDSServerModule)
frxReport1: TfrxReport;
frxDBDataset1: TfrxDBDataset;
frxPDFExport1: TfrxPDFExport;
fdConn: TFDConnection;
qryRelatorio: TFDQuery;
FDStanStorageBinLink1: TFDStanStorageBinLink;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
qryRelatorioCODIGO: TIntegerField;
qryRelatorioapelido: TStringField;
qryRelatoriorazaosocial: TStringField;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
private
{ Private declarations }
public
{ Public declarations }
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
function DownloadFile(const AArquivo: String; out Size: Int64): TStream;
function GerarPDF(out Size: Int64): TStream;
end;
implementation
{$R *.dfm}
uses System.StrUtils;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods1.GerarPDF(out Size: Int64): TStream;
//var
// CaminhoPDF : String;
// Debug : String;
begin
// qryRelatorio.Active := True;
//
// CaminhoPDF := 'C:\Temp\PDF\'; //;ExtractFilePath('..\..\..\PDF\');
//
// frxPDFExport1.FileName := CaminhoPDF + 'Relatorio.pdf';
// frxPDFExport1.DefaultPath := CaminhoPDF + '\';
// frxPDFExport1.ShowDialog := False;
// frxPDFExport1.ShowProgress := False;
// frxPDFExport1.OverwritePrompt := False;
//
// frxReport1.PrepareReport();
// frxReport1.Export(frxPDFExport1);
// qryRelatorio.Active := False;
//
// Result := TFileStream.Create(CaminhoPDF + 'Relatorio.pdf', fmOpenRead or fmShareDenyNone);
// Size := Result.Size;
//
// Result.Position := 0;
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
function TServerMethods1.DownloadFile(const AArquivo: String;
out Size: Int64): TStream;
var
CaminhoImagem: String;
Debug: String;
begin
CaminhoImagem := ExtractFilePath('..\..\..\img\');
Debug := CaminhoImagem + AArquivo;
Result := TFileStream.Create(CaminhoImagem + AArquivo, fmOpenRead or fmShareDenyNone);
Size := Result.Size;
Result.Position := 0;
end;
end.
|
{! Unified reading from StdIn for Linux.
@copyright
(c)2021 Medical Data Solutions GmbH, www.medaso.de
@license
MIT:
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.
@author
jrgdre: J.Drechsler, Medical Data Solutions GmbH
@version
1.0.0 2021-07-11 jrgdre, initial release
}
unit StdIn_Linux;
{$mode Delphi}
interface
{$ifdef Linux}
uses
classes,
StdIn;
{! Append `memory` with the values read from StdIn.
Works for following use cases:
1. `prg < file`
2. `(type, cat) file | prg`
3. `prg`
In the first two cases it is assumed, that all the input is in the file.
The file is read with blocking calls, until the end of the file is reached.
In the third case the function waits for the user to input the first char.
If `timeOut` is reached before that, the procedure exits.
After the first char is read, the routine waits indefinitely for more chars
to to be entered, until it reads the EOF signal.
The default value of `0` for `timeOut` makes the procedure wait indefinitely
also for the first char.
`timeOut` as a fixed resolution of 50ms.
@returns TStdInReadError
}
function Linux_Read_StdIn(
var ms : TMemoryStream; //!< target of read operation
const timeOut: NativeUInt = 0 //!< timeout for first key input (50ms res.)
): TStdInReadError;
{$endif}
implementation
{$ifdef Linux}
uses
sysutils,
baseunix, // FpRead
keyboard, // PollKeyEvent
termio; // IsATTY
{! Read from a redirected input stream.
}
function ReadFile(
var ms: TMemoryStream;
const h : THandle
): TStdInReadError;
var
b: Byte;
begin
b := 0;
while (FpRead(h, b, 1) > 0) do begin
try
ms.WriteByte(b);
except
on E: Exception do begin
Result := sireWriteError;
Exit;
end;
end;
end;
Result := sireNoError;
end;
{! Read interactive keyboard input, with timeout for first key.
- For all consecutive keys the function waits indefinitely.
- Reading the input stops, when the user inputs EOF (CTRL-D on Linux).
The global variable `ShowHint` in `Stdin.pas` controls, if the function
writes `Hint1` and `Hint2` (also global variables in `Stdin.pas`) to the
console.
The global variable `TimeOutResolutionMS` in `Stdin.pas` controls the sleep
time between the checks for the first input.
}
function ReadInteractive(
var ms : TMemoryStream;
const h : THandle;
const timeOut: NativeUInt
): TStdInReadError;
var
c : Char;
ts: QWord;
ke: TKeyEvent;
begin
if ShowHint then begin
WriteLn(Format(Hint1, [timeOut]));
WriteLn(Hint2);
end;
InitKeyboard;
ts := GetTickCount64;
while (PollKeyEvent = 0) do begin
Sleep(timeOutResolutionMS);
if ((GetTickCount64 - ts) >= timeOut) then begin
Result := sireTimeOut;
DoneKeyboard;
Exit;
end;
end;
ke := GetkeyEvent;
ke := TranslateKeyEvent(ke);
if (GetKeyEventFlags(ke) = kbASCII) then begin
c := GetKeyEventChar(ke);
if (c = #13) then
WriteLn
else
Write(c);
end
else
c := #0;
DoneKeyboard;
while (not EOF) do begin
if (c = #0) then
System.Read(c);
if (ms.Write(c, 1) = 0) then begin
Result := sireWriteError;
Exit;
end;
c := #0;
end;
Result := sireNoError;
end;
{
}
function Linux_Read_StdIn(
var ms : TMemoryStream;
const timeOut: NativeUInt = 0
): TStdInReadError;
var
h: THandle;
begin
h := GetFileHandle(Input);
if (h < 0) then begin
Result := sireInvalidHandle;
Exit;
end;
if (IsATTY(h) = 1) then
Result := ReadInteractive(ms, h, timeOut)
else begin
Result := ReadFile(ms, h);
end;
end;
{$endif}
end.
|
unit OAuth2.Contract.Grant.GrantType;
interface
uses
Web.HTTPApp,
OAuth2.Contract.ResponseType,
OAuth2.Contract.Repository.Client,
OAuth2.Contract.Repository.AccessToken,
OAuth2.Contract.Repository.Scope,
OAuth2.RequestType.AuthorizationRequest,
OAuth2.CryptKey;
type
IOAuth2GrantTypeGrant = interface
['{73258B0C-F1DC-4149-89E5-AC7A73C14FCA}']
function GetIdentifier: string;
function RespondToAccessTokenRequest(ARequest: TWebRequest; AResponseType: IOAuth2ResponseType; AAccessTokenTTL: Int64): IOAuth2ResponseType;
function CanRespondToAuthorizationRequest(ARequest: TWebRequest): Boolean;
function ValidateAuthorizationRequest(ARequest: TWebRequest): TOAuth2AuthorizationRequest;
function CompleteAuthorizationRequest(AAuthorizationRequest: TOAuth2AuthorizationRequest): IOAuth2ResponseType;
function CanRespondToAccessTokenRequest(ARequest: TWebRequest): Boolean;
procedure SetRefreshTokenTTL(ARefreshTokenTTL: Int64);
procedure SetClientRepository(AClientRepository: IOAuth2ClientRepository);
procedure SetAccessTokenRepository(AAccessTokenRepository: IOAuth2AccessTokenRepository);
procedure SetScopeRepository(AScopeRepository: IOAuth2ScopeRepository);
procedure SetDefaultScope(ADefaultScope: string);
procedure SetPrivateKey(APrivateKey: TOAuth2CryptKey);
procedure SetEncryptionKey(AKey: string);
end;
implementation
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.TestRunner;
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.Classes,
System.SysUtils,
System.Rtti,
System.Generics.Collections,
{$ELSE}
Classes,
SysUtils,
Rtti,
Generics.Collections,
{$ENDIF}
DUnitX.TestFramework,
DUnitX.Extensibility,
DUnitX.InternalInterfaces,
DUnitX.Generics,
DUnitX.WeakReference,
DUnitX.Filters,
DUnitX.Exceptions;
type
/// Note - we rely on the fact that there will only ever be 1 testrunner
/// per thread, if this changes then handling of WriteLn will need to change
TDUnitXTestRunner = class(TWeakReferencedObject, ITestRunner)
private class var
FRttiContext : TRttiContext;
public class var
FActiveRunners : TDictionary<TThreadID,IWeakReference<ITestRunner>>;
private
FLoggers : TList<ITestLogger>;
FUseRTTI : boolean;
FFixtureClasses : TDictionary<TClass,string>;
FFixtureList : ITestFixtureList;
FLogMessages : TStringList;
FLogMessagesEx : TLogMessageArray;
FFailsOnNoAsserts : boolean;
FCurrentTestName : string;
protected
procedure CountAndFilterTests(const fixtureList: ITestFixtureList; var count, active: Cardinal);
//Logger calls - sequence ordered
procedure Loggers_TestingStarts(const threadId: TThreadID; testCount, testActiveCount: Cardinal);
procedure Loggers_StartTestFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure Loggers_SetupFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure Loggers_EndSetupFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure Loggers_BeginTest(const threadId: TThreadID; const Test: ITestInfo);
procedure Loggers_SetupTest(const threadId: TThreadID; const Test: ITestInfo);
procedure Loggers_EndSetupTest(const threadId: TThreadID; const Test: ITestInfo);
procedure Loggers_ExecuteTest(const threadId: TThreadID; const Test: ITestInfo);
procedure Loggers_AddSuccess(const threadId: TThreadID; const Test: ITestResult);
procedure Loggers_AddError(const threadId: TThreadID; const Error: ITestError);
procedure Loggers_AddFailure(const threadId: TThreadID; const Failure: ITestError);
procedure Loggers_AddIgnored(const threadId: TThreadID; const AIgnored: ITestResult);
procedure Loggers_AddMemoryLeak(const threadId: TThreadID; const Test: ITestResult);
procedure Loggers_EndTest(const threadId: TThreadID; const Test: ITestResult);
procedure Loggers_TeardownTest(const threadId: TThreadID; const Test: ITestInfo);
procedure Loggers_EndTeardownTest(const aThreadId: TThreadID; const aTest: ITestInfo);
procedure Loggers_TeardownFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure Loggers_EndTearDownFixture(const aThreadId: TThreadID; const aFixture: ITestFixtureInfo);
procedure Loggers_EndTestFixture(const threadId: TThreadID; const results: IFixtureResult);
procedure Loggers_TestingEnds(const RunResults: IRunResults);
//ITestRunner
procedure AddLogger(const value: ITestLogger);
function Execute: IRunResults;
procedure ExecuteFixtures(const parentFixtureResult: IFixtureResult; const context: ITestExecuteContext; const threadId: TThreadID; const fixtures: ITestFixtureList);
procedure ExecuteSetupFixtureMethod(const context: ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const fixtureResult: IFixtureResult);
function ExecuteTestSetupMethod(const context: ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const test: ITest; out errorResult: ITestResult; const memoryAllocationProvider: IMemoryLeakMonitor): boolean;
procedure ExecuteTests(const context: ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const fixtureResult: IFixtureResult);
function ExecuteTest(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const memoryAllocationProvider: IMemoryLeakMonitor): ITestResult;
function ExecuteSuccessfulResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const aMessage: string; const aLogMessages: TLogMessageArray): ITestResult;
function ExecuteFailureResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const exception: Exception; const aLogMessages: TLogMessageArray): ITestError;
function ExecuteTimedOutResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const exception: Exception; const aLogMessages: TLogMessageArray) : ITestError;
function ExecuteErrorResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const exception: Exception; const aLogMessages: TLogMessageArray): ITestError;
function ExecuteIgnoredResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const ignoreReason: string): ITestResult;
procedure InvalidateTestsInFixture(const aFixture: ITestFixture; const aContext: ITestExecuteContext; const aThreadId: TThreadID; const aException: Exception; const aFixtureResult: IFixtureResult);
function CheckMemoryAllocations(const test: ITest; out errorResult: ITestResult; const memoryAllocationProvider: IMemoryLeakMonitor): boolean;
function ExecuteTestTearDown(const context: ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const test: ITest; out errorResult: ITestResult; const memoryAllocationProvider: IMemoryLeakMonitor): boolean;
procedure ExecuteTearDownFixtureMethod(const context: ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const fixtureResult: IFixtureResult);
procedure RecordResult(const context: ITestExecuteContext; const threadId: TThreadID; const fixtureResult: IFixtureResult; const testResult: ITestResult);
function GetUseRTTI: Boolean;
procedure SetUseRTTI(const value: Boolean);
function GetFailsOnNoAsserts: boolean;
procedure SetFailsOnNoAsserts(const value: boolean);
procedure Log(const logType: TLogLevel; const msg: string); overload;
procedure Log(const msg: string); overload;
//for backwards compatibilty with DUnit tests.
procedure Status(const msg: string); overload;
//redirects WriteLn to our loggers.
procedure WriteLn(const msg: string); overload;
procedure WriteLn; overload;
function CurrentTestName : string;
//internals
procedure RTTIDiscoverFixtureClasses;
function BuildFixtures: IInterface;
procedure AddStatus(const threadId; const msg: string);
function DoCreateFixture(const AInstance: TObject; const AFixtureClass: TClass; const AName: string; const ACategory: string): ITestFixture; virtual;
function CreateFixture(const AInstance: TObject; const AFixtureClass: TClass; const AName: string; const ACategory: string): ITestFixture;
function ShouldRunThisTest(const test: ITest): boolean;
class constructor Create;
class destructor Destroy;
public
constructor Create; overload;
constructor Create(const AListener: ITestLogger); overload;
constructor Create(const AListeners: array of ITestLogger); overload;
destructor Destroy; override;
class function GetActiveRunner: ITestRunner;
class function GetCurrentTestName : string;
end;
implementation
uses
{$IFDEF USE_NS}
System.TypInfo,
System.StrUtils,
System.Types,
{$ELSE}
TypInfo,
StrUtils,
Types,
{$ENDIF}
DUnitX.Attributes,
DUnitX.CommandLine.Options,
DUnitX.TestFixture,
DUnitX.RunResults,
DUnitX.TestResult,
DUnitX.FixtureResult,
DUnitX.Utils,
DUnitX.IoC,
DUnitX.Extensibility.PluginManager,
DUnitX.ResStrs;
{ TDUnitXTestRunner }
procedure TDUnitXTestRunner.Log(const msg: string);
begin
Self.Log(TLogLevel.Information,msg);
end;
procedure TDUnitXTestRunner.Loggers_AddError(const threadId: TThreadID; const Error: ITestError);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestError(threadId, Error);
end;
end;
procedure TDUnitXTestRunner.Loggers_AddFailure(const threadId: TThreadID; const Failure: ITestError);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestFailure(threadId, Failure);
end;
end;
procedure TDUnitXTestRunner.Loggers_AddIgnored(const threadId: TThreadID; const AIgnored: ITestResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestIgnored(threadId,AIgnored);
end;
end;
procedure TDUnitXTestRunner.Loggers_AddMemoryLeak(const threadId: TThreadID; const Test: ITestResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestMemoryLeak(threadId,Test);
end;
end;
procedure TDUnitXTestRunner.AddLogger(const value: ITestLogger);
begin
if not FLoggers.Contains(value) then
FLoggers.Add(value);
end;
procedure TDUnitXTestRunner.Loggers_AddSuccess(const threadId: TThreadID; const Test: ITestResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestSuccess(threadId,Test);
end;
end;
procedure TDUnitXTestRunner.AddStatus(const threadId; const msg: string);
begin
//TODO : What should be here???
end;
function TDUnitXTestRunner.BuildFixtures : IInterface;
var
pluginManager : IPluginManager;
begin
result := FFixtureList;
if FFixtureList <> nil then
exit;
FFixtureList := TTestFixtureList.Create;
pluginManager := TPluginManager.Create(Self.CreateFixture,FUseRTTI);
pluginManager.Init;//loads the plugin features.
//generate the fixtures. The plugin Manager calls back into CreateFixture
pluginManager.CreateFixtures;
FFixtureList.Sort;
result := FFixtureList;
end;
class constructor TDUnitXTestRunner.Create;
begin
FRttiContext := TRttiContext.Create;
FActiveRunners := TDictionary<TThreadID,IWeakReference<ITestRunner>>.Create;
end;
function TDUnitXTestRunner.CheckMemoryAllocations(const test: ITest; out errorResult: ITestResult; const memoryAllocationProvider: IMemoryLeakMonitor): boolean;
var
LSetUpMemoryAllocated: Int64;
LTearDownMemoryAllocated: Int64;
LTestMemoryAllocated: Int64;
LMsg: string;
LMemoryAllocationProvider2: IMemoryLeakMonitor2;
testInfo : ITestInfo;
begin
Result := True;
errorResult := nil;
if (test.IgnoreMemoryLeaks) then
Exit;
LSetUpMemoryAllocated := memoryAllocationProvider.SetUpMemoryAllocated;
LTestMemoryAllocated := memoryAllocationProvider.TestMemoryAllocated;
LTearDownMemoryAllocated := memoryAllocationProvider.TearDownMemoryAllocated;
if (LSetUpMemoryAllocated + LTestMemoryAllocated + LTearDownMemoryAllocated = 0) then
Exit(True);
if memoryAllocationProvider.QueryInterface(IMemoryLeakMonitor2, LMemoryAllocationProvider2) = 0 then
LMsg := LMemoryAllocationProvider2.GetReport;
testInfo := test as ITestInfo;
if (LTestMemoryAllocated = 0) then
begin
// The leak occurred in the setup/teardown
Result := False;
LMsg := Format(SSetupTeardownBytesLeaked, [LSetUpMemoryAllocated + LTearDownMemoryAllocated]) + LMsg;
errorResult := TDUnitXTestResult.Create(testInfo, TTestResultType.MemoryLeak, LMsg);
end
else if (LSetUpMemoryAllocated + LTearDownMemoryAllocated = 0) then
begin
// The leak occurred in the test only
Result := False;
LMsg := Format(STestBytesLeaked, [LTestMemoryAllocated]) + LMsg;
errorResult := TDUnitXTestResult.Create(testInfo, TTestResultType.MemoryLeak, LMsg);
end
else
begin
// The leak occurred in the setup/teardown/test
Result := False;
LMsg := Format(SSetupTestTeardownBytesLeaked, [LSetUpMemoryAllocated + LTestMemoryAllocated + LTearDownMemoryAllocated]) + LMsg;
errorResult := TDUnitXTestResult.Create(testInfo, TTestResultType.MemoryLeak, LMsg);
end;
end;
constructor TDUnitXTestRunner.Create;
begin
inherited;
FLoggers := TList<ITestLogger>.Create;
FFixtureClasses := TDictionary<TClass,string>.Create;
FUseRTTI := False;
FLogMessages := TStringList.Create;
MonitorEnter(TDUnitXTestRunner.FActiveRunners);
try
TDUnitXTestRunner.FActiveRunners.Add(TThread.CurrentThread.ThreadID, TWeakReference<ITestRunner>.Create(Self));
finally
MonitorExit(TDUnitXTestRunner.FActiveRunners);
end;
end;
constructor TDUnitXTestRunner.Create(const AListener: ITestLogger);
begin
Create;
if AListener <> nil then
FLoggers.Add(AListener);
end;
constructor TDUnitXTestRunner.Create(const AListeners: array of ITestLogger);
begin
Create;
FLoggers.AddRange(AListeners);
end;
function TDUnitXTestRunner.DoCreateFixture(const AInstance : TObject;const AFixtureClass: TClass; const AName: string; const ACategory : string): ITestFixture;
begin
if AInstance <> nil then
result := TDUnitXTestFixture.Create(AName,ACategory, AInstance,AInstance.ClassType.UnitName)
else
result := TDUnitXTestFixture.Create(AName, ACategory, AFixtureClass,AFixtureClass.UnitName);
end;
function TDUnitXTestRunner.CreateFixture(const AInstance : TObject;const AFixtureClass: TClass; const AName: string; const ACategory : string): ITestFixture;
begin
Result := DoCreateFixture(AInstance, AFixtureClass, AName, ACategory);
FFixtureList.Add(Result);
end;
function TDUnitXTestRunner.CurrentTestName: string;
begin
result := FCurrentTestName;
end;
destructor TDUnitXTestRunner.Destroy;
var
tId: TThreadID;
begin
MonitorEnter(TDUnitXTestRunner.FActiveRunners);
try
tId := TThread.CurrentThread.ThreadID;
if TDUnitXTestRunner.FActiveRunners.ContainsKey(tId) then
TDUnitXTestRunner.FActiveRunners.Remove(tId);
finally
MonitorExit(TDUnitXTestRunner.FActiveRunners);
end;
FLogMessages.Free;
FLoggers.Free;
FFixtureClasses.Free;
inherited;
end;
class destructor TDUnitXTestRunner.Destroy;
begin
FActiveRunners.Free;
FRttiContext.Free;
end;
procedure TDUnitXTestRunner.RecordResult(const context: ITestExecuteContext; const threadId: TThreadID; const fixtureResult : IFixtureResult; const testResult: ITestResult);
begin
case testResult.ResultType of
TTestResultType.Pass:
begin
context.RecordResult(fixtureResult,testResult);
Self.Loggers_AddSuccess(threadId, testResult);
end;
TTestResultType.Failure:
begin
Log(TLogLevel.Error, STestFailed + testResult.Test.Name + ' : ' + testResult.Message);
context.RecordResult(fixtureResult, testResult);
Self.Loggers_AddFailure(threadId, ITestError(testResult));
end;
TTestResultType.Error:
begin
Log(TLogLevel.Error, STestError + testResult.Test.Name + ' : ' + testResult.Message);
context.RecordResult(fixtureResult, testResult);
Self.Loggers_AddError(threadId, ITestError(testResult));
end;
TTestResultType.Ignored :
begin
Log(TLogLevel.Error, STestIgnored + testResult.Test.Name + ' : ' + testResult.Message);
context.RecordResult(fixtureResult,testResult);
Self.Loggers_AddIgnored(threadId, testResult);
end;
TTestResultType.MemoryLeak :
begin
Log(TLogLevel.Error, STestLeaked + testResult.Test.Name + ' : ' + testResult.Message);
context.RecordResult(fixtureResult,testResult);
Self.Loggers_AddMemoryLeak(threadId, testResult);
end;
end;
end;
procedure TDUnitXTestRunner.RTTIDiscoverFixtureClasses;
var
types : TArray<TRttiType>;
rType : TRttiType;
attributes : TArray<TCustomAttribute>;
attribute : TCustomAttribute;
sName : string;
begin
types := FRttiContext.GetTypes;
for rType in types do
begin
//try and keep the iteration down as much as possible
if (rType.TypeKind = TTypeKind.tkClass) and (not rType.InheritsFrom(TPersistent)) then
begin
attributes := rType.GetAttributes;
if Length(attributes) > 0 then
for attribute in attributes do
begin
if attribute.ClassType = TestFixtureAttribute then
begin
sName := TestFixtureAttribute(attribute).Name;
if sName = '' then
sName := TRttiInstanceType(rType).MetaclassType.ClassName;
if not FFixtureClasses.ContainsKey(TRttiInstanceType(rType).MetaclassType) then
FFixtureClasses.Add(TRttiInstanceType(rType).MetaclassType,sName);
end;
end;
end;
end;
end;
procedure TDUnitXTestRunner.Loggers_EndSetupFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnEndSetupFixture(threadId,fixture);
end;
procedure TDUnitXTestRunner.Loggers_EndSetupTest(const threadId: TThreadID; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
try
logger.OnEndSetupTest(threadid,Test);
except
//Hmmmm what to do with errors here. This kinda smells.
on e : Exception do
begin
try
logger.OnLog(TLogLevel.Error, SOnEndSetupEventError + e.Message);
except
on e : Exception do
System.Write(SOnEndSetupTestLogError + e.Message);
end;
end;
end;
end;
end;
procedure TDUnitXTestRunner.Loggers_EndTearDownFixture(const aThreadId: TThreadID; const aFixture: ITestFixtureInfo);
var
lLogger: ITestLogger;
begin
for lLogger in FLoggers do
lLogger.OnEndTearDownFixture(aThreadId, aFixture);
end;
procedure TDUnitXTestRunner.Loggers_EndTeardownTest(const aThreadId: TThreadID; const aTest: ITestInfo);
var
lLogger: ITestLogger;
begin
for lLogger in FLoggers do
lLogger.OnEndTeardownTest(aThreadId, aTest);
end;
procedure TDUnitXTestRunner.Loggers_EndTest(const threadId: TThreadID; const Test: ITestResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnEndTest(threadId,Test);
end;
procedure TDUnitXTestRunner.Loggers_EndTestFixture(const threadId: TThreadID; const results: IFixtureResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnEndTestFixture(threadId,results);
end;
end;
procedure TDUnitXTestRunner.Loggers_ExecuteTest(const threadId: TThreadID; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnExecuteTest(threadId, Test);
end;
procedure TDUnitXTestRunner.CountAndFilterTests(const fixtureList : ITestFixtureList; var count : Cardinal; var active : Cardinal);
var
fixture : ITestFixture;
test : ITest;
begin
for fixture in fixtureList do
begin
for test in fixture.Tests do
begin
if TDUnitX.Filter <> nil then
test.Enabled := TDUnitX.Filter.Match(test);
if test.Enabled then
begin
Inc(count);
if not test.Ignored then
Inc(active);
end;
end;
if fixture.HasChildFixtures then
CountAndFilterTests(fixture.children,count,active);
// if not (fixture.HasTests or fixture.HasChildTests) then
// fixture.Enabled := false;
end;
end;
//TODO - this needs to be thread aware so we can run tests in threads.
function TDUnitXTestRunner.Execute: IRunResults;
var
fixtureList : ITestFixtureList;
context : ITestExecuteContext;
threadId : TThreadID;
testCount : Cardinal;
testActiveCount : Cardinal;
fixtures : IInterface;
begin
result := nil;
fixtures := BuildFixtures;
fixtureList := fixtures as ITestFixtureList;
if fixtureList.Count = 0 then
raise ENoTestsRegistered.Create(SNoFixturesFound);
testCount := 0;
//TODO: Count the active tests that we have.
testActiveCount := 0;
//TODO : Filter tests here?
CountAndFilterTests(fixtureList,testCount,testActiveCount);
//TODO: Move to the fixtures class
result := TDUnitXRunResults.Create;
context := result as ITestExecuteContext;
//TODO: Record Test metrics.. runtime etc.
threadId := TThread.CurrentThread.ThreadID;
Self.Loggers_TestingStarts(threadId, testCount, testActiveCount);
try
ExecuteFixtures(nil,context, threadId, fixtureList);
context.RollupResults; //still need this for overall time.
finally
Self.Loggers_TestingEnds(result);
end;
end;
function TDUnitXTestRunner.ExecuteErrorResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const exception: Exception; const aLogMessages: TLogMessageArray) : ITestError;
var
testInfo : ITestInfo;
begin
testInfo := test as ITestInfo;
Result := TDUnitXTestError.Create(testInfo, TTestResultType.Error, exception, ExceptAddr, exception.Message, aLogMessages);
end;
class function TDUnitXTestRunner.GetActiveRunner: ITestRunner;
var
ref : IWeakReference<ITestRunner>;
begin
result := nil;
if FActiveRunners.TryGetValue(TThread.CurrentThread.ThreadId,ref) then
result := ref.Data;
end;
class function TDUnitXTestRunner.GetCurrentTestName: string;
var
runner : ITestRunner;
begin
runner := GetActiveRunner;
if runner <> nil then
result := runner.CurrentTestName;
end;
function TDUnitXTestRunner.GetFailsOnNoAsserts: boolean;
begin
Result := FFailsOnNoAsserts;
end;
function TDUnitXTestRunner.ExecuteFailureResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const exception : Exception; const aLogMessages: TLogMessageArray) : ITestError;
var
testInfo : ITestInfo;
begin
testInfo := test as ITestInfo;
//TODO: Does test failure require its own results interface and class?
Result := TDUnitXTestError.Create(testInfo, TTestResultType.Failure, exception, ExceptAddr, exception.Message, aLogMessages);
end;
procedure TDUnitXTestRunner.ExecuteFixtures(const parentFixtureResult : IFixtureResult; const context: ITestExecuteContext; const threadId: TThreadID; const fixtures: ITestFixtureList);
var
fixture: ITestFixture;
fixtureResult : IFixtureResult;
begin
for fixture in fixtures do
begin
if not fixture.Enabled then
System.continue;
if (not fixture.HasTests) and (not fixture.HasChildTests) then
System.Continue;
fixtureResult := TDUnitXFixtureResult.Create(parentFixtureResult, fixture as ITestFixtureInfo);
if parentFixtureResult = nil then
context.RecordFixture(fixtureResult);
Self.Loggers_StartTestFixture(threadId, fixture as ITestFixtureInfo);
try
//Initialize the fixture as it may have been destroyed in a previous run (when using gui runner).
if fixture.HasTests then
fixture.InitFixtureInstance;
//only run the setup method if there are actually tests
if fixture.HasActiveTests and Assigned(fixture.SetupFixtureMethod) then
ExecuteSetupFixtureMethod(context, threadId, fixture, fixtureResult);
if fixture.HasTests then
ExecuteTests(context, threadId, fixture, fixtureResult);
if fixture.HasChildFixtures then
ExecuteFixtures(fixtureResult, context, threadId, fixture.Children);
if fixture.HasActiveTests and Assigned(fixture.TearDownFixtureMethod) then
//TODO: Tricker yet each test above us requires errors that occur here
ExecuteTearDownFixtureMethod(context, threadId, fixture, fixtureResult);
//rollup durations - needs to be done here to ensure correct timing.
(fixtureResult as IFixtureResultBuilder).RollUpResults;
finally
Self.Loggers_EndTestFixture(threadId, fixtureResult);
end;
end;
end;
function TDUnitXTestRunner.ExecuteIgnoredResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const ignoreReason: string): ITestResult;
begin
result := TDUnitXTestResult.Create(test as ITestInfo, TTestResultType.Ignored, ignoreReason);
end;
procedure TDUnitXTestRunner.ExecuteSetupFixtureMethod(const context: ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const fixtureResult: IFixtureResult);
begin
try
Self.Loggers_SetupFixture(threadid, fixture as ITestFixtureInfo);
fixture.SetupFixtureMethod;
Self.Loggers_EndSetupFixture(threadid, fixture as ITestFixtureInfo);
except
on e: Exception do
begin
// Log error into each test
InvalidateTestsInFixture(fixture, context, threadId, e, fixtureResult);
Log(TLogLevel.Error, Format(SFixtureSetupError, [fixture.Name, e.Message]));
Log(TLogLevel.Error, SSkippingFixture);
end;
end;
end;
function TDUnitXTestRunner.ExecuteSuccessfulResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const aMessage: string; const aLogMessages: TLogMessageArray): ITestResult;
var
testInfo : ITestInfo;
begin
testInfo := test as ITestInfo;
Result := TDUnitXTestResult.Create(testInfo, TTestResultType.Pass, aMessage, aLogMessages);
end;
procedure TDUnitXTestRunner.ExecuteTearDownFixtureMethod(const context: ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const fixtureResult: IFixtureResult);
begin
try
Self.Loggers_TeardownFixture(threadId, fixture as ITestFixtureInfo);
fixture.ExecuteFixtureTearDown; //deals with destructors in a way that stops memory leak reporting from reporting bogus leaks.
Self.Loggers_EndTearDownFixture(threadId, fixture as ITestFixtureInfo);
except
on e: Exception do
begin
InvalidateTestsInFixture(fixture, context, threadId, e, fixtureResult);
Log(TLogLevel.Error, Format(SFixtureTeardownError, [fixture.Name, e.Message]));
end;
end;
end;
function TDUnitXTestRunner.ExecuteTest(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const memoryAllocationProvider : IMemoryLeakMonitor) : ITestResult;
var
testExecute: ITestExecute;
assertBeforeCount : Cardinal;
assertAfterCount : Cardinal;
begin
if Supports(test, ITestExecute, testExecute) then
begin
FLogMessages.Clear;
SetLength(FLogMessagesEx, 0);
FCurrentTestName := test.Name;
try
Self.Loggers_ExecuteTest(threadId, test as ITestInfo);
assertBeforeCount := 0;//to shut the compiler up;
if FFailsOnNoAsserts then
assertBeforeCount := TDUnitX.GetAssertCount(threadId);
memoryAllocationProvider.PreTest;
try
testExecute.Execute(context);
finally
memoryAllocationProvider.PostTest;
end;
if FFailsOnNoAsserts then
begin
assertAfterCount := TDUnitX.GetAssertCount(threadId);
if (assertBeforeCount = assertAfterCount) then
raise ENoAssertionsMade.Create(SNoAssertions);
end;
Result := ExecuteSuccessfulResult(context, threadId, test, FLogMessages.Text, FLogMessagesEx);
FLogMessages.Clear;
SetLength(FLogMessagesEx, 0);
finally
FCurrentTestName := '';
end;
end
else
begin
//This will be handled by the caller as a test error.
raise Exception.CreateFmt(SITestExecuteNotSupported, [test.Name]);
end;
end;
procedure TDUnitXTestRunner.ExecuteTests(const context : ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const fixtureResult : IFixtureResult);
var
tests : IEnumerable<ITest>;
test : ITest;
testResult : ITestResult;
setupResult : ITestResult;
tearDownResult : ITestResult;
memoryAllocationResult : ITestResult;
memoryAllocationProvider : IMemoryLeakMonitor;
begin
tests := fixture.Tests;
for test in tests do
begin
if not ShouldRunThisTest(test) then
System.Continue;
memoryAllocationProvider := TDUnitXIoC.DefaultContainer.Resolve<IMemoryLeakMonitor>();
//Start a fresh for this test. If we had an exception last execute of the
//setup or tear down that may have changed this execution. Therefore we try
//again to see if things have changed. Remember setup, test, tear down can
//hold state
setupResult := nil;
testResult := nil;
tearDownResult := nil;
memoryAllocationResult := nil;
Self.Loggers_BeginTest(threadId, test as ITestInfo);
//If the setup fails then we need to show this as the result.
if Assigned(fixture.SetupMethod) and (not test.Ignored) then
if not (ExecuteTestSetupMethod(context, threadId, fixture, test, setupResult, memoryAllocationProvider)) then
testResult := setupResult;
try
try
if test.Ignored then
testResult := ExecuteIgnoredResult(context,threadId,test,test.IgnoreReason)
//If we haven't already failed, then run the test.
else if testResult = nil then
testResult := ExecuteTest(context, threadId, test, memoryAllocationProvider);
except
//Handle the results which are raised in the test.
on e: ETestPass do
testResult := ExecuteSuccessfulResult(context, threadId, test, e.Message, FLogMessagesEx);
on e: ETestFailure do
testResult := ExecuteFailureResult(context, threadId, test, e, FLogMessagesEx);
on e: ETimedOut do
testResult := ExecuteTimedOutResult(context, threadId, test, e, FLogMessagesEx);
on e: Exception do
testResult := ExecuteErrorResult(context, threadId, test, e, FLogMessagesEx);
end;
//If the tear down fails then we need to show this as the test result.
if Assigned(fixture.TearDownMethod) and (not test.Ignored) then
if not (ExecuteTestTearDown(context, threadId, fixture, test, tearDownResult, memoryAllocationProvider)) then
testResult := tearDownResult;
if(testResult.ResultType = TTestResultType.Pass) then
if (not CheckMemoryAllocations(test, memoryAllocationResult, memoryAllocationProvider)) then
testResult := memoryAllocationResult;
finally
RecordResult(context, threadId, fixtureResult, testResult);
Self.Loggers_EndTest(threadId, testResult);
end;
end;
end;
function TDUnitXTestRunner.ExecuteTestSetupMethod(const context : ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const test: ITest; out errorResult: ITestResult; const memoryAllocationProvider : IMemoryLeakMonitor): boolean;
begin
Result := False;
errorResult := nil;
//Setup method is called before each test method.
if Assigned(fixture.SetupMethod) then
begin
try
Self.Loggers_SetupTest(threadId, test as ITestInfo);
memoryAllocationProvider.PreSetup;
fixture.SetupMethod;
memoryAllocationProvider.PostSetUp;
Self.Loggers_EndSetupTest(threadId, test as ITestInfo);
Result := True;
except
on e: {$IFDEF USE_NS}System.SysUtils.{$ENDIF}Exception do
begin
errorResult := ExecuteErrorResult(context, threadId, test, e, FLogMessagesEx);
end;
end;
end;
end;
function TDUnitXTestRunner.ExecuteTestTearDown(const context:
ITestExecuteContext; const threadId: TThreadID; const fixture: ITestFixture; const test: ITest; out errorResult: ITestResult; const memoryAllocationProvider : IMemoryLeakMonitor): boolean;
begin
Result := False;
errorResult := nil;
try
Self.Loggers_TeardownTest(threadId, test as ITestInfo);
memoryAllocationProvider.PreTearDown;
fixture.TearDownMethod;
memoryAllocationProvider.PostTearDown;
Self.Loggers_EndTeardownTest(threadId, test as ITestInfo);
result := true;
except
on e: {$IFDEF USE_NS}System.SysUtils.{$ENDIF}Exception do
begin
errorResult := ExecuteErrorResult(context, threadId, test, e, FLogMessagesEx);
end;
end;
end;
function TDUnitXTestRunner.ExecuteTimedOutResult(const context: ITestExecuteContext; const threadId: TThreadID; const test: ITest; const exception: Exception; const aLogMessages: TLogMessageArray): ITestError;
begin
Result := TDUnitXTestError.Create(test as ITestInfo, TTestResultType.Failure, exception, ExceptAddr, exception.Message, aLogMessages);
end;
function TDUnitXTestRunner.GetUseRTTI: Boolean;
begin
result := FUseRTTI;
end;
procedure TDUnitXTestRunner.InvalidateTestsInFixture(const aFixture: ITestFixture; const aContext: ITestExecuteContext; const aThreadId: TThreadID; const aException: Exception; const aFixtureResult: IFixtureResult);
var
lTest: ITest;
lTestResult: ITestResult;
begin
for lTest in aFixture.Tests do
begin
if not ShouldRunThisTest(lTest) then
Continue;
Self.Loggers_BeginTest(aThreadId, lTest as ITestInfo);
lTestResult := ExecuteErrorResult(aContext, aThreadId, lTest, aException, FLogMessagesEx);
RecordResult(aContext, aThreadId, aFixtureResult, lTestResult);
Self.Loggers_EndTest(aThreadId, lTestResult);
end;
end;
procedure TDUnitXTestRunner.SetFailsOnNoAsserts(const value: boolean);
begin
FFailsOnNoAsserts := value;
end;
procedure TDUnitXTestRunner.SetUseRTTI(const value: Boolean);
begin
FUseRTTI := value;
end;
procedure TDUnitXTestRunner.Status(const msg: string);
begin
Self.Log(TLogLevel.Information,msg);
end;
procedure TDUnitXTestRunner.WriteLn;
begin
Self.Log(TLogLevel.Information,'');
end;
procedure TDUnitXTestRunner.WriteLn(const msg: string);
begin
Self.Log(TLogLevel.Information,msg);
end;
procedure TDUnitXTestRunner.Loggers_SetupFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnSetupFixture(threadId,fixture);
end;
procedure TDUnitXTestRunner.Loggers_SetupTest(const threadId: TThreadID; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnSetupTest(threadId,Test);
end;
procedure TDUnitXTestRunner.Loggers_BeginTest(const threadId: TThreadID; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnBeginTest(threadId, Test);
end;
procedure TDUnitXTestRunner.Loggers_StartTestFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnStartTestFixture(threadId, fixture);
end;
procedure TDUnitXTestRunner.Loggers_TeardownFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnTearDownFixture(threadId, fixture);
end;
procedure TDUnitXTestRunner.Loggers_TeardownTest(const threadId: TThreadID; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnTeardownTest(threadId, Test);
end;
procedure TDUnitXTestRunner.Loggers_TestingEnds(const RunResults: IRunResults);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnTestingEnds(RunResults);
end;
procedure TDUnitXTestRunner.Loggers_TestingStarts(const threadId: TThreadID; testCount, testActiveCount: Cardinal);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnTestingStarts(threadId, testCount, testActiveCount);
end;
procedure TDUnitXTestRunner.Log(const logType: TLogLevel; const msg: string);
var
logger : ITestLogger;
NewIdx: integer;
begin
if logType >= TDUnitX.Options.LogLevel then
begin
//TODO : Need to get this to the current test result.
FLogMessages.Add(msg);
NewIdx := Length(FLogMessagesEx);
SetLength(FLogMessagesEx, NewIdx + 1);
FLogMessagesEx[NewIdx].Level := logType;
FLogMessagesEx[NewIdx].Msg := msg;
for logger in FLoggers do
logger.OnLog(logType, msg);
end;
end;
function TDUnitXTestRunner.ShouldRunThisTest(const test: ITest): boolean;
begin
Result := True;
if not test.Enabled then
Result := False;
if test.Ignored and TDUnitX.Options.DontShowIgnored then
Result := False;
end;
end.
|
(*
Copyright (c) 2011-2013, Stefan Glienke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of this library nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
unit DSharp.Logging;
interface
uses
Classes,
Generics.Collections,
Rtti,
SysUtils,
TypInfo;
type
TLogKind = (
lkEnterMethod,
lkLeaveMethod,
lkMessage,
lkWarning,
lkError,
lkException,
lkValue);
TLogEntry = record
private
FLogKind: TLogKind;
FText: string;
FValues: TArray<TValue>;
function GetValue: TValue;
public
constructor Create(const AText: string; const AValues: array of TValue;
const ALogKind: TLogKind);
property LogKind: TLogKind read FLogKind;
property Text: string read FText;
property Values: TArray<TValue> read FValues;
property Value: TValue read GetValue;
end;
ILog = interface
['{23190A44-748D-457D-A6BF-DBD739AE325B}']
procedure LogEntry(const ALogEntry: TLogEntry);
procedure EnterMethod(const AName: string); overload;
procedure EnterMethod(AValue: TValue; const AName: string); overload;
procedure LeaveMethod(const AName: string); overload;
procedure LeaveMethod(AValue: TValue; const AName: string); overload;
procedure LogError(const ATitle: string); overload;
procedure LogError(const ATitle: string; const AValues: array of TValue); overload;
procedure LogException(AException: Exception = nil; const ATitle: string = '');
procedure LogMessage(const ATitle: string); overload;
procedure LogMessage(const ATitle: string; const AValues: array of TValue); overload;
procedure LogValue(const AName: string; const AValue: TValue);
procedure LogWarning(const ATitle: string); overload;
procedure LogWarning(const ATitle: string; const AValues: array of TValue); overload;
end;
TLogBase = class abstract(TInterfacedObject, ILog)
protected
procedure LogEntry(const ALogEntry: TLogEntry); virtual; abstract;
public
procedure EnterMethod(const AName: string); overload;
procedure EnterMethod(AValue: TValue; const AName: string); overload;
procedure LeaveMethod(const AName: string); overload;
procedure LeaveMethod(AValue: TValue; const AName: string); overload;
procedure LogError(const ATitle: string); overload;
procedure LogError(const ATitle: string; const AValues: array of TValue); overload;
procedure LogException(AException: Exception = nil; const ATitle: string = '');
procedure LogMessage(const ATitle: string); overload;
procedure LogMessage(const ATitle: string; const AValues: array of TValue); overload;
procedure LogValue(const AName: string; const AValue: TValue); overload;
procedure LogValue<T>(const AName: string; const AValue: T); overload;
procedure LogWarning(const ATitle: string); overload;
procedure LogWarning(const ATitle: string; const AValues: array of TValue); overload;
end;
TTextLog = class abstract(TLogBase)
protected
procedure LogEntry(const ALogEntry: TLogEntry); override;
procedure WriteLine(const Text: string); virtual; abstract;
end;
TStringsLog = class(TTextLog)
private
FStrings: TStrings;
protected
procedure WriteLine(const Text: string); override;
public
constructor Create(AStrings: TStrings);
end;
LogManager = record
private
class var
FGetLog: TFunc<PTypeInfo, ILog>;
FNullLog: ILog;
public
class constructor Create;
class property GetLog: TFunc<PTypeInfo, ILog> read FGetLog write FGetLog;
type
TNullLog = class(TLogBase)
protected
procedure LogEntry(const ALogEntry: TLogEntry); override;
end;
end;
function Logging: ILog; overload;
function Logging(ATypeInfo: PTypeInfo): ILog; overload;
procedure RegisterLogging(ALog: ILog);
procedure UnregisterLogging(ALog: ILog);
implementation
uses
DSharp.Core.Reflection;
type
TLogProxy = class(TLogBase)
private
FLogs: TList<ILog>;
protected
procedure LogEntry(const ALogEntry: TLogEntry); override;
property Logs: TList<ILog> read FLogs;
public
constructor Create;
destructor Destroy; override;
end;
var
GLog: ILog;
resourcestring
REnterMethod = 'Enter: ';
RLeaveMethod = 'Leave: ';
function Format(const Format: string; const Args: array of TValue): string;
begin
Result := SysUtils.Format(Format, TValue.ToVarRecs(Args));
end;
function Logging: ILog;
begin
Result := Logging(nil);
end;
function Logging(ATypeInfo: PTypeInfo): ILog;
begin
if not Assigned(GLog) then
GLog := TLogProxy.Create;
Result := GLog;
end;
procedure RegisterLogging(ALog: ILog);
begin
(Logging as TLogProxy).Logs.Add(ALog);
end;
procedure UnregisterLogging(ALog: ILog);
begin
(Logging as TLogProxy).Logs.Remove(ALog);
end;
{ TLogBase }
procedure TLogBase.EnterMethod(const AName: string);
begin
LogEntry(TLogEntry.Create(AName, [], lkEnterMethod));
end;
procedure TLogBase.EnterMethod(AValue: TValue; const AName: string);
begin
LogEntry(TLogEntry.Create(AName, [AValue], lkEnterMethod));
end;
procedure TLogBase.LeaveMethod(const AName: string);
begin
LogEntry(TLogEntry.Create(AName, [], lkLeaveMethod));
end;
procedure TLogBase.LeaveMethod(AValue: TValue; const AName: string);
begin
LogEntry(TLogEntry.Create(AName, [AValue], lkLeaveMethod));
end;
procedure TLogBase.LogError(const ATitle: string);
begin
LogError(ATitle, []);
end;
procedure TLogBase.LogError(const ATitle: string;
const AValues: array of TValue);
begin
LogEntry(TLogEntry.Create(ATitle, AValues, lkError));
end;
procedure TLogBase.LogException(AException: Exception; const ATitle: string);
begin
if not Assigned(AException) then
begin
AException := ExceptObject as Exception;
end;
LogEntry(TLogEntry.Create(ATitle, [AException], lkException));
end;
procedure TLogBase.LogMessage(const ATitle: string);
begin
LogMessage(ATitle, []);
end;
procedure TLogBase.LogMessage(const ATitle: string;
const AValues: array of TValue);
begin
LogEntry(TLogEntry.Create(ATitle, AValues, lkMessage));
end;
procedure TLogBase.LogValue(const AName: string; const AValue: TValue);
begin
LogEntry(TLogEntry.Create(AName, [AValue], lkValue));
end;
procedure TLogBase.LogValue<T>(const AName: string; const AValue: T);
begin
LogEntry(TLogEntry.Create(AName, [TValue.From<T>(AValue)], lkValue));
end;
procedure TLogBase.LogWarning(const ATitle: string);
begin
LogWarning(ATitle, []);
end;
procedure TLogBase.LogWarning(const ATitle: string;
const AValues: array of TValue);
begin
LogEntry(TLogEntry.Create(ATitle, AValues, lkWarning));
end;
{ TLogProxy }
constructor TLogProxy.Create;
begin
FLogs := TList<ILog>.Create();
end;
destructor TLogProxy.Destroy;
begin
FLogs.Free();
inherited;
end;
procedure TLogProxy.LogEntry(const ALogEntry: TLogEntry);
var
LLog: ILog;
begin
for LLog in FLogs do
LLog.LogEntry(ALogEntry);
end;
{ TLogEntry }
constructor TLogEntry.Create(const AText: string;
const AValues: array of TValue; const ALogKind: TLogKind);
begin
FLogKind := ALogKind;
FText := AText;
FValues := TArrayHelper.Copy<TValue>(AValues);
end;
{ TTextLog }
procedure TTextLog.LogEntry(const ALogEntry: TLogEntry);
var
LMessage: string;
LValue: TValue;
begin
LValue := ALogEntry.Value;
case ALogEntry.LogKind of
lkEnterMethod:
begin
LMessage := REnterMethod;
if not LValue.IsEmpty then
LMessage := LMessage + UTF8ToString(LValue.TypeInfo.Name) + '.';
LMessage := LMessage + ALogEntry.Text;
end;
lkLeaveMethod:
begin
LMessage := RLeaveMethod;
if not LValue.IsEmpty then
LMessage := LMessage + UTF8ToString(LValue.TypeInfo.Name) + '.';
LMessage := LMessage + ALogEntry.Text;
end;
lkMessage:
begin
LMessage := Format('INFO: ' + ALogEntry.Text, ALogEntry.Values);
end;
lkWarning:
begin
LMessage := Format('WARN: ' + ALogEntry.Text, ALogEntry.Values);
end;
lkError:
begin
LMessage := Format('ERROR: ' + ALogEntry.Text, ALogEntry.Values);
end;
lkException:
begin
if ALogEntry.Text <> '' then
LMessage := ALogEntry.Text + ': ';
LMessage := LMessage + LValue.AsType<Exception>.ToString;
end;
lkValue:
begin
if ALogEntry.Text <> '' then
LMessage := ALogEntry.Text + ': ';
LMessage := LMessage + TValue.ToString(LValue);
end;
end;
WriteLine(LMessage);
end;
{ TStringsLog }
constructor TStringsLog.Create(AStrings: TStrings);
begin
FStrings := AStrings;
end;
procedure TStringsLog.WriteLine(const Text: string);
begin
FStrings.Add(Text);
end;
function TLogEntry.GetValue: TValue;
begin
if Length(FValues) > 0 then
Result := FValues[0];
end;
{ LogManager }
class constructor LogManager.Create;
begin
FNullLog := TNullLog.Create;
FGetLog :=
function(TypeInfo: PTypeInfo): ILog
begin
Result := FNullLog;
end;
end;
{ LogManager.TNullLog }
procedure LogManager.TNullLog.LogEntry(const ALogEntry: TLogEntry);
begin
// nothing to do
end;
end.
|
{$O-}
unit procs;
interface
uses shlobj, activex, ole2, comobj, windows, defs, inifiles, sysutils;
function BrowseForFolder(Handle: HWND; var FolderName: String; const ATitle: String): Boolean;
procedure loadsettings( fname: string; var st: settings );
procedure savesettings( fname: string; st: settings );
procedure log( fname: string; s: string );
function bufgetstr( var buf: array of byte; bfrom, bto: longword ): string;
function bufgetint( var buf: array of byte; bfrom: longword ): longword;
implementation
(* *
* Browsing in folders with a winapi call *
* *)
function BrowseCallbackProc(wnd: HWND; Msg: DWORD; lP: LPARAM; lpData: LPARAM): Integer; stdcall;
begin
if Msg=BFFM_INITIALIZED then begin
if (lpData>0) and (Length(PChar(lpData))>1) then
SendMessage(wnd, BFFM_SETSELECTION, ord(TRUE), lpData);
end;
Result:=0;
end;
function BrowseForFolder(Handle: HWND; var FolderName: String; const ATitle: String): Boolean;
const
BIF_NEWDIALOGSTYLE = $0040;
var
TempPath: array[0..MAX_PATH] of char;
DisplayName: array[0..MAX_PATH] of char;
BrowseInfo: TBrowseInfo;
ItemID: PItemIDList;
Malloc: activex.IMAlloc;
begin
FillChar(BrowseInfo, sizeof(BrowseInfo), 0);
BrowseInfo.hwndOwner := Handle;
BrowseInfo.pszDisplayName := DisplayName;
BrowseInfo.lpszTitle := PChar(ATitle);
BrowseInfo.ulFlags := BIF_RETURNONLYFSDIRS or BIF_NEWDIALOGSTYLE;
BrowseInfo.lpfn:=BrowseCallbackProc;
BrowseInfo.lParam:=Integer(PChar(FolderName));
ItemID := SHBrowseForFolder(BrowseInfo);
Result := Assigned(ItemId);
if Result then begin
Result:=SHGetPathFromIDList(ItemID, TempPath);
FolderName := TempPath;
OleCheck(SHGetMalloc(Malloc));
Malloc.Free(ItemID);
end;
end;
(* *
* Save and load settings *
* *)
procedure loadsettings( fname: string; var st: settings );
var ini: tinifile;
begin
ini := tinifile.create( fname );
st.path := ini.readstring( 'Settings', 'SavegamePath', extractfilepath( paramstr( 0 ) ) );
st.savegame := ini.readstring( 'Settings', 'CurrentSavegame', '' );
st.logfile := ini.readstring( 'Settings', 'LogFile', 'program.log' );
ini.destroy;
end;
procedure savesettings( fname: string; st: settings );
var ini: tinifile;
begin
ini := tinifile.create( fname );
ini.writestring( 'Settings', 'Savegamepath', st.path );
ini.writestring( 'Settings', 'CurrentSavegame', st.savegame );
ini.writestring( 'Settings', 'LogFile', st.logfile );
ini.destroy;
end;
(* *
* Logging *
* *)
procedure log( fname: string; s: string );
var f: textfile;
begin
assignfile( f, fname );
if fileexists( fname ) then append( f ) else rewrite( f );
writeln( f, format( '[%s] - %s', [timetostr( now ), s] ) );
closefile( f );
end;
(* *
* Get data from buffers *
* *)
function bufgetstr( var buf: array of byte; bfrom, bto: longword ): string;
var i: longword;
begin
result := '';
for i := bfrom to bto do
result := result + chr( buf[i] );
result := pchar( result );
end;
function bufgetint( var buf: array of byte; bfrom: longword ): longword;
begin
result := buf[bfrom] + buf[bfrom+1]*$100 + buf[bfrom+2]*$10000 + buf[bfrom+3]*$1000000;
end;
end.
|
{
Pitch Detection
Description:
MPM algorithm for detecting the pitch of a piece of audio.
Reference: http://www.cs.otago.ac.nz/tartini/papers/A_Smarter_Way_to_Find_Pitch.pdf
}
unit MPM;
interface
type IntArray = array of integer;
type DoubleArray = array of double;
const defaultCutoff : double = 0.97; // Ratio to the highest NSDF peak, above which estimates can be selected
function DetectNote(const buffer : DoubleArray; const sampleRate : double; out clarity : double; const cutoff : double = defaultCutoff) : integer;
function PitchToNote(const frequency : double) : integer;
function DetectPitch(const buffer : DoubleArray; const sampleRate : double; out clarity : double; const cutoff : double = defaultCutoff) : double;
implementation
const smallCutoff : double = 0.5; // Don't consider NSDF peaks of lower magnitudes
const lowerPitchCutoff : double = 80.0; // Only consider pitches above this frequency (Hz)
const tuning : double = 440; // Tuning of A4 (in Hz)
// Estimates the pitch of an audio buffer and returns the closest MIDI note
function DetectNote(const buffer : DoubleArray; const sampleRate : double; out clarity : double; const cutoff : double = defaultCutoff) : integer;
begin
DetectNote := PitchToNote(DetectPitch(buffer, sampleRate, clarity, cutoff));
end;
// Converts frequency (in Hz) to the closest MIDI note
function PitchToNote(const frequency : double) : integer;
begin
PitchToNote := Round(12 * Ln(frequency / tuning) / Ln(2)) + 57;
end;
// Estimates the pitch of an audio buffer (in Hz)
function DetectPitch(const buffer : DoubleArray; const sampleRate : double; out clarity : double; const cutoff : double = defaultCutoff) : double;
var i, tau, bufferSize, periodIndex, posCount, estimateCount : integer;
maxAmp, turningPtX, turningPtY, actualCutoff, period, pitchEstimate : double;
maxPositions : IntArray;
nsdf, periodEstimates, ampEstimates : DoubleArray;
begin
bufferSize := Length(buffer);
SetLength(nsdf, bufferSize);
SetLength(maxPositions, bufferSize);
NormalizedSquareDifference(buffer, nsdf);
SelectPeaks(nsdf, maxPositions, posCount);
SetLength(maxPositions, posCount);
SetLength(ampEstimates, posCount);
SetLength(periodEstimates, posCount);
estimateCount := 0;
maxAmp := (-1) * (MaxInt - 1);
for i := 0 to (posCount - 1) do
begin
tau := maxPositions[i];
if (nsdf[tau] > maxAmp) then
maxAmp := nsdf[tau];
if (nsdf[tau] > smallCutoff) then
begin
ParabolicInterpolation(nsdf, tau, turningPtX, turningPtY);
ampEstimates[estimateCount] := turningPtY;
periodEstimates[estimateCount] := turningPtX;
if (turningPtY > maxAmp) then
maxAmp := turningPtY;
Inc(estimateCount, 1);
end;
end;
clarity := 0;
DetectPitch := -1;
if (estimateCount > 0) then
begin
actualCutoff := cutoff * maxAmp;
periodIndex := 0;
for i := 0 to (estimateCount - 1) do
begin
if (ampEstimates[i] >= actualCutoff) then
begin
periodIndex := i;
break;
end;
end;
period := periodEstimates[periodIndex];
pitchEstimate := sampleRate / period;
if (pitchEstimate > lowerPitchCutoff) then
begin
clarity := ampEstimates[periodIndex];
DetectPitch := pitchEstimate;
end
end;
end;
procedure NormalizedSquareDifference(const buffer : DoubleArray; var nsdf : DoubleArray);
var i, tau, bufferSize : integer;
acf, divisorM : double;
begin
bufferSize := Length(buffer);
for tau := 0 to (bufferSize - 1) do
begin
acf := 0;
divisorM := 0;
for i := 0 to (bufferSize - tau - 1) do
begin
acf := acf + buffer[i] * buffer[i + tau];
divisorM := divisorM + (buffer[i] * buffer[i]) + (buffer[i + tau] * buffer[i + tau]);
end;
nsdf[tau] := 2 * (acf / divisorM);
end;
end;
procedure ParabolicInterpolation(const nsdf : DoubleArray; const tau : integer; out turningPtX, turningPtY : double);
var bottom, delta : double;
begin
bottom := nsdf[tau + 1] + nsdf[tau - 1] - (2 * nsdf[tau]);
if (bottom = 0.0) then
begin
turningPtX := tau;
turningPtY := nsdf[tau];
end
else
begin
delta := nsdf[tau - 1] - nsdf[tau + 1];
turningPtX := tau + delta / (2 * bottom);
turningPtY := nsdf[tau] - (delta * delta) / (8 * bottom);
end;
end;
procedure SelectPeaks(const nsdf : DoubleArray; var maxPositions : IntArray; out posCount : integer);
var pos, curMaxPos, nsdfSize : integer;
begin
pos := 0;
curMaxPos := 0;
posCount := 0;
nsdfSize := Length(nsdf);
while (pos < ((nsdfSize - 1) / 3)) and (nsdf[pos] > 0) do
Inc(pos, 1);
while (pos < nsdfSize - 1) and (nsdf[pos] <= 0) do
Inc(pos, 1);
if (pos = 0) then
pos := 1;
while (pos < nsdfSize - 1) do
begin
if (nsdf[pos] > nsdf[pos - 1]) and (nsdf[pos] >= nsdf[pos + 1]) then
begin
if (curMaxPos = 0) then
curMaxPos := pos
else if (nsdf[pos] > nsdf[curMaxPos]) then
curMaxPos := pos;
end;
Inc(pos, 1);
if (pos < (nsdfSize - 1)) and (nsdf[pos] <= 0) then
begin
if (curMaxPos > 0) then
begin
maxPositions[posCount] := curMaxPos;
curMaxPos := 0;
Inc(posCount, 1);
end;
while (pos < (nsdfSize - 1)) and (nsdf[pos] <= 0) do
Inc(pos, 1);
end;
end;
if (curMaxPos > 0) then
begin
maxPositions[posCount] := curMaxPos;
Inc(posCount, 1);
end;
end;
end.
|
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Abbrevia
*
* The Initial Developer of the Original Code is
* Robert Love
*
* Portions created by the Initial Developer are Copyright (C) 1997-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
unit AbFloppySpanTests;
{$I AbDefine.inc}
interface
uses
// Note: The Floppy Span tests are designed to be platform specific
Windows, Forms, Dialogs,Controls,SysUtils, Classes, TestFrameWork,abUtils,
abTestFramework, AbZipper, AbArctyp, AbUnzper{$IFDEF WINZIPTESTS},SyncObjs{$ENDIF} ;
type
TAbFloppySpanTests = class(TabTestCase)
private
protected
WinDir : String;
HandleWriteFailure1Test : Boolean;
procedure SetUp; override;
procedure TearDown; override;
//Events for HandleWriteFailure1
procedure HandleWriteFailure1ProgressEvent(Sender : TObject; Item : TAbArchiveItem; Progress : Byte; var Abort : Boolean);
//Events for CheckFreeForAV
procedure CheckFreeForAVFailureEvent(Sender : TObject; Item : TAbArchiveItem;
ProcessType : TAbProcessType; ErrorClass : TAbErrorClass; ErrorCode : Integer);
procedure CheckFreeForAVItemProgressEvent(Sender : TObject; Item : TAbArchiveItem; Progress : Byte; var Abort : Boolean);
published
procedure CreateBasicSpan;
procedure VerifyBasicSpan;
procedure CheckFreeForAV;
procedure HandleWriteProtectedMedia;
procedure HandleWriteFailure1;
{$IFDEF WINZIPTESTS}
procedure WinzipExtractTest;
{$ENDIF}
end;
implementation
uses ShellAPI;
{ TAbFloppySpanTests }
procedure TAbFloppySpanTests.SetUp;
begin
inherited;
// Get directory windows is installed to
SetLength(WinDir,MAX_PATH);
SetLength(WinDir,GetWindowsDirectory(pchar(WinDir), MAX_PATH));
WinDir := AbAddBackSlash(WinDir);
end;
procedure TAbFloppySpanTests.VerifyBasicSpan;
var
UnZip : TAbUnZipper;
mStream : TMemoryStream;
fStream : TFileStream;
I : Integer;
TestFile : string;
begin
// Create a Basic Span by zipping all .EXE Files in C:\WINDOWS\
// On My(Robert Love) Machine this takes two disks to do.
if MessageDlg('This test requires the TESTSPAN.ZIP created in the '+#13+#10+'"CreateBasicSpan" test. Please Insert Disk #1'+#13+#10+''+#13+#10+'Pressing Cancel will terminate this test.', mtInformation, [mbOK,mbCancel], 0) = mrCancel then
Fail('Test Aborted');
UnZip := TAbUnZipper.create(nil);
mStream := TMemoryStream.Create;
try
UnZip.BaseDirectory := GetTestTempDir;
CheckFileExists('A:\SPANTEST.ZIP');
UnZip.FileName := 'A:\SPANTEST.ZIP';
Check(Unzip.Count > 0,'Archive A:\SPANTEST.ZIP is empty');
For I := 0 to Unzip.Count -1 do
begin
testFile := WinDir + ExtractFileName(UnZip.Items[I].FileName);
// Make sure file exist to compare to.
CheckFileExists(TestFile);
// Extract File in Span to Memory
UnZip.ExtractToStream(UnZip.Items[I].FileName,mStream);
// Open the Existing File in Read Only Mode.
fStream := TFileStream.Create(TestFile,fmOpenRead);
try
// Make sure memory Stream of File and Actual File Match, Byte for Byte (This takes some time to complete)
CheckStreamMatch(mStream,fStream,'Test File: ' + TestFile + ' did not Match Archive');
finally
fStream.Free;
end;
mStream.SetSize(0);
end;
finally
UnZip.Free;
mStream.Free;
end;
end;
procedure TAbFloppySpanTests.CreateBasicSpan;
var
Zip : TAbZipper;
begin
// UnZips the Basic Span that was created by zipping all .EXE Files in C:\WINDOWS\
// Compares each file byte by byte to original.
if MessageDlg('Insert Disk #1 to create A:\TESTSPAN.ZIP'+#13+#10+''+#13+#10+'Pressing Cancel Abort Test', mtWarning, [mbOK,mbCancel], 0) = mrCancel then
Fail('User Aborted Test');
Zip := TAbZipper.create(nil);
try
Zip.BaseDirectory := WinDir;
Zip.FileName := 'A:\SPANTEST.ZIP';
Zip.AddFiles('*.EXE',faAnyFile);
Zip.Save;
finally
Zip.Free;
end;
end;
{$IFDEF WINZIPTESTS}
procedure TAbFloppySpanTests.WinzipExtractTest;
var
ExtractTo : String;
FileList : TStringList;
SR : TSearchRec;
I : integer;
FS1,FS2 : TFileStream;
begin
// This test will use the Winzip command line utility to determine if the
// file created in CreateBasicSpan can be extracted.
// This is a good comptability routine.
if MessageDlg('This test requires the TESTSPAN.ZIP created in the '+#13+#10+'"CreateBasicSpan" test. '+ #13#10 + 'It also requires WinZIP Command Line Utility. '+#13#10#13#10 +'Please Insert LAST Disk of span set.'+#13+#10+''+#13+#10+'Pressing Cancel will terminate this test.', mtInformation, [mbOK,mbCancel], 0) = mrCancel then
Fail('Test Aborted');
ExtractTo := TestTempDir + 'WZSpan\';
DelTree(ExtractTo);
Check(DirExists(extractTo),'DelTree() was just called it Directory should be deleted');
CreateDir(ExtractTo);
ExecuteAndWait(UnWinZip, 'A:\SPANTEST.ZIP ' + ExtractTo);
// Files have now been extracted Time to test.
FileList := TStringList.Create;
try
// Find all the files in the extact Directory
if FindFirst(ExtractTo + '*.*',faAnyFile,SR) = 0 then
begin
repeat
if not (SR.Attr = faDirectory) then
FileList.Add(SR.Name);
until FindNext(SR) <> 0;
end;
FindClose(SR);
// Make Sure Files where Extracted
Check(Filelist.Count > 0,'Unable to find any extract files');
For I := 0 to FileList.Count -1 do
begin
FS1 := TFileStream.Create(WinDir + ExtractFileName(FileList.Strings[I]),fmOpenRead);
FS2 := TFileStream.Create(ExtractTo + ExtractFileName(FileList.Strings[I]),fmOpenRead);
try
// Make sure Files Match
CheckStreamMatch(FS1,FS2,FileList.Strings[I] + 'Did not match Master File');
finally
FS1.Free;
FS2.Free;
end;
end;
finally
FileList.free;
end;
end;
{$ENDIF}
procedure TAbFloppySpanTests.TearDown;
begin
inherited;
end;
procedure TAbFloppySpanTests.CheckFreeForAV;
var
FUnZipper : TAbUnZipper;
begin
//[ 785269 ] Access violation on free
ShowMessage('Insert Floppy Disk with FTest.zip on it');
FUnZipper:=TAbUnZipper.Create(Nil);
With FUnZipper do
Try
ForceType:=True;
ArchiveType:=atZip;
BaseDirectory:= GetTestTempDir;
OnProcessItemFailure:=CheckFreeForAVFailureEvent;
// OnRequestLastDisk:=RequestLastDisk;
// OnRequestNthDisk:=RequestNthDisk;
// OnArchiveProgress:=Progress;
OnArchiveItemProgress := CheckFreeForAVItemProgressEvent;
FileName:='A:\Ftest.zip';
ExtractFiles('*.*');
Finally
Free;
end;
end;
procedure TAbFloppySpanTests.CheckFreeForAVFailureEvent(Sender: TObject;
Item: TAbArchiveItem; ProcessType: TAbProcessType;
ErrorClass: TAbErrorClass; ErrorCode: Integer);
begin
// Do Nothing
end;
procedure TAbFloppySpanTests.CheckFreeForAVItemProgressEvent(
Sender: TObject; Item: TAbArchiveItem; Progress: Byte;
var Abort: Boolean);
begin
Abort := true;
end;
procedure TAbFloppySpanTests.HandleWriteProtectedMedia;
var
Zip : TAbZipper;
begin
ExpectedException := EFCreateError;
ShowMessage('Insert Blank Write Protected Disk in to Drive A');
Zip := TAbZipper.create(nil);
try
Zip.BaseDirectory := GetTestFileDir;
Zip.FileName := 'A:\SPANTEST.ZIP';
Zip.AddFiles('MPL-1_1.txt',faAnyFile);
Zip.Save;
finally
Zip.Free;
end;
end;
procedure TAbFloppySpanTests.HandleWriteFailure1ProgressEvent(
Sender: TObject; Item: TAbArchiveItem; Progress: Byte;
var Abort: Boolean);
begin
if Progress > 50 then
ShowMessage('Take Disk out of drive to simulate failure');
end;
procedure TAbFloppySpanTests.HandleWriteFailure1;
var
Zip : TAbZipper;
begin
//[ 785249 ] ProcessItemFailure not called
ExpectedException := EFOpenError;
ShowMessage('Insert Blank Formated Disk in to Drive A');
Zip := TAbZipper.create(nil);
try
Zip.BaseDirectory := GetTestFileDir;
Zip.OnArchiveItemProgress := HandleWriteFailure1ProgressEvent;
Zip.FileName := 'A:\SPANTEST.ZIP';
Zip.AddFiles('MPL-1_1.txt',faAnyFile);
Zip.Save;
finally
Zip.Free;
end;
end;
initialization
TestFramework.RegisterTest('Abbrevia.Floppy Spanning Suite',
TAbFloppySpanTests.Suite);
end.
|
unit AlgoCals;
interface
uses FrogObj, NLO, EFieldCals, OutputCals, ReadIn, Exper, StratTypes,
MargCals, RunTypeU, RunTypeFactory;
type
TAlgoCals = class(TFrogObject)
private
mN: integer;
mRunType: TRunType;
mNLOType: TNLOType;
mRunTypeFactory: TRunTypeFactory;
function GetRunTypeEnum: TRunTypeEnum;
procedure SetRunTypeEnum(pEnum: TRunTypeEnum);
public
property N: integer read mN write mN;
property RunTypeEnum: TRunTypeEnum read GetRunTypeEnum write SetRunTypeEnum;
property RunType: TRunType read mRunType;
property NLOType: TNLOType read mNLOType write mNLOType;
function NLOClass: TNLOClass;
constructor Create;
destructor Destroy; override;
end;
implementation
uses PG, SHG, SD, THG, DFG1, DFG2, WindowMgr, Classes, SysUtils;
constructor TAlgoCals.Create;
var
initCals: TStringList;
rt, nt, i: Integer;
begin
inherited Create;
// These initial values should be kept in synch with the default
// vals programmed into the GUI. The only other way to do it is to refresh
// all the Cal objects with the GUI vals at CalsForm.Create.
//mN := 64;
//mNLOType := nlPG;
//mRunType := rtTheory;
mRunTypeFactory := TRunTypeFactory.Create;
initCals := WindowManager.LoadDefaultAlgoCals;
if initCals = nil then
begin
mN := 64;
mNLOType := nlSHG;
mRunType := mRunTypeFactory.getRunTypeForEnum(rteTheory);
Exit;
end;
mN := StrToInt(initCals.Strings[0]);
rt := StrToInt(initCals.Strings[1]);
// mRunType := rtTheory;
// for i := 0 to rt - 1 do // A way to turn an int back into an ordinal.
// mRunType := Succ(mRunType);
mRunType := mRunTypeFactory.getRunTypeForInt(rt);
nt := StrToInt(initCals.Strings[2]);
mNLOType := nlPG;
// Start with PG, then loop thru nt times to get to the "real" NLO.
for i := 0 to nt - 1 do
mNLOType := Succ(mNLOType);
initCals.Free;
end;
function TAlgoCals.NLOClass: TNLOClass;
begin
case mNLOType of
nlPG: NLOClass := TPG;
nlSHG: NLOClass := TSHG;
nlSD: NLOClass := TSD;
nlTHG: NLOCLass := TTHG;
nlDFG1: NLOClass := TDFG1;
nlDFG2: NLOClass := TDFG2;
end;
end;
destructor TAlgoCals.Destroy;
var
currentCals: TStringList;
myWinMgr: TWindowManager;
begin
// Save the current values in the Registry before exiting.
// The global variable WindowManager is controlled by the Main Form, and
// deleted on exit. The Cals form is auto-created and destructed on the way
// out, so its lifecycle is longer than MainForm. So forget about trying
// to synch it up, and let's just create one for here.
myWinMgr := TWindowManager.Create;
currentCals := TStringList.Create;
currentCals.Add(IntToStr(mN));
currentCals.Add(IntToStr(Ord(mRunType.GetEnum)));
currentCals.Add(IntToStr(Ord(mNLOType)));
myWinMgr.SaveDefaultAlgoCals(currentCals);
myWinMgr.Free;
inherited Destroy;
end;
function TAlgoCals.GetRunTypeEnum: TRunTypeEnum;
begin
GetRunTypeEnum := mRunType.GetEnum;
end;
procedure TAlgoCals.SetRunTypeEnum(pEnum: TRunTypeEnum);
begin
mRunType := mRunTypeFactory.getRunTypeForEnum(pEnum);
end;
end.
|
unit DBBKMarker;
interface
uses sysUtils,Classes,DB,ComWriUtils;
type
TDBBookMarker = class(TObject)
private
FDataset: TDataset;
FBookmark: TBookmarkStr;
FisBOF,FisEOF : boolean;
FID: integer;
protected
public
constructor Create(ADataset : TDataset; AID:integer);
procedure Init;
property Dataset : TDataset read FDataset;
procedure SavePosition;
procedure RestorePosition;
property Bookmark : TBookmarkStr read FBookmark;
function MoveBy(distance : integer): integer;
procedure First;
procedure Last;
property ID : integer read FID;
end;
TDBBookMarkers = class(TObject)
private
FList : TObjectList;
FDataset: TDataset;
protected
public
constructor Create(ADataset : TDataset);
Destructor Destroy;override;
property Dataset : TDataset read FDataset;
function GetBookMarker(var ID:integer):TDBBookMarker;
end;
implementation
uses SafeCode;
{ TDBBookMarker }
constructor TDBBookMarker.Create(ADataset: TDataset; AID:integer);
begin
CheckObject(ADataset,'Error : Dataset is nil for BookMarker.');
inherited Create;
FDataset := ADataset;
FID := AID;
FisEof := false;
FisBof := false;
end;
procedure TDBBookMarker.Init;
begin
FDataset.First;
SavePosition;
end;
procedure TDBBookMarker.First;
begin
FDataset.First;
SavePosition;
end;
procedure TDBBookMarker.Last;
begin
FDataset.Last;
SavePosition;
end;
function TDBBookMarker.MoveBy(distance: integer): integer;
begin
RestorePosition;
result := FDataset.MoveBy(distance);
SavePosition;
end;
procedure TDBBookMarker.RestorePosition;
begin
if FisBOF then
begin
FDataSet.First;
FDataSet.Prior;
end
else if FisEOF then
begin
FDataSet.last;
FDataSet.next;
end
else if (length(FBookmark)>0) and FDataSet.BookmarkValid(@FBookmark[1]) then
FDataSet.Bookmark:=FBookmark else
Init;
end;
procedure TDBBookMarker.SavePosition;
begin
FBookmark := FDataSet.Bookmark;
FisBOF:= FDataSet.BOF;
FisEOF:= FDataSet.EOF;
end;
{ TDBBookMarkers }
constructor TDBBookMarkers.Create(ADataset : TDataset);
begin
inherited Create;
FList := TObjectList.Create;
FDataset := ADataset;
end;
destructor TDBBookMarkers.Destroy;
begin
FList.free;
Inherited Destroy;
end;
function TDBBookMarkers.GetBookMarker(var ID: integer): TDBBookMarker;
begin
if (ID>=0) and (ID<FList.count) then
result := TDBBookMarker(FList[ID]) else
begin
ID := FList.count;
result := TDBBookMarker.Create(FDataset,ID);
result.Init;
FList.Add(result);
end;
end;
end.
|
UNIT B1Dhelps;
{$D-}
{$N+}
INTERFACE
USES
Graph, CUPSmupp, CUPS, CUPSgui;
TYPE
HelpScreens = (progHS,
partHS,part1aHS,part1bHS,
tryEnergyHS,examineHS,
part2HS,part2aHS,part2bHS,
part3HS,part3aHS,part3bHS);
PROCEDURE SetUpTryEnergyHS(VAR A:HelpScrType);
PROCEDURE DisplayHelpScreen(thisHS:HelpScreens);
IMPLEMENTATION
{ ------------ PROCEDURES FOR HELP SCREENS -------------- }
PROCEDURE SetUpProgHS(VAR A:HelpScrType);
BEGIN
A[1] := '';
A[2] := ' ONE DIMENSIONAL BOUND STATES ';
A[3] := '';
A[4] := ' Ian D.Johnston';
A[5] := ' University of Sydney, Australia';
A[6] := '';
A[7] := ' version 1.00 ';
A[8] := ' (c) 1995 John Wiley and Sons, Inc.';
A[9] := '';
A[10] := '';
A[11] := '';
A[12] := ' This program explores the properties of the ';
A[13] := ' bound state wave functions of an electron in';
A[14] := ' a one-dimensional potential well.';
A[15] := ' (1) It solves the Schroedinger equation for a';
A[16] := ' range of different wells.';
A[17] := ' (2) It studies properties of eigenfunctions';
A[18] := ' by calculating various overlap integrals.';
A[19] := ' (3) It shows the time development of general ';
A[20] := ' states made up of these eigenfunctions.';
A[21] := '';
A[22] := '';
A[23] := ' Press <Enter> or click the mouse to continue.';
END;
PROCEDURE SetUpPartHS(VAR A:HelpScrType);
BEGIN
A[1] := ' This program is in three different parts,';
A[2] := ' which you get to with the PARTS.. menu.';
A[3] := '';
A[4] := '';
A[5] := ' FINDING EIGENVALUES allows you to choose';
A[6] := ' one of a range of potential wells';
A[7] := ' and to find the eigenfunctions and ';
A[8] := ' eigenvalues of an electron in the well.';
A[9] := '';
A[10] := '';
A[11] := ' WAVEFUNCTION PROPERTIES allows you to study';
A[12] := ' properties of eigenfunctions found in the';
A[13] := ' first part: orthogonality, normalization';
A[14] := ' and a wide range of overlap integrals.';
A[15] := '';
A[16] := '';
A[17] := ' TIME DEVELOPMENT allows you to investigate how';
A[18] := ' a general state, made up of eigenfunctions';
A[19] := ' found in part 1, develop with time.';
A[21] := '';
A[22] := ' CAUTION!! If you choose a new potential you must';
A[23] := ' find its spectrum before going to parts 2 or 3.';
END;
PROCEDURE SetUpPart1aHS(VAR A:HelpScrType);
BEGIN
A[1] := ' PARTS.. Choose one of';
A[2] := ' PART 1: FINDING EIGENVALUES';
A[3] := ' PART 2: WAVEFUNCTION PROPERTIES ';
A[4] := ' PART 3: TIME DEVELOPMENT ';
A[5] := '';
A[6] := '';
A[7] := ' POTENTIAL.. Select a well from a number of ';
A[8] := ' standard shapes.';
A[9] := '';
A[10] := '';
A[11] := ' PARAMETERS VARY WELL PARAMETERS Input ';
A[12] := ' different values for the well.';
A[13] := '';
A[14] := ' ADD A PERTURBATION Include a small';
A[15] := ' extra term in the potential.';
A[16] := '';
A[17] := '';
A[18] := ' METHOD..TRY ENERGY (WITH MOUSE) ';
A[19] := ' TRY ENERGY (FROM KEYBOARD)';
A[20] := ' Observe solution of the wave';
A[21] := ' equation for different EB';
A[22] := '';
A[23] := '';
A[24] := ' Press <Enter> for the next screen....';
END;
PROCEDURE SetUpPart1bHS(VAR A:HelpScrType);
BEGIN
A[1] := ' METHOD..HUNT FOR ZERO Use a binary search';
A[2] := ' method to find an energy with';
A[3] := ' correct asymptotic behaviour.';
A[4] := '';
A[5] := ' EXAMINE SOLUTION Read details of the';
A[6] := ' solution from the screen using';
A[7] := ' the mouse';
A[8] := '';
A[9] := '';
A[10] := ' SPECTRUM.. FIND EIGENVALUES Automatically';
A[11] := ' find all the eigenvalues for';
A[12] := ' the well.';
A[13] := '';
A[14] := ' SEE WAVEFUNCTIONS ';
A[15] := ' SEE WFS AND PROBS Display each';
A[16] := ' of the eigenfunctions (and';
A[17] := ' probabilities) on request.';
A[18] := '';
A[19] := ' EXAMINE SOLUTION As above';
A[20] := '';
A[21] := ' SOUND Toggle between on and off.';
A[22] := '';
A[23] := '';
A[24] := ' Press <Enter> to resume';
END;
PROCEDURE SetUpTryEnergyHS(VAR A:HelpScrType);
BEGIN
A[1] := ' ';
A[2] := ' Try choosing a value for the binding energy';
A[3] := ' (either with the mouse or from the keyboard).';
A[4] := ' For each energy you choose, the program will';
A[5] := ' solve the wave equation and draw the solution';
A[6] := ' on the corresponding level of the graph.';
A[7] := ' ';
A[8] := ' Observe the behaviour of this solution at ';
A[9] := ' large values of x. In most cases it diverges';
A[10] := ' either up or down. Such solutions do not';
A[11] := ' correspond to an eigenvalue of the energy.';
A[12] := ' If however the solution seems to approach ';
A[13] := ' zero asymptotically, the energy you chose is';
A[14] := ' very close to an eigenvalue, and the solution';
A[15] := ' is very close to an eigenfunction.';
A[16] := '';
A[17] := ' In most cases the best you will be able to ';
A[18] := ' do is to find two values of energy which span';
A[19] := ' an eigenvalue. You can then use the next';
A[20] := ' menu choice (HUNT FOR ZERO) to find the exact';
A[21] := ' value of the binding energy between these two';
A[22] := ' bounds which produces an exact eigenfunction.';
A[23] := '';
A[24] := ' Press <Enter> to resume';
END;
PROCEDURE SetUpExamineHS(VAR A:HelpScrType);
BEGIN
A[1] := '';
A[2] := ' Use this facility to examine values of the wave';
A[3] := ' function for various values of x.';
A[4] := ' Note that, irrespective of where you click the';
A[5] := ' mouse (so long as it is within the graph) the';
A[6] := ' program will simply return the x co-ordinate of';
A[7] := ' the point at which you clicked, and the value ';
A[8] := ' of the wave function (plotted in pink) at that';
A[9] := ' x value. ';
A[10] := '';
A[11] := ' Obviously, you can only access this facility if';
A[12] := ' you have just calculated a wave function, either';
A[13] := ' with the HUNT FOR ZERO or SEE WAVE FUNCTIONS';
A[14] := ' options.';
A[15] := '';
A[16] := '';
A[17] := ' To return to the main menu when you are finished ';
A[18] := ' examining the function, select <F10>.';
A[19] := '';
A[20] := '';
A[21] := '';
A[22] := '';
A[23] := '';
A[24] := ' Press <Enter> to resume';
A[25] := '';
END;
PROCEDURE SetUpPart2HS(VAR A:HelpScrType);
BEGIN
A[2] := ' This part of the program will allow you to';
A[3] := ' explore the properties of real wave functions';
A[4] := ' by calculating various overlap intregrals.';
A[5] := ' ';
A[6] := ' It works with the potential well you chose in';
A[7] := ' part 1, and its set of (bound) eigenstates.';
A[8] := ' If you did not go through part 1, it will use';
A[9] := ' a square well which has 6 eigenstates.';
A[10] := ' ';
A[11] := ' It will allow you to integrate integrands of';
A[12] := ' the form:';
A[13] := ' psi1 * operator * psi2';
A[14] := ' where psi1 and psi2 are eigenfunctions of the';
A[15] := ' system, or more general states constructed ';
A[16] := ' from real linear combinations of eigenstates.';
A[17] := ' ';
A[18] := ' ';
A[19] := ' ';
A[20] := ' ';
A[21] := ' ';
A[22] := ' ';
A[23] := ' Press <Enter> for the next screen....';
END;
PROCEDURE SetUpPart2aHS(VAR A:HelpScrType);
BEGIN
A[1] := ' PARTS.. Choose one of';
A[2] := ' PART 1: FINDING EIGENVALUES';
A[3] := ' PART 2: WAVEFUNCTION PROPERTIES ';
A[4] := ' PART 3: TIME DEVELOPMENT ';
A[5] := '';
A[6] := '';
A[7] := ' PSI1.. EIGENSTATE, n = .. Choose one of the ';
A[8] := ' eigenfunctions as the first ';
A[9] := ' part of the overlap integrand.';
A[10] := ' ';
A[11] := ' GENERAL STATE Choose a real linear';
A[12] := ' combination of eigenfunctions as';
A[13] := ' the first part of the integrand.';
A[14] := '';
A[15] := '';
A[16] := ' OPERATOR.. Choose an operator to operate on';
A[17] := ' a second function to form the ';
A[18] := ' second part of the integrand.';
A[19] := ' The operators available are:';
A[20] := ' 1, X, D/DX, X^2, D^2/DX^2,';
A[21] := ' V, E, X.D/DX, D/DX.X';
A[22] := '';
A[23] := '';
A[24] := ' Press <Enter> for the next screen....';
END;
PROCEDURE SetUpPart2bHS(VAR A:HelpScrType);
BEGIN
A[1] := ' PSI2.. EIGENSTATE Choose one of the eigen-';
A[2] := ' functions to be the operand for';
A[3] := ' the second part of the integrand.';
A[4] := ' ';
A[5] := ' GENERAL STATE Choose a real linear';
A[6] := ' combination of eigenfunctions.';
A[7] := '';
A[8] := ' OTHER FUNCTION A facility is available ';
A[9] := ' to specify your own function. ';
A[9] := ' Consult manual.';
A[10] := '';
A[11] := '';
A[12] := ' INTEGRATE Calculates and displays the product';
A[13] := ' psi1 * operator * psi2';
A[14] := ' Then integrates over all x.';
A[15] := ' ';
A[16] := ' ';
A[17] := ' ';
A[18] := ' ';
A[19] := ' ';
A[20] := ' ';
A[21] := ' Press <Enter> to resume.';
END;
PROCEDURE SetUpPart3HS(VAR A:HelpScrType);
BEGIN
A[2] := ' This part of the program will allow you to';
A[3] := ' explore the time development of general state';
A[4] := ' wave functions made up of linear combinations';
A[5] := ' of eigenfunctions, by using the sinusoidal ';
A[6] := ' time variation of the individual eigenstates.';
A[7] := ' ';
A[8] := ' It works with the potential well you chose in';
A[9] := ' part 1, and its set of (bound) eigenstates.';
A[10] := ' If you did not go through part 1, it will use';
A[11] := ' a square well which has 6 eigenstates.';
A[12] := ' ';
A[13] := ' The time-varying wave function is represented';
A[14] := ' either by plotting amplitude as a function of ';
A[15] := ' x, and representing the phase by color; or by';
A[16] := ' plotting real and imaginary parts separately.';
A[17] := ' ';
A[18] := ' ';
A[19] := ' ';
A[20] := ' ';
A[21] := ' ';
A[22] := ' ';
A[23] := ' Press <Enter> for the next screen....';
END;
PROCEDURE SetUpPart3aHS(VAR A:HelpScrType);
BEGIN
A[1] := ' PARTS.. Choose one of';
A[2] := ' PART 1: FINDING EIGENVALUES';
A[3] := ' PART 2: WAVEFUNCTION PROPERTIES ';
A[4] := ' PART 3: TIME DEVELOPMENT ';
A[5] := '';
A[6] := '';
A[7] := ' WAVE FUNC.. CHOOSE A WAVE FUNCTION';
A[8] := ' Choose a linear combination of ';
A[9] := ' eigenfunctions of the well from ';
A[10] := ' part 1 to form wave function at t=0';
A[11] := ' Coefficients may be real or complex.';
A[12] := '';
A[13] := ' RUN Animate using current values of';
A[14] := ' time (t) and time step (dt).';
A[15] := ' Default values t = 0, dt = .0001';
A[16] := ' Note: the units are fs.';
A[17] := ' During animation choices are:';
A[18] := ' STOP, REVERSE, SLOWER, FASTER';
A[19] := ' RESTART, ESCAPE';
A[20] := '';
A[21] := ' BEGIN OVER Set time to 0 and step to 1.';
A[22] := ' ';
A[23] := ' ';
A[24] := ' Press <Enter> for the next screen....';
END;
PROCEDURE SetUpPart3bHS(VAR A:HelpScrType);
BEGIN
A[1] := ' MEASURE.. POSITION Calculate and display <x>';
A[2] := ' at the current value of time.';
A[3] := ' ';
A[4] := ' MOMENTUM Calculate and display <d/dx>';
A[5] := ' at the current value of time.';
A[6] := ' ';
A[7] := ' USER DEFINED A facility is available for';
A[8] := ' your own code here. Consult manual.';
A[9] := ' ';
A[10] := ' SET TIME Enter a new value of the time.';
A[11] := ' and recalculate wave function.';
A[12] := ' ';
A[13] := ' ';
A[14] := ' PLOT HOW.. Choose between';
A[15] := ' AMPLITUDE AND PHASE';
A[16] := ' REAL AND IMAGINARY';
A[17] := ' ';
A[18] := ' ';
A[19] := ' ';
A[20] := ' ';
A[21] := ' Press <Enter> to resume';
END;
PROCEDURE DisplayHelpScreen(thisHS:HelpScreens);
VAR
HS : HelpScrType;
OK : Boolean;
i : Integer;
BEGIN
FOR i:=1 TO 25 DO HS[i] := '';
OK := true;
CASE thisHS OF
progHS : SetUpProgHS(HS);
partHS : SetUpPartHS(HS);
part1aHS : SetUpPart1aHS(HS);
part1bHS : SetUpPart1bHS(HS);
tryEnergyHS : SetUpTryEnergyHS(HS);
examineHS : SetUpExamineHS(HS);
part2HS : SetUpPart2HS(HS);
part2aHS : SetUpPart2aHS(HS);
part2bHS : SetUpPart2bHS(HS);
part3HS : SetUpPart3HS(HS);
part3aHS : SetUpPart3aHS(HS);
part3bHS : SetUpPart3bHS(HS);
ELSE OK := false;
END; {case}
IF OK THEN
Help(HS);
END;
BEGIN
END.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Ported to Delphi by Michal Wojcik.
//
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the GNU General Public License version 2 or later.
{$H+}
unit RequestBuilder;
interface
uses
classes,
IniFiles,
OutputStream,
InputStream;
type
TRequestBuilder = class
private
resource : string;
method : string;
bodyParts : TList; //= TLinkedList();
headers : THashedStringList; //= THashMap();
inputs : THashedStringList; //= THashMap();
host : string;
port : Integer;
boundary : string;
isMultipart : Boolean;
bodyLength : Integer;
function isGet() : Boolean;
procedure buildBody();
procedure sendHeaders(output : TOutputStream);
procedure sendBody(output : TOutputStream);
procedure addHostHeader();
procedure addBodyPart(input : string);
procedure multipart();
class function URLEncode(const ASrc: string): string; static;
public
constructor Create; overload;
constructor Create(resource : string); overload;
destructor Destroy; override;
procedure setMethod(method : string);
procedure addHeader(key : string; value : string);
function getText() : string;
function buildRequestLine() : string;
procedure send(output : TOutputStream);
function inputString() : string;
function getBoundary() : string;
procedure addInput(key : string; value : TObject); overload;
procedure addInput(key : string; value : string); overload;
procedure addCredentials(username : string; password : string);
procedure setHostAndPort(host : string; port : Integer);
procedure addInputAsPart(name : string; content : TObject); overload;
procedure addInputAsPart(name : string; content : string); overload;
procedure addInputAsPart(name : string; input : TInputStream; size : Integer; contentType : string); overload;
end;
implementation
uses
ByteArrayInputStream,
ByteArrayOutputStream,
StringBuffer,
SysUtils,
IdCoderMIME,
IdURI,
StreamReader,
StringObject,
FitObject;
const
ENDL = #13#10;
// static final byte[] ENDL := #13#10.getBytes();
type
TInputStreamPart = class
public
input : TInputStream;
size : Integer;
contentType : string;
constructor Create(input : TInputStream; size : Integer; contentType : string);
end;
constructor TRequestBuilder.Create;
begin
Create('');
end;
constructor TRequestBuilder.Create(resource : string);
begin
method := 'GET';
bodyParts := TList.Create();
headers := THashedStringList.Create();
inputs := THashedStringList.Create();
isMultipart := false;
bodyLength := 0;
self.resource := resource;
end;
destructor TRequestBuilder.Destroy;
begin
bodyParts.Free;
headers.Free;
inputs.Free;
end;
procedure TRequestBuilder.setMethod(method : string);
begin
self.method := method;
end;
procedure TRequestBuilder.addHeader(key : string; value : string);
begin
headers.Values[key] := value;
end;
function TRequestBuilder.getText() : string;
var
output : TByteArrayOutputStream;
begin
output := TByteArrayOutputStream.Create();
send(output);
Result := output.toString();
end;
function TRequestBuilder.buildRequestLine() : string;
var
text : TStringBuffer;
inputStr : string;
begin
text := TStringBuffer.Create();
text.append(method).append(' ').append(resource);
if (isGet()) then
begin
inputStr := inputString();
if (Length(inputStr) > 0) then
text.append('?').append(inputStr);
end;
text.append(' HTTP/1.1');
Result := text.toString();
end;
function TRequestBuilder.isGet() : Boolean;
begin
Result := method = 'GET';
end;
procedure TRequestBuilder.send(output : TOutputStream);
begin
output.write(buildRequestLine() {.getBytes('UTF-8')});
output.write(ENDL);
buildBody();
sendHeaders(output);
output.write(ENDL);
sendBody(output);
end;
procedure TRequestBuilder.sendHeaders(output : TOutputStream);
var
key : string;
i : Integer;
begin
addHostHeader();
for i := 0 to headers.Count - 1 do
begin
key := headers.Names[i];
//Trim added to resolve problem that empty value is removed from list
output.write((key + ': ' + Trim(headers.Values[key])) {.getBytes('UTF-8')});
output.write(ENDL);
end;
end;
procedure TRequestBuilder.buildBody();
var
bytes : string;
i : Integer;
name : string;
value : TObject;
partBuffer : TStringBuffer;
part : TInputStreamPart;
tail : TStringBuffer;
begin
if (not isMultipart) then
begin
bytes := inputString() {.getBytes('UTF-8')};
bodyParts.add(TByteArrayInputStream.Create(bytes));
Inc(bodyLength, Length(bytes));
end
else
begin
for i := 0 to inputs.Count - 1 do
begin
name := inputs[i];
value := inputs.Objects[i];
partBuffer := TStringBuffer.Create();
partBuffer.append('--').append(getBoundary()).append(#13#10);
partBuffer.append('Content-Disposition: form-data; name="').append(name).append('"').append(#13#10);
if (value is TInputStreamPart) then
begin
part := value as TInputStreamPart;
partBuffer.append('Content-Type: ').append(part.contentType).append(#13#10);
partBuffer.append(#13#10);
addBodyPart(partBuffer.toString());
bodyParts.add(part.input);
Inc(bodyLength, part.size);
addBodyPart(#13#10);
end
else
begin
partBuffer.append('Content-Type: text/plain').append(#13#10);
partBuffer.append(#13#10);
partBuffer.append((value as TFitObject).toString);
partBuffer.append(#13#10);
addBodyPart(partBuffer.toString());
end;
end;
tail := TStringBuffer.Create();
tail.append('--').append(getBoundary()).append('--').append(#13#10);
addBodyPart(tail.toString());
end;
addHeader('Content-Length', IntToStr(bodyLength));
end;
procedure TRequestBuilder.addBodyPart(input : string);
var
bytes : string;
begin
bytes := input {.toString().getBytes('UTF-8')};
bodyParts.add(TByteArrayInputStream.Create(bytes));
Inc(bodyLength, length(bytes));
end;
procedure TRequestBuilder.sendBody(output : TOutputStream);
var
i : Integer;
input : TInputStream;
reader : TStreamReader;
bytes : string;
begin
for i := 0 to bodyParts.Count - 1 do
begin
input := TInputStream(bodyParts[i]);
reader := TStreamReader.Create(input);
while (not reader.isEof()) do
begin
bytes := reader.readBytes(1000);
output.write(bytes);
end;
reader.Free;
end;
end;
procedure TRequestBuilder.addHostHeader();
begin
if (host <> '') then
addHeader('Host', host + ':' + IntToStr(port))
else
addHeader('Host', ' '); // Needs to be a space because without that key would be removed....
end;
procedure TRequestBuilder.addInput(key : string; value : TObject);
begin
inputs.AddObject(key, value);
end;
procedure TRequestBuilder.addInput(key : string; value : string);
var
str : TStringObject;
begin
str := TStringObject.Create(value);
inputs.AddObject(key, str);
end;
class function TRequestBuilder.URLEncode(const ASrc: string): string;
var
i: Integer;
begin
Result := ''; {Do not Localize}
for i := 1 to Length(ASrc) do begin
if ASrc[i] in ['a'..'z','A'..'Z','0'..'9','.','-','*','_'] then
Result := Result + ASrc[i]
else if ASrc[i] = ' ' then
Result := Result + '+'
else
Result := Result + '%' + IntToHex(Ord(ASrc[i]), 2); {do not localize}
end;
end;
function TRequestBuilder.inputString() : string;
var
buffer : TStringBuffer;
first : Boolean;
i : Integer;
key : string;
value : TFitObject;
begin
buffer := TStringBuffer.Create();
first := true;
for i := 0 to inputs.Count - 1 do
begin
key := inputs[i];
value := (inputs.Objects[i] as TFitObject);
if (not first) then
buffer.append('&');
buffer.append(key).append('=').append(URLEncode(value.toString() {, 'UTF-8')}));
first := false;
end;
Result := buffer.toString();
end;
procedure TRequestBuilder.addCredentials(username : string; password : string);
var
rawUserpass : string;
userpass : string;
Enc : TIdEncoderMime;
begin
rawUserpass := username + ':' + password;
Enc := TIdEncoderMIME.Create(nil);
userpass := Enc.Encode(rawUserpass);
Enc.Free;
addHeader('Authorization', 'Basic ' + userpass);
end;
procedure TRequestBuilder.setHostAndPort(host : string; port : Integer);
begin
self.host := host;
self.port := port;
end;
function TRequestBuilder.getBoundary() : string;
begin
if (boundary = '') then
boundary := '----------' + IntToStr(Random(MaxInt)) + 'BoUnDaRy';
Result := boundary;
end;
procedure TRequestBuilder.addInputAsPart(name : string; content : TObject);
begin
multipart();
addInput(name, content);
end;
procedure TRequestBuilder.addInputAsPart(name : string; content : string);
begin
multipart();
addInput(name, content);
end;
procedure TRequestBuilder.addInputAsPart(name : string; input : TInputStream; size : Integer; contentType : string);
begin
addInputAsPart(name, TInputStreamPart.Create(input, size, contentType));
end;
procedure TRequestBuilder.multipart();
begin
if (not isMultipart) then
begin
isMultipart := true;
setMethod('POST');
addHeader('Content-Type', 'multipart/form-data; boundary=' + getBoundary());
end;
end;
constructor TInputStreamPart.Create(input : TInputStream; size : Integer; contentType : string);
begin
self.input := input;
self.size := size;
self.contentType := contentType;
end;
initialization
Randomize;
end.
|
unit uDivisaoTest;
interface
uses
TestFrameWork
,uDivisao;
type
TDivisaoTest = class(TTestCase)
procedure verificarDivisaoDoisNumerosPositivos();
procedure verificarDivisaoNumeroPositivoENumeroNegativo();
procedure verificarDivisaoNumeroPositivoEZero();
end;
implementation
uses
System.SysUtils, uExceptions;
procedure TDivisaoTest.verificarDivisaoDoisNumerosPositivos;
var
operacao: TDivisao;
saidaEsperada: Double;
saidaResultante: Double;
begin
// Cenário
operacao := TDivisao.Create();
saidaEsperada := 3;
saidaResultante := 0;
//Ação
try
saidaResultante := operacao.executar(12, 4);
finally
operacao.Free();
end;
//Validação
Assert(saidaEsperada = saidaResultante, 'Esperava "' + FloatToStr(saidaEsperada) + '" mas obteve "' + FloatToStr(saidaResultante) + '"');
end;
procedure TDivisaoTest.verificarDivisaoNumeroPositivoENumeroNegativo;
var
operacao: TDivisao;
saidaEsperada: Double;
saidaResultante: Double;
begin
// Cenário
operacao := TDivisao.Create();
saidaEsperada := -4;
saidaResultante := 0;
//Ação
try
saidaResultante := operacao.executar(12, -3);
finally
operacao.Free();
end;
//Validação
Assert(saidaEsperada = saidaResultante, 'Esperava "' + FloatToStr(saidaEsperada) + '" mas obteve "' + FloatToStr(saidaResultante) + '"');
end;
procedure TDivisaoTest.verificarDivisaoNumeroPositivoEZero;
var
operacao: TDivisao;
saidaEsperada: String;
saidaResultante: String;
resultado: Double;
begin
// Cenário
operacao := TDivisao.Create();
saidaEsperada := TExceptionDivisaoPorZero.ClassName;
saidaResultante := '';
//Ação
try
try
resultado := operacao.executar(4, 0);
except
on E: Exception do
begin
saidaResultante := e.ClassName;
end;
end;
finally
operacao.Free();
end;
//Validação
Assert(saidaEsperada = saidaResultante, 'Esperava "' + saidaEsperada + '" mas obteve "' + saidaResultante + '"');
end;
initialization
TestFrameWork.RegisterTest(TDivisaoTest.Suite);
end.
|
unit UtilsString;
interface
function HexToInt(Hex: AnsiString): Integer;
implementation
function HexToInt(Hex: AnsiString): Integer;
var
I: Integer;
Res: Integer;
ch: AnsiChar;
begin
Res := 0;
for I := 0 to Length(Hex) - 1 do
begin
ch := Hex[I + 1];
if (ch >= '0') and (ch <= '9') then
Res := Res * 16 + Ord(ch) - Ord('0')
else if (ch >= 'A') and (ch <= 'F') then
Res := Res * 16 + Ord(ch) - Ord('A') + 10
else if (ch >= 'a') and (ch <= 'f') then
Res := Res * 16 + Ord(ch) - Ord('a') + 10
else
begin
//raise Exception.Create('Error: not a Hex String');
end;
end;
Result := Res;
end;
end.
|
unit UGridSort;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Buttons, StdCtrls, Grids, Math, FastDIB, FastFX, FastSize,
FastFiles, FConvert, FastBlend, uimgbuttons;
type
TTypeMySort = (tstext, tsint, tsdate, tstime, tsnone);
TMyRadioButton = record
Name: string;
Field: string;
TypeData: TTypeMySort;
end;
TSortOneStr = class
Rt: trect;
Name: String;
Field: String;
TypeData: TTypeMySort;
Proc: integer;
select: boolean;
smouse: boolean;
constructor Create;
// (Nm, Fld : string; TpDt : TTypeMySort; Prc : integer);
procedure Draw(dib: tfastdib);
destructor destroy;
end;
TMySortList = class
rttext: trect;
rtdir: trect;
direction: boolean;
Count: integer;
List: array of TSortOneStr;
procedure clear;
procedure Add(Name, Field: string; TypeData: TTypeMySort; Proc: integer);
procedure Init(cv: tcanvas);
procedure Draw(cv: tcanvas);
function selectindex: integer;
function MouseMove(cv: tcanvas; X, Y: integer): integer;
function MouseClick(cv: tcanvas; X, Y: integer): integer;
constructor Create;
destructor destroy;
end;
TFrSortGrid = class(TForm)
Image3: TImage;
Image4: TImage;
procedure FormCreate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormDestroy(Sender: TObject);
procedure Image3MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
procedure Image3MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure Image4MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
procedure Image4MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
private
{ Private declarations }
direction: boolean;
public
{ Public declarations }
end;
var
FrSortGrid: TFrSortGrid;
// SortMyList : array[0..4] of TMyRadioButton;
mysortlist: TMySortList;
sortbuttons: TBTNSPanel;
Procedure GridSort(Grid: tstringgrid; StartRow, ACol: integer);
// procedure SortMyListClear;
implementation
uses ucommon, uInitForms, ugrid, umyfiles, uhotkeys;
{$R *.dfm}
constructor TSortOneStr.Create;
// (Nm, Fld : string; TpDt : TTypeMySort; Prc : integer);
begin
Name := '';
Field := '';
TypeData := tsnone;
Proc := 0;
select := false;
smouse := false;
Rt.Left := 0;
Rt.Top := 0;
Rt.Right := 0;
Rt.Bottom := 0;
end;
procedure TSortOneStr.Draw(dib: tfastdib);
var
wd, ht: integer;
rts, rtt: trect;
begin
dib.SetTextColor(colortorgb(FrSortGrid.Font.Color));
ht := Rt.Bottom - Rt.Top - 6;
if smouse then
begin
dib.SetBrush(bs_Solid, 0, colortorgb(smoothcolor(FrSortGrid.Color, 48)));
end
else
begin
dib.SetBrush(bs_Solid, 0, colortorgb(FrSortGrid.Color));
end;
dib.FillRect(Rt);
rts.Left := Rt.Left;
rts.Top := Rt.Top + 3;
rts.Right := Rt.Left + ht - 2;
rts.Bottom := Rt.Top + 1 + ht;
rtt.Left := Rt.Left + ht + 5;
rtt.Top := Rt.Top;
rtt.Right := Rt.Right;
rtt.Bottom := Rt.Bottom;
// wd:=trunc(ht*0.45);
// dib.SetFontEx(FrSortGrid.Font.Name,wd,ht,1,false,false,false);
dib.SetPen(ps_Solid, 1, colortorgb(FrSortGrid.Font.Color));
dib.Rectangle(Rt.Left, Rt.Top + 3, Rt.Left + ht - 2, Rt.Top + 1 + ht);
dib.SetFont(FrSortGrid.Font.Name, ht);
dib.DrawText(Name, rtt, DT_VCENTER);
if select then
dib.DrawText('X', rts, DT_CENTER);
end;
destructor TSortOneStr.destroy;
begin
freemem(@Rt.Left);
freemem(@Rt.Top);
freemem(@Rt.Right);
freemem(@Rt.Bottom);
freemem(@Name);
freemem(@Field);
freemem(@TypeData);
freemem(@Proc);
freemem(@select);
freemem(@smouse);
end;
constructor TMySortList.Create;
begin
rttext.Left := 0;
rttext.Top := 0;
rttext.Right := 0;
rttext.Bottom := 0;
rtdir.Left := 0;
rtdir.Top := 0;
rtdir.Right := 0;
rtdir.Bottom := 0;
direction := false;
Count := 0;
end;
procedure TMySortList.clear;
var
i: integer;
begin
rttext.Left := 0;
rttext.Top := 0;
rttext.Right := 0;
rttext.Bottom := 0;
rtdir.Left := 0;
rtdir.Top := 0;
rtdir.Right := 0;
rtdir.Bottom := 0;
direction := false;
for i := Count - 1 downto 0 do
begin
List[Count - 1].FreeInstance;
Count := Count - 1;
Setlength(List, Count);
end;
end;
procedure TMySortList.Add(Name, Field: string; TypeData: TTypeMySort;
Proc: integer);
begin
Count := Count + 1;
Setlength(List, Count);
List[Count - 1] := TSortOneStr.Create; // (Name,Field,TypeData,Proc);
List[Count - 1].Name := Name;
List[Count - 1].Field := Field;
List[Count - 1].TypeData := TypeData;
List[Count - 1].Proc := Proc;
end;
function TMySortList.selectindex: integer;
var
i: integer;
begin
result := -1;
for i := 0 to Count - 1 do
begin
if List[i].select then
begin
result := i;
exit;
end;
end;
end;
procedure TMySortList.Init(cv: tcanvas);
var
i, wdth, hght, hrw, ps: integer;
begin
wdth := cv.ClipRect.Right - cv.ClipRect.Left;
hght := Count * 25 + 10;
if hght - 10 > cv.ClipRect.Bottom - cv.ClipRect.Top then
hght := cv.ClipRect.Bottom - cv.ClipRect.Top;
// hght:=cv.ClipRect.Bottom - cv.ClipRect.Top;
hrw := (hght - 10) div Count;
ps := 5;
for i := 0 to Count - 1 do
begin
List[i].Rt.Left := 5;
List[i].Rt.Top := ps;
List[i].Rt.Right := wdth - 5;
List[i].Rt.Bottom := List[i].Rt.Top + hrw;
ps := List[i].Rt.Bottom;
end;
rtdir.Top := ps;
rtdir.Bottom := rtdir.Top + hrw;
rtdir.Right := wdth - 5;
rtdir.Left := rtdir.Right - (wdth div 3);
rttext.Top := ps;
rttext.Bottom := rttext.Top + hrw;
rttext.Left := 5;
rttext.Right := rtdir.Left - 5;
if Count = 1 then
List[0].select := true;
end;
procedure TMySortList.Draw(cv: tcanvas);
var
tmp: tfastdib;
i: integer;
Rt: trect;
begin
Init(cv);
tmp := tfastdib.Create;
try
tmp.SetSize(cv.ClipRect.Right - cv.ClipRect.Left,
cv.ClipRect.Bottom - cv.ClipRect.Top, 32);
tmp.clear(TColorToTfcolor(FrSortGrid.Color));
tmp.SetBrush(bs_Solid, 0, colortorgb(FrSortGrid.Color));
tmp.FillRect(Rect(0, 0, tmp.Width, tmp.Height));
tmp.SetTransparent(true);
tmp.SetPen(ps_Solid, 1, colortorgb(FrSortGrid.Font.Color));
tmp.Rectangle(1, 1, cv.ClipRect.Right - 1, cv.ClipRect.Bottom - 1);
for i := 0 to Count - 1 do
List[i].Draw(tmp);
tmp.SetTransparent(false);
tmp.DrawRect(cv.Handle, cv.ClipRect.Left, cv.ClipRect.Top,
cv.ClipRect.Right, cv.ClipRect.Bottom, 0, 0);
cv.Refresh;
finally
tmp.Free;
end;
end;
function TMySortList.MouseMove(cv: tcanvas; X, Y: integer): integer;
var
i: integer;
begin
result := -1;
for i := 0 to Count - 1 do
begin
// List[i].smouse:=false;
if (Y > List[i].Rt.Top + 5) and (Y < List[i].Rt.Bottom - 5) then
begin
List[i].smouse := true;
result := i;
exit;
end
else
List[i].smouse := false;
end;
end;
function TMySortList.MouseClick(cv: tcanvas; X, Y: integer): integer;
var
i: integer;
begin
result := -1;
for i := 0 to Count - 1 do
begin
// List[i].smouse:=false;
if (Y > List[i].Rt.Top) and (Y < List[i].Rt.Bottom) then
begin
List[i].select := not List[i].select;
result := i;
end
else
List[i].select := false;
end;
end;
destructor TMySortList.destroy;
begin
clear;
freemem(@List);
freemem(@Count);
end;
procedure execsorting(Grid: tstringgrid; StartRow, ACol: integer);
var
rw: integer;
begin
// case SortMyList[FrSortGrid.RadioGroup1.ItemIndex].TypeData of
rw := mysortlist.selectindex;
case mysortlist.List[rw].TypeData of
tstext:
begin
SortGridAlphabet(Grid, StartRow, ACol, mysortlist.List[rw].Field,
FrSortGrid.direction);
if makelogging then
WriteLog('MAIN', 'USortGrid.execsorting tstext Grid=' + Grid.Name +
' StartRow=' + inttostr(StartRow) + ' Col=' + inttostr(ACol));
end;
tstime:
begin
SortGridTime(Grid, StartRow, ACol, mysortlist.List[rw].Field,
FrSortGrid.direction);
if makelogging then
WriteLog('MAIN', 'USortGrid.execsorting tstime Grid=' + Grid.Name +
' StartRow=' + inttostr(StartRow) + ' Col=' + inttostr(ACol));
end;
tsdate:
begin
case mysortlist.List[rw].Proc of
0:
SortGridDate(Grid, StartRow, ACol, mysortlist.List[rw].Field,
FrSortGrid.direction);
1:
SortGridStartTime(Grid, FrSortGrid.direction);
end;
if makelogging then
WriteLog('MAIN', 'USortGrid.execsorting tsdate Grid=' + Grid.Name +
' StartRow=' + inttostr(StartRow) + ' Col=' + inttostr(ACol));
end;
end; // case
end;
Procedure GridSort(Grid: tstringgrid; StartRow, ACol: integer);
begin
try
sortbuttons.SetDefaultFonts;
if makelogging then
WriteLog('MAIN', 'USortGrid.GridSort Start Grid=' + Grid.Name +
' StartRow=' + inttostr(StartRow) + ' Col=' + inttostr(ACol));
mysortlist.Draw(FrSortGrid.Image3.Canvas);
FrSortGrid.ShowModal;
if FrSortGrid.ModalResult = mrok then
begin
if mysortlist.selectindex < 0 then
exit;
execsorting(Grid, StartRow, ACol);
if makelogging then
WriteLog('MAIN', 'USortGrid.GridSort Finish Grid=' + Grid.Name +
' StartRow=' + inttostr(StartRow) + ' Col=' + inttostr(ACol));
end;
except
on E: Exception do
WriteLog('MAIN', 'USortGrid.GridSort | ' + E.Message);
end;
end;
procedure TFrSortGrid.FormCreate(Sender: TObject);
var
rw, btn: integer;
begin
InitFrSortGrid;
mysortlist := TMySortList.Create;
sortbuttons := TBTNSPanel.Create;
sortbuttons.Top := 5;
sortbuttons.Bottom := 5;
sortbuttons.Left := 5;
sortbuttons.Right := 10;
sortbuttons.BackGround := FrSortGrid.Color;
sortbuttons.Interval := 5;
sortbuttons.HeightRow := 25;
rw := sortbuttons.AddRow;
btn := sortbuttons.Rows[rw].AddButton('от А к Z', imnone);
sortbuttons.Rows[rw].Btns[btn].Alignment := psCenter;
sortbuttons.Rows[rw].Btns[btn].Hint := 'Сортировать от А к Z';
// btnsctlleft.Rows[RowTemp].Btns[BtnTemp].ImagePosition:=psCenter;
sortbuttons.Rows[rw].Btns[btn].HintShow := true;
sortbuttons.Rows[rw].Btns[btn].FontHint.Size := 8;
sortbuttons.Rows[rw].Btns[btn].ColorBorder := FrSortGrid.Font.Color;
sortbuttons.Rows[rw].Btns[btn].Color := FrSortGrid.Color;
rw := sortbuttons.AddRow;
btn := sortbuttons.Rows[rw].AddButton('от Z к А', imnone);
sortbuttons.Rows[rw].Btns[btn].Alignment := psCenter;
sortbuttons.Rows[rw].Btns[btn].Hint := 'Сортировать от Z к А';
// btnsctlleft.Rows[RowTemp].Btns[BtnTemp].ImagePosition:=psCenter;
sortbuttons.Rows[rw].Btns[btn].HintShow := true;
sortbuttons.Rows[rw].Btns[btn].FontHint.Size := 8;
sortbuttons.Rows[rw].Btns[btn].ColorBorder := FrSortGrid.Font.Color;
sortbuttons.Rows[rw].Btns[btn].Color := FrSortGrid.Color;
rw := sortbuttons.AddRow;
btn := sortbuttons.Rows[rw].AddButton('Отмена', imnone);
sortbuttons.Rows[rw].Btns[btn].Alignment := psCenter;
sortbuttons.Rows[rw].Btns[btn].Hint := 'Выход без сортировки';
// btnsctlleft.Rows[RowTemp].Btns[BtnTemp].ImagePosition:=psCenter;
sortbuttons.Rows[rw].Btns[btn].HintShow := true;
sortbuttons.Rows[rw].Btns[btn].FontHint.Size := 8;
sortbuttons.Rows[rw].Btns[btn].ColorBorder := FrSortGrid.Font.Color;
sortbuttons.Rows[rw].Btns[btn].Color := FrSortGrid.Color;
sortbuttons.Draw(Image4.Canvas);
// speedbutton3.Glyph.Assign(Image1.Picture.Graphic);
direction := true;
end;
procedure TFrSortGrid.FormDestroy(Sender: TObject);
begin
mysortlist.Free;
end;
procedure TFrSortGrid.FormKeyPress(Sender: TObject; var Key: Char);
begin
// case Key of
// #13 : begin
// if makelogging then WriteLog('MAIN', 'USortGrid.TFrSortGrid.FormKeyPress Key=13 ModalResult := mrOk');
// ModalResult := mrOk;
// end;
if Key = #27 then
begin
if makelogging then
WriteLog('MAIN',
'USortGrid.TFrSortGrid.FormKeyPress Key=27 ModalResult := mrCancel');
ModalResult := mrCancel;
end;
// end;
end;
procedure TFrSortGrid.Image3MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
begin
mysortlist.MouseMove(Image3.Canvas, X, Y);
mysortlist.Draw(Image3.Canvas);
Image3.Repaint;
end;
procedure TFrSortGrid.Image3MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
begin
mysortlist.MouseClick(Image3.Canvas, X, Y);
mysortlist.Draw(Image3.Canvas);
Image3.Repaint;
end;
procedure TFrSortGrid.Image4MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
var
i: integer;
begin
for i := 0 to mysortlist.Count - 1 do
mysortlist.List[i].smouse := false;
mysortlist.Draw(Image3.Canvas);
Image3.Repaint;
sortbuttons.MouseMove(Image4.Canvas, X, Y);
// sortbuttons.Draw(Image4.Canvas);
Image4.Repaint;
end;
procedure TFrSortGrid.Image4MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
var
res: integer;
begin
res := sortbuttons.ClickButton(Image4.Canvas, X, Y);
sortbuttons.Draw(Image4.Canvas);
Image4.Repaint;
case res of
0:
begin
direction := true;
if makelogging then
WriteLog('MAIN', 'USortGrid.TFrSortGrid Direction := true');
ModalResult := mrok;
end;
1:
begin
direction := false;
if makelogging then
WriteLog('MAIN', 'USortGrid.TFrSortGrid Direction := false');
ModalResult := mrok;
end;
2:
begin
if makelogging then
WriteLog('MAIN', 'USortGrid.TFrSortGrid Cansel');
Close;
end;
end;
end;
end.
|
PROGRAM Prime(INPUT, OUTPUT);
CONST
Min = 2;
Max = 100;
TYPE
Sets = SET OF Min .. Max;
VAR
StartSet: Sets;
Next, Elem: INTEGER;
PROCEDURE Sieve(VAR Next, Elem: INTEGER; VAR StartSet: Sets);
BEGIN
Next := Min;
WHILE Next * Next < Max
DO
BEGIN
Elem := Next;
WHILE Elem <= Max
DO
BEGIN
Elem := Elem + Next;
StartSet := StartSet - [Elem]
END;
Next := Next + 1
END
END;
PROCEDURE PrintSet(VAR Elem: INTEGER; VAR StartSet: Sets);
BEGIN
Elem := Min;
WHILE Elem <> Max
DO
BEGIN
IF Elem IN StartSet
THEN
WRITE(Elem, ',');
Elem := Elem + 1
END;
WRITELN
END;
BEGIN
StartSet := [Min .. Max];
Sieve(Next, Elem, StartSet);
WRITE('Простые числа в диапазоне до ', Max, ' будут: ');
PrintSet(Elem, StartSet)
END.
|
unit fmain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
IdHL7, IdTCPConnection,idGlobal,idSync;
type
{ TForm1 }
{ TLog }
TLog = class(TIdNotify)
protected
FMsg: string;
procedure DoNotify; override;
public
class procedure LogMsg(const AMsg :string);
end;
TForm1 = class(TForm)
btnStart: TButton;
btnListen: TButton;
edtServerPort: TEdit;
edtServer: TEdit;
edtPort: TEdit;
idHl7Client: TIdHL7;
idHl7Server: TIdHL7;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
memClient: TMemo;
memClientReplyText: TMemo;
memGeneral: TMemo;
memServerReply: TMemo;
memServer: TMemo;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
Panel7: TPanel;
Panel8: TPanel;
procedure btnListenClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure FormCreate(Sender: TObject);
procedure idHl7ClientConnCountChange(ASender: TIdHL7; AConnCount: integer);
procedure idHl7ClientConnect(Sender: TObject);
procedure idHl7ClientDisconnect(Sender: TObject);
procedure idHl7ClientReceiveError(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; AException: Exception; var VReply: string; var VDropConnection: boolean);
procedure idHl7ServerConnCountChange(ASender: TIdHL7; AConnCount: integer);
procedure idHl7ServerConnect(Sender: TObject);
procedure idHl7ServerDisconnect(Sender: TObject);
procedure idHl7ServerReceiveError(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; AException: Exception; var VReply: string; var VDropConnection: boolean);
procedure Panel3Click(Sender: TObject);
protected
procedure hl7ServerReceive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; var VHandled: boolean; var VReply: string);
procedure hl7ServerMsgArrive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string);
procedure hl7clientReceive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; var VHandled: boolean; var VReply: string);
procedure logGeneral(sText : String);
private
procedure clientSend();
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TLog }
procedure TLog.DoNotify;
begin
Form1.memGeneral.Lines.Add(Fmsg);
end;
class procedure TLog.LogMsg(const AMsg :string);
begin
with TLog.Create do
try
FMsg := AMsg;
Notify;
except
Free;
raise;
end;
end;
{ TForm1 }
procedure TForm1.btnStartClick(Sender: TObject);
begin
if idHl7Client.Connected then begin
idHl7Client.Stop;
end;
idHl7Client.Port := StrToInt(edtPort.Text);
idHl7Client.Address := edtServer.Text;
clientSend;
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: boolean);
begin
if idHl7Client.Status = isConnected then begin
idHl7Client.Stop;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
idHl7Server.OnReceiveMessage := @hl7ServerReceive;
idHl7Server.OnMessageArrive := @hl7ServerMsgArrive;
idHl7Client.OnReceiveMessage:= @hl7clientReceive;
end;
procedure TForm1.idHl7ClientConnCountChange(ASender: TIdHL7; AConnCount: integer);
begin
logGeneral('clientcon_count change : ');
end;
procedure TForm1.idHl7ClientConnect(Sender: TObject);
begin
logGeneral('clientconnect : ');
end;
procedure TForm1.idHl7ClientDisconnect(Sender: TObject);
begin
logGeneral('clientdisconnect : ');
end;
procedure TForm1.idHl7ClientReceiveError(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; AException: Exception; var VReply: string; var VDropConnection: boolean);
begin
logGeneral('clientrcverr : ' + AException.Message);
VDropConnection := True;
end;
procedure TForm1.idHl7ServerConnCountChange(ASender: TIdHL7; AConnCount: integer);
begin
//Currently if evcents log to memo even in critical section it breaks the whole thread schedule system
logGeneral('servercon_count change : ');
end;
procedure TForm1.idHl7ServerConnect(Sender: TObject);
begin
logGeneral('serverconnect : ');
end;
procedure TForm1.idHl7ServerDisconnect(Sender: TObject);
begin
//Currently if evcents log to memo even in critical section it breaks the whole thread schedule system
logGeneral('serverdisconnect : ');
end;
procedure TForm1.idHl7ServerReceiveError(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; AException: Exception; var VReply: string; var VDropConnection: boolean);
begin
logGeneral('servrcverr : ' + AException.Message);
VDropConnection := True;
end;
procedure TForm1.Panel3Click(Sender: TObject);
begin
end;
procedure TForm1.hl7ServerReceive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string; var VHandled: boolean; var VReply: string);
begin
vReply := memServerReply.Lines.Text;
memServer.lines.text := Amsg;
vhandled := True;
logGeneral('servreceived '+AMsg+
'- reply provided '+vReply);
end;
procedure TForm1.hl7ServerMsgArrive(ASender: TObject; AConnection: TIdTCPConnection; AMsg: string);
begin
logGeneral('servmsgarrive : ' + AMsg);
memServer.lines.add(amsg);
idHl7Server.AsynchronousSend(memServerReply.Lines.text,AConnection);
end;
procedure TForm1.hl7clientReceive(ASender: TObject;
AConnection: TIdTCPConnection; AMsg: string; var VHandled: boolean;
var VReply: string);
begin
memClientReplyText.lines.text := Amsg;
vhandled := True;
logGeneral('clreceived '+AMsg);
end;
procedure TForm1.logGeneral(sText: String);
begin
TLog.LogMsg(sText);
end;
procedure TForm1.clientSend;
var
iX: integer;
sAnt: string;
// vR : TSendResponse;
vMsg : IInterface;
begin
if idHl7Client.Status <> isConnected then begin
idHl7Client.Start;
idHl7Client.WaitForConnection(10000);
end;
idHl7Client.SendMessage(memClient.Lines.Text);
iX := 0;
while (iX < 10) do begin
Inc(iX);
sleep(10);
Application.ProcessMessages;
(*vR*)vMsg := idHl7Client.GetMessage(sAnt);
if vMsg <> nil (*vR = srOK*) then begin
memClientReplyText.Lines.text := 'success : '+sAnt;
break
(* end else if vR = srError then begin
memClientReplyText.Lines.text := 'error : '+sAnt;
break;
end else if vR = srTimeout then begin
memClientReplyText.Lines.text := 'timeout waiting for reply ';
break;*)
end;
end;
// memClientReplyText.Lines.Text := sAnt;
end;
procedure TForm1.btnListenClick(Sender: TObject);
begin
if btnListen.Tag = 0 then begin
idHl7Server.Port := StrToInt(edtServerPort.Text);
idHl7Server.Start;
btnListen.Tag := 1;
btnListen.Caption := 'Stop';
end else begin
idHl7Server.Stop;
btnListen.Caption := 'Start';
btnListen.Tag := 0;
end;
end;
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Ported to Delphi by Michal Wojcik.
//
{$H+}
unit CellComparator;
interface
uses
StrUtils,
SysUtils,
Parse,
TypeAdapter,
Fixture;
type
TCellComparator = class
private
cell : TParse;
result : Variant;
typeAdapter : TTypeAdapter;
expected : Variant;
fixture : TFixture;
procedure compare();
function parseCell() : Variant;
procedure tryRelationalMatch();
procedure compareCellToResultInt(theFixture : TFixture; a : TTypeAdapter; theCell : TParse);
public
class procedure compareCellToResult(theFixture : TFixture; a : TTypeAdapter; theCell : TParse);
end;
implementation
uses
FitMatcherException,
FitFailureException,
CouldNotParseFitFailureException,
FitMatcher,
TypInfo,
Variants;
type
TUnparseable = class
end;
{ TCellComparator }
class procedure TCellComparator.compareCellToResult(theFixture : TFixture; a : TTypeAdapter; theCell : TParse);
var
cellComparator : TCellComparator;
begin
cellComparator := TCellComparator.Create;
try
cellComparator.compareCellToResultInt(theFixture, a, theCell);
finally
cellComparator.Free;
end;
end;
procedure TCellComparator.compareCellToResultInt(theFixture : TFixture; a : TTypeAdapter; theCell : TParse);
begin
typeAdapter := a;
cell := theCell;
fixture := theFixture;
try
result := typeAdapter.get();
expected := parseCell();
if VarIsEmpty(expected) then
begin
tryRelationalMatch();
end
else
begin
compare();
end;
except
on e : Exception do
fixture.doException(cell, e);
end;
end;
procedure TCellComparator.compare();
begin
if (typeAdapter.equals(expected, result)) then
begin
fixture.right(cell)
end
else
begin
fixture.wrong(cell, typeAdapter.toString(result));
end;
end;
function TCellComparator.parseCell() : Variant;
begin
try
result := typeAdapter.parse(cell.text());
exit;
// Ignore parse exceptions, print non-parse exceptions,
// return null so that compareCellToResult tries relational matching.
except
on e : EConvertError {NumberFormatException} do
;
on e : TParseException do
;
on e : Exception do
; //TODO e.printStackTrace();
end;
//Result := EmptyParam;
// Result := TUnparseable.Create;
end;
procedure TCellComparator.tryRelationalMatch();
var
adapterType : TTypeKind;
matcher : TFitMatcher;
cantParseException : TFitFailureException;
begin
(*
Class adapterType = typeAdapter.type;
FitFailureException cantParseException = new CouldNotParseFitFailureException(cell.text(), adapterType
.getName());
if (result != null)
{
FitMatcher matcher = new FitMatcher(cell.text(), result);
try
{
if (matcher.matches())
right(cell);
else
wrong(cell);
cell.body = matcher.message();
} catch (FitMatcherException fme)
{
exception(cell, cantParseException);
} catch (Exception e)
{
exception(cell, e);
}
} else
{
// TODO-RcM Is this always accurate?
exception(cell, cantParseException);
}
}
*)
adapterType := typeAdapter.TheType;
cantParseException := TCouldNotParseFitFailureException.Create(cell.text(), TTypeKindNames[adapterType]);
if (result <> null) then
begin
matcher := TFitMatcher.Create(cell.text(), result);
try
if (matcher.matches()) then
begin
fixture.right(cell);
end
else
begin
fixture.wrong(cell);
end;
cell.body := matcher.message();
except
on fme : TFitMatcherException do
fixture.doException(cell, cantParseException);
on e : Exception do
fixture.doException(cell, e);
end;
end
else
begin
fixture.DoException(cell, cantParseException);
end;
end;
end.
|
unit Config;
interface
uses
windows,
sysutils,
inifiles,
registry,
winsock,
NetUtils;
type
TConfig = class
private
ini: TMemIniFile;
FsectionName: string;
FOsuSongPath: string;
FPuushPath: string;
FTempPath: string;
FHost: string;
FPort: Word;
FIsWhiteIP: boolean;
FNetThread: TPingThread;
function getOsuSongPath: string;
function getPuushPath: string;
function getTemp: string;
procedure setOsuSongPath(const Value: string);
function getHost: string;
function getPort: Word;
procedure setHost(const Value: string);
procedure OnGetIP(Sender: TObject);
procedure OnPing(Sender: TObject);
procedure OnForward(Sender: TObject);
procedure setPort(const Value: Word);
function getInternalIP: string;
public
constructor Create(iniFileName: string; sectionName: string);
destructor Destroy; override;
function getValue(name: string): Variant;
procedure setValue(name: string; Value: Variant);
property OsuSongPath: string read getOsuSongPath write setOsuSongPath;
property PuushPath: string read getPuushPath;
property TempPath: string read getTemp;
property IsWhiteIP: boolean read FIsWhiteIP;
property Host: string read getHost write setHost;
property port: Word read getPort write setPort;
property InternalIP: string read getInternalIP;
end;
implementation
{ TConfig }
constructor TConfig.Create(iniFileName: string; sectionName: string);
begin
ini := TMemIniFile.Create(iniFileName);
FsectionName := sectionName;
ini.WriteString(FsectionName, 'beer', 'included');
ini.WriteString(FsectionName, 'KawaiiLevel', 'over9000');
ini.WriteString(FsectionName, 'Loli', 'on');
FOsuSongPath := ini.ReadString(FsectionName, 'OsuSongPath', '');
FHost := ini.ReadString(FsectionName, 'Host', '');
FPort := ini.ReadInteger(FsectionName, 'Port', 778);
ini.WriteString(FsectionName, 'Host', FHost);
ini.WriteInteger(FsectionName, 'Port', FPort);
FNetThread := TPingThread.Create;
FNetThread.OnGetIP := self.OnGetIP;
FNetThread.OnPing := self.OnPing;
FNetThread.OnForwardPort := self.OnForward;
FNetThread.getIP;
FNetThread.ForwardPort('osu!share', InternalIP, port);
end;
destructor TConfig.Destroy;
begin
ini.UpdateFile;
FreeAndNil(ini);
FreeAndNil(FNetThread);
TMiniUPnP.RemovePort(port);
inherited;
end;
function TConfig.getHost: string;
begin
result := FHost;
end;
function TConfig.getInternalIP: string;
type
pu_long = ^u_long;
var
varTWSAData: TWSAData;
varPHostEnt: PHostEnt;
varTInAddr: TInAddr;
namebuf: array [0 .. 255] of AnsiChar;
begin
if WSAStartup($101, varTWSAData) <> 0 then
result := ''
else
begin
gethostname(namebuf, sizeof(namebuf));
varPHostEnt := gethostbyname(namebuf);
varTInAddr.S_addr := u_long(pu_long(varPHostEnt^.h_addr_list^)^);
result := inet_ntoa(varTInAddr);
end;
WSACleanup;
end;
function TConfig.getOsuSongPath: string;
var
Reg: TRegistry;
s: string;
begin
if FOsuSongPath = '' then
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CLASSES_ROOT;
if Reg.OpenKeyReadOnly('osu\DefaultIcon') then
begin
s := Reg.ReadString('');
delete(s, 1, 1);
FOsuSongPath := ExtractFileDir(s) + '\Songs';
setValue('OsuSongPath', FOsuSongPath);
end;
finally
Reg.Free;
end;
end;
result := FOsuSongPath;
end;
function TConfig.getPuushPath: string;
var
Reg: TRegistry;
s: string;
begin
if FPuushPath = '' then
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CLASSES_ROOT;
if Reg.OpenKeyReadOnly('*\shell\puush\command') then
begin
s := Reg.ReadString('');
FPuushPath := copy(s, 1, pos(' -upload', s) - 1);
end;
finally
Reg.Free;
end;
end;
result := FPuushPath;
end;
function TConfig.getTemp: string;
var
buf: string;
len: integer;
begin
if FTempPath = '' then
begin
SetLength(buf, MAX_PATH + 1);
len := getTempPath(MAX_PATH, PChar(buf));
SetLength(buf, len);
FTempPath := buf + FsectionName;
end;
result := FTempPath;
end;
function TConfig.getPort: Word;
begin
result := FPort;
end;
function TConfig.getValue(name: string): Variant;
begin
result := ini.ReadString(FsectionName, name, '');
end;
procedure TConfig.OnForward(Sender: TObject);
begin
FNetThread.Ping(Host, port);
end;
procedure TConfig.OnGetIP(Sender: TObject);
begin
FHost := (Sender as TPingThread).IP;
end;
procedure TConfig.OnPing(Sender: TObject);
begin
FIsWhiteIP := (Sender as TPingThread).IsPingSucces;
end;
procedure TConfig.setHost(const Value: string);
begin
FHost := Value;
setValue('Host', FHost);
end;
procedure TConfig.setOsuSongPath(const Value: string);
begin
FOsuSongPath := Value;
setValue('OsuSongPath', FOsuSongPath);
end;
procedure TConfig.setPort(const Value: Word);
begin
FPort := Value;
setValue('port', FPort);
end;
procedure TConfig.setValue(name: string; Value: Variant);
begin
ini.WriteString(FsectionName, name, Value);
end;
end.
|
unit NormalLayerUnit;
{Neural Network library, by Eric C. Joyce
A normalizing layer applies the four learned parameters to its input.
m = learned mean
s = learned standard deviation
g = learned coefficient
b = learned constant
input vec(x) output vec(y)
[ x1 ] [ g*((x1 - m)/s)+b ]
[ x2 ] [ g*((x2 - m)/s)+b ]
[ x3 ] [ g*((x3 - m)/s)+b ]
[ x4 ] [ g*((x4 - m)/s)+b ]
[ x5 ] [ g*((x5 - m)/s)+b ]
Note that this file does NOT seed the randomizer. That should be done by the parent program.}
interface
{**************************************************************************************************
Constants }
const
LAYER_NAME_LEN = 32; { Length of a Layer 'name' string }
//{$DEFINE __NORMAL_DEBUG 1}
{**************************************************************************************************
Typedefs }
type
NormalLayer = record
inputs: cardinal; { Number of inputs }
m: double; { Mu: the mean learned during training }
s: double; { Sigma: the standard deviation learned during training }
g: double; { The factor learned during training }
b: double; { The constant learned during training }
layerName: array [0..LAYER_NAME_LEN - 1] of char;
out: array of double;
end;
{**************************************************************************************************
Prototypes }
procedure setM_Normal(const m: double; var layer: NormalLayer);
procedure setS_Normal(const s: double; var layer: NormalLayer);
procedure setG_Normal(const g: double; var layer: NormalLayer);
procedure setB_Normal(const b: double; var layer: NormalLayer);
procedure setName_Normal(const n: array of char; var layer: NormalLayer);
procedure print_Normal(const layer: NormalLayer);
function run_Normal(const xvec: array of double; var layer: NormalLayer): cardinal;
implementation
{**************************************************************************************************
Normalization-Layers }
procedure setM_Normal(const m: double; var layer: NormalLayer);
begin
layer.m := m;
end;
procedure setS_Normal(const s: double; var layer: NormalLayer);
begin
layer.s := s;
end;
procedure setG_Normal(const g: double; var layer: NormalLayer);
begin
layer.g := g;
end;
procedure setB_Normal(const b: double; var layer: NormalLayer);
begin
layer.b := b;
end;
procedure setName_Normal(const n: array of char; var layer: NormalLayer);
var
i: byte;
lim: byte;
begin
if length(n) < LAYER_NAME_LEN then
lim := length(n)
else
lim := LAYER_NAME_LEN;
for i := 0 to lim - 1 do
layer.layerName[i] := n[i];
layer.layerName[lim] := chr(0);
end;
procedure print_Normal(const layer: NormalLayer);
begin
{$ifdef __NORMAL_DEBUG}
writeln('print_Normal()');
{$endif}
writeln('Input Length = ', layer.inputs);
writeln('Mean = ', layer.m);
writeln('Std.dev = ', layer.s);
writeln('Coefficient = ', layer.g);
writeln('Constant = ', layer.b);
writeln('');
end;
function run_Normal(const xvec: array of double; var layer: NormalLayer): cardinal;
var
j: cardinal;
begin
for j := 0 to layer.inputs - 1 do
layer.out[j] := layer.g * ((xvec[j] - layer.m) / layer.s) + layer.b;
result := layer.inputs;
end; |
unit DialogPersonalComplete;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AncestorDialogScale, StdCtrls, Buttons, ExtCtrls,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxTextEdit,
cxCurrencyEdit, cxMaskEdit, cxButtonEdit, Vcl.Menus, dsdDB, Vcl.ActnList,
dsdAction, cxPropertiesStore, dsdAddOn, cxButtons,DB;
type
TDialogPersonalCompleteForm = class(TAncestorDialogScaleForm)
infoPanelPersona1: TPanel;
infoPanelPersona2: TPanel;
infoPanelPersona3: TPanel;
infoPanelPersona4: TPanel;
PanelPersonal1: TPanel;
PanelPersonal2: TPanel;
PanelPersonal3: TPanel;
PanelPersonal4: TPanel;
PanelPosition1: TPanel;
PanelPosition2: TPanel;
PanelPosition3: TPanel;
PanelPosition4: TPanel;
PanelPositionName1: TPanel;
PanelPositionName2: TPanel;
PanelPositionName3: TPanel;
PanelPositionName4: TPanel;
LabelPersonalName1: TLabel;
LabelPersonalName2: TLabel;
LabelPersonalName3: TLabel;
LabePersonalName4: TLabel;
LabelPositionName1: TLabel;
LabelPositionName2: TLabel;
LabelPositionName3: TLabel;
LabelPositionName4: TLabel;
gbPersonalCode2: TGroupBox;
gbPersonalCode1: TGroupBox;
gbPersonalCode3: TGroupBox;
gbPersonalCode4: TGroupBox;
gbPersonalName1: TGroupBox;
gbPersonalName2: TGroupBox;
gbPersonalName3: TGroupBox;
gbPersonalName4: TGroupBox;
gbPositionName1: TGroupBox;
gbPositionName2: TGroupBox;
gbPositionName3: TGroupBox;
gbPositionName4: TGroupBox;
EditPersonalCode1: TcxCurrencyEdit;
EditPersonalName1: TcxButtonEdit;
EditPersonalCode2: TcxCurrencyEdit;
EditPersonalCode3: TcxCurrencyEdit;
EditPersonalCode4: TcxCurrencyEdit;
EditPersonalName2: TcxButtonEdit;
EditPersonalName3: TcxButtonEdit;
EditPersonalName4: TcxButtonEdit;
infoPanelPersona5: TPanel;
PanelPosition5: TPanel;
LabelPositionName5: TLabel;
gbPositionName5: TGroupBox;
PanelPositionName5: TPanel;
PanelPersonal5: TPanel;
LabePersonalName5: TLabel;
gbPersonalCode5: TGroupBox;
EditPersonalCode5: TcxCurrencyEdit;
gbPersonalName5: TGroupBox;
EditPersonalName5: TcxButtonEdit;
infoPanelPersonaStick1: TPanel;
PanelPositionStick1: TPanel;
LabelPositionStickName1: TLabel;
gbPositionStickName1: TGroupBox;
PanelPositionStickName1: TPanel;
PanelPersonalStick1: TPanel;
LabelPersonalStickName1: TLabel;
gbPersonalStickCode1: TGroupBox;
EditPersonalStickCode1: TcxCurrencyEdit;
gbPersonalStickName1: TGroupBox;
EditPersonalStickName1: TcxButtonEdit;
procedure FormKeyDown(Sender: TObject; var Key: Word;Shift: TShiftState);
procedure EditPersonalCode1Exit(Sender: TObject);
procedure EditPersonalCode1Enter(Sender: TObject);
procedure EditPersonalCode1PropertiesChange(Sender: TObject);
procedure EditPersonalName1PropertiesButtonClick(Sender: TObject;AButtonIndex: Integer);
procedure FormCreate(Sender: TObject);
procedure EditPersonalCode1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EditPersonalName1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
fStartWrite:Boolean;
fChangePersonalCode:Boolean;
ParamsPersonalComplete_local: TParams;
function Checked: boolean; override;//Проверка корректного ввода в Edit
public
function Execute(var execParamsPersonalComplete:TParams): boolean;virtual;
end;
var
DialogPersonalCompleteForm: TDialogPersonalCompleteForm;
implementation
uses UtilScale,DMMainScale,GuidePersonal;
{$R *.dfm}
{------------------------------------------------------------------------}
function TDialogPersonalCompleteForm.Execute(var execParamsPersonalComplete:TParams): Boolean; //Проверка корректного ввода в Edit
begin
if (execParamsPersonalComplete.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)
and(execParamsPersonalComplete.ParamByName('MovementDescId').AsInteger<>zc_Movement_Loss)
and(execParamsPersonalComplete.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice)
then begin
Result:=false;
exit;
end;
//
CopyValuesParamsFrom(execParamsPersonalComplete,ParamsPersonalComplete_local);
//
fStartWrite:=true;
with ParamsPersonalComplete_local do
begin
if execParamsPersonalComplete.ParamByName('MovementDescId').AsInteger=zc_Movement_Sale
then Caption:='Изменить для Накладной № <'+execParamsPersonalComplete.ParamByName('InvNumber').AsString+'> от<'+execParamsPersonalComplete.ParamByName('OperDate').AsString+'>'+'<'+execParamsPersonalComplete.ParamByName('ToName').AsString+'>'
else Caption:='Изменить для Накладной № <'+execParamsPersonalComplete.ParamByName('InvNumber').AsString+'> от<'+execParamsPersonalComplete.ParamByName('OperDate').AsString+'>'+'<'+execParamsPersonalComplete.ParamByName('FromName').AsString+'>';
//
EditPersonalCode1.Text:=ParamByName('PersonalCode1').AsString;
EditPersonalName1.Text:=ParamByName('PersonalName1').AsString;
PanelPositionName1.Caption:=ParamByName('PositionName1').AsString;
EditPersonalCode2.Text:=ParamByName('PersonalCode2').AsString;
EditPersonalName2.Text:=ParamByName('PersonalName2').AsString;
PanelPositionName2.Caption:=ParamByName('PositionName2').AsString;
EditPersonalCode3.Text:=ParamByName('PersonalCode3').AsString;
EditPersonalName3.Text:=ParamByName('PersonalName3').AsString;
PanelPositionName3.Caption:=ParamByName('PositionName3').AsString;
EditPersonalCode4.Text:=ParamByName('PersonalCode4').AsString;
EditPersonalName4.Text:=ParamByName('PersonalName4').AsString;
PanelPositionName4.Caption:=ParamByName('PositionName4').AsString;
EditPersonalCode5.Text:=ParamByName('PersonalCode5').AsString;
EditPersonalName5.Text:=ParamByName('PersonalName5').AsString;
PanelPositionName5.Caption:=ParamByName('PositionName5').AsString;
EditPersonalStickCode1.Text:=ParamByName('PersonalCode1_Stick').AsString;
EditPersonalStickName1.Text:=ParamByName('PersonalName1_Stick').AsString;
PanelPositionStickName1.Caption:=ParamByName('PositionName1_Stick').AsString;
end;
// ...
if infoPanelPersona1.Visible = true then ActiveControl:=EditPersonalCode1
else if infoPanelPersona2.Visible = true then ActiveControl:=EditPersonalCode2
else if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self);
fStartWrite:=false;
fChangePersonalCode:=false;
result:=ShowModal=mrOk;
if result then CopyValuesParamsFrom(ParamsPersonalComplete_local,execParamsPersonalComplete);
end;
{------------------------------------------------------------------------}
function TDialogPersonalCompleteForm.Checked: boolean; //Проверка корректного ввода в Edit
var PersonalCode1:Integer;
PersonalStickCode1:Integer;
PersonalCode2:Integer;
PersonalCode3:Integer;
PersonalCode4:Integer;
PersonalCode5:Integer;
begin
Result:=false;
//
try PersonalCode1:= StrToInt(EditPersonalCode1.Text); except PersonalCode1:= 0;end;
try PersonalCode2:= StrToInt(EditPersonalCode2.Text); except PersonalCode2:= 0;end;
try PersonalCode3:= StrToInt(EditPersonalCode3.Text); except PersonalCode3:= 0;end;
try PersonalCode4:= StrToInt(EditPersonalCode4.Text); except PersonalCode4:= 0;end;
try PersonalCode5:= StrToInt(EditPersonalCode5.Text); except PersonalCode5:= 0;end;
try PersonalStickCode1:= StrToInt(EditPersonalStickCode1.Text); except PersonalStickCode1:= 0;end;
//
EditPersonalCode1Exit(EditPersonalCode1);
EditPersonalCode1Exit(EditPersonalCode2);
EditPersonalCode1Exit(EditPersonalCode3);
EditPersonalCode1Exit(EditPersonalCode4);
EditPersonalCode1Exit(EditPersonalCode5);
EditPersonalCode1Exit(EditPersonalStickCode1);
//
//
Result:=(PersonalCode1<>0)and(trim(EditPersonalName1.Text)<>'')and(ParamsPersonalComplete_local.ParamByName('PersonalId1').AsInteger<>0)
or (infoPanelPersona1.Visible = false);
if not Result then
begin
ActiveControl:=EditPersonalCode1;
ShowMessage('Введите Комплектовщик 1.');
exit;
end;
//
//
Result:=((PersonalCode2<>0)and(trim(EditPersonalName2.Text)<>'')and(ParamsPersonalComplete_local.ParamByName('PersonalId2').AsInteger<>0))
or ((PersonalCode2=0)and(trim(EditPersonalName2.Text)='')and(ParamsPersonalComplete_local.ParamByName('PersonalId2').AsInteger=0)
and(PersonalCode3=0)and(PersonalCode4=0)and(PersonalCode5=0)
)
or (infoPanelPersona2.Visible = false);
if not Result then
begin
ActiveControl:=EditPersonalCode2;
ShowMessage('Введите Комплектовщик 2.');
exit;
end;
//
//
Result:=((PersonalCode3<>0)and(trim(EditPersonalName3.Text)<>'')and(ParamsPersonalComplete_local.ParamByName('PersonalId3').AsInteger<>0))
or ((PersonalCode3=0)and(trim(EditPersonalName3.Text)='')and(ParamsPersonalComplete_local.ParamByName('PersonalId3').AsInteger=0)
and(PersonalCode4=0)and(PersonalCode5=0)
)
or (infoPanelPersona3.Visible = false);
if not Result then
begin
ActiveControl:=EditPersonalCode3;
ShowMessage('Введите Код для Комплектовщик 3.');
exit;
end;
//
//
Result:=((PersonalCode4<>0)and(trim(EditPersonalName4.Text)<>'')and(ParamsPersonalComplete_local.ParamByName('PersonalId4').AsInteger<>0))
or ((PersonalCode4=0)and(trim(EditPersonalName4.Text)='')and(ParamsPersonalComplete_local.ParamByName('PersonalId4').AsInteger=0)
and(PersonalCode5=0)
)
or (infoPanelPersona4.Visible = false);
if not Result then
begin
ActiveControl:=EditPersonalCode4;
ShowMessage('Введите Комплектовщик 4.');
exit;
end;
//
//
Result:=((PersonalCode5<>0)and(trim(EditPersonalName5.Text)<>'')and(ParamsPersonalComplete_local.ParamByName('PersonalId5').AsInteger<>0))
or ((PersonalCode5=0)and(trim(EditPersonalName5.Text)='')and(ParamsPersonalComplete_local.ParamByName('PersonalId5').AsInteger=0)
)
or (infoPanelPersona5.Visible = false);
if not Result then
begin
ActiveControl:=EditPersonalCode5;
ShowMessage('Введите Комплектовщик 5.');
exit;
end;
//
//
Result:=((PersonalStickCode1<>0)and(trim(EditPersonalStickName1.Text)<>'')and(ParamsPersonalComplete_local.ParamByName('PersonalId1_Stick').AsInteger<>0))
or ((PersonalStickCode1=0)and(trim(EditPersonalStickName1.Text)='')and(ParamsPersonalComplete_local.ParamByName('PersonalId1_Stick').AsInteger=0)
)
or (infoPanelPersonaStick1.Visible = false);
if not Result then
begin
ActiveControl:=EditPersonalStickCode1;
ShowMessage('Введите Стикеровщик 1.');
exit;
end;
//
//
end;
{------------------------------------------------------------------------------}
procedure TDialogPersonalCompleteForm.FormCreate(Sender: TObject);
begin
Create_ParamsPersonalComplete(ParamsPersonalComplete_local);
fStartWrite:=true;
//
infoPanelPersona1.Visible:= GetArrayList_Value_byName(Default_Array,'isPersonalComplete1') = AnsiUpperCase('TRUE');
infoPanelPersona2.Visible:= GetArrayList_Value_byName(Default_Array,'isPersonalComplete2') = AnsiUpperCase('TRUE');
infoPanelPersona3.Visible:= GetArrayList_Value_byName(Default_Array,'isPersonalComplete3') = AnsiUpperCase('TRUE');
infoPanelPersona4.Visible:= GetArrayList_Value_byName(Default_Array,'isPersonalComplete4') = AnsiUpperCase('TRUE');
infoPanelPersona5.Visible:= GetArrayList_Value_byName(Default_Array,'isPersonalComplete5') = AnsiUpperCase('TRUE');
infoPanelPersonaStick1.Visible:= GetArrayList_Value_byName(Default_Array,'isPersonalStick1') = AnsiUpperCase('TRUE');
end;
{------------------------------------------------------------------------------}
procedure TDialogPersonalCompleteForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key=13 then
if (ActiveControl=EditPersonalCode1)or(ActiveControl=EditPersonalName1)
then
// 2...
if infoPanelPersona2.Visible = true then ActiveControl:=EditPersonalCode2
else if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (ActiveControl=EditPersonalCode2)or(ActiveControl=EditPersonalName2)
then
// 3...
if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (ActiveControl=EditPersonalCode3)or(ActiveControl=EditPersonalName3)
then
// 4...
if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (ActiveControl=EditPersonalCode4)or(ActiveControl=EditPersonalName4)
then
// 5...
if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (ActiveControl=EditPersonalCode5)or(ActiveControl=EditPersonalName5)
then
// 1...
if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (ActiveControl=EditPersonalStickCode1)or(ActiveControl=EditPersonalStickName1)
then bbOkClick(self);
end;
{------------------------------------------------------------------------------}
procedure TDialogPersonalCompleteForm.EditPersonalCode1KeyDown(Sender: TObject;var Key: Word; Shift: TShiftState);
var Value:Integer;
begin
if Key=13 then
begin
try Value:= StrToInt((TcxCurrencyEdit(Sender).Text)); except Value:= 0; end;
//
if (TcxCurrencyEdit(Sender).Tag = 1) then
if Value = 0 then ActiveControl:=EditPersonalName1
else// 2...
if infoPanelPersona2.Visible = true then ActiveControl:=EditPersonalCode2
else if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else begin ActiveControl:=EditPersonalName1;if ActiveControl=EditPersonalName1 then bbOkClick(self);end
else if (TcxCurrencyEdit(Sender).Tag = 2) then if Value = 0 then ActiveControl:=EditPersonalName2
else // 3...
if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else begin ActiveControl:=EditPersonalName2;if ActiveControl=EditPersonalName2 then bbOkClick(self);end
else if (TcxCurrencyEdit(Sender).Tag = 3) then if Value = 0 then ActiveControl:=EditPersonalName3
else // 4...
if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else begin ActiveControl:=EditPersonalName3;if ActiveControl=EditPersonalName3 then bbOkClick(self);end
else if (TcxCurrencyEdit(Sender).Tag = 4) then if Value = 0 then ActiveControl:=EditPersonalName4
else // 5...
if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else begin ActiveControl:=EditPersonalName4;if ActiveControl=EditPersonalName4 then bbOkClick(self);end
else if (TcxCurrencyEdit(Sender).Tag = 5) then if Value = 0 then ActiveControl:=EditPersonalName5
else // 1...
if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else begin ActiveControl:=EditPersonalName5;if ActiveControl=EditPersonalName5 then bbOkClick(self);end
else if (TcxCurrencyEdit(Sender).Tag = 11) then if Value = 0 then ActiveControl:=EditPersonalStickName1 else begin ActiveControl:=EditPersonalStickName1;if ActiveControl=EditPersonalStickName1 then bbOkClick(self);end;
end;
end;
{------------------------------------------------------------------------------}
procedure TDialogPersonalCompleteForm.EditPersonalName1KeyDown(Sender: TObject;var Key: Word; Shift: TShiftState);
begin
if Key=13 then
begin
if (TcxCurrencyEdit(Sender).Tag = 1)
then // 2...
if infoPanelPersona2.Visible = true then ActiveControl:=EditPersonalCode2
else if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (TcxCurrencyEdit(Sender).Tag = 2)
then // 3...
if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (TcxCurrencyEdit(Sender).Tag = 3)
then // 4...
if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (TcxCurrencyEdit(Sender).Tag = 4)
then // 5...
if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (TcxCurrencyEdit(Sender).Tag = 5)
then // 1...
if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
else if (TcxCurrencyEdit(Sender).Tag = 11)
then bbOkClick(self);
end;
end;
{------------------------------------------------------------------------------}
procedure TDialogPersonalCompleteForm.EditPersonalCode1Enter(Sender: TObject);
begin TEdit(Sender).SelectAll;end;
{------------------------------------------------------------------------------}
procedure TDialogPersonalCompleteForm.EditPersonalCode1Exit(Sender: TObject);
var execParams:TParams;
PersonalCode:Integer;
idx,idx2:String;
begin
idx:=IntToStr(TcxButtonEdit(Sender).Tag);
//
if idx = '1' then try PersonalCode:= StrToInt(EditPersonalCode1.Text); except PersonalCode:= 0;end;
if idx = '2' then try PersonalCode:= StrToInt(EditPersonalCode2.Text); except PersonalCode:= 0;end;
if idx = '3' then try PersonalCode:= StrToInt(EditPersonalCode3.Text); except PersonalCode:= 0;end;
if idx = '4' then try PersonalCode:= StrToInt(EditPersonalCode4.Text); except PersonalCode:= 0;end;
if idx = '5' then try PersonalCode:= StrToInt(EditPersonalCode5.Text); except PersonalCode:= 0;end;
if idx = '11' then begin
try PersonalCode:= StrToInt(EditPersonalStickCode1.Text); except PersonalCode:= 0;end;
idx2:=IntToStr(TcxButtonEdit(Sender).Tag-10);
end;
//
if PersonalCode = 0 then
begin
if TcxButtonEdit(Sender).Tag < 10
then begin
ParamsPersonalComplete_local.ParamByName('PersonalId'+idx).AsInteger:=0;
ParamsPersonalComplete_local.ParamByName('PersonalCode'+idx).AsInteger:=0;
ParamsPersonalComplete_local.ParamByName('PersonalName'+idx).AsString:='';
ParamsPersonalComplete_local.ParamByName('PositionId'+idx).AsInteger:=0;
ParamsPersonalComplete_local.ParamByName('PositionCode'+idx).AsInteger:=0;
ParamsPersonalComplete_local.ParamByName('PositionName'+idx).AsString:='';
end
else begin
ParamsPersonalComplete_local.ParamByName('PersonalId'+idx2+'_Stick').AsInteger:=0;
ParamsPersonalComplete_local.ParamByName('PersonalCode'+idx2+'_Stick').AsInteger:=0;
ParamsPersonalComplete_local.ParamByName('PersonalName'+idx2+'_Stick').AsString:='';
ParamsPersonalComplete_local.ParamByName('PositionId'+idx2+'_Stick').AsInteger:=0;
ParamsPersonalComplete_local.ParamByName('PositionCode'+idx2+'_Stick').AsInteger:=0;
ParamsPersonalComplete_local.ParamByName('PositionName'+idx2+'_Stick').AsString:='';
end;
//
fStartWrite:=true;
if idx = '1' then begin EditPersonalName1.Text:=''; PanelPositionName1.Caption:=''; end;
if idx = '2' then begin EditPersonalName2.Text:=''; PanelPositionName2.Caption:=''; end;
if idx = '3' then begin EditPersonalName3.Text:=''; PanelPositionName3.Caption:=''; end;
if idx = '4' then begin EditPersonalName4.Text:=''; PanelPositionName4.Caption:=''; end;
if idx = '5' then begin EditPersonalName5.Text:=''; PanelPositionName5.Caption:=''; end;
if idx = '11' then begin EditPersonalStickName1.Text:=''; PanelPositionStickName1.Caption:=''; end;
fStartWrite:=false;
//
fChangePersonalCode:=false;
end
else if fChangePersonalCode = true then
begin
Create_ParamsPersonal(execParams,'');
//
if DMMainScaleForm.gpGet_Scale_Personal(execParams,PersonalCode) = true
then begin
if TcxButtonEdit(Sender).Tag < 10
then begin
ParamsPersonalComplete_local.ParamByName('PersonalId'+idx).AsInteger:=execParams.ParamByName('PersonalId').AsInteger;
ParamsPersonalComplete_local.ParamByName('PersonalCode'+idx).AsInteger:=execParams.ParamByName('PersonalCode').AsInteger;
ParamsPersonalComplete_local.ParamByName('PersonalName'+idx).AsString:=execParams.ParamByName('PersonalName').AsString;
ParamsPersonalComplete_local.ParamByName('PositionId'+idx).AsInteger:=execParams.ParamByName('PositionId').AsInteger;
ParamsPersonalComplete_local.ParamByName('PositionCode'+idx).AsInteger:=execParams.ParamByName('PositionCode').AsInteger;
ParamsPersonalComplete_local.ParamByName('PositionName'+idx).AsString:=execParams.ParamByName('PositionName').AsString;
end
else begin
ParamsPersonalComplete_local.ParamByName('PersonalId'+idx2+'_Stick').AsInteger:=execParams.ParamByName('PersonalId').AsInteger;
ParamsPersonalComplete_local.ParamByName('PersonalCode'+idx2+'_Stick').AsInteger:=execParams.ParamByName('PersonalCode').AsInteger;
ParamsPersonalComplete_local.ParamByName('PersonalName'+idx2+'_Stick').AsString:=execParams.ParamByName('PersonalName').AsString;
ParamsPersonalComplete_local.ParamByName('PositionId'+idx2+'_Stick').AsInteger:=execParams.ParamByName('PositionId').AsInteger;
ParamsPersonalComplete_local.ParamByName('PositionCode'+idx2+'_Stick').AsInteger:=execParams.ParamByName('PositionCode').AsInteger;
ParamsPersonalComplete_local.ParamByName('PositionName'+idx2+'_Stick').AsString:=execParams.ParamByName('PositionName').AsString;
end;
//
fStartWrite:=true;
//
if idx = '1' then
begin
EditPersonalCode1.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName1.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName1.Caption:=execParams.ParamByName('PositionName').AsString;
end;
if idx = '2' then
begin
EditPersonalCode2.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName2.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName2.Caption:=execParams.ParamByName('PositionName').AsString;
end;
if idx = '3' then
begin
EditPersonalCode3.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName3.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName3.Caption:=execParams.ParamByName('PositionName').AsString;
end;
if idx = '4' then
begin
EditPersonalCode4.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName4.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName4.Caption:=execParams.ParamByName('PositionName').AsString;
end;
if idx = '5' then
begin
EditPersonalCode5.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName5.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName5.Caption:=execParams.ParamByName('PositionName').AsString;
end;
if idx = '11' then
begin
EditPersonalStickCode1.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalStickName1.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionStickName1.Caption:=execParams.ParamByName('PositionName').AsString;
end;
//
fStartWrite:=false;
//
fChangePersonalCode:=false;
end
else begin
if execParams.ParamByName('PersonalId').AsInteger>1
then ShowMessage('Ошибка.У сотрудника с кодом <'+IntToStr(PersonalCode)+'> нельзя определить <Должность>.'+#10+#13+'Попробуйте выбрать его из <Справочника>.')
else ShowMessage('Ошибка.Не найден сотрудник с кодом <'+IntToStr(PersonalCode)+'>.');
ParamsPersonalComplete_local.ParamByName('PersonalId'+idx).AsInteger:=0;
//
fStartWrite:=true;
if idx = '1' then begin EditPersonalName1.Text:=''; PanelPositionName1.Caption:='';
// 1...
if infoPanelPersona1.Visible = true then ActiveControl:=EditPersonalCode1
else if infoPanelPersona2.Visible = true then ActiveControl:=EditPersonalCode2
else if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 //else bbOkClick(self)
end;
if idx = '2' then begin EditPersonalName2.Text:=''; PanelPositionName2.Caption:='';
// 2...
if infoPanelPersona2.Visible = true then ActiveControl:=EditPersonalCode2
else if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 //else bbOkClick(self)
end;
if idx = '3' then begin EditPersonalName3.Text:=''; PanelPositionName3.Caption:='';
// 3...
if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 //else bbOkClick(self)
end;
if idx = '4' then begin EditPersonalName4.Text:=''; PanelPositionName4.Caption:='';
// 4...
if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 //else bbOkClick(self)
end;
if idx = '5' then begin EditPersonalName5.Text:=''; PanelPositionName5.Caption:='';
// 5...
if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 //else bbOkClick(self)
end;
if idx = '11' then begin EditPersonalStickName1.Text:=''; PanelPositionStickName1.Caption:='';
// 1...
if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 //else bbOkClick(self)
end;
fStartWrite:=false;
//
end;
//
execParams.Free;
end;
//
end;
{------------------------------------------------------------------------------}
procedure TDialogPersonalCompleteForm.EditPersonalCode1PropertiesChange(Sender: TObject);
begin
if fStartWrite=false
then fChangePersonalCode:=true;
end;
{------------------------------------------------------------------------------}
procedure TDialogPersonalCompleteForm.EditPersonalName1PropertiesButtonClick(Sender: TObject; AButtonIndex: Integer);
var execParams:TParams;
idx,idx2:String;
begin
Create_ParamsPersonal(execParams,'');
//
idx:=IntToStr(TcxButtonEdit(Sender).Tag);
//
with execParams do
if TcxButtonEdit(Sender).Tag < 10
then begin
ParamByName('PersonalId').AsInteger:=ParamsPersonalComplete_local.ParamByName('PersonalId'+idx).AsInteger;
ParamByName('PersonalCode').AsInteger:=ParamsPersonalComplete_local.ParamByName('PersonalCode'+idx).AsInteger;
end
else begin
idx2:=IntToStr(TcxButtonEdit(Sender).Tag-10);
ParamByName('PersonalId').AsInteger:=ParamsPersonalComplete_local.ParamByName('PersonalId'+idx2+'_Stick').AsInteger;
ParamByName('PersonalCode').AsInteger:=ParamsPersonalComplete_local.ParamByName('PersonalCode'+idx2+'_Stick').AsInteger;
end;
//
if GuidePersonalForm.Execute(execParams)
then begin
if TcxButtonEdit(Sender).Tag < 10
then begin
ParamsPersonalComplete_local.ParamByName('PersonalId'+idx).AsInteger:=execParams.ParamByName('PersonalId').AsInteger;
ParamsPersonalComplete_local.ParamByName('PersonalCode'+idx).AsInteger:=execParams.ParamByName('PersonalCode').AsInteger;
ParamsPersonalComplete_local.ParamByName('PersonalName'+idx).AsString:=execParams.ParamByName('PersonalName').AsString;
ParamsPersonalComplete_local.ParamByName('PositionId'+idx).AsInteger:=execParams.ParamByName('PositionId').AsInteger;
ParamsPersonalComplete_local.ParamByName('PositionCode'+idx).AsInteger:=execParams.ParamByName('PositionCode').AsInteger;
ParamsPersonalComplete_local.ParamByName('PositionName'+idx).AsString:=execParams.ParamByName('PositionName').AsString;
end
else begin
ParamsPersonalComplete_local.ParamByName('PersonalId'+idx2+'_Stick').AsInteger:=execParams.ParamByName('PersonalId').AsInteger;
ParamsPersonalComplete_local.ParamByName('PersonalCode'+idx2+'_Stick').AsInteger:=execParams.ParamByName('PersonalCode').AsInteger;
ParamsPersonalComplete_local.ParamByName('PersonalName'+idx2+'_Stick').AsString:=execParams.ParamByName('PersonalName').AsString;
ParamsPersonalComplete_local.ParamByName('PositionId'+idx2+'_Stick').AsInteger:=execParams.ParamByName('PositionId').AsInteger;
ParamsPersonalComplete_local.ParamByName('PositionCode'+idx2+'_Stick').AsInteger:=execParams.ParamByName('PositionCode').AsInteger;
ParamsPersonalComplete_local.ParamByName('PositionName'+idx2+'_Stick').AsString:=execParams.ParamByName('PositionName').AsString;
end;
//
fStartWrite:=true;
//
if idx = '1' then
begin
EditPersonalCode1.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName1.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName1.Caption:=execParams.ParamByName('PositionName').AsString;
// 2...
if infoPanelPersona2.Visible = true then ActiveControl:=EditPersonalCode2
else if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
end;
if idx = '2' then
begin
EditPersonalCode2.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName2.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName2.Caption:=execParams.ParamByName('PositionName').AsString;
// 3...
if infoPanelPersona3.Visible = true then ActiveControl:=EditPersonalCode3
else if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
end;
if idx = '3' then
begin
EditPersonalCode3.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName3.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName3.Caption:=execParams.ParamByName('PositionName').AsString;
// 4...
if infoPanelPersona4.Visible = true then ActiveControl:=EditPersonalCode4
else if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
end;
if idx = '4' then
begin
EditPersonalCode4.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName4.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName4.Caption:=execParams.ParamByName('PositionName').AsString;
// 5...
if infoPanelPersona5.Visible = true then ActiveControl:=EditPersonalCode5
else if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
end;
if idx = '5' then
begin
EditPersonalCode5.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalName5.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionName5.Caption:=execParams.ParamByName('PositionName').AsString;
// 1...
if infoPanelPersonaStick1.Visible = true then ActiveControl:=EditPersonalStickCode1 else bbOkClick(self)
end;
if idx = '11' then
begin
EditPersonalStickCode1.Text:=execParams.ParamByName('PersonalCode').AsString;
EditPersonalStickName1.Text:=execParams.ParamByName('PersonalName').AsString;
PanelPositionStickName1.Caption:=execParams.ParamByName('PositionName').AsString;
ActiveControl:=bbOk;
end;
//
fStartWrite:=false;
//
end;
//
execParams.Free;
end;
{------------------------------------------------------------------------------}
end.
|
unit Project87.BaseUnit;
interface
uses
QGame.Scene,
Strope.Math,
Project87.Types.StarMap,
Project87.Types.GameObject;
const
UNIT_VIEW_RANGE = 1200 * 1200;
type
TOwner = (oPlayer = 0, oEnemy = 1);
TBaseUnit = class (TPhysicalObject)
private
FCounter: Word;
protected
FSide: TLifeFraction;
FTowerAngle: Single;
FShowShieldTime: Single;
FLife: Single;
FViewRange: Single;
FDistanceToHero: Single;
FSeeHero: Boolean;
function GetSideColor(ASide: TLifeFraction): Cardinal;
public
constructor CreateUnit(const APosition: TVector2F; AAngle: Single;
ASide: TLifeFraction); virtual;
procedure OnUpdate(const ADelta: Double); override;
procedure OnCollide(OtherObject: TPhysicalObject); override;
procedure Hit(ADamage: Single); virtual;
procedure Kill; virtual;
property Life: Single read FLife;
end;
implementation
uses
Project87.Resources,
Project87.Asteroid,
Project87.BaseEnemy,
Project87.Fluid,
Project87.Hero;
{$REGION ' TBaseUnit '}
constructor TBaseUnit.CreateUnit(const APosition: TVector2F; AAngle: Single;
ASide: TLifeFraction);
begin
inherited Create;
FPosition := APosition;
FAngle := AAngle;
FUseCollistion := True;
FRadius := 35;
FMass := 1;
FLife := 100;
FViewRange := UNIT_VIEW_RANGE;
end;
function TBaseUnit.GetSideColor(ASide: TLifeFraction): Cardinal;
begin
Result := $FFFFFFFF;
case ASide of
lfRed: Result := $FFFF2222;
lfGreen: Result := $FF22FF22;
lfBlue: Result := $FF2222FF;
end;
end;
procedure TBaseUnit.OnCollide(OtherObject: TPhysicalObject);
begin
if (OtherObject is TAsteroid) or
(OtherObject is THeroShip) or
(OtherObject is TBaseEnemy)
then
FShowShieldTime := 0.7;
end;
procedure TBaseUnit.OnUpdate(const ADelta: Double);
begin
Inc(FCounter);
if FCounter > 10 then
begin
FCounter := 0;
FDistanceToHero := (FPosition - THeroShip.GetInstance.Position).LengthSqr;
if FDistanceToHero < UNIT_VIEW_RANGE then
FSeeHero := true;
end;
if (FShowShieldTime > 0) then
begin
FShowShieldTime := FShowShieldTime - ADelta;
if (FShowShieldTime < 0) then
FShowShieldTime := 0;
end;
end;
procedure TBaseUnit.Hit(ADamage: Single);
begin
FShowShieldTime := 0.7;
FLife := FLife - ADamage;
if (FLife < 0) then
Kill;
end;
procedure TBaseUnit.Kill;
begin
FIsDead := True;
end;
{$ENDREGION}
end.
|
{
@abstract(Layers for @code(google.maps.Map) class from Google Maps API.)
@author(Xavier Martinez (cadetill) <cadetill@gmail.com>)
@created(August 12, 2022)
@lastmod(September 14, 2022)
The GMLib.Layers contains all classes needed to manege all layers classes.
}
unit GMLib.Layers;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
GMLib.Classes;
type
// @include(..\Help\docs\GMLib.Layers.TGMTrafficLayerOptions.txt)
TGMTrafficLayerOptions = class(TGMPersistentStr)
private
FAutoRefresh: Boolean;
procedure SetAutoRefresh(const Value: Boolean);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\Help\docs\GMLib.Layers.TGMTrafficLayerOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl;
published
// @include(..\Help\docs\GMLib.Layers.TGMTrafficLayerOptions.AutoRefresh.txt)
property AutoRefresh: Boolean read FAutoRefresh write SetAutoRefresh;
end;
// @include(..\Help\docs\GMLib.Layers.TGMTrafficLayer.txt)
TGMTrafficLayer = class(TGMPersistentStr)
private
FTrafficLayerOptions: TGMTrafficLayerOptions;
FShow: Boolean;
procedure SetShow(const Value: Boolean);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\Help\docs\GMLib.Layers.TGMTrafficLayer.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\Help\docs\GMLib.Layers.TGMTrafficLayer.Destroy.txt)
destructor Destroy; override;
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl;
published
// @include(..\Help\docs\GMLib.Layers.TGMTrafficLayer.Show.txt)
property Show: Boolean read FShow write SetShow;
// @include(..\Help\docs\GMLib.Layers.TGMTrafficLayer.TrafficLayerOptions.txt)
property TrafficLayerOptions: TGMTrafficLayerOptions read FTrafficLayerOptions write FTrafficLayerOptions;
end;
// @include(..\Help\docs\GMLib.Layers.TGMTransitLayer.txt)
TGMTransitLayer = class(TGMPersistentStr)
private
FShow: Boolean;
procedure SetShow(const Value: Boolean);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\Help\docs\GMLib.Layers.TGMTransitLayer.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl;
published
// @include(..\Help\docs\GMLib.Layers.TGMTransitLayer.Show.txt)
property Show: Boolean read FShow write SetShow;
end;
// @include(..\Help\docs\GMLib.Layers.TGMByciclingLayer.txt)
TGMByciclingLayer = class(TGMPersistentStr)
private
FShow: Boolean;
procedure SetShow(const Value: Boolean);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\Help\docs\GMLib.Layers.TGMByciclingLayer.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl;
published
// @include(..\Help\docs\GMLib.Layers.TGMByciclingLayer.Show.txt)
property Show: Boolean read FShow write SetShow;
end;
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayerOptions.txt)
TGMKmlLayerOptions = class(TGMPersistentStr)
private
FScreenOverlays: Boolean;
FSuppressInfoWindows: Boolean;
FUrl: string;
FClickable: Boolean;
FPreserveViewport: Boolean;
procedure SetClickable(const Value: Boolean);
procedure SetPreserveViewport(const Value: Boolean);
procedure SetScreenOverlays(const Value: Boolean);
procedure SetSuppressInfoWindows(const Value: Boolean);
procedure SetUrl(const Value: string);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayerOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl;
published
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayerOptions.Clickable.txt)
property Clickable: Boolean read FClickable write SetClickable default True;
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayerOptions.PreserveViewport.txt)
property PreserveViewport: Boolean read FPreserveViewport write SetPreserveViewport default False;
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayerOptions.ScreenOverlays.txt)
property ScreenOverlays: Boolean read FScreenOverlays write SetScreenOverlays default True;
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayerOptions.SuppressInfoWindows.txt)
property SuppressInfoWindows: Boolean read FSuppressInfoWindows write SetSuppressInfoWindows default False;
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayerOptions.Url.txt)
property Url: string read FUrl write SetUrl;
end;
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayer.txt)
TGMKmlLayer = class(TGMPersistentStr)
private
FShow: Boolean;
FKmlLayerOptions: TGMKmlLayerOptions;
procedure SetShow(const Value: Boolean);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayer.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayer.Destroy.txt)
destructor Destroy; override;
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl;
published
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayer.Show.txt)
property Show: Boolean read FShow write SetShow;
// @include(..\Help\docs\GMLib.Layers.TGMKmlLayer.KmlLayerOptions.txt)
property KmlLayerOptions: TGMKmlLayerOptions read FKmlLayerOptions write FKmlLayerOptions;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
GMLib.Transform;
{ TGMTrafficLayerOptions }
procedure TGMTrafficLayerOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMTrafficLayerOptions then
begin
AutoRefresh := TGMTrafficLayerOptions(Source).AutoRefresh;
end;
end;
constructor TGMTrafficLayerOptions.Create(AOwner: TPersistent);
begin
inherited;
FAutoRefresh := True;
end;
function TGMTrafficLayerOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference/map#TrafficLayerOptions';
end;
function TGMTrafficLayerOptions.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
LowerCase(TGMTransform.GMBoolToStr(FAutoRefresh, True))
]);
end;
procedure TGMTrafficLayerOptions.SetAutoRefresh(const Value: Boolean);
begin
if FAutoRefresh = Value then Exit;
FAutoRefresh := Value;
ControlChanges('AutoRefresh');
end;
{ TGMTrafficLayer }
procedure TGMTrafficLayer.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMTrafficLayer then
begin
Show := TGMTrafficLayer(Source).Show;
TrafficLayerOptions.Assign(TGMTrafficLayer(Source).TrafficLayerOptions);
end;
end;
constructor TGMTrafficLayer.Create(AOwner: TPersistent);
begin
inherited;
FShow := False;
FTrafficLayerOptions := TGMTrafficLayerOptions.Create(Self);
end;
destructor TGMTrafficLayer.Destroy;
begin
if Assigned(FTrafficLayerOptions) then
FTrafficLayerOptions.Free;
inherited;
end;
function TGMTrafficLayer.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference/map#TrafficLayer';
end;
function TGMTrafficLayer.PropToString: string;
const
Str = '%s,%s';
begin
Result := Format(Str, [
LowerCase(TGMTransform.GMBoolToStr(FShow, True)),
FTrafficLayerOptions.PropToString
]);
end;
procedure TGMTrafficLayer.SetShow(const Value: Boolean);
begin
if FShow = Value then Exit;
FShow := Value;
ControlChanges('Show');
end;
{ TGMTransitLayer }
procedure TGMTransitLayer.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMTransitLayer then
begin
Show := TGMTransitLayer(Source).Show;
end;
end;
constructor TGMTransitLayer.Create(AOwner: TPersistent);
begin
inherited;
FShow := False;
end;
function TGMTransitLayer.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference/map#TransitLayer';
end;
function TGMTransitLayer.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
LowerCase(TGMTransform.GMBoolToStr(FShow, True))
]);
end;
procedure TGMTransitLayer.SetShow(const Value: Boolean);
begin
if FShow = Value then Exit;
FShow := Value;
ControlChanges('Show');
end;
{ TGMByciclingLayer }
procedure TGMByciclingLayer.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMByciclingLayer then
begin
Show := TGMByciclingLayer(Source).Show;
end;
end;
constructor TGMByciclingLayer.Create(AOwner: TPersistent);
begin
inherited;
FShow := False;
end;
function TGMByciclingLayer.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference/map#BicyclingLayer';
end;
function TGMByciclingLayer.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
LowerCase(TGMTransform.GMBoolToStr(FShow, True))
]);
end;
procedure TGMByciclingLayer.SetShow(const Value: Boolean);
begin
if FShow = Value then Exit;
FShow := Value;
ControlChanges('Show');
end;
{ TGMKmlLayer }
procedure TGMKmlLayer.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMKmlLayer then
begin
Show := TGMKmlLayer(Source).Show;
KmlLayerOptions.Assign(TGMKmlLayer(Source).KmlLayerOptions);
end;
end;
constructor TGMKmlLayer.Create(AOwner: TPersistent);
begin
inherited;
FShow := False;
FKmlLayerOptions := TGMKmlLayerOptions.Create(Self);
end;
destructor TGMKmlLayer.Destroy;
begin
if Assigned(FKmlLayerOptions) then
FKmlLayerOptions.Free;
inherited;
end;
function TGMKmlLayer.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference/kml';
end;
function TGMKmlLayer.PropToString: string;
const
Str = '%s,%s';
begin
Result := Format(Str, [
LowerCase(TGMTransform.GMBoolToStr(FShow, True)),
FKmlLayerOptions.PropToString
]);
end;
procedure TGMKmlLayer.SetShow(const Value: Boolean);
begin
if FShow = Value then Exit;
FShow := Value;
ControlChanges('Show');
end;
{ TGMKmlLayerOptions }
procedure TGMKmlLayerOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMKmlLayerOptions then
begin
Clickable := TGMKmlLayerOptions(Source).Clickable;
PreserveViewport := TGMKmlLayerOptions(Source).PreserveViewport;
ScreenOverlays := TGMKmlLayerOptions(Source).ScreenOverlays;
SuppressInfoWindows := TGMKmlLayerOptions(Source).SuppressInfoWindows;
Url := TGMKmlLayerOptions(Source).Url;
end;
end;
constructor TGMKmlLayerOptions.Create(AOwner: TPersistent);
begin
inherited;
FClickable := True;
FPreserveViewport := False;
FScreenOverlays := True;
FSuppressInfoWindows := False;
FUrl := '';
end;
function TGMKmlLayerOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference/kml#KmlLayerOptions';
end;
function TGMKmlLayerOptions.PropToString: string;
const
Str = '%s,%s,%s,%s,%s';
begin
Result := Format(Str, [
LowerCase(TGMTransform.GMBoolToStr(FClickable, True)),
LowerCase(TGMTransform.GMBoolToStr(FPreserveViewport, True)),
LowerCase(TGMTransform.GMBoolToStr(FScreenOverlays, True)),
LowerCase(TGMTransform.GMBoolToStr(FSuppressInfoWindows, True)),
QuotedStr(FUrl)
]);
end;
procedure TGMKmlLayerOptions.SetClickable(const Value: Boolean);
begin
if FClickable = Value then Exit;
FClickable := Value;
ControlChanges('Clickable');
end;
procedure TGMKmlLayerOptions.SetPreserveViewport(const Value: Boolean);
begin
if FPreserveViewport = Value then Exit;
FPreserveViewport := Value;
ControlChanges('PreserveViewport');
end;
procedure TGMKmlLayerOptions.SetScreenOverlays(const Value: Boolean);
begin
if FScreenOverlays = Value then Exit;
FScreenOverlays := Value;
ControlChanges('ScreenOverlays');
end;
procedure TGMKmlLayerOptions.SetSuppressInfoWindows(const Value: Boolean);
begin
if FSuppressInfoWindows = Value then Exit;
FSuppressInfoWindows := Value;
ControlChanges('SuppressInfoWindows');
end;
procedure TGMKmlLayerOptions.SetUrl(const Value: string);
begin
if FUrl = Value then Exit;
FUrl := Value;
ControlChanges('Url');
end;
end.
|
unit UFrm;
interface
uses Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons,
Vcl.Controls, System.Classes,
//
System.IniFiles, Vcl.Graphics;
type
TFrm = class(TForm)
Label1: TLabel;
EdCompName: TEdit;
Label2: TLabel;
EdDV: TComboBox;
Ck64bit: TCheckBox;
Label3: TLabel;
BtnInstall: TBitBtn;
BtnExit: TBitBtn;
M: TRichEdit;
LbVersion: TLabel;
LinkLabel1: TLinkLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
procedure BtnInstallClick(Sender: TObject);
procedure LinkLabel1LinkClick(Sender: TObject; const Link: string;
LinkType: TSysLinkType);
private
AppDir: String;
Ini: TIniFile;
InternalDelphiVersionKey: String;
MSBuild_Dir: String;
procedure Compile;
procedure CompilePackage(const aBat, aPackage, aPlatform: String);
procedure LoadDelphiVersions;
procedure AddLibrary;
procedure Log(const A: String; bBold: Boolean = True; Color: TColor = clBlack);
procedure PublishFiles(const aPlatform, aFiles: String);
procedure RegisterBPL(const aPackage: String);
procedure OnLine(const Text: String);
procedure FindMSBuild;
end;
var
Frm: TFrm;
implementation
{$R *.dfm}
uses System.SysUtils, System.Win.Registry,
Winapi.Windows, Winapi.Messages, Winapi.ShlObj, Winapi.ShellApi,
Vcl.Dialogs, System.IOUtils, System.UITypes,
UCmdExecBuffer;
const BDS_KEY = 'Software\Embarcadero\BDS';
//-- Object to use in Delphi Version ComboBox
type TDelphiVersion = class
InternalNumber: String;
end;
//--
function HasInList(const Item, List: String): Boolean;
begin
Result := Pos(';'+Item+';', ';'+List+';')>0;
end;
function PVToEnter(const A: String): String;
begin
Result := StringReplace(A, ';', #13#10, [rfReplaceAll]);
end;
function AddBarDir(const Dir: String): String;
begin
Result := IncludeTrailingPathDelimiter(Dir);
end;
procedure TFrm.Log(const A: String; bBold: Boolean = True; Color: TColor = clBlack);
begin
M.SelStart := Length(M.Text);
if bBold then
M.SelAttributes.Style := [fsBold]
else
M.SelAttributes.Style := [];
M.SelAttributes.Color := Color;
M.SelText := A+#13#10;
SendMessage(M.Handle, WM_VSCROLL, SB_BOTTOM, 0); //scroll to bottom
//M.SelStart := Length(M.Text);
end;
procedure TFrm.FormCreate(Sender: TObject);
var aIniArq: String;
begin
AppDir := ExtractFilePath(Application.ExeName);
aIniArq := AppDir+'CompInstall.ini';
try
if not FileExists(aIniArq) then
raise Exception.Create('Ini file not found');
Ini := TIniFile.Create(aIniArq);
EdCompName.Text := Ini.ReadString('General', 'Name', '');
if EdCompName.Text='' then
raise Exception.Create('Component name not specifyed at ini file');
Ck64bit.Visible := Ini.ReadBool('General', 'Allow64bit', False);
LoadDelphiVersions; //load list of delphi versions
FindMSBuild;
except
BtnInstall.Enabled := False;
raise;
end;
end;
procedure TFrm.FormDestroy(Sender: TObject);
var I: Integer;
begin
if Assigned(Ini) then Ini.Free;
//--Free objects of delphi versions list
for I := 0 to EdDV.Items.Count-1 do
EdDV.Items.Objects[I].Free;
//--
end;
procedure TFrm.LinkLabel1LinkClick(Sender: TObject; const Link: string;
LinkType: TSysLinkType);
begin
ShellExecute(0, '', PChar(Link), '', '', SW_SHOWNORMAL);
end;
procedure TFrm.BtnExitClick(Sender: TObject);
begin
Close;
end;
procedure TFrm.LoadDelphiVersions;
var R: TRegistry;
aAllowedVersions: String;
procedure Add(const Key, IniVer, Text: String);
var DV: TDelphiVersion;
begin
if R.KeyExists(Key) and HasInList(IniVer, aAllowedVersions) then
begin
DV := TDelphiVersion.Create;
DV.InternalNumber := Key;
EdDV.Items.AddObject(Text, DV);
end;
end;
begin
aAllowedVersions := Ini.ReadString('General', 'DelphiVersions', ''); //list splited by ";"
if aAllowedVersions='' then
raise Exception.Create('No Delphi version specifyed at ini file');
R := TRegistry.Create;
try
R.RootKey := HKEY_CURRENT_USER;
if R.OpenKeyReadOnly(BDS_KEY) then
begin
Add('3.0', '2005', 'Delphi 2005');
Add('4.0', '2006', 'Delphi 2006');
Add('5.0', '2007', 'Delphi 2007');
Add('6.0', '2009', 'Delphi 2009');
Add('7.0', '2010', 'Delphi 2010');
Add('8.0', 'XE', 'Delphi XE');
Add('9.0', 'XE2', 'Delphi XE2');
Add('10.0', 'XE3', 'Delphi XE3');
Add('11.0', 'XE4', 'Delphi XE4');
Add('12.0', 'XE5', 'Delphi XE5');
Add('14.0', 'XE6', 'Delphi XE6');
Add('15.0', 'XE7', 'Delphi XE7');
Add('16.0', 'XE8', 'Delphi XE8');
Add('17.0', '10', 'Delphi 10 Seattle');
Add('18.0', '10.1', 'Delphi 10.1 Berlin');
Add('19.0', '10.2', 'Delphi 10.2 Tokyo');
Add('20.0', '10.3', 'Delphi 10.3 Rio');
end;
finally
R.Free;
end;
if EdDV.Items.Count=0 then
raise Exception.Create('None Delphi version installed or supported');
EdDV.ItemIndex := EdDV.Items.Count-1; //select last version
end;
procedure TFrm.BtnInstallClick(Sender: TObject);
begin
M.Clear; //clear log
if EdDV.ItemIndex=-1 then
begin
MessageDlg('Select a Delphi version', mtError, [mbOK], 0);
EdDV.SetFocus;
Exit;
end;
InternalDelphiVersionKey := TDelphiVersion(EdDV.Items.Objects[EdDV.ItemIndex]).InternalNumber;
//check if Delphi IDE is running
if FindWindow('TAppBuilder', nil)<>0 then
begin
MessageDlg('Please, close Delphi IDE first!', mtError, [mbOK], 0);
Exit;
end;
BtnInstall.Enabled := False;
BtnExit.Enabled := False;
Refresh;
try
Log('COMPILE COMPONENT...');
Compile;
if Ini.ReadBool('General', 'AddLibrary', False) then
AddLibrary;
Log('COMPONENT INSTALLED!', True, clGreen);
except
on E: Exception do
Log('ERROR: '+E.Message, True, clRed);
end;
BtnInstall.Enabled := True;
BtnExit.Enabled := True;
end;
procedure TFrm.Compile;
var R: TRegistry;
aRootDir: String;
aBat, aPac, aSec, aPubFiles: String;
S: TStringList;
begin
R := TRegistry.Create;
try
R.RootKey := HKEY_CURRENT_USER;
if not R.OpenKeyReadOnly(BDS_KEY+'\'+InternalDelphiVersionKey) then
raise Exception.Create('Main Registry of delphi version not found');
aRootDir := R.ReadString('RootDir');
if aRootDir='' then
raise Exception.Create('Can not get Delphi Root Folder');
finally
R.Free;
end;
if not DirectoryExists(aRootDir) then
raise Exception.Create('Delphi root folder does not exist');
aBat := AddBarDir(aRootDir)+'bin\rsvars.bat';
if not FileExists(aBat) then
raise Exception.Create('Internal Delphi Batch file "rsvars" not found');
S := TStringList.Create;
try
S.Text := PVToEnter(Ini.ReadString('General', 'Packages', ''));
if S.Count=0 then
raise Exception.Create('No package found in the Ini file');
for aPac in S do
begin
aSec := 'P_'+aPac; //section of package in the ini file
aPubFiles := Ini.ReadString(aSec, 'PublishFiles', ''); //list of files to publish
CompilePackage(aBat, aPac, 'Win32');
PublishFiles('Win32', aPubFiles);
if Ck64bit.Visible and Ck64bit.Checked then
if Ini.ReadBool(aSec, 'Allow64bit', False) then
begin
CompilePackage(aBat, aPac, 'Win64');
PublishFiles('Win64', aPubFiles);
end;
if Ini.ReadBool(aSec, 'Install', False) then
RegisterBPL(aPac);
end;
finally
S.Free;
end;
end;
procedure TFrm.CompilePackage(const aBat, aPackage, aPlatform: String);
var C: TCmdExecBuffer;
MSBuildExe: String;
begin
Log('Compile package '+aPackage+' ('+aPlatform+')');
MSBuildExe := AddBarDir(MSBuild_Dir)+'MSBUILD.EXE';
C := TCmdExecBuffer.Create;
try
C.OnLine := OnLine;
C.CommandLine :=
Format('%s & "%s" "%s.dproj" /t:build /p:config=Release /p:platform=%s',
[aBat, MSBuildExe, AppDir+aPackage, aPlatform]);
C.WorkDir := AppDir;
if not C.Exec then
raise Exception.Create('Could not execute MSBUILD');
if C.ExitCode<>0 then
raise Exception.CreateFmt('Error compiling package %s (Exit Code %d)', [aPackage, C.ExitCode]);
finally
C.Free;
end;
Log('');
end;
procedure TFrm.OnLine(const Text: String);
begin
Log(TrimRight(Text), False);
end;
procedure TFrm.AddLibrary;
procedure AddKey(const aPlatform: String);
var Key, A, Dir: String;
R: TRegistry;
const SEARCH_KEY = 'Search Path';
begin
Log('Add library path to '+aPlatform);
Key := BDS_KEY+'\'+InternalDelphiVersionKey+'\Library\'+aPlatform;
Dir := AppDir+aPlatform+'\Release';
R := TRegistry.Create;
try
R.RootKey := HKEY_CURRENT_USER;
if not R.OpenKey(Key, False) then
raise Exception.Create('Registry key for Library '+aPlatform+' not found');
A := R.ReadString(SEARCH_KEY);
if not HasInList(Dir, A) then
R.WriteString(SEARCH_KEY, A+';'+Dir);
finally
R.Free;
end;
end;
begin
AddKey('Win32');
if Ck64bit.Visible and Ck64bit.Checked then
AddKey('Win64');
end;
function GetPublicDocs: String;
var Path: array[0..MAX_PATH] of Char;
begin
if not ShGetSpecialFolderPath(0, Path, CSIDL_COMMON_DOCUMENTS, False) then
raise Exception.Create('Could not find Public Documents folder location') ;
Result := Path;
end;
procedure TFrm.RegisterBPL(const aPackage: String);
var R: TRegistry;
BplDir: String;
begin
Log('Install BPL into IDE of '+aPackage);
BplDir := AddBarDir(GetPublicDocs)+'Embarcadero\Studio\'+InternalDelphiVersionKey+'\Bpl';
R := TRegistry.Create;
try
R.RootKey := HKEY_CURRENT_USER;
if not R.OpenKey(BDS_KEY+'\'+InternalDelphiVersionKey+'\Known Packages', False) then
raise Exception.Create('Know Packages registry section not found');
R.WriteString(AddBarDir(BplDir)+aPackage+'.bpl', EdCompName.Text);
finally
R.Free;
end;
end;
procedure TFrm.PublishFiles(const aPlatform, aFiles: String);
var S: TStringList;
A, aSource, aDest: String;
begin
S := TStringList.Create;
try
S.Text := PVToEnter(aFiles);
for A in S do
begin
aSource := AppDir+A;
aDest := AppDir+aPlatform+'\Release\'+A;
Log(Format('Copy file %s to %s', [A{aSource}, aDest]), False);
TFile.Copy(aSource, aDest, True);
end;
finally
S.Free;
end;
end;
procedure TFrm.FindMSBuild;
var R: TRegistry;
S: TStringList;
I: Integer;
Dir: String;
Found: Boolean;
const TOOLS_KEY = 'Software\Microsoft\MSBUILD\ToolsVersions';
begin
R := TRegistry.Create;
try
R.RootKey := HKEY_LOCAL_MACHINE;
if not R.OpenKeyReadOnly(TOOLS_KEY) then
raise Exception.Create('MSBUILD not found');
S := TStringList.Create;
try
R.GetKeyNames(S);
R.CloseKey;
if S.Count=0 then
raise Exception.Create('There is no .NET Framework version available');
S.Sort;
Found := False;
for I := S.Count-1 downto 0 do
begin
if not R.OpenKeyReadOnly(TOOLS_KEY+'\'+S[I]) then
raise Exception.Create('Internal error on reading .NET version key');
Dir := R.ReadString('MSBuildToolsPath');
R.CloseKey;
if Dir<>'' then
begin
if FileExists(AddBarDir(Dir)+'MSBUILD.EXE') then
begin
//msbuild found
Found := True;
Break;
end;
end;
end;
finally
S.Free;
end;
finally
R.Free;
end;
if not Found then
raise Exception.Create('MSBUILD not found in any .NET Framework version');
MSBuild_Dir := Dir;
//Log('MSBUILD path: '+MSBuild_Dir);
end;
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.MessageBody.OXML;
interface
uses
System.Classes, System.SysUtils, System.Rtti, System.Generics.Collections,
// OXml
OXmlRTTISerialize,
OXmlUtils,
// WiRL
WiRL.Core.Attributes,
WiRL.Core.Declarations,
WiRL.http.Accept.MediaType,
WiRL.Core.MessageBodyReader,
WiRL.Core.MessageBodyWriter,
WiRL.Core.Exceptions,
WiRL.http.Request,
WiRL.http.Response;
type
[Consumes(TMediaType.APPLICATION_XML)]
TObjectReaderOXML = class(TInterfacedObject, IMessageBodyReader)
private
procedure Deserialize(const ADocument: string; AObject: TObject);
public
function ReadFrom(AParam: TRttiParameter;
AMediaType: TMediaType; ARequest: TWiRLRequest): TValue;
end;
[Produces(TMediaType.APPLICATION_XML)]
TObjectWriterOXML = class(TInterfacedObject, IMessageBodyWriter)
public
procedure WriteTo(const AValue: TValue; const AAttributes: TAttributeArray;
AMediaType: TMediaType; AResponse: TWiRLResponse);
end;
implementation
uses
Data.DB,
System.TypInfo,
WiRL.Core.Utils,
WiRL.Rtti.Utils;
{ TObjectReaderOXML }
procedure TObjectReaderOXML.Deserialize(const ADocument: string; AObject: TObject);
var
LDeserializer : TXMLRTTIDeserializer;
LClassName: string;
begin
LDeserializer := TXMLRTTIDeserializer.Create;
try
LDeserializer.UseRoot := False;
LDeserializer.InitXML(ADocument);
LDeserializer.ReadObjectInfo(LClassName);
LDeserializer.ReadObject(AObject);
finally
LDeserializer.Free;
end;
end;
function TObjectReaderOXML.ReadFrom(AParam: TRttiParameter;
AMediaType: TMediaType; ARequest: TWiRLRequest): TValue;
var
LObj: TObject;
begin
LObj := TRttiHelper.CreateInstance(AParam.ParamType);
Deserialize(ARequest.Content, LObj);
end;
{ TObjectWriterOXML }
procedure TObjectWriterOXML.WriteTo(const AValue: TValue;
const AAttributes: TAttributeArray; AMediaType: TMediaType;
AResponse: TWiRLResponse);
var
LStreamWriter: TStreamWriter;
LSer: TXMLRTTISerializer;
begin
LStreamWriter := TStreamWriter.Create(AResponse.ContentStream);
try
LSer := TXMLRTTISerializer.Create;
try
LSer.UseRoot := False;
LSer.CollectionStyle := csOXML;
LSer.ObjectVisibility := [mvPublished];
LSer.WriterSettings.IndentType := itIndent;
LSer.InitStream(AResponse.ContentStream);
LSer.WriteObject(AValue.AsObject);
LSer.ReleaseDocument;
finally
LSer.Free;
end;
finally
LStreamWriter.Free;
end;
end;
initialization
TMessageBodyReaderRegistry.Instance.RegisterReader(TObjectReaderOXML,
function(AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Boolean
begin
Result := Assigned(AType) and
AType.IsInstance and
not TRttiHelper.IsObjectOfType<TDataSet>(AType, True);
end,
function(AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Integer
begin
Result := TMessageBodyReaderRegistry.AFFINITY_HIGH;
end
);
TMessageBodyWriterRegistry.Instance.RegisterWriter(TObjectWriterOXML,
function(AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Boolean
begin
Result := Assigned(AType) and
AType.IsInstance and
not TRttiHelper.IsObjectOfType<TDataSet>(AType, True);
end,
function(AType: TRttiType; const AAttributes: TAttributeArray; AMediaType: TMediaType): Integer
begin
Result := TMessageBodyWriterRegistry.AFFINITY_HIGH;
end
);
end.
|
(*******************************************************************************
Contributors: Igor Ivkin (igor@arkadia.com)
Alcinoe.LibPhoneNumber is a wrapper for a several functions that use Google's
C++ library libphonenumber to parse and format phone numbers written in a free
form. This wrapper requires few DLLs to be working correctly. These DLLs are
distributed in the folder "Lib/dll".
This wrapper is based on a custom DLL-modification that provides three main
functions:
1. To convert a given string phone written in a free form to Int64.
2. To convert phone given as Int64 to international format defined for its country.
3. To define a type of the phone (landing line, mobile, toll-free etc).
*******************************************************************************)
unit Alcinoe.LibPhoneNumber;
interface
uses
system.Classes,
system.sysutils;
function ALStrPhoneNumberToInt64(const PhoneNumber, CountryCode: AnsiString): Int64; overload;
function ALStrPhoneNumberToInt64(PhoneNumber: AnsiString): Int64; overload;
function ALInt64PhoneNumberToStr(PhoneNumber: Int64): AnsiString;
function ALGetPhoneNumberType(PhoneNumber: Int64): integer;
const
cALFixedLine = 0;
cALMobile = 1;
cALFixedLineOrMobil = 2; // mostly for US
cALTollFree = 3;
cALPremiumRate = 4;
cALSharedCost = 5; // see http://en.wikipedia.org/wiki/Shared_Cost_Service
cALVoIP = 6;
cALPersonalNumber = 7;
cALPager = 8;
cALUAN = 9; // see "Universal Access Numbers"
cALVoiceMail = 10;
cALUnknown = 11;
implementation
uses
System.AnsiStrings,
Alcinoe.StringUtils;
{****************************************************************************************************************}
function _StrPhoneNumberToInt64(phoneNumber, countryCode: PAnsiChar): Int64; cdecl; external 'libphonenumber.dll';
function _Int64PhoneNumberToStr(phoneNumber: Int64; buffer: PAnsiChar): Cardinal; cdecl; external 'libphonenumber.dll';
function _GetPhoneNumberType(phoneNumber: Int64): integer; cdecl; external 'libphonenumber.dll';
{**********************************************************************************}
function ALStrPhoneNumberToInt64(const PhoneNumber, CountryCode: AnsiString): Int64;
begin
result := _StrPhoneNumberToInt64(PAnsiChar(PhoneNumber), PAnsiChar(AlUppercase(CountryCode)));
end;
{***************************************************}
{This function analyzes the phone number looking like
[FR] 06.34.54.12.22, extract country code if it is possible and
converts this number to an Int64 representation looking like 33634541222 }
function ALStrPhoneNumberToInt64(PhoneNumber: AnsiString): Int64;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function _IsDecimal(const S: AnsiString): boolean;
var i: integer;
begin
result := s <> '';
if not result then exit;
for i := low(s) to high(S) do begin
if not (S[i] in ['0'..'9']) then begin
result := false;
break;
end;
end;
end;
var LCountryCode: AnsiString;
P1, P2: integer;
begin
PhoneNumber := ALTrim(PhoneNumber); //1rt trim the aPhoneNumber
if _IsDecimal(PhoneNumber) and alTryStrToInt64(PhoneNumber, result) then exit; // if their is not the '+' sign we can do nothing because ALStrPhoneNumberToInt64 will return 0
// if alTryStrToInt64 not success it's mean it's a tooo big number, so better to return 0
LCountryCode := '';
P1 := ALPosA('[',PhoneNumber); // look if their is some prefix or suffix like [FR] to give an hint about the country
while P1 > 0 do begin
P2 := ALPosA(']', PhoneNumber, P1+1);
if P2 = P1 + 3 then begin
LCountryCode := ALUpperCase(ALCopyStr(PhoneNumber, P1+1, 2)); // [FR] 06.34.54.12.22 => FR
if (length(LCountryCode) = 2) and
(LCountryCode[1] in ['A'..'Z']) and
(LCountryCode[2] in ['A'..'Z']) then begin
delete(PhoneNumber,P1,4); // "[FR] 06.34.54.12.22" => " 06.34.54.12.22"
PhoneNumber := ALtrim(PhoneNumber); // " 06.34.54.12.22" => "06.34.54.12.22"
break; // break the loop, we found the country code hint
end
else LCountryCode := '';
end;
P1 := ALPosA('[',PhoneNumber, P1+1);
end;
result := ALStrPhoneNumberToInt64(PhoneNumber, LCountryCode); //even if the aPhoneNumber is already an integer we need to format it
//because user can gave us +330625142445 but it's must be stored as
// +33625142445
end;
{***************************************************************}
function ALInt64PhoneNumberToStr(PhoneNumber: Int64): AnsiString;
var ln: Cardinal;
begin
SetLength(Result, 255);
ln := _Int64PhoneNumberToStr(PhoneNumber, @Result[1]);
SetLength(Result, ln);
end;
{*********************************************************}
function ALGetPhoneNumberType(PhoneNumber: Int64): integer;
begin
result := _GetPhoneNumberType(PhoneNumber);
end;
end.
|
unit UPrefFAppraiserXFer;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
{ This is the Frame that contains the Appraiser Transfer Preferences}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UContainer;
type
TPrefAppraiserXFer = class(TFrame)
chkAddYrSuffix: TCheckBox;
chkAddSiteSuffix: TCheckBox;
chkAddBasemtSuffix: TCheckBox;
chkLenderEmailinPDF: TCheckBox;
Panel1: TPanel;
chkGRMTransfer: TCheckBox;
private
FDoc: TContainer;
public
constructor CreateFrame(AOwner: TComponent; ADoc: TContainer);
procedure LoadPrefs; //loads in the prefs from the app
procedure SavePrefs;
end;
implementation
uses
UGlobals, UInit,IniFiles;
{$R *.dfm}
constructor TPrefAppraiserXFer.CreateFrame(AOwner: TComponent; ADoc: TContainer);
begin
inherited Create(AOwner);
FDoc := ADoc;
LoadPrefs;
end;
procedure TPrefAppraiserXFer.LoadPrefs;
begin
//load appraiser Transfers
chkAddYrSuffix.checked := appPref_AppraiserAddYrSuffix;
chkAddBasemtSuffix.checked := appPref_AppraiserAddBsmtSFSuffix;
chkAddSiteSuffix.checked := appPref_AppraiserAddSiteSuffix;
chkLenderEmailinPDF.checked := appPref_AppraiserLenderEmailinPDF;
//chkBorrowerToOwner.checked := appPref_AppraiserBorrowerToOwner;
chkGRMTransfer.Checked := appPref_AppraiserGRMTransfer;
end;
procedure TPrefAppraiserXFer.SavePrefs;
var
PrefFile: TMemIniFile;
IniFilePath : String;
begin
//save appraiser Transfers
appPref_AppraiserAddYrSuffix := chkAddYrSuffix.checked;
appPref_AppraiserAddBsmtSFSuffix := chkAddBasemtSuffix.checked;
appPref_AppraiserAddSiteSuffix := chkAddSiteSuffix.checked;
appPref_AppraiserLenderEmailinPDF := chkLenderEmailinPDF.checked;
//appPref_AppraiserBorrowerToOwner := chkBorrowerToOwner.checked;
appPref_AppraiserGRMTransfer := chkGRMTransfer.Checked;
IniFilePath := IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI;
PrefFile := TMemIniFile.Create(IniFilePath); //create the INI reader
try
With PrefFile do
begin
WriteBool('Appraisal', 'AddYrSuffix', appPref_AppraiserAddYrSuffix); //Add Yr suffix
WriteBool('Appraisal', 'AddBsmtSFSuffix', appPref_AppraiserAddBsmtSFSuffix); //basement sf transfer
WriteBool('Appraisal', 'AddSiteSuffix', appPref_AppraiserAddSiteSuffix); //sqft or ac suffic transfer
WriteBool('Appraisal', 'LenderEmailinPDF', appPref_AppraiserLenderEmailinPDF); //auto-run reviewer
WriteBool('Appraisal', 'AppraiserGRMTransfer', appPref_AppraiserGRMTransfer); //save user credentials to the license file
UpdateFile; // do it now
end;
finally
PrefFile.Free;
end;
end;
end.
|
unit RegistryUtil;
interface
uses Windows, Registry, SysUtils, StrUtils;
const
// REGISTRY_ROOT = 'HKEY_LOCAL_MACHINE';
CREATE_IFNOTEXIST = false; // создавать иди нет ключи если пр обращении обнаружено, что ключ не существует
//KEY_WOW64_64KEY = $0100;
KEY_WOW64_32KEY = $0200;
type
ERegUtilException = class( Exception )
end;
function GetStringParam( name, path: string ): string; overload;
function GetStringParam( name, path, defValue: string ): string; overload;
procedure SetStringParam( name, path, value: string );
function GetIntegerParam( name, path: string ): integer; overload;
function GetIntegerParamL( name, path: string ): integer; overload;
function GetIntegerParam( name, path: string; defValue: integer ): integer; overload;
function GetIntegerParamL( name, path: string; defValue: integer ): integer; overload;
procedure SetIntegerParam( name, path: string; value: integer );
procedure SetIntegerParamL( name, path: string; value: integer );
function GetBoolParam( name, path: string ): boolean; overload;
function GetBoolParam( name, path: string; defValue: boolean ): boolean; overload;
procedure SetBoolParam( name, path: string; value: boolean );
function DeleteParam( name, path: string ): boolean;
function IsKeyExist( path: string ): boolean;
function IsParamExist( name, path: string ): boolean;
function IsParamExistL( name, path: string ): boolean;
// function IsParamExist( path: string ): boolean;
function RenameKey( oldpath, newpath: string ): boolean;
function RemoveKey( path: string ): boolean;
function RemoveParam( name, path: string ): boolean;
procedure CopyKey( oldpath, newpath: string );
implementation
function RemoveParam( name, path: string ): boolean;
var
Registry: TRegistry;
begin
if not IsParamExist( name, path ) then
begin
Result := false;
exit;
end;
Registry := TRegistry.Create( KEY_ALL_ACCESS or KEY_WOW64_32KEY );
// KEY_WOW64_32KEY
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
Registry.OpenKey( path, false );
Result := Registry.DeleteValue( name );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
// function IsParamExist( path: string ): boolean;
// var
// Registry: TRegistry;
// begin
// Registry := TRegistry.Create;
// Registry.RootKey := HKEY_LOCAL_MACHINE;
// try
// Result := Registry.P( path );
// finally
// FreeAndNil( Registry );
// end;
// end;
procedure CopyKey( oldpath, newpath: string );
begin
if not IsKeyExist( oldpath ) then
raise ERegUtilException.Create( 'Раздел ' + oldpath + ' не существует' );
if IsKeyExist( newpath ) then
raise ERegUtilException.Create( 'Раздел ' + newpath + ' уже существует' );
RenameKey( oldpath, newpath );
// RemoveKey( oldpath );
end;
function IsKeyExist( path: string ): boolean;
var
Registry: TRegistry;
begin
Registry := TRegistry.Create( KEY_READ or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
Result := Registry.KeyExists( path );
finally
FreeAndNil( Registry );
end;
end;
function RemoveKey( path: string ): boolean;
var
Registry: TRegistry;
begin
Registry := TRegistry.Create( KEY_ALL_ACCESS or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
Result := Registry.DeleteKey( path );
finally
FreeAndNil( Registry );
end;
end;
function RenameKey( oldpath, newpath: string ): boolean;
var
Registry: TRegistry;
begin
Result := false;
Registry := TRegistry.Create( KEY_ALL_ACCESS or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
if Registry.OpenKey( oldpath, false ) then
begin
Registry.MoveKey( oldpath, newpath, false );
Result := true;
end;
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
function IsParamExist( name, path: string ): boolean;
var
Registry: TRegistry;
begin
Registry := TRegistry.Create( KEY_READ or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
if not Registry.OpenKey( path, false ) then
Result := false
else
Result := Registry.ValueExists( name );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
function IsParamExistL( name, path: string ): boolean;
var
Registry: TRegistry;
begin
Registry := TRegistry.Create( KEY_READ or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_CURRENT_USER;
try
if not Registry.OpenKey( path, false ) then
Result := false
else
Result := Registry.ValueExists( name );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
function DeleteParam( name, path: string ): boolean;
var
Registry: TRegistry;
begin
Result := false;
Registry := TRegistry.Create( KEY_ALL_ACCESS or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
if Registry.OpenKey( path, false ) then
if Registry.ValueExists( name ) then
Result := Registry.DeleteValue( name );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
function GetStringParam( name, path: string ): string;
var
Registry: TRegistry;
begin
// Registry := TRegistry.Create( KEY_READ or KEY_WOW64_64KEY );
Registry := TRegistry.Create( KEY_READ or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
if not Registry.OpenKey( path, CREATE_IFNOTEXIST ) then
raise ERegistryException.Create( 'Ошибка при чтении ключа реестра' )
else
Result := Registry.ReadString( name );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
function GetStringParam( name, path, defValue: string ): string;
begin
try
Result := GetStringParam( name, path );
if Result = '' then
Result := defValue;
except
Result := defValue;
end;
end;
procedure SetStringParam( name, path, value: string );
var
Registry: TRegistry;
begin
Registry := TRegistry.Create( KEY_ALL_ACCESS or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
if not Registry.OpenKey( path, true ) then
raise ERegistryException.Create( 'Ошибка при записи ключа реестра' )
else
Registry.WriteString( name, value );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
function GetIntegerParam( name, path: string ): integer;
var
Registry: TRegistry;
begin
Result := -1;
try
try
Registry := TRegistry.Create( KEY_READ or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
if not Registry.OpenKey( path, CREATE_IFNOTEXIST ) then
raise ERegistryException.Create( 'Ошибка при чтении ключа реестра' )
else
Result := Registry.ReadInteger( name );
except
on E: Exception do
raise ERegistryException.Create( E.message );
end;
finally
try
Registry.CloseKey;
FreeAndNil( Registry );
finally
// nothing
end;
end;
end;
function GetIntegerParamL( name, path: string ): integer;
var
Registry: TRegistry;
begin
Result := -1;
try
try
Registry := TRegistry.Create( KEY_READ or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_CURRENT_USER;
if not Registry.OpenKey( path, CREATE_IFNOTEXIST ) then
raise ERegistryException.Create( 'Ошибка при чтении ключа реестра' )
else
Result := Registry.ReadInteger( name );
except
on E: Exception do
raise ERegistryException.Create( E.message );
end;
finally
try
Registry.CloseKey;
FreeAndNil( Registry );
finally
// nothing
end;
end;
end;
function GetIntegerParam( name, path: string; defValue: integer ): integer;
begin
try
Result := GetIntegerParam( name, path );
except
Result := defValue;
end;
end;
function GetIntegerParamL( name, path: string; defValue: integer ): integer;
begin
try
if IsParamExistL( name, path ) then
Result := GetIntegerParamL( name, path )
else
Result := defValue;
except
Result := defValue;
end;
end;
procedure SetIntegerParam( name, path: string; value: integer );
var
Registry: TRegistry;
begin
Registry := TRegistry.Create( KEY_ALL_ACCESS or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
if not Registry.OpenKey( path, true ) then
raise ERegistryException.Create( 'Ошибка при записи ключа реестра' )
else
Registry.WriteInteger( name, value );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
procedure SetIntegerParamL( name, path: string; value: integer );
var
Registry: TRegistry;
begin
Registry := TRegistry.Create( KEY_ALL_ACCESS or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_CURRENT_USER;
try
if not Registry.OpenKey( path, true ) then
raise ERegistryException.Create( 'Ошибка при записи ключа реестра' )
else
Registry.WriteInteger( name, value );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
function GetBoolParam( name, path: string ): boolean;
var
Registry: TRegistry;
begin
Result := false;
Registry := TRegistry.Create( KEY_READ or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
if not Registry.OpenKey( path, CREATE_IFNOTEXIST ) then
raise ERegistryException.Create( 'Ошибка при чтении ключа реестра' )
else
try
Result := Registry.ReadBool( name );
except
// do nothing
end;
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
function GetBoolParam( name, path: string; defValue: boolean ): boolean;
begin
try
Result := GetBoolParam( name, path );
except
Result := defValue;
end;
end;
procedure SetBoolParam( name, path: string; value: boolean );
var
Registry: TRegistry;
begin
Registry := TRegistry.Create( KEY_ALL_ACCESS or KEY_WOW64_32KEY );
Registry.RootKey := HKEY_LOCAL_MACHINE;
try
if not Registry.OpenKey( path, true ) then
raise ERegistryException.Create( 'Ошибка при записи ключа реестра' )
else
Registry.WriteBool( name, value );
finally
try
Registry.CloseKey;
finally
// nothing
end;
FreeAndNil( Registry );
end;
end;
end.
|
unit Tests;
interface
uses
Test;
type
TTests = class
private
count_:Integer;
public
item:array of TTest;
constructor create();
function getCount():integer;
procedure push(test:TTest);
function pop():TTest;
end;
implementation
{ TTests }
constructor TTests.create;
begin
count_:=0;
end;
function TTests.getCount: integer;
begin
result:=count_;
end;
function TTests.pop: TTest;
begin
result:=item[count_-1];
dec(count_);
setLength(item,count_);
end;
procedure TTests.push(test:TTest);
begin
inc(count_);
SetLength(item,count_);
item[count_-1]:=test;
end;
end.
|
unit ZQueryExecutorFactory;
interface
uses
ConnectionInfo,
QueryExecutorFactory,
AbstractQueryExecutorFactory,
ConnectionFactory,
ZConnectionFactory,
QueryExecutor,
SysUtils,
Classes;
type
TZQueryExecutorFactory = class (TAbstractQueryExecutorFactory)
private
procedure ValidateConnectionFactoryType(
ConnectionFactory: IConnectionFactory
);
public
constructor Create(
ConnectionFactory: IConnectionFactory
); overload;
function CreateQueryExecutor(ConnectionInfo: TConnectionInfo): IQueryExecutor; overload; override;
function CreateQueryExecutor(Connection: TObject): IQueryExecutor; overload; override;
end;
implementation
uses
ZConnection,
ZQueryExecutor,
AuxZeosFunctions;
{ TZQueryExecutorFactory }
constructor TZQueryExecutorFactory.Create(
ConnectionFactory: IConnectionFactory
);
begin
inherited Create(ConnectionFactory);
end;
function TZQueryExecutorFactory.CreateQueryExecutor(
Connection: TObject): IQueryExecutor;
begin
if not (Connection is TZConnection)
then begin
raise Exception.CreateFmt(
'Connection'' type isn''t a %s',
[
TZConnection.ClassName
]
);
end;
Result := TZQueryExecutor.Create(TZConnection(Connection));
end;
function TZQueryExecutorFactory.CreateQueryExecutor(
ConnectionInfo: TConnectionInfo
): IQueryExecutor;
var ZConnection: TZConnection;
begin
ZConnection :=
TZConnection(FConnectionFactory.CreateConnection(ConnectionInfo));
Result := CreateQueryExecutor(ZConnection);
end;
procedure TZQueryExecutorFactory.ValidateConnectionFactoryType(
ConnectionFactory: IConnectionFactory);
begin
if not (ConnectionFactory.Self is TZConnectionFactory)
then begin
raise Exception.CreateFmt(
'Type of connection factory isn''t a %s',
[
TZConnectionFactory.ClassName
]
);
end;
end;
end.
|
unit u_Formatacoes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, Buttons, ExtCtrls,DBClient, Mask, Grids,
DBGrids, DB, MaskUtils;
function PadL(Str: String; n : integer):String; overload; {alinhamento para esquerda e completa com espaços a direita}
function PadL(Str: String; n : integer; Add: Char): String; overload; {alinhamento para esquerda e completa com 'Char' a direita}
function StrToStrZero(Str: String; n:integer):String; {alinhamento a direita e completa com zeros a esquerda}
function Repl(Str: String; n : integer):String; {replica um caracter 'n' vezes}
function PadR(Str:String; n : integer):String; overload; {alinhamento para direita e compelta com espaços a esquerda}
function PadR(Str:String; n : integer; Add: Char):String; overload; {Alinhamento para direita e compelta com 'Char' a esquerda}
function SubstituiString(Texto, Old, New: String): String;
function NrOnly(Str:String; NewStr : String = '.'):String; {Retira ponto e virgula}
function TrocaTxt(Str:String; Str1, Str2: Char): String; {Troca Char por Char}
function TiraCharEsp(Str:String):String; {Retira caracteres especiais (acentuados)}
function UpperLower(Str: String):String; {Deixa 1o. caracter de cada Palavra do nome maiusculo e o restante minusculo}
const
// Mascaras usadas em todo fonte
Mask_DDMMYYYY = 'DDMMYYYY';
Mask_YYYYMMDD = 'YYYYMMDD';
Mask_DDMMYY = 'DDMMYY';
Mask_PtFlut = '0.00';
Mask_PtFlut3 = '0.000';
Mask_PtFlut4 = '0.0000';
Mask_PtFlut5 = '0.00000';
Mask_PtFlut6 = '0.000000';
Mask_Decimal = '000000';
Mask_Dolar = '######';
Mask_CpoMaior = '##\.###\.###\/####\-##;0;';
Mask_CpoMenor = '###\.###\.###\-##;0;';
implementation
function PadL(Str: String; n : integer):String; overload;
begin
Result := '';
if Str <> '' then
begin
Str := Trim(Str);
Result := Format('%-'+ intToStr(n)+ '.'+ intToStr(n) + 's', [Str]);
end;
end;
function PadL(Str: String; n : integer; Add: Char): String; overload;
var TamOld, i : integer;
ValNew : String;
begin
ValNew := Trim(Str);
TamOld := Length(ValNew);
for i := (TamOld+1) to n do
ValNew := ValNew + add;
Result := ValNew;
end;
function StrToStrZero(Str: String; n:integer):String;
var
i , tamanho: integer;
aux, Compl: String;
begin
Compl := '';
Aux := Str;
Tamanho := Length(Str);
{Preenche Complemento com Zeros}
for i := 1 to n-tamanho do
Compl := Compl + '0';
{String = Zeros + String}
aux := Compl + aux;
Result := aux;
end;
function Repl(Str: String; n : integer):String;
var i : integer;
begin
Result := '';
for i := 1 to n do
Result := Result + Str;
end;
function PadR(Str:String; n : integer):String; overload;
begin
Str := Trim(Str);
Result := Format('%'+ intToStr(n) + '.' + intToStr(n) + 's', [Str]);
end;
function PadR(Str:String; n : integer; Add: Char):String; overload;
var TamOld, i : integer;
ValNew, Compl : String;
begin
Compl := '';
ValNew := Trim(Str);
TamOld := Length(ValNew);
for i := (TamOld+1) to n do
Compl := Compl + add;
Result := Compl + ValNew;
end;
{function NrOnly(Str:String):String;
const
DSPonto = '.';
DSVirgula = ';';
DSBarra = '-';
var
i, count: integer;
StrNew : String;
begin
StrNew := Str;
Count := Length(Str);
for i := 1 to Count do
if (Pos(DSPonto, StrNew[i])>0) or
(Pos(DSVirgula, StrNew[i])>0) or
(Pos(DSBarra, StrNew[i])>0) then
Delete(StrNew, i, 1);
Result := StrNew;
end;}
function TrocaTxt(Str:String; Str1, Str2: Char): String;
var
i, count: integer;
StrNew: String;
begin
StrNew := Str;
Count := Length(Str);
for i := 1 to Count do
if (Pos(Str1, StrNew[i])>0) then
StrNew[i] := Str2;
Result := StrNew;
end;
function TiraCharEsp(Str:String):String;
const ComAcento = 'àâêôûãõáéíóúçüÀÂÊÔÛÃÕÁÉÍÓÚÇÜ';
SemAcento = 'aaeouaoaeioucuAAEOUAOAEIOUCU';
var
x, Count: Integer;
StrNew: String;
begin
Count := Length(Trim(Str));
StrNew := Trim(Str);
for x := 1 to Count do
if Pos(StrNew[x], ComAcento)>0 then
StrNew[x] := SemAcento[Pos(StrNew[x], ComAcento)];
Result := StrNew;
end;
function UpperLower(Str: String):String;
const
Prep = 'de_dos_da';
var OldStr, NewStr, Palavra: String;
Count, i : integer;
begin
OldStr := TrimLeft(Str)+ ' ';
Count := Length(OldStr)+1;
NewStr := '';
Palavra := '';
for i := 1 to Count do
begin
Palavra := Palavra + OldStr[i];
if (OldStr[i] = ' ') then
begin
if (Pos(Trim(Palavra), Prep)= 0 ) then
NewStr := NewStr + AnsiUpperCase( Copy(Palavra,1,1)) +
AnsiLowerCase(Copy(Palavra, 2, Length(Palavra)))
else
NewStr := NewStr + Palavra;
Palavra := '';
end;
end;
Result := Copy( NewStr,1 , Length(NewStr)-1);
end;
function SubstituiString(Texto, Old, New: String): String;
var I : Integer;
begin
while ( Pos( Old, Texto ) > 0 ) do
begin
i := Pos( Old, Texto );
Delete( Texto, i, 1 );
Insert( New, Texto, i );
end;
Result := Texto;
end;
function NrOnly(Str:String;NewStr : String = '.'):String;
begin
Result := SubstituiString(Str,',',NewStr)
end;
end.
|
unit Zasobnik;
// Tato unita implementuje tridu TORStack, ktera resi zasobnik jizdnich cest pro
// jednu oblast rizeni
// Kazda oblast rizeni ma svuj zasobnik
interface
uses Generics.Collections, Classes, IdContext, SysUtils, UPO;
type
TORStackVolba = (PV = 0, VZ = 1);
// 1 povel v zasobniku
// Z teto abstratni tridy dedi konkretni povely.
TORStackCmd = class abstract
id:Integer;
end;
// povel ke staveni jizdni cesty
TORStackCmdJC = class(TORStackCmd)
JC:TObject;
nouz:boolean;
Pnl:TIDContext;
end;
// povel k zapnuti zadosti o tratovy souhlas
TORStackCmdZTS = class(TORStackCmd)
uvazka:TObject; // TBlkUvazka
end;
// povel k udeleni tratoveho souhlasu
TORStackCmdUTS = class(TORStackCmd)
uvazka:TObject; // TBlkUvazka
end;
TORStack = class
private const
_MAX_STACK_JC = 12;
private
OblR:TObject;
findex:Integer;
fvolba:TORStackVolba;
fhint:string;
stack:TList<TORStackCmd>;
fUPOenabled:boolean;
EZs:TList<TIdContext>; // klienti, kteri maji otevrenou editaci zasobniku
// obsluzne funkce jednotlivych pozadavku z panelu
procedure ORCmdPV(SenderPnl:TIdContext);
procedure ORCmdVZ(SenderPnl:TIdContext);
procedure ORCmdEZ(SenderPnl:TIdContext; show:boolean);
procedure ORCmdRM(SenderPnl:TIdContext; id:Integer);
procedure ORCmdSWITCH(SenderPnl:TIdContext; fromId:Integer; toId:Integer; listend:boolean = false);
procedure ORCmdUPO(SenderPnl:TIdContext);
// zmena volby a hintu
procedure SetVolba(volba:TORStackVolba);
procedure SetHint(hint:string);
procedure SetUPOEnabled(enabled:boolean);
// odeslani seznamu jizdnich cest v zasobniku do prislusne oblasti rizeni
procedure SendList(connection:TIdContext);
procedure RemoveFromStack(index:Integer; SenderPnl:TIDContext = nil);
function GetStackString(cmd:TORStackCmd):string;
function GetCount():Integer;
procedure AddCmd(cmd:TORStackCmd);
procedure ZpracujJC(cmd:TORStackCmdJC);
procedure ZpracujZTS(cmd:TORStackCmdZTS);
procedure ZpracujUTS(cmd:TORStackCmdUTS);
procedure SetFirstEnabled(enabled:boolean);
function FindCmdIndexById(id:Integer):Integer;
public
constructor Create(index:Integer; OblR:TObject);
destructor Destroy(); override;
procedure ParseCommand(SenderPnl:TIdContext; data:TStrings);
procedure AddJC(JC:TObject; SenderPnl:TIDContext; nouz:boolean);
procedure AddZTS(uvazka:TObject; SenderPnl:TIDContext);
procedure AddUTS(uvazka:TObject; SenderPnl:TIDContext);
procedure Update();
procedure NewConnection(SenderPnl:TIdContext);
procedure OnDisconnect(SenderPnl:TIdContext);
procedure OnWriteToRead(SenderPnl:TIdContext);
procedure RemoveJC(JC:TObject); // maze prvni nalezenou cestu - tuto metodu vyuziva jizdni cesta pri dokonceni staveni
procedure RemoveZTS(uvazka:TObject); // maze ZTS pokud je na prvni pozici v zasobniku
procedure RemoveUTS(uvazka:TObject); // maze UTS pokud je na prvni pozici v zasobniku
procedure ClearStack(); // mazani zasobniku je volano pri vypnuti systemu
function GetList():string;
function IsJCInStack(JC:TObject):boolean;
property volba:TORStackVolba read fvolba write SetVolba;
property hint:string read fhint write SetHint;
property UPOenabled:boolean read fUPOenabled write SetUPOEnabled;
property Count:Integer read GetCount;
property firstEnabled:boolean write SetFirstEnabled;
end;//TORStack
implementation
uses TOblRizeni, TCPServerOR, Logging, TechnologieJC, TBlok, TBloky,
TBlokUvazka, TBlokTrat, appEv;
////////////////////////////////////////////////////////////////////////////////
constructor TORStack.Create(index:Integer; OblR:TObject);
begin
inherited Create();
Self.OblR := OblR;
Self.findex := index;
Self.fvolba := TORStackVolba.PV;
Self.UPOenabled := false;
Self.EZs := TList<TIdContext>.Create();
Self.stack := TList<TORStackCmd>.Create();
end;//ctor
destructor TORStack.Destroy();
begin
Self.ClearStack();
Self.stack.Free();
Self.EZs.Free();
inherited Destroy();
end;//dtor
////////////////////////////////////////////////////////////////////////////////
procedure TORStack.ParseCommand(SenderPnl:TIdContext; data:TStrings);
begin
try
data[2] := UpperCase(data[2]);
if (data[2] = 'VZ') then
Self.ORCmdVZ(SenderPnl)
else if (data[2] = 'PV') then
Self.ORCmdPV(SenderPnl)
else if (data[2] = 'EZ') then
begin
if (data[3] = '1') then
Self.ORCmdEZ(SenderPnl, true)
else
Self.ORCmdEZ(SenderPnl, false);
end
else if (data[2] = 'RM') then
Self.ORCmdRM(SenderPnl, StrToInt(data[3]))
else if (data[2] = 'UPO') then
Self.ORCmdUPO(SenderPnl)
else if (data[2] = 'SWITCH') then begin
if (UpperCase(data[4]) = 'END') then
Self.ORCmdSWITCH(SenderPnl, StrToInt(data[3]), 0, true)
else
Self.ORCmdSWITCH(SenderPnl, StrToInt(data[3]), StrToInt(data[4]), false);
end;
except
on e:Exception do
writelog('Server: stack data parse error : '+e.Message, WR_ERROR);
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TORStack.ORCmdPV(SenderPnl:TIdContext);
begin
Self.volba := PV;
end;//procedure
procedure TORStack.ORCmdVZ(SenderPnl:TIdContext);
begin
Self.volba := VZ;
end;//procedure
procedure TORStack.ORCmdEZ(SenderPnl:TIdContext; show:boolean);
begin
if (show) then
begin
if (not Self.EZs.Contains(SenderPnl)) then
Self.EZs.Add(SenderPnl);
Self.SendList(SenderPnl);
end else begin
if (Self.EZs.Contains(SenderPnl)) then
Self.EZs.Remove(SenderPnl);
end;
end;//procedure
procedure TORStack.ORCmdRM(SenderPnl:TIdContext; id:Integer);
var i:Integer;
begin
i := Self.FindCmdIndexById(id);
if (i = -1) then
begin
ORTCPServer.SendInfoMsg(SenderPnl, 'Povel s tímto ID v zásobníku neexistuje!');
Exit();
end;
try
if ((i = 0) and (Self.stack[i].ClassType = TORStackCmdJC) and (((Self.stack[i] as TORSTackCmdJC).JC as TJC).staveni)) then
begin
ORTCPServer.SendInfoMsg(SenderPnl, 'Nelze smazat JC, která se staví');
Exit();
end;
except
end;
Self.RemoveFromStack(i, SenderPnl);
end;//procedure
procedure TORStack.ORCmdSWITCH(SenderPnl:TIdContext; fromId:Integer; toId:Integer; listend:boolean = false);
var i, j:Integer;
tmp:TORStackCmd;
begin
if ((fromId = toId) and (not listend)) then
begin
Self.SendList(SenderPnl);
Exit();
end;
i := Self.FindCmdIndexById(fromId);
if (i = -1) then
begin
ORTCPServer.SendInfoMsg(SenderPnl, 'Povel s výchozím ID v zásobníku neexistuje!');
Exit();
end;
tmp := Self.stack[i];
Self.stack.Delete(i);
try
if (listend) then
begin
Self.stack.Add(tmp);
end else begin
j := Self.FindCmdIndexById(toId);
if (j = -1) then
begin
ORTCPServer.SendInfoMsg(SenderPnl, 'Povel s cílovým ID v zásobníku neexistuje!');
Self.stack.Insert(i, tmp);
Exit();
end;
Self.stack.Insert(j, tmp);
end;
except
Self.stack.Insert(i, tmp);
end;
(Self.OblR as TOR).BroadcastData('ZAS;LIST;'+Self.GetList());
(Self.OblR as TOR).changed := true;
end;
////////////////////////////////////////////////////////////////////////////////
// klik na UPO -> zobrazit upozorneni proc JC nelze postavit
procedure TORStack.ORCmdUPO(SenderPnl:TIdContext);
var cmd:TORStackCmdJC;
begin
if ((Self.stack.Count = 0)) then Exit();
// ted jsou v ceste jen bariery na potvrzeni -> cestu muzu klasicky zacit stavet pres StavJC:
(Self.OblR as TOR).BroadcastData('ZAS;FIRST;0');
Self.UPOenabled := false;
if (Self.stack[0].ClassType = TORStackCmdJC) then begin
cmd := (Self.stack[0] as TORSTackCmdJC);
(cmd.JC as TJC).StavJC(SenderPnl, Self.OblR, Self, cmd.nouz);
end else if (Self.stack[0].ClassType = TORStackCmdZTS) then
((Self.stack[0] as TORStackCmdZTS).uvazka as TBlkUvazka).DoZTS(SenderPnl, Self.OblR)
else if (Self.stack[0].ClassType = TORStackCmdUTS) then
((Self.stack[0] as TORStackCmdZTS).uvazka as TBlkUvazka).DoUTS(SenderPnl, Self.OblR)
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// Pridani obecneho prikazu do zasobniku:
procedure TORStack.AddCmd(cmd:TORStackCmd);
var description:string;
i, max:Integer;
begin
if (Self.stack.Count >= _MAX_STACK_JC) then
begin
writelog('Zásobník OŘ '+(Self.OblR as TOR).id+' - zásobník je plný, nelze přidat další příkaz', WR_STACK);
raise Exception.Create('Zásobník je plný');
end;
max := 0;
for i := 0 to Self.stack.Count-1 do
if (Self.stack[i].id > max) then
max := Self.stack[i].id;
cmd.id := max + 1;
description := Self.GetStackString(cmd);
Self.stack.Add(cmd);
(Self.OblR as TOR).BroadcastData('ZAS;ADD;'+IntToStr(cmd.id)+'|'+description);
writelog('Zásobník OŘ '+(Self.OblR as TOR).id+' - : přidán příkaz ' + description + ', id = '+IntToStr(cmd.id), WR_STACK);
(Self.OblR as TOR).changed := true;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// Pridani jizdni cesty do zasobniku:
procedure TORStack.AddJC(JC:TObject; SenderPnl:TIDContext; nouz:boolean);
var cmd:TORStackCmdJC;
begin
cmd := TORStackCmdJC.Create();
cmd.JC := JC;
cmd.Pnl := SenderPnl;
cmd.nouz := nouz;
try
Self.AddCmd(cmd);
except
on E:Exception do
ORTCPServer.SendInfoMsg(SenderPnl, E.Message);
end;
end;//procedure
// Pridani zdosti o tratovy souhlas do zasobniku
procedure TORStack.AddZTS(uvazka:TObject; SenderPnl:TIDContext);
var cmd:TORStackCmdZTS;
begin
cmd := TORStackCmdZTS.Create();
cmd.uvazka := uvazka;
try
Self.AddCmd(cmd);
except
on E:Exception do
ORTCPServer.SendInfoMsg(SenderPnl, E.Message);
end;
end;//procedure
// Pridani udeleni tratoveho souhlasu do zasobniku:
procedure TORStack.AddUTS(uvazka:TObject; SenderPnl:TIDContext);
var cmd:TORStackCmdUTS;
begin
cmd := TORStackCmdUTS.Create();
cmd.uvazka := uvazka;
try
Self.AddCmd(cmd);
except
on E:Exception do
ORTCPServer.SendInfoMsg(SenderPnl, E.Message);
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TORStack.SetVolba(volba:TORStackVolba);
begin
Self.fvolba := volba;
case (volba) of
PV : begin
(Self.OblR as TOR).BroadcastData('ZAS;PV');
Self.UPOenabled := false;
writelog('Zásobník OŘ '+(Self.OblR as TOR).id+' - PV', WR_STACK);
end;
VZ : begin
(Self.OblR as TOR).BroadcastData('ZAS;VZ');
writelog('Zásobník OŘ '+(Self.OblR as TOR).id+' - VZ', WR_STACK);
end;
end;//case
(Self.OblR as TOR).changed := true;
end;//procedure
procedure TORStack.SetHint(hint:string);
begin
if (hint <> Self.fhint) then
begin
Self.fhint := hint;
(Self.OblR as TOR).BroadcastData('ZAS;HINT;'+hint);
(Self.OblR as TOR).changed := true;
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// tady se resi zpracovani prikazu v zasobniku
procedure TORStack.Update();
begin
if (Self.stack.Count = 0) then Exit();
if (Self.EZs.Count > 0) then Exit();
try
if (Self.stack[0].ClassType = TORStackCmdJC) then
Self.ZpracujJC(Self.stack[0] as TORStackCmdJC)
else if (Self.stack[0].ClassType = TORStackCmdZTS) then
Self.ZpracujZTS(Self.stack[0] as TORStackCmdZTS)
else if (Self.stack[0].ClassType = TORStackCmdUTS) then
Self.ZpracujUTS(Self.stack[0] as TORStackCmdUTS);
except
on e:Exception do
begin
AppEvents.LogException(E, 'Zásobník OŘ '+(Self.OblR as TOR).id+' - update exception, mažu příkaz ze zásobníku');
Self.RemoveFromStack(0);
end;
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TORStack.ZpracujJC(cmd:TORStackCmdJC);
var JC:TJC;
bariery:TJCBariery;
i:Integer;
begin
JC := (cmd.JC as TJC);
if ((JC.staveni) or (Self.volba = TORStackVolba.PV)) then
begin
Self.hint := '';
Exit();
end;
bariery := JC.KontrolaPodminek(cmd.nouz);
if ((bariery.Count > 0) or (cmd.nouz)) then
begin
// v jizdni ceste jsou bariery
if ((bariery.Count > 0) and (TJC.CriticalBariera(bariery[0].typ))) then
begin
// kriticka bariera -> hint := CRIT, kritickou barieru na pozadani zobrazim dispecerovi (pres klik na UPO zasobniku)
Self.hint := 'CRIT';
Self.UPOenabled := true;
Exit();
end;
// tady mame zajisteno, ze v jizdni ceste nejsou kriticke bariery
// (KontrolaPodminek() zarucuje, ze kriticke bariery jsou na zacatku seznamu)
// nyni oznamime nekriticke bariery ktere nemaji upozorneni
for i := 0 to bariery.Count-1 do
begin
if (not JC.WarningBariera(bariery[i].typ)) then
begin
// tyto bariery nelze rozkliknout pomoci UPO
Self.hint := bariery[i].blok.name;
Self.UPOenabled := false;
Exit();
end;
end;//for i
// neupozornovaci bariery nejsou -> podivam se na zbytek barier (ty by mely byt upozornovaci a melo byt se u nich dat kliknout na UPO)
Self.UPOenabled := true;
if ((bariery.Count > 0) and (bariery[0].blok <> nil)) then
Self.hint := bariery[0].blok.name // tohleto si muzeme dovolit, protoze mame zajiteno, ze v JC je alespon jedna bariera (viz podminka vyse)
else
Self.hint := '';
Exit();
end;//if bariery.Count > 0
// zadne bariery -> stavim jizdni cestu
writelog('Zásobník OŘ '+(Self.OblR as TOR).id+' - JC '+JC.nazev+' : podmínky splněny, stavím', WR_STACK);
// pokud nejsou zadne bariery, stavime jizdni cestu
(Self.OblR as TOR).BroadcastData('ZAS;FIRST;0');
JC.StavJC(cmd.Pnl, Self.OblR, Self);
Self.UPOenabled := false;
bariery.Free();
end;//procedure
procedure TORStack.ZpracujZTS(cmd:TORStackCmdZTS);
var uv:TBlkUvazka;
begin
uv := (cmd.uvazka as TBlkUvazka);
Self.hint := (uv as TBlk).name;
if ((Self.volba = TORStackVolba.VZ) and (uv.CanZTS())) then
begin
Self.UPOenabled := (uv.Stitek <> '');
if (uv.Stitek = '') then
begin
uv.zadost := true;
Self.RemoveFromStack(0);
end;
end else begin
Self.UPOenabled := false;
end;
end;//procedure
procedure TORStack.ZpracujUTS(cmd:TORStackCmdUTS);
var uv:TBlkUvazka;
begin
uv := (cmd.uvazka as TBlkUvazka);
Self.hint := (uv as TBlk).name;
if ((Self.volba = TORStackVolba.VZ) and
(not uv.zadost) and ((uv.parent as TBlkTrat).Zadost)) then
begin
Self.UPOenabled := (uv.Stitek <> '');
if (uv.Stitek = '') then
begin
uv.UdelSouhlas();
Self.RemoveFromStack(0);
end;
end else begin
Self.UPOenabled := false;
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// odeslani cest v zasobniku
// format dat: {id|name}{id|name} ...
procedure TORStack.SendList(connection:TIdContext);
begin
ORTCPServer.SendLn(connection, (Self.OblR as TOR).id+';ZAS;LIST;'+Self.GetList());
end;//procedure
function TORStack.GetList():string;
var i:Integer;
begin
if ((Self.stack.Count > 0) and (Self.stack[0].ClassType = TORStackCmdJC) and
(not ((Self.stack[0] as TORStackCmdJC).JC as TJC).staveni)) then
Result := '1;'
else
Result := '0;';
for i := 0 to Self.stack.Count-1 do
Result := Result + '[' + IntToStr(Self.stack[i].id) + '|' + Self.GetStackString(Self.stack[i]) + ']';
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TORStack.ClearStack();
var cmd:TORStackCmd;
begin
for cmd in Self.stack do
cmd.Free();
Self.stack.Clear();
Self.EZs.Clear();
(Self.OblR as TOR).BroadcastData('ZAS;LIST;1;;');
Self.hint := '';
Self.UPOenabled := false;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TORStack.NewConnection(SenderPnl:TIdContext);
begin
ORTCPServer.SendLn(SenderPnl, (Self.OblR as TOR).id+';ZAS;INDEX;'+IntToStr(Self.findex));
case (Self.volba) of
PV : ORTCPServer.SendLn(SenderPnl, (Self.OblR as TOR).id+';ZAS;PV');
VZ : ORTCPServer.SendLn(SenderPnl, (Self.OblR as TOR).id+';ZAS;VZ');
end;
ORTCPServer.SendLn(SenderPnl, (Self.OblR as TOR).id+';ZAS;HINT;'+Self.hint);
if (Self.UPOenabled) then
ORTCPServer.SendLn(SenderPnl, (Self.OblR as TOR).id+';ZAS;UPO;1')
else
ORTCPServer.SendLn(SenderPnl, (Self.OblR as TOR).id+';ZAS;UPO;0');
Self.SendList(SenderPnl);
end;//procedure
procedure TORStack.OnDisconnect(SenderPnl:TIdContext);
begin
if (Self.EZs.Contains(SenderPnl)) then
Self.EZs.Remove(SenderPnl);
end;
procedure TORStack.OnWriteToRead(SenderPnl:TIdContext);
begin
if (Self.EZs.Contains(SenderPnl)) then
Self.EZs.Remove(SenderPnl);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TORStack.RemoveJC(JC:TObject);
var i:Integer;
begin
for i := 0 to Self.stack.Count-1 do
if ((Self.stack[i].ClassType = TORStackCmdJC) and ((Self.stack[i] as TORStackCmdJC).JC = JC)) then
begin
writelog('Zásobník OŘ '+(Self.OblR as TOR).id+' - JC '+((Self.stack[i] as TORStackCmdJC).JC as TJC).nazev+
' : smazána ze zásobníku, id = '+IntToStr(Self.stack[i].id), WR_STACK);
Self.RemoveFromStack(i);
Exit();
end;
end;//procedure
procedure TORStack.RemoveZTS(uvazka:TObject);
begin
if ((Self.stack.Count > 0) and (Self.stack[0].ClassType = TORStackCmdZTS) and
((Self.stack[0] as TORStackCmdZTS).uvazka = uvazka)) then
Self.RemoveFromStack(0);
end;
procedure TORStack.RemoveUTS(uvazka:TObject);
begin
if ((Self.stack.Count > 0) and (Self.stack[0].ClassType = TORStackCmdUTS) and
((Self.stack[0] as TORStackCmdUTS).uvazka = uvazka)) then
Self.RemoveFromStack(0);
end;
////////////////////////////////////////////////////////////////////////////////
function TORStack.IsJCInStack(JC:TObject):boolean;
var i:Integer;
begin
for i := 0 to Self.stack.Count-1 do
if ((Self.stack[i].ClassType = TORStackCmdJC) and ((Self.stack[i] as TORStackCmdJC).JC = JC)) then
Exit(true);
Result := false;
end;//function
////////////////////////////////////////////////////////////////////////////////
procedure TORStack.SetUPOEnabled(enabled:boolean);
begin
if (Self.fUPOenabled = enabled) then Exit();
if (enabled) then
(Self.OblR as TOR).BroadcastData('ZAS;UPO;1')
else
(Self.OblR as TOR).BroadcastData('ZAS;UPO;0');
Self.fUPOenabled := enabled;
end;//procedure
///////////////////////////////////////////////////////////////////////////////
procedure TORStack.RemoveFromStack(index:Integer; SenderPnl:TIDContext = nil);
begin
if (index < Self.stack.Count) then
begin
(Self.OblR as TOR).BroadcastData('ZAS;RM;'+IntToStr(Self.stack[index].id));
Self.stack.Delete(index);
Self.hint := '';
end;
if (index = 0) then
Self.UPOenabled := false;
if (Self.stack.Count = 0) then
Self.EZs.Clear();
(Self.OblR as TOR).changed := true;
end;//procedure
///////////////////////////////////////////////////////////////////////////////
function TORStack.GetStackString(cmd:TORStackCmd):string;
begin
try
if (cmd.ClassType = TORStackCmdJC) then
begin
if ((cmd as TORStackCmdJC).nouz) then
Result := 'NC '+ ((cmd as TORStackCmdJC).JC as TJC).nazev
else
case (((cmd as TORStackCmdJC).JC as TJC).data.TypCesty) of
TJCType.vlak : Result := 'VC '+ ((cmd as TORStackCmdJC).JC as TJC).nazev;
TJCType.posun : Result := 'PC '+ ((cmd as TORStackCmdJC).JC as TJC).nazev;
end;//case
end
else if (cmd.ClassType = TORStackCmdZTS) then
begin
Result := 'ZTS ' + ((cmd as TORStackCmdZTS).uvazka as TBlk).name;
end
else if (cmd.ClassType = TORStackCmdUTS) then
begin
Result := 'UTS ' + ((cmd as TORStackCmdUTS).uvazka as TBlk).name;
end;
except
Result := 'neexistující příkaz';
end;
end;//function
///////////////////////////////////////////////////////////////////////////////
function TORStack.GetCount():Integer;
begin
Result := Self.stack.Count;
end;//function
///////////////////////////////////////////////////////////////////////////////
procedure TORStack.SetFirstEnabled(enabled:boolean);
begin
if (enabled) then
(Self.OblR as TOR).BroadcastData('ZAS;FIRST;1')
else
(Self.OblR as TOR).BroadcastData('ZAS;FIRST;0');
end;
///////////////////////////////////////////////////////////////////////////////
function TORStack.FindCmdIndexById(id:Integer):Integer;
var i:Integer;
begin
for i := 0 to Self.stack.Count-1 do
if (Self.stack[i].id = id) then
Exit(i);
Result := -1;
end;
///////////////////////////////////////////////////////////////////////////////
end.//unit
|
(*
Copyright (c) 2011-2013, Stefan Glienke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of this library nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
unit DSharp.Testing.Mock.Setup;
interface
uses
DSharp.Testing.Mock.Interfaces,
SysUtils;
type
Setup<T> = record
private
FSetup: ISetup<T>;
public
class operator Implicit(const Value: ISetup<T>): Setup<T>;
function WillExecute: IExpectInSequence<T>; overload;
function WillExecute(const Action: TMockAction): IExpectInSequence<T>; overload;
function WillRaise(const ExceptionClass: ExceptClass;
const Msg: string = ''): IExpectInSequence<T>; overload;
function WillRaise(const ExceptionClass: ExceptClass; const Msg: string;
const Args: array of const): IExpectInSequence<T>; overload;
function WillReturn<TResult>(const Value: TResult): IExpectInSequence<T>;
end;
implementation
uses
Rtti;
{ Setup<T> }
class operator Setup<T>.Implicit(const Value: ISetup<T>): Setup<T>;
begin
Result.FSetup := Value;
end;
function Setup<T>.WillExecute: IExpectInSequence<T>;
begin
Result := FSetup.WillExecute(nil);
end;
function Setup<T>.WillExecute(const Action: TMockAction): IExpectInSequence<T>;
begin
Result := FSetup.WillExecute(Action);
end;
function Setup<T>.WillRaise(const ExceptionClass: ExceptClass;
const Msg: string): IExpectInSequence<T>;
begin
Result := FSetup.WillRaise(
function: Exception
begin
Result := ExceptionClass.Create(Msg);
end);
end;
function Setup<T>.WillRaise(const ExceptionClass: ExceptClass;
const Msg: string; const Args: array of const): IExpectInSequence<T>;
var
LMsg: string;
begin
LMsg := Format(Msg, Args);
Result := FSetup.WillRaise(
function: Exception
begin
Result := ExceptClass.Create(LMsg);
end);
end;
function Setup<T>.WillReturn<TResult>(const Value: TResult): IExpectInSequence<T>;
begin
Result := FSetup.WillReturn(TValue.From<TResult>(Value));
end;
end.
|
program generadorDeArchivosDat;
uses sysutils;
TYPE intFile = FILE OF INTEGER;
rFile = FILE OF REAL;
chFile = FILE OF CHAR;
function validFileName(name:string):boolean;
begin
if (pos('.',name)) <> 0
then validFileName := True
else validFileName := False
end;
VAR userTypeChoise, fileName: String;
userIntValue: Integer;
userRealValue: Real;
userCharValue: Char;
integerFile: intFile;
realFile: rFile;
charFile: chFile;
userDecision: char;
begin
repeat //Repeat until user stops
repeat
write('Seleccione tipo de archivo(Integer, Real, Char): '); readln(userTypeChoise);
until (userTypeChoise = 'integer') or (userTypeChoise = 'Integer') or (userTypeChoise = 'real')
or (userTypeChoise = 'Real') or (userTypeChoise = 'char') or (userTypeChoise = 'Char');
repeat
write('Elija un nombre para el archivo(nombre.extension): ');readln(fileName);
until validFileName(fileName);
if not DirectoryExists('ArchivosCreados')
then CreateDir('ArchivosCreados');
writeln('El archivo se creara en la carpeta "ArchivosCreados"');
writeln();
case userTypeChoise of
'integer','Integer': begin
assign(integerFile,concat('ArchivosCreados/', fileName));
rewrite(integerFile);
write('Ingresa los valores que quieras separados por espacios: ');
repeat
read(userIntValue);
write(integerFile, userIntValue);
until eoln();
close(integerFile);
writeln('El archivo ',fileName,' fue creado.');
end;
'real','Real': begin
assign(realFile,concat('ArchivosCreados/', fileName));
rewrite(realFile);
write('Ingresa los valores que quieras separados por espacios: ');
repeat
read(userRealValue);
write(realFile, userRealValue);
until eoln();
close(realFile);
writeln('El archivo ',fileName,' fue creado.');
end;
'char','Char': begin
assign(charFile,concat('ArchivosCreados/', fileName));
rewrite(charFile);
write('Ingresa los valores que quieras separados por espacios: ');
repeat
read(userCharValue);
write(charFile, userCharValue);
until eoln();
close(charFile);
writeln('El archivo ',fileName,' fue creado.');
end;
end;
readln();
writeln();
repeat
write('Desea crear otro archivo ?(S / N): ');readln(userDecision);
until (userDecision = 'S') or (userDecision = 'N');
until userDecision = 'N' ;
end.
|
Program intuition_events;
{$IFNDEF HASAMIGA}
{$FATAL This source is compatible with Amiga, AROS and MorphOS only !}
{$ENDIF}
{$MODE OBJFPC}{$H+}{$HINTS ON}
{$UNITPATH ../../../Base/CHelpers}
{$UNITPATH ../../../Base/Trinity}
{
===========================================================================
Project : intuition_events
Topic : Event handling
Author : The AROS Development Team.
Source : http://www.aros.org/documentation/developers/samplecode/intuition_events.c
===========================================================================
This example was originally written in c by The AROS Development Team.
The original examples are available online and published at the AROS
website (http://www.aros.org/documentation/developers/samples.php)
Free Pascal sources were adjusted in order to support the following targets
out of the box:
- Amiga-m68k, AROS-i386 and MorphOS-ppc
In order to accomplish that goal, some use of support units is used that
aids compilation in a more or less uniform way.
Conversion from c to Free Pascal was done by Magorium in 2015.
===========================================================================
Unless otherwise noted, these examples must be considered
copyrighted by their respective owner(s)
===========================================================================
}
{*
Example for event handling of intuition windows
*}
Uses
exec, agraphics, intuition, utility,
{$IFDEF AMIGA}
systemvartags,
{$ENDIF}
chelpers,
trinity;
var
window : pWindow;
procedure clean_exit(const s: STRPTR); forward;
procedure handle_events; forward;
function Main: Integer;
begin
window := OpenWindowTags(nil,
[
TAG_(WA_Left) , 400,
TAG_(WA_Top) , 70,
TAG_(WA_InnerWidth) , 300,
TAG_(WA_InnerHeight) , 300,
TAG_(WA_Title) , TAG_(PChar('Intuition events')),
TAG_(WA_Activate) , TAG_(TRUE),
TAG_(WA_RMBTrap) , TAG_(TRUE), // handle right mouse button as normal mouse button
TAG_(WA_CloseGadget) , TAG_(TRUE),
TAG_(WA_DragBar) , TAG_(TRUE),
TAG_(WA_GimmeZeroZero) , TAG_(TRUE),
TAG_(WA_DepthGadget) , TAG_(TRUE),
TAG_(WA_NoCareRefresh) , TAG_(TRUE), // we don't want to listen to refresh messages
TAG_(WA_IDCMP) , TAG_(IDCMP_CLOSEWINDOW or IDCMP_MOUSEBUTTONS or IDCMP_VANILLAKEY or IDCMP_RAWKEY),
TAG_END
]);
if not assigned(window) then clean_exit('Can''t open window' + LineEnding);
WriteLn(LineEnding, 'Press "r" to disable VANILLAKEY');
handle_events();
clean_exit(nil);
result := 0;
end;
procedure handle_events;
var
imsg : pIntuiMessage;
port : pMsgPort;
signals : ULONG;
iclass : ULONG;
code : UWORD;
qualifier : UWORD;
mousex, mousey : SmallInt;
terminated : boolean;
begin
port := window^.userPort;
terminated := false;
while not(terminated) do
begin
signals := Wait(1 shl port^.mp_SigBit);
while (SetAndGet(imsg, GetMsg(port)) <> nil) do
begin
iclass := imsg^.IClass;
code := imsg^.Code;
qualifier := imsg^.Qualifier;
mousex := imsg^.MouseX;
mousey := imsg^.MouseY;
{*
After we have stored the necessary values from the message
in variables we can immediately reply the message. Note
that this is only possible because we have no VERIFY events.
*}
ReplyMsg(pMessage(imsg));
Case IClass of
IDCMP_CLOSEWINDOW :
begin
WriteLn('IDCMP_CLOSEWINDOW');
terminated := true;
end;
IDCMP_MOUSEBUTTONS:
begin
case (code) of
SELECTDOWN: Write('left mouse button down');
SELECTUP: Write('left mouse button up');
MENUDOWN: Write('right mouse button down');
MENUUP: Write('right mouse button up');
MIDDLEDOWN: Write('middle mouse button down');
MIDDLEUP: Write('middle mouse button up');
end;
WriteLn(' at ', mousex, ' ', mousey);
end;
IDCMP_VANILLAKEY:
begin
WriteLn('Vanillakey ', code, ' ', WideChar(code));
if (WideChar(code) = 'r') then
begin
// ModifyIDCMP(window, window^.IDCMPFlags &= ~IDCMP_VANILLAKEY);
ModifyIDCMP(window, window^.IDCMPFlags and not (IDCMP_VANILLAKEY));
WriteLn('RAWKEY only');
end;
end;
IDCMP_RAWKEY:
begin
WriteLn('Rawkey ', code, ' ', WideChar(code));
end;
end;
end;
end;
end;
procedure clean_exit(const s: STRPTR);
begin
if assigned(s) then WriteLn(s);
// Give back allocated resourses
if assigned(window) then CloseWindow(window);
Halt(0);
end;
{
===========================================================================
Some additional code is required in order to open and close libraries in a
cross-platform uniform way.
Since AROS units automatically opens and closes libraries, this code is
only actively used when compiling for Amiga and/or MorphOS.
===========================================================================
}
Function OpenLibs: boolean;
begin
Result := False;
{$IF DEFINED(MORPHOS) or DEFINED(AMIGA)}
GfxBase := OpenLibrary(GRAPHICSNAME, 0);
if not assigned(GfxBase) then Exit;
{$ENDIF}
{$IF DEFINED(MORPHOS)}
IntuitionBase := OpenLibrary(INTUITIONNAME, 0);
if not assigned(IntuitionBase) then Exit;
{$ENDIF}
Result := True;
end;
Procedure CloseLibs;
begin
{$IF DEFINED(MORPHOS)}
if assigned(IntuitionBase) then CloseLibrary(pLibrary(IntuitionBase));
{$ENDIF}
{$IF DEFINED(MORPHOS) or DEFINED(AMIGA)}
if assigned(GfxBase) then CloseLibrary(pLibrary(GfxBase));
{$ENDIF}
end;
begin
if OpenLibs
then ExitCode := Main()
else ExitCode := 10;
CloseLibs;
end.
|
unit core_pathfinding;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fgl, VectorGeometry,core_types, core_chunk,
graphics, VectorTypes,astar3d_pathFinder,
astar3d_point3d, astar3d_breadCrumb,core_listofrecords,
core_orders_manager,core_orders;
//right
{concept: unit requires a path to target. path manager calculates route and
stores result for next call in a map. }
type
//maps actor indexes to path search result
TPathMap = specialize TFPGMap<integer,TPath>;
TNeededPaths = specialize TFPGMap<integer,TStartFinish>;
{ TPathManager }
TPathManager = class
private
{ TSearchThread }
type
TSearchThread = class (TThread)
paused:boolean;
procedure Execute; override;
function findPathStar3D(ab: TStartFinish): TPath;
Constructor Create(CreateSuspended : boolean);
end;
protected
thread:TSearchThread;
neededPaths:TNeededPaths;
function findPathJPS(A,B:TAffineVector;const filename:string):boolean;
public
paths:TPathMap;
function getNextPoint(actorID:integer):TAffineVector;
function findPath(actorID: integer; start, finish: TAffineVector;
flyngAlilowed, iisJobSearch: boolean): TAffineVector;
//i guess when actor is destroyed his path may be freed
procedure freePath(actorID:integer);
//save map slice to a bitmap
procedure saveSlice(yLevel:integer);
procedure update;
constructor create;
destructor destroy;
end;
var
pathManager:TPathManager;
implementation
var
currentSearch:record
ab:TStartFinish;
actorID:integer;
finished:boolean;
end;
pathFinderStar:TPathFinder;
foundPaths:TPathMap;
{ TPathManager.TSearchThread }
procedure TPathManager.TSearchThread.Execute;
begin
while not Terminated do begin
if paused then begin
sleep(100);
continue;
end;
//first shoult try and find straight line?
foundPaths.Add(currentSearch.actorID,findPathStar3D(currentSearch.ab));
currentSearch.finished:=true;
paused:=true;
end;
end;
function TPathManager.TSearchThread.findPathStar3D(ab: TStartFinish):TPath;
var
pos:TVector3i;
path:TSearchNode;
a,b:tpoint3d;
listLength:integer;
begin
a:=vector3imake(
ab.start[0]+world_width2,
ab.start[1],
ab.start[2]+world_depth2);
b:=vector3imake(
ab.finish[0]+world_width2,
ab.finish[1],
ab.finish[2]+world_depth2);
path:=pathFinderStar.FindPathList(a,b,ab.flyngAllowed,ab.isJobSearch,listLength);
result:=nil;
if path<>nil then begin
result:=TPath.create(path,listLength);
//result.free;
end;
//debug draw
{
if path<>nil then
while (path.fnext <> nil) do
begin
//oM.addOrder(orCreateJobArea,jtDig,random(999999),);
//log(('Route: ' + path.next.position.ToString));
pos:=(path.fnext.position);
//pos[1]:=chunk_height-pos[1];
setBlockAt(pos,btOxy9,true);
path := path.fnext;
end;
}
end;
constructor TPathManager.TSearchThread.Create(CreateSuspended: boolean);
begin
inherited create(CreateSuspended);
FreeOnTerminate:=false;
paused:=true;
end;
{ TPathManager }
function TPathManager.getNextPoint(actorID: integer): TAffineVector;
begin
//if by accident path doesn't exist then add
end;
function TPathManager.findPath(actorID: integer; start, finish: TAffineVector;
flyngAlilowed, iisJobSearch: boolean): TAffineVector;
var p,b:TStartFinish;
begin
//if path request already exists then swap
if neededPaths.IndexOf(actorID)>-1 then begin
p.fromVectors(start,finish);
neededPaths[actorID]:=p;
end else begin
b:=p.fromVectors(start,finish);
b.flyngAllowed:=flyngAlilowed;
b.isJobSearch:=iisJobSearch;
neededPaths.Add(actorID,b);
end;
//thread.paused:=false;
end;
function TPathManager.findPathJPS(A, B: TAffineVector; const filename: string
): boolean;
begin
result:=true;
end;
procedure TPathManager.freePath(actorID: integer);
begin
{ TODO -cwazne : niechaj path sie usuwa z pathmanagera kiedy aktor ginie }
paths[actorID].free;
paths.Remove(actorID);
end;
procedure TPathManager.saveSlice(yLevel: integer);
var
i,j,x,y,z,w,h:integer;
groundBlok,midBlok,topBlok:eblockTypes;
bmp:tbitmap;
col:tcolor;
begin
bmp:=tbitmap.create;
bmp.SetSize(world_width,world_depth);
for x:=0 to world_width-1 do
for z:=0 to world_depth-1 do begin
col:=clGreen;
groundBlok:=eblockTypes(chunksPointer^[x div chunk_width,z div chunk_width].blocks[
x mod chunk_width,ylevel,z mod chunk_width]);
midBlok:=eblockTypes(chunksPointer^[x div chunk_width,z div chunk_width].blocks[
x mod chunk_width,ylevel+2,z mod chunk_width]);
topBlok:=eblockTypes(chunksPointer^[x div chunk_width,z div chunk_width].blocks[
x mod chunk_width,ylevel+3,z mod chunk_width]);
if (groundBlok<>btNone) and (midBlok<>btNone) then col:=clRed;
bmp.canvas.Pixels[x,z]:=col;
end;
bmp.SaveToFile(appPath+'slice.bmp');
bmp.free;
end;
procedure TPathManager.update;
var ind:integer;
begin
//path search thread finished processing
if currentSearch.finished then begin
//move path from found list to public list
//ind:=-1;
if paths.IndexOf(currentSearch.actorID)>-1 then begin
paths[currentSearch.actorID].free;
paths.remove(currentSearch.actorID);
//paths[currentSearch.actorID].free;
//paths[currentSearch.actorID]:=foundPaths[currentSearch.actorID];
paths.Add(currentSearch.actorID,foundPaths[currentSearch.actorID]);
end else
ind:=paths.Add(currentSearch.actorID,foundPaths[currentSearch.actorID]);
foundPaths.Remove(currentSearch.actorID);
currentSearch.finished:= false;
oM.addOrder2i(orPathFound,currentSearch.actorID,ind);
thread.paused:=true;
end else
if (thread.paused) and (neededPaths.count>0) and (not currentSearch.finished) then begin
currentSearch.ab:=neededPaths.Data[0];
currentSearch.actorID:=neededPaths.Keys[0];
neededPaths.Delete(0);
thread.paused:=false;
end;
end;
constructor TPathManager.create;
begin
paths:=TPathMap.Create;
paths.Duplicates:=TDuplicates.dupError;
neededPaths:=TNeededPaths.create;
foundPaths:=TPathMap.Create;
pathFinderStar:=TPathFinder.create;
thread:=tsearchthread.Create(false);
end;
destructor TPathManager.destroy;
var
i:integer;
p,n:tsearchnode;
begin
//will self terminate after search is done so wait for it
thread.paused:=true;
thread.Terminate;
thread.WaitFor;
thread.Free;
// thread.WaitFor;
for i:=0 to paths.Count-1 do paths.Data[i].free;
paths.Destroy;
neededPaths.Destroy;
for i:=0 to foundPaths.Count-1 do foundPaths.Data[i].destroy;
foundPaths.Destroy;
pathFinderStar.Destroy;
end;
end.
|
{
FormUtil
Position speichern und laden
xx/xxxx FPC Ubuntu
--------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY
Author: Peter Lorenz
Is that code useful for you? Donate!
Paypal webmaster@peter-ebe.de
--------------------------------------------------------------------
}
{$I ..\share_settings.inc}
unit formutil_unit;
interface
uses
{$IFDEF FPC}
{$IFNDEF UNIX}Windows, {$ENDIF}
Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, ExtCtrls, IniFiles;
{$ELSE}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes,
IniFiles, Vcl.Forms;
{$ENDIF}
procedure ReadFormPos(const konfig: string; Form: TForm;
defaultwidth, defaultheight: Integer; noFormSize: Boolean);
procedure WriteFormPos(const konfig: string; Form: TForm);
implementation
const
csForm: string = 'FORM_';
csWindowState: string = 'WINDOWSTATE';
csMonitor: string = 'MONITOR';
csTop: string = 'TOP';
csLeft: string = 'LEFT';
csHeightScaled: string = 'HEIGHT_SCALED';
csWidthScaled: string = 'WIDTH_SCALED';
csHeight: string = 'HEIGHT';
csWidth: string = 'WIDTH';
csDPI: string = 'DPI';
csScaled: string = 'SCALED';
procedure CheckFormPos(Form: TForm; MonitorNum: Integer);
var
Monitor: TMonitor;
begin
if (MonitorNum >= 0) and (MonitorNum <= Screen.MonitorCount - 1) then
Monitor := Screen.Monitors[MonitorNum]
else
Monitor := Screen.PrimaryMonitor;
// Größe
// if Form.Width > Monitor.WorkareaRect.Width then Form.Width:= Monitor.WorkareaRect.Width;
// if Form.Height > Monitor.WorkareaRect.Height then Form.Height:= Monitor.WorkareaRect.Height;
// Position (links/oben)
if Form.Left < Monitor.WorkareaRect.Left then
Form.Left := Monitor.WorkareaRect.Left;
if Form.Top < Monitor.WorkareaRect.Top then
Form.Top := Monitor.WorkareaRect.Top;
// Position (rechts/unten)
if Form.Left + Form.Width > Monitor.WorkareaRect.Left + Monitor.WorkareaRect.Width
then
Form.Left := Monitor.WorkareaRect.Left + Monitor.WorkareaRect.Width -
Form.Width;
if Form.Top + Form.Height > Monitor.WorkareaRect.Top + Monitor.WorkareaRect.Height
then
Form.Top := Monitor.WorkareaRect.Top + Monitor.WorkareaRect.Height -
Form.Height;
end;
procedure ReadFormPos(const konfig: string; Form: TForm;
defaultwidth, defaultheight: Integer; noFormSize: Boolean);
var
ini: TIniFile;
MonitorNum: Integer;
Monitor: TMonitor;
// Reset: Boolean;
begin
ini := nil;
MonitorNum := Screen.PrimaryMonitor.MonitorNum;
try
ini := TIniFile.Create(konfig);
MonitorNum := ini.ReadInteger(csForm + Form.Name, csMonitor,
Screen.PrimaryMonitor.MonitorNum);
if (MonitorNum >= 0) and (MonitorNum <= Screen.MonitorCount - 1) then
Monitor := Screen.Monitors[MonitorNum]
else
Monitor := Screen.PrimaryMonitor;
if ini.ReadInteger(csForm + Form.Name, csWindowState, Integer(wsNormal))
= Integer(wsMaximized) then
begin
Form.WindowState := wsMaximized;
end
else
begin
// Reset := (ini.ReadInteger(csForm + Form.Name, csDPI, Form.PixelsPerInch) <> Form.PixelsPerInch);
// or (ini.ReadBool(csForm + Form.Name, csScaled, Form.Scaled) <> Form.Scaled);
if noFormSize then // or Reset then
begin
Form.Height := defaultheight;
Form.Width := defaultwidth;
end
else
begin
if Form.Scaled then
begin
Form.Height := ini.ReadInteger(csForm + Form.Name, csHeightScaled,
trunc(defaultheight * Form.Monitor.PixelsPerInch / Form.PixelsPerInch));
Form.Width := ini.ReadInteger(csForm + Form.Name, csWidthScaled,
trunc(defaultwidth * Form.Monitor.PixelsPerInch / Form.PixelsPerInch));
end
else
begin
Form.Height := ini.ReadInteger(csForm + Form.Name, csHeight,
defaultheight);
Form.Width := ini.ReadInteger(csForm + Form.Name, csWidth,
defaultwidth);
end;
end;
Form.Top := ini.ReadInteger(csForm + Form.Name, csTop, 100);
Form.Left := ini.ReadInteger(csForm + Form.Name, csLeft, 100);
end;
finally
FreeAndNil(ini);
CheckFormPos(Form, MonitorNum);
end;
end;
procedure WriteFormPos(const konfig: string; Form: TForm);
var
ini: TIniFile;
begin
ini := nil;
try
ini := TIniFile.Create(konfig);
ini.WriteInteger(csForm + Form.Name, csWindowState,
Integer(Form.WindowState));
ini.WriteInteger(csForm + Form.Name, csMonitor, Form.Monitor.MonitorNum);
ini.WriteInteger(csForm + Form.Name, csTop, Form.Top);
ini.WriteInteger(csForm + Form.Name, csLeft, Form.Left);
if Form.Scaled then
begin
ini.WriteInteger(csForm + Form.Name, csHeightScaled, Form.Height);
ini.WriteInteger(csForm + Form.Name, csWidthScaled, Form.Width);
end
else
begin
ini.WriteInteger(csForm + Form.Name, csHeight, Form.Height);
ini.WriteInteger(csForm + Form.Name, csWidth, Form.Width);
end;
ini.WriteInteger(csForm + Form.Name, csDPI, Form.PixelsPerInch);
ini.WriteBool(csForm + Form.Name, csScaled, Form.Scaled);
finally
FreeAndNil(ini);
end;
end;
end.
|
unit IdTestTrivialFTP;
interface
uses
IdTest,
IdObjs,
IdSys,
IdGlobal,
IdTrivialFTP,
IdTrivialFTPServer;
type
TIdTestTrivialFTP = class(TIdTest)
private
procedure CallbackReadFile(Sender: TObject; var FileName: String; const PeerInfo: TPeerInfo;
var GrantAccess: Boolean; var AStream: TIdStream; var FreeStreamOnComplete: Boolean);
published
procedure TestBasic;
end;
implementation
const
cFile='file.txt';
cContent='12345';
procedure TIdTestTrivialFTP.CallbackReadFile(Sender: TObject;
var FileName: String; const PeerInfo: TPeerInfo;
var GrantAccess: Boolean; var AStream: TIdStream;
var FreeStreamOnComplete: Boolean);
begin
if FileName=cFile then
begin
AStream:=TIdStringStream.Create(cContent);
end;
end;
procedure TIdTestTrivialFTP.TestBasic;
var
c:TIdTrivialFTP;
s:TIdTrivialFTPServer;
aStream:TIdMemoryStream;
aContent:string;
begin
c:=TIdTrivialFTP.Create;
s:=TIdTrivialFTPServer.Create;
aStream:=TIdMemoryStream.Create;
try
s.OnReadFile:=Self.CallbackReadFile;
//set ThreadedEvent, else theres a deadlock because we do a blocking read soon
s.ThreadedEvent:=True;
s.Active:=True;
c.ReceiveTimeout:=1000;
c.Get(cFile,aStream);
aStream.Position:=0;
aContent:=ReadStringFromStream(aStream);
Assert(aContent=cContent);
finally
sys.FreeAndNil(aStream);
Sys.FreeAndNil(c);
Sys.FreeAndNil(s);
end;
end;
initialization
TIdTest.RegisterTest(TIdTestTrivialFTP);
end.
|
unit ChainOfResponsibility.Clients.Client;
interface
uses
ChainOfResponsibility.AbstractClasses.AbstractHandler;
type
TClient = class
public
class procedure ClientCode(AHandler: TAbstractHandler);
end;
implementation
uses
System.Generics.Collections, ChainOfResponsibility.Util.StringClass,
ChainOfResponsibility.Util.Utils;
{ TClient }
class procedure TClient.ClientCode(AHandler: TAbstractHandler);
var
oList: TList<TString>;
oString: TString;
oResult: TObject;
I: Integer;
begin
oList := TList<TString>.Create;
try
oList.Add(TString.New('Nut'));
oList.Add(TString.New('Banana'));
oList.Add(TString.New('Cup of coffee'));
for oString in oList do
begin
// grava log says 'Client: Who wants a ' + oString.Str + '?'
TUtilsSingleton.WriteLog('Who wants a ' + oString.Str + ' ?');
oResult := AHandler.Handle(oString);
if oResult <> nil then
TUtilsSingleton.WriteLog(TString(oResult))
else
TUtilsSingleton.WriteLog
(TString.New(oString.Str + ' was left untouched.'));
end;
finally
for I := 0 to Pred(oList.Count) do
oList[I].Free;
oList.Free;
end;
end;
end.
|
unit Unit2;
interface
type
TNumDivisor = class
private
FNumero: integer;
procedure SetNumero(const Value: integer);
public
function GetNumeroDivisores() : Integer;
published
property Numero : integer read FNumero write SetNumero;
end;
TNumPrimo = class(TNumDivisor)
public
function IsNumeroPrimo : boolean;
end;
implementation
{ TNumDivisor }
function TNumDivisor.GetNumeroDivisores: Integer;
var
I: Integer;
begin
Result := 0;
for I := 1 to FNumero do
begin
if ((FNumero mod I) = 0) then
begin
inc(Result);
end;
end;
end;
procedure TNumDivisor.SetNumero(const Value: integer);
begin
FNumero := Value;
end;
{ TNumPrimo }
function TNumPrimo.IsNumeroPrimo: boolean;
begin
Result := GetNumeroDivisores() = 2;
end;
end.
|
unit MyMenu;
interface
uses GraphABC,MyButton;
type
Menu = class
x: integer := 0;
y: integer := 0;
padding: integer := 35;
buttons: array of MyButton.button;
constructor Create();
procedure AddButton(actionProc: procedure; texturePath: string; textureFocusPath: string);
procedure Render();
procedure Update(x: integer; y: integer);
procedure MoveFocusUp();
procedure MoveFocusDown();
procedure ActionActiveButton();
function Width(): integer;
function Heigth(): integer;
function GetFocusedButtonIndex():integer;
end;
implementation
constructor Menu.Create();
begin
SetLength(buttons, 0);
end;
//Procedure
procedure Menu.AddButton(actionProc: procedure; texturePath: string; textureFocusPath: string);
begin
var button := new MyButton.button(actionProc, texturePath, textureFocusPath);
if buttons.Length = 0 then begin
button.focus := true;
end;
SetLength(buttons, buttons.Length + 1);
buttons[buttons.Length - 1] := button;
end;
procedure Menu.Render();
begin
for var i := 0 to buttons.Length - 1 do
begin
buttons[i].Render(Self.x, Self.y + i * (buttons[i].height + Self.padding));
end;
end;
procedure Menu.Update(x: integer; y: integer);
begin
Self.x := Trunc(x);
Self.y := Trunc(y);
end;
procedure Menu.MoveFocusUp();
begin
var buttonIndex:=GetFocusedButtonIndex();
buttons[buttonIndex].focus := false;
if buttonIndex=0 then begin
buttons[buttons.Length-1].focus:=true
end
else begin
buttons[buttonIndex-1].focus:=true
end;
end;
procedure Menu.MoveFocusDown();
begin
var buttonIndex:=GetFocusedButtonIndex();
buttons[buttonIndex].focus := false;
if buttonIndex=buttons.Length-1 then begin
buttons[0].focus:=true
end
else begin
buttons[buttonIndex+1].focus:=true
end;
end;
procedure Menu.ActionActiveButton();
begin
var buttonIndex := GetFocusedButtonIndex();
buttons[buttonIndex].actionProc();
end;
//Function
function Menu.Width(): integer;
begin
for var i := 0 to Self.buttons.Length - 1 do
begin
if Result < buttons[i].width then begin
Result := buttons[i].width;
end;
end;
end;
function Menu.Heigth(): integer;
begin
for var i := 0 to Self.buttons.Length - 1 do
begin
Result += buttons[i].height;
if i > 0 then begin
Result += Self.padding;
end;
end;
end;
function Menu.GetFocusedButtonIndex():integer;
begin
for var i:=0 to buttons.Length -1 do
begin
if buttons[i].focus then begin
Result:=i;
exit;
end;
end;
end;
initialization
finalization
end.
|
unit DUnitX.Tests.Utils;
{$I DUnitX.inc}
interface
uses
DUnitX.TestFramework,
{$IFDEF USE_NS}
System.SysUtils,
System.UITypes;
{$ELSE}
SysUtils,
UITypes;
{$ENDIF}
type
[TestFixture('TValueHelper')]
[Category('Utils')]
TValueHelperTests = class
private var
{$IFDEF DELPHI_XE_UP}
originalFormatSettings: TFormatSettings;
{$ELSE}
originalLCID: Integer;
{$ENDIF}
protected var
expectedDate: TDate;
expectedTime: TTime;
protected
procedure setFormatSettings(const locale: String);
procedure revertFormatSettings();
{$IFDEF DELPHI_2010_DOWN}
function GetLCIDFromLocale(const locale: string): integer;
{$ENDIF}
public
// Delphi 2010 does support calling of constructor
{$IFDEF DELPHI_XE_UP}
constructor Create;
{$ELSE}
procedure AfterConstruction; override;
{$ENDIF}
destructor Destroy; override;
[Test]
[TestCase('EN-US local format', 'EN-US,06/22/2020')]
[TestCase('EN-US iso8601 format', 'EN-US,2020-06-22')]
[TestCase('EN-GB local format', 'EN-GB,22/06/2020')]
[TestCase('EN-GB iso8601 format', 'EN-GB,2020-06-22')]
[TestCase('DE local format', 'DE,22.06.2020')]
[TestCase('DE local format, no leading zeroes', 'DE,22.6.2020')]
[TestCase('DE local format, no explicit century', 'DE,22.06.20')]
[TestCase('DE iso8601 format', 'DE,2020-06-22')]
procedure TestDateConversion(const locale: String; const text: String);
[Test]
[TestCase('EN-US local format, no leading zero, no seconds', 'EN-US,6:36 pm')]
[TestCase('EN-US local format, with seconds', 'EN-US,06:36:00 PM')]
[TestCase('DE local format, no seconds', 'DE,18:36')]
[TestCase('DE local format, with seconds', 'DE,18:36:00')]
[TestCase('DE iso8601 format', 'DE,18:36:00.000')]
[TestCase('EN-GB local 12 h format', 'EN-GB,06:36 pm')]
[TestCase('EN-GB local 24 h format', 'EN-GB,18:36')]
procedure TestTimeConversion(const locale: String; const text: String);
[Test]
[TestCase('EN-US local format, verbose', 'EN-US,06/22/2020 06:36:00 pm')]
[TestCase('EN-US local format short', 'EN-US,6/22/2020 6:36 pm')]
[TestCase('EN-US iso 8601 format', 'EN-US,2020-06-22 18:36:00')]
[TestCase('EN-US iso 8601 format, verbose', 'EN-US,2020-06-22T18:36:00.000Z')]
[TestCase('EN-GB local format, 24 h, verbose', 'EN-GB,22/06/2020 18:36:00')]
[TestCase('EN-GB local format, 12 h, verbose', 'EN-GB,22/06/2020 06:36:00 pm')]
[TestCase('EN-GB iso8601 format', 'EN-GB,2020-06-22 18:36')]
[TestCase('EN-GB iso8601 format, verbose', 'EN-GB,2020-06-22T18:36:00+00')]
[TestCase('DE local format, verbose', 'DE,22.06.2020 18:36:00.000')]
[TestCase('DE local format, short', 'DE,22.6.20 18:36')]
[TestCase('DE iso8601 format', 'DE,2020-06-22 18:36:00')]
procedure TestDateTimeConversion(const locale: String; const text: String);
[Test]
[TestCase('claRed = xFFFF0000', 'claRed,xFFFF0000')]
[TestCase('Red = xFFFF0000', 'Red,xFFFF0000')]
[TestCase('red = xFFFF0000', 'red,xFFFF0000')]
[TestCase('$FFFF0000 = xFFFF0000', '$FFFF0000,xFFFF0000')]
[TestCase('xFFFF0000 = xFFFF0000', 'xFFFF0000,xFFFF0000')]
procedure TestAlphaColorTestCase(const AColor: TAlphaColor; const AColorOrd: Cardinal);
[Test]
[TestCase('clRed = 255', 'clRed,255')]
[TestCase('clred = 255', 'clred,255')]
[TestCase('clRed = $000000FF', 'clRed,$000000FF')]
[TestCase('clBlue = $00FF0000', 'clBlue,$00FF0000')]
[TestCase('$00FF0000 = $00FF0000', '$00FF0000,$00FF0000')]
[TestCase('$000000FF = $000000FF', '$000000FF,$000000FF')]
procedure TestColorTestCase(const AColor: TColor; const AColorOrd: Integer);
end;
implementation uses
{$IFDEF USE_NS}
System.DateUtils,
System.Rtti,
WinApi.Windows,
{$ELSE}
DateUtils,
Rtti,
Windows,
{$ENDIF}
DUnitX.Utils;
{ TValueHelperTests }
{$IFDEF DELPHI_XE_UP}
constructor TValueHelperTests.Create;
{$ELSE}
procedure TValueHelperTests.AfterConstruction;
{$ENDIF}
begin
inherited;
{$IFDEF DELPHI_XE_UP}
originalFormatSettings := {$IFDEF USE_NS}System.{$ENDIF}SysUtils.FormatSettings;
{$ELSE}
originalLCID := GetThreadLocale;
{$ENDIF}
expectedDate := EncodeDate(2020, 06, 22);
expectedTime := EncodeTime(18, 36, 00, 000);
end;
destructor TValueHelperTests.Destroy;
begin
revertFormatSettings();
inherited;
end;
procedure TValueHelperTests.revertFormatSettings();
begin
{$IFDEF DELPHI_XE_UP}
{$IFDEF USE_NS}System.{$ENDIF}SysUtils.FormatSettings := originalFormatSettings;
{$ELSE}
SetThreadLocale(originalLCID);
GetFormatSettings;
{$ENDIF}
end;
{$IFDEF DELPHI_2010_DOWN}
// I could not find a better way than hardcode them for D2010..
// Full list: https://docs.microsoft.com/en-us/openspecs/office_standards/ms-oe376/6c085406-a698-4e12-9d4d-c3b0ee3dbc4a
function TValueHelperTests.GetLCIDFromLocale(const locale: string): integer;
begin
if locale = 'EN-US' then
result := 1033
else if locale = 'EN-GB' then
result := 2057
else if locale = 'DE' then
result := 1031
else
raise Exception.Create('Unsupported locale passed to GetLCIDFromLocale function');
end;
{$ENDIF}
procedure TValueHelperTests.setFormatSettings(const locale: String);
{$If Defined(DELPHI_XE2_DOWN)}
var
_lcid: LCID;
{$IFEND}
begin
{$If Defined(DELPHI_XE2_DOWN)}
{$IFDEF DELPHI_2010_DOWN}
_lcid := GetLCIDFromLocale(locale);
SetThreadLocale(_lcid);
GetFormatSettings;
{$ELSE}
_lcid := LocaleNameToLCID(PChar(locale), 0);
GetLocaleFormatSettings(_lcid, FormatSettings);
{$ENDIF}
{$Else}
FormatSettings := TFormatSettings.Create(locale);
{$IFEND}
end;
procedure TValueHelperTests.TestAlphaColorTestCase(const AColor: TAlphaColor;
const AColorOrd: Cardinal);
begin
Assert.AreEqual(AColorOrd, AColor);
end;
procedure TValueHelperTests.TestColorTestCase(const AColor: TColor;
const AColorOrd: Integer);
begin
Assert.AreEqual(AColorOrd, AColor);
end;
procedure TValueHelperTests.TestDateConversion(const locale, text: String);
var
asTValue: TValue;
actual: TDate;
begin
setFormatSettings(locale);
Assert.IsTrue( TValue.From(text).TryConvert<TDate>(asTValue), 'TryConvert<TDate>' );
Assert.IsTrue( asTValue.IsType<TDate>(), 'IsType TDate' );
actual := asTValue.AsType<TDate>();
Assert.IsTrue( SameDate(expectedDate, actual), 'SameDate(..)' );
end;
procedure TValueHelperTests.TestDateTimeConversion(const locale, text: String);
var
asTValue: TValue;
expected, actual: TDateTime;
begin
setFormatSettings(locale);
Assert.IsTrue( TValue.From(text).TryConvert<TDateTime>(asTValue), 'TryConvert<TDateTime>' );
Assert.IsTrue( asTvalue.IsType<TDateTime>(), 'IsType TDateTime' );
expected := (expectedDate + expectedTime);
actual := asTValue.AsType<TDateTime>();
Assert.IsTrue( SameDateTime(expected, actual), 'SameDateTime(..)' );
end;
procedure TValueHelperTests.TestTimeConversion(const locale, text: String);
var
asTValue: TValue;
actual: TTime;
begin
setFormatSettings(locale);
Assert.IsTrue( TValue.From(text).TryConvert<TTime>(asTValue), 'TryConvert<TTime>' );
Assert.IsTrue( asTvalue.IsType<TTime>(), 'IsType TTime' );
actual := asTValue.AsType<TTime>();
Assert.IsTrue( SameTime(expectedTime, actual), 'SameTime(..)' );
end;
initialization
TDUnitX.RegisterTestFixture(TValueHelperTests);
end.
|
unit UTVControl;
interface
uses USimulation;
// Модель поточной линии по контролю телевизоров
type
// Класс TTVSet - проверяемый телевизор
TTVSet = class(TLink)
public
StartingTime : Double;
AdjustmentCount : Integer;
end;
TTVSetGenerator = class(TProcess)
protected
procedure RunProcess; override;
end;
// Класс TInspector - контролер
TInspector = class(TProcess)
protected
procedure RunProcess; override;
end;
// Класс TAdjuster - настройщик
TAdjuster = class(TProcess)
protected
procedure RunProcess; override;
end;
// Класс TTVControl - имитация линия контроля
TTVControl = class(TSimulation)
public
// Очередь телевизоров на проверку
InspectionQueue : TList;
// Очередь свободных проверяющих
Inspectors : array of TProcess;
// Настройщик
Adjuster : TAdjuster;
// Очередь на настройку
AdjustmentQueue : TList;
// Статистика по времени нахождения в системе
TimeInSystemStat : TStatistics;
// Статистика по количеству циклов настройки
AdjustmentCountStat : TStatistics;
// Статистика по занятости проверяющих
InspectorsStat : TServiceStatistics;
// Статистика по занятости настройщика
AdjustmentStat : TServiceStatistics;
// Генератор объектов
Generator : TTVSetGenerator;
destructor Destroy; override;
procedure StopStat; override;
protected
procedure RunSimulation; override;
procedure Init; override;
end;
var
rndTVSet,
rndInspector,
rndAdjuster : TRandom;
MinCreationDelay : Double = 3.5;
MaxCreationDelay : Double = 7.5;
MinInspectionTime : Double = 6;
MaxInspectionTime : Double = 12;
NoAdjustmentProb : Double = 0.85;
MinAdjustmentTime : Double = 20;
MaxAdjustmentTime : Double = 40;
InspectorCount : Integer = 2;
SimulationTime : Double = 480;
VisTimeStep : Double = 0.5;
implementation
{ TTVSetGenerator }
procedure TTVSetGenerator.RunProcess;
var
par : TTVControl;
tv : TTVSet;
begin
par := Parent as TTVControl;
while True do
begin
ClearFinished;
// Создать новый телевизор
tv := TTVSet.Create;
// Зафиксировать время прибытия
tv.StartingTime := SimTime;
// Циклов настройки не было
tv.AdjustmentCount := 0;
// Поместить телевизор в очередь проверки
tv.Insert(par.InspectionQueue);
ActivateDelay(par.Inspectors, 0);
// Подождать до следующего
Hold(rndTVSet.Uniform(MinCreationDelay, MaxCreationDelay));
end;
end;
{ TInspector }
procedure TInspector.RunProcess;
var
Piece : TTVSet;
par : TTVControl;
begin
// Работа проверяющего
par := Parent as TTVControl;
while True do
begin
// Если нет телевизоров для проверки
while par.InspectionQueue.Empty do
// Встать в очередь и ждать прибытия
Passivate;
// Извлечь из очереди первый телевизор
Piece := par.InspectionQueue.First as TTVSet;
Piece.Insert(par.RunningObjects);
// Зафиксировать начало работы
par.InspectorsStat.Start(SimTime);
// Проверка
Hold(rndInspector.Uniform(MinInspectionTime, MaxInspectionTime));
// Зафиксировать конец работы
par.InspectorsStat.Finish(SimTime);
// С вероятность NoAdjustmentProb телевизор исправен
if rndInspector.Draw(NoAdjustmentProb) then
begin
// Внести статистику о времени пребывания в системе
par.TimeInSystemStat.AddData(SimTime - Piece.StartingTime);
// Внести статистику о количестве циклов настройки
if Piece.AdjustmentCount > 0 then
par.AdjustmentCountStat.AddData(Piece.AdjustmentCount);
// Удалить телевизор
Piece.Insert(par.FinishedObjects);
end
else
begin
// Поместить телевизор в очередь на настройку
Piece.Insert(par.AdjustmentQueue);
// Дать сигнал настройщику
par.Adjuster.ActivateDelay(0);
end;
end;
end;
{ TAdjuster }
procedure TAdjuster.RunProcess;
var
par : TTVControl;
Piece : TTVSet;
begin
// Работа настройщика
par := Parent as TTVControl;
while True do
begin
// Если нет телевизоров для настройки, ожидать
while par.AdjustmentQueue.Empty do
Passivate;
// Извлечь первый телевизор из очереди
Piece := par.AdjustmentQueue.First as TTVSet;
Piece.Insert(par.RunningObjects);
// Зафиксировать начало работы
par.AdjustmentStat.Start(SimTime);
// Выполнить работу
Hold(rndAdjuster.Uniform(MinAdjustmentTime, MaxAdjustmentTime));
// Увеличить количество циклов настройки телевизора
Inc(Piece.AdjustmentCount);
// Зафиксировать конец работы
par.AdjustmentStat.Finish(SimTime);
// Поместить телевизор в очередь на проверку
Piece.Insert(par.InspectionQueue);
end;
end;
{ TTVControl }
destructor TTVControl.Destroy;
var
i : Integer;
begin
Generator.Free;
TimeInSystemStat.Free;
InspectorsStat.Free;
AdjustmentStat.Free;
AdjustmentCountStat.Free;
for i := 0 to InspectorCount - 1 do
Inspectors[i].Free;
Adjuster.Free;
InspectionQueue.Free;
AdjustmentQueue.Free;
inherited;
end;
procedure TTVControl.Init;
var
i : Integer;
begin
inherited;
InspectionQueue := TList.Create;
Adjuster := TAdjuster.Create;
AdjustmentQueue := TList.Create;
Generator := TTVSetGenerator.Create;
// Создать контролеров
SetLength(Inspectors, InspectorCount);
for i := 0 to InspectorCount - 1 do
Inspectors[i] := TInspector.Create;
TimeInSystemStat := TStatistics.Create;
AdjustmentCountStat := TStatistics.Create;
InspectorsStat := TServiceStatistics.Create(InspectorCount);
AdjustmentStat := TServiceStatistics.Create(1);
MakeVisualizator(VisTimeStep);
end;
procedure TTVControl.RunSimulation;
begin
Generator.ActivateDelay(0);
// Время моделирования
Hold(SimulationTime);
// Скорректировать статистики
StopStat;
end;
procedure TTVControl.StopStat;
begin
inherited;
InspectionQueue.StopStat(SimTime);
AdjustmentQueue.StopStat(SimTime);
InspectorsStat.StopStat(SimTime);
AdjustmentStat.StopStat(SimTime);
end;
end.
|
unit OAuth2.CodeChallengeVerifier.S256Verifier;
interface
uses
OAuth2.Contract.CodeChallengeVerifier;
type
TOAuth2S256Verifier = class(TInterfacedObject, IOAuth2CodeChallengeVerifier)
private
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
function GetMethod: string;
function VerifyCodeChallenge(ACodeVerifier: string; ACodeChallenge: string): Boolean;
end;
implementation
uses
System.SysUtils,
System.NetEncoding,
System.StrUtils,
System.Hash;
{ TOAuth2S256Verifier }
function TOAuth2S256Verifier.GetMethod: string;
begin
Result := 'S256';
end;
function TOAuth2S256Verifier.VerifyCodeChallenge(ACodeVerifier, ACodeChallenge: string): Boolean;
var
LBase64Encoding: TBase64Encoding;
LBase64String: string;
begin
LBase64Encoding := TBase64Encoding.Create(0);
try
LBase64String := TEncoding.UTF8.GetString(LBase64Encoding.Encode(THashSHA2.GetHashBytes(ACodeVerifier))).TrimRight(['=']).Replace('+', '-').Replace('/', '_');
Result := LBase64String = ACodeChallenge;
finally
LBase64Encoding.Free;
end;
end;
end.
|
{
mteTypes
General helpers for mteFunctions.
See http://github.com/matortheeternal/mteFunctions
}
unit mteTypes;
const
// Times
aDay = 1.0;
aHour = aDay / 24.0;
aMinute = aHour / 60.0;
// Colors
clAqua = $FFFF00;
clBlack = $000000;
clBlue = $FF0000;
clCream = $F0FBFF;
clDkGray = $808080;
clFuchsia = $FF00FF;
clGray = $808080;
clGreen = $008000;
clLime = $00FF00;
clLtGray = $C0C0C0;
clMaroon = $000080;
clMedGray = $A4A0A0;
clMoneyGreen = $C0DCC0;
clNavy = $800000;
clOlive = $008080;
clPurple = $800080;
clRed = $0000FF;
clSilver = $C0C0C0;
clSkyBlue = $F0CAA6;
clTeal = $808000;
clWhite = $FFFFFF;
clYellow = $00FFFF;
// Web Colors
clWebSnow = $FAFAFF;
clWebFloralWhite = $F0FAFF;
clWebLavenderBlush = $F5F0FF;
clWebOldLace = $E6F5FD;
clWebIvory = $F0FFFF;
clWebCornSilk = $DCF8FF;
clWebBeige = $DCF5F5;
clWebAntiqueWhite = $D7EBFA;
clWebWheat = $B3DEF5;
clWebAliceBlue = $FFF8F0;
clWebGhostWhite = $FFF8F8;
clWebLavender = $FAE6E6;
clWebSeashell = $EEF5FF;
clWebLightYellow = $E0FFFF;
clWebPapayaWhip = $D5EFFF;
clWebNavajoWhite = $ADDEFF;
clWebMoccasin = $B5E4FF;
clWebBurlywood = $87B8DE;
clWebAzure = $FFFFF0;
clWebMintcream = $FAFFF5;
clWebHoneydew = $F0FFF0;
clWebLinen = $E6F0FA;
clWebLemonChiffon = $CDFAFF;
clWebBlanchedAlmond = $CDEBFF;
clWebBisque = $C4E4FF;
clWebPeachPuff = $B9DAFF;
clWebTan = $8CB4D2;
clWebYellow = $00FFFF;
clWebDarkOrange = $008CFF;
clWebRed = $0000FF;
clWebDarkRed = $00008B;
clWebMaroon = $000080;
clWebIndianRed = $5C5CCD;
clWebSalmon = $7280FA;
clWebCoral = $507FFF;
clWebGold = $00D7FF;
clWebTomato = $4763FF;
clWebCrimson = $3C14DC;
clWebBrown = $2A2AA5;
clWebChocolate = $1E69D2;
clWebSandyBrown = $60A4F4;
clWebLightSalmon = $7AA0FF;
clWebLightCoral = $8080F0;
clWebOrange = $00A5FF;
clWebOrangeRed = $0045FF;
clWebFirebrick = $2222B2;
clWebSaddleBrown = $13458B;
clWebSienna = $2D52A0;
clWebPeru = $3F85CD;
clWebDarkSalmon = $7A96E9;
clWebRosyBrown = $8F8FBC;
clWebPaleGoldenrod = $AAE8EE;
clWebLightGoldenrodYellow = $D2FAFA;
clWebOlive = $008080;
clWebForestGreen = $228B22;
clWebGreenYellow = $2FFFAD;
clWebChartreuse = $00FF7F;
clWebLightGreen = $90EE90;
clWebAquamarine = $D4FF7F;
clWebSeaGreen = $578B2E;
clWebGoldenRod = $20A5DA;
clWebKhaki = $8CE6F0;
clWebOliveDrab = $238E6B;
clWebGreen = $008000;
clWebYellowGreen = $32CD9A;
clWebLawnGreen = $00FC7C;
clWebPaleGreen = $98FB98;
clWebMediumAquamarine = $AACD66;
clWebMediumSeaGreen = $71B33C;
clWebDarkGoldenRod = $0B86B8;
clWebDarkKhaki = $6BB7BD;
clWebDarkOliveGreen = $2F6B55;
clWebDarkgreen = $006400;
clWebLimeGreen = $32CD32;
clWebLime = $00FF00;
clWebSpringGreen = $7FFF00;
clWebMediumSpringGreen = $9AFA00;
clWebDarkSeaGreen = $8FBC8F;
clWebLightSeaGreen = $AAB220;
clWebPaleTurquoise = $EEEEAF;
clWebLightCyan = $FFFFE0;
clWebLightBlue = $E6D8AD;
clWebLightSkyBlue = $FACE87;
clWebCornFlowerBlue = $ED9564;
clWebDarkBlue = $8B0000;
clWebIndigo = $82004B;
clWebMediumTurquoise = $CCD148;
clWebTurquoise = $D0E040;
clWebCyan = $FFFF00;
clWebAqua = $FFFF00;
clWebPowderBlue = $E6E0B0;
clWebSkyBlue = $EBCE87;
clWebRoyalBlue = $E16941;
clWebMediumBlue = $CD0000;
clWebMidnightBlue = $701919;
clWebDarkTurquoise = $D1CE00;
clWebCadetBlue = $A09E5F;
clWebDarkCyan = $8B8B00;
clWebTeal = $808000;
clWebDeepskyBlue = $FFBF00;
clWebDodgerBlue = $FF901E;
clWebBlue = $FF0000;
clWebNavy = $800000;
clWebDarkViolet = $D30094;
clWebDarkOrchid = $CC3299;
clWebMagenta = $FF00FF;
clWebFuchsia = $FF00FF;
clWebDarkMagenta = $8B008B;
clWebMediumVioletRed = $8515C7;
clWebPaleVioletRed = $9370DB;
clWebBlueViolet = $E22B8A;
clWebMediumOrchid = $D355BA;
clWebMediumPurple = $DB7093;
clWebPurple = $800080;
clWebDeepPink = $9314FF;
clWebLightPink = $C1B6FF;
clWebViolet = $EE82EE;
clWebOrchid = $D670DA;
clWebPlum = $DDA0DD;
clWebThistle = $D8BFD8;
clWebHotPink = $B469FF;
clWebPink = $CBC0FF;
clWebLightSteelBlue = $DEC4B0;
clWebMediumSlateBlue = $EE687B;
clWebLightSlateGray = $998877;
clWebWhite = $FFFFFF;
clWebLightgrey = $D3D3D3;
clWebGray = $808080;
clWebSteelBlue = $B48246;
clWebSlateBlue = $CD5A6A;
clWebSlateGray = $908070;
clWebWhiteSmoke = $F5F5F5;
clWebSilver = $C0C0C0;
clWebDimGray = $696969;
clWebMistyRose = $E1E4FF;
clWebDarkSlateBlue = $8B3D48;
clWebDarkSlategray = $4F4F2F;
clWebGainsboro = $DCDCDC;
clWebDarkGray = $A9A9A9;
clWebBlack = $000000;
{*****************************************************************************}
{ Boolean Helpers
Functions for handling and converting booleans.
List of functions:
- IfThenVar
- BoolToStr
}
{*****************************************************************************}
{
IfThenVar:
Returns one of two variants based on a boolean argument.
Like IfThen from StrUtils, but returns a variant.
}
function IfThenVar(AValue: boolean; ATrue, AFalse: Variant): Variant;
begin
if AValue then
Result := ATrue
else
Result := AFalse;
end;
{
BoolToStr:
Returns 'True' if @b is true, 'False' if @b is false.
}
function BoolToStr(b: Boolean): String;
begin
Result := IfThenVar(b, 'True', 'False');
end;
{*****************************************************************************}
{ Integer Helpers
Functions for handling and converting integers.
List of functions:
- IntLog
- FormatFileSize
}
{*****************************************************************************}
{
IntLog:
Returns the integer logarithm of @Value using @Base.
Example usage:
i := IntLog(8, 2);
AddMessage(IntToStr(i)); // 3
i := IntLog(257, 2);
AddMessage(IntToStr(i)); // 8
i := IntLog(1573741824, 1024);
AddMessage(IntToStr(i)); // 3
}
function IntLog(Value, Base: Integer): Integer;
begin
Result := 0;
// a base <= 1 is invalid when performing a logarithm
if Base <= 1 then
raise Exception.Create('IntLog: Base cannot be less than or equal to 1');
// compute the logarithm by performing integer division repeatedly
while Value >= Base do begin
Value := Value div Base;
Inc(Result);
end;
end;
{
FormatFileSize:
Formats a file size in @bytes to a human readable string.
NOTE:
Currently xEdit scripting doesn't support an Int64 or Cardinal data
type, so the maximum value this function can take is +2147483648,
which comes out to 2.00GB.
Example usage:
AddMessage(FormatFileSize(5748224)); // '5.48 MB'
AddMessage(FormatFileSize(-2147483647)); // '-2.00 GB
}
function FormatFileSize(const bytes: Integer): string;
var
units: array[0..3] of string;
var
uIndex: Integer;
begin
// initialize units array
units[0] := 'bytes';
units[1] := 'KB'; // Kilobyte, 10^3 bytes
units[2] := 'MB'; // Megabyte, 10^6 bytes
units[3] := 'GB'; // Gigabyte, 10^9 bytes
// get unit to used based on the size of bytes
uIndex := IntLog(abs(bytes), 1024);
// return formatted file size string
if (uIndex > 0) then
Result := Format('%f %s', [bytes / IntPower(1024, uIndex), units[uIndex]])
else
Result := Format('%d %s', [bytes, units[uIndex]]);
end;
{*****************************************************************************}
{ String Helpers
Functions for handling and converting strings.
List of functions:
- TitleCase
- SentenceCase
- ItPos
- LastPos
- CopyFromTo
- ReverseString
- GetTextIn
- StrEndsWith
- AppendIfMissing
- RemoveFromEnd
- StrStartsWith
- PrependIfMissing
- RemoveFromStart
- IsURL
- Wordwrap
}
{*****************************************************************************}
{
TitleCase:
Capitalizes the first letter of each word in @sText.
Example usage:
AddMessage(TitleCase('the title of a book'));
// 'The Title Of A Book'
AddMessage(TitleCase('a text,with.punctuation!yay'));
// 'A Text,With.Punctuation!Yay'
AddMessage(TitleCase('[this(is/going);to,be'#13'great!'));
// 'This(Is/Going);To,Be'#13'Great!'
}
function TitleCase(sText: String): String;
const
cDelimiters = #9#10#13' ,.:;"\/()[]{}';
var
i: Integer;
bDelimited: boolean;
sChar: string;
begin
// set default result
Result := '';
// if input isn't empty, loop through the characters in it
if (sText <> '') then begin
bDelimited := true;
for i := 1 to Length(sText) do begin
sChar := LowerCase(Copy(sText, i, 1));
if (Pos(sChar, cDelimiters) > 0) then
bDelimited := true
else if bDelimited then begin
sChar := UpCase(sChar);
bDelimited := false;
end;
Result := Result + sChar;
end;
end;
end;
{
SentenceCase:
Capitalizes the first character of each sentence in @sText.
Example usage:
AddMessage(SentenceCase('this is a sentence. so is this.'));
// 'This is a sentence. So is this.'
AddMessage(SentenceCase('lets Try something! different?!?this time.,a'));
// 'Lets Try something! Different?!?This time.,a'
}
function SentenceCase(sText: string): string;
const
cTerminators = '!.?';
var
i: Integer;
bTerminated: boolean;
sChar: string;
begin
// set result
Result := '';
// if input isn't empty, loop through the characters in it
if (sText <> '') then begin
bTerminated := true;
for i := 1 to Length(sText) do begin
sChar := LowerCase(Copy(sText, i, 1));
if (Pos(sChar, cTerminators) > 0) then
bTerminated := true
else if bTerminated and (sChar <> ' ') then begin
sChar := UpCase(sChar);
bTerminated := false;
end;
Result := Result + sChar;
end;
end;
end;
{
ItPos:
Returns the position of the @target iteration of @substr in @str.
If the requested iteration isn't found 0 is returned.
Example usage:
s := '10101';
k := ItPos('1', s, 3);
AddMessage(IntToStr(k)); // 5
}
function ItPos(substr, str: String; target: Integer): Integer;
var
i, found: Integer;
begin
Result := 0;
found := 0;
// exit if the target iteration is less than 1
// because that doesn't make any sense
if target < 1 then
exit;
// exit if substring is empty
if substr = '' then
exit;
// loop through the input string
for i := 1 to Length(str) do begin
// check if the substring is at the current position
if Copy(str, i, Length(substr)) = substr then
Inc(found);
// if this is the target iteration, set Result and break
if found = target then begin
Result := i;
Break;
end;
end;
end;
{
LastPos:
Gets the last position of @substr in @str. Returns 0 if the substring
isn't found in the input string.
Example usage:
s := 'C:\Program Files (x86)\steam\SteamApps\common\Skyrim\TES5Edit.exe';
AddMessage(Copy(s, LastPos('\', s) + 1, Length(s))); // 'TES5Edit.exe'
}
function LastPos(substr, str: String): Integer;
var
i: integer;
begin
Result := 0;
// if str and substr are the same length,
// Result is whether or not they're equal
if (Length(str) - Length(substr) <= 0) then begin
if (str = substr) then
Result := 1;
exit;
end;
// loop through the string backwards
for i := Length(str) - Length(substr) downto 1 do begin
if (Copy(str, i, Length(substr)) = substr) then begin
Result := i;
break;
end;
end;
end;
{
CopyFromTo:
Returns a substring in a string @str inclusively between two indexes
@iStart and @iEnd.
Example usage:
AddMessage(CopyFromTo('this is an example', 6, 10)); // 'is an'
}
function CopyFromTo(str: string; iStart, iEnd: Integer): string;
begin
if iStart < 1 then
raise Exception.Create('CopyFromTo: Start index cannot be less than 1');
if iEnd < iStart then
raise Exception.Create('CopyFromTo: End index cannot be less than the start index');
Result := Copy(str, iStart, (iEnd - iStart) + 1);
end;
{
ReverseString:
Reverses the input string @s.
Example usage:
s := 'backwards';
s := ReverseString(s);
AddMessage(s); // 'sdrawkcab'
}
function ReverseString(var s: string): string;
var
i: integer;
begin
Result := '';
for i := Length(s) downto 1 do begin
Result := Result + Copy(s, i, 1);
end;
end;
{
GetTextIn:
Returns a substring of @str between characters @open and @close.
Example usage:
AddMessage(GetTextIn('example of [some text] in brackets', '[', ']'));
// 'some text'
}
function GetTextIn(str: string; open, close: char): string;
var
i, openIndex: integer;
bOpen: boolean;
sChar: string;
begin
Result := '';
bOpen := false;
openIndex := 0;
// loop through string looking for the open char
for i := 1 to Length(str) do begin
sChar := Copy(str, i, 1);
// if open char found, set openIndex and bOpen boolean
// if already opened reset open index if open <> close
if (sChar = open) and not (bOpen and (open = close)) then begin
openIndex := i;
bOpen := true;
end
// if opened and we find the close char, set result and break
else if bOpen and (sChar = close) then begin
Result := CopyFromTo(str, openIndex + 1, i - 1);
break;
end;
end;
end;
{
StrEndsWith:
Checks to see if a string ends with an entered substring.
Example usage:
s := 'This is a sample string.';
if StrEndsWith(s, 'string.') then
AddMessage('It works!');
}
function StrEndsWith(str, substr: string): boolean;
var
n1, n2: integer;
begin
Result := false;
n1 := Length(str);
n2 := Length(substr);
if n1 < n2 then exit;
Result := (Copy(str, n1 - n2 + 1, n2) = substr);
end;
{
AppendIfMissing:
Appends substr to the end of str if it's not already there.
Example usage:
s := 'This is a sample string.';
AddMessage(AppendIfMissing(s, 'string.')); //'This is a sample string.'
AddMessage(AppendIfMissing(s, ' Hello.')); //'This is a sample string. Hello.'
}
function AppendIfMissing(str, substr: string): string;
begin
Result := str;
if not StrEndsWith(str, substr) then
Result := str + substr;
end;
{
RemoveFromEnd:
Creates a new string with substr removed from the end of s2, if found.
Example usage:
s := 'This is a sample string.';
AddMessage(RemoveFromEnd(s, 'string.')); //'This is a sample '
}
function RemoveFromEnd(str, substr: string): string;
begin
Result := str;
if StrEndsWith(str, substr) then
Result := Copy(str, 1, Length(str) - Length(substr));
end;
{
StrStartsWith:
Checks to see if a string starts with an entered substring.
Example usage:
s := 'This is a sample string.';
if StrStartsWith(s, 'This ') then
AddMessage('It works!');
}
function StrStartsWith(str, substr: string): boolean;
var
n1, n2: integer;
begin
Result := false;
n1 := Length(str);
n2 := Length(substr);
if n1 < n2 then exit;
Result := (Copy(str, 1, n2) = substr);
end;
{
PrependIfMissing:
Prepends substr to the beginning of str if it's not already there.
Example usage:
s := 'This is a sample string.';
AddMessage(PrependIfMissing(s, 'This ')); //'This is a sample string.'
AddMessage(PrependIfMissing(s, 'Hello. ')); //'Hello. This is a sample string.'
}
function PrependIfMissing(str, substr: string): string;
begin
Result := str;
if not StrStartsWith(str, substr) then
Result := substr + str;
end;
{
RemoveFromStart:
Creates a new string with substr removed from the start of substr, if found.
Example usage:
s := 'This is a sample string.';
AddMessage(RemoveFromStart(s, 'This ')); //'is a sample string.'
}
function RemoveFromStart(str, substr: string): string;
begin
Result := str;
if StrStartsWith(str, substr) then
Result := Copy(str, Length(substr) + 1, Length(str));
end;
{
IsUrl:
Returns true if the string @s is an http:// or https:// url.
Example usage:
if IsUrl(s) then
ShellExecute(0, 'open', PChar(s), nil, nil , SW_SHOWNORMAL);
}
function IsURL(s: string): boolean;
begin
s := Lowercase(s);
Result := (Pos('http://', s) = 1) or (Pos('https://', s) = 1);
end;
{
Wordwrap:
Inserts line breaks in string @s before @charCount has been exceeded.
Example usage:
s := 'Some very long string that probably should have line breaks '+
'in it because it's going to go off of your screen and mess '+
'up labels or hints or other such things if you don't wrap '+
'it.';
AddMessage(WordWrap(s, 60));
// 'Some very long string that probably should have line breaks '#13 +
'in it because it's going to go off of your screen and mess '#13 +
'up labels or hints or other such things if you don't wrap '#13 +
'it.'
}
function Wordwrap(s: string; charCount: integer): string;
const
bDebugThis = false;
var
i, j, lastSpace, counter: Integer;
sChar, sNextChar: string;
begin
// initialize variables
counter := 0;
lastSpace := 0;
i := 1;
// debug message
if bDebugThis then AddMessage(Format('Called Wordwrap(%s, %d)', [s, charCount]));
// loop for every character except the last one
while (i < Length(s)) do begin
// increment the counter for characters on the line and get the character
// at the current position and the next position
Inc(counter);
sChar := Copy(s, i, 1);
sNextChar := Copy(s, i + 1, 1);
// debug message
if bDebugThis then AddMessage(Format(' [%d] Counter = %d, Char = %s', [i, counter, sChar]));
// track the position of the last space we've seen
if (sChar = ' ') or (sChar = ',') then
lastSpace := i;
// if we encounter a new line, reset the counter for the characters on the line
// also don't make a new line if the next character is a newline character
if (sChar = #13) or (sChar = #10)
or (sNextChar = #13) or (sNextChar = #10) then begin
lastSpace := 0;
counter := 0;
end;
// if we've exceeded the number of characters allowed on the line and we've seen
// a space on the line, insert a line break at the space and reset the counter
if (counter > charCount) and (lastSpace > 0) then begin
Insert(#13#10, s, lastSpace + 1);
counter := i - lastSpace;
lastSpace := 0;
i := i + 2;
end;
// proceed to next character in the while loop
Inc(i);
end;
// return the modified string
Result := s;
end;
{*****************************************************************************}
{ Date and Time Helpers
Functions for handling dates and times.
NOTE: I did not implement SecondOf or RateStr down to seconds because
limitations in precision in the jvInterpreter.
List of functions:
- DayOf
- HourOf
- MinuteOf
- RateStr
- TimeStr
}
{*****************************************************************************}
{
DayOf:
Returns the day portion of a TDateTime as an integer
}
function DayOf(date: TDateTime): Integer;
begin
Result := Trunc(date);
end;
{
HourOf:
Returns the hour portion of a TDateTime as an integer
}
function HourOf(date: TDateTime): Integer;
begin
Result := Trunc(date / aHour) mod 24;
end;
{
MinuteOf:
Returns the minute portion of a TDateTime as an integer
}
function MinuteOf(date: TDateTime): Integer;
begin
Result := Trunc(date / aMinute) mod 60;
end;
{
RateStr:
Converts a TDateTime to a rate string, e.g. Every 24.0 hours
}
function RateStr(rate: TDateTime): string;
begin
if rate > aDay then
Result := Format('Every %0.1f days', [rate])
else if rate > aHour then
Result := Format('Every %0.1f hours', [rate * 24.0])
else
Result := Format('Every %0.1f minutes', [rate * 24.0 * 60.0])
end;
{
DurationStr:
Converts a TDateTime to a duratrion string, e.g. 19d 20h 3m
}
function DurationStr(duration: TDateTime; sep: String): string;
begin
Result := Format('%dd%s%dh%s%dm',
[DayOf(duration), sep, HourOf(duration), sep, MinuteOf(duration)]);
end;
{*****************************************************************************}
{ Color Helpers
Functions for handling Colors.
List of functions:
- GetRValue
- GetGValue
- GetBValue
- RGB
- ColorToHex
- HexToColor
}
{*****************************************************************************}
function GetRValue(rgb: Integer): Byte;
begin
Result := Byte(rgb);
end;
function GetGValue(rgb: Integer): Byte;
begin
Result := Byte(rgb shr 8);
end;
function GetBValue(rgb: Integer): Byte;
begin
Result := Byte(rgb shr 16);
end;
function RGB(r, g, b: Byte): Integer;
begin
Result := (r or (g shl 8) or (b shl 16));
end;
function ColorToHex(Color: Integer): string;
begin
Result :=
IntToHex(GetRValue(Color), 2) +
IntToHex(GetGValue(Color), 2) +
IntToHex(GetBValue(Color), 2);
end;
function HexToColor(sColor : string): Integer;
begin
Result :=
RGB(
StrToInt('$'+Copy(sColor, 1, 2)),
StrToInt('$'+Copy(sColor, 3, 2)),
StrToInt('$'+Copy(sColor, 5, 2))
);
end;
{*****************************************************************************}
{ Class Helpers
Functions for handling common classes like TStringLists and TLists.
List of functions:
- IntegerListSum
- SaveStringToFile
- LoadStringFromFile
- ApplyTemplate
- FreeAndNil
- TryToFree
}
{*****************************************************************************}
{
IntegerListSum:
Calculates the integer sum of all values in a TStringList to maxIndex
}
function IntegerListSum(sl: TStringList; maxIndex: integer): integer;
var
i: Integer;
begin
Result := 0;
// raise exception if input list is not assigned
if not Assigned(sl) then
raise Exception.Create('IntegerListSum: Input stringlist is not assigned');
// raise exception if input max index is out of bounds
if maxIndex >= sl.Count then
raise Exception.Create('IntegerListSum: Input maxIndex is out of bounds for the input stringlist');
// perform the sum
for i := 0 to maxIndex do
Result := Result + StrToInt(sl[i]);
end;
{
SaveStringToFile:
Saves a string @s to a file at @fn
}
procedure SaveStringToFile(s: string; fn: string);
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.Text := s;
sl.SaveToFile(fn);
finally
sl.Free;
end;
end;
{
LoadStringFromFile:
Loads a the file at @fn and returns its contents as a string
}
function LoadStringFromFile(fn: string): String;
var
sl: TStringList;
begin
Result := '';
sl := TStringList.Create;
try
sl.LoadFromFile(fn);
Result := sl.Text;
finally
sl.Free;
end;
end;
{
ApplyTemplate:
Applies the values in the stringlist @map to corresponding names in @template
}
function ApplyTemplate(const template: string; var map: TStringList): string;
const
openTag = '{{';
closeTag = '}}';
var
i: Integer;
name, value: string;
begin
Result := template;
// raise exception if input map is not assigned
if not Assigned(map) then
raise Exception.Create('ApplyTemplate: Input map stringlist is not assigned');
// apply the map to the template
for i := 0 to Pred(map.Count) do begin
name := map.Names[i];
value := map.ValueFromIndex[i];
Result := StringReplace(Result, openTag + name + closeTag, value, [rfReplaceAll]);
end;
end;
{
FreeAndNil:
Frees @obj then sets it to nil
}
procedure FreeAndNil(var obj: TObject);
begin
obj.Free;
obj := nil;
end;
{
TryToFree:
Attempts to free and nil an object
}
procedure TryToFree(var obj: TObject);
const
bDebugThis = false;
begin
try
if Assigned(obj) then
obj.Free;
obj := nil;
except
on x: Exception do begin
if bDebugThis then ShowMessage('TryToFree exception: '+x.Message);
end;
end;
end;
end. |
Unit SteamManager;
Interface
Uses SysUtils, SteamAPI, SteamCallback;
Type
TSteamAchievement = Class
Protected
_ID:AnsiString;
_Name:AnsiString;
_Description:AnsiString;
_Achieved:Boolean;
Procedure Load();
Public
Constructor Create(Const ID:AnsiString);
Function Unlock():Boolean;
Property ID:AnsiString Read _ID;
Property Name:AnsiString Read _Name;
Property Description:AnsiString Read _Description;
Property Achieved:Boolean Read _Achieved;
End;
TSteamStat = Class
Protected
_ID:AnsiString;
_Value:Integer;
Procedure Load();
Procedure SetValue(Const Val:Integer);
Public
Constructor Create(Const ID:AnsiString);
Property Value:Integer Read _Value Write SetValue;
End;
TSteamLeaderboard = Class
Protected
_ID:AnsiString;
Public
Constructor Create(Const ID:AnsiString);
Procedure Post(Const Value:Integer);
End;
TSteamManager = Class
Protected
_Loaded:Boolean;
_Running:Boolean;
_LoggedOn:Boolean;
_StatsRequested:Boolean;
_StoreStats:Boolean;
_SteamID:AnsiString;
_AppID:AnsiString;
_UserName:AnsiString;
_Language:AnsiString;
_LicenseResult:SteamUserHasLicenseForAppResult;
_Achievements:Array Of TSteamAchievement;
_AchievementCount:Integer;
_Stats:Array Of TSteamStat;
_StatCount:Integer;
Procedure OnUserStats(P:Pointer);
Public
Constructor Create();
Destructor Destroy; Override;
{ CALL THIS METHOD EVERY FRAME!!!}
Procedure Update;
Function GetAchievement(Const AchID:AnsiString):TSteamAchievement;
Function AddAchievement(Const AchID:AnsiString):TSteamAchievement;
Function UnlockAchievement(Const AchID:AnsiString):Boolean;
Function GetStat(Const StatID:AnsiString):TSteamStat;
Function AddStat(Const StatID:AnsiString):TSteamStat;
Property UserName:AnsiString Read _UserName;
Property Language:AnsiString Read _Language;
Property SteamID:AnsiString Read _SteamID;
Property AppID:AnsiString Read _AppID;
Property Loaded:Boolean Read _Loaded;
Property Enabled:Boolean Read _Running;
End;
Implementation
Var
_SteamInstance:TSteamManager;
{Utilities}
Function CardinalToString(Const N:Cardinal):AnsiString;
Begin
Str(N, Result);
End;
Function UInt64ToString(Const N:UInt64):AnsiString;
Begin
Str(N, Result);
End;
{ Steam }
Constructor TSteamManager.Create();
Var
CurrentAppID:Cardinal;
Begin
_SteamInstance := Self;
_LoggedOn := False;
//Log.Write(logDebug, 'Steam', 'Trying to load Steam library...');
_Loaded := LoadSteamAPI();
If Not _Loaded Then
Begin
//Log.Write(logWarning, 'Steam', 'Failed to hook into Steam...');
_Running := False;
Exit;
End;
_Running := SteamAPI_InitSafe();
If Not _Running Then
Exit;
CurrentAppID := ISteamUtils_GetAppID();
If (SteamAPI_RestartAppIfNecessary(CurrentAppID)) Then
Begin
_Running := False;
Halt(0);
Exit;
End;
_AppID := CardinalToString(CurrentAppID);
//Log.Write(logDebug, 'Steam', 'App ID: '+ _AppID);
_SteamID := UInt64ToString(ISteamUser_GetSteamID());
//Log.Write(logDebug, 'Steam', 'User ID: '+ _SteamID);
_UserName := ISteamFriends_GetPersonaName();
//Log.Write(logDebug, 'Steam', 'Username: '+ _UserName);
_Language := ISteamApps_GetCurrentGameLanguage();
//Log.Write(logDebug, 'Steam', 'Language: '+ _Language);
//_LicenseResult := ISteamGameServer_UserHasLicenseForApp(steamID:SteamID; appID:SteamAppId):
End;
Destructor TSteamManager.Destroy;
Var
I:Integer;
Begin
If _Running Then
Begin
_Running := False;
SteamAPI_Shutdown();
End;
For I:=0 To Pred(_AchievementCount) Do
FreeAndNil(_Achievements[I]);
For I:=0 To Pred(_StatCount) Do
FreeAndNil(_Stats[I]);
_SteamInstance := Nil;
End;
Procedure TSteamManager.Update();
Var
I:Integer;
controllerState:SteamControllerState;
Begin
If Not _Running Then
Exit;
// Is the user logged on? If not we can't get stats.
If _StatsRequested Then
Begin
_LoggedOn := ISteamUser_BLoggedOn();
If (_LoggedOn) Then
Begin
SteamCallbackDispatcher.Create(SteamStatsCallbackID , Self.OnUserStats, SizeOf(Steam_UserStatsReceived));
If ISteamUserStats_RequestCurrentStats() Then
_StatsRequested := False;
End;
End;
If _StoreStats Then
Begin
// If this failed, we never sent anything to the server, try again later.
If ISteamUserStats_StoreStats() Then
_StoreStats := False;
End;
SteamAPI_RunCallbacks();
(* For I:=0 To 3 Do
Begin
If ISteamController_GetControllerState(I, controllerState) Then
Begin
End;
End;*)
End;
Procedure TSteamManager.OnUserStats(P: Pointer);
Var
Info:PSteam_UserStatsReceived;
GameID:AnsiString;
I:Integer;
Begin
Info := P;
GameID := UInt64ToString(Info.GameID);
If GameID<> Self.AppID Then
Exit;
//Log.Write(logDebug, 'Steam', 'Received stats, with return code '+CardinalToString(Info.Result));
// load achievements
For I:=0 To Pred(_AchievementCount) Do
Begin
_Achievements[I].Load();
End;
// load stats
For I:=0 To Pred(_StatCount) Do
Begin
_Stats[I].Load();
End;
End;
{ SteamAchievement }
Constructor TSteamAchievement.Create(const ID: AnsiString);
Begin
Self._ID := ID;
End;
Procedure TSteamAchievement.Load;
Var
Ret:Boolean;
Begin
Ret := ISteamUserStats_GetAchievement(PAnsiChar(_ID), _Achieved);
If Ret Then
Begin
_Name := ISteamUserStats_GetAchievementDisplayAttribute(PAnsiChar(_ID), 'name');
_Description := ISteamUserStats_GetAchievementDisplayAttribute(PAnsiChar(_ID), 'desc');
End Else
Begin
//Log.Write(logWarning, 'Steam', 'GetAchievement failed for Achievement ' + _ID);
End;
End;
Function TSteamAchievement.Unlock():Boolean;
Begin
If (_Achieved) Or (_SteamInstance=Nil) Or (Not _SteamInstance._LoggedOn) Then
Begin
Result := False;
Exit;
End;
_Achieved := True;
// the icon may change once it's unlocked
//_IconImage := 0;
// mark it down
ISteamUserStats_SetAchievement(PAnsiChar(ID));
// Store stats end of frame
_SteamInstance._StoreStats := True;
Result := True;
End;
Function TSteamManager.AddAchievement(const AchID: AnsiString):TSteamAchievement;
Begin
Result := Self.GetAchievement(AchID);
If Assigned(Result) Then
Exit;
Result := TSteamAchievement.Create(AchID);
Inc(_AchievementCount);
SetLength(_Achievements, _AchievementCount);
_Achievements[Pred(_AchievementCount)] := Result;
_StatsRequested := True;
End;
Function TSteamManager.GetAchievement(const AchID: AnsiString): TSteamAchievement;
Var
I:Integer;
Begin
For I:=0 To Pred(_AchievementCount) Do
If _Achievements[I]._ID = AchID Then
Begin
Result := _Achievements[I];
Exit;
End;
Result := Nil;
End;
Function TSteamManager.UnlockAchievement(const AchID: AnsiString): Boolean;
Var
Ach:TSteamAchievement;
Begin
Ach := Self.GetAchievement(AchID);
If Ach = Nil Then
Begin
Result := False;
Exit;
End;
Result := Ach.Unlock();
End;
Function TSteamManager.AddStat(const StatID: AnsiString): TSteamStat;
Begin
Result := Self.GetStat(StatID);
If Assigned(Result) Then
Exit;
Result := TSteamStat.Create(StatID);
Inc(_StatCount);
SetLength(_Stats, _StatCount);
_Stats[Pred(_StatCount)] := Result;
_StatsRequested := True;
End;
Function TSteamManager.GetStat(const StatID: AnsiString): TSteamStat;
Var
I:Integer;
Begin
For I:=0 To Pred(_StatCount) Do
If _Stats[I]._ID = StatID Then
Begin
Result := _Stats[I];
Exit;
End;
Result := Nil;
End;
{ SteamStat }
Constructor TSteamStat.Create(const ID: AnsiString);
Begin
Self._ID := ID;
End;
Procedure TSteamStat.Load;
Begin
ISteamUserStats_GetStatInt(PAnsiChar(_ID), _Value);
//Log.Write(logDebug, 'Steam', 'Stat '+_ID + ' = ' + IntegerProperty.Stringify(_Value));
End;
Procedure TSteamStat.SetValue(const Val: Integer);
Begin
_Value := Val;
If (Not _SteamInstance._LoggedOn) Then
Exit;
ISteamUserStats_SetStatInt(PAnsiChar(_ID), _Value);
_SteamInstance._StoreStats := True;
End;
{ SteamLeaderboard }
Constructor TSteamLeaderboard.Create(const ID: AnsiString);
Begin
Self._ID := ID;
// TODO
(* SteamAPICall_t hSteamAPICall = SteamUserStats()->FindLeaderboard(pchLeaderboardName);
m_callResultFindLeaderboard.Set(hSteamAPICall, this,
&CSteamLeaderboards::OnFindLeaderboard);*)
End;
Procedure TSteamLeaderboard.Post(const Value: Integer);
Begin
// TODO
End;
End.
|
unit rsa;
interface
uses Windows, SysUtils, Classes;
const FINGERPRINT_LENGTH = 20;
{
int __stdcall rsa_base64_generate_key_pair(
int bits,
char **privatekey,
char **publickey
);
}
function rsa_base64_generate_key_pair(
bits: integer;
var privatekey: PChar;
var publickey: PChar
): integer; stdcall;
{
int __stdcall rsa_base64_get_keysize(const char *rsa_base64);
}
function rsa_base64_get_keysize(const rsa_base64: PChar): integer; stdcall;
{
int __stdcall rsa_base64_get_fingerprint(
const char *rsa_base64,
unsigned char *fingerprint
);
// fingerprint size must be FINGERPRINT_LENGTH
}
function rsa_base64_get_fingerprint(
const rsa_base64: PChar;
fingerprint: PByte
): integer; stdcall;
{
int __stdcall rsa_base64_publickey_from_privatekey(
const char *rsa_privatekey,
char **rsa_publickey
);
}
function rsa_base64_publickey_from_privatekey(
const rsa_privatekey: PChar;
var rsa_publickey: PChar
): integer; stdcall;
{
int __stdcall rsa_base64_private_encrypt(
const char *rsa_base64,
int inlen,
const char *indata,
int *outlen,
char **outdata
);
}
function rsa_base64_private_encrypt(
const rsa_base64: PChar;
inlen: integer;
const indata: PByte;
var outlen: integer;
var outdata: PByte
): integer; stdcall;
{
int __stdcall rsa_base64_public_decrypt(
const char *rsa_base64,
int inlen,
const char *indata,
int *outlen,
char **outdata
);
}
function rsa_base64_public_decrypt(
const rsa_base64: PChar;
inlen: integer;
const indata: PByte;
var outlen: integer;
var outdata: PByte
): integer; stdcall;
{
int __stdcall rsa_base64_public_encrypt(
const char *rsa_base64,
int inlen,
const char *indata,
int *outlen,
char **outdata
);
}
function rsa_base64_public_encrypt(
const rsa_base64: PChar;
inlen: integer;
const indata: PByte;
var outlen: integer;
var outdata: PByte
): integer; stdcall;
{
int __stdcall rsa_base64_private_decrypt(
const char *rsa_base64,
int inlen,
const char *indata,
int *outlen,
char **outdata
);
}
function rsa_base64_private_decrypt(
const rsa_base64: PChar;
inlen: integer;
const indata: PByte;
var outlen: integer;
var outdata: PByte
): integer; stdcall;
{
int __stdcall rsa_base64_private_encrypt_to_base64(
const char *rsa_base64,
int inlen,
const unsigned char *indata,
char **outbase64
);
}
function rsa_base64_private_encrypt_to_base64(
const rsa_base64: PChar;
inlen: integer;
const indata: PByte;
var outbase64: PChar
): integer; stdcall;
{
int __stdcall rsa_base64_public_decrypt_from_base64(
const char *rsa_base64,
const char *inbase64,
int *outlen,
unsigned char **outdata
);
}
function rsa_base64_public_decrypt_from_base64(
const rsa_base64: PChar;
const inbase64: PChar;
var outlen: integer;
var outdata: PByte
): integer; stdcall;
{
int __stdcall rsa_base64_public_encrypt_to_base64(
const char *rsa_base64,
int inlen,
const unsigned char *indata,
char **outbase64
);
}
function rsa_base64_public_encrypt_to_base64(
const rsa_base64: PChar;
inlen: integer;
const indata: PByte;
var outbase64: PChar
): integer; stdcall;
{
int __stdcall rsa_base64_private_decrypt_from_base64(
const char *rsa_base64,
const char *inbase64,
int *outlen,
unsigned char **outdata
);
}
function rsa_base64_private_decrypt_from_base64(
const rsa_base64: PChar;
const inbase64: PChar;
var outlen: integer;
var outdata: PByte
): integer; stdcall;
function rsa_base64_get_fingerprint_string(const rsa_base64: string): string;
implementation
const rsa_dll = 'popmm.dll';
function rsa_base64_generate_key_pair; external rsa_dll name 'rsa_base64_generate_key_pair';
function rsa_base64_get_keysize; external rsa_dll name 'rsa_base64_get_keysize';
function rsa_base64_get_fingerprint; external rsa_dll name 'rsa_base64_get_fingerprint';
function rsa_base64_publickey_from_privatekey; external rsa_dll name 'rsa_base64_publickey_from_privatekey';
function rsa_base64_private_encrypt; external rsa_dll name 'rsa_base64_private_encrypt';
function rsa_base64_public_decrypt; external rsa_dll name 'rsa_base64_public_decrypt';
function rsa_base64_public_encrypt; external rsa_dll name 'rsa_base64_public_encrypt';
function rsa_base64_private_decrypt; external rsa_dll name 'rsa_base64_private_decrypt';
function rsa_base64_private_encrypt_to_base64; external rsa_dll name 'rsa_base64_private_encrypt_to_base64';
function rsa_base64_public_decrypt_from_base64; external rsa_dll name 'rsa_base64_public_decrypt_from_base64';
function rsa_base64_public_encrypt_to_base64; external rsa_dll name 'rsa_base64_private_encrypt_to_base64';
function rsa_base64_private_decrypt_from_base64; external rsa_dll name 'rsa_base64_public_decrypt_from_base64';
function rsa_base64_get_fingerprint_string(const rsa_base64: string): string;
var
fp: array [1..FINGERPRINT_LENGTH] of byte;
n: integer;
begin
Result := '';
FillChar(fp, sizeof(fp), 0);
rsa_base64_get_fingerprint(PChar(rsa_base64), @fp);
for n := low(fp) to high(fp) do
begin
Result := Result + IntToHex(fp[n], 2);
end;
end;
end.
|
unit ScriptDatosEngine;
interface
uses ScriptEngine, Script_Datos;
type
TScriptDatosEngine = class(TScriptEngine)
private
FEDatoNotFound: boolean;
protected
Datos: TScriptDatos;
public
constructor Create(const VerticalCache: Boolean); reintroduce;
destructor Destroy; override;
procedure Load(const OIDValor: integer; const OIDSesion: integer);
function Execute: boolean; override;
procedure OnEDatoNotFound;
property EDatoNotFound: boolean read FEDatoNotFound;
end;
implementation
uses uPSI_Datos, uPSI_Mensaje, Script_Mensaje;
{ TScriptDatosEngine }
constructor TScriptDatosEngine.Create(const VerticalCache: Boolean);
begin
inherited Create;
RegisterPlugin(TPSImport_Mensaje, TScriptMensaje);
RegisterPlugin(TPSImport_Datos, TScriptDatos);
Datos := TScriptDatos.Create(Self, VerticalCache);
RegisterScriptRootClass('Datos', Datos);
end;
destructor TScriptDatosEngine.Destroy;
begin
Datos.Free;
inherited;
end;
function TScriptDatosEngine.Execute: boolean;
begin
FEDatoNotFound := false;
Result := inherited Execute;
if FEDatoNotFound then
Result := false;
end;
procedure TScriptDatosEngine.Load(const OIDValor, OIDSesion: integer);
begin
Datos.OIDValor := OIDValor;
Datos.OIDSesion := OIDSesion;
end;
procedure TScriptDatosEngine.OnEDatoNotFound;
begin
FEDatoNotFound := true;
Stop;
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit CoreAppImpl;
interface
{$MODE OBJFPC}
uses
RunnableIntf,
DependencyContainerIntf,
AppIntf,
DispatcherIntf,
EnvironmentIntf,
EnvironmentEnumeratorIntf,
ErrorHandlerIntf,
StdInIntf,
CoreAppConsts;
type
(*!-----------------------------------------------
* Base abstract class that implements IWebApplication
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TCoreWebApplication = class(TInterfacedObject, IWebApplication, IRunnable)
protected
dependencyContainer : IDependencyContainer;
dispatcher : IDispatcher;
environment : ICGIEnvironment;
errorHandler : IErrorHandler;
fStdInReader : IStdIn;
(*!-----------------------------------------------
* execute application and write response
*------------------------------------------------
* @return current application instance
*-----------------------------------------------
* TODO: need to think about how to execute when
* application is run as daemon.
*-----------------------------------------------*)
function execute() : IRunnable;
procedure reset();
(*!-----------------------------------------------
* initialize application dependencies
*------------------------------------------------
* @param container dependency container
* @return true if application dependency succesfully
* constructed
*-----------------------------------------------*)
function initialize(const container : IDependencyContainer) : boolean; virtual;
(*!-----------------------------------------------
* Build application route dispatcher
*------------------------------------------------
* @param container dependency container
*-----------------------------------------------*)
procedure buildDispatcher(const container : IDependencyContainer);
(*!-----------------------------------------------
* Build application dependencies
*------------------------------------------------
* @param container dependency container
*-----------------------------------------------*)
procedure buildDependencies(const container : IDependencyContainer); virtual; abstract;
(*!-----------------------------------------------
* Build application routes
*------------------------------------------------
* @param container dependency container
*-----------------------------------------------*)
procedure buildRoutes(const container : IDependencyContainer); virtual; abstract;
(*!-----------------------------------------------
* initialize application route dispatcher
*------------------------------------------------
* @param container dependency container
* @return dispatcher instance
*-----------------------------------------------*)
function initDispatcher(const container : IDependencyContainer) : IDispatcher; virtual; abstract;
public
(*!-----------------------------------------------
* constructor
*------------------------------------------------
* @param container dependency container
* @param env CGI environment instance
* @param errHandler error handler
* @param stdIn standard input reader
*-----------------------------------------------*)
constructor create(
const container : IDependencyContainer;
const env : ICGIEnvironment;
const errHandler : IErrorHandler;
const stdInReader : IStdIn
);
destructor destroy(); override;
function run() : IRunnable; virtual; abstract;
end;
implementation
uses
SysUtils,
ResponseIntf,
///exception-related units
EInvalidDispatcherImpl;
procedure TCoreWebApplication.reset();
begin
dispatcher := nil;
environment := nil;
errorHandler := nil;
dependencyContainer := nil;
fStdInReader := nil;
end;
(*!-----------------------------------------------
* constructor
*------------------------------------------------
* @param container dependency container
* @param env CGI environment instance
* @param errHandler error handler
*-----------------------------------------------
* errHandler is injected as application dependencies
* instead of using dependency container because
* we need to make sure that during building
* application dependencies and routes, if something
* goes wrong, we can be sure that there is error handler
* to handle the exception
*-----------------------------------------------*)
constructor TCoreWebApplication.create(
const container : IDependencyContainer;
const env : ICGIEnvironment;
const errHandler : IErrorHandler;
const stdInReader : IStdIn
);
begin
inherited create();
randomize();
reset();
dependencyContainer := container;
environment := env;
errorHandler := errHandler;
fStdInReader := stdInReader;
end;
(*!-----------------------------------------------
* destructor
*-----------------------------------------------*)
destructor TCoreWebApplication.destroy();
begin
reset();
inherited destroy();
end;
(*!-----------------------------------------------
* Build application route dispatcher
*------------------------------------------------
* @param container dependency container
* @throws EInvalidDispatcher
*-----------------------------------------------
* route dispatcher is essentials but because
* we allow user to use IDispatcher
* implementation they like, we need to be informed
* about it.
*-----------------------------------------------*)
procedure TCoreWebApplication.buildDispatcher(const container : IDependencyContainer);
begin
dispatcher := initDispatcher(container);
if (dispatcher = nil) then
begin
raise EInvalidDispatcher.create(sErrInvalidDispatcher);
end;
end;
(*!-----------------------------------------------
* initialize application dependencies
*------------------------------------------------
* @param container dependency container
* @return true if application dependency succesfully
* constructed
*-----------------------------------------------
* TODO: need to think about how to initialize when
* application is run as daemon. Current implementation
* is we put this in run() method which maybe not right
* place.
*-----------------------------------------------*)
function TCoreWebApplication.initialize(const container : IDependencyContainer) : boolean;
begin
buildDependencies(container);
buildRoutes(container);
buildDispatcher(container);
result := true;
end;
(*!-----------------------------------------------
* execute application and write response
*------------------------------------------------
* @return current application instance
*-----------------------------------------------
* TODO: need to think about how to execute when
* application is run as daemon.
*-----------------------------------------------*)
function TCoreWebApplication.execute() : IRunnable;
var response : IResponse;
begin
response := dispatcher.dispatchRequest(environment, fStdInReader);
try
response.write();
result := self;
finally
response := nil;
end;
end;
end.
|
unit signals;
interface
uses threads, spinlock, kernel, config;
type
TSignalState = (ssSignaled, ssNotSignaled);
PSignal = ^TSignal;
TSignal = record
SignalGuard: TSpinlock;
State: TSignalState;
Owner: PThread;
Waiting: PThread;
AutoReset: boolean;
end;
procedure CreateSignal(var Signal: TSignal; InitiallySignaled, AutoReset: boolean);
procedure DestroySignal(var Signal: TSignal);
procedure WaitForSignal(var Signal: TSignal);
procedure SignalSignal(var Signal: TSignal);
implementation
uses scheduler, mutex;
procedure CreateSignal(var Signal: TSignal; InitiallySignaled, AutoReset: boolean);
begin
if InitiallySignaled then
Signal.State := ssSignaled
else
Signal.State := ssNotSignaled;
Signal.Owner := nil;
Signal.Waiting := nil;
Signal.AutoReset := AutoReset;
SpinInit(Signal.SignalGuard);
end;
procedure DestroySignal(var Signal: TSignal);
begin
if Signal.Owner <> nil then ErrorHandler(etLockedResourceDestroyed, GetCurrentThread);
if Signal.Waiting <> nil then ErrorHandler(etRequiredResourceDestroyed, GetCurrentThread);
end;
procedure WaitForSignal(var Signal: TSignal);
var p,t: PThread;
NewPrio: TThreadPriority;
function FindWaitee(Thread: PThread): PThread;
begin
FindWaitee := Thread;
while FindWaitee^.State = tsWaiting do
case FindWaitee^.WaitType of
wtMutex: FindWaitee := PMutex(FindWaitee^.WaitingFor)^.Owner;
wtSignal: FindWaitee := PSignal(FindWaitee^.WaitingFor)^.Owner;
end;
end;
begin
SpinWait(Signal.SignalGuard);
DisableScheduling;
t := GetCurrentThread;
if Signal.State = ssNotSignaled then
begin
if DeadlockDetection then
begin
if FindWaitee(Signal.Owner) = t then
ErrorHandler(etDeadlock, t);
end;
t^.Waitlist := nil;
if Signal.Waiting = nil then
Signal.Waiting := t
else
begin
p := Signal.Waiting;
while assigned(p^.Waitlist) do
p := p^.Waitlist;
p^.Waitlist := t;
end;
t^.WaitType := wtSignal;
t^.WaitingFor := @Signal;
if SignalPriorityInheritance then
begin
NewPrio:=t^.Priority;
if NewPrio>Signal.Owner^.Priority then
ChangePriority(Signal.Owner^, NewPrio);
end;
BlockThread(Signal.SignalGuard,true);
end
else
begin
SpinUnlock(Signal.SignalGuard);
EnableScheduling;
end;
end;
procedure SignalSignal(var Signal: TSignal);
var p: PThread;
begin
SpinWait(Signal.SignalGuard);
if SignalPriorityInheritance then ChangePriority(Signal.Owner^, Signal.Owner^.StoredPriority);
if Signal.AutoReset then
Signal.State := ssNotSignaled
else
Signal.State := ssSignaled;
p := Signal.Waiting;
while assigned(p) do
begin
UnblockThread(p^);
p := p^.Waitlist;
end;
Signal.Waiting := nil;
SpinUnlock(Signal.SignalGuard);
end;
end.
|
unit Aspect4D.UnitTest.Security;
interface
uses
Aspect4D,
System.Rtti,
System.SysUtils;
type
ESecurityException = class(Exception);
SecurityAttribute = class(AspectAttribute)
private
fPassword: string;
protected
{ protected declarations }
public
constructor Create(const password: string);
property Password: string read fPassword;
end;
TSecurityAspect = class(TAspect, IAspect)
private
{ private declarations }
protected
function GetName: string;
procedure DoBefore(instance: TObject; method: TRttiMethod;
const args: TArray<TValue>; out invoke: Boolean; out result: TValue);
procedure DoAfter(instance: TObject; method: TRttiMethod;
const args: TArray<TValue>; var result: TValue);
procedure DoException(instance: TObject; method: TRttiMethod;
const args: TArray<TValue>; out raiseException: Boolean;
theException: Exception; out result: TValue);
public
{ public declarations }
end;
var
GlobalPasswordSystem: string = '';
implementation
{ SecurityAttribute }
constructor SecurityAttribute.Create(const password: string);
begin
fPassword := password;
end;
{ TSecurityAspect }
procedure TSecurityAspect.DoAfter(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; var result: TValue);
begin
// Method unused
end;
procedure TSecurityAspect.DoBefore(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out invoke: Boolean;
out result: TValue);
var
att: TCustomAttribute;
begin
for att in method.GetAttributes do
if att is SecurityAttribute then
if (GlobalPasswordSystem <> SecurityAttribute(att).Password) then
raise ESecurityException.Create('The password is invalid!');
end;
procedure TSecurityAspect.DoException(instance: TObject; method: TRttiMethod; const args: TArray<TValue>; out raiseException: Boolean;
theException: Exception; out result: TValue);
begin
// Method unused
end;
function TSecurityAspect.GetName: string;
begin
Result := Self.QualifiedClassName;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.