text stringlengths 14 6.51M |
|---|
unit RBTree;
interface
uses
Classes;
type
TColor = (clRed, clBlack);
TRBNodeP = ^TRBNode;
TRBNode = record
Key: Pointer;
Left, Right, Parent: TRBNodeP;
Color: TColor;
Data: Pointer;
end;
TRBTree = class
private
FCount: Integer;
Root: TRBNodeP;
Leftmost: TRBNodeP;
Rightmost: TRBNodeP;
CompareFunc: TListSortCompare;
procedure RotateLeft(var x: TRBNodeP);
procedure RotateRight(var x: TRBNodeP);
function Minimum(var x: TRBNodeP): TRBNodeP;
function Maximum(var x: TRBNodeP): TRBNodeP;
procedure fast_erase(x: TRBNodeP);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Find(Key: Pointer): TRBNodeP;
function Add(Key: Pointer; Data: Pointer): TRBNodeP;
procedure Delete(z: TRBNodeP);
procedure RBInc(var x: TRBNodeP);
procedure RBDec(var x: TRBNodeP);
public
property First: TRBNodeP read leftmost;
property Last: TRBNodeP read rightmost;
property Count: Integer read FCount;
end;
implementation
function ComparePointer(Item1, Item2: Pointer): Integer;
begin
if Longword (Item1) < Longword(Item2) then
begin
Result := -1;
end
else if (Item1 = Item2) then
begin
Result := 0;
end
else
begin
Result := 1;
end
end;
procedure TRBTree.RBInc(var x: TRBNodeP);
var
y: TRBNodeP;
begin
if (x^.Right <> nil) then
begin
x := x^.Right;
while (x^.Left <> nil) do
begin
x := x^.Left;
end;
end
else
begin
y := x^.Parent;
while (x = y^.Right) do
begin
x := y;
y := y^.Parent;
end;
if (x^.Right <> y) then
x := y;
end
end;
procedure TRBTree.RBDec(var x: TRBNodeP);
var
y: TRBNodeP;
begin
if (x^.Left <> nil) then
begin
y := x^.Left;
while (y^.Right <> nil) do
begin
y := y^.Right;
end;
x := y;
end
else
begin
y := x^.Parent;
while (x = y^.Left) do
begin
x := y;
y := y^.Parent;
end;
x := y;
end
end;
constructor TRBTree.Create;
begin
inherited Create;
FCount := 0;
CompareFunc := ComparePointer;
Root := nil;
Leftmost := nil;
Rightmost := nil;
end;
destructor TRBTree.Destroy();
begin
Clear;
inherited Destroy;
end;
procedure TRBTree.fast_erase(x: TRBNodeP);
begin
if (x^.Left <> nil) then fast_erase(x^.Left);
if (x^.Right <> nil) then fast_erase(x^.Right);
dispose(x);
end;
procedure TRBTree.Clear;
begin
if (Root <> nil) then
fast_erase(Root);
Root := nil;
Leftmost := nil;
Rightmost := nil;
FCount := 0;
end;
function TRBTree.Find(Key: Pointer): TRBNodeP;
var
cmp: Integer;
begin
Result := root;
while (Result <> nil) do
begin
cmp := CompareFunc(Result^.Key, Key);
if cmp < 0 then
begin
Result := Result^.Right;
end
else if cmp > 0 then
begin
Result := Result^.Left;
end
else
begin
break;
end;
end;
end;
procedure TRBTree.RotateLeft(var x: TRBNodeP);
var
y: TRBNodeP;
begin
y := x^.Right;
x^.Right := y^.Left;
if (y^.Left <> nil) then
begin
y^.Left^.Parent := x;
end;
y^.Parent := x^.Parent;
if (x = Root) then
begin
Root := y;
end
else if (x = x^.Parent^.Left) then
begin
x^.Parent^.Left := y;
end
else
begin
x^.Parent^.Right := y;
end;
y^.Left := x;
x^.Parent := y;
end;
procedure TRBTree.RotateRight(var x: TRBNodeP);
var
y: TRBNodeP;
begin
y := x^.Left;
x^.Left := y^.Right;
if (y^.Right <> nil) then
begin
y^.Right^.Parent := x;
end;
y^.Parent := x^.Parent;
if (x = Root) then
begin
root := y;
end
else if (x = x^.Parent^.Right) then
begin
x^.Parent^.Right := y;
end
else
begin
x^.Parent^.Left := y;
end;
y^.Right := x;
x^.Parent := y;
end;
function TRBTree.Minimum(var x: TRBNodeP): TRBNodeP;
begin
Result := x;
while (Result^.Left <> nil) do
Result := Result^.Left;
end;
function TRBTree.Maximum(var x: TRBNodeP): TRBNodeP;
begin
Result := x;
while (Result^.Right <> nil) do
Result := Result^.Right;
end;
function TRBTree.Add(key: Pointer; Data: Pointer): TRBNodeP;
var
x, y, z, zpp: TRBNodeP;
cmp: Integer;
begin
z := New(TRBNodeP);
{ Initialize fields in new node z }
z^.Key := key;
z^.Left := nil;
z^.Right := nil;
z^.Color := clRed;
z^.Data := Data;
Inc(FCount);
Result := z;
{ Maintain leftmost and rightmost nodes }
if ((leftmost = nil) or (compareFunc(key, leftmost^.Key) < 0)) then
begin
leftmost := z;
end;
if ((rightmost = nil) or (compareFunc(rightmost^.Key, key) < 0)) then
begin
rightmost := z;
end;
{ Insert node z }
y := nil;
x := root;
while (x <> nil) do
begin
y := x;
cmp := compareFunc(key, x^.Key);
if (cmp < 0) then
begin
x := x^.Left;
end
else if (cmp > 0) then
begin
x := x^.Right;
end
else
begin
{ Value already exists in tree. }
Result := x;
Dec(FCount);
dispose(z);
exit;
end;
end;
z^.Parent := y;
if (y = nil) then
begin
Root := z;
end
else if (compareFunc(key, y^.Key) < 0) then
begin
y^.Left := z;
end
else
begin
y^.Right := z;
end;
{ Rebalance tree }
while ((z <> Root) and (z^.Parent^.Color = clRed)) do
begin
zpp := z^.Parent^.Parent;
if (z^.Parent = zpp^.Left) then
begin
y := zpp^.Right;
if ((y <> nil) and (y^.color = clRed)) then
begin
z^.Parent^.Color := clBlack;
y^.Color := clBlack;
zpp^.Color := clRed;
z := zpp;
end
else
begin
if (z = z^.Parent^.Right) then
begin
z := z^.Parent;
rotateLeft(z);
end;
z^.Parent^.Color := clBlack;
zpp^.Color := clRed;
rotateRight(zpp);
end;
end
else
begin
y := zpp^.Left;
if ((y <> nil) and (y^.Color = clRed)) then
begin
z^.Parent^.Color := clBlack;
y^.Color := clBlack;
zpp^.Color := clRed;
z := zpp;
end
else
begin
if (z = z^.Parent^.Left) then
begin
z := z^.Parent;
rotateRight(z);
end;
z^.Parent^.Color := clBlack;
zpp^.Color := clRed;
rotateLeft(zpp);
end;
end;
end;
root^.Color := clBlack;
end;
procedure TRBTree.Delete(Z: TRBNodeP);
var
w, x, y, x_parent: TRBNodeP;
tmpcol: TColor;
begin
if Z = NIL then Exit;
y := z;
x := nil;
x_parent := nil;
if (y^.Left = nil) then
begin { z has at most one non-null child. y = z. }
x := y^.Right; { x might be null. }
end
else
begin
if (y^.Right = nil) then
begin { z has exactly one non-null child. y = z. }
x := y^.Left; { x is not null. }
end
else
begin
{ z has two non-null children. Set y to }
y := y^.Right; { z's successor. x might be null. }
while (y^.Left <> nil) do
begin
y := y^.Left;
end;
x := y^.Right;
end;
end;
if (y <> z) then
begin
{ "copy y's sattelite data into z" }
{ relink y in place of z. y is z's successor }
z^.Left^.Parent := y;
y^.Left := z^.Left;
if (y <> z^.Right) then
begin
x_parent := y^.Parent;
if (x <> nil) then
begin
x^.Parent := y^.Parent;
end;
y^.Parent^.Left := x; { y must be a child of left }
y^.Right := z^.Right;
z^.Right^.Parent := y;
end
else
begin
x_parent := y;
end;
if (Root = z) then
begin
Root := y;
end
else
if (z^.Parent^.Left = z) then
begin
z^.Parent^.Left := y;
end
else
begin
z^.Parent^.Right := y;
end;
y^.Parent := z^.Parent;
tmpcol := y^.Color;
y^.Color := z^.Color;
z^.Color := tmpcol;
y := z;
{ y now points to node to be actually deleted }
end
else
begin { y = z }
x_parent := y^.Parent;
if (x <> nil) then
begin
x^.Parent := y^.Parent;
end;
if (root = z) then
begin
root := x;
end
else
begin
if (z^.Parent^.Left = z) then
begin
z^.Parent^.Left := x;
end
else
begin
z^.Parent^.Right := x;
end;
end;
if (leftmost = z) then
begin
if (z^.Right = nil) then
begin { z^.left must be null also }
leftmost := z^.Parent;
end
else
begin
leftmost := minimum(x);
end;
end;
if (rightmost = z) then
begin
if (z^.Left = nil) then
begin { z^.right must be null also }
rightmost := z^.Parent;
end
else
begin { x == z^.left }
rightmost := maximum(x);
end;
end;
end;
{ Rebalance tree }
if (y^.color = clBlack) then
begin
while ((x <> Root) and ((x = nil) or (x^.Color = clBlack))) do
begin
if (x = x_parent^.Left) then
begin
w := x_parent^.Right;
if (w^.color = clRed) then
begin
w^.color := clBlack;
x_parent^.color := clRed;
rotateLeft(x_parent);
w := x_parent^.Right;
end;
if (((w^.left = nil) or
(w^.left^.color = clBlack)) and
((w^.right = nil) or
(w^.right^.color = clBlack))) then
begin
w^.Color := clRed;
x := x_parent;
x_parent := x_parent^.Parent;
end
else
begin
if ((w^.Right = nil) or (w^.Right^.Color = clBlack)) then
begin
w^.Left^.Color := clBlack;
w^.Color := clRed;
rotateRight(w);
w := x_parent^.Right;
end;
w^.Color := x_parent^.Color;
x_parent^.Color := clBlack;
if (w^.Right <> nil) then
begin
w^.Right^.Color := clBlack;
end;
rotateLeft(x_parent);
x := Root; { break; }
end
end
else
begin
{ same as above, with right <^. left. }
w := x_parent^.Left;
if (w^.color = clRed) then
begin
w^.Color := clBlack;
x_parent^.Color := clRed;
rotateRight(x_parent);
w := x_parent^.Left;
end;
if (((w^.right = nil) or
(w^.right^.color = clBlack)) and
((w^.left = nil) or
(w^.left^.color = clBlack))) then
begin
w^.Color := clRed;
x := x_parent;
x_parent := x_parent^.Parent;
end
else
begin
if ((w^.Left = nil) or (w^.Left^.Color = clBlack)) then
begin
w^.Right^.Color := clBlack;
w^.Color := clRed;
rotateLeft(w);
w := x_parent^.Left;
end;
w^.Color := x_parent^.Color;
x_parent^.Color := clBlack;
if (w^.Left <> nil) then
begin
w^.Left^.Color := clBlack;
end;
rotateRight(x_parent);
x := Root; { break; }
end;
end;
end;
if (x <> nil) then
begin
x^.Color := clBlack;
end;
end;
Dec(FCount);
dispose(y);
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PAXCOMP_EVENT.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
{$O-}
unit PAXCOMP_EVENT;
interface
uses {$I uses.def}
SysUtils,
Classes,
PAXCOMP_TYPES,
PAXCOMP_SYS;
type
TEventHandlerRec = class
public
_ESI: Integer; // 4
_EDI: Integer; // 8
Code: Pointer; // 12
Data: TObject; // 16
Prog: Pointer; // 20
CallConv: Integer; // 24
RetSize: Integer; // 28
procedure Invoke;
procedure InvokeDirect;
end;
TEventHandlerList = class(TTypedList)
private
function GetRecord(I: Integer): TEventHandlerRec;
public
function Lookup(Code: Pointer; Data: TObject): TEventHandlerRec;
function Add(Prog, Code, Data: Pointer; CallConv, RetSize: Integer): TEventHandlerRec;
property Records[I: Integer]: TEventHandlerRec read GetRecord; default;
end;
implementation
uses
PAXCOMP_CONSTANTS,
PAXCOMP_PROG,
PAXCOMP_STDLIB,
PAXCOMP_PAUSE,
PAXCOMP_INVOKE;
// -- TEventHandlerRec ---------------------------------------------------------
{$IFDEF PAX64}
procedure TEventHandlerRec.InvokeDirect;
begin
RaiseNotImpl;
end;
{$ELSE}
procedure TEventHandlerRec.InvokeDirect; assembler;
asm
sub esp, 4 // reserve place for Code
push ecx
mov ecx, [eax + 12]
// add ecx, 14
mov [esp + 4], ecx // Code
pop ecx
mov esi, [eax + 4] // esi
mov edi, [eax + 8] // edi
mov eax, [eax + 16] // Data
add esp, 4
mov ebx, [esp - 4]
jmp ebx
end;
{$ENDIF}
{$IFDEF PAX64}
procedure SaveRegisters(var _RAX, _RCX, _RDX, _R8, _R9: IntPax); assembler;
asm
mov _RAX, rax
mov _RCX, rcx
mov _RDX, rdx
mov _R8, r8
mov _R9, r9
end;
{$ENDIF}
procedure TEventHandlerRec.Invoke;
var
P: TProgram;
EPoint, OldEPoint: TInvoke;
{$IFDEF PAX64}
_RAX, _RCX, _RDX, _R8, _R9: IntPax;
{$ELSE}
_EAX, _ECX, _EDX, _EBP: Integer;
{$ENDIF}
OldESP0: Integer;
OldIsEvent: Boolean;
S: TMemoryStream;
begin
{$IFDEF PAX64}
SaveRegisters(_RAX, _RCX, _RDX, _R8, _R9);
{$ELSE}
asm
mov _EBP, ebp
mov _EAX, eax
mov _ECX, ecx
mov _EDX, edx
end;
{$ENDIF}
P := Prog;
P := P.RootProg;
if not P.IsPauseUpdated then
begin
EPoint := TInvoke.CreateInternal;
{$IFDEF PAX64}
EPoint._EAX := _RAX;
EPoint._ECX := _RCX;
EPoint._EDX := _RDX;
EPoint._R8 := _R8;
EPoint._R9 := _R9;
{$ELSE}
EPoint._EAX := _EAX;
EPoint._ECX := _ECX;
EPoint._EDX := _EDX;
{$ENDIF}
EPoint.CallConv := CallConv;
EPoint.StackSize := RetSize;
EPoint.StackFrame := Pointer(_EBP + 4 + RetSize);
OldEPoint := P.EPoint;
OldESP0 := P.RootESP0;
OldIsEvent := P.RootIsEvent;
S := TMemoryStream.Create;
try
P.RootTryStack.SaveToStream(S);
P.RootTryStack.Clear;
P.RootIsEvent := true;
EPoint.Address := Code;
EPoint.SetThis(Data);
if CallConv = ccREGISTER then
EPoint._EAX := Integer(Data);
P.EPoint := EPoint;
P.RunEx;
finally
S.Position := 0;
P.RootTryStack.LoadFromStream(S);
P.RootESP0 := OldESP0;
P.RootIsEvent := OldIsEvent;
P.EPoint := OldEPoint;
FreeAndNil(EPoint);
FreeAndNil(S);
end;
// emulate ret RetSize
if P.IsHalted then
raise THaltException.Create(P.ExitCode);
if P.HasError then
if P.fCurrException <> nil then
begin
if P.PauseRec <> nil then
begin
P.PauseRec.Clear;
end;
raise P.fCurrException;
end;
end;
{$IFDEF PAX64}
Exit;
{$ELSE}
if RetSize = 0 then
Exit;
_ecx := RetSize;
{$ENDIF}
{
asm
mov ecx, _ecx
mov esp, ebp
pop ebp
mov ebx, [esp]
@@loop:
pop edx
sub ecx, 4
jnz @@loop
pop edx
jmp ebx
end;
}
{$IFDEF PAX64}
Exit;
{$ELSE}
asm
mov ecx, _ecx
mov esp, ebp
pop ebp
fild dword ptr [esp]
@@loop:
pop edx
sub ecx, 4
jnz @@loop
fistp dword ptr [esp]
pop edx
jmp edx
end;
{$ENDIF}
end;
// -- TEventHandlerList --------------------------------------------------------
function TEventHandlerList.GetRecord(I: Integer): TEventHandlerRec;
begin
result := TEventHandlerRec(L[I]);
end;
function TEventHandlerList.Add(Prog, Code, Data: Pointer; CallConv, RetSize: Integer): TEventHandlerRec;
begin
result := Lookup(Code, Data);
if result = nil then
begin
result := TEventHandlerRec.Create;
result.Code := Code;
result.Data := Data;
result._ESI := Integer(TProgram(Prog).DataPtr);
result._EDI := Integer(TProgram(Prog).CodePtr);
result.Prog := Prog;
result.CallConv := CallConv;
result.RetSize := RetSize;
L.Add(result);
end;
end;
function TEventHandlerList.Lookup(Code: Pointer; Data: TObject): TEventHandlerRec;
var
R: TEventHandlerRec;
I: Integer;
begin
for I:=0 to Count - 1 do
begin
R := Records[I];
if (R.Code = Code) and (R.Data = Data) then
begin
result := R;
Exit;
end;
end;
result := nil;
end;
end.
|
unit LogbooksTable;
{$mode objfpc}{$H+}
//========================================================================================
//
// Unit : LogbooksTable.pas
//
// Description :
//
// Called By :
//
// Calls : dlgHUDirNameEntry
//
// Ver. : 1.00
//
// Date : 18 Apr 2019
//
// *ToDo:
//
//========================================================================================
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
// Applikcation Units
AppSettings,
// HULib Units
HUConstants, HUDirNameEntry;
type
{ TfrmLogbooksTable }
TfrmLogbooksTable = class(TForm)
memMode: TMemo;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
fMode : string;
fLogName : string;
fLogPath : string;
function GetMode : string;
procedure SetMode(Mode : string);
function GetLogName : string;
procedure SetLogName(LogName : string);
function GetLogPath : string;
procedure SetLogPath(LogPath : string);
public
property pMode : string read GetMode write SetMode;
property pLogName : string read GetLogName write SetLogName;
property pLogPath : string read GetLogPath write SetLogPath;
procedure CreateNewLogbook;
end;// TfrmLogbooksTable
var
frmLogbooksTable: TfrmLogbooksTable;
implementation
{$R *.lfm}
//========================================================================================
// PRIVATE CONSTANTS
//========================================================================================
//========================================================================================
// PUBLIC CONSTANTS
//========================================================================================
//========================================================================================
// PRIVATE VARIABLES
//========================================================================================
//========================================================================================
// PUBLIC VARIABLES
//========================================================================================
//========================================================================================
// PRIVATE ROUTINES
//========================================================================================
//========================================================================================
// PUBLIC ROUTINES
//========================================================================================
procedure TfrmLogbooksTable.CreateNewLogbook;
var
vstrNewLogPath: string;
begin
dlgHUDirNameEntry.pDirName := '';
dlgHUDirNameEntry.pDirPath := frmSettings.pLogBooksDirectory;
dlgHUDirNameEntry.ShowModal;
vstrNewLogPath := dlgHUDirNameEntry.pDirPath;
// We cancelled here
if vstrNewLogPath = '' then
Exit;
if not CreateDir(vstrNewLogPath)then
begin
showmessage('Logbook FAILED');
exit;
end;
pMode := 'Create';
pLogName := dlgHUDirNameEntry.pDirName;
pLogPath := dlgHUDirNameEntry.pDirPath;
frmLogbooksTable.ShowModal ;
end;// procedure TfrmLogbooksTable.CreateNewLogbook
//========================================================================================
// PROPERTY ROUTINES
//========================================================================================
function TfrmLogbooksTable.GetMode: string;
begin
Result := fMode;
end;// function TfrmLogbooksTable.GetMode
//----------------------------------------------------------------------------------------
procedure TfrmLogbooksTable.SetMode(Mode: string);
begin
fMode := Mode;
end;// procedure TfrmLogbooksTable.SetMode
//========================================================================================
function TfrmLogbooksTable.GetLogName: string;
begin
Result := fLogName;
end;// function TfrmLogbooksTable.GetLogName
//----------------------------------------------------------------------------------------
procedure TfrmLogbooksTable.SetLogName(LogName: string);
begin
fLogName := LogName;
end;// procedure TfrmLogbooksTable.SetMode
//========================================================================================
function TfrmLogbooksTable.GetLogPath: string;
begin
Result := fLogPath;
end;// function TfrmLogbooksTable.GetLogPath
//----------------------------------------------------------------------------------------
procedure TfrmLogbooksTable.SetLogPath(LogPath: string);
begin
fLogPath := LogPath;
end;// procedure TfrmLogbooksTable.SetPath
//========================================================================================
// MENU ROUTINES
//========================================================================================
//========================================================================================
// COMMAND BUTTON ROUTINES
//========================================================================================
//========================================================================================
// CONTROL ROUTINES
//========================================================================================
//========================================================================================
// FILE ROUTINES
//========================================================================================
//========================================================================================
// FORM ROUTINES
//========================================================================================
procedure TfrmLogbooksTable.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
end;// procedure TfrmLogbooksTable.FormClose
//========================================================================================
procedure TfrmLogbooksTable.FormCreate(Sender: TObject);
begin
end;// procedure TfrmLogbooksTable.FormCreate
//========================================================================================
procedure TfrmLogbooksTable.FormShow(Sender: TObject);
begin
case pMode of
'Create': begin
memMode.Lines.Add('Creating Logbook');
memMode.Lines.Add(pLogName);
// Copy and Rename Databases
//CopyFile(const SrcFilename, DestFilename: string);
end;// 'Create'
'Edit': memMode.Text := 'Edit';
end;// case pMode of
end;// procedure TfrmLogbooksTable.FormShow
//========================================================================================
end.// unit LogbooksTable
|
{******************************************************************}
{ GDIPKerning }
{ }
{ home page : http://www.mwcs.de }
{ email : martin.walter@mwcs.de }
{ }
{ date : 20-11-2007 }
{ }
{ version : 1.1 }
{ }
{ Use of this file is permitted for commercial and non-commercial }
{ use, as long as the author is credited. }
{ This file (c) 2007 Martin Walter }
{ }
{ This Software is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. }
{ }
{ *****************************************************************}
unit GDIPKerning;
interface
uses
Winapi.Windows, System.Classes, Winapi.GDIPAPI, Winapi.GDIPOBJ;
type
TKerningPairs = array of TKerningPair;
PKerningPairs = ^TKerningPairs;
TKerning = record
Chars: Cardinal;
Cell: Integer;
Kerning: Integer;
end;
PKerning = ^TKerning;
TGPKerningText = class(TObject)
private
FKerningList: TList;
FKerningPairs: TKerningPairs;
FPairCount: Integer;
FLastFont: string;
FLastWeight: Integer;
FLastStyle: Integer;
FFontSizeFactor: Single;
FFont: HFont;
FOldFont: HFont;
FDC: HDC;
FGPFont: TGPFont;
procedure PrepareDC;
procedure UnprepareDC;
procedure PrepareFont(const LF: TLogFontW);
procedure UnprepareFont;
procedure PrepareKerning(const Font: TGPFont); overload;
procedure PrepareKerning(const Font: TGPFont; const Graphics: TGPGraphics;
WithFactor: Boolean); overload;
procedure UnprepareKerning;
procedure ClearKerningList;
procedure AddToKerningList(const First, Second: Word;
Cell, Kerning: Integer);
function IndexOfKerning(const First, Second: Word): Integer;
function GetDistance(const Index: Integer;
const DistanceFactor, KerningFactor: Single): Single;
procedure Clear;
function AddGlyphToPath(const Path: TGPGraphicsPath; const Char: WideChar;
const Family: TGPFontFamily; const Style: Integer; const Size: Single;
const Origin: TGPPointF; const Format: TGPStringFormat): TStatus;
function AddGlyphToGraphics(const Graphics: TGPGraphics;
const Char: WideChar; const Font: TGPFont; const Origin: TGPPointF;
const Format: TGPStringFormat; const Brush: TGPBrush): TStatus;
procedure AddUnderline(const Path: TGPGraphicsPath;
const Left, Top, Width: Single; const Font: TGPFont);
procedure AddStrikeOut(const Path: TGPGraphicsPath;
const Left, Top, Width: Single; const Font: TGPFont);
public
constructor Create;
destructor Destroy; override;
function AddToPath(const Path, UPath, SPath: TGPGraphicsPath;
const Text: string; const Family: TGPFontFamily; Style: Integer;
const Size: Single; Origin: TGPPointF; const Format: TGPStringFormat;
const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): TStatus; overload;
function AddToPath(const Path, UPath, SPath: TGPGraphicsPath;
const Text: string; const Family: TGPFontFamily; Style: Integer;
const Size: Single; Origin: TGPPoint; const Format: TGPStringFormat;
const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): TStatus; overload;
function AddToPath(const Path: TGPGraphicsPath; const Text: string;
const Family: TGPFontFamily; Style: Integer; const Size: Single;
Origin: TGPPointF; const Format: TGPStringFormat;
const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): TStatus; overload;
function AddToPath(const Path: TGPGraphicsPath; const Text: string;
const Family: TGPFontFamily; const Style: Integer; const Size: Single;
Origin: TGPPoint; const Format: TGPStringFormat;
const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): TStatus; overload;
function AddToGraphics(const Graphics: TGPGraphics;
const Text: string; const Font: TGPFont; Origin: TGPPointF;
const Format: TGPStringFormat; const Brush: TGPBrush;
const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): TStatus; overload;
function AddToGraphics(const Graphics: TGPGraphics;
const Text: string; const Font: TGPFont; Origin: TGPPoint;
const Format: TGPStringFormat; const Brush: TGPBrush;
const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): TStatus; overload;
function MeasureText(const Text: string; const Font: TGPFont;
const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): Single;
function GetCellWidth(const First, Second: Word;
const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): Single;
procedure Prepare(const Family: TGPFontFamily; Style: Integer;
const Size: Single; const Format: TGPStringFormat);
procedure Unprepare;
end;
function KerningText: TGPKerningText;
implementation
var
FKerningText: TGPKerningText;
function KerningText: TGPKerningText;
begin
if not Assigned(FKerningText) then
FKerningText := TGPKerningText.Create;
Result := FKerningText;
end;
{ TKerningText }
function TGPKerningText.AddGlyphToGraphics(const Graphics: TGPGraphics;
const Char: WideChar; const Font: TGPFont; const Origin: TGPPointF;
const Format: TGPStringFormat; const Brush: TGPBrush): TStatus;
begin
Result := Graphics.DrawString(Char, -1, Font, Origin, Format, Brush);
end;
function TGPKerningText.AddGlyphToPath(const Path: TGPGraphicsPath;
const Char: WideChar; const Family: TGPFontFamily; const Style: Integer;
const Size: Single; const Origin: TGPPointF;
const Format: TGPStringFormat): TStatus;
begin
Result := Path.AddString(Char, -1, Family, Style, Size, Origin, Format);
end;
procedure TGPKerningText.AddStrikeOut(const Path: TGPGraphicsPath;
const Left, Top, Width: Single; const Font: TGPFont);
var
YPos: Single;
Height: Single;
begin
YPos := Top + Font.GetSize / 2;
Height := Font.GetSize / 10;
Path.SetFillMode(FillModeWinding);
Path.AddRectangle(MakeRect(Left, YPos, Width, Height));
end;
function TGPKerningText.AddToGraphics(const Graphics: TGPGraphics;
const Text: string; const Font: TGPFont; Origin: TGPPointF;
const Format: TGPStringFormat; const Brush: TGPBrush;
const DistanceFactor: Single = 1; const KerningFactor: Single = 1): TStatus;
var
P1, P2: PWideChar;
Status: TStatus;
begin
Status := Ok;
if Text = '' then
begin
Result := Ok;
Exit;
end;
PrepareKerning(Font, Graphics, False);
try
P1 := PWideChar(Text);
while (P1^ <> #0) do
begin
Status := AddGlyphToGraphics(Graphics, P1^, Font, Origin, Format, Brush);
if Status <> Ok then
Break;
P2 := P1 + 1;
Origin.X := Origin.X + GetCellWidth(Word(P1^), Word(P2^),
DistanceFactor, KerningFactor);
Inc(P1);
end;
finally
UnprepareDC;
end;
Result := Status;
end;
function TGPKerningText.AddToGraphics(const Graphics: TGPGraphics;
const Text: string; const Font: TGPFont; Origin: TGPPoint;
const Format: TGPStringFormat; const Brush: TGPBrush;
const DistanceFactor: Single = 1; const KerningFactor: Single = 1): TStatus;
var
OriginF: TGPPointF;
begin
OriginF.X := Origin.X;
OriginF.Y := Origin.Y;
Result := AddToGraphics(Graphics, Text, Font, OriginF, Format, Brush,
DistanceFactor, KerningFactor);
end;
procedure TGPKerningText.AddToKerningList(const First, Second: Word;
Cell, Kerning: Integer);
var
Item: PKerning;
begin
GetMem(Item, SizeOf(TKerning));
Item^.Chars := First shl 16 + Second;
Item^.Cell := Cell;
Item^.Kerning := Kerning;
FKerningList.Add(Item);
end;
procedure TGPKerningText.Clear;
begin
UnprepareKerning;
UnprepareDC;
UnprepareFont;
FGPFont.Free;
FGPFont := nil;
end;
procedure TGPKerningText.ClearKerningList;
var
C: Integer;
begin
for C := 0 to FKerningList.Count - 1 do
FreeMem(FKerningList[C]);
FKerningList.Clear;
end;
constructor TGPKerningText.Create;
begin
inherited;
FKerningList := TList.Create;
end;
destructor TGPKerningText.Destroy;
begin
Clear;
FKerningList.Free;
inherited;
end;
function TGPKerningText.GetCellWidth(const First, Second: Word;
const DistanceFactor: Single = 1; const KerningFactor: Single = 1): Single;
var
GM: TGlyphMetrics;
Count: Cardinal;
Cell: Integer;
Kerning: Integer;
Mat: TMat2;
C: Integer;
begin
C := IndexOfKerning(First, Second);
if C <> -1 then
begin
Result := GetDistance(C, DistanceFactor, KerningFactor) * FFontSizeFactor;
Exit;
end;
FillChar(Mat, SizeOf(Mat), 0);
Mat.eM11.value := 1;
Mat.eM22.value := 1;
Count := GetGlyphOutlineW(FDC, First, GGO_METRICS, GM, 0, nil, Mat);
if (Count = GDI_ERROR) then
begin
Result := -1;
Exit;
end;
Cell := GM.gmCellIncX + GM.gmCellIncY;
Kerning := 0;
for C := 0 to FPairCount - 1 do
begin
if (FKerningPairs[C].wFirst = First) and
(FKerningPairs[C].wSecond = Second) then
begin
Kerning := FKerningPairs[C].iKernAmount;
Break;
end;
end;
AddToKerningList(First, Second, Cell, Kerning);
Result := (Cell * DistanceFactor + Kerning * KerningFactor) * FFontSizeFactor;
end;
function TGPKerningText.GetDistance(const Index: Integer;
const DistanceFactor, KerningFactor: Single): Single;
var
Kerning: PKerning;
begin
Kerning := PKerning(FKerningList[Index]);
Result := Kerning^.Cell * DistanceFactor + Kerning^.Kerning * KerningFactor;
end;
function TGPKerningText.IndexOfKerning(const First, Second: Word): Integer;
var
Chars: Cardinal;
begin
Chars := First shl 16 + Second;
for Result := 0 to FKerningList.Count - 1 do
if PKerning(FKerningList[Result])^.Chars = Chars then
Exit;
Result := -1;
end;
function TGPKerningText.MeasureText(const Text: string;
const Font: TGPFont; const DistanceFactor: Single = 1;
const KerningFactor: Single = 1): Single;
var
P1, P2: PWideChar;
begin
Result := 0;
if Text = '' then
Exit;
PrepareKerning(Font);
try
P1 := PWideChar(Text);
while (P1^ <> #0) do
begin
P2 := P1 + 1;
Result := Result + GetCellWidth(Word(P1^), Word(P2^), DistanceFactor,
KerningFactor);
Inc(P1);
end;
finally
UnprepareDC;
end;
end;
procedure TGPKerningText.Prepare(const Family: TGPFontFamily; Style: Integer;
const Size: Single; const Format: TGPStringFormat);
begin
FGPFont.Free;
FGPFont := TGPFont.Create(Family, Size, Style);
PrepareKerning(FGPFont);
end;
procedure TGPKerningText.PrepareDC;
begin
if (FDC <> 0) then
Exit;
FDC := GetDC(0);
FOldFont := SelectObject(FDC, FFont);
end;
procedure TGPKerningText.PrepareFont(const LF: TLogFontW);
begin
if (FFont <> 0) then
Exit;
FFont := CreateFontIndirectW(LF);
end;
procedure TGPKerningText.PrepareKerning(const Font: TGPFont;
const Graphics: TGPGraphics; WithFactor: Boolean);
var
LF: TLogFontW;
S: string;
DC: HDC;
Factor, Size: Single;
begin
Font.GetLogFontW(Graphics, LF);
Size := Font.GetSize;
if Font.GetUnit in [UnitWorld, UnitPixel] then
WithFactor := True;
if WithFactor then
begin
FFontSizeFactor := Size / 1000;
LF.lfHeight := -1000;
//LF.lfHeight := Round(Size * -1000)
end
else
begin
DC := Graphics.GetHDC;
Factor := -GetDeviceCaps(DC, LOGPIXELSY) / 72;
FFontSizeFactor := Size * Factor / 1000;
LF.lfHeight := 1000;
//LF.lfHeight := Round(Size * Factor * 1000);
Graphics.ReleaseHDC(DC);
end;
S := LF.lfFaceName;
if (S = FLastFont) and
(LF.lfWeight = FLastWeight) and (LF.lfItalic = FLastStyle) then
begin
PrepareDC;
Exit;
end else
UnprepareFont;
FLastFont := string(LF.lfFaceName);
FLastWeight := LF.lfWeight;
FLastStyle := LF.lfItalic;
PrepareFont(LF);
PrepareDC;
ClearKerningList;
FPairCount := GetKerningPairs(FDC, 0, PKerningPair(nil)^);
if (FPairCount > 0) then
begin
SetLength(FKerningPairs, FPairCount);
GetKerningPairs(FDC, FPairCount, FKerningPairs[0]);
end;
end;
procedure TGPKerningText.PrepareKerning(const Font: TGPFont);
var
G: TGPGraphics;
DC: HDC;
begin
DC := GetDC(0);
G := TGPGraphics.Create(DC);
PrepareKerning(Font, G, True);
G.Free;
ReleaseDC(0, DC);
end;
function TGPKerningText.AddToPath(const Path: TGPGraphicsPath;
const Text: string; const Family: TGPFontFamily; Style: Integer;
const Size: Single; Origin: TGPPointF; const Format: TGPStringFormat;
const DistanceFactor: Single = 1;const KerningFactor: Single = 1): TStatus;
begin
Result := AddToPath(Path, Path, Path, Text,
Family, Style, Size, Origin, Format, DistanceFactor, KerningFactor);
end;
function TGPKerningText.AddToPath(const Path: TGPGraphicsPath;
const Text: string; const Family: TGPFontFamily; const Style: Integer;
const Size: Single; Origin: TGPPoint; const Format: TGPStringFormat;
const DistanceFactor: Single = 1;const KerningFactor: Single = 1): TStatus;
var
OriginF: TGPPointF;
begin
OriginF.X := Origin.X;
OriginF.Y := Origin.Y;
Result := AddToPath(Path, Text,
Family, Style, Size, OriginF, Format, DistanceFactor, KerningFactor);
end;
function TGPKerningText.AddToPath(const Path, UPath, SPath: TGPGraphicsPath;
const Text: string; const Family: TGPFontFamily; Style: Integer;
const Size: Single; Origin: TGPPointF; const Format: TGPStringFormat;
const DistanceFactor: Single = 1;const KerningFactor: Single = 1): TStatus;
var
P1, P2: PWideChar;
Status: TStatus;
Font: TGPFont;
Underline, StrikeOut: Boolean;
X, Width: Single;
begin
Status := Ok;
if Text = '' then
begin
Result := Ok;
Exit;
end;
Underline := Style and FontStyleUnderline = FontStyleUnderline;
StrikeOut := Style and FontStyleStrikeout = FontStyleStrikeout;
Style := Style and not FontStyleUnderline and not FontStyleStrikeout;
Font := TGPFont.Create(Family, Size, Style);
try
PrepareKerning(Font);
X := Origin.X;
if Underline or StrikeOut then
Width := MeasureText(Text, Font, DistanceFactor, KerningFactor)
else
Width := 0;
if StrikeOut then
AddStrikeOut(SPath, X, Origin.Y, Width, Font);
try
P1 := PWideChar(Text);
while (P1^ <> #0) do
begin
Status := AddGlyphToPath(Path, P1^, Family, Style, Size, Origin, Format);
if Status <> Ok then
Break;
P2 := P1 + 1;
Origin.X := Origin.X + GetCellWidth(Word(P1^), Word(P2^),
DistanceFactor, KerningFactor);
Inc(P1);
end;
finally
UnprepareDC;
end;
if Underline then
AddUnderline(UPath, X, Origin.Y, Width, Font);
finally
Font.Free;
end;
Result := Status;
end;
function TGPKerningText.AddToPath(const Path, UPath, SPath: TGPGraphicsPath;
const Text: string; const Family: TGPFontFamily; Style: Integer;
const Size: Single; Origin: TGPPoint; const Format: TGPStringFormat;
const DistanceFactor: Single = 1; const KerningFactor: Single = 1): TStatus;
var
OriginF: TGPPointF;
begin
OriginF.X := Origin.X;
OriginF.Y := Origin.Y;
Result := AddToPath(Path, UPath, SPath, Text, Family, Style, Size,
OriginF, Format, DistanceFactor, KerningFactor);
end;
procedure TGPKerningText.AddUnderline(const Path: TGPGraphicsPath;
const Left, Top, Width: Single; const Font: TGPFont);
var
YPos: Single;
Height: Single;
begin
YPos := Top + Font.GetSize;
Height := Font.GetSize / 10;
Path.SetFillMode(FillModeWinding);
Path.AddRectangle(MakeRect(Left, YPos, Width, Height));
end;
procedure TGPKerningText.Unprepare;
begin
UnprepareDC;
FGPFont.Free;
FGPFont := nil;
end;
procedure TGPKerningText.UnprepareDC;
begin
if (FOldFont <> 0) and (FDC <> 0) then
SelectObject(FDC, FOldFont);
FoldFont := 0;
if FDC <> 0 then
ReleaseDC(0, FDC);
FDC := 0;
end;
procedure TGPKerningText.UnprepareFont;
begin
if FFont <> 0 then
DeleteObject(FFont);
FFont := 0;
end;
procedure TGPKerningText.UnprepareKerning;
begin
SetLength(FKerningPairs, 0);
FPairCount := 0;
ClearKerningList;
end;
initialization
FKerningText := nil;
finalization
FKerningText.Free;
end.
|
unit Antlr.Runtime;
(*
[The "BSD licence"]
Copyright (c) 2008 Erik van Bilsen
Copyright (c) 2005-2007 Kunle Odutola
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code MUST RETAIN the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior WRITTEN permission.
4. Unless explicitly state otherwise, any contribution intentionally
submitted for inclusion in this work to the copyright owner or licensor
shall be under the terms and conditions of this license, without any
additional terms or conditions.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*)
interface
{$IF CompilerVersion < 20}
{$MESSAGE ERROR 'You need Delphi 2009 or higher to use the Antlr runtime'}
{$IFEND}
uses
SysUtils,
Classes,
Generics.Defaults,
Generics.Collections,
Antlr.Runtime.Tools,
Antlr.Runtime.Collections;
type
TCharStreamConstants = (cscEOF = -1);
type
ERecognitionException = class;
ENoViableAltException = class;
/// <summary>
/// A simple stream of integers. This is useful when all we care about is the char
/// or token type sequence (such as for interpretation).
/// </summary>
IIntStream = interface(IANTLRInterface)
['{6B851BDB-DD9C-422B-AD1E-567E52D2654F}']
{ Property accessors }
function GetSourceName: String;
{ Methods }
/// <summary>
/// Advances the read position of the stream. Updates line and column state
/// </summary>
procedure Consume;
/// <summary>
/// Get int at current input pointer + I ahead (where I=1 is next int)
/// Negative indexes are allowed. LA(-1) is previous token (token just matched).
/// LA(-i) where i is before first token should yield -1, invalid char or EOF.
/// </summary>
function LA(I: Integer): Integer;
function LAChar(I: Integer): Char;
/// <summary>Tell the stream to start buffering if it hasn't already.</summary>
/// <remarks>
/// Executing Rewind(Mark()) on a stream should not affect the input position.
/// The Lexer tracks line/col info as well as input index so its markers are
/// not pure input indexes. Same for tree node streams. */
/// </remarks>
/// <returns>Return a marker that can be passed to
/// <see cref="IIntStream.Rewind(Integer)"/> to return to the current position.
/// This could be the current input position, a value return from
/// <see cref="IIntStream.Index"/>, or some other marker.</returns>
function Mark: Integer;
/// <summary>
/// Return the current input symbol index 0..N where N indicates the
/// last symbol has been read. The index is the symbol about to be
/// read not the most recently read symbol.
/// </summary>
function Index: Integer;
/// <summary>
/// Resets the stream so that the next call to
/// <see cref="IIntStream.Index"/> would return marker.
/// </summary>
/// <remarks>
/// The marker will usually be <see cref="IIntStream.Index"/> but
/// it doesn't have to be. It's just a marker to indicate what
/// state the stream was in. This is essentially calling
/// <see cref="IIntStream.Release"/> and <see cref="IIntStream.Seek"/>.
/// If there are other markers created after the specified marker,
/// this routine must unroll them like a stack. Assumes the state the
/// stream was in when this marker was created.
/// </remarks>
procedure Rewind(const Marker: Integer); overload;
/// <summary>
/// Rewind to the input position of the last marker.
/// </summary>
/// <remarks>
/// Used currently only after a cyclic DFA and just before starting
/// a sem/syn predicate to get the input position back to the start
/// of the decision. Do not "pop" the marker off the state. Mark(I)
/// and Rewind(I) should balance still. It is like invoking
/// Rewind(last marker) but it should not "pop" the marker off.
/// It's like Seek(last marker's input position).
/// </remarks>
procedure Rewind; overload;
/// <summary>
/// You may want to commit to a backtrack but don't want to force the
/// stream to keep bookkeeping objects around for a marker that is
/// no longer necessary. This will have the same behavior as
/// <see cref="IIntStream.Rewind(Integer)"/> except it releases resources without
/// the backward seek.
/// </summary>
/// <remarks>
/// This must throw away resources for all markers back to the marker
/// argument. So if you're nested 5 levels of Mark(), and then Release(2)
/// you have to release resources for depths 2..5.
/// </remarks>
procedure Release(const Marker: Integer);
/// <summary>
/// Set the input cursor to the position indicated by index. This is
/// normally used to seek ahead in the input stream.
/// </summary>
/// <remarks>
/// No buffering is required to do this unless you know your stream
/// will use seek to move backwards such as when backtracking.
///
/// This is different from rewind in its multi-directional requirement
/// and in that its argument is strictly an input cursor (index).
///
/// For char streams, seeking forward must update the stream state such
/// as line number. For seeking backwards, you will be presumably
/// backtracking using the
/// <see cref="IIntStream.Mark"/>/<see cref="IIntStream.Rewind(Integer)"/>
/// mechanism that restores state and so this method does not need to
/// update state when seeking backwards.
///
/// Currently, this method is only used for efficient backtracking using
/// memoization, but in the future it may be used for incremental parsing.
///
/// The index is 0..N-1. A seek to position i means that LA(1) will return
/// the ith symbol. So, seeking to 0 means LA(1) will return the first
/// element in the stream.
/// </remarks>
procedure Seek(const Index: Integer);
/// <summary>Returns the size of the entire stream.</summary>
/// <remarks>
/// Only makes sense for streams that buffer everything up probably,
/// but might be useful to display the entire stream or for testing.
/// This value includes a single EOF.
/// </remarks>
function Size: Integer;
{ Properties }
/// <summary>
/// Where are you getting symbols from? Normally, implementations will
/// pass the buck all the way to the lexer who can ask its input stream
/// for the file name or whatever.
/// </summary>
property SourceName: String read GetSourceName;
end;
/// <summary>A source of characters for an ANTLR lexer </summary>
ICharStream = interface(IIntStream)
['{C30EF0DB-F4BD-4CBC-8C8F-828DABB6FF36}']
{ Property accessors }
function GetLine: Integer;
procedure SetLine(const Value: Integer);
function GetCharPositionInLine: Integer;
procedure SetCharPositionInLine(const Value: Integer);
{ Methods }
/// <summary>
/// Get the ith character of lookahead. This is usually the same as
/// LA(I). This will be used for labels in the generated lexer code.
/// I'd prefer to return a char here type-wise, but it's probably
/// better to be 32-bit clean and be consistent with LA.
/// </summary>
function LT(const I: Integer): Integer;
/// <summary>
/// This primarily a useful interface for action code (just make sure
/// actions don't use this on streams that don't support it).
/// For infinite streams, you don't need this.
/// </summary>
function Substring(const Start, Stop: Integer): String;
{ Properties }
/// <summary>
/// The current line in the character stream (ANTLR tracks the
/// line information automatically. To support rewinding character
/// streams, we are able to [re-]set the line.
/// </summary>
property Line: Integer read GetLine write SetLine;
/// <summary>
/// The index of the character relative to the beginning of the
/// line (0..N-1). To support rewinding character streams, we are
/// able to [re-]set the character position.
/// </summary>
property CharPositionInLine: Integer read GetCharPositionInLine write SetCharPositionInLine;
end;
IToken = interface(IANTLRInterface)
['{73BF129C-2F45-4C68-838E-BF5D3536AC6D}']
{ Property accessors }
function GetTokenType: Integer;
procedure SetTokenType(const Value: Integer);
function GetLine: Integer;
procedure SetLine(const Value: Integer);
function GetCharPositionInLine: Integer;
procedure SetCharPositionInLine(const Value: Integer);
function GetChannel: Integer;
procedure SetChannel(const Value: Integer);
function GetTokenIndex: Integer;
procedure SetTokenIndex(const Value: Integer);
function GetText: String;
procedure SetText(const Value: String);
{ Properties }
property TokenType: Integer read GetTokenType write SetTokenType;
/// <summary>The line number on which this token was matched; line=1..N</summary>
property Line: Integer read GetLine write SetLine;
/// <summary>
/// The index of the first character relative to the beginning of the line 0..N-1
/// </summary>
property CharPositionInLine: Integer read GetCharPositionInLine write SetCharPositionInLine;
/// <summary>The line number on which this token was matched; line=1..N</summary>
property Channel: Integer read GetChannel write SetChannel;
/// <summary>
/// An index from 0..N-1 of the token object in the input stream
/// </summary>
/// <remarks>
/// This must be valid in order to use the ANTLRWorks debugger.
/// </remarks>
property TokenIndex: Integer read GetTokenIndex write SetTokenIndex;
/// <summary>The text of the token</summary>
/// <remarks>
/// When setting the text, it might be a NOP such as for the CommonToken,
/// which doesn't have string pointers, just indexes into a char buffer.
/// </remarks>
property Text: String read GetText write SetText;
end;
/// <summary>
/// A source of tokens must provide a sequence of tokens via NextToken()
/// and also must reveal it's source of characters; CommonToken's text is
/// computed from a CharStream; it only store indices into the char stream.
///
/// Errors from the lexer are never passed to the parser. Either you want
/// to keep going or you do not upon token recognition error. If you do not
/// want to continue lexing then you do not want to continue parsing. Just
/// throw an exception not under RecognitionException and Delphi will naturally
/// toss you all the way out of the recognizers. If you want to continue
/// lexing then you should not throw an exception to the parser--it has already
/// requested a token. Keep lexing until you get a valid one. Just report
/// errors and keep going, looking for a valid token.
/// </summary>
ITokenSource = interface(IANTLRInterface)
['{2C71FAD0-AEEE-417D-B576-4059F7C4CEB4}']
{ Property accessors }
function GetSourceName: String;
{ Methods }
/// <summary>
/// Returns a Token object from the input stream (usually a CharStream).
/// Does not fail/return upon lexing error; just keeps chewing on the
/// characters until it gets a good one; errors are not passed through
/// to the parser.
/// </summary>
function NextToken: IToken;
{ Properties }
/// <summary>
/// Where are you getting tokens from? normally the implication will simply
/// ask lexers input stream.
/// </summary>
property SourceName: String read GetSourceName;
end;
/// <summary>A stream of tokens accessing tokens from a TokenSource </summary>
ITokenStream = interface(IIntStream)
['{59E5B39D-31A6-496D-9FA9-AC75CC584B68}']
{ Property accessors }
function GetTokenSource: ITokenSource;
procedure SetTokenSource(const Value: ITokenSource);
{ Methods }
/// <summary>
/// Get Token at current input pointer + I ahead (where I=1 is next
/// Token).
/// I < 0 indicates tokens in the past. So -1 is previous token and -2 is
/// two tokens ago. LT(0) is undefined. For I>=N, return Token.EOFToken.
/// Return null for LT(0) and any index that results in an absolute address
/// that is negative.
/// </summary>
function LT(const K: Integer): IToken;
/// <summary>
/// Get a token at an absolute index I; 0..N-1. This is really only
/// needed for profiling and debugging and token stream rewriting.
/// If you don't want to buffer up tokens, then this method makes no
/// sense for you. Naturally you can't use the rewrite stream feature.
/// I believe DebugTokenStream can easily be altered to not use
/// this method, removing the dependency.
/// </summary>
function Get(const I: Integer): IToken;
/// <summary>Return the text of all tokens from start to stop, inclusive.
/// If the stream does not buffer all the tokens then it can just
/// return ''; Users should not access $ruleLabel.text in
/// an action of course in that case.
/// </summary>
function ToString(const Start, Stop: Integer): String; overload;
/// <summary>Because the user is not required to use a token with an index stored
/// in it, we must provide a means for two token objects themselves to
/// indicate the start/end location. Most often this will just delegate
/// to the other ToString(Integer,Integer). This is also parallel with
/// the TreeNodeStream.ToString(Object,Object).
/// </summary>
function ToString(const Start, Stop: IToken): String; overload;
{ Properties }
property TokenSource: ITokenSource read GetTokenSource write SetTokenSource;
end;
/// <summary>
/// This is the complete state of a stream.
///
/// When walking ahead with cyclic DFA for syntactic predicates, we
/// need to record the state of the input stream (char index, line,
/// etc...) so that we can rewind the state after scanning ahead.
/// </summary>
ICharStreamState = interface(IANTLRInterface)
['{62D2A1CD-ED3A-4C95-A366-AB8F2E54060B}']
{ Property accessors }
function GetP: Integer;
procedure SetP(const Value: Integer);
function GetLine: Integer;
procedure SetLine(const Value: Integer);
function GetCharPositionInLine: Integer;
procedure SetCharPositionInLine(const Value: Integer);
{ Properties }
/// <summary>Index into the char stream of next lookahead char </summary>
property P: Integer read GetP write SetP;
/// <summary>What line number is the scanner at before processing buffer[P]? </summary>
property Line: Integer read GetLine write SetLine;
/// <summary>What char position 0..N-1 in line is scanner before processing buffer[P]? </summary>
property CharPositionInLine: Integer read GetCharPositionInLine write SetCharPositionInLine;
end;
/// <summary>
/// A pretty quick <see cref="ICharStream"/> that uses a character array
/// directly as it's underlying source.
/// </summary>
IANTLRStringStream = interface(ICharStream)
['{2FA24299-FF97-4AB6-8CA6-5D3DA13C4AB2}']
{ Methods }
/// <summary>
/// Resets the stream so that it is in the same state it was
/// when the object was created *except* the data array is not
/// touched.
/// </summary>
procedure Reset;
end;
/// <summary>
/// A character stream - an <see cref="ICharStream"/> - that loads
/// and caches the contents of it's underlying file fully during
/// object construction
/// </summary>
/// <remarks>
/// This looks very much like an ANTLReaderStream or an ANTLRInputStream
/// but, it is a special case. Since we know the exact size of the file to
/// load, we can avoid lots of data copying and buffer resizing.
/// </remarks>
IANTLRFileStream = interface(IANTLRStringStream)
['{2B0145DB-2DAA-48A0-8316-B47A69EDDD1A}']
{ Methods }
/// <summary>
/// Loads and buffers the specified file to be used as this
/// ANTLRFileStream's source
/// </summary>
/// <param name="FileName">File to load</param>
/// <param name="Encoding">Encoding to apply to file</param>
procedure Load(const FileName: String; const Encoding: TEncoding);
end;
/// <summary>
/// A stripped-down version of org.antlr.misc.BitSet that is just
/// good enough to handle runtime requirements such as FOLLOW sets
/// for automatic error recovery.
/// </summary>
IBitSet = interface(IANTLRInterface)
['{F2045045-FC46-4779-A65D-56C65D257A8E}']
{ Property accessors }
function GetIsNil: Boolean;
{ Methods }
/// <summary>return "this or a" in a new set </summary>
function BitSetOr(const A: IBitSet): IBitSet;
/// <summary>Or this element into this set (grow as necessary to accommodate)</summary>
procedure Add(const El: Integer);
/// <summary> Grows the set to a larger number of bits.</summary>
/// <param name="bit">element that must fit in set
/// </param>
procedure GrowToInclude(const Bit: Integer);
procedure OrInPlace(const A: IBitSet);
function Size: Integer;
function Member(const El: Integer): Boolean;
// remove this element from this set
procedure Remove(const El: Integer);
function NumBits: Integer;
/// <summary>return how much space is being used by the bits array not
/// how many actually have member bits on.
/// </summary>
function LengthInLongWords: Integer;
function ToArray: TIntegerArray;
function ToPackedArray: TUInt64Array;
function ToString: String; overload;
function ToString(const TokenNames: TStringArray): String; overload;
function Equals(Obj: TObject): Boolean;
{ Properties }
property IsNil: Boolean read GetIsNil;
end;
TBitSetArray = array of IBitSet;
/// <summary>
/// The set of fields needed by an abstract recognizer to recognize input
/// and recover from errors
/// </summary>
/// <remarks>
/// As a separate state object, it can be shared among multiple grammars;
/// e.g., when one grammar imports another.
/// These fields are publicly visible but the actual state pointer per
/// parser is protected.
/// </remarks>
IRecognizerSharedState = interface(IANTLRInterface)
['{6CB6E17A-0B01-4AA7-8D49-5742A3CB8901}']
{ Property accessors }
function GetFollowing: TBitSetArray;
procedure SetFollowing(const Value: TBitSetArray);
function GetFollowingStackPointer: Integer;
procedure SetFollowingStackPointer(const Value: Integer);
function GetErrorRecovery: Boolean;
procedure SetErrorRecovery(const Value: Boolean);
function GetLastErrorIndex: Integer;
procedure SetLastErrorIndex(const Value: Integer);
function GetFailed: Boolean;
procedure SetFailed(const Value: Boolean);
function GetSyntaxErrors: Integer;
procedure SetSyntaxErrors(const Value: Integer);
function GetBacktracking: Integer;
procedure SetBacktracking(const Value: Integer);
function GetRuleMemo: TDictionaryArray<Integer, Integer>;
function GetRuleMemoCount: Integer;
procedure SetRuleMemoCount(const Value: Integer);
function GetToken: IToken;
procedure SetToken(const Value: IToken);
function GetTokenStartCharIndex: Integer;
procedure SetTokenStartCharIndex(const Value: Integer);
function GetTokenStartLine: Integer;
procedure SetTokenStartLine(const Value: Integer);
function GetTokenStartCharPositionInLine: Integer;
procedure SetTokenStartCharPositionInLine(const Value: Integer);
function GetChannel: Integer;
procedure SetChannel(const Value: Integer);
function GetTokenType: Integer;
procedure SetTokenType(const Value: Integer);
function GetText: String;
procedure SetText(const Value: String);
{ Properties }
/// <summary>
/// Tracks the set of token types that can follow any rule invocation.
/// Stack grows upwards. When it hits the max, it grows 2x in size
/// and keeps going.
/// </summary>
property Following: TBitSetArray read GetFollowing write SetFollowing;
property FollowingStackPointer: Integer read GetFollowingStackPointer write SetFollowingStackPointer;
/// <summary>
/// This is true when we see an error and before having successfully
/// matched a token. Prevents generation of more than one error message
/// per error.
/// </summary>
property ErrorRecovery: Boolean read GetErrorRecovery write SetErrorRecovery;
/// <summary>
/// The index into the input stream where the last error occurred.
/// </summary>
/// <remarks>
/// This is used to prevent infinite loops where an error is found
/// but no token is consumed during recovery...another error is found,
/// ad naseum. This is a failsafe mechanism to guarantee that at least
/// one token/tree node is consumed for two errors.
/// </remarks>
property LastErrorIndex: Integer read GetLastErrorIndex write SetLastErrorIndex;
/// <summary>
/// In lieu of a return value, this indicates that a rule or token
/// has failed to match. Reset to false upon valid token match.
/// </summary>
property Failed: Boolean read GetFailed write SetFailed;
/// <summary>
/// Did the recognizer encounter a syntax error? Track how many.
/// </summary>
property SyntaxErrors: Integer read GetSyntaxErrors write SetSyntaxErrors;
/// <summary>
/// If 0, no backtracking is going on. Safe to exec actions etc...
/// If >0 then it's the level of backtracking.
/// </summary>
property Backtracking: Integer read GetBacktracking write SetBacktracking;
/// <summary>
/// An array[size num rules] of Map<Integer,Integer> that tracks
/// the stop token index for each rule.
/// </summary>
/// <remarks>
/// RuleMemo[RuleIndex] is the memoization table for RuleIndex.
/// For key RuleStartIndex, you get back the stop token for
/// associated rule or MEMO_RULE_FAILED.
///
/// This is only used if rule memoization is on (which it is by default).
/// </remarks>
property RuleMemo: TDictionaryArray<Integer, Integer> read GetRuleMemo;
property RuleMemoCount: Integer read GetRuleMemoCount write SetRuleMemoCount;
// Lexer Specific Members
// LEXER FIELDS (must be in same state object to avoid casting
// constantly in generated code and Lexer object) :(
/// <summary>
/// Token object normally returned by NextToken() after matching lexer rules.
/// </summary>
/// <remarks>
/// The goal of all lexer rules/methods is to create a token object.
/// This is an instance variable as multiple rules may collaborate to
/// create a single token. NextToken will return this object after
/// matching lexer rule(s). If you subclass to allow multiple token
/// emissions, then set this to the last token to be matched or
/// something nonnull so that the auto token emit mechanism will not
/// emit another token.
/// </remarks>
property Token: IToken read GetToken write SetToken;
/// <summary>
/// What character index in the stream did the current token start at?
/// </summary>
/// <remarks>
/// Needed, for example, to get the text for current token. Set at
/// the start of nextToken.
/// </remarks>
property TokenStartCharIndex: Integer read GetTokenStartCharIndex write SetTokenStartCharIndex;
/// <summary>
/// The line on which the first character of the token resides
/// </summary>
property TokenStartLine: Integer read GetTokenStartLine write SetTokenStartLine;
/// <summary>The character position of first character within the line</summary>
property TokenStartCharPositionInLine: Integer read GetTokenStartCharPositionInLine write SetTokenStartCharPositionInLine;
/// <summary>The channel number for the current token</summary>
property Channel: Integer read GetChannel write SetChannel;
/// <summary>The token type for the current token</summary>
property TokenType: Integer read GetTokenType write SetTokenType;
/// <summary>
/// You can set the text for the current token to override what is in
/// the input char buffer. Use setText() or can set this instance var.
/// </summary>
property Text: String read GetText write SetText;
end;
ICommonToken = interface(IToken)
['{06B1B0C3-2A0D-477A-AE30-414F51ACE8A0}']
{ Property accessors }
function GetStartIndex: Integer;
procedure SetStartIndex(const Value: Integer);
function GetStopIndex: Integer;
procedure SetStopIndex(const Value: Integer);
function GetInputStream: ICharStream;
procedure SetInputStream(const Value: ICharStream);
{ Methods }
function ToString: String;
{ Properties }
property StartIndex: Integer read GetStartIndex write SetStartIndex;
property StopIndex: Integer read GetStopIndex write SetStopIndex;
property InputStream: ICharStream read GetInputStream write SetInputStream;
end;
/// <summary>
/// A Token object like we'd use in ANTLR 2.x; has an actual string created
/// and associated with this object. These objects are needed for imaginary
/// tree nodes that have payload objects. We need to create a Token object
/// that has a string; the tree node will point at this token. CommonToken
/// has indexes into a char stream and hence cannot be used to introduce
/// new strings.
/// </summary>
IClassicToken = interface(IToken)
{ Property accessors }
function GetTokenType: Integer;
procedure SetTokenType(const Value: Integer);
function GetLine: Integer;
procedure SetLine(const Value: Integer);
function GetCharPositionInLine: Integer;
procedure SetCharPositionInLine(const Value: Integer);
function GetChannel: Integer;
procedure SetChannel(const Value: Integer);
function GetTokenIndex: Integer;
procedure SetTokenIndex(const Value: Integer);
function GetText: String;
procedure SetText(const Value: String);
function GetInputStream: ICharStream;
procedure SetInputStream(const Value: ICharStream);
{ Properties }
property TokenType: Integer read GetTokenType write SetTokenType;
property Line: Integer read GetLine write SetLine;
property CharPositionInLine: Integer read GetCharPositionInLine write SetCharPositionInLine;
property Channel: Integer read GetChannel write SetChannel;
property TokenIndex: Integer read GetTokenIndex write SetTokenIndex;
property Text: String read GetText write SetText;
property InputStream: ICharStream read GetInputStream write SetInputStream;
end;
/// <summary>
/// A generic recognizer that can handle recognizers generated from
/// lexer, parser, and tree grammars. This is all the parsing
/// support code essentially; most of it is error recovery stuff and
/// backtracking.
/// </summary>
IBaseRecognizer = interface(IANTLRObject)
['{90813CE2-614B-4773-A26E-936E7DE7E9E9}']
{ Property accessors }
function GetInput: IIntStream;
function GetBacktrackingLevel: Integer;
function GetState: IRecognizerSharedState;
function GetNumberOfSyntaxErrors: Integer;
function GetGrammarFileName: String;
function GetSourceName: String;
function GetTokenNames: TStringArray;
{ Methods }
procedure BeginBacktrack(const Level: Integer);
procedure EndBacktrack(const Level: Integer; const Successful: Boolean);
/// <summary>Reset the parser's state. Subclasses must rewind the input stream.</summary>
procedure Reset;
/// <summary>
/// Match current input symbol against ttype. Attempt
/// single token insertion or deletion error recovery. If
/// that fails, throw EMismatchedTokenException.
/// </summary>
/// <remarks>
/// To turn off single token insertion or deletion error
/// recovery, override MismatchRecover() and have it call
/// plain Mismatch(), which does not recover. Then any error
/// in a rule will cause an exception and immediate exit from
/// rule. Rule would recover by resynchronizing to the set of
/// symbols that can follow rule ref.
/// </remarks>
function Match(const Input: IIntStream; const TokenType: Integer;
const Follow: IBitSet): IANTLRInterface;
function MismatchIsUnwantedToken(const Input: IIntStream;
const TokenType: Integer): Boolean;
function MismatchIsMissingToken(const Input: IIntStream;
const Follow: IBitSet): Boolean;
/// <summary>A hook to listen in on the token consumption during error recovery.
/// The DebugParser subclasses this to fire events to the listenter.
/// </summary>
procedure BeginResync;
procedure EndResync;
/// <summary>
/// Report a recognition problem.
/// </summary>
/// <remarks>
/// This method sets errorRecovery to indicate the parser is recovering
/// not parsing. Once in recovery mode, no errors are generated.
/// To get out of recovery mode, the parser must successfully Match
/// a token (after a resync). So it will go:
///
/// 1. error occurs
/// 2. enter recovery mode, report error
/// 3. consume until token found in resynch set
/// 4. try to resume parsing
/// 5. next Match() will reset errorRecovery mode
///
/// If you override, make sure to update syntaxErrors if you care about that.
/// </remarks>
procedure ReportError(const E: ERecognitionException);
/// <summary> Match the wildcard: in a symbol</summary>
procedure MatchAny(const Input: IIntStream);
procedure DisplayRecognitionError(const TokenNames: TStringArray;
const E: ERecognitionException);
/// <summary>
/// What error message should be generated for the various exception types?
///
/// Not very object-oriented code, but I like having all error message generation
/// within one method rather than spread among all of the exception classes. This
/// also makes it much easier for the exception handling because the exception
/// classes do not have to have pointers back to this object to access utility
/// routines and so on. Also, changing the message for an exception type would be
/// difficult because you would have to subclassing exception, but then somehow get
/// ANTLR to make those kinds of exception objects instead of the default.
///
/// This looks weird, but trust me--it makes the most sense in terms of flexibility.
///
/// For grammar debugging, you will want to override this to add more information
/// such as the stack frame with GetRuleInvocationStack(e, this.GetType().Fullname)
/// and, for no viable alts, the decision description and state etc...
///
/// Override this to change the message generated for one or more exception types.
/// </summary>
function GetErrorMessage(const E: ERecognitionException;
const TokenNames: TStringArray): String;
/// <summary>
/// What is the error header, normally line/character position information?
/// </summary>
function GetErrorHeader(const E: ERecognitionException): String;
/// <summary>
/// How should a token be displayed in an error message? The default
/// is to display just the text, but during development you might
/// want to have a lot of information spit out. Override in that case
/// to use t.ToString() (which, for CommonToken, dumps everything about
/// the token). This is better than forcing you to override a method in
/// your token objects because you don't have to go modify your lexer
/// so that it creates a new type.
/// </summary>
function GetTokenErrorDisplay(const T: IToken): String;
/// <summary>
/// Override this method to change where error messages go
/// </summary>
procedure EmitErrorMessage(const Msg: String);
/// <summary>
/// Recover from an error found on the input stream. This is
/// for NoViableAlt and mismatched symbol exceptions. If you enable
/// single token insertion and deletion, this will usually not
/// handle mismatched symbol exceptions but there could be a mismatched
/// token that the Match() routine could not recover from.
/// </summary>
procedure Recover(const Input: IIntStream; const RE: ERecognitionException);
// Not currently used
function RecoverFromMismatchedSet(const Input: IIntStream;
const E: ERecognitionException; const Follow: IBitSet): IANTLRInterface;
procedure ConsumeUntil(const Input: IIntStream; const TokenType: Integer); overload;
/// <summary>Consume tokens until one matches the given token set </summary>
procedure ConsumeUntil(const Input: IIntStream; const BitSet: IBitSet); overload;
/// <summary>
/// Returns List <String> of the rules in your parser instance
/// leading up to a call to this method. You could override if
/// you want more details such as the file/line info of where
/// in the parser source code a rule is invoked.
/// </summary>
/// <remarks>
/// NOT IMPLEMENTED IN THE DELPHI VERSION YET
/// This is very useful for error messages and for context-sensitive
/// error recovery.
/// </remarks>
//function GetRuleInvocationStack: IList<IANTLRInterface>; overload;
/// <summary>
/// A more general version of GetRuleInvocationStack where you can
/// pass in, for example, a RecognitionException to get it's rule
/// stack trace. This routine is shared with all recognizers, hence,
/// static.
///
/// TODO: move to a utility class or something; weird having lexer call this
/// </summary>
/// <remarks>
/// NOT IMPLEMENTED IN THE DELPHI VERSION YET
/// </remarks>
//function GetRuleInvocationStack(const E: Exception;
// const RecognizerClassName: String): IList<IANTLRInterface>; overload;
/// <summary>A convenience method for use most often with template rewrites.
/// Convert a List<Token> to List<String>
/// </summary>
function ToStrings(const Tokens: IList<IToken>): IList<String>;
/// <summary>
/// Given a rule number and a start token index number, return
/// MEMO_RULE_UNKNOWN if the rule has not parsed input starting from
/// start index. If this rule has parsed input starting from the
/// start index before, then return where the rule stopped parsing.
/// It returns the index of the last token matched by the rule.
/// </summary>
/// <remarks>
/// For now we use a hashtable and just the slow Object-based one.
/// Later, we can make a special one for ints and also one that
/// tosses out data after we commit past input position i.
/// </remarks>
function GetRuleMemoization(const RuleIndex, RuleStartIndex: Integer): Integer;
/// <summary>
/// Has this rule already parsed input at the current index in the
/// input stream? Return the stop token index or MEMO_RULE_UNKNOWN.
/// If we attempted but failed to parse properly before, return
/// MEMO_RULE_FAILED.
///
/// This method has a side-effect: if we have seen this input for
/// this rule and successfully parsed before, then seek ahead to
/// 1 past the stop token matched for this rule last time.
/// </summary>
function AlreadyParsedRule(const Input: IIntStream;
const RuleIndex: Integer): Boolean;
/// <summary>
/// Record whether or not this rule parsed the input at this position
/// successfully. Use a standard hashtable for now.
/// </summary>
procedure Memoize(const Input: IIntStream; const RuleIndex,
RuleStartIndex: Integer);
/// <summary>
/// Return how many rule/input-index pairs there are in total.
/// TODO: this includes synpreds. :(
/// </summary>
/// <returns></returns>
function GetRuleMemoizationChaceSize: Integer;
procedure TraceIn(const RuleName: String; const RuleIndex: Integer;
const InputSymbol: String);
procedure TraceOut(const RuleName: String; const RuleIndex: Integer;
const InputSymbol: String);
{ Properties }
property Input: IIntStream read GetInput;
property BacktrackingLevel: Integer read GetBacktrackingLevel;
property State: IRecognizerSharedState read GetState;
/// <summary>
/// Get number of recognition errors (lexer, parser, tree parser). Each
/// recognizer tracks its own number. So parser and lexer each have
/// separate count. Does not count the spurious errors found between
/// an error and next valid token match
///
/// See also ReportError()
/// </summary>
property NumberOfSyntaxErrors: Integer read GetNumberOfSyntaxErrors;
/// <summary>
/// For debugging and other purposes, might want the grammar name.
/// Have ANTLR generate an implementation for this property.
/// </summary>
/// <returns></returns>
property GrammarFileName: String read GetGrammarFileName;
/// <summary>
/// For debugging and other purposes, might want the source name.
/// Have ANTLR provide a hook for this property.
/// </summary>
/// <returns>The source name</returns>
property SourceName: String read GetSourceName;
/// <summary>
/// Used to print out token names like ID during debugging and
/// error reporting. The generated parsers implement a method
/// that overrides this to point to their string[] tokenNames.
/// </summary>
property TokenNames: TStringArray read GetTokenNames;
end;
/// <summary>
/// The most common stream of tokens is one where every token is buffered up
/// and tokens are prefiltered for a certain channel (the parser will only
/// see these tokens and cannot change the filter channel number during the
/// parse).
///
/// TODO: how to access the full token stream? How to track all tokens matched per rule?
/// </summary>
ICommonTokenStream = interface(ITokenStream)
{ Methods }
/// <summary>
/// A simple filter mechanism whereby you can tell this token stream
/// to force all tokens of type TType to be on Channel.
/// </summary>
///
/// <remarks>
/// For example,
/// when interpreting, we cannot exec actions so we need to tell
/// the stream to force all WS and NEWLINE to be a different, ignored
/// channel.
/// </remarks>
procedure SetTokenTypeChannel(const TType, Channel: Integer);
procedure DiscardTokenType(const TType: Integer);
procedure DiscardOffChannelTokens(const Discard: Boolean);
function GetTokens: IList<IToken>; overload;
function GetTokens(const Start, Stop: Integer): IList<IToken>; overload;
/// <summary>Given a start and stop index, return a List of all tokens in
/// the token type BitSet. Return null if no tokens were found. This
/// method looks at both on and off channel tokens.
/// </summary>
function GetTokens(const Start, Stop: Integer;
const Types: IBitSet): IList<IToken>; overload;
function GetTokens(const Start, Stop: Integer;
const Types: IList<Integer>): IList<IToken>; overload;
function GetTokens(const Start, Stop,
TokenType: Integer): IList<IToken>; overload;
procedure Reset;
end;
IDFA = interface;
TSpecialStateTransitionHandler = function(const DFA: IDFA; S: Integer;
const Input: IIntStream): Integer of Object;
/// <summary>
/// A DFA implemented as a set of transition tables.
/// </summary>
/// <remarks>
/// <para>
/// Any state that has a semantic predicate edge is special; those states are
/// generated with if-then-else structures in a SpecialStateTransition()
/// which is generated by cyclicDFA template.
/// </para>
/// <para>
/// There are at most 32767 states (16-bit signed short). Could get away with byte
/// sometimes but would have to generate different types and the simulation code too.
/// </para>
/// <para>
/// As a point of reference, the Tokens rule DFA for the lexer in the Java grammar
/// sample has approximately 326 states.
/// </para>
/// </remarks>
IDFA = interface(IANTLRInterface)
['{36312B59-B718-48EF-A0EC-4529DE70F4C2}']
{ Property accessors }
function GetSpecialStateTransitionHandler: TSpecialStateTransitionHandler;
procedure SetSpecialStateTransitionHandler(const Value: TSpecialStateTransitionHandler);
{ Methods }
/// <summary>
/// From the input stream, predict what alternative will succeed using this
/// DFA (representing the covering regular approximation to the underlying CFL).
/// </summary>
/// <param name="Input">Input stream</param>
/// <returns>Return an alternative number 1..N. Throw an exception upon error.</returns>
function Predict(const Input: IIntStream): Integer;
/// <summary>
/// A hook for debugging interface
/// </summary>
/// <param name="NVAE"></param>
procedure Error(const NVAE: ENoViableAltException);
function SpecialStateTransition(const S: Integer; const Input: IIntStream): Integer;
function Description: String;
function SpecialTransition(const State, Symbol: Integer): Integer;
{ Properties }
property SpecialStateTransitionHandler: TSpecialStateTransitionHandler read GetSpecialStateTransitionHandler write SetSpecialStateTransitionHandler;
end;
/// <summary>
/// A lexer is recognizer that draws input symbols from a character stream.
/// lexer grammars result in a subclass of this object. A Lexer object
/// uses simplified Match() and error recovery mechanisms in the interest
/// of speed.
/// </summary>
ILexer = interface(IBaseRecognizer)
['{331AAB49-E7CD-40E7-AEF5-427F7D6577AD}']
{ Property accessors }
function GetCharStream: ICharStream;
procedure SetCharStream(const Value: ICharStream);
function GetLine: Integer;
function GetCharPositionInLine: Integer;
function GetCharIndex: Integer;
function GetText: String;
procedure SetText(const Value: String);
{ Methods }
/// <summary>
/// Return a token from this source; i.e., Match a token on the char stream.
/// </summary>
function NextToken: IToken;
/// <summary>
/// Instruct the lexer to skip creating a token for current lexer rule and
/// look for another token. NextToken() knows to keep looking when a lexer
/// rule finishes with token set to SKIP_TOKEN. Recall that if token==null
/// at end of any token rule, it creates one for you and emits it.
/// </summary>
procedure Skip;
/// <summary>This is the lexer entry point that sets instance var 'token' </summary>
procedure DoTokens;
/// <summary>
/// Currently does not support multiple emits per nextToken invocation
/// for efficiency reasons. Subclass and override this method and
/// NextToken (to push tokens into a list and pull from that list rather
/// than a single variable as this implementation does).
/// </summary>
procedure Emit(const Token: IToken); overload;
/// <summary>
/// The standard method called to automatically emit a token at the
/// outermost lexical rule. The token object should point into the
/// char buffer start..stop. If there is a text override in 'text',
/// use that to set the token's text.
/// </summary>
/// <remarks><para>Override this method to emit custom Token objects.</para>
/// <para>If you are building trees, then you should also override
/// Parser or TreeParser.GetMissingSymbol().</para>
///</remarks>
function Emit: IToken; overload;
procedure Match(const S: String); overload;
procedure Match(const C: Integer); overload;
procedure MatchAny;
procedure MatchRange(const A, B: Integer);
/// <summary>
/// Lexers can normally Match any char in it's vocabulary after matching
/// a token, so do the easy thing and just kill a character and hope
/// it all works out. You can instead use the rule invocation stack
/// to do sophisticated error recovery if you are in a Fragment rule.
/// </summary>
procedure Recover(const RE: ERecognitionException);
function GetCharErrorDisplay(const C: Integer): String;
procedure TraceIn(const RuleName: String; const RuleIndex: Integer);
procedure TraceOut(const RuleName: String; const RuleIndex: Integer);
{ Properties }
/// <summary>Set the char stream and reset the lexer </summary>
property CharStream: ICharStream read GetCharStream write SetCharStream;
property Line: Integer read GetLine;
property CharPositionInLine: Integer read GetCharPositionInLine;
/// <summary>What is the index of the current character of lookahead? </summary>
property CharIndex: Integer read GetCharIndex;
/// <summary>
/// Gets or sets the 'lexeme' for the current token.
/// </summary>
/// <remarks>
/// <para>
/// The getter returns the text matched so far for the current token or any
/// text override.
/// </para>
/// <para>
/// The setter sets the complete text of this token. It overrides/wipes any
/// previous changes to the text.
/// </para>
/// </remarks>
property Text: String read GetText write SetText;
end;
/// <summary>A parser for TokenStreams. Parser grammars result in a subclass
/// of this.
/// </summary>
IParser = interface(IBaseRecognizer)
['{7420879A-5D1F-43CA-BD49-2264D7514501}']
{ Property accessors }
function GetTokenStream: ITokenStream;
procedure SetTokenStream(const Value: ITokenStream);
{ Methods }
procedure TraceIn(const RuleName: String; const RuleIndex: Integer);
procedure TraceOut(const RuleName: String; const RuleIndex: Integer);
{ Properties }
/// <summary>Set the token stream and reset the parser </summary>
property TokenStream: ITokenStream read GetTokenStream write SetTokenStream;
end;
/// <summary>
/// Rules can return start/stop info as well as possible trees and templates
/// </summary>
IRuleReturnScope = interface(IANTLRInterface)
['{E9870056-BF6D-4CB2-B71C-10B80797C0B4}']
{ Property accessors }
function GetStart: IANTLRInterface;
procedure SetStart(const Value: IANTLRInterface);
function GetStop: IANTLRInterface;
procedure SetStop(const Value: IANTLRInterface);
function GetTree: IANTLRInterface;
procedure SetTree(const Value: IANTLRInterface);
function GetTemplate: IANTLRInterface;
{ Properties }
/// <summary>Return the start token or tree </summary>
property Start: IANTLRInterface read GetStart write SetStart;
/// <summary>Return the stop token or tree </summary>
property Stop: IANTLRInterface read GetStop write SetStop;
/// <summary>Has a value potentially if output=AST; </summary>
property Tree: IANTLRInterface read GetTree write SetTree;
/// <summary>
/// Has a value potentially if output=template;
/// Don't use StringTemplate type to avoid dependency on ST assembly
/// </summary>
property Template: IANTLRInterface read GetTemplate;
end;
/// <summary>
/// Rules that return more than a single value must return an object
/// containing all the values. Besides the properties defined in
/// RuleLabelScope.PredefinedRulePropertiesScope there may be user-defined
/// return values. This class simply defines the minimum properties that
/// are always defined and methods to access the others that might be
/// available depending on output option such as template and tree.
///
/// Note text is not an actual property of the return value, it is computed
/// from start and stop using the input stream's ToString() method. I
/// could add a ctor to this so that we can pass in and store the input
/// stream, but I'm not sure we want to do that. It would seem to be undefined
/// to get the .text property anyway if the rule matches tokens from multiple
/// input streams.
///
/// I do not use getters for fields of objects that are used simply to
/// group values such as this aggregate.
/// </summary>
IParserRuleReturnScope = interface(IRuleReturnScope)
['{9FB62050-E23B-4FE4-87D5-2C1EE67AEC3E}']
end;
/// <summary>Useful for dumping out the input stream after doing some
/// augmentation or other manipulations.
/// </summary>
///
/// <remarks>
/// You can insert stuff, Replace, and delete chunks. Note that the
/// operations are done lazily--only if you convert the buffer to a
/// String. This is very efficient because you are not moving data around
/// all the time. As the buffer of tokens is converted to strings, the
/// ToString() method(s) check to see if there is an operation at the
/// current index. If so, the operation is done and then normal String
/// rendering continues on the buffer. This is like having multiple Turing
/// machine instruction streams (programs) operating on a single input tape. :)
///
/// Since the operations are done lazily at ToString-time, operations do not
/// screw up the token index values. That is, an insert operation at token
/// index I does not change the index values for tokens I+1..N-1.
///
/// Because operations never actually alter the buffer, you may always get
/// the original token stream back without undoing anything. Since
/// the instructions are queued up, you can easily simulate transactions and
/// roll back any changes if there is an error just by removing instructions.
/// For example,
///
/// var
/// Input: ICharStream;
/// Lex: ILexer;
/// Tokens: ITokenRewriteStream;
/// Parser: IParser;
/// Input := TANTLRFileStream.Create('input');
/// Lex := TLexer.Create(Input);
/// Tokens := TTokenRewriteStream.Create(Lex);
/// Parser := TParser.Create(tokens);
/// Parser.startRule();
///
/// Then in the rules, you can execute
/// var
/// t,u: IToken;
/// ...
/// Input.InsertAfter(t, 'text to put after t');
/// Input.InsertAfter(u, 'text after u');
/// WriteLn(Tokens.ToString());
///
/// Actually, you have to cast the 'input' to a TokenRewriteStream. :(
///
/// You can also have multiple "instruction streams" and get multiple
/// rewrites from a single pass over the input. Just name the instruction
/// streams and use that name again when printing the buffer. This could be
/// useful for generating a C file and also its header file--all from the
/// same buffer:
///
/// Tokens.InsertAfter('pass1', t, 'text to put after t');
/// Tokens.InsertAfter('pass2', u, 'text after u');
/// WriteLn(Tokens.ToString('pass1'));
/// WriteLn(Tokens.ToString('pass2'));
///
/// If you don't use named rewrite streams, a "default" stream is used as
/// the first example shows.
/// </remarks>
ITokenRewriteStream = interface(ICommonTokenStream)
['{7B49CBB6-9395-4781-B616-F201889EEA13}']
{ Methods }
procedure Rollback(const InstructionIndex: Integer); overload;
/// <summary>Rollback the instruction stream for a program so that
/// the indicated instruction (via instructionIndex) is no
/// longer in the stream. UNTESTED!
/// </summary>
procedure Rollback(const ProgramName: String;
const InstructionIndex: Integer); overload;
procedure DeleteProgram; overload;
/// <summary>Reset the program so that no instructions exist </summary>
procedure DeleteProgram(const ProgramName: String); overload;
procedure InsertAfter(const T: IToken; const Text: IANTLRInterface); overload;
procedure InsertAfter(const Index: Integer; const Text: IANTLRInterface); overload;
procedure InsertAfter(const ProgramName: String; const T: IToken;
const Text: IANTLRInterface); overload;
procedure InsertAfter(const ProgramName: String; const Index: Integer;
const Text: IANTLRInterface); overload;
procedure InsertAfter(const T: IToken; const Text: String); overload;
procedure InsertAfter(const Index: Integer; const Text: String); overload;
procedure InsertAfter(const ProgramName: String; const T: IToken;
const Text: String); overload;
procedure InsertAfter(const ProgramName: String; const Index: Integer;
const Text: String); overload;
procedure InsertBefore(const T: IToken; const Text: IANTLRInterface); overload;
procedure InsertBefore(const Index: Integer; const Text: IANTLRInterface); overload;
procedure InsertBefore(const ProgramName: String; const T: IToken;
const Text: IANTLRInterface); overload;
procedure InsertBefore(const ProgramName: String; const Index: Integer;
const Text: IANTLRInterface); overload;
procedure InsertBefore(const T: IToken; const Text: String); overload;
procedure InsertBefore(const Index: Integer; const Text: String); overload;
procedure InsertBefore(const ProgramName: String; const T: IToken;
const Text: String); overload;
procedure InsertBefore(const ProgramName: String; const Index: Integer;
const Text: String); overload;
procedure Replace(const Index: Integer; const Text: IANTLRInterface); overload;
procedure Replace(const Start, Stop: Integer; const Text: IANTLRInterface); overload;
procedure Replace(const IndexT: IToken; const Text: IANTLRInterface); overload;
procedure Replace(const Start, Stop: IToken; const Text: IANTLRInterface); overload;
procedure Replace(const ProgramName: String; const Start, Stop: Integer;
const Text: IANTLRInterface); overload;
procedure Replace(const ProgramName: String; const Start, Stop: IToken;
const Text: IANTLRInterface); overload;
procedure Replace(const Index: Integer; const Text: String); overload;
procedure Replace(const Start, Stop: Integer; const Text: String); overload;
procedure Replace(const IndexT: IToken; const Text: String); overload;
procedure Replace(const Start, Stop: IToken; const Text: String); overload;
procedure Replace(const ProgramName: String; const Start, Stop: Integer;
const Text: String); overload;
procedure Replace(const ProgramName: String; const Start, Stop: IToken;
const Text: String); overload;
procedure Delete(const Index: Integer); overload;
procedure Delete(const Start, Stop: Integer); overload;
procedure Delete(const IndexT: IToken); overload;
procedure Delete(const Start, Stop: IToken); overload;
procedure Delete(const ProgramName: String; const Start, Stop: Integer); overload;
procedure Delete(const ProgramName: String; const Start, Stop: IToken); overload;
function GetLastRewriteTokenIndex: Integer;
function ToOriginalString: String; overload;
function ToOriginalString(const Start, Stop: Integer): String; overload;
function ToString(const ProgramName: String): String; overload;
function ToString(const ProgramName: String;
const Start, Stop: Integer): String; overload;
function ToDebugString: String; overload;
function ToDebugString(const Start, Stop: Integer): String; overload;
end;
/// <summary>The root of the ANTLR exception hierarchy.</summary>
/// <remarks>
/// To avoid English-only error messages and to generally make things
/// as flexible as possible, these exceptions are not created with strings,
/// but rather the information necessary to generate an error. Then
/// the various reporting methods in Parser and Lexer can be overridden
/// to generate a localized error message. For example, MismatchedToken
/// exceptions are built with the expected token type.
/// So, don't expect getMessage() to return anything.
///
/// You can access the stack trace, which means that you can compute the
/// complete trace of rules from the start symbol. This gives you considerable
/// context information with which to generate useful error messages.
///
/// ANTLR generates code that throws exceptions upon recognition error and
/// also generates code to catch these exceptions in each rule. If you
/// want to quit upon first error, you can turn off the automatic error
/// handling mechanism using rulecatch action, but you still need to
/// override methods mismatch and recoverFromMismatchSet.
///
/// In general, the recognition exceptions can track where in a grammar a
/// problem occurred and/or what was the expected input. While the parser
/// knows its state (such as current input symbol and line info) that
/// state can change before the exception is reported so current token index
/// is computed and stored at exception time. From this info, you can
/// perhaps print an entire line of input not just a single token, for example.
/// Better to just say the recognizer had a problem and then let the parser
/// figure out a fancy report.
/// </remarks>
ERecognitionException = class(Exception)
strict private
FApproximateLineInfo: Boolean;
strict protected
/// <summary>What input stream did the error occur in? </summary>
FInput: IIntStream;
/// <summary>
/// What is index of token/char were we looking at when the error occurred?
/// </summary>
FIndex: Integer;
/// <summary>
/// The current Token when an error occurred. Since not all streams
/// can retrieve the ith Token, we have to track the Token object.
/// </summary>
FToken: IToken;
/// <summary>[Tree parser] Node with the problem.</summary>
FNode: IANTLRInterface;
/// <summary>The current char when an error occurred. For lexers. </summary>
FC: Integer;
/// <summary>Track the line at which the error occurred in case this is
/// generated from a lexer. We need to track this since the
/// unexpected char doesn't carry the line info.
/// </summary>
FLine: Integer;
FCharPositionInLine: Integer;
strict protected
procedure ExtractInformationFromTreeNodeStream(const Input: IIntStream);
function GetUnexpectedType: Integer; virtual;
public
/// <summary>Used for remote debugger deserialization </summary>
constructor Create; overload;
constructor Create(const AMessage: String); overload;
constructor Create(const AInput: IIntStream); overload;
constructor Create(const AMessage: String; const AInput: IIntStream); overload;
/// <summary>
/// If you are parsing a tree node stream, you will encounter some
/// imaginary nodes w/o line/col info. We now search backwards looking
/// for most recent token with line/col info, but notify getErrorHeader()
/// that info is approximate.
/// </summary>
property ApproximateLineInfo: Boolean read FApproximateLineInfo write FApproximateLineInfo;
/// <summary>
/// Returns the current Token when the error occurred (for parsers
/// although a tree parser might also set the token)
/// </summary>
property Token: IToken read FToken write FToken;
/// <summary>
/// Returns the [tree parser] node where the error occured (for tree parsers).
/// </summary>
property Node: IANTLRInterface read FNode write FNode;
/// <summary>
/// Returns the line at which the error occurred (for lexers)
/// </summary>
property Line: Integer read FLine write FLine;
/// <summary>
/// Returns the character position in the line when the error
/// occurred (for lexers)
/// </summary>
property CharPositionInLine: Integer read FCharPositionInLine write FCharPositionInLine;
/// <summary>Returns the input stream in which the error occurred</summary>
property Input: IIntStream read FInput write FInput;
/// <summary>
/// Returns the token type or char of the unexpected input element
/// </summary>
property UnexpectedType: Integer read GetUnexpectedType;
/// <summary>
/// Returns the current char when the error occurred (for lexers)
/// </summary>
property Character: Integer read FC write FC;
/// <summary>
/// Returns the token/char index in the stream when the error occurred
/// </summary>
property Index: Integer read FIndex write FIndex;
end;
/// <summary>
/// A mismatched char or Token or tree node.
/// </summary>
EMismatchedTokenException = class(ERecognitionException)
strict private
FExpecting: Integer;
public
constructor Create(const AExpecting: Integer; const AInput: IIntStream);
function ToString: String; override;
property Expecting: Integer read FExpecting write FExpecting;
end;
EUnwantedTokenException = class(EMismatchedTokenException)
strict private
function GetUnexpectedToken: IToken;
public
property UnexpectedToken: IToken read GetUnexpectedToken;
function ToString: String; override;
end;
/// <summary>
/// We were expecting a token but it's not found. The current token
/// is actually what we wanted next. Used for tree node errors too.
/// </summary>
EMissingTokenException = class(EMismatchedTokenException)
strict private
FInserted: IANTLRInterface;
function GetMissingType: Integer;
public
constructor Create(const AExpecting: Integer; const AInput: IIntStream;
const AInserted: IANTLRInterface);
function ToString: String; override;
property MissingType: Integer read GetMissingType;
property Inserted: IANTLRInterface read FInserted write FInserted;
end;
EMismatchedTreeNodeException = class(ERecognitionException)
strict private
FExpecting: Integer;
public
constructor Create(const AExpecting: Integer; const AInput: IIntStream);
function ToString: String; override;
property Expecting: Integer read FExpecting write FExpecting;
end;
ENoViableAltException = class(ERecognitionException)
strict private
FGrammarDecisionDescription: String;
FDecisionNumber: Integer;
FStateNumber: Integer;
public
constructor Create(const AGrammarDecisionDescription: String;
const ADecisionNumber, AStateNumber: Integer; const AInput: IIntStream);
function ToString: String; override;
property GrammarDecisionDescription: String read FGrammarDecisionDescription;
property DecisionNumber: Integer read FDecisionNumber;
property StateNumber: Integer read FStateNumber;
end;
EEarlyExitException = class(ERecognitionException)
strict private
FDecisionNumber: Integer;
public
constructor Create(const ADecisionNumber: Integer; const AInput: IIntStream);
property DecisionNumber: Integer read FDecisionNumber;
end;
EMismatchedSetException = class(ERecognitionException)
strict private
FExpecting: IBitSet;
public
constructor Create(const AExpecting: IBitSet; const AInput: IIntStream);
function ToString: String; override;
property Expecting: IBitSet read FExpecting write FExpecting;
end;
EMismatchedNotSetException = class(EMismatchedSetException)
public
function ToString: String; override;
end;
EFailedPredicateException = class(ERecognitionException)
strict private
FRuleName: String;
FPredicateText: String;
public
constructor Create(const AInput: IIntStream; const ARuleName,
APredicateText: String);
function ToString: String; override;
property RuleName: String read FRuleName write FRuleName;
property PredicateText: String read FPredicateText write FPredicateText;
end;
EMismatchedRangeException = class(ERecognitionException)
strict private
FA: Integer;
FB: Integer;
public
constructor Create(const AA, AB: Integer; const AInput: IIntStream);
function ToString: String; override;
property A: Integer read FA write FA;
property B: Integer read FB write FB;
end;
type
TCharStreamState = class(TANTLRObject, ICharStreamState)
strict private
FP: Integer;
FLine: Integer;
FCharPositionInLine: Integer;
protected
{ ICharStreamState }
function GetP: Integer;
procedure SetP(const Value: Integer);
function GetLine: Integer;
procedure SetLine(const Value: Integer);
function GetCharPositionInLine: Integer;
procedure SetCharPositionInLine(const Value: Integer);
end;
type
TANTLRStringStream = class(TANTLRObject, IANTLRStringStream, ICharStream)
private
FData: PChar;
FOwnsData: Boolean;
/// <summary>How many characters are actually in the buffer?</summary>
FN: Integer;
/// <summary>Current line number within the input (1..n )</summary>
FLine: Integer;
/// <summary>Index in our array for the next char (0..n-1)</summary>
FP: Integer;
/// <summary>
/// The index of the character relative to the beginning of the
/// line (0..n-1)
/// </summary>
FCharPositionInLine: Integer;
/// <summary>
/// Tracks the depth of nested <see cref="IIntStream.Mark"/> calls
/// </summary>
FMarkDepth: Integer;
/// <summary>
/// A list of CharStreamState objects that tracks the stream state
/// (i.e. line, charPositionInLine, and p) that can change as you
/// move through the input stream. Indexed from 1..markDepth.
/// A null is kept @ index 0. Create upon first call to Mark().
/// </summary>
FMarkers: IList<ICharStreamState>;
/// <summary>
/// Track the last Mark() call result value for use in Rewind().
/// </summary>
FLastMarker: Integer;
/// <summary>
/// What is name or source of this char stream?
/// </summary>
FName: String;
protected
{ IIntStream }
function GetSourceName: String; virtual;
procedure Consume; virtual;
function LA(I: Integer): Integer; virtual;
function LAChar(I: Integer): Char;
function Index: Integer;
function Size: Integer;
function Mark: Integer; virtual;
procedure Rewind(const Marker: Integer); overload; virtual;
procedure Rewind; overload; virtual;
procedure Release(const Marker: Integer); virtual;
procedure Seek(const Index: Integer); virtual;
property SourceName: String read GetSourceName write FName;
protected
{ ICharStream }
function GetLine: Integer; virtual;
procedure SetLine(const Value: Integer); virtual;
function GetCharPositionInLine: Integer; virtual;
procedure SetCharPositionInLine(const Value: Integer); virtual;
function LT(const I: Integer): Integer; virtual;
function Substring(const Start, Stop: Integer): String; virtual;
protected
{ IANTLRStringStream }
procedure Reset; virtual;
public
constructor Create; overload;
/// <summary>
/// Initializes a new instance of the ANTLRStringStream class for the
/// specified string. This copies data from the string to a local
/// character array
/// </summary>
constructor Create(const AInput: String); overload;
/// <summary>
/// Initializes a new instance of the ANTLRStringStream class for the
/// specified character array. This is the preferred constructor as
/// no data is copied
/// </summary>
constructor Create(const AData: PChar;
const ANumberOfActualCharsInArray: Integer); overload;
destructor Destroy; override;
end;
TANTLRFileStream = class(TANTLRStringStream, IANTLRFileStream)
strict private
/// <summary>Fully qualified name of the stream's underlying file</summary>
FFileName: String;
protected
{ IIntStream }
function GetSourceName: String; override;
protected
{ IANTLRFileStream }
procedure Load(const FileName: String; const Encoding: TEncoding); virtual;
public
/// <summary>
/// Initializes a new instance of the ANTLRFileStream class for the
/// specified file name
/// </summary>
constructor Create(const AFileName: String); overload;
/// <summary>
/// Initializes a new instance of the ANTLRFileStream class for the
/// specified file name and encoding
/// </summary>
constructor Create(const AFileName: String; const AEncoding: TEncoding); overload;
end;
TBitSet = class(TANTLRObject, IBitSet, ICloneable)
strict private
const
BITS = 64; // number of bits / ulong
LOG_BITS = 6; // 2 shl 6 = 64
///<summary> We will often need to do a mod operator (i mod nbits).
/// Its turns out that, for powers of two, this mod operation is
/// same as <![CDATA[(I and (nbits-1))]]>. Since mod is slow, we use a precomputed
/// mod mask to do the mod instead.
/// </summary>
MOD_MASK = BITS - 1;
strict private
/// <summary>The actual data bits </summary>
FBits: TUInt64Array;
strict private
class function WordNumber(const Bit: Integer): Integer; static;
class function BitMask(const BitNumber: Integer): UInt64; static;
class function NumWordsToHold(const El: Integer): Integer; static;
protected
{ ICloneable }
function Clone: IANTLRInterface; virtual;
protected
{ IBitSet }
function GetIsNil: Boolean; virtual;
function BitSetOr(const A: IBitSet): IBitSet; virtual;
procedure Add(const El: Integer); virtual;
procedure GrowToInclude(const Bit: Integer); virtual;
procedure OrInPlace(const A: IBitSet); virtual;
function Size: Integer; virtual;
function Member(const El: Integer): Boolean; virtual;
procedure Remove(const El: Integer); virtual;
function NumBits: Integer; virtual;
function LengthInLongWords: Integer; virtual;
function ToArray: TIntegerArray; virtual;
function ToPackedArray: TUInt64Array; virtual;
function ToString(const TokenNames: TStringArray): String; reintroduce; overload; virtual;
public
/// <summary>Construct a bitset of size one word (64 bits) </summary>
constructor Create; overload;
/// <summary>Construction from a static array of ulongs </summary>
constructor Create(const ABits: array of UInt64); overload;
/// <summary>Construction from a list of integers </summary>
constructor Create(const AItems: IList<Integer>); overload;
/// <summary>Construct a bitset given the size</summary>
/// <param name="nbits">The size of the bitset in bits</param>
constructor Create(const ANBits: Integer); overload;
class function BitSetOf(const El: Integer): IBitSet; overload; static;
class function BitSetOf(const A, B: Integer): IBitSet; overload; static;
class function BitSetOf(const A, B, C: Integer): IBitSet; overload; static;
class function BitSetOf(const A, B, C, D: Integer): IBitSet; overload; static;
function ToString: String; overload; override;
function Equals(Obj: TObject): Boolean; override;
end;
TRecognizerSharedState = class(TANTLRObject, IRecognizerSharedState)
strict private
FFollowing: TBitSetArray;
FFollowingStackPointer: Integer;
FErrorRecovery: Boolean;
FLastErrorIndex: Integer;
FFailed: Boolean;
FSyntaxErrors: Integer;
FBacktracking: Integer;
FRuleMemo: TDictionaryArray<Integer, Integer>;
FToken: IToken;
FTokenStartCharIndex: Integer;
FTokenStartLine: Integer;
FTokenStartCharPositionInLine: Integer;
FChannel: Integer;
FTokenType: Integer;
FText: String;
protected
{ IRecognizerSharedState }
function GetFollowing: TBitSetArray;
procedure SetFollowing(const Value: TBitSetArray);
function GetFollowingStackPointer: Integer;
procedure SetFollowingStackPointer(const Value: Integer);
function GetErrorRecovery: Boolean;
procedure SetErrorRecovery(const Value: Boolean);
function GetLastErrorIndex: Integer;
procedure SetLastErrorIndex(const Value: Integer);
function GetFailed: Boolean;
procedure SetFailed(const Value: Boolean);
function GetSyntaxErrors: Integer;
procedure SetSyntaxErrors(const Value: Integer);
function GetBacktracking: Integer;
procedure SetBacktracking(const Value: Integer);
function GetRuleMemo: TDictionaryArray<Integer, Integer>;
function GetRuleMemoCount: Integer;
procedure SetRuleMemoCount(const Value: Integer);
function GetToken: IToken;
procedure SetToken(const Value: IToken);
function GetTokenStartCharIndex: Integer;
procedure SetTokenStartCharIndex(const Value: Integer);
function GetTokenStartLine: Integer;
procedure SetTokenStartLine(const Value: Integer);
function GetTokenStartCharPositionInLine: Integer;
procedure SetTokenStartCharPositionInLine(const Value: Integer);
function GetChannel: Integer;
procedure SetChannel(const Value: Integer);
function GetTokenType: Integer;
procedure SetTokenType(const Value: Integer);
function GetText: String;
procedure SetText(const Value: String);
public
constructor Create;
end;
TCommonToken = class(TANTLRObject, ICommonToken, IToken)
strict protected
FTokenType: Integer;
FLine: Integer;
FCharPositionInLine: Integer;
FChannel: Integer;
FInput: ICharStream;
/// <summary>We need to be able to change the text once in a while. If
/// this is non-null, then getText should return this. Note that
/// start/stop are not affected by changing this.
/// </summary>
FText: String;
/// <summary>What token number is this from 0..n-1 tokens; < 0 implies invalid index </summary>
FIndex: Integer;
/// <summary>The char position into the input buffer where this token starts </summary>
FStart: Integer;
/// <summary>The char position into the input buffer where this token stops </summary>
FStop: Integer;
protected
{ IToken }
function GetTokenType: Integer; virtual;
procedure SetTokenType(const Value: Integer); virtual;
function GetLine: Integer; virtual;
procedure SetLine(const Value: Integer); virtual;
function GetCharPositionInLine: Integer; virtual;
procedure SetCharPositionInLine(const Value: Integer); virtual;
function GetChannel: Integer; virtual;
procedure SetChannel(const Value: Integer); virtual;
function GetTokenIndex: Integer; virtual;
procedure SetTokenIndex(const Value: Integer); virtual;
function GetText: String; virtual;
procedure SetText(const Value: String); virtual;
protected
{ ICommonToken }
function GetStartIndex: Integer;
procedure SetStartIndex(const Value: Integer);
function GetStopIndex: Integer;
procedure SetStopIndex(const Value: Integer);
function GetInputStream: ICharStream;
procedure SetInputStream(const Value: ICharStream);
protected
constructor Create; overload;
public
constructor Create(const ATokenType: Integer); overload;
constructor Create(const AInput: ICharStream; const ATokenType, AChannel,
AStart, AStop: Integer); overload;
constructor Create(const ATokenType: Integer; const AText: String); overload;
constructor Create(const AOldToken: IToken); overload;
function ToString: String; override;
end;
TClassicToken = class(TANTLRObject, IClassicToken, IToken)
strict private
FText: String;
FTokenType: Integer;
FLine: Integer;
FCharPositionInLine: Integer;
FChannel: Integer;
/// <summary>What token number is this from 0..n-1 tokens </summary>
FIndex: Integer;
protected
{ IClassicToken }
function GetTokenType: Integer; virtual;
procedure SetTokenType(const Value: Integer); virtual;
function GetLine: Integer; virtual;
procedure SetLine(const Value: Integer); virtual;
function GetCharPositionInLine: Integer; virtual;
procedure SetCharPositionInLine(const Value: Integer); virtual;
function GetChannel: Integer; virtual;
procedure SetChannel(const Value: Integer); virtual;
function GetTokenIndex: Integer; virtual;
procedure SetTokenIndex(const Value: Integer); virtual;
function GetText: String; virtual;
procedure SetText(const Value: String); virtual;
function GetInputStream: ICharStream; virtual;
procedure SetInputStream(const Value: ICharStream); virtual;
public
constructor Create(const ATokenType: Integer); overload;
constructor Create(const AOldToken: IToken); overload;
constructor Create(const ATokenType: Integer; const AText: String); overload;
constructor Create(const ATokenType: Integer; const AText: String;
const AChannel: Integer); overload;
function ToString: String; override;
end;
TToken = class sealed
public
const
EOR_TOKEN_TYPE = 1;
/// <summary>imaginary tree navigation type; traverse "get child" link </summary>
DOWN = 2;
/// <summary>imaginary tree navigation type; finish with a child list </summary>
UP = 3;
MIN_TOKEN_TYPE = UP + 1;
EOF = Integer(cscEOF);
INVALID_TOKEN_TYPE = 0;
/// <summary>
/// All tokens go to the parser (unless skip() is called in that rule)
/// on a particular "channel". The parser tunes to a particular channel
/// so that whitespace etc... can go to the parser on a "hidden" channel.
/// </summary>
DEFAULT_CHANNEL = 0;
/// <summary>
/// Anything on different channel than DEFAULT_CHANNEL is not parsed by parser.
/// </summary>
HIDDEN_CHANNEL = 99;
public
class var
EOF_TOKEN: IToken;
INVALID_TOKEN: IToken;
/// <summary>
/// In an action, a lexer rule can set token to this SKIP_TOKEN and ANTLR
/// will avoid creating a token for this symbol and try to fetch another.
/// </summary>
SKIP_TOKEN: IToken;
private
class procedure Initialize; static;
end;
/// <summary>
/// Global constants
/// </summary>
TConstants = class sealed
public
const
VERSION = '3.1b1';
// Moved to version 2 for v3.1: added grammar name to enter/exit Rule
DEBUG_PROTOCOL_VERSION = '2';
ANTLRWORKS_DIR = 'antlrworks';
end;
TBaseRecognizer = class abstract(TANTLRObject, IBaseRecognizer)
public
const
MEMO_RULE_FAILED = -2;
MEMO_RULE_UNKNOWN = -1;
INITIAL_FOLLOW_STACK_SIZE = 100;
NEXT_TOKEN_RULE_NAME = 'nextToken';
// copies from Token object for convenience in actions
DEFAULT_TOKEN_CHANNEL = TToken.DEFAULT_CHANNEL;
HIDDEN = TToken.HIDDEN_CHANNEL;
strict protected
/// <summary>
/// An externalized representation of the - shareable - internal state of
/// this lexer, parser or tree parser.
/// </summary>
/// <remarks>
/// The state of a lexer, parser, or tree parser are collected into
/// external state objects so that the state can be shared. This sharing
/// is needed to have one grammar import others and share same error
/// variables and other state variables. It's a kind of explicit multiple
/// inheritance via delegation of methods and shared state.
/// </remarks>
FState: IRecognizerSharedState;
property State: IRecognizerSharedState read FState;
strict protected
/// <summary>
/// Match needs to return the current input symbol, which gets put
/// into the label for the associated token ref; e.g., x=ID. Token
/// and tree parsers need to return different objects. Rather than test
/// for input stream type or change the IntStream interface, I use
/// a simple method to ask the recognizer to tell me what the current
/// input symbol is.
/// </summary>
/// <remarks>This is ignored for lexers.</remarks>
function GetCurrentInputSymbol(const Input: IIntStream): IANTLRInterface; virtual;
/// <summary>
/// Factor out what to do upon token mismatch so tree parsers can behave
/// differently. Override and call MismatchRecover(input, ttype, follow)
/// to get single token insertion and deletion. Use this to turn off
/// single token insertion and deletion. Override mismatchRecover
/// to call this instead.
/// </summary>
procedure Mismatch(const Input: IIntStream; const TokenType: Integer;
const Follow: IBitSet); virtual;
/// <summary>
/// Attempt to Recover from a single missing or extra token.
/// </summary>
/// <remarks>
/// EXTRA TOKEN
///
/// LA(1) is not what we are looking for. If LA(2) has the right token,
/// however, then assume LA(1) is some extra spurious token. Delete it
/// and LA(2) as if we were doing a normal Match(), which advances the
/// input.
///
/// MISSING TOKEN
///
/// If current token is consistent with what could come after
/// ttype then it is ok to "insert" the missing token, else throw
/// exception For example, Input "i=(3;" is clearly missing the
/// ')'. When the parser returns from the nested call to expr, it
/// will have call chain:
///
/// stat -> expr -> atom
///
/// and it will be trying to Match the ')' at this point in the
/// derivation:
///
/// => ID '=' '(' INT ')' ('+' atom)* ';'
/// ^
/// Match() will see that ';' doesn't Match ')' and report a
/// mismatched token error. To Recover, it sees that LA(1)==';'
/// is in the set of tokens that can follow the ')' token
/// reference in rule atom. It can assume that you forgot the ')'.
/// </remarks>
function RecoverFromMismatchedToken(const Input: IIntStream;
const TokenType: Integer; const Follow: IBitSet): IANTLRInterface; virtual;
/// <summary>
/// Conjure up a missing token during error recovery.
/// </summary>
/// <remarks>
/// The recognizer attempts to recover from single missing
/// symbols. But, actions might refer to that missing symbol.
/// For example, x=ID {f($x);}. The action clearly assumes
/// that there has been an identifier matched previously and that
/// $x points at that token. If that token is missing, but
/// the next token in the stream is what we want we assume that
/// this token is missing and we keep going. Because we
/// have to return some token to replace the missing token,
/// we have to conjure one up. This method gives the user control
/// over the tokens returned for missing tokens. Mostly,
/// you will want to create something special for identifier
/// tokens. For literals such as '{' and ',', the default
/// action in the parser or tree parser works. It simply creates
/// a CommonToken of the appropriate type. The text will be the token.
/// If you change what tokens must be created by the lexer,
/// override this method to create the appropriate tokens.
/// </remarks>
function GetMissingSymbol(const Input: IIntStream;
const E: ERecognitionException; const ExpectedTokenType: Integer;
const Follow: IBitSet): IANTLRInterface; virtual;
/// <summary>
/// Push a rule's follow set using our own hardcoded stack
/// </summary>
/// <param name="fset"></param>
procedure PushFollow(const FSet: IBitSet);
/// <summary>Compute the context-sensitive FOLLOW set for current rule.
/// This is set of token types that can follow a specific rule
/// reference given a specific call chain. You get the set of
/// viable tokens that can possibly come next (lookahead depth 1)
/// given the current call chain. Contrast this with the
/// definition of plain FOLLOW for rule r:
///
/// FOLLOW(r)={x | S=>*alpha r beta in G and x in FIRST(beta)}
///
/// where x in T* and alpha, beta in V*; T is set of terminals and
/// V is the set of terminals and nonterminals. In other words,
/// FOLLOW(r) is the set of all tokens that can possibly follow
/// references to r in *any* sentential form (context). At
/// runtime, however, we know precisely which context applies as
/// we have the call chain. We may compute the exact (rather
/// than covering superset) set of following tokens.
///
/// For example, consider grammar:
///
/// stat : ID '=' expr ';' // FOLLOW(stat)=={EOF}
/// | "return" expr '.'
/// ;
/// expr : atom ('+' atom)* ; // FOLLOW(expr)=={';','.',')'}
/// atom : INT // FOLLOW(atom)=={'+',')',';','.'}
/// | '(' expr ')'
/// ;
///
/// The FOLLOW sets are all inclusive whereas context-sensitive
/// FOLLOW sets are precisely what could follow a rule reference.
/// For input input "i=(3);", here is the derivation:
///
/// stat => ID '=' expr ';'
/// => ID '=' atom ('+' atom)* ';'
/// => ID '=' '(' expr ')' ('+' atom)* ';'
/// => ID '=' '(' atom ')' ('+' atom)* ';'
/// => ID '=' '(' INT ')' ('+' atom)* ';'
/// => ID '=' '(' INT ')' ';'
///
/// At the "3" token, you'd have a call chain of
///
/// stat -> expr -> atom -> expr -> atom
///
/// What can follow that specific nested ref to atom? Exactly ')'
/// as you can see by looking at the derivation of this specific
/// input. Contrast this with the FOLLOW(atom)={'+',')',';','.'}.
///
/// You want the exact viable token set when recovering from a
/// token mismatch. Upon token mismatch, if LA(1) is member of
/// the viable next token set, then you know there is most likely
/// a missing token in the input stream. "Insert" one by just not
/// throwing an exception.
/// </summary>
function ComputeContextSensitiveRuleFOLLOW: IBitSet; virtual;
(* Compute the error recovery set for the current rule. During
* rule invocation, the parser pushes the set of tokens that can
* follow that rule reference on the stack; this amounts to
* computing FIRST of what follows the rule reference in the
* enclosing rule. This local follow set only includes tokens
* from within the rule; i.e., the FIRST computation done by
* ANTLR stops at the end of a rule.
*
* EXAMPLE
*
* When you find a "no viable alt exception", the input is not
* consistent with any of the alternatives for rule r. The best
* thing to do is to consume tokens until you see something that
* can legally follow a call to r *or* any rule that called r.
* You don't want the exact set of viable next tokens because the
* input might just be missing a token--you might consume the
* rest of the input looking for one of the missing tokens.
*
* Consider grammar:
*
* a : '[' b ']'
* | '(' b ')'
* ;
* b : c '^' INT ;
* c : ID
* | INT
* ;
*
* At each rule invocation, the set of tokens that could follow
* that rule is pushed on a stack. Here are the various "local"
* follow sets:
*
* FOLLOW(b1_in_a) = FIRST(']') = ']'
* FOLLOW(b2_in_a) = FIRST(')') = ')'
* FOLLOW(c_in_b) = FIRST('^') = '^'
*
* Upon erroneous input "[]", the call chain is
*
* a -> b -> c
*
* and, hence, the follow context stack is:
*
* depth local follow set after call to rule
* 0 <EOF> a (from main())
* 1 ']' b
* 3 '^' c
*
* Notice that ')' is not included, because b would have to have
* been called from a different context in rule a for ')' to be
* included.
*
* For error recovery, we cannot consider FOLLOW(c)
* (context-sensitive or otherwise). We need the combined set of
* all context-sensitive FOLLOW sets--the set of all tokens that
* could follow any reference in the call chain. We need to
* resync to one of those tokens. Note that FOLLOW(c)='^' and if
* we resync'd to that token, we'd consume until EOF. We need to
* sync to context-sensitive FOLLOWs for a, b, and c: {']','^'}.
* In this case, for input "[]", LA(1) is in this set so we would
* not consume anything and after printing an error rule c would
* return normally. It would not find the required '^' though.
* At this point, it gets a mismatched token error and throws an
* exception (since LA(1) is not in the viable following token
* set). The rule exception handler tries to Recover, but finds
* the same recovery set and doesn't consume anything. Rule b
* exits normally returning to rule a. Now it finds the ']' (and
* with the successful Match exits errorRecovery mode).
*
* So, you cna see that the parser walks up call chain looking
* for the token that was a member of the recovery set.
*
* Errors are not generated in errorRecovery mode.
*
* ANTLR's error recovery mechanism is based upon original ideas:
*
* "Algorithms + Data Structures = Programs" by Niklaus Wirth
*
* and
*
* "A note on error recovery in recursive descent parsers":
* http://portal.acm.org/citation.cfm?id=947902.947905
*
* Later, Josef Grosch had some good ideas:
*
* "Efficient and Comfortable Error Recovery in Recursive Descent
* Parsers":
* ftp://www.cocolab.com/products/cocktail/doca4.ps/ell.ps.zip
*
* Like Grosch I implemented local FOLLOW sets that are combined
* at run-time upon error to avoid overhead during parsing.
*)
function ComputeErrorRecoverySet: IBitSet; virtual;
function CombineFollows(const Exact: Boolean): IBitSet;
protected
{ IBaseRecognizer }
function GetInput: IIntStream; virtual; abstract;
function GetBacktrackingLevel: Integer;
function GetState: IRecognizerSharedState;
function GetNumberOfSyntaxErrors: Integer;
function GetGrammarFileName: String; virtual;
function GetSourceName: String; virtual; abstract;
function GetTokenNames: TStringArray; virtual;
procedure BeginBacktrack(const Level: Integer); virtual;
procedure EndBacktrack(const Level: Integer; const Successful: Boolean); virtual;
procedure Reset; virtual;
function Match(const Input: IIntStream; const TokenType: Integer;
const Follow: IBitSet): IANTLRInterface; virtual;
function MismatchIsUnwantedToken(const Input: IIntStream;
const TokenType: Integer): Boolean;
function MismatchIsMissingToken(const Input: IIntStream;
const Follow: IBitSet): Boolean;
procedure BeginResync; virtual;
procedure EndResync; virtual;
procedure ReportError(const E: ERecognitionException); virtual;
procedure MatchAny(const Input: IIntStream); virtual;
procedure DisplayRecognitionError(const TokenNames: TStringArray;
const E: ERecognitionException); virtual;
function GetErrorMessage(const E: ERecognitionException;
const TokenNames: TStringArray): String; virtual;
function GetErrorHeader(const E: ERecognitionException): String; virtual;
function GetTokenErrorDisplay(const T: IToken): String; virtual;
procedure EmitErrorMessage(const Msg: String); virtual;
procedure Recover(const Input: IIntStream; const RE: ERecognitionException); virtual;
function RecoverFromMismatchedSet(const Input: IIntStream;
const E: ERecognitionException; const Follow: IBitSet): IANTLRInterface; virtual;
procedure ConsumeUntil(const Input: IIntStream; const TokenType: Integer); overload; virtual;
procedure ConsumeUntil(const Input: IIntStream; const BitSet: IBitSet); overload; virtual;
//function GetRuleInvocationStack: IList<IANTLRInterface>; overload; virtual;
//function GetRuleInvocationStack(const E: Exception;
// const RecognizerClassName: String): IList<IANTLRInterface>; overload;
function ToStrings(const Tokens: IList<IToken>): IList<String>; virtual;
function GetRuleMemoization(const RuleIndex, RuleStartIndex: Integer): Integer; virtual;
function AlreadyParsedRule(const Input: IIntStream;
const RuleIndex: Integer): Boolean; virtual;
procedure Memoize(const Input: IIntStream; const RuleIndex,
RuleStartIndex: Integer); virtual;
function GetRuleMemoizationChaceSize: Integer;
procedure TraceIn(const RuleName: String; const RuleIndex: Integer;
const InputSymbol: String); virtual;
procedure TraceOut(const RuleName: String; const RuleIndex: Integer;
const InputSymbol: String); virtual;
property Input: IIntStream read GetInput;
public
constructor Create; overload;
constructor Create(const AState: IRecognizerSharedState); overload;
end;
TCommonTokenStream = class(TANTLRObject, ICommonTokenStream, ITokenStream)
strict private
FTokenSource: ITokenSource;
/// <summary>Record every single token pulled from the source so we can reproduce
/// chunks of it later.
/// </summary>
FTokens: IList<IToken>;
/// <summary><![CDATA[Map<tokentype, channel>]]> to override some Tokens' channel numbers </summary>
FChannelOverrideMap: IDictionary<Integer, Integer>;
/// <summary><![CDATA[Set<tokentype>;]]> discard any tokens with this type </summary>
FDiscardSet: IHashList<Integer, Integer>;
/// <summary>Skip tokens on any channel but this one; this is how we skip whitespace... </summary>
FChannel: Integer;
/// <summary>By default, track all incoming tokens </summary>
FDiscardOffChannelTokens: Boolean;
/// <summary>Track the last Mark() call result value for use in Rewind().</summary>
FLastMarker: Integer;
/// <summary>
/// The index into the tokens list of the current token (next token
/// to consume). p==-1 indicates that the tokens list is empty
/// </summary>
FP: Integer;
strict protected
/// <summary>Load all tokens from the token source and put in tokens.
/// This is done upon first LT request because you might want to
/// set some token type / channel overrides before filling buffer.
/// </summary>
procedure FillBuffer; virtual;
/// <summary>Look backwards k tokens on-channel tokens </summary>
function LB(const K: Integer): IToken; virtual;
/// <summary>Given a starting index, return the index of the first on-channel
/// token.
/// </summary>
function SkipOffTokenChannels(const I: Integer): Integer; virtual;
function SkipOffTokenChannelsReverse(const I: Integer): Integer; virtual;
protected
{ IIntStream }
function GetSourceName: String; virtual;
procedure Consume; virtual;
function LA(I: Integer): Integer; virtual;
function LAChar(I: Integer): Char;
function Mark: Integer; virtual;
function Index: Integer; virtual;
procedure Rewind(const Marker: Integer); overload; virtual;
procedure Rewind; overload; virtual;
procedure Release(const Marker: Integer); virtual;
procedure Seek(const Index: Integer); virtual;
function Size: Integer; virtual;
protected
{ ITokenStream }
function GetTokenSource: ITokenSource; virtual;
procedure SetTokenSource(const Value: ITokenSource); virtual;
function LT(const K: Integer): IToken; virtual;
function Get(const I: Integer): IToken; virtual;
function ToString(const Start, Stop: Integer): String; reintroduce; overload; virtual;
function ToString(const Start, Stop: IToken): String; reintroduce; overload; virtual;
protected
{ ICommonTokenStream }
procedure SetTokenTypeChannel(const TType, Channel: Integer);
procedure DiscardTokenType(const TType: Integer);
procedure DiscardOffChannelTokens(const Discard: Boolean);
function GetTokens: IList<IToken>; overload;
function GetTokens(const Start, Stop: Integer): IList<IToken>; overload;
function GetTokens(const Start, Stop: Integer;
const Types: IBitSet): IList<IToken>; overload;
function GetTokens(const Start, Stop: Integer;
const Types: IList<Integer>): IList<IToken>; overload;
function GetTokens(const Start, Stop,
TokenType: Integer): IList<IToken>; overload;
procedure Reset; virtual;
public
constructor Create; overload;
constructor Create(const ATokenSource: ITokenSource); overload;
constructor Create(const ATokenSource: ITokenSource;
const AChannel: Integer); overload;
constructor Create(const ALexer: ILexer); overload;
constructor Create(const ALexer: ILexer;
const AChannel: Integer); overload;
function ToString: String; overload; override;
end;
TDFA = class abstract(TANTLRObject, IDFA)
strict private
FSpecialStateTransitionHandler: TSpecialStateTransitionHandler;
FEOT: TSmallintArray;
FEOF: TSmallintArray;
FMin: TCharArray;
FMax: TCharArray;
FAccept: TSmallintArray;
FSpecial: TSmallintArray;
FTransition: TSmallintMatrix;
FDecisionNumber: Integer;
FRecognizer: Pointer; { IBaseRecognizer }
function GetRecognizer: IBaseRecognizer;
procedure SetRecognizer(const Value: IBaseRecognizer);
strict protected
procedure NoViableAlt(const S: Integer; const Input: IIntStream);
property Recognizer: IBaseRecognizer read GetRecognizer write SetRecognizer;
property DecisionNumber: Integer read FDecisionNumber write FDecisionNumber;
property EOT: TSmallintArray read FEOT write FEOT;
property EOF: TSmallintArray read FEOF write FEOF;
property Min: TCharArray read FMin write FMin;
property Max: TCharArray read FMax write FMax;
property Accept: TSmallintArray read FAccept write FAccept;
property Special: TSmallintArray read FSpecial write FSpecial;
property Transition: TSmallintMatrix read FTransition write FTransition;
protected
{ IDFA }
function GetSpecialStateTransitionHandler: TSpecialStateTransitionHandler;
procedure SetSpecialStateTransitionHandler(const Value: TSpecialStateTransitionHandler);
function Predict(const Input: IIntStream): Integer;
procedure Error(const NVAE: ENoViableAltException); virtual;
function SpecialStateTransition(const S: Integer;
const Input: IIntStream): Integer; virtual;
function Description: String; virtual;
function SpecialTransition(const State, Symbol: Integer): Integer;
public
class function UnpackEncodedString(const EncodedString: String): TSmallintArray; static;
class function UnpackEncodedStringArray(const EncodedStrings: TStringArray): TSmallintMatrix; overload; static;
class function UnpackEncodedStringArray(const EncodedStrings: array of String): TSmallintMatrix; overload; static;
class function UnpackEncodedStringToUnsignedChars(const EncodedString: String): TCharArray; static;
end;
TLexer = class abstract(TBaseRecognizer, ILexer, ITokenSource)
strict private
const
TOKEN_dot_EOF = Ord(cscEOF);
strict private
/// <summary>Where is the lexer drawing characters from? </summary>
FInput: ICharStream;
protected
{ IBaseRecognizer }
function GetSourceName: String; override;
function GetInput: IIntStream; override;
procedure Reset; override;
procedure ReportError(const E: ERecognitionException); override;
function GetErrorMessage(const E: ERecognitionException;
const TokenNames: TStringArray): String; override;
protected
{ ILexer }
function GetCharStream: ICharStream; virtual;
procedure SetCharStream(const Value: ICharStream); virtual;
function GetLine: Integer; virtual;
function GetCharPositionInLine: Integer; virtual;
function GetCharIndex: Integer; virtual;
function GetText: String; virtual;
procedure SetText(const Value: String); virtual;
function NextToken: IToken; virtual;
procedure Skip;
procedure DoTokens; virtual; abstract;
procedure Emit(const Token: IToken); overload; virtual;
function Emit: IToken; overload; virtual;
procedure Match(const S: String); reintroduce; overload; virtual;
procedure Match(const C: Integer); reintroduce; overload; virtual;
procedure MatchAny; reintroduce; overload; virtual;
procedure MatchRange(const A, B: Integer); virtual;
procedure Recover(const RE: ERecognitionException); reintroduce; overload; virtual;
function GetCharErrorDisplay(const C: Integer): String;
procedure TraceIn(const RuleName: String; const RuleIndex: Integer); reintroduce; overload; virtual;
procedure TraceOut(const RuleName: String; const RuleIndex: Integer); reintroduce; overload; virtual;
strict protected
property Input: ICharStream read FInput;
property CharIndex: Integer read GetCharIndex;
property Text: String read GetText write SetText;
public
constructor Create; overload;
constructor Create(const AInput: ICharStream); overload;
constructor Create(const AInput: ICharStream;
const AState: IRecognizerSharedState); overload;
end;
TParser = class(TBaseRecognizer, IParser)
strict private
FInput: ITokenStream;
protected
property Input: ITokenStream read FInput;
protected
{ IBaseRecognizer }
procedure Reset; override;
function GetCurrentInputSymbol(const Input: IIntStream): IANTLRInterface; override;
function GetMissingSymbol(const Input: IIntStream;
const E: ERecognitionException; const ExpectedTokenType: Integer;
const Follow: IBitSet): IANTLRInterface; override;
function GetSourceName: String; override;
function GetInput: IIntStream; override;
protected
{ IParser }
function GetTokenStream: ITokenStream; virtual;
procedure SetTokenStream(const Value: ITokenStream); virtual;
procedure TraceIn(const RuleName: String; const RuleIndex: Integer); reintroduce; overload;
procedure TraceOut(const RuleName: String; const RuleIndex: Integer); reintroduce; overload;
public
constructor Create(const AInput: ITokenStream); overload;
constructor Create(const AInput: ITokenStream;
const AState: IRecognizerSharedState); overload;
end;
TRuleReturnScope = class(TANTLRObject, IRuleReturnScope)
protected
{ IRuleReturnScope }
function GetStart: IANTLRInterface; virtual;
procedure SetStart(const Value: IANTLRInterface); virtual;
function GetStop: IANTLRInterface; virtual;
procedure SetStop(const Value: IANTLRInterface); virtual;
function GetTree: IANTLRInterface; virtual;
procedure SetTree(const Value: IANTLRInterface); virtual;
function GetTemplate: IANTLRInterface; virtual;
end;
TParserRuleReturnScope = class(TRuleReturnScope, IParserRuleReturnScope)
strict private
FStart: IToken;
FStop: IToken;
protected
{ IRuleReturnScope }
function GetStart: IANTLRInterface; override;
procedure SetStart(const Value: IANTLRInterface); override;
function GetStop: IANTLRInterface; override;
procedure SetStop(const Value: IANTLRInterface); override;
end;
TTokenRewriteStream = class(TCommonTokenStream, ITokenRewriteStream)
public
const
DEFAULT_PROGRAM_NAME = 'default';
PROGRAM_INIT_SIZE = 100;
MIN_TOKEN_INDEX = 0;
strict protected
// Define the rewrite operation hierarchy
type
IRewriteOperation = interface(IANTLRInterface)
['{285A54ED-58FF-44B1-A268-2686476D4419}']
{ Property accessors }
function GetInstructionIndex: Integer;
procedure SetInstructionIndex(const Value: Integer);
function GetIndex: Integer;
procedure SetIndex(const Value: Integer);
function GetText: IANTLRInterface;
procedure SetText(const Value: IANTLRInterface);
function GetParent: ITokenRewriteStream;
procedure SetParent(const Value: ITokenRewriteStream);
{ Methods }
/// <summary>Execute the rewrite operation by possibly adding to the buffer.
/// Return the index of the next token to operate on.
/// </summary>
function Execute(const Buf: TStringBuilder): Integer;
{ Properties }
property InstructionIndex: Integer read GetInstructionIndex write SetInstructionIndex;
property Index: Integer read GetIndex write SetIndex;
property Text: IANTLRInterface read GetText write SetText;
property Parent: ITokenRewriteStream read GetParent write SetParent;
end;
TRewriteOperation = class(TANTLRObject, IRewriteOperation)
strict private
// What index into rewrites List are we?
FInstructionIndex: Integer;
// Token buffer index
FIndex: Integer;
FText: IANTLRInterface;
FParent: Pointer; {ITokenRewriteStream;}
protected
{ IRewriteOperation }
function GetInstructionIndex: Integer;
procedure SetInstructionIndex(const Value: Integer);
function GetIndex: Integer;
procedure SetIndex(const Value: Integer);
function GetText: IANTLRInterface;
procedure SetText(const Value: IANTLRInterface);
function GetParent: ITokenRewriteStream;
procedure SetParent(const Value: ITokenRewriteStream);
function Execute(const Buf: TStringBuilder): Integer; virtual;
protected
constructor Create(const AIndex: Integer; const AText: IANTLRInterface;
const AParent: ITokenRewriteStream);
property Index: Integer read FIndex write FIndex;
property Text: IANTLRInterface read FText write FText;
property Parent: ITokenRewriteStream read GetParent write SetParent;
public
function ToString: String; override;
end;
IInsertBeforeOp = interface(IRewriteOperation)
['{BFB732E2-BE6A-4691-AE3B-5C8013DE924E}']
end;
TInsertBeforeOp = class(TRewriteOperation, IInsertBeforeOp)
protected
{ IRewriteOperation }
function Execute(const Buf: TStringBuilder): Integer; override;
end;
/// <summary>I'm going to try replacing range from x..y with (y-x)+1 ReplaceOp
/// instructions.
/// </summary>
IReplaceOp = interface(IRewriteOperation)
['{630C434A-99EA-4589-A65D-64A7B3DAC407}']
{ Property accessors }
function GetLastIndex: Integer;
procedure SetLastIndex(const Value: Integer);
{ Properties }
property LastIndex: Integer read GetLastIndex write SetLastIndex;
end;
TReplaceOp = class(TRewriteOperation, IReplaceOp)
private
FLastIndex: Integer;
protected
{ IRewriteOperation }
function Execute(const Buf: TStringBuilder): Integer; override;
protected
{ IReplaceOp }
function GetLastIndex: Integer;
procedure SetLastIndex(const Value: Integer);
public
constructor Create(const AStart, AStop: Integer;
const AText: IANTLRInterface; const AParent: ITokenRewriteStream);
function ToString: String; override;
end;
IDeleteOp = interface(IRewriteOperation)
['{C39345BC-F170-4C3A-A989-65E6B9F0712B}']
end;
TDeleteOp = class(TReplaceOp)
public
function ToString: String; override;
end;
strict private
type
TRewriteOpComparer<T: IRewriteOperation> = class(TComparer<T>)
public
function Compare(const Left, Right: T): Integer; override;
end;
strict private
/// <summary>You may have multiple, named streams of rewrite operations.
/// I'm calling these things "programs."
/// Maps String (name) -> rewrite (IList)
/// </summary>
FPrograms: IDictionary<String, IList<IRewriteOperation>>;
/// <summary>Map String (program name) -> Integer index </summary>
FLastRewriteTokenIndexes: IDictionary<String, Integer>;
strict private
function InitializeProgram(const Name: String): IList<IRewriteOperation>;
protected
{ ITokenRewriteStream }
procedure Rollback(const InstructionIndex: Integer); overload; virtual;
procedure Rollback(const ProgramName: String;
const InstructionIndex: Integer); overload; virtual;
procedure DeleteProgram; overload; virtual;
procedure DeleteProgram(const ProgramName: String); overload; virtual;
procedure InsertAfter(const T: IToken; const Text: IANTLRInterface); overload; virtual;
procedure InsertAfter(const Index: Integer; const Text: IANTLRInterface); overload; virtual;
procedure InsertAfter(const ProgramName: String; const T: IToken;
const Text: IANTLRInterface); overload; virtual;
procedure InsertAfter(const ProgramName: String; const Index: Integer;
const Text: IANTLRInterface); overload; virtual;
procedure InsertAfter(const T: IToken; const Text: String); overload;
procedure InsertAfter(const Index: Integer; const Text: String); overload;
procedure InsertAfter(const ProgramName: String; const T: IToken;
const Text: String); overload;
procedure InsertAfter(const ProgramName: String; const Index: Integer;
const Text: String); overload;
procedure InsertBefore(const T: IToken; const Text: IANTLRInterface); overload; virtual;
procedure InsertBefore(const Index: Integer; const Text: IANTLRInterface); overload; virtual;
procedure InsertBefore(const ProgramName: String; const T: IToken;
const Text: IANTLRInterface); overload; virtual;
procedure InsertBefore(const ProgramName: String; const Index: Integer;
const Text: IANTLRInterface); overload; virtual;
procedure InsertBefore(const T: IToken; const Text: String); overload;
procedure InsertBefore(const Index: Integer; const Text: String); overload;
procedure InsertBefore(const ProgramName: String; const T: IToken;
const Text: String); overload;
procedure InsertBefore(const ProgramName: String; const Index: Integer;
const Text: String); overload;
procedure Replace(const Index: Integer; const Text: IANTLRInterface); overload; virtual;
procedure Replace(const Start, Stop: Integer; const Text: IANTLRInterface); overload; virtual;
procedure Replace(const IndexT: IToken; const Text: IANTLRInterface); overload; virtual;
procedure Replace(const Start, Stop: IToken; const Text: IANTLRInterface); overload; virtual;
procedure Replace(const ProgramName: String; const Start, Stop: Integer;
const Text: IANTLRInterface); overload; virtual;
procedure Replace(const ProgramName: String; const Start, Stop: IToken;
const Text: IANTLRInterface); overload; virtual;
procedure Replace(const Index: Integer; const Text: String); overload;
procedure Replace(const Start, Stop: Integer; const Text: String); overload;
procedure Replace(const IndexT: IToken; const Text: String); overload;
procedure Replace(const Start, Stop: IToken; const Text: String); overload;
procedure Replace(const ProgramName: String; const Start, Stop: Integer;
const Text: String); overload;
procedure Replace(const ProgramName: String; const Start, Stop: IToken;
const Text: String); overload;
procedure Delete(const Index: Integer); overload; virtual;
procedure Delete(const Start, Stop: Integer); overload; virtual;
procedure Delete(const IndexT: IToken); overload; virtual;
procedure Delete(const Start, Stop: IToken); overload; virtual;
procedure Delete(const ProgramName: String; const Start, Stop: Integer); overload; virtual;
procedure Delete(const ProgramName: String; const Start, Stop: IToken); overload; virtual;
function GetLastRewriteTokenIndex: Integer; overload; virtual;
function ToOriginalString: String; overload; virtual;
function ToOriginalString(const Start, Stop: Integer): String; overload; virtual;
function ToString(const ProgramName: String): String; overload; virtual;
function ToString(const ProgramName: String;
const Start, Stop: Integer): String; overload; virtual;
function ToDebugString: String; overload; virtual;
function ToDebugString(const Start, Stop: Integer): String; overload; virtual;
protected
{ ITokenStream }
function ToString(const Start, Stop: Integer): String; overload; override;
strict protected
procedure Init; virtual;
function GetProgram(const Name: String): IList<IRewriteOperation>; virtual;
function GetLastRewriteTokenIndex(const ProgramName: String): Integer; overload; virtual;
procedure SetLastRewriteTokenIndex(const ProgramName: String; const I: Integer); overload; virtual;
/// <summary>
/// Return a map from token index to operation.
/// </summary>
/// <remarks>We need to combine operations and report invalid operations (like
/// overlapping replaces that are not completed nested). Inserts to
/// same index need to be combined etc... Here are the cases:
///
/// I.i.u I.j.v leave alone, nonoverlapping
/// I.i.u I.i.v combine: Iivu
///
/// R.i-j.u R.x-y.v | i-j in x-y delete first R
/// R.i-j.u R.i-j.v delete first R
/// R.i-j.u R.x-y.v | x-y in i-j ERROR
/// R.i-j.u R.x-y.v | boundaries overlap ERROR
///
/// I.i.u R.x-y.v | i in x-y delete I
/// I.i.u R.x-y.v | i not in x-y leave alone, nonoverlapping
/// R.x-y.v I.i.u | i in x-y ERROR
/// R.x-y.v I.x.u R.x-y.uv (combine, delete I)
/// R.x-y.v I.i.u | i not in x-y leave alone, nonoverlapping
///
/// I.i.u = insert u before op @ index i
/// R.x-y.u = replace x-y indexed tokens with u
///
/// First we need to examine replaces. For any replace op:
///
/// 1. wipe out any insertions before op within that range.
/// 2. Drop any replace op before that is contained completely within
/// that range.
/// 3. Throw exception upon boundary overlap with any previous replace.
///
/// Then we can deal with inserts:
///
/// 1. for any inserts to same index, combine even if not adjacent.
/// 2. for any prior replace with same left boundary, combine this
/// insert with replace and delete this replace.
/// 3. throw exception if index in same range as previous replace
///
/// Don't actually delete; make op null in list. Easier to walk list.
/// Later we can throw as we add to index -> op map.
///
/// Note that I.2 R.2-2 will wipe out I.2 even though, technically, the
/// inserted stuff would be before the replace range. But, if you
/// add tokens in front of a method body '{' and then delete the method
/// body, I think the stuff before the '{' you added should disappear too.
/// </remarks>
function ReduceToSingleOperationPerIndex(
const Rewrites: IList<IRewriteOperation>): IDictionary<Integer, IRewriteOperation>;
function GetKindOfOps(const Rewrites: IList<IRewriteOperation>;
const Kind: TGUID): IList<IRewriteOperation>; overload;
/// <summary>
/// Get all operations before an index of a particular kind
/// </summary>
function GetKindOfOps(const Rewrites: IList<IRewriteOperation>;
const Kind: TGUID; const Before: Integer): IList<IRewriteOperation>; overload;
function CatOpText(const A, B: IANTLRInterface): IANTLRInterface;
public
constructor Create; overload;
constructor Create(const ATokenSource: ITokenSource); overload;
constructor Create(const ATokenSource: ITokenSource;
const AChannel: Integer); overload;
constructor Create(const ALexer: ILexer); overload;
constructor Create(const ALexer: ILexer;
const AChannel: Integer); overload;
function ToString: String; overload; override;
end;
{ These functions return X or, if X = nil, an empty default instance }
function Def(const X: IToken): IToken; overload;
function Def(const X: IRuleReturnScope): IRuleReturnScope; overload;
implementation
uses
StrUtils,
Math,
Antlr.Runtime.Tree;
{ ERecognitionException }
constructor ERecognitionException.Create;
begin
Create('', nil);
end;
constructor ERecognitionException.Create(const AMessage: String);
begin
Create(AMessage, nil);
end;
constructor ERecognitionException.Create(const AInput: IIntStream);
begin
Create('', AInput);
end;
constructor ERecognitionException.Create(const AMessage: String;
const AInput: IIntStream);
var
TokenStream: ITokenStream;
CharStream: ICharStream;
begin
inherited Create(AMessage);
FInput := AInput;
FIndex := AInput.Index;
if Supports(AInput, ITokenStream, TokenStream) then
begin
FToken := TokenStream.LT(1);
FLine := FToken.Line;
FCharPositionInLine := FToken.CharPositionInLine;
end;
if Supports(AInput, ITreeNodeStream) then
ExtractInformationFromTreeNodeStream(AInput)
else
begin
if Supports(AInput, ICharStream, CharStream) then
begin
FC := AInput.LA(1);
FLine := CharStream.Line;
FCharPositionInLine := CharStream.CharPositionInLine;
end
else
FC := AInput.LA(1);
end;
end;
procedure ERecognitionException.ExtractInformationFromTreeNodeStream(
const Input: IIntStream);
var
Nodes: ITreeNodeStream;
Adaptor: ITreeAdaptor;
Payload, PriorPayload: IToken;
I, NodeType: Integer;
PriorNode: IANTLRInterface;
Tree: ITree;
Text: String;
CommonTree: ICommonTree;
begin
Nodes := Input as ITreeNodeStream;
FNode := Nodes.LT(1);
Adaptor := Nodes.TreeAdaptor;
Payload := Adaptor.GetToken(FNode);
if Assigned(Payload) then
begin
FToken := Payload;
if (Payload.Line <= 0) then
begin
// imaginary node; no line/pos info; scan backwards
I := -1;
PriorNode := Nodes.LT(I);
while Assigned(PriorNode) do
begin
PriorPayload := Adaptor.GetToken(PriorNode);
if Assigned(PriorPayload) and (PriorPayload.Line > 0) then
begin
// we found the most recent real line / pos info
FLine := PriorPayload.Line;
FCharPositionInLine := PriorPayload.CharPositionInLine;
FApproximateLineInfo := True;
Break;
end;
Dec(I);
PriorNode := Nodes.LT(I)
end;
end
else
begin
// node created from real token
FLine := Payload.Line;
FCharPositionInLine := Payload.CharPositionInLine;
end;
end else
if Supports(FNode, ITree, Tree) then
begin
FLine := Tree.Line;
FCharPositionInLine := Tree.CharPositionInLine;
if Supports(FNode, ICommonTree, CommonTree) then
FToken := CommonTree.Token;
end
else
begin
NodeType := Adaptor.GetNodeType(FNode);
Text := Adaptor.GetNodeText(FNode);
FToken := TCommonToken.Create(NodeType, Text);
end;
end;
function ERecognitionException.GetUnexpectedType: Integer;
var
Nodes: ITreeNodeStream;
Adaptor: ITreeAdaptor;
begin
if Supports(FInput, ITokenStream) then
Result := FToken.TokenType
else
if Supports(FInput, ITreeNodeStream, Nodes) then
begin
Adaptor := Nodes.TreeAdaptor;
Result := Adaptor.GetNodeType(FNode);
end else
Result := FC;
end;
{ EMismatchedTokenException }
constructor EMismatchedTokenException.Create(const AExpecting: Integer;
const AInput: IIntStream);
begin
inherited Create(AInput);
FExpecting := AExpecting;
end;
function EMismatchedTokenException.ToString: String;
begin
Result := 'MismatchedTokenException(' + IntToStr(UnexpectedType)
+ '!=' + IntToStr(Expecting) + ')';
end;
{ EUnwantedTokenException }
function EUnwantedTokenException.GetUnexpectedToken: IToken;
begin
Result := FToken;
end;
function EUnwantedTokenException.ToString: String;
var
Exp: String;
begin
if (Expecting = TToken.INVALID_TOKEN_TYPE) then
Exp := ''
else
Exp := ', expected ' + IntToStr(Expecting);
if (Token = nil) then
Result := 'UnwantedTokenException(found=nil' + Exp + ')'
else
Result := 'UnwantedTokenException(found=' + Token.Text + Exp + ')'
end;
{ EMissingTokenException }
constructor EMissingTokenException.Create(const AExpecting: Integer;
const AInput: IIntStream; const AInserted: IANTLRInterface);
begin
inherited Create(AExpecting, AInput);
FInserted := AInserted;
end;
function EMissingTokenException.GetMissingType: Integer;
begin
Result := Expecting;
end;
function EMissingTokenException.ToString: String;
begin
if Assigned(FInserted) and Assigned(FToken) then
Result := 'MissingTokenException(inserted ' + FInserted.ToString
+ ' at ' + FToken.Text + ')'
else
if Assigned(FToken) then
Result := 'MissingTokenException(at ' + FToken.Text + ')'
else
Result := 'MissingTokenException';
end;
{ EMismatchedTreeNodeException }
constructor EMismatchedTreeNodeException.Create(const AExpecting: Integer;
const AInput: IIntStream);
begin
inherited Create(AInput);
FExpecting := AExpecting;
end;
function EMismatchedTreeNodeException.ToString: String;
begin
Result := 'MismatchedTreeNodeException(' + IntToStr(UnexpectedType)
+ '!=' + IntToStr(Expecting) + ')';
end;
{ ENoViableAltException }
constructor ENoViableAltException.Create(
const AGrammarDecisionDescription: String; const ADecisionNumber,
AStateNumber: Integer; const AInput: IIntStream);
begin
inherited Create(AInput);
FGrammarDecisionDescription := AGrammarDecisionDescription;
FDecisionNumber := ADecisionNumber;
FStateNumber := AStateNumber;
end;
function ENoViableAltException.ToString: String;
begin
if Supports(Input, ICharStream) then
Result := 'NoViableAltException(''' + Char(UnexpectedType) + '''@['
+ FGrammarDecisionDescription + '])'
else
Result := 'NoViableAltException(''' + IntToStr(UnexpectedType) + '''@['
+ FGrammarDecisionDescription + '])'
end;
{ EEarlyExitException }
constructor EEarlyExitException.Create(const ADecisionNumber: Integer;
const AInput: IIntStream);
begin
inherited Create(AInput);
FDecisionNumber := ADecisionNumber;
end;
{ EMismatchedSetException }
constructor EMismatchedSetException.Create(const AExpecting: IBitSet;
const AInput: IIntStream);
begin
inherited Create(AInput);
FExpecting := AExpecting;
end;
function EMismatchedSetException.ToString: String;
begin
Result := 'MismatchedSetException(' + IntToStr(UnexpectedType)
+ '!=' + Expecting.ToString + ')';
end;
{ EMismatchedNotSetException }
function EMismatchedNotSetException.ToString: String;
begin
Result := 'MismatchedNotSetException(' + IntToStr(UnexpectedType)
+ '!=' + Expecting.ToString + ')';
end;
{ EFailedPredicateException }
constructor EFailedPredicateException.Create(const AInput: IIntStream;
const ARuleName, APredicateText: String);
begin
inherited Create(AInput);
FRuleName := ARuleName;
FPredicateText := APredicateText;
end;
function EFailedPredicateException.ToString: String;
begin
Result := 'FailedPredicateException(' + FRuleName + ',{' + FPredicateText + '}?)';
end;
{ EMismatchedRangeException }
constructor EMismatchedRangeException.Create(const AA, AB: Integer;
const AInput: IIntStream);
begin
inherited Create(FInput);
FA := AA;
FB := AB;
end;
function EMismatchedRangeException.ToString: String;
begin
Result := 'MismatchedNotSetException(' + IntToStr(UnexpectedType)
+ ' not in [' + IntToStr(FA)+ ',' + IntToStr(FB) + '])';
end;
{ TCharStreamState }
function TCharStreamState.GetCharPositionInLine: Integer;
begin
Result := FCharPositionInLine;
end;
function TCharStreamState.GetLine: Integer;
begin
Result := FLine;
end;
function TCharStreamState.GetP: Integer;
begin
Result := FP;
end;
procedure TCharStreamState.SetCharPositionInLine(const Value: Integer);
begin
FCharPositionInLine := Value;
end;
procedure TCharStreamState.SetLine(const Value: Integer);
begin
FLine := Value;
end;
procedure TCharStreamState.SetP(const Value: Integer);
begin
FP := Value;
end;
{ TANTLRStringStream }
constructor TANTLRStringStream.Create(const AInput: String);
begin
inherited Create;
FLine := 1;
FOwnsData := True;
FN := Length(AInput);
if (FN > 0) then
begin
GetMem(FData,FN * SizeOf(Char));
Move(AInput[1],FData^,FN * SizeOf(Char));
end;
end;
procedure TANTLRStringStream.Consume;
begin
if (FP < FN) then
begin
Inc(FCharPositionInLine);
if (FData[FP] = #10) then
begin
Inc(FLine);
FCharPositionInLine := 0;
end;
Inc(FP);
end;
end;
constructor TANTLRStringStream.Create(const AData: PChar;
const ANumberOfActualCharsInArray: Integer);
begin
inherited Create;
FLine := 1;
FOwnsData := False;
FData := AData;
FN := ANumberOfActualCharsInArray;
end;
constructor TANTLRStringStream.Create;
begin
inherited Create;
FLine := 1;
end;
destructor TANTLRStringStream.Destroy;
begin
if (FOwnsData) then
FreeMem(FData);
inherited;
end;
function TANTLRStringStream.GetCharPositionInLine: Integer;
begin
Result := FCharPositionInLine;
end;
function TANTLRStringStream.GetLine: Integer;
begin
Result := FLine;
end;
function TANTLRStringStream.GetSourceName: String;
begin
Result := FName;
end;
function TANTLRStringStream.Index: Integer;
begin
Result := FP;
end;
function TANTLRStringStream.LA(I: Integer): Integer;
begin
if (I = 0) then
Result := 0 // undefined
else begin
if (I < 0) then
begin
Inc(I); // e.g., translate LA(-1) to use offset i=0; then data[p+0-1]
if ((FP + I - 1) < 0) then
begin
Result := Integer(cscEOF);
Exit;
end;
end;
if ((FP + I - 1) >= FN) then
Result := Integer(cscEOF)
else
Result := Integer(FData[FP + I - 1]);
end;
end;
function TANTLRStringStream.LAChar(I: Integer): Char;
begin
Result := Char(LA(I));
end;
function TANTLRStringStream.LT(const I: Integer): Integer;
begin
Result := LA(I);
end;
function TANTLRStringStream.Mark: Integer;
var
State: ICharStreamState;
begin
if (FMarkers = nil) then
begin
FMarkers := TList<ICharStreamState>.Create;
FMarkers.Add(nil); // depth 0 means no backtracking, leave blank
end;
Inc(FMarkDepth);
if (FMarkDepth >= FMarkers.Count) then
begin
State := TCharStreamState.Create;
FMarkers.Add(State);
end
else
State := FMarkers[FMarkDepth];
State.P := FP;
State.Line := FLine;
State.CharPositionInLine := FCharPositionInLine;
FLastMarker := FMarkDepth;
Result := FMarkDepth;
end;
procedure TANTLRStringStream.Release(const Marker: Integer);
begin
// unwind any other markers made after m and release m
FMarkDepth := Marker;
// release this marker
Dec(FMarkDepth);
end;
procedure TANTLRStringStream.Reset;
begin
FP := 0;
FLine := 1;
FCharPositionInLine := 0;
FMarkDepth := 0;
end;
procedure TANTLRStringStream.Rewind(const Marker: Integer);
var
State: ICharStreamState;
begin
State := FMarkers[Marker];
// restore stream state
Seek(State.P);
FLine := State.Line;
FCharPositionInLine := State.CharPositionInLine;
Release(Marker);
end;
procedure TANTLRStringStream.Rewind;
begin
Rewind(FLastMarker);
end;
procedure TANTLRStringStream.Seek(const Index: Integer);
begin
if (Index <= FP) then
FP := Index // just jump; don't update stream state (line, ...)
else begin
// seek forward, consume until p hits index
while (FP < Index) do
Consume;
end;
end;
procedure TANTLRStringStream.SetCharPositionInLine(const Value: Integer);
begin
FCharPositionInLine := Value;
end;
procedure TANTLRStringStream.SetLine(const Value: Integer);
begin
FLine := Value;
end;
function TANTLRStringStream.Size: Integer;
begin
Result := FN;
end;
function TANTLRStringStream.Substring(const Start, Stop: Integer): String;
begin
Result := Copy(FData, Start + 1, Stop - Start + 1);
end;
{ TANTLRFileStream }
constructor TANTLRFileStream.Create(const AFileName: String);
begin
Create(AFilename,TEncoding.Default);
end;
constructor TANTLRFileStream.Create(const AFileName: String;
const AEncoding: TEncoding);
begin
inherited Create;
FFileName := AFileName;
Load(FFileName, AEncoding);
end;
function TANTLRFileStream.GetSourceName: String;
begin
Result := FFileName;
end;
procedure TANTLRFileStream.Load(const FileName: String;
const Encoding: TEncoding);
var
FR: TStreamReader;
S: String;
begin
if (FFileName <> '') then
begin
if (Encoding = nil) then
FR := TStreamReader.Create(FileName,TEncoding.Default)
else
FR := TStreamReader.Create(FileName,Encoding);
try
if (FOwnsData) then
begin
FreeMem(FData);
FData := nil;
end;
FOwnsData := True;
S := FR.ReadToEnd;
FN := Length(S);
if (FN > 0) then
begin
GetMem(FData,FN * SizeOf(Char));
Move(S[1],FData^,FN * SizeOf(Char));
end;
finally
FR.Free;
end;
end;
end;
{ TBitSet }
class function TBitSet.BitSetOf(const El: Integer): IBitSet;
begin
Result := TBitSet.Create(El + 1);
Result.Add(El);
end;
class function TBitSet.BitSetOf(const A, B: Integer): IBitSet;
begin
Result := TBitSet.Create(Max(A,B) + 1);
Result.Add(A);
Result.Add(B);
end;
class function TBitSet.BitSetOf(const A, B, C: Integer): IBitSet;
begin
Result := TBitSet.Create;
Result.Add(A);
Result.Add(B);
Result.Add(C);
end;
class function TBitSet.BitSetOf(const A, B, C, D: Integer): IBitSet;
begin
Result := TBitSet.Create;
Result.Add(A);
Result.Add(B);
Result.Add(C);
Result.Add(D);
end;
procedure TBitSet.Add(const El: Integer);
var
N: Integer;
begin
N := WordNumber(El);
if (N >= Length(FBits)) then
GrowToInclude(El);
FBits[N] := FBits[N] or BitMask(El);
end;
class function TBitSet.BitMask(const BitNumber: Integer): UInt64;
var
BitPosition: Integer;
begin
BitPosition := BitNumber and MOD_MASK;
Result := UInt64(1) shl BitPosition;
end;
function TBitSet.BitSetOr(const A: IBitSet): IBitSet;
begin
Result := Clone as IBitSet;
Result.OrInPlace(A);
end;
function TBitSet.Clone: IANTLRInterface;
var
BS: TBitSet;
begin
BS := TBitSet.Create;
Result := BS;
SetLength(BS.FBits,Length(FBits));
if (Length(FBits) > 0) then
Move(FBits[0],BS.FBits[0],Length(FBits) * SizeOf(UInt64));
end;
constructor TBitSet.Create;
begin
Create(BITS);
end;
constructor TBitSet.Create(const ABits: array of UInt64);
begin
inherited Create;
SetLength(FBits, Length(ABits));
if (Length(ABits) > 0) then
Move(ABits[0], FBits[0], Length(ABits) * SizeOf(UInt64));
end;
constructor TBitSet.Create(const AItems: IList<Integer>);
var
V: Integer;
begin
Create(BITS);
for V in AItems do
Add(V);
end;
constructor TBitSet.Create(const ANBits: Integer);
begin
inherited Create;
SetLength(FBits,((ANBits - 1) shr LOG_BITS) + 1);
end;
function TBitSet.Equals(Obj: TObject): Boolean;
var
OtherSet: TBitSet absolute Obj;
I, N: Integer;
begin
Result := False;
if (Obj = nil) or (not (Obj is TBitSet)) then
Exit;
N := Min(Length(FBits), Length(OtherSet.FBits));
// for any bits in common, compare
for I := 0 to N - 1 do
begin
if (FBits[I] <> OtherSet.FBits[I]) then
Exit;
end;
// make sure any extra bits are off
if (Length(FBits) > N) then
begin
for I := N + 1 to Length(FBits) - 1 do
begin
if (FBits[I] <> 0) then
Exit;
end;
end
else
if (Length(OtherSet.FBits) > N) then
begin
for I := N + 1 to Length(OtherSet.FBits) - 1 do
begin
if (OtherSet.FBits[I] <> 0) then
Exit;
end;
end;
Result := True;
end;
function TBitSet.GetIsNil: Boolean;
var
I: Integer;
begin
for I := Length(FBits) - 1 downto 0 do
if (FBits[I] <> 0) then
begin
Result := False;
Exit;
end;
Result := True;
end;
procedure TBitSet.GrowToInclude(const Bit: Integer);
var
NewSize: Integer;
begin
NewSize := Max(Length(FBits) shl 1,NumWordsToHold(Bit));
SetLength(FBits,NewSize);
end;
function TBitSet.LengthInLongWords: Integer;
begin
Result := Length(FBits);
end;
function TBitSet.Member(const El: Integer): Boolean;
var
N: Integer;
begin
if (El < 0) then
Result := False
else
begin
N := WordNumber(El);
if (N >= Length(FBits)) then
Result := False
else
Result := ((FBits[N] and BitMask(El)) <> 0);
end;
end;
function TBitSet.NumBits: Integer;
begin
Result := Length(FBits) shl LOG_BITS;
end;
class function TBitSet.NumWordsToHold(const El: Integer): Integer;
begin
Result := (El shr LOG_BITS) + 1;
end;
procedure TBitSet.OrInPlace(const A: IBitSet);
var
I, M: Integer;
ABits: TUInt64Array;
begin
if Assigned(A) then
begin
// If this is smaller than a, grow this first
if (A.LengthInLongWords > Length(FBits)) then
SetLength(FBits,A.LengthInLongWords);
M := Min(Length(FBits), A.LengthInLongWords);
ABits := A.ToPackedArray;
for I := M - 1 downto 0 do
FBits[I] := FBits[I] or ABits[I];
end;
end;
procedure TBitSet.Remove(const El: Integer);
var
N: Integer;
begin
N := WordNumber(El);
if (N < Length(FBits)) then
FBits[N] := (FBits[N] and not BitMask(El));
end;
function TBitSet.Size: Integer;
var
I, Bit: Integer;
W: UInt64;
begin
Result := 0;
for I := Length(FBits) - 1 downto 0 do
begin
W := FBits[I];
if (W <> 0) then
begin
for Bit := BITS - 1 downto 0 do
begin
if ((W and (UInt64(1) shl Bit)) <> 0) then
Inc(Result);
end;
end;
end;
end;
function TBitSet.ToArray: TIntegerArray;
var
I, En: Integer;
begin
SetLength(Result,Size);
En := 0;
for I := 0 to (Length(FBits) shl LOG_BITS) - 1 do
begin
if Member(I) then
begin
Result[En] := I;
Inc(En);
end;
end;
end;
function TBitSet.ToPackedArray: TUInt64Array;
begin
Result := FBits;
end;
function TBitSet.ToString: String;
begin
Result := ToString(nil);
end;
function TBitSet.ToString(const TokenNames: TStringArray): String;
var
Buf: TStringBuilder;
I: Integer;
HavePrintedAnElement: Boolean;
begin
HavePrintedAnElement := False;
Buf := TStringBuilder.Create;
try
Buf.Append('{');
for I := 0 to (Length(FBits) shl LOG_BITS) - 1 do
begin
if Member(I) then
begin
if (I > 0) and HavePrintedAnElement then
Buf.Append(',');
if Assigned(TokenNames) then
Buf.Append(TokenNames[I])
else
Buf.Append(I);
HavePrintedAnElement := True;
end;
end;
Buf.Append('}');
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
class function TBitSet.WordNumber(const Bit: Integer): Integer;
begin
Result := Bit shr LOG_BITS; // Bit / BITS
end;
{ TRecognizerSharedState }
constructor TRecognizerSharedState.Create;
var
I: Integer;
begin
inherited;
SetLength(FFollowing,TBaseRecognizer.INITIAL_FOLLOW_STACK_SIZE);
for I := 0 to TBaseRecognizer.INITIAL_FOLLOW_STACK_SIZE - 1 do
FFollowing[I] := TBitSet.Create;
FFollowingStackPointer := -1;
FLastErrorIndex := -1;
FTokenStartCharIndex := -1;
end;
function TRecognizerSharedState.GetBacktracking: Integer;
begin
Result := FBacktracking;
end;
function TRecognizerSharedState.GetChannel: Integer;
begin
Result := FChannel;
end;
function TRecognizerSharedState.GetErrorRecovery: Boolean;
begin
Result := FErrorRecovery;
end;
function TRecognizerSharedState.GetFailed: Boolean;
begin
Result := FFailed;
end;
function TRecognizerSharedState.GetFollowing: TBitSetArray;
begin
Result := FFollowing;
end;
function TRecognizerSharedState.GetFollowingStackPointer: Integer;
begin
Result := FFollowingStackPointer;
end;
function TRecognizerSharedState.GetLastErrorIndex: Integer;
begin
Result := FLastErrorIndex;
end;
function TRecognizerSharedState.GetRuleMemo: TDictionaryArray<Integer, Integer>;
begin
Result := FRuleMemo;
end;
function TRecognizerSharedState.GetRuleMemoCount: Integer;
begin
Result := Length(FRuleMemo);
end;
function TRecognizerSharedState.GetSyntaxErrors: Integer;
begin
Result := FSyntaxErrors;
end;
function TRecognizerSharedState.GetText: String;
begin
Result := FText;
end;
function TRecognizerSharedState.GetToken: IToken;
begin
Result := FToken;
end;
function TRecognizerSharedState.GetTokenStartCharIndex: Integer;
begin
Result := FTokenStartCharIndex;
end;
function TRecognizerSharedState.GetTokenStartCharPositionInLine: Integer;
begin
Result := FTokenStartCharPositionInLine;
end;
function TRecognizerSharedState.GetTokenStartLine: Integer;
begin
Result := FTokenStartLine;
end;
function TRecognizerSharedState.GetTokenType: Integer;
begin
Result := FTokenType;
end;
procedure TRecognizerSharedState.SetBacktracking(const Value: Integer);
begin
FBacktracking := Value;
end;
procedure TRecognizerSharedState.SetChannel(const Value: Integer);
begin
FChannel := Value;
end;
procedure TRecognizerSharedState.SetErrorRecovery(const Value: Boolean);
begin
FErrorRecovery := Value;
end;
procedure TRecognizerSharedState.SetFailed(const Value: Boolean);
begin
FFailed := Value;
end;
procedure TRecognizerSharedState.SetFollowing(const Value: TBitSetArray);
begin
FFollowing := Value;
end;
procedure TRecognizerSharedState.SetFollowingStackPointer(const Value: Integer);
begin
FFollowingStackPointer := Value;
end;
procedure TRecognizerSharedState.SetLastErrorIndex(const Value: Integer);
begin
FLastErrorIndex := Value;
end;
procedure TRecognizerSharedState.SetRuleMemoCount(const Value: Integer);
begin
SetLength(FRuleMemo, Value);
end;
procedure TRecognizerSharedState.SetSyntaxErrors(const Value: Integer);
begin
FSyntaxErrors := Value;
end;
procedure TRecognizerSharedState.SetText(const Value: String);
begin
FText := Value;
end;
procedure TRecognizerSharedState.SetToken(const Value: IToken);
begin
FToken := Value;
end;
procedure TRecognizerSharedState.SetTokenStartCharIndex(const Value: Integer);
begin
FTokenStartCharIndex := Value;
end;
procedure TRecognizerSharedState.SetTokenStartCharPositionInLine(
const Value: Integer);
begin
FTokenStartCharPositionInLine := Value;
end;
procedure TRecognizerSharedState.SetTokenStartLine(const Value: Integer);
begin
FTokenStartLine := Value;
end;
procedure TRecognizerSharedState.SetTokenType(const Value: Integer);
begin
FTokenType := Value;
end;
{ TCommonToken }
constructor TCommonToken.Create;
begin
inherited;
FChannel := TToken.DEFAULT_CHANNEL;
FCharPositionInLine := -1;
FIndex := -1;
end;
constructor TCommonToken.Create(const ATokenType: Integer);
begin
Create;
FTokenType := ATokenType;
end;
constructor TCommonToken.Create(const AInput: ICharStream; const ATokenType,
AChannel, AStart, AStop: Integer);
begin
Create;
FInput := AInput;
FTokenType := ATokenType;
FChannel := AChannel;
FStart := AStart;
FStop := AStop;
end;
constructor TCommonToken.Create(const ATokenType: Integer; const AText: String);
begin
Create;
FTokenType := ATokenType;
FChannel := TToken.DEFAULT_CHANNEL;
FText := AText;
end;
function TCommonToken.GetChannel: Integer;
begin
Result := FChannel;
end;
function TCommonToken.GetCharPositionInLine: Integer;
begin
Result := FCharPositionInLine;
end;
function TCommonToken.GetInputStream: ICharStream;
begin
Result := FInput;
end;
function TCommonToken.GetLine: Integer;
begin
Result := FLine;
end;
function TCommonToken.GetStartIndex: Integer;
begin
Result := FStart;
end;
function TCommonToken.GetStopIndex: Integer;
begin
Result := FStop;
end;
function TCommonToken.GetText: String;
begin
if (FText <> '') then
Result := FText
else
if (FInput = nil) then
Result := ''
else
Result := FInput.Substring(FStart, FStop);
end;
function TCommonToken.GetTokenIndex: Integer;
begin
Result := FIndex;
end;
function TCommonToken.GetTokenType: Integer;
begin
Result := FTokenType;
end;
procedure TCommonToken.SetChannel(const Value: Integer);
begin
FChannel := Value;
end;
procedure TCommonToken.SetCharPositionInLine(const Value: Integer);
begin
FCharPositionInLine := Value;
end;
procedure TCommonToken.SetInputStream(const Value: ICharStream);
begin
FInput := Value;
end;
procedure TCommonToken.SetLine(const Value: Integer);
begin
FLine := Value;
end;
procedure TCommonToken.SetStartIndex(const Value: Integer);
begin
FStart := Value;
end;
procedure TCommonToken.SetStopIndex(const Value: Integer);
begin
FStop := Value;
end;
procedure TCommonToken.SetText(const Value: String);
begin
(* Override the text for this token. The property getter
* will return this text rather than pulling from the buffer.
* Note that this does not mean that start/stop indexes are
* not valid. It means that the input was converted to a new
* string in the token object.
*)
FText := Value;
end;
procedure TCommonToken.SetTokenIndex(const Value: Integer);
begin
FIndex := Value;
end;
procedure TCommonToken.SetTokenType(const Value: Integer);
begin
FTokenType := Value;
end;
function TCommonToken.ToString: String;
var
ChannelStr, Txt: String;
begin
if (FChannel > 0) then
ChannelStr := ',channel=' + IntToStr(FChannel)
else
ChannelStr := '';
Txt := GetText;
if (Txt <> '') then
begin
Txt := ReplaceStr(Txt,#10,'\n');
Txt := ReplaceStr(Txt,#13,'\r');
Txt := ReplaceStr(Txt,#9,'\t');
end else
Txt := '<no text>';
Result := Format('[@%d,%d:%d=''%s'',<%d>%s,%d:%d]',
[FIndex,FStart,FStop,Txt,FTokenType,ChannelStr,FLine,FCharPositionInLine]);
end;
constructor TCommonToken.Create(const AOldToken: IToken);
var
OldCommonToken: ICommonToken;
begin
Create;
FText := AOldToken.Text;
FTokenType := AOldToken.TokenType;
FLine := AOldToken.Line;
FIndex := AOldToken.TokenIndex;
FCharPositionInLine := AOldToken.CharPositionInLine;
FChannel := AOldToken.Channel;
if Supports(AOldToken, ICommonToken, OldCommonToken) then
begin
FStart := OldCommonToken.StartIndex;
FStop := OldCommonToken.StopIndex;
end;
end;
{ TClassicToken }
constructor TClassicToken.Create(const AOldToken: IToken);
begin
inherited Create;
FText := AOldToken.Text;
FTokenType := AOldToken.TokenType;
FLine := AOldToken.Line;
FCharPositionInLine := AOldToken.CharPositionInLine;
FChannel := AOldToken.Channel;
end;
constructor TClassicToken.Create(const ATokenType: Integer);
begin
inherited Create;
FTokenType := ATokenType;
end;
constructor TClassicToken.Create(const ATokenType: Integer; const AText: String;
const AChannel: Integer);
begin
inherited Create;
FTokenType := ATokenType;
FText := AText;
FChannel := AChannel;
end;
constructor TClassicToken.Create(const ATokenType: Integer;
const AText: String);
begin
inherited Create;
FTokenType := ATokenType;
FText := AText;
end;
function TClassicToken.GetChannel: Integer;
begin
Result := FChannel;
end;
function TClassicToken.GetCharPositionInLine: Integer;
begin
Result := FCharPositionInLine;
end;
function TClassicToken.GetInputStream: ICharStream;
begin
// No default implementation
Result := nil;
end;
function TClassicToken.GetLine: Integer;
begin
Result := FLine;
end;
function TClassicToken.GetText: String;
begin
Result := FText;
end;
function TClassicToken.GetTokenIndex: Integer;
begin
Result := FIndex;
end;
function TClassicToken.GetTokenType: Integer;
begin
Result := FTokenType;
end;
procedure TClassicToken.SetChannel(const Value: Integer);
begin
FChannel := Value;
end;
procedure TClassicToken.SetCharPositionInLine(const Value: Integer);
begin
FCharPositionInLine := Value;
end;
procedure TClassicToken.SetInputStream(const Value: ICharStream);
begin
// No default implementation
end;
procedure TClassicToken.SetLine(const Value: Integer);
begin
FLine := Value;
end;
procedure TClassicToken.SetText(const Value: String);
begin
FText := Value;
end;
procedure TClassicToken.SetTokenIndex(const Value: Integer);
begin
FIndex := Value;
end;
procedure TClassicToken.SetTokenType(const Value: Integer);
begin
FTokenType := Value;
end;
function TClassicToken.ToString: String;
var
ChannelStr, Txt: String;
begin
if (FChannel > 0) then
ChannelStr := ',channel=' + IntToStr(FChannel)
else
ChannelStr := '';
Txt := FText;
if (Txt <> '') then
begin
Txt := ReplaceStr(Txt,#10,'\n');
Txt := ReplaceStr(Txt,#13,'\r');
Txt := ReplaceStr(Txt,#9,'\t');
end else
Txt := '<no text>';
Result := Format('[@%d,''%s'',<%d>%s,%d:%d]',
[FIndex,Txt,FTokenType,ChannelStr,FLine,FCharPositionInLine]);
end;
{ TToken }
class procedure TToken.Initialize;
begin
EOF_TOKEN := TCommonToken.Create(EOF);
INVALID_TOKEN := TCommonToken.Create(INVALID_TOKEN_TYPE);
SKIP_TOKEN := TCommonToken.Create(INVALID_TOKEN_TYPE);
end;
{ TBaseRecognizer }
constructor TBaseRecognizer.Create;
begin
inherited;
FState := TRecognizerSharedState.Create;
end;
function TBaseRecognizer.AlreadyParsedRule(const Input: IIntStream;
const RuleIndex: Integer): Boolean;
var
StopIndex: Integer;
begin
StopIndex := GetRuleMemoization(RuleIndex, Input.Index);
Result := (StopIndex <> MEMO_RULE_UNKNOWN);
if Result then
begin
if (StopIndex = MEMO_RULE_FAILED) then
FState.Failed := True
else
Input.Seek(StopIndex + 1); // jump to one past stop token
end;
end;
procedure TBaseRecognizer.BeginBacktrack(const Level: Integer);
begin
// No defeault implementation
end;
procedure TBaseRecognizer.BeginResync;
begin
// No defeault implementation
end;
procedure TBaseRecognizer.ConsumeUntil(const Input: IIntStream;
const TokenType: Integer);
var
TType: Integer;
begin
TType := Input.LA(1);
while (TType <> TToken.EOF) and (TType <> TokenType) do
begin
Input.Consume;
TType := Input.LA(1);
end;
end;
function TBaseRecognizer.CombineFollows(const Exact: Boolean): IBitSet;
var
I, Top: Integer;
LocalFollowSet: IBitSet;
begin
Top := FState.FollowingStackPointer;
Result := TBitSet.Create;
for I := Top downto 0 do
begin
LocalFollowSet := FState.Following[I];
Result.OrInPlace(LocalFollowSet);
if (Exact) then
begin
// can we see end of rule?
if LocalFollowSet.Member(TToken.EOR_TOKEN_TYPE) then
begin
// Only leave EOR in set if at top (start rule); this lets
// us know if have to include follow(start rule); i.e., EOF
if (I > 0) then
Result.Remove(TToken.EOR_TOKEN_TYPE);
end
else
// can't see end of rule, quit
Break;
end;
end;
end;
function TBaseRecognizer.ComputeContextSensitiveRuleFOLLOW: IBitSet;
begin
Result := CombineFollows(True);
end;
function TBaseRecognizer.ComputeErrorRecoverySet: IBitSet;
begin
Result := CombineFollows(False);
end;
procedure TBaseRecognizer.ConsumeUntil(const Input: IIntStream;
const BitSet: IBitSet);
var
TType: Integer;
begin
TType := Input.LA(1);
while (TType <> TToken.EOF) and (not BitSet.Member(TType)) do
begin
Input.Consume;
TType := Input.LA(1);
end;
end;
constructor TBaseRecognizer.Create(const AState: IRecognizerSharedState);
begin
if (AState = nil) then
Create
else
begin
inherited Create;
FState := AState;
end;
end;
procedure TBaseRecognizer.DisplayRecognitionError(
const TokenNames: TStringArray; const E: ERecognitionException);
var
Hdr, Msg: String;
begin
Hdr := GetErrorHeader(E);
Msg := GetErrorMessage(E, TokenNames);
EmitErrorMessage(Hdr + ' ' + Msg);
end;
procedure TBaseRecognizer.EmitErrorMessage(const Msg: String);
begin
WriteLn(Msg);
end;
procedure TBaseRecognizer.EndBacktrack(const Level: Integer;
const Successful: Boolean);
begin
// No defeault implementation
end;
procedure TBaseRecognizer.EndResync;
begin
// No defeault implementation
end;
function TBaseRecognizer.GetBacktrackingLevel: Integer;
begin
Result := FState.Backtracking;
end;
function TBaseRecognizer.GetCurrentInputSymbol(
const Input: IIntStream): IANTLRInterface;
begin
// No defeault implementation
Result := nil;
end;
function TBaseRecognizer.GetErrorHeader(const E: ERecognitionException): String;
begin
Result := 'line ' + IntToStr(E.Line) + ':' + IntToStr(E.CharPositionInLine);
end;
function TBaseRecognizer.GetErrorMessage(const E: ERecognitionException;
const TokenNames: TStringArray): String;
var
UTE: EUnwantedTokenException absolute E;
MTE: EMissingTokenException absolute E;
MMTE: EMismatchedTokenException absolute E;
MTNE: EMismatchedTreeNodeException absolute E;
NVAE: ENoViableAltException absolute E;
EEE: EEarlyExitException absolute E;
MSE: EMismatchedSetException absolute E;
MNSE: EMismatchedNotSetException absolute E;
FPE: EFailedPredicateException absolute E;
TokenName: String;
begin
Result := E.Message;
if (E is EUnwantedTokenException) then
begin
if (UTE.Expecting = TToken.EOF) then
TokenName := 'EOF'
else
TokenName := TokenNames[UTE.Expecting];
Result := 'extraneous input ' + GetTokenErrorDisplay(UTE.UnexpectedToken)
+ ' expecting ' + TokenName;
end
else
if (E is EMissingTokenException) then
begin
if (MTE.Expecting = TToken.EOF) then
TokenName := 'EOF'
else
TokenName := TokenNames[MTE.Expecting];
Result := 'missing ' + TokenName + ' at ' + GetTokenErrorDisplay(E.Token);
end
else
if (E is EMismatchedTokenException) then
begin
if (MMTE.Expecting = TToken.EOF) then
TokenName := 'EOF'
else
TokenName := TokenNames[MMTE.Expecting];
Result := 'mismatched input ' + GetTokenErrorDisplay(E.Token)
+ ' expecting ' + TokenName;
end
else
if (E is EMismatchedTreeNodeException) then
begin
if (MTNE.Expecting = TToken.EOF) then
Result := 'EOF'
else
Result := TokenNames[MTNE.Expecting];
// The ternary operator is only necessary because of a bug in the .NET framework
Result := 'mismatched tree node: ';
if (MTNE.Node <> nil) and (MTNE.Node.ToString <> '') then
Result := Result + MTNE.Node.ToString;
Result := Result + ' expecting ' + TokenName;
end
else
if (E is ENoViableAltException) then
begin
// for development, can add "decision=<<"+nvae.grammarDecisionDescription+">>"
// and "(decision="+nvae.decisionNumber+") and
// "state "+nvae.stateNumber
Result := 'no viable alternative at input ' + GetTokenErrorDisplay(E.Token);
end
else
if (E is EEarlyExitException) then
begin
// for development, can add "(decision="+eee.decisionNumber+")"
Result := 'required (...)+ loop did not match anyting at input '
+ GetTokenErrorDisplay(E.Token);
end else
if (E is EMismatchedSetException) then
begin
Result := 'mismatched input ' + GetTokenErrorDisplay(E.Token)
+ ' expecting set ' + MSE.Expecting.ToString;
end
else
if (E is EMismatchedNotSetException) then
begin
Result := 'mismatched input ' + GetTokenErrorDisplay(E.Token)
+ ' expecting set ' + MSE.Expecting.ToString;
end
else
if (E is EFailedPredicateException) then
begin
Result := 'rule ' + FPE.RuleName
+ ' failed predicate: {' + FPE.PredicateText + '}?';
end;
end;
function TBaseRecognizer.GetGrammarFileName: String;
begin
// No defeault implementation
Result := '';
end;
function TBaseRecognizer.GetMissingSymbol(const Input: IIntStream;
const E: ERecognitionException; const ExpectedTokenType: Integer;
const Follow: IBitSet): IANTLRInterface;
begin
// No defeault implementation
Result := nil;
end;
function TBaseRecognizer.GetNumberOfSyntaxErrors: Integer;
begin
Result := FState.SyntaxErrors;
end;
function TBaseRecognizer.GetRuleMemoization(const RuleIndex,
RuleStartIndex: Integer): Integer;
var
Dict: IDictionary<Integer, Integer>;
begin
Dict := FState.RuleMemo[RuleIndex];
if (Dict = nil) then
begin
Dict := TDictionary<Integer, Integer>.Create;
FState.RuleMemo[RuleIndex] := Dict;
end;
if (not Dict.TryGetValue(RuleStartIndex, Result)) then
Result := MEMO_RULE_UNKNOWN;
end;
function TBaseRecognizer.GetRuleMemoizationChaceSize: Integer;
var
RuleMap: IDictionary<Integer, Integer>;
begin
Result := 0;
if Assigned(FState.RuleMemo) then
begin
for RuleMap in FState.RuleMemo do
if Assigned(RuleMap) then
Inc(Result,RuleMap.Count); // how many input indexes are recorded?
end;
end;
function TBaseRecognizer.GetState: IRecognizerSharedState;
begin
Result := FState;
end;
function TBaseRecognizer.GetTokenErrorDisplay(const T: IToken): String;
begin
Result := T.Text;
if (Result = '') then
begin
if (T.TokenType = TToken.EOF) then
Result := '<EOF>'
else
Result := '<' + IntToStr(T.TokenType) + '>';
end;
Result := ReplaceStr(Result,#10,'\n');
Result := ReplaceStr(Result,#13,'\r');
Result := ReplaceStr(Result,#9,'\t');
Result := '''' + Result + '''';
end;
function TBaseRecognizer.GetTokenNames: TStringArray;
begin
// no default implementation
Result := nil;
end;
function TBaseRecognizer.Match(const Input: IIntStream;
const TokenType: Integer; const Follow: IBitSet): IANTLRInterface;
begin
Result := GetCurrentInputSymbol(Input);
if (Input.LA(1) = TokenType) then
begin
Input.Consume;
FState.ErrorRecovery := False;
FState.Failed := False;
end else
begin
if (FState.Backtracking > 0) then
FState.Failed := True
else
begin
Mismatch(Input, TokenType, Follow);
Result := RecoverFromMismatchedToken(Input, TokenType, Follow);
end;
end;
end;
procedure TBaseRecognizer.MatchAny(const Input: IIntStream);
begin
FState.ErrorRecovery := False;
FState.Failed := False;
Input.Consume;
end;
procedure TBaseRecognizer.Memoize(const Input: IIntStream; const RuleIndex,
RuleStartIndex: Integer);
var
StopTokenIndex: Integer;
Dict: IDictionary<Integer, Integer>;
begin
Dict := FState.RuleMemo[RuleIndex];
if Assigned(Dict) then
begin
if FState.Failed then
StopTokenIndex := MEMO_RULE_FAILED
else
StopTokenIndex := Input.Index - 1;
Dict.AddOrSetValue(RuleStartIndex, StopTokenIndex);
end;
end;
procedure TBaseRecognizer.Mismatch(const Input: IIntStream;
const TokenType: Integer; const Follow: IBitSet);
begin
if MismatchIsUnwantedToken(Input, TokenType) then
raise EUnwantedTokenException.Create(TokenType, Input)
else
if MismatchIsMissingToken(Input, Follow) then
raise EMissingTokenException.Create(TokenType, Input, nil)
else
raise EMismatchedTokenException.Create(TokenType, Input);
end;
function TBaseRecognizer.MismatchIsMissingToken(const Input: IIntStream;
const Follow: IBitSet): Boolean;
var
ViableTokensFollowingThisRule, Follow2: IBitSet;
begin
if (Follow = nil) then
// we have no information about the follow; we can only consume
// a single token and hope for the best
Result := False
else
begin
Follow2 := Follow;
// compute what can follow this grammar element reference
if (Follow.Member(TToken.EOR_TOKEN_TYPE)) then
begin
ViableTokensFollowingThisRule := ComputeContextSensitiveRuleFOLLOW();
Follow2 := Follow.BitSetOr(ViableTokensFollowingThisRule);
if (FState.FollowingStackPointer >= 0) then
// remove EOR if we're not the start symbol
Follow2.Remove(TToken.EOR_TOKEN_TYPE);
end;
// if current token is consistent with what could come after set
// then we know we're missing a token; error recovery is free to
// "insert" the missing token
// BitSet cannot handle negative numbers like -1 (EOF) so I leave EOR
// in follow set to indicate that the fall of the start symbol is
// in the set (EOF can follow).
if (Follow2.Member(Input.LA(1)) or Follow2.Member(TToken.EOR_TOKEN_TYPE)) then
Result := True
else
Result := False;
end;
end;
function TBaseRecognizer.MismatchIsUnwantedToken(const Input: IIntStream;
const TokenType: Integer): Boolean;
begin
Result := (Input.LA(2) = TokenType);
end;
procedure TBaseRecognizer.PushFollow(const FSet: IBitSet);
var
F: TBitSetArray;
I: Integer;
begin
if ((FState.FollowingStackPointer + 1) >= Length(FState.Following)) then
begin
SetLength(F, Length(FState.Following) * 2);
FillChar(F[0], Length(F) * SizeOf(IBitSet), 0);
for I := 0 to Length(FState.Following) - 1 do
F[I] := FState.Following[I];
FState.Following := F;
end;
FState.FollowingStackPointer := FState.FollowingStackPointer + 1;
FState.Following[FState.FollowingStackPointer] := FSet;
end;
procedure TBaseRecognizer.Recover(const Input: IIntStream;
const RE: ERecognitionException);
var
FollowSet: IBitSet;
begin
if (FState.LastErrorIndex = Input.Index) then
// uh oh, another error at same token index; must be a case
// where LT(1) is in the recovery token set so nothing is
// consumed; consume a single token so at least to prevent
// an infinite loop; this is a failsafe.
Input.Consume;
FState.LastErrorIndex := Input.Index;
FollowSet := ComputeErrorRecoverySet;
BeginResync;
ConsumeUntil(Input,FollowSet);
EndResync;
end;
function TBaseRecognizer.RecoverFromMismatchedSet(const Input: IIntStream;
const E: ERecognitionException; const Follow: IBitSet): IANTLRInterface;
begin
if MismatchIsMissingToken(Input, Follow) then
begin
ReportError(E);
// we don't know how to conjure up a token for sets yet
Result := GetMissingSymbol(Input, E, TToken.INVALID_TOKEN_TYPE, Follow);
end
else
begin
// TODO do single token deletion like above for Token mismatch
Result := nil;
raise E;
end;
end;
function TBaseRecognizer.RecoverFromMismatchedToken(const Input: IIntStream;
const TokenType: Integer; const Follow: IBitSet): IANTLRInterface;
var
E: ERecognitionException;
begin
// if next token is what we are looking for then "delete" this token
if MismatchIsUnwantedToken(Input, TokenType) then
begin
E := EUnwantedTokenException.Create(TokenType, Input);
BeginResync;
Input.Consume; // simply delete extra token
EndResync;
ReportError(E); // report after consuming so AW sees the token in the exception
// we want to return the token we're actually matching
Result := GetCurrentInputSymbol(Input);
Input.Consume; // move past ttype token as if all were ok
end
else
begin
// can't recover with single token deletion, try insertion
if MismatchIsMissingToken(Input, Follow) then
begin
E := nil;
Result := GetMissingSymbol(Input, E, TokenType, Follow);
E := EMissingTokenException.Create(TokenType, Input, Result);
ReportError(E); // report after inserting so AW sees the token in the exception
end
else
begin
// even that didn't work; must throw the exception
raise EMismatchedTokenException.Create(TokenType, Input);
end;
end;
end;
procedure TBaseRecognizer.ReportError(const E: ERecognitionException);
begin
// if we've already reported an error and have not matched a token
// yet successfully, don't report any errors.
if (not FState.ErrorRecovery) then
begin
FState.SyntaxErrors := FState.SyntaxErrors + 1; // don't count spurious
FState.ErrorRecovery := True;
DisplayRecognitionError(GetTokenNames, E);
end;
end;
procedure TBaseRecognizer.Reset;
var
I: Integer;
begin
// wack everything related to error recovery
if (FState = nil) then
Exit; // no shared state work to do
FState.FollowingStackPointer := -1;
FState.ErrorRecovery := False;
FState.LastErrorIndex := -1;
FState.Failed := False;
FState.SyntaxErrors := 0;
// wack everything related to backtracking and memoization
FState.Backtracking := 0;
if Assigned(FState.RuleMemo) then
for I := 0 to Length(FState.RuleMemo) - 1 do
begin
// wipe cache
FState.RuleMemo[I] := nil;
end;
end;
function TBaseRecognizer.ToStrings(const Tokens: IList<IToken>): IList<String>;
var
Token: IToken;
begin
if (Tokens = nil) then
Result := nil
else
begin
Result := TList<String>.Create;
for Token in Tokens do
Result.Add(Token.Text);
end;
end;
procedure TBaseRecognizer.TraceIn(const RuleName: String;
const RuleIndex: Integer; const InputSymbol: String);
begin
Write('enter ' + RuleName + ' ' + InputSymbol);
if (FState.Failed) then
WriteLn(' failed=True');
if (FState.Backtracking > 0) then
Write(' backtracking=' + IntToStr(FState.Backtracking));
WriteLn;
end;
procedure TBaseRecognizer.TraceOut(const RuleName: String;
const RuleIndex: Integer; const InputSymbol: String);
begin
Write('exit ' + RuleName + ' ' + InputSymbol);
if (FState.Failed) then
WriteLn(' failed=True');
if (FState.Backtracking > 0) then
Write(' backtracking=' + IntToStr(FState.Backtracking));
WriteLn;
end;
{ TCommonTokenStream }
procedure TCommonTokenStream.Consume;
begin
if (FP < FTokens.Count) then
begin
Inc(FP);
FP := SkipOffTokenChannels(FP); // leave p on valid token
end;
end;
constructor TCommonTokenStream.Create;
begin
inherited;
FP := -1;
FChannel := TToken.DEFAULT_CHANNEL;
FTokens := TList<IToken>.Create;
FTokens.Capacity := 500;
end;
constructor TCommonTokenStream.Create(const ATokenSource: ITokenSource);
begin
Create;
FTokenSource := ATokenSource;
end;
procedure TCommonTokenStream.DiscardOffChannelTokens(const Discard: Boolean);
begin
FDiscardOffChannelTokens := Discard;
end;
procedure TCommonTokenStream.DiscardTokenType(const TType: Integer);
begin
if (FDiscardSet = nil) then
FDiscardSet := THashList<Integer, Integer>.Create;
FDiscardSet.Add(TType, TType);
end;
procedure TCommonTokenStream.FillBuffer;
var
Index: Integer;
T: IToken;
Discard: Boolean;
begin
Index := 0;
T := FTokenSource.NextToken;
while Assigned(T) and (T.TokenType <> Integer(cscEOF)) do
begin
Discard := False;
// is there a channel override for token type?
if Assigned(FChannelOverrideMap) then
if FChannelOverrideMap.ContainsKey(T.TokenType) then
T.Channel := FChannelOverrideMap[T.TokenType];
if Assigned(FDiscardSet) and FDiscardSet.ContainsKey(T.TokenType) then
Discard := True
else
if FDiscardOffChannelTokens and (T.Channel <> FChannel) then
Discard := True;
if (not Discard) then
begin
T.TokenIndex := Index;
FTokens.Add(T);
Inc(Index);
end;
T := FTokenSource.NextToken;
end;
// leave p pointing at first token on channel
FP := 0;
FP := SkipOffTokenChannels(FP);
end;
function TCommonTokenStream.Get(const I: Integer): IToken;
begin
Result := FTokens[I];
end;
function TCommonTokenStream.GetSourceName: String;
begin
Result := FTokenSource.SourceName;
end;
function TCommonTokenStream.GetTokens(const Start, Stop: Integer;
const Types: IList<Integer>): IList<IToken>;
begin
Result := GetTokens(Start, Stop, TBitSet.Create(Types));
end;
function TCommonTokenStream.GetTokens(const Start, Stop,
TokenType: Integer): IList<IToken>;
begin
Result := GetTokens(Start, Stop, TBitSet.BitSetOf(TokenType));
end;
function TCommonTokenStream.GetTokens(const Start, Stop: Integer;
const Types: IBitSet): IList<IToken>;
var
I, StartIndex, StopIndex: Integer;
T: IToken;
begin
if (FP = -1) then
FillBuffer;
StopIndex := Min(Stop,FTokens.Count - 1);
StartIndex := Max(Start,0);
if (StartIndex > StopIndex) then
Result := nil
else
begin
Result := TList<IToken>.Create;
for I := StartIndex to StopIndex do
begin
T := FTokens[I];
if (Types = nil) or Types.Member(T.TokenType) then
Result.Add(T);
end;
if (Result.Count = 0) then
Result := nil;
end;
end;
function TCommonTokenStream.GetTokens: IList<IToken>;
begin
if (FP = -1) then
FillBuffer;
Result := FTokens;
end;
function TCommonTokenStream.GetTokens(const Start,
Stop: Integer): IList<IToken>;
begin
Result := GetTokens(Start, Stop, IBitSet(nil));
end;
function TCommonTokenStream.GetTokenSource: ITokenSource;
begin
Result := FTokenSource;
end;
function TCommonTokenStream.Index: Integer;
begin
Result := FP;
end;
function TCommonTokenStream.LA(I: Integer): Integer;
begin
Result := LT(I).TokenType;
end;
function TCommonTokenStream.LAChar(I: Integer): Char;
begin
Result := Char(LA(I));
end;
function TCommonTokenStream.LB(const K: Integer): IToken;
var
I, N: Integer;
begin
if (FP = -1) then
FillBuffer;
if (K = 0) then
Result := nil
else
if ((FP - K) < 0) then
Result := nil
else
begin
I := FP;
N := 1;
// find k good tokens looking backwards
while (N <= K) do
begin
// skip off-channel tokens
I := SkipOffTokenChannelsReverse(I - 1); // leave p on valid token
Inc(N);
end;
if (I < 0) then
Result := nil
else
Result := FTokens[I];
end;
end;
function TCommonTokenStream.LT(const K: Integer): IToken;
var
I, N: Integer;
begin
if (FP = -1) then
FillBuffer;
if (K = 0) then
Result := nil
else
if (K < 0) then
Result := LB(-K)
else
if ((FP + K - 1) >= FTokens.Count) then
Result := TToken.EOF_TOKEN
else
begin
I := FP;
N := 1;
// find k good tokens
while (N < K) do
begin
// skip off-channel tokens
I := SkipOffTokenChannels(I + 1); // leave p on valid token
Inc(N);
end;
if (I >= FTokens.Count) then
Result := TToken.EOF_TOKEN
else
Result := FTokens[I];
end;
end;
function TCommonTokenStream.Mark: Integer;
begin
if (FP = -1) then
FillBuffer;
FLastMarker := Index;
Result := FLastMarker;
end;
procedure TCommonTokenStream.Release(const Marker: Integer);
begin
// no resources to release
end;
procedure TCommonTokenStream.Reset;
begin
FP := 0;
FLastMarker := 0;
end;
procedure TCommonTokenStream.Rewind(const Marker: Integer);
begin
Seek(Marker);
end;
procedure TCommonTokenStream.Rewind;
begin
Seek(FLastMarker);
end;
procedure TCommonTokenStream.Seek(const Index: Integer);
begin
FP := Index;
end;
procedure TCommonTokenStream.SetTokenSource(const Value: ITokenSource);
begin
FTokenSource := Value;
FTokens.Clear;
FP := -1;
FChannel := TToken.DEFAULT_CHANNEL;
end;
procedure TCommonTokenStream.SetTokenTypeChannel(const TType, Channel: Integer);
begin
if (FChannelOverrideMap = nil) then
FChannelOverrideMap := TDictionary<Integer, Integer>.Create;
FChannelOverrideMap[TType] := Channel;
end;
function TCommonTokenStream.Size: Integer;
begin
Result := FTokens.Count;
end;
function TCommonTokenStream.SkipOffTokenChannels(const I: Integer): Integer;
var
N: Integer;
begin
Result := I;
N := FTokens.Count;
while (Result < N) and (FTokens[Result].Channel <> FChannel) do
Inc(Result);
end;
function TCommonTokenStream.SkipOffTokenChannelsReverse(
const I: Integer): Integer;
begin
Result := I;
while (Result >= 0) and (FTokens[Result].Channel <> FChannel) do
Dec(Result);
end;
function TCommonTokenStream.ToString: String;
begin
if (FP = -1) then
FillBuffer;
Result := ToString(0, FTokens.Count - 1);
end;
function TCommonTokenStream.ToString(const Start, Stop: Integer): String;
var
I, Finish: Integer;
Buf: TStringBuilder;
T: IToken;
begin
if (Start < 0) or (Stop < 0) then
Result := ''
else
begin
if (FP = -1) then
FillBuffer;
if (Stop >= FTokens.Count) then
Finish := FTokens.Count - 1
else
Finish := Stop;
Buf := TStringBuilder.Create;
try
for I := Start to Finish do
begin
T := FTokens[I];
Buf.Append(T.Text);
end;
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
end;
function TCommonTokenStream.ToString(const Start, Stop: IToken): String;
begin
if Assigned(Start) and Assigned(Stop) then
Result := ToString(Start.TokenIndex, Stop.TokenIndex)
else
Result := '';
end;
constructor TCommonTokenStream.Create(const ATokenSource: ITokenSource;
const AChannel: Integer);
begin
Create(ATokenSource);
FChannel := AChannel;
end;
constructor TCommonTokenStream.Create(const ALexer: ILexer);
begin
Create(ALexer as ITokenSource);
end;
constructor TCommonTokenStream.Create(const ALexer: ILexer;
const AChannel: Integer);
begin
Create(ALexer as ITokenSource, AChannel);
end;
{ TDFA }
function TDFA.Description: String;
begin
Result := 'n/a';
end;
procedure TDFA.Error(const NVAE: ENoViableAltException);
begin
// No default implementation
end;
function TDFA.GetRecognizer: IBaseRecognizer;
begin
Result := IBaseRecognizer(FRecognizer);
end;
function TDFA.GetSpecialStateTransitionHandler: TSpecialStateTransitionHandler;
begin
Result := FSpecialStateTransitionHandler;
end;
procedure TDFA.NoViableAlt(const S: Integer; const Input: IIntStream);
var
NVAE: ENoViableAltException;
begin
if (Recognizer.State.Backtracking > 0) then
Recognizer.State.Failed := True
else
begin
NVAE := ENoViableAltException.Create(Description, FDecisionNumber, S, Input);
Error(NVAE);
raise NVAE;
end;
end;
function TDFA.Predict(const Input: IIntStream): Integer;
var
Mark, S, SNext, SpecialState: Integer;
C: Char;
begin
Result := 0;
Mark := Input.Mark; // remember where decision started in input
S := 0; // we always start at s0
try
while True do
begin
SpecialState := FSpecial[S];
if (SpecialState >= 0) then
begin
S := FSpecialStateTransitionHandler(Self, SpecialState, Input);
if (S = -1) then
begin
NoViableAlt(S, Input);
Exit;
end;
Input.Consume;
Continue;
end;
if (FAccept[S] >= 1) then
begin
Result := FAccept[S];
Exit;
end;
// look for a normal char transition
C := Char(Input.LA(1)); // -1 == \uFFFF, all tokens fit in 65000 space
if (C >= FMin[S]) and (C <= FMax[S]) then
begin
SNext := FTransition[S,Integer(C) - Integer(FMin[S])]; // move to next state
if (SNext < 0) then
begin
// was in range but not a normal transition
// must check EOT, which is like the else clause.
// eot[s]>=0 indicates that an EOT edge goes to another
// state.
if (FEOT[S] >= 0) then // EOT Transition to accept state?
begin
S := FEOT[S];
Input.Consume;
// TODO: I had this as return accept[eot[s]]
// which assumed here that the EOT edge always
// went to an accept...faster to do this, but
// what about predicated edges coming from EOT
// target?
Continue;
end;
NoViableAlt(S, Input);
Exit;
end;
S := SNext;
Input.Consume;
Continue;
end;
if (FEOT[S] >= 0) then
begin
// EOT Transition?
S := FEOT[S];
Input.Consume;
Continue;
end;
if (C = Char(TToken.EOF)) and (FEOF[S] >= 0) then
begin
// EOF Transition to accept state?
Result := FAccept[FEOF[S]];
Exit;
end;
// not in range and not EOF/EOT, must be invalid symbol
NoViableAlt(S, Input);
Exit;
end;
finally
Input.Rewind(Mark);
end;
end;
procedure TDFA.SetRecognizer(const Value: IBaseRecognizer);
begin
FRecognizer := Pointer(Value);
end;
procedure TDFA.SetSpecialStateTransitionHandler(
const Value: TSpecialStateTransitionHandler);
begin
FSpecialStateTransitionHandler := Value;
end;
function TDFA.SpecialStateTransition(const S: Integer;
const Input: IIntStream): Integer;
begin
// No default implementation
Result := -1;
end;
function TDFA.SpecialTransition(const State, Symbol: Integer): Integer;
begin
Result := 0;
end;
class function TDFA.UnpackEncodedString(
const EncodedString: String): TSmallintArray;
var
I, J, DI, Size: Integer;
N, V: Char;
begin
Size := 0;
I := 1;
while (I <= Length(EncodedString)) do
begin
Inc(Size,Integer(EncodedString[I]));
Inc(I,2);
end;
SetLength(Result,Size);
DI := 0;
I := 1;
while (I <= Length(EncodedString)) do
begin
N := EncodedString[I];
V := EncodedString[I + 1];
// add v n times to data
for J := 1 to Integer(N) do
begin
Result[DI] := Smallint(V);
Inc(DI);
end;
Inc(I,2);
end;
end;
class function TDFA.UnpackEncodedStringArray(
const EncodedStrings: array of String): TSmallintMatrix;
var
I: Integer;
begin
SetLength(Result,Length(EncodedStrings));
for I := 0 to Length(EncodedStrings) - 1 do
Result[I] := UnpackEncodedString(EncodedStrings[I]);
end;
class function TDFA.UnpackEncodedStringArray(
const EncodedStrings: TStringArray): TSmallintMatrix;
var
I: Integer;
begin
SetLength(Result,Length(EncodedStrings));
for I := 0 to Length(EncodedStrings) - 1 do
Result[I] := UnpackEncodedString(EncodedStrings[I]);
end;
class function TDFA.UnpackEncodedStringToUnsignedChars(
const EncodedString: String): TCharArray;
var
I, J, DI, Size: Integer;
N, V: Char;
begin
Size := 0;
I := 1;
while (I <= Length(EncodedString)) do
begin
Inc(Size,Integer(EncodedString[I]));
Inc(I,2);
end;
SetLength(Result,Size);
DI := 0;
I := 1;
while (I <= Length(EncodedString)) do
begin
N := EncodedString[I];
V := EncodedString[I + 1];
// add v n times to data
for J := 1 to Integer(N) do
begin
Result[DI] := V;
Inc(DI);
end;
Inc(I,2);
end;
end;
{ TLexer }
constructor TLexer.Create;
begin
inherited;
end;
constructor TLexer.Create(const AInput: ICharStream);
begin
inherited Create;
FInput := AInput;
end;
constructor TLexer.Create(const AInput: ICharStream;
const AState: IRecognizerSharedState);
begin
inherited Create(AState);
FInput := AInput;
end;
function TLexer.Emit: IToken;
begin
Result := TCommonToken.Create(FInput, FState.TokenType, FState.Channel,
FState.TokenStartCharIndex, GetCharIndex - 1);
Result.Line := FState.TokenStartLine;
Result.Text := FState.Text;
Result.CharPositionInLine := FState.TokenStartCharPositionInLine;
Emit(Result);
end;
procedure TLexer.Emit(const Token: IToken);
begin
FState.Token := Token;
end;
function TLexer.GetCharErrorDisplay(const C: Integer): String;
begin
case C of
// TToken.EOF
TOKEN_dot_EOF:
Result := '<EOF>';
10:
Result := '\n';
9:
Result := '\t';
13:
Result := '\r';
else
Result := Char(C);
end;
Result := '''' + Result + '''';
end;
function TLexer.GetCharIndex: Integer;
begin
Result := FInput.Index;
end;
function TLexer.GetCharPositionInLine: Integer;
begin
Result := FInput.CharPositionInLine;
end;
function TLexer.GetCharStream: ICharStream;
begin
Result := FInput;
end;
function TLexer.GetErrorMessage(const E: ERecognitionException;
const TokenNames: TStringArray): String;
var
MTE: EMismatchedTokenException absolute E;
NVAE: ENoViableAltException absolute E;
EEE: EEarlyExitException absolute E;
MNSE: EMismatchedNotSetException absolute E;
MSE: EMismatchedSetException absolute E;
MRE: EMismatchedRangeException absolute E;
begin
if (E is EMismatchedTokenException) then
Result := 'mismatched character ' + GetCharErrorDisplay(E.Character)
+ ' expecting ' + GetCharErrorDisplay(MTE.Expecting)
else
if (E is ENoViableAltException) then
// for development, can add "decision=<<"+nvae.grammarDecisionDescription+">>"
// and "(decision="+nvae.decisionNumber+") and
// "state "+nvae.stateNumber
Result := 'no viable alternative at character ' + GetCharErrorDisplay(NVAE.Character)
else
if (E is EEarlyExitException) then
// for development, can add "(decision="+eee.decisionNumber+")"
Result := 'required (...)+ loop did not match anything at character '
+ GetCharErrorDisplay(EEE.Character)
else
if (E is EMismatchedNotSetException) then
Result := 'mismatched character ' + GetCharErrorDisplay(MNSE.Character)
+ ' expecting set ' + MNSE.Expecting.ToString
else
if (E is EMismatchedSetException) then
Result := 'mismatched character ' + GetCharErrorDisplay(MSE.Character)
+ ' expecting set ' + MSE.Expecting.ToString
else
if (E is EMismatchedRangeException) then
Result := 'mismatched character ' + GetCharErrorDisplay(MRE.Character)
+ ' expecting set ' + GetCharErrorDisplay(MRE.A) + '..'
+ GetCharErrorDisplay(MRE.B)
else
Result := inherited GetErrorMessage(E, TokenNames);
end;
function TLexer.GetInput: IIntStream;
begin
Result := FInput;
end;
function TLexer.GetLine: Integer;
begin
Result := FInput.Line;
end;
function TLexer.GetSourceName: String;
begin
Result := FInput.SourceName;
end;
function TLexer.GetText: String;
begin
if (FState.Text <> '') then
Result := FState.Text
else
Result := FInput.Substring(FState.TokenStartCharIndex, GetCharIndex - 1)
end;
procedure TLexer.Match(const S: String);
var
I: Integer;
MTE: EMismatchedTokenException;
begin
for I := 1 to Length(S) do
begin
if (FInput.LA(1) <> Integer(S[I])) then
begin
if (FState.Backtracking > 0) then
begin
FState.Failed := True;
Exit;
end;
MTE := EMismatchedTokenException.Create(Integer(S[I]), FInput);
Recover(MTE); // don't really recover; just consume in lexer
raise MTE;
end;
FInput.Consume;
FState.Failed := False;
end;
end;
procedure TLexer.Match(const C: Integer);
var
MTE: EMismatchedTokenException;
begin
if (FInput.LA(1) <> C) then
begin
if (FState.Backtracking > 0) then
begin
FState.Failed := True;
Exit;
end;
MTE := EMismatchedTokenException.Create(C, FInput);
Recover(MTE);
raise MTE;
end;
FInput.Consume;
FState.Failed := False;
end;
procedure TLexer.MatchAny;
begin
FInput.Consume;
end;
procedure TLexer.MatchRange(const A, B: Integer);
var
MRE: EMismatchedRangeException;
begin
if (FInput.LA(1) < A) or (FInput.LA(1) > B) then
begin
if (FState.Backtracking > 0) then
begin
FState.Failed := True;
Exit;
end;
MRE := EMismatchedRangeException.Create(A, B, FInput);
Recover(MRE);
raise MRE;
end;
FInput.Consume;
FState.Failed := False;
end;
function TLexer.NextToken: IToken;
begin
while True do
begin
FState.Token := nil;
FState.Channel := TToken.DEFAULT_CHANNEL;
FState.TokenStartCharIndex := FInput.Index;
FState.TokenStartCharPositionInLine := FInput.CharPositionInLine;
FState.TokenStartLine := Finput.Line;
FState.Text := '';
if (FInput.LA(1) = Integer(cscEOF)) then
begin
Result := TToken.EOF_TOKEN;
Exit;
end;
try
DoTokens;
if (FState.Token = nil) then
Emit
else
if (FState.Token = TToken.SKIP_TOKEN) then
Continue;
Exit(FState.Token);
except
on NVA: ENoViableAltException do
begin
ReportError(NVA);
Recover(NVA); // throw out current char and try again
end;
on RE: ERecognitionException do
begin
ReportError(RE);
// Match() routine has already called Recover()
end;
end;
end;
end;
procedure TLexer.Recover(const RE: ERecognitionException);
begin
FInput.Consume;
end;
procedure TLexer.ReportError(const E: ERecognitionException);
begin
DisplayRecognitionError(GetTokenNames, E);
end;
procedure TLexer.Reset;
begin
inherited; // reset all recognizer state variables
// wack Lexer state variables
if Assigned(FInput) then
FInput.Seek(0); // rewind the input
if (FState = nil) then
Exit; // no shared state work to do
FState.Token := nil;
FState.TokenType := TToken.INVALID_TOKEN_TYPE;
FState.Channel := TToken.DEFAULT_CHANNEL;
FState.TokenStartCharIndex := -1;
FState.TokenStartCharPositionInLine := -1;
FState.TokenStartLine := -1;
FState.Text := '';
end;
procedure TLexer.SetCharStream(const Value: ICharStream);
begin
FInput := nil;
Reset;
FInput := Value;
end;
procedure TLexer.SetText(const Value: String);
begin
FState.Text := Value;
end;
procedure TLexer.Skip;
begin
FState.Token := TToken.SKIP_TOKEN;
end;
procedure TLexer.TraceIn(const RuleName: String; const RuleIndex: Integer);
var
InputSymbol: String;
begin
InputSymbol := Char(FInput.LT(1)) + ' line=' + IntToStr(GetLine) + ':'
+ IntToStr(GetCharPositionInLine);
inherited TraceIn(RuleName, RuleIndex, InputSymbol);
end;
procedure TLexer.TraceOut(const RuleName: String; const RuleIndex: Integer);
var
InputSymbol: String;
begin
InputSymbol := Char(FInput.LT(1)) + ' line=' + IntToStr(GetLine) + ':'
+ IntToStr(GetCharPositionInLine);
inherited TraceOut(RuleName, RuleIndex, InputSymbol);
end;
{ TParser }
constructor TParser.Create(const AInput: ITokenStream);
begin
inherited Create; // highlight that we go to base class to set state object
SetTokenStream(AInput);
end;
constructor TParser.Create(const AInput: ITokenStream;
const AState: IRecognizerSharedState);
begin
inherited Create(AState); // share the state object with another parser
SetTokenStream(AInput);
end;
function TParser.GetCurrentInputSymbol(
const Input: IIntStream): IANTLRInterface;
begin
Result := FInput.LT(1)
end;
function TParser.GetInput: IIntStream;
begin
Result := FInput;
end;
function TParser.GetMissingSymbol(const Input: IIntStream;
const E: ERecognitionException; const ExpectedTokenType: Integer;
const Follow: IBitSet): IANTLRInterface;
var
TokenText: String;
T: ICommonToken;
Current: IToken;
begin
if (ExpectedTokenType = TToken.EOF) then
TokenText := '<missing EOF>'
else
TokenText := '<missing ' + GetTokenNames[ExpectedTokenType] + '>';
T := TCommonToken.Create(ExpectedTokenType, TokenText);
Current := FInput.LT(1);
if (Current.TokenType = TToken.EOF) then
Current := FInput.LT(-1);
T.Line := Current.Line;
T.CharPositionInLine := Current.CharPositionInLine;
T.Channel := DEFAULT_TOKEN_CHANNEL;
Result := T;
end;
function TParser.GetSourceName: String;
begin
Result := FInput.SourceName;
end;
function TParser.GetTokenStream: ITokenStream;
begin
Result := FInput;
end;
procedure TParser.Reset;
begin
inherited; // reset all recognizer state variables
if Assigned(FInput) then
FInput.Seek(0); // rewind the input
end;
procedure TParser.SetTokenStream(const Value: ITokenStream);
begin
FInput := nil;
Reset;
FInput := Value;
end;
procedure TParser.TraceIn(const RuleName: String; const RuleIndex: Integer);
begin
inherited TraceIn(RuleName, RuleIndex, FInput.LT(1).ToString);
end;
procedure TParser.TraceOut(const RuleName: String; const RuleIndex: Integer);
begin
inherited TraceOut(RuleName, RuleIndex, FInput.LT(1).ToString);
end;
{ TRuleReturnScope }
function TRuleReturnScope.GetStart: IANTLRInterface;
begin
Result := nil;
end;
function TRuleReturnScope.GetStop: IANTLRInterface;
begin
Result := nil;
end;
function TRuleReturnScope.GetTemplate: IANTLRInterface;
begin
Result := nil;
end;
function TRuleReturnScope.GetTree: IANTLRInterface;
begin
Result := nil;
end;
procedure TRuleReturnScope.SetStart(const Value: IANTLRInterface);
begin
raise EInvalidOperation.Create('Setter has not been defined for this property.');
end;
procedure TRuleReturnScope.SetStop(const Value: IANTLRInterface);
begin
raise EInvalidOperation.Create('Setter has not been defined for this property.');
end;
procedure TRuleReturnScope.SetTree(const Value: IANTLRInterface);
begin
raise EInvalidOperation.Create('Setter has not been defined for this property.');
end;
{ TParserRuleReturnScope }
function TParserRuleReturnScope.GetStart: IANTLRInterface;
begin
Result := FStart;
end;
function TParserRuleReturnScope.GetStop: IANTLRInterface;
begin
Result := FStop;
end;
procedure TParserRuleReturnScope.SetStart(const Value: IANTLRInterface);
begin
FStart := Value as IToken;
end;
procedure TParserRuleReturnScope.SetStop(const Value: IANTLRInterface);
begin
FStop := Value as IToken;
end;
{ TTokenRewriteStream }
procedure TTokenRewriteStream.Delete(const Start, Stop: IToken);
begin
Delete(DEFAULT_PROGRAM_NAME, Start, Stop);
end;
procedure TTokenRewriteStream.Delete(const IndexT: IToken);
begin
Delete(DEFAULT_PROGRAM_NAME, IndexT, IndexT);
end;
constructor TTokenRewriteStream.Create;
begin
inherited;
Init;
end;
constructor TTokenRewriteStream.Create(const ATokenSource: ITokenSource);
begin
inherited Create(ATokenSource);
Init;
end;
constructor TTokenRewriteStream.Create(const ALexer: ILexer);
begin
Create(ALexer as ITokenSource);
end;
constructor TTokenRewriteStream.Create(const ALexer: ILexer;
const AChannel: Integer);
begin
Create(ALexer as ITokenSource, AChannel);
end;
function TTokenRewriteStream.CatOpText(const A, B: IANTLRInterface): IANTLRInterface;
var
X, Y: String;
begin
if Assigned(A) then
X := A.ToString
else
X := '';
if Assigned(B) then
Y := B.ToString
else
Y := '';
Result := TANTLRString.Create(X + Y);
end;
constructor TTokenRewriteStream.Create(const ATokenSource: ITokenSource;
const AChannel: Integer);
begin
inherited Create(ATokenSource, AChannel);
Init;
end;
procedure TTokenRewriteStream.Delete(const ProgramName: String; const Start,
Stop: IToken);
begin
Replace(ProgramName, Start, Stop, nil);
end;
procedure TTokenRewriteStream.Delete(const ProgramName: String; const Start,
Stop: Integer);
begin
Replace(ProgramName, Start, Stop, nil);
end;
procedure TTokenRewriteStream.Delete(const Start, Stop: Integer);
begin
Delete(DEFAULT_PROGRAM_NAME, Start, Stop);
end;
procedure TTokenRewriteStream.Delete(const Index: Integer);
begin
Delete(DEFAULT_PROGRAM_NAME, Index, Index);
end;
procedure TTokenRewriteStream.DeleteProgram(const ProgramName: String);
begin
Rollback(ProgramName, MIN_TOKEN_INDEX);
end;
procedure TTokenRewriteStream.DeleteProgram;
begin
DeleteProgram(DEFAULT_PROGRAM_NAME);
end;
function TTokenRewriteStream.GetLastRewriteTokenIndex: Integer;
begin
Result := GetLastRewriteTokenIndex(DEFAULT_PROGRAM_NAME);
end;
function TTokenRewriteStream.GetKindOfOps(
const Rewrites: IList<IRewriteOperation>;
const Kind: TGUID): IList<IRewriteOperation>;
begin
Result := GetKindOfOps(Rewrites, Kind, Rewrites.Count);
end;
function TTokenRewriteStream.GetKindOfOps(
const Rewrites: IList<IRewriteOperation>; const Kind: TGUID;
const Before: Integer): IList<IRewriteOperation>;
var
I: Integer;
Op: IRewriteOperation;
Obj: IInterface;
begin
Result := TList<IRewriteOperation>.Create;
I := 0;
while (I < Before) and (I < Rewrites.Count) do
begin
Op := Rewrites[I];
if Assigned(Op) and (Op.QueryInterface(Kind, Obj) = 0) then
Result.Add(Op);
Inc(I);
end;
end;
function TTokenRewriteStream.GetLastRewriteTokenIndex(
const ProgramName: String): Integer;
begin
if (not FLastRewriteTokenIndexes.TryGetValue(ProgramName, Result)) then
Result := -1;
end;
function TTokenRewriteStream.GetProgram(
const Name: String): IList<IRewriteOperation>;
var
InstructionStream: IList<IRewriteOperation>;
begin
InstructionStream := FPrograms[Name];
if (InstructionStream = nil) then
InstructionStream := InitializeProgram(Name);
Result := InstructionStream;
end;
procedure TTokenRewriteStream.InsertAfter(const ProgramName: String;
const T: IToken; const Text: IANTLRInterface);
begin
InsertAfter(ProgramName, T.TokenIndex, Text);
end;
procedure TTokenRewriteStream.Init;
var
List: IList<IRewriteOperation>;
begin
FPrograms := TDictionary<String, IList<IRewriteOperation>>.Create;
List := TList<IRewriteOperation>.Create;
List.Capacity := PROGRAM_INIT_SIZE;
FPrograms.Add(DEFAULT_PROGRAM_NAME, List);
FLastRewriteTokenIndexes := TDictionary<String, Integer>.Create;
end;
function TTokenRewriteStream.InitializeProgram(
const Name: String): IList<IRewriteOperation>;
begin
Result := TList<IRewriteOperation>.Create;
Result.Capacity := PROGRAM_INIT_SIZE;
FPrograms[Name] := Result;
end;
procedure TTokenRewriteStream.InsertAfter(const ProgramName: String;
const Index: Integer; const Text: IANTLRInterface);
begin
// to insert after, just insert before next index (even if past end)
InsertBefore(ProgramName, Index + 1, Text);
end;
procedure TTokenRewriteStream.InsertAfter(const T: IToken;
const Text: IANTLRInterface);
begin
InsertAfter(DEFAULT_PROGRAM_NAME, T, Text);
end;
procedure TTokenRewriteStream.InsertAfter(const Index: Integer;
const Text: IANTLRInterface);
begin
InsertAfter(DEFAULT_PROGRAM_NAME, Index, Text);
end;
procedure TTokenRewriteStream.InsertBefore(const Index: Integer;
const Text: IANTLRInterface);
begin
InsertBefore(DEFAULT_PROGRAM_NAME, Index, Text);
end;
procedure TTokenRewriteStream.InsertBefore(const ProgramName: String;
const T: IToken; const Text: IANTLRInterface);
begin
InsertBefore(ProgramName, T.TokenIndex, Text);
end;
procedure TTokenRewriteStream.InsertBefore(const ProgramName: String;
const Index: Integer; const Text: IANTLRInterface);
var
Op: IRewriteOperation;
begin
Op := TInsertBeforeOp.Create(Index, Text, Self);
GetProgram(ProgramName).Add(Op);
end;
procedure TTokenRewriteStream.InsertBefore(const T: IToken;
const Text: IANTLRInterface);
begin
InsertBefore(DEFAULT_PROGRAM_NAME, T, Text);
end;
procedure TTokenRewriteStream.Replace(const Start, Stop: IToken;
const Text: IANTLRInterface);
begin
Replace(DEFAULT_PROGRAM_NAME, Stop, Stop, Text);
end;
procedure TTokenRewriteStream.Replace(const IndexT: IToken;
const Text: IANTLRInterface);
begin
Replace(DEFAULT_PROGRAM_NAME, IndexT, IndexT, Text);
end;
procedure TTokenRewriteStream.Replace(const ProgramName: String; const Start,
Stop: Integer; const Text: IANTLRInterface);
var
Op: IRewriteOperation;
Rewrites: IList<IRewriteOperation>;
begin
if (Start > Stop) or (Start < 0) or (Stop < 0) or (Stop >= GetTokens.Count) then
raise EArgumentOutOfRangeException.Create('replace: range invalid: '
+ IntToStr(Start) + '..' + IntToStr(Stop) + '(size='
+ IntToStr(GetTokens.Count) + ')');
Op := TReplaceOp.Create(Start, Stop, Text, Self);
Rewrites := GetProgram(ProgramName);
Op.InstructionIndex := Rewrites.Count;
Rewrites.Add(Op);
end;
function TTokenRewriteStream.ReduceToSingleOperationPerIndex(
const Rewrites: IList<IRewriteOperation>): IDictionary<Integer, IRewriteOperation>;
var
I, J: Integer;
Op: IRewriteOperation;
ROp, PrevROp: IReplaceOp;
IOp, PrevIOp: IInsertBeforeOp;
Inserts, PrevInserts, PrevReplaces: IList<IRewriteOperation>;
Disjoint, Same: Boolean;
begin
// WALK REPLACES
for I := 0 to Rewrites.Count - 1 do
begin
Op := Rewrites[I];
if (Op = nil) then
Continue;
if (not Supports(Op, IReplaceOp, ROp)) then
Continue;
// Wipe prior inserts within range
Inserts := GetKindOfOps(Rewrites, IInsertBeforeOp, I);
for J := 0 to Inserts.Count - 1 do
begin
IOp := Inserts[J] as IInsertBeforeOp;
if (IOp.Index >= ROp.Index) and (IOp.Index <= ROp.LastIndex) then
begin
// delete insert as it's a no-op.
Rewrites[IOp.InstructionIndex] := nil;
end;
end;
// Drop any prior replaces contained within
PrevReplaces := GetKindOfOps(Rewrites, IReplaceOp, I);
for J := 0 to PrevReplaces.Count - 1 do
begin
PrevROp := PrevReplaces[J] as IReplaceOp;
if (PrevROp.Index >= ROp.Index) and (PrevROp.LastIndex <= ROp.LastIndex) then
begin
// delete replace as it's a no-op.
Rewrites[PrevROp.InstructionIndex] := nil;
Continue;
end;
// throw exception unless disjoint or identical
Disjoint := (PrevROp.LastIndex < ROp.Index) or (PrevROp.Index > ROp.LastIndex);
Same := (PrevROp.Index = ROp.Index) and (PrevROp.LastIndex = ROp.LastIndex);
if (not Disjoint) and (not Same) then
raise EArgumentOutOfRangeException.Create('replace of boundaries of '
+ ROp.ToString + ' overlap with previous ' + PrevROp.ToString);
end;
end;
// WALK INSERTS
for I := 0 to Rewrites.Count - 1 do
begin
Op := Rewrites[I];
if (Op = nil) then
Continue;
if (not Supports(Op, IInsertBeforeOp, IOp)) then
Continue;
// combine current insert with prior if any at same index
PrevInserts := GetKindOfOps(Rewrites, IInsertBeforeOp, I);
for J := 0 to PrevInserts.Count - 1 do
begin
PrevIOp := PrevInserts[J] as IInsertBeforeOp;
if (PrevIOp.Index = IOp.Index) then
begin
// combine objects
// convert to strings...we're in process of toString'ing
// whole token buffer so no lazy eval issue with any templates
IOp.Text := CatOpText(IOp.Text, PrevIOp.Text);
// delete redundant prior insert
Rewrites[PrevIOp.InstructionIndex] := nil;
end;
end;
// look for replaces where iop.index is in range; error
PrevReplaces := GetKindOfOps(Rewrites, IReplaceOp, I);
for J := 0 to PrevReplaces.Count - 1 do
begin
Rop := PrevReplaces[J] as IReplaceOp;
if (IOp.Index = ROp.Index) then
begin
ROp.Text := CatOpText(IOp.Text, ROp.Text);
Rewrites[I] := nil; // delete current insert
Continue;
end;
if (IOp.Index >= ROp.Index) and (IOp.Index <= ROp.LastIndex) then
raise EArgumentOutOfRangeException.Create('insert op '
+ IOp.ToString + ' within boundaries of previous ' + ROp.ToString);
end;
end;
Result := TDictionary<Integer, IRewriteOperation>.Create;
for Op in Rewrites do
begin
if (Op = nil) then
Continue; // ignore deleted ops
if (Result.ContainsKey(Op.Index)) then
raise Exception.Create('should only be one op per index');
Result.Add(Op.Index, Op);
end;
end;
procedure TTokenRewriteStream.Replace(const ProgramName: String; const Start,
Stop: IToken; const Text: IANTLRInterface);
begin
Replace(ProgramName, Start.TokenIndex, Stop.TokenIndex, Text);
end;
procedure TTokenRewriteStream.Replace(const Index: Integer;
const Text: IANTLRInterface);
begin
Replace(DEFAULT_PROGRAM_NAME, Index, Index, Text);
end;
procedure TTokenRewriteStream.Replace(const Start, Stop: Integer;
const Text: IANTLRInterface);
begin
Replace(DEFAULT_PROGRAM_NAME, Start, Stop, Text);
end;
procedure TTokenRewriteStream.Rollback(const InstructionIndex: Integer);
begin
Rollback(DEFAULT_PROGRAM_NAME, InstructionIndex);
end;
procedure TTokenRewriteStream.Rollback(const ProgramName: String;
const InstructionIndex: Integer);
var
InstructionStream: IList<IRewriteOperation>;
begin
InstructionStream := FPrograms[ProgramName];
if Assigned(InstructionStream) then
FPrograms[ProgramName] := InstructionStream.GetRange(MIN_TOKEN_INDEX,
InstructionIndex - MIN_TOKEN_INDEX);
end;
procedure TTokenRewriteStream.SetLastRewriteTokenIndex(
const ProgramName: String; const I: Integer);
begin
FLastRewriteTokenIndexes[ProgramName] := I;
end;
function TTokenRewriteStream.ToDebugString: String;
begin
Result := ToDebugString(MIN_TOKEN_INDEX, Size - 1);
end;
function TTokenRewriteStream.ToDebugString(const Start, Stop: Integer): String;
var
Buf: TStringBuilder;
I: Integer;
begin
Buf := TStringBuilder.Create;
try
if (Start >= MIN_TOKEN_INDEX) then
for I := Start to Min(Stop,GetTokens.Count - 1) do
Buf.Append(Get(I).ToString);
finally
Buf.Free;
end;
end;
function TTokenRewriteStream.ToOriginalString: String;
begin
Result := ToOriginalString(MIN_TOKEN_INDEX, Size - 1);
end;
function TTokenRewriteStream.ToOriginalString(const Start,
Stop: Integer): String;
var
Buf: TStringBuilder;
I: Integer;
begin
Buf := TStringBuilder.Create;
try
if (Start >= MIN_TOKEN_INDEX) then
for I := Start to Min(Stop, GetTokens.Count - 1) do
Buf.Append(Get(I).Text);
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
function TTokenRewriteStream.ToString: String;
begin
Result := ToString(MIN_TOKEN_INDEX, Size - 1);
end;
function TTokenRewriteStream.ToString(const ProgramName: String): String;
begin
Result := ToString(ProgramName, MIN_TOKEN_INDEX, Size - 1);
end;
function TTokenRewriteStream.ToString(const ProgramName: String; const Start,
Stop: Integer): String;
var
Rewrites: IList<IRewriteOperation>;
I, StartIndex, StopIndex: Integer;
IndexToOp: IDictionary<Integer, IRewriteOperation>;
Buf: TStringBuilder;
Tokens: IList<IToken>;
T: IToken;
Op: IRewriteOperation;
Pair: TPair<Integer, IRewriteOperation>;
begin
Rewrites := FPrograms[ProgramName];
Tokens := GetTokens;
// ensure start/end are in range
StopIndex := Min(Stop,Tokens.Count - 1);
StartIndex := Max(Start,0);
if (Rewrites = nil) or (Rewrites.Count = 0) then
begin
// no instructions to execute
Result := ToOriginalString(StartIndex, StopIndex);
Exit;
end;
Buf := TStringBuilder.Create;
try
// First, optimize instruction stream
IndexToOp := ReduceToSingleOperationPerIndex(Rewrites);
// Walk buffer, executing instructions and emitting tokens
I := StartIndex;
while (I <= StopIndex) and (I < Tokens.Count) do
begin
if (not IndexToOp.TryGetValue(I, Op)) then
Op := nil;
IndexToOp.Remove(I); // remove so any left have index size-1
T := Tokens[I];
if (Op = nil) then
begin
// no operation at that index, just dump token
Buf.Append(T.Text);
Inc(I); // move to next token
end
else
I := Op.Execute(Buf); // execute operation and skip
end;
// include stuff after end if it's last index in buffer
// So, if they did an insertAfter(lastValidIndex, "foo"), include
// foo if end==lastValidIndex.
if (StopIndex = Tokens.Count - 1) then
begin
// Scan any remaining operations after last token
// should be included (they will be inserts).
for Pair in IndexToOp do
begin
if (Pair.Value.Index >= Tokens.Count - 1) then
Buf.Append(Pair.Value.Text.ToString);
end;
end;
Result := Buf.ToString;
finally
Buf.Free;
end;
end;
function TTokenRewriteStream.ToString(const Start, Stop: Integer): String;
begin
Result := ToString(DEFAULT_PROGRAM_NAME, Start, Stop);
end;
procedure TTokenRewriteStream.InsertBefore(const Index: Integer;
const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
InsertBefore(Index, S);
end;
procedure TTokenRewriteStream.InsertBefore(const T: IToken; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
InsertBefore(T, S);
end;
procedure TTokenRewriteStream.InsertBefore(const ProgramName: String;
const Index: Integer; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
InsertBefore(ProgramName, Index, S);
end;
procedure TTokenRewriteStream.InsertBefore(const ProgramName: String;
const T: IToken; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
InsertBefore(ProgramName, T, S);
end;
procedure TTokenRewriteStream.InsertAfter(const Index: Integer;
const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
InsertAfter(Index,S);
end;
procedure TTokenRewriteStream.InsertAfter(const T: IToken; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
InsertAfter(T,S);
end;
procedure TTokenRewriteStream.InsertAfter(const ProgramName: String;
const Index: Integer; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
InsertAfter(ProgramName,Index,S);
end;
procedure TTokenRewriteStream.InsertAfter(const ProgramName: String;
const T: IToken; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
InsertAfter(ProgramName,T,S);
end;
procedure TTokenRewriteStream.Replace(const IndexT: IToken; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
Replace(IndexT, S);
end;
procedure TTokenRewriteStream.Replace(const Start, Stop: Integer;
const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
Replace(Start, Stop, S);
end;
procedure TTokenRewriteStream.Replace(const Index: Integer; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
Replace(Index, S);
end;
procedure TTokenRewriteStream.Replace(const ProgramName: String; const Start,
Stop: IToken; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
Replace(ProgramName, Start, Stop, S);
end;
procedure TTokenRewriteStream.Replace(const ProgramName: String; const Start,
Stop: Integer; const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
Replace(ProgramName, Start, Stop, S);
end;
procedure TTokenRewriteStream.Replace(const Start, Stop: IToken;
const Text: String);
var
S: IANTLRString;
begin
S := TANTLRString.Create(Text);
Replace(Start, Stop, S);
end;
{ TTokenRewriteStream.TRewriteOperation }
constructor TTokenRewriteStream.TRewriteOperation.Create(const AIndex: Integer;
const AText: IANTLRInterface; const AParent: ITokenRewriteStream);
begin
inherited Create;
FIndex := AIndex;
FText := AText;
FParent := Pointer(AParent);
end;
function TTokenRewriteStream.TRewriteOperation.Execute(
const Buf: TStringBuilder): Integer;
begin
Result := FIndex;
end;
function TTokenRewriteStream.TRewriteOperation.GetIndex: Integer;
begin
Result := FIndex;
end;
function TTokenRewriteStream.TRewriteOperation.GetInstructionIndex: Integer;
begin
Result := FInstructionIndex;
end;
function TTokenRewriteStream.TRewriteOperation.GetParent: ITokenRewriteStream;
begin
Result := ITokenRewriteStream(FParent);
end;
function TTokenRewriteStream.TRewriteOperation.GetText: IANTLRInterface;
begin
Result := FText;
end;
procedure TTokenRewriteStream.TRewriteOperation.SetIndex(const Value: Integer);
begin
FIndex := Value;
end;
procedure TTokenRewriteStream.TRewriteOperation.SetInstructionIndex(
const Value: Integer);
begin
FInstructionIndex := Value;
end;
procedure TTokenRewriteStream.TRewriteOperation.SetParent(
const Value: ITokenRewriteStream);
begin
FParent := Pointer(Value);
end;
procedure TTokenRewriteStream.TRewriteOperation.SetText(
const Value: IANTLRInterface);
begin
FText := Value;
end;
function TTokenRewriteStream.TRewriteOperation.ToString: String;
var
OpName: String;
DollarIndex: Integer;
begin
OpName := ClassName;
DollarIndex := Pos('$',OpName) - 1; // Delphi strings are 1-based
if (DollarIndex >= 0) then
OpName := Copy(OpName,DollarIndex + 1,Length(OpName) - (DollarIndex + 1));
Result := '<' + OpName + '@' + IntToStr(FIndex) + ':"' + FText.ToString + '">';
end;
{ TTokenRewriteStream.TRewriteOpComparer<T> }
function TTokenRewriteStream.TRewriteOpComparer<T>.Compare(const Left,
Right: T): Integer;
begin
if (Left.GetIndex < Right.GetIndex) then
Result := -1
else
if (Left.GetIndex > Right.GetIndex) then
Result := 1
else
Result := 0;
end;
{ TTokenRewriteStream.TInsertBeforeOp }
function TTokenRewriteStream.TInsertBeforeOp.Execute(
const Buf: TStringBuilder): Integer;
begin
Buf.Append(Text.ToString);
Buf.Append(Parent.Get(Index).Text);
Result := Index + 1;
end;
{ TTokenRewriteStream.TReplaceOp }
constructor TTokenRewriteStream.TReplaceOp.Create(const AStart, AStop: Integer;
const AText: IANTLRInterface; const AParent: ITokenRewriteStream);
begin
inherited Create(AStart, AText, AParent);
FLastIndex := AStop;
end;
function TTokenRewriteStream.TReplaceOp.Execute(
const Buf: TStringBuilder): Integer;
begin
if (Text <> nil) then
Buf.Append(Text.ToString);
Result := FLastIndex + 1;
end;
function TTokenRewriteStream.TReplaceOp.GetLastIndex: Integer;
begin
Result := FLastIndex;
end;
procedure TTokenRewriteStream.TReplaceOp.SetLastIndex(const Value: Integer);
begin
FLastIndex := Value;
end;
function TTokenRewriteStream.TReplaceOp.ToString: String;
begin
Result := '<ReplaceOp@' + IntToStr(Index) + '..' + IntToStr(FLastIndex)
+ ':"' + Text.ToString + '">';
end;
{ TTokenRewriteStream.TDeleteOp }
function TTokenRewriteStream.TDeleteOp.ToString: String;
begin
Result := '<DeleteOp@' + IntToStr(Index) + '..' + IntToStr(FLastIndex) + '>';
end;
{ Utilities }
var
EmptyToken: IToken = nil;
EmptyRuleReturnScope: IRuleReturnScope = nil;
function Def(const X: IToken): IToken; overload;
begin
if Assigned(X) then
Result := X
else
begin
if (EmptyToken = nil) then
EmptyToken := TCommonToken.Create;
Result := EmptyToken;
end;
end;
function Def(const X: IRuleReturnScope): IRuleReturnScope;
begin
if Assigned(X) then
Result := X
else
begin
if (EmptyRuleReturnScope = nil) then
EmptyRuleReturnScope := TRuleReturnScope.Create;
Result := EmptyRuleReturnScope;
end;
end;
initialization
TToken.Initialize;
end.
|
{
ON_HIGHLIGHT이 설정된 경우만 하이라이트(그림자) 효과가 발생함
- $DEFINE ON_HIGHLIGHT
}
unit ThItemHighlighter;
interface
uses
System.Types, System.SysUtils, FMX.Types, System.UITypes, FMX.Controls,
FMX.Graphics, ThTypes;
type
TThItemShadowHighlighter = class(TInterfacedObject, IItemHighlighter)
private
FParent: IItemHighlightObject;
FHighlight: Boolean;
FHighlightColor: TAlphaColor;
FHighlightSize: Single;
procedure SetHighlightColor(const Value: TAlphaColor);
procedure SetHighlightSize(const Value: Single);
protected
function GetHighlightRect: TRectF;
public
constructor Create(AParent: IItemHighlightObject);
procedure DrawHighlight;
property HighlightColor: TAlphaColor read FHighlightColor write SetHighlightColor;
property HighlightSize: Single read FHighlightSize write SetHighlightSize;
end;
// Not used
TThItemRectBorderHighlighter = class(TInterfacedObject, IItemHighlighter)
private
FParent: IItemHighlightObject;
FHighlight: Boolean;
FHighlightColor: TAlphaColor;
FHighlightSize: Single;
procedure SetHighlightColor(const Value: TAlphaColor);
procedure SetHighlightSize(const Value: Single);
protected
function GetHighlightRect: TRectF;
public
constructor Create(AParent: IItemHighlightObject);
procedure DrawHighlight;
property HighlightColor: TAlphaColor read FHighlightColor write SetHighlightColor;
property HighlightSize: Single read FHighlightSize write SetHighlightSize;
end;
implementation
uses
System.UIConsts, ThConsts;
{ TThItemShadowHighligher }
constructor TThItemShadowHighlighter.Create(AParent: IItemHighlightObject);
begin
FParent := AParent;
FHighlight := False;
end;
procedure TThItemShadowHighlighter.DrawHighlight;
begin
FParent.PaintItem(GetHighlightRect, FHighlightColor);
end;
function TThItemShadowHighlighter.GetHighlightRect: TRectF;
var
ViewportScale: Single;
ScaledHighlightSize: Single;
begin
Result := TControl(FParent).ClipRect;
ViewportScale := TControl(FParent).AbsoluteScale.X;
// Item의 스케일에서 Canvas의 Scale로 처리 필요
// - Item도 스케일이 변경될 수 있음
ScaledHighlightSize := HighlightSize / ViewportScale;
Result.Offset(ScaledHighlightSize, ScaledHighlightSize);
end;
procedure TThItemShadowHighlighter.SetHighlightColor(const Value: TAlphaColor);
begin
if FHighlightColor = Value then
Exit;
FHighlightColor := Value;
TControl(FParent).Repaint;
end;
procedure TThItemShadowHighlighter.SetHighlightSize(const Value: Single);
begin
if FHighlightSize = Value then
Exit;
FHighlightSize := Value;
TControl(FParent).Repaint;
end;
{ TThItemBorderHighlighter }
constructor TThItemRectBorderHighlighter.Create(AParent: IItemHighlightObject);
begin
FParent := AParent;
FHighlight := False;
end;
procedure TThItemRectBorderHighlighter.DrawHighlight;
var
State: TCanvasSaveState;
begin
with TControl(FParent) do
begin
State := Canvas.SaveState;
try
Canvas.Stroke.Color := FHighlightColor;
Canvas.Stroke.Thickness := FHighlightSize;
Canvas.Stroke.Dash := TStrokeDash.Dash;
Canvas.DrawRect(ClipRect, 0, 0, AllCorners, 1);
finally
Canvas.RestoreState(State);
end;
end;
end;
function TThItemRectBorderHighlighter.GetHighlightRect: TRectF;
var
ViewportScale: Single;
ScaledHighlightSize: Single;
begin
Result := TControl(FParent).ClipRect;
ViewportScale := TControl(FParent).AbsoluteScale.X;
// Item의 스케일에서 Canvas의 Scale로 처리 필요
// - Item도 스케일이 변경될 수 있음
ScaledHighlightSize := HighlightSize / ViewportScale;
Result.Inflate(ScaledHighlightSize, ScaledHighlightSize);
end;
procedure TThItemRectBorderHighlighter.SetHighlightColor(const Value: TAlphaColor);
begin
if FHighlightColor = Value then
Exit;
FHighlightColor := Value;
TControl(FParent).Repaint;
end;
procedure TThItemRectBorderHighlighter.SetHighlightSize(const Value: Single);
begin
if FHighlightSize = Value then
Exit;
FHighlightSize := Value;
TControl(FParent).Repaint;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clTranslator;
interface
uses
Classes;
type
TclXLATTable = record
Name: string[20];
Table: array [0..255] of Byte;
ReverseTable: array [0..255] of Byte;
end;
TclCharSetTranslator = class
private
class function GetXLATByID(const ATableID: string): TclXLATTable;
class function ToUtf8(Source: PWideChar; SourceLength: Integer;
Dest: PChar; DestLength: Integer): Integer;
class function FromUtf8(Source: PChar; SourceLength: Integer;
Dest: PWideChar; DestLength: Integer): Integer;
public
class function TranslateToUtf8(const ASource: WideString): string;
class function TranslateFromUtf8(const ASource: string): WideString;
class function TranslateTo(const ACharSet, ASource: string): string; overload;
class function TranslateFrom(const ACharSet, ASource: string): string; overload;
class procedure TranslateTo(const ACharSet: string; ASource, ADestination: TStream); overload;
class procedure TranslateFrom(const ACharSet: string; ASource, ADestination: TStream); overload;
class procedure GetSupportedCharSets(ACharSets: TStrings);
end;
implementation
uses
SysUtils, Windows;
const
CharSetTables: array [0..11] of TclXLATTable = (
(
Name: 'ISO-8859-1';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff)
),
(
Name: 'ISO-8859-2';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a5,$a2,$a3,$a4,$a5,$8c,$a7
,$a8,$a9,$aa,$ab,$8f,$ad,$ae,$af,$b0,$b9,$b2,$b3,$b4,$b5,$9c,$b7,$b8,$b9,$ba,$bb,$9f,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$a6,$8d,$8e,$ac
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$b6,$9d,$9e,$bc,$a0,$a1,$a2,$a3,$a4,$a1,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b1,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff)
),
(
Name: 'Windows-1250';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff)
),
(
Name: 'ibm866';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14//21
,$15,$16,$17,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29//42
,$2a,$2b,$2c,$2d,$2e,$2f,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e//63
,$3f,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53//84
,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f,$60,$61,$62,$63,$64,$65,$66,$67,$68//105
,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77,$78,$79,$7a,$7b,$7c,$7d//126
,$7e,$7f,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2//147
,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7//168
,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc//189
,$bd,$be,$bf,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1//210
,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$f0,$f1,$f2,$f3,$f4,$f5,$f6//231
,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff,$a8,$a3,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb//252
,$fc,$fd,$fe,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14//21
,$15,$16,$17,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29//42
,$2a,$2b,$2c,$2d,$2e,$2f,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e//63
,$3f,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53//84
,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f,$60,$61,$62,$63,$64,$65,$66,$67,$68//105
,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77,$78,$79,$7a,$7b,$7c,$7d//126
,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f,$90,$91,$92//147
,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$f1,$a4,$a5,$a6,$a7//168
,$f0,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$f0,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc//189
,$bd,$be,$bf,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f,$90,$91//210
,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6//231
,$a7,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb//252
,$ec,$ed,$ee,$ef)
),
(
Name: 'ISO-8859-5';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7
,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf
,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7
,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$90,$91,$92,$93,$94,$95,$96,$97
,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af
,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7
,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df
,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef)
),
(
Name: 'koi8-r';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$b8,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$a8,$b4,$b5,$b6,$b7,$a3,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$fe,$e0,$e1,$f6,$e4,$e5,$f4,$e3,$f5,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$ff,$f0,$f1,$f2,$f3,$e6,$e2
,$fc,$fb,$e7,$f8,$fd,$f9,$f7,$fa,$de,$c0,$c1,$d6,$c4,$c5,$d4,$c3,$d5,$c8,$c9,$ca,$cb,$cc,$cd,$ce
,$cf,$df,$d0,$d1,$d2,$d3,$c6,$c2,$dc,$db,$c7,$d8,$dd,$d9,$d7,$da);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$b8,$a4,$a5,$a6,$a7
,$b3,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$a3,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$e1,$e2,$f7,$e7,$e4,$e5,$f6,$fa,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f2,$f3,$f4,$f5,$e6,$e8,$e3,$fe
,$fb,$fd,$ff,$f9,$f8,$fc,$e0,$f1,$c1,$c2,$d7,$c7,$c4,$c5,$d6,$da,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0
,$d2,$d3,$d4,$d5,$c6,$c8,$c3,$de,$db,$dd,$df,$d9,$d8,$dc,$c0,$d1)
),
(
Name: 'koi8-u';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$b8,$ba,$a5,$b3,$bf
,$a8,$a9,$aa,$ab,$ac,$b4,$ae,$af,$b0,$b1,$b2,$a8,$aa,$b5,$b2,$af,$b8,$b9,$ba,$bb,$bc,$a5,$be,$bf
,$fe,$e0,$e1,$f6,$e4,$e5,$f4,$e3,$f5,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$ff,$f0,$f1,$f2,$f3,$e6,$e2
,$fc,$fb,$e7,$f8,$fd,$f9,$f7,$fa,$de,$c0,$c1,$d6,$c4,$c5,$d4,$c3,$d5,$c8,$c9,$ca,$cb,$cc,$cd,$ce
,$cf,$df,$d0,$d1,$d2,$d3,$c6,$c2,$dc,$db,$c7,$d8,$dd,$d9,$d7,$da);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$bd,$a6,$a7
,$b3,$a9,$b4,$ab,$ac,$ad,$ae,$b7,$b0,$b1,$b6,$a6,$ad,$b5,$b6,$b7,$a3,$b9,$a4,$bb,$bc,$bd,$be,$a7
,$e1,$e2,$f7,$e7,$e4,$e5,$f6,$fa,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f2,$f3,$f4,$f5,$e6,$e8,$e3,$fe
,$fb,$fd,$ff,$f9,$f8,$fc,$e0,$f1,$c1,$c2,$d7,$c7,$c4,$c5,$d6,$da,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0
,$d2,$d3,$d4,$d5,$c6,$c8,$c3,$de,$db,$dd,$df,$d9,$d8,$dc,$c0,$d1)
),
(
Name: 'KOI8-WIN';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$da,$9b,$9c,$9d,$9e,$9f,$a0,$e7,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$d7,$de,$c0,$c6,$c4,$c5,$d2,$d6,$d3,$d5,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$d1,$cf,$df,$d0,$d1,$d4,$c1
,$dd,$d8,$c3,$dc,$d9,$db,$c2,$c7,$f7,$fe,$e0,$e6,$e4,$e5,$f2,$f6,$f3,$f5,$e8,$e9,$ea,$eb,$ec,$ed
,$ee,$fa,$ef,$ff,$f0,$f1,$f4,$e1,$fd,$f8,$e3,$fc,$f9,$fb,$e2,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c2,$d7,$de,$da,$c4,$c5,$c3,$df,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d2,$d4,$d5,$c6,$c8,$d6,$c9,$c7,$c0
,$d9,$dc,$9a,$dd,$db,$d8,$c1,$d3,$e2,$f7,$fe,$fa,$e4,$e5,$e3,$a1,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f2
,$f4,$f5,$e6,$e8,$f6,$e9,$e7,$e0,$f9,$fc,$f1,$fd,$fb,$f8,$e1,$f3)
),
(
Name: 'WIN-KOI8';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$ff,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$e1,$e2,$f7,$e7,$e4,$e5,$f6,$fa,$c8,$ea,$eb,$ec,$ed,$ee,$ef,$f0,$f2,$f3,$f4,$f5,$e6,$e8,$e3,$fe
,$fb,$fd,$da,$f9,$f8,$fc,$e0,$f1,$c1,$c2,$d7,$c7,$c4,$c5,$d6,$ff,$e8,$ca,$cb,$cc,$cd,$ce,$cf,$d0
,$d2,$d3,$d4,$d5,$c6,$c8,$c3,$de,$db,$dd,$df,$d9,$d8,$dc,$c0,$d1);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17 //23
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f//47
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47//71
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f//95
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77//119
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f//143
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7//167
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf//191
,$fe,$e0,$e1,$f6,$e4,$e5,$f4,$e3,$f5,$c9,$e9,$ea,$eb,$ec,$ed,$ee,$ef,$ff,$f0,$f1,$f2,$f3,$e6,$e2//215
,$fc,$fb,$da,$f8,$fd,$f9,$f7,$fa,$de,$c0,$c1,$d6,$c4,$c5,$d4,$c3,$d5,$e9,$c9,$ca,$cb,$cc,$cd,$ce//239
,$cf,$df,$d0,$d1,$d2,$d3,$c6,$c2,$dc,$db,$c7,$d8,$dd,$d9,$d7,$e7)
),
(
Name: 'Windows-1251';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff)
),
(
Name: 'x-mac-cyrillic';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf
,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$a8,$b8,$ff,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$dd,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$de,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f,$90,$91,$92,$93,$94,$95,$96,$97
,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$df)
),
(
Name: 'Latin1';
Table:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff);
ReverseTable:
($00,$01,$02,$03,$04,$05,$06,$07,$08,$09,$0a,$0b,$0c,$0d,$0e,$0f,$10,$11,$12,$13,$14,$15,$16,$17
,$18,$19,$1a,$1b,$1c,$1d,$1e,$1f,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$2a,$2b,$2c,$2d,$2e,$2f
,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$3a,$3b,$3c,$3d,$3e,$3f,$40,$41,$42,$43,$44,$45,$46,$47
,$48,$49,$4a,$4b,$4c,$4d,$4e,$4f,$50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5a,$5b,$5c,$5d,$5e,$5f
,$60,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6a,$6b,$6c,$6d,$6e,$6f,$70,$71,$72,$73,$74,$75,$76,$77
,$78,$79,$7a,$7b,$7c,$7d,$7e,$7f,$80,$81,$82,$83,$84,$85,$86,$87,$88,$89,$8a,$8b,$8c,$8d,$8e,$8f
,$90,$91,$92,$93,$94,$95,$96,$97,$98,$99,$9a,$9b,$9c,$9d,$9e,$9f,$a0,$a1,$a2,$a3,$a4,$a5,$a6,$a7
,$a8,$a9,$aa,$ab,$ac,$ad,$ae,$af,$b0,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8,$b9,$ba,$bb,$bc,$bd,$be,$bf
,$c0,$c1,$c2,$c3,$c4,$c5,$c6,$c7,$c8,$c9,$ca,$cb,$cc,$cd,$ce,$cf,$d0,$d1,$d2,$d3,$d4,$d5,$d6,$d7
,$d8,$d9,$da,$db,$dc,$dd,$de,$df,$e0,$e1,$e2,$e3,$e4,$e5,$e6,$e7,$e8,$e9,$ea,$eb,$ec,$ed,$ee,$ef
,$f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7,$f8,$f9,$fa,$fb,$fc,$fd,$fe,$ff)
)
);
{ TclCharSetTranslator }
class procedure TclCharSetTranslator.GetSupportedCharSets(ACharSets: TStrings);
var
i: Integer;
begin
ACharSets.Clear();
for i := Low(CharSetTables) to High(CharSetTables) do
begin
ACharSets.Add(CharSetTables[i].Name);
end;
end;
class function TclCharSetTranslator.GetXLATByID(const ATableID: string): TclXLATTable;
var
i: Integer;
begin
Result.Name := '';
for i := Low(CharSetTables) to High(CharSetTables) do
begin
if CompareText(CharSetTables[i].Name, ATableID) = 0 then
begin
Result := CharSetTables[i];
Break;
end;
end;
end;
class procedure TclCharSetTranslator.TranslateTo(const ACharSet: string;
ASource, ADestination: TStream);
var
i: Integer;
Xlat: TclXLATTable;
Ch: Byte;
PrevSourcePos, PrevDestPos: Integer;
begin
Xlat := GetXLATByID(ACharSet);
PrevSourcePos := ASource.Position;
PrevDestPos := ADestination.Position;
ASource.Position := 0;
ADestination.Position := 0;
if (Xlat.Name <> '') then
begin
for i := 0 to ASource.Size - 1 do
begin
ASource.Read(Ch, 1);
Ch := Xlat.ReverseTable[Ch];
ADestination.Write(Ch, 1);
end;
end else
begin
ADestination.CopyFrom(ASource, ASource.Size);
end;
ASource.Position := PrevSourcePos;
ADestination.Position := PrevDestPos;
end;
class procedure TclCharSetTranslator.TranslateFrom(const ACharSet: string;
ASource, ADestination: TStream);
var
i: Integer;
Xlat: TclXLATTable;
Ch: Byte;
PrevSourcePos, PrevDestPos: Integer;
begin
Xlat := GetXLATByID(ACharSet);
PrevSourcePos := ASource.Position;
PrevDestPos := ADestination.Position;
ASource.Position := 0;
ADestination.Position := 0;
if (Xlat.Name <> '') then
begin
for i := 0 to ASource.Size - 1 do
begin
ASource.Read(Ch, 1);
Ch := Xlat.Table[Ch];
ADestination.Write(Ch, 1);
end;
end else
begin
ADestination.CopyFrom(ASource, ASource.Size);
end;
ASource.Position := PrevSourcePos;
ADestination.Position := PrevDestPos;
end;
class function TclCharSetTranslator.TranslateTo(const ACharSet, ASource: string): string;
var
Src, Dst: TStringStream;
begin
Src := TStringStream.Create(ASource);
Dst := TStringStream.Create('');
try
TranslateTo(ACharSet, Src, Dst);
Result := Dst.DataString;
finally
Dst.Free();
Src.Free();
end;
end;
class function TclCharSetTranslator.TranslateFrom(const ACharSet, ASource: string): string;
var
Src, Dst: TStringStream;
begin
Src := TStringStream.Create(ASource);
Dst := TStringStream.Create('');
try
TranslateFrom(ACharSet, Src, Dst);
Result := Dst.DataString;
finally
Dst.Free();
Src.Free();
end;
end;
class function TclCharSetTranslator.ToUtf8(Source: PWideChar; SourceLength: Integer;
Dest: PChar; DestLength: Integer): Integer;
var
i, count: Integer;
c: Cardinal;
begin
count := 0;
i := 0;
while (i < SourceLength) and (count < DestLength) do
begin
c := Cardinal(Source[i]);
Inc(i);
if c <= $7F then
begin
Dest[count] := Char(c);
Inc(count);
end else
if c > $7FF then
begin
if count + 3 > DestLength then Break;
Dest[count] := Char($E0 or (c shr 12));
Dest[count+1] := Char($80 or ((c shr 6) and $3F));
Dest[count+2] := Char($80 or (c and $3F));
Inc(count,3);
end else
begin
if count + 2 > DestLength then Break;
Dest[count] := Char($C0 or (c shr 6));
Dest[count + 1] := Char($80 or (c and $3F));
Inc(count, 2);
end;
end;
if count >= DestLength then
begin
count := DestLength - 1;
end;
Dest[count] := #0;
Result := count + 1;
end;
class function TclCharSetTranslator.FromUtf8(Source: PChar;
SourceLength: Integer; Dest: PWideChar; DestLength: Integer): Integer;
var
i, count: Integer;
c: Byte;
wc: Cardinal;
begin
Result := -1;
count := 0;
i := 0;
while (i < SourceLength) and (count < DestLength) do
begin
wc := Cardinal(Source[i]);
Inc(i);
if (wc and $80) <> 0 then
begin
wc := wc and $3F;
if i > SourceLength then Exit;
if (wc and $20) <> 0 then
begin
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then
begin
if (c = $20) then
begin
Dest[count] := #32;
end else
begin
Dest[count] := #128;
end;
Inc(count);
continue;
end;
if i > SourceLength then Exit;
wc := (wc shl 6) or (c and $3F);
end;
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then
begin
if (c = $20) then
begin
Dest[count] := #32;
end else
begin
Dest[count] := #128;
end;
Inc(count);
continue;
end;
Dest[count] := WideChar((wc shl 6) or (c and $3F));
end else
begin
Dest[count] := WideChar(wc);
end;
Inc(count);
end;
if count >= DestLength then
begin
count := DestLength - 1;
end;
Dest[count] := #0;
Result := count + 1;
end;
class function TclCharSetTranslator.TranslateFromUtf8(const ASource: string): WideString;
var
len: Integer;
ws: WideString;
begin
Result := '';
if (ASource = '') then Exit;
SetLength(ws, Length(ASource));
len := FromUtf8(PChar(ASource), Length(ASource), PWideChar(ws), Length(ws) + 1);
if (len > 0) then
begin
SetLength(ws, len - 1);
end else
begin
ws := '';
end;
Result := ws;
end;
class function TclCharSetTranslator.TranslateToUtf8(const ASource: WideString): string;
var
len: Integer;
s: string;
begin
Result := '';
if (ASource = '') then Exit;
SetLength(s, Length(ASource) * 3);
len := ToUtf8(PWideChar(ASource), Length(ASource), PChar(s), Length(s) + 1);
if (len > 0) then
begin
SetLength(s, len - 1);
end else
begin
s := '';
end;
Result := s;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Command.Push;
interface
uses
VSoft.CancellationToken,
DPM.Console.ExitCodes,
DPM.Console.Command.Base,
DPM.Core.Configuration.Interfaces,
// DPM.Core.Sources.Interfaces,
DPM.Core.Repository.Interfaces,
DPM.Core.Logging;
type
TPushCommand = class(TBaseCommand)
private
FRepositoryManager : IPackageRepositoryManager;
protected
function Execute(const cancellationToken : ICancellationToken) : TExitCode; override;
public
constructor Create(const logger : ILogger; const configurationManager : IConfigurationManager; const repositoryManager : IPackageRepositoryManager);reintroduce;
end;
implementation
uses
System.SysUtils,
VSoft.Uri,
DPM.Core.Options.Common,
DPM.Core.Options.Push;
{ TPushCommand }
constructor TPushCommand.Create(const logger : ILogger; const configurationManager : IConfigurationManager; const repositoryManager : IPackageRepositoryManager);
begin
inherited Create(logger,configurationManager);
FRepositoryManager := repositoryManager;
end;
function TPushCommand.Execute(const cancellationToken : ICancellationToken) : TExitCode;
var
config : IConfiguration;
sourceConfig : ISourceConfig;
sourceUri : IUri;
error : string;
begin
TPushOptions.Default.ApplyCommon(TCommonOptions.Default);
if not FileExists(TPushOptions.Default.ConfigFile) then
begin
Logger.Error('No configuration file found, create one by adding a source - see sources command.');
exit(TExitCode.InitException);
end;
config := FConfigurationManager.LoadConfig(TPushOptions.Default.ConfigFile);
if config = nil then
exit(TExitCode.InitException);
FRepositoryManager.Initialize(config);
//validate the source
sourceConfig := config.Sources.Where(function(const item : ISourceConfig):boolean
begin
result := SameText(item.Name, TPushOptions.Default.Source );
end).FirstOrDefault;
if sourceConfig = nil then
begin
Logger.Error('No source named [' + TPushOptions.Default.Source + '] is registered');
exit(TExitCode.InvalidArguments);
end;
if not TUriFactory.TryParseWithError(sourceConfig.Source,false, sourceUri, error) then
begin
Logger.Error('Error parsing source Uri [' + sourceConfig.Source + '] - ' + error);
exit(TExitCode.Error);
end;
if not FRepositoryManager.Push(cancellationToken, TPushOptions.Default) then
exit(TExitCode.Error);
result := TExitCode.OK;
end;
end.
|
unit ToStringTest;
interface
uses
DUnitX.TestFramework,
SysUtils,
uIntX,
uConstants;
type
[TestFixture]
TToStringTest = class(TObject)
public
[Test]
procedure VerySimple();
[Test]
procedure Simple();
[Test]
procedure Zero();
[Test]
procedure Neg();
[Test]
procedure Big();
[Test]
procedure Binary();
[Test]
procedure Octal();
[Test]
procedure Octal2();
[Test]
procedure Octal3();
[Test]
procedure Hex();
[Test]
procedure HexLower();
[Test]
procedure OtherBase();
end;
implementation
[Test]
procedure TToStringTest.VerySimple();
var
IntX: TIntX;
begin
IntX := TIntX.Create(11);
Assert.AreEqual(IntX.ToString(), '11');
end;
[Test]
procedure TToStringTest.Simple();
var
IntX: TIntX;
begin
IntX := TIntX.Create(12345670);
Assert.AreEqual(IntX.ToString(), '12345670');
end;
[Test]
procedure TToStringTest.Zero();
var
IntX: TIntX;
begin
IntX := TIntX.Create(0);
Assert.AreEqual(IntX.ToString(), '0');
end;
[Test]
procedure TToStringTest.Neg();
var
IntX: TIntX;
begin
IntX := TIntX.Create(TConstants.MinIntValue);
Assert.AreEqual(IntX.ToString(), InttoStr(TConstants.MinIntValue));
end;
[Test]
procedure TToStringTest.Big();
var
IntX: TIntX;
Int64X: Int64;
begin
IntX := TIntX.Create(TConstants.MaxIntValue);
IntX := IntX + IntX + IntX + IntX + IntX + IntX + IntX + IntX;
Int64X := TConstants.MaxIntValue;
Int64X := Int64X + Int64X + Int64X + Int64X + Int64X + Int64X +
Int64X + Int64X;
Assert.AreEqual(IntX.ToString(), InttoStr(Int64X));
end;
[Test]
procedure TToStringTest.Binary();
var
IntX: TIntX;
begin
IntX := TIntX.Create(19);
Assert.AreEqual(IntX.ToString(2), '10011');
end;
[Test]
procedure TToStringTest.Octal();
var
IntX: TIntX;
begin
IntX := TIntX.Create(100);
Assert.AreEqual(IntX.ToString(8), '144');
end;
[Test]
procedure TToStringTest.Octal2();
var
IntX: TIntX;
begin
IntX := TIntX.Create(901);
Assert.AreEqual(IntX.ToString(8), '1605');
end;
[Test]
procedure TToStringTest.Octal3();
var
IntX: TIntX;
begin
IntX := $80000000;
Assert.AreEqual(IntX.ToString(8), '20000000000');
IntX := $100000000;
Assert.AreEqual(IntX.ToString(8), '40000000000');
end;
[Test]
procedure TToStringTest.Hex();
var
IntX: TIntX;
begin
IntX := TIntX.Create($ABCDEF);
Assert.AreEqual(IntX.ToString(16), 'ABCDEF');
end;
[Test]
procedure TToStringTest.HexLower();
var
IntX: TIntX;
begin
IntX := TIntX.Create($FF00FF00FF00FF);
Assert.AreEqual(IntX.ToString(16, False), 'ff00ff00ff00ff');
end;
[Test]
procedure TToStringTest.OtherBase();
var
IntX: TIntX;
begin
IntX := TIntX.Create(-144);
Assert.AreEqual(IntX.ToString(140), '-{1}{4}');
end;
initialization
TDUnitX.RegisterTestFixture(TToStringTest);
end.
|
unit UnitControl;
interface
uses
Math, TypeControl;
type
TUnit = class
private
FId: Int64;
FMass: Double;
FX: Double;
FY: Double;
FSpeedX: Double;
FSpeedY: Double;
FAngle: Double;
FAngularSpeed: Double;
function GetId: Int64;
function GetMass: Double;
function GetX: Double;
function GetY: Double;
function GetSpeedX: Double;
function GetSpeedY: Double;
function GetAngle: Double;
function GetAngularSpeed: Double;
public
property Id: Int64 read GetId;
property Mass: Double read GetMass;
property X: Double read GetX;
property Y: Double read GetY;
property SpeedX: Double read GetSpeedX;
property SpeedY: Double read GetSpeedY;
property Angle: Double read GetAngle;
property AngularSpeed: Double read GetAngularSpeed;
constructor Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double;
const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double);
destructor Destroy; override;
function GetAngleTo(x: Double; y: Double): Double; overload;
function GetAngleTo(otherUnit: TUnit): Double; overload;
function GetDistanceTo(x: Double; y: Double): Double; overload;
function GetDistanceTo(otherUnit: TUnit): Double; overload;
end;
TUnitArray = array of TUnit;
implementation
function TUnit.GetId: Int64;
begin
Result := FId;
end;
function TUnit.GetMass: Double;
begin
Result := FMass;
end;
function TUnit.GetX: Double;
begin
Result := FX;
end;
function TUnit.GetY: Double;
begin
Result := FY;
end;
function TUnit.GetSpeedX: Double;
begin
Result := FSpeedX;
end;
function TUnit.GetSpeedY: Double;
begin
Result := FSpeedY;
end;
function TUnit.GetAngle: Double;
begin
Result := FAngle;
end;
function TUnit.GetAngularSpeed: Double;
begin
Result := FAngularSpeed;
end;
constructor TUnit.Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double;
const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double);
begin
FId := AId;
FMass := AMass;
FX := AX;
FY := AY;
FSpeedX := ASpeedX;
FSpeedY := ASpeedY;
FAngle := AAngle;
FAngularSpeed := AAngularSpeed;
end;
destructor TUnit.Destroy;
begin
inherited;
end;
function TUnit.GetAngleTo(x: Double; y: Double): Double;
var
absoluteAngleTo, relativeAngleTo: Double;
begin
absoluteAngleTo := ArcTan2(y - FY, x - FX);
relativeAngleTo := absoluteAngleTo - FAngle;
while relativeAngleTo > PI do
begin
RelativeAngleTo := relativeAngleTo - 2 * PI;
end;
while relativeAngleTo < -PI do
begin
RelativeAngleTo := relativeAngleTo + 2 * PI;
end;
Result := relativeAngleTo;
end;
function TUnit.getAngleTo(otherUnit: TUnit): Double;
begin
Result := GetAngleTo(otherUnit.X, otherUnit.Y);
end;
function TUnit.getDistanceTo(x: Double; y: Double): Double;
begin
Result := Sqrt(Sqr(FX - x) + Sqr(FY - y));
end;
function TUnit.getDistanceTo(otherUnit: TUnit): Double;
begin
Result := GetDistanceTo(otherUnit.X, otherUnit.Y);
end;
end.
|
unit UnitGroupsReplace;
interface
uses
System.SysUtils,
uConstants,
uMemory,
uTranslate,
uDBContext,
uDBEntities,
uSettings,
uShellIntegration;
type
TGroupAction = record
Action: Integer;
OutGroup: TGroup;
InGroup: TGroup;
end;
TGroupsActions = array of TGroupAction;
TGroupsActionsW = record
Actions: TGroupsActions;
end;
procedure FilterGroups(DBContext: IDBContext; var Groups: TGroups; var OutRegGroups, InRegGroups: TGroups; var Actions: TGroupsActionsW);
implementation
uses
UnitGroupReplace;
procedure AddGroupsAction(var Actions: TGroupsActions; Action: TGroupAction);
var
I: Integer;
B: Boolean;
begin
B := False;
for I := 0 to Length(Actions) - 1 do
if Actions[I].OutGroup.GroupCode = Action.OutGroup.GroupCode then
begin
B := True;
Break;
end;
if not B then
begin
SetLength(Actions, Length(Actions) + 1);
Actions[Length(Actions) - 1] := Action;
end;
end;
function ExistsActionForGroup(Actions: TGroupsActions; Group: TGroup): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Length(Actions) - 1 do
if Actions[I].OutGroup.GroupCode = Group.GroupCode then
begin
Result := True;
Break;
end;
end;
function GetGroupAction(Actions: TGroupsActions; Group: TGroup): TGroupAction;
var
I: Integer;
begin
for I := 0 to Length(Actions) - 1 do
if Actions[I].OutGroup.GroupCode = Group.GroupCode then
begin
Result := Actions[I];
Break;
end;
end;
procedure FilterGroups(DBContext: IDBContext; var Groups: TGroups; var OutRegGroups, InRegGroups: TGroups; var Actions: TGroupsActionsW);
var
I: Integer;
PI: PInteger;
Action: TGroupAction;
GrNameIn, GrNameOut: string;
Options: GroupReplaceOptions;
GroupsRepository: IGroupsRepository;
function GroupExistsIn(GroupCode: string): string;
var
J: Integer;
begin
Result := '';
for J := 0 to InRegGroups.Count - 1 do
if InRegGroups[J].GroupCode = GroupCode then
begin
Result := InRegGroups[J].GroupName;
Break;
end;
end;
function GroupExistsInByNameByCode(GroupCode: string): Boolean;
var
J: Integer;
begin
Result := False;
for J := 0 to InRegGroups.Count - 1 do
if InRegGroups[J].GroupCode = GroupCode then
begin
Result := True;
Break;
end;
end;
function GroupExistsOut(GroupCode: string): string;
var
J: Integer;
begin
Result := '';
for J := 0 to OutRegGroups.Count - 1 do
if OutRegGroups[J].GroupCode = GroupCode then
begin
Result := OutRegGroups[J].GroupName;
Break;
end;
end;
function GroupByNameOut(GroupName: string; default: TGroup): TGroup;
var
J: Integer;
begin
Result := default;
for J := 0 to OutRegGroups.Count - 1 do
if OutRegGroups[J].GroupName = GroupName then
begin
Result := OutRegGroups[J];
Exit;
end;
end;
procedure ReplaceGroup(GroupToRemove, GroupToAdd: TGroup; Groups: TGroups);
var
GroupsToRemove, GroupsToAdd: TGroups;
begin
GroupsToRemove := TGroups.Create;
GroupsToAdd := TGroups.Create;
try
GroupsToRemove.Add(GroupToRemove);
GroupsToAdd.Add(GroupToAdd);
Groups.RemoveGroups(GroupsToRemove).AddGroups(GroupsToAdd);
finally
GroupsToRemove.Clear;
GroupsToAdd.Clear;
F(GroupsToRemove);
F(GroupsToAdd);
end;
end;
begin
GroupsRepository := DBContext.Groups;
PI := @I;
for I := 0 to Groups.Count - 1 do
begin
if Groups.Count <= I then
Break;
if not ExistsActionForGroup(Actions.Actions, Groups[I]) then
begin
GrNameIn := GroupExistsIn(Groups[I].GroupCode);
GrNameOut := GroupExistsOut(Groups[I].GroupCode);
if ((GrNameIn <> '') or GroupExistsInByNameByCode(Groups[I].GroupName)) then
Options.AllowAdd := False
else
begin
if GrNameOut <> '' then
Options.AllowAdd := True
else
Options.AllowAdd := False;
end;
Options.AllowAdd := True;
if GrNameOut = '' then
GroupReplaceNotExists(DBContext, Groups[I], Action, Options)
else
GroupReplaceExists(DBContext, GroupByNameOut(Groups[I].GroupName, Groups[I]), Action, Options);
if Action.Action <> GROUP_ACTION_ADD then
AddGroupsAction(Actions.Actions, Action);
if Action.Action = GROUP_ACTION_ADD_IN_EXISTS then
ReplaceGroup(Action.OutGroup, Action.InGroup, Groups);
if Action.Action = GROUP_ACTION_ADD_IN_NEW then
ReplaceGroup(Action.OutGroup, Action.InGroup, Groups);
if Action.Action = GROUP_ACTION_NO_ADD then
begin
Groups.RemoveGroup(Action.OutGroup);
Pi^ := I - 1;
end;
if Action.Action = GROUP_ACTION_ADD then
begin
if GroupsRepository.Add(GroupByNameOut(Groups[I].GroupName, Groups[I])) then
begin
if Action.InGroup <> nil then
ReplaceGroup(Action.OutGroup, Action.InGroup, Groups);
Action.InGroup := GroupsRepository.GetByName(Groups[I].GroupName, False);
Action.Action := GROUP_ACTION_ADD_IN_EXISTS;
AddGroupsAction(Actions.Actions, Action);
F(InRegGroups);
InRegGroups := GroupsRepository.GetAll(True, True);
end else
begin
MessageBoxDB(0, Format(TA('An error occurred while adding a group', 'Groups'),
[Groups[I].GroupName]), TA('Error'), TD_BUTTON_OK, TD_ICON_ERROR);
end;
end;
end else
begin
Action := GetGroupAction(Actions.Actions, Groups[I]);
if Action.Action = GROUP_ACTION_ADD_IN_EXISTS then
ReplaceGroup(Action.OutGroup, Action.InGroup, Groups);
if Action.Action = GROUP_ACTION_ADD_IN_NEW then
ReplaceGroup(Action.OutGroup, Action.InGroup, Groups);
if Action.Action = GROUP_ACTION_NO_ADD then
begin
Groups.RemoveGroup(Action.OutGroup);
Pi^ := I - 1;
end;
end;
end;
end;
end.
|
unit Chapter09._05_Solution2;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Math,
DeepStar.Utils;
/// 背包问题
/// 动态规划
/// 时间复杂度: O(n * C) 其中n为物品个数; C为背包容积
/// 空间复杂度: O(n * C)
type
TSolution = class(TObject)
public
function knapsack01(const w, v: TArr_int; c: integer): integer;
end;
procedure Main;
implementation
procedure Main;
var
w, v: TArr_int;
begin
w := [1, 2, 3];
v := [6, 10, 12];
with TSolution.Create do
begin
WriteLn(knapsack01(w, v, 5));
Free;
end;
end;
{ TSolution }
function TSolution.knapsack01(const w, v: TArr_int; c: integer): integer;
var
memo: TArr2D_int;
n, i, j: integer;
begin
Assert((Length(w) = Length(v)) and (c >= 0));
n := Length(w);
if (n = 0) or (c = 0) then
Exit(0);
SetLength(memo, n, c + 1);
for i := 0 to c do
memo[0, i] := IfThen(i >= w[0], v[0], 0);
for i := 1 to n - 1 do
begin
for j := 0 to c do
begin
memo[i, j] := memo[i - 1, j];
if j >= w[i] then
memo[i, j] := Max(memo[i, j], v[i] + memo[i - 1, j-w[i]]);
end;
end;
Result := memo[n - 1, c];
end;
end.
|
unit UnitConst;
interface
const
ERR_MSG_TITLE = '错误';
ERR_FILE_NOT_FOUND = '找不到文件!';
ERR_CAN_NOT_CREATE = '不能创建文件!';
ERR_CONNECT_DB_FAILURE = '数据库连接失败!';
ERR_LOGIN_FAILURE = '用户登录失败!';
ERR_NO_RECORD_FOUND = '没有相关记录!';
ERR_CRITICAL = '对不起,出错了,请联系管理员。';
ERR_USER_WRONG = '用户名不正确!';
ERR_PWD_WRONG = '密码不正确!';
MSG_RECOMMAND = '提示';
MSG_WARNING = '警告';
MSG_LOGIN = '已登入';
MSG_LOGOUT = '未登入';
MSG_NOT_SAVE_DATA = '修改的数据还没有保存,是否保存?';
MSG_DELETE_CONFIRM = '删除将不能恢复,确认要删除该记录吗?';
MSG_DELETE_SUB_DATA = '有其它记录关联该记录,删除该记录将连同删除子记录,确认删除吗?';
MSG_MANDATORY_PWD = '请填写用户密码!';
MSG_MANDATORY_NAME = '请填写用户名称!';
MSG_MANDATORY_GROUP = '请选择用户类型!';
MSG_MANDATORY_SUBJECT = '请填写科目名称!';
MSG_MANDATORY_QUES = '请填写问题内容!';
MSG_MANDATORY_SUBJ = '请选择科目!';
MSG_MANDATORY_QUES_NEED = '请先选择问题!';
MSG_MANDATORY_TYPE = '请选择问题类型!';
MSG_DOUBLE_USERNAME = '系统已经存在该用户名,请更换成其他名称!';
MSG_DOUBLE_QUESTYPE = '系统已经存在该问题类型,请更换成其他类型!';
MSG_CAN_NOT_DELETE = '不能删除该记录。';
MSG_CAN_NOT_UPDATE = '不能更新该记录。';
MSG_INF_REQUEST = '请先填写相关信息!';
INF_PWD_BASE = 'ExamLib by maple';
INF_AUTHOR = 'maple';
INF_SYSTEM = '系统员';
INI_FILE_NAME = 'system.ini';
INI_DB_SECTION = 'DB';
INI_DB_ADOSTRING = 'ADOString';
INI_DB_ADOSTRING_DEFAULT_VAL = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:Database Password=''''';
INI_DB_FILE = 'FilePath';
INI_IMAGE_PATH = 'ImagePath';
INI_DB_FILE_DEFAULT_PATH = 'Data\ExamLib.mdb';
INI_DEFAULT_IMAGE_PATH = 'Data\Image\';
INI_USER_SECTION = 'User';
INI_USER_NAME = 'Name';
INI_USER_DEFAULT_NAME = 'maple';
INI_USER_PWD = 'Pwd';
INI_USER_SAVE_PWD = 'SavePwd';
INI_USER_DEFAULT_PWD = 'Pass99';
DB_TABLE_USER = 'eUser';
DB_TABLE_ANSWER = 'eAnswer';
DB_TABLE_QUESTION = 'eQuestion';
DB_TABLE_QUESTYPE = 'eQuesType';
DB_TABLE_SUBJECT = 'eSubject';
DB_ID = 'id';
DB_NAME = 'name';
DB_PWD = 'pwd';
DB_AND = ' and ';
DB_EQUAL = ' = ';
IMAGE_QUES = 'Q_';
IMAGE_ANSW = 'A_';
ALIGN_LEFT = 1;
ALIGN_CENTER = 2;
ALIGN_RIGHT = 3;
implementation
end.
|
unit uAddBirthPlace;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uAddModifForm, StdCtrls, Buttons, uFormControl, uFControl,
uLabeledFControl, uSpravControl, uAdr_DataModule, uInvisControl;
type
TAddBirthPlace = class(TAddModifForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
qFFC_Adress: TqFFormControl;
qFSC_Coutry: TqFSpravControl;
qFSC_Region: TqFSpravControl;
qFSC_City: TqFSpravControl;
procedure OkButtonClick(Sender: TObject);
procedure qFSC_CoutryOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure qFSC_RegionOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure qFSC_CityOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure qFSC_CoutryChange(Sender: TObject);
procedure qFSC_RegionChange(Sender: TObject);
private
{ Private declarations }
public
constructor Create(AOwner:TComponent; DMod: TAdrDM; Mode: TFormMode; Where: Variant);
end;
var
AddBirthPlace: TAddBirthPlace;
implementation
uses uAdressForm, RXMemDS, uUnivSprav;
{$R *.dfm}
constructor TAddBirthPlace.Create(AOwner:TComponent; DMod: TAdrDM; Mode: TFormMode; Where: Variant);
begin
inherited Create(AOwner);
DBHandle:=Integer(DMod.pFIBDB_Adr.Handle);
if (Mode=fmAdd) then
begin
end;
qFFC_Adress.Prepare(DMod.pFIBDB_Adr,Mode,Where,Null);
end;
procedure TAddBirthPlace.OkButtonClick(Sender: TObject);
begin
qFFC_Adress.Ok;
end;
procedure TAddBirthPlace.qFSC_CoutryOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
Params:TUnivParams;
OutPut : TRxMemoryData;
begin
Params.FormCaption:='Довідник країн';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_Country_Form';
Params.ModifFormClass:='TAdd_Country_Form';
Params.TableName:='adr_country';
Params.Fields:='Name_country,id_country';
Params.FieldsName:='Назва';
Params.KeyField:='id_country';
Params.ReturnFields:='Name_country,id_country';
Params.DeleteSQL:='execute procedure adr_country_d(:id_country);';
Params.DBHandle:=DBHandle;
OutPut:=TRxMemoryData.Create(self);
if GetUnivSprav(Params,OutPut)
then
begin
value:=output['id_country'];
DisplayText:=VarToStr(output['Name_country']);
end;
end;
procedure TAddBirthPlace.qFSC_RegionOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
Params:TUnivParams;
OutPut : TRxMemoryData;
begin
if VarIsNull(qFSC_Coutry.Value) then
begin
MessageDlg('Спочатку оберіть країну!',mtError,[mbOk],-1);
Exit;
end;
Params.FormCaption:='Довідник регіонів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_Region_Form';
Params.ModifFormClass:='TAdd_Region_Form';
Params.TableName:='adr_region_select('+IntToStr(qFSC_Coutry.Value)+')';
Params.Fields:='Name_region,id_region';
Params.FieldsName:='Назва';
Params.KeyField:='id_region';
Params.ReturnFields:='Name_region,id_region';
Params.DeleteSQL:='execute procedure adr_region_d(:id_region);';
Params.DBHandle:=DBHandle;
OutPut:=TRxMemoryData.Create(self);
if GetUnivSprav(Params,OutPut)
then
begin
// ShowInfo(output);
value:=output['id_region'];
DisplayText:=VarToStr(output['Name_region']);
end;
end;
procedure TAddBirthPlace.qFSC_CityOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
Params:TUnivParams;
OutPut : TRxMemoryData;
begin
if VarIsNull(qFSC_Region.Value) then
begin
MessageDlg('Спочатку оберіть регіон!',mtError,[mbOk],-1);
Exit;
end;
Params.FormCaption:='Довідник міст';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_Place_Form';
Params.ModifFormClass:='TAdd_Place_Form';
Params.TableName:='adr_place_select('+IntToStr(qFSC_Region.Value)+',null)';
Params.Fields:='Name_place,id_place';
Params.FieldsName:='Назва';
Params.KeyField:='id_place';
Params.ReturnFields:='Name_place,id_place';
Params.DeleteSQL:='execute procedure adr_place_d(:id_place);';
Params.DBHandle:=DBHandle;
OutPut:=TRxMemoryData.Create(self);
if GetUnivSprav(Params,OutPut)
then
begin
value:=output['id_place'];
DisplayText:=VarToStr(output['Name_place']);
end;
end;
procedure TAddBirthPlace.qFSC_CoutryChange(Sender: TObject);
begin
if Visible then
qFSC_Region.Clear;
end;
procedure TAddBirthPlace.qFSC_RegionChange(Sender: TObject);
begin
if Visible then
qFSC_City.Clear;
end;
initialization
RegisterClass(TAddBirthPlace);
end.
|
unit ufrmDialogUser;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, StdCtrls,
System.Actions, Vcl.ActnList, ufraFooterDialog3Button, uAppUtils,
uModApp, uDXUtils, uModAuthUser, uInterface, uDMClient, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxClasses,
cxGridLevel, cxGrid, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit,
cxNavigator, cxGridCustomView, cxGridCustomTableView, cxGridTableView;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogUser = class(TfrmMasterDialog, ICRUDAble)
DataUser: TGroupBox;
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
lbl4: TLabel;
lbl5: TLabel;
lbl6: TLabel;
edtLogin: TEdit;
edtPassword: TEdit;
edtConfirm: TEdit;
edtFullName: TEdit;
cbbStatus: TComboBox;
edtDescription: TEdit;
cxgrdlvlMenu: TcxGridLevel;
cxgrdMenu: TcxGrid;
cxGridTableMenu: TcxGridTableView;
procedure actDeleteExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FUser: TModAuthUser;
function GetUser: TModAuthUser;
property User: TModAuthUser read GetUser write FUser;
public
procedure LoadData(AID: String);
{ Public declarations }
published
end;
var
frmDialogUser: TfrmDialogUser;
iUbahPO: Integer;
implementation
uses uConn, DB, uTSCommonDlg, uRetnoUnit, ufrmUser;
{$R *.dfm}
procedure TfrmDialogUser.actDeleteExecute(Sender: TObject);
begin
inherited;
if not TAppUtils.Confirm('Anda yakin akan menghapus data ?') then
Exit;
if DMClient.CrudClient.DeleteFromDB(FUser) then
begin
TAppUtils.InformationBerhasilHapus;
LoadData('');
end;
end;
procedure TfrmDialogUser.actSaveExecute(Sender: TObject);
begin
inherited;
if not ValidateEmptyCtrl([1]) then
Exit;
if edtPassword.Text <> edtConfirm.Text then
begin
TAppUtils.Warning('Password dan Konfirmasi Beda');
Exit;
end;
User.USR_FULLNAME := edtFullName.Text;
User.USR_USERNAME := edtLogin.Text;
User.USR_PASSWD := edtPassword.Text;
User.USR_STATUS := cbbStatus.ItemIndex;
User.USR_DESCRIPTION := edtDescription.Text;
if DMClient.CrudClient.SaveToDB(User) then
begin
TAppUtils.InformationBerhasilSimpan;
LoadData('');
end;
end;
procedure TfrmDialogUser.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action:= caFree;
end;
function TfrmDialogUser.GetUser: TModAuthUser;
begin
if FUser = nil then
FUser := TModAuthUser.Create;
Result := FUser;
end;
procedure TfrmDialogUser.LoadData(AID: String);
begin
ClearByTag([0,1]);
cxGridTableMenu.ClearRows;
if AID = '' then
Exit;
FreeAndNil(FUser);
FUser := DMClient.CrudClient.Retrieve(TModAuthUser.ClassName, AID) as TModAuthUser;
if FUser <> nil then
begin
edtLogin.Text := FUser.USR_USERNAME;
edtPassword.Text := FUser.USR_PASSWD;
edtConfirm.Text := FUser.USR_PASSWD;
edtFullName.Text := FUser.USR_FULLNAME;
cbbStatus.ItemIndex := FUser.USR_STATUS;
edtDescription.Text := FUser.USR_DESCRIPTION;
end;
// DMClient.DSProviderClient.Menu_GetDSLookup()
end;
end.
|
{..............................................................................}
{..............................................................................}
Function CheckName(ARecord : String; AName : String) : Boolean;
Begin
Result := False;
If ARecord = '' Then Exit;
If AName = '' Then Exit;
AName := UpperCase(AName);
If Pos(AName+'=',ARecord) > 0 Then
Result := True;
End;
{..............................................................................}
{..............................................................................}
Function CheckNameAndValue(ARecord : String; AName : String; AValue : String) : Boolean;
Begin
Result := False;
If ARecord = '' Then Exit;
If AName = '' Then Exit;
AName := UpperCase(AName);
AValue := UpperCase(AValue);
If Pos(AName+'='+AValue,ARecord) > 0 Then
Result := True;
End;
{..............................................................................}
{..............................................................................}
Function WithNameCheckValue(ARecord : String; AName : String; AnOldValue : String) : String;
Const
Delimiter = '|';
Var
APos, ANameLength, AFullLength : Integer;
AValuePos : Integer;
SubString : String;
Finished : Boolean;
Begin
Result := '';
If AName = '' Then Exit;
AName := UpperCase(AName) + '=';
AnOldValue := UpperCase(AnOldValue);
// Function from SysUtils that trims leading/trailing spaces
// and control characters from a string
ARecord := Trim(ARecord);
// Both AName and AValue parameters exist...
If AnOldValue <> '' Then
If Pos(AName+AnOldValue,ARecord) > 0 Then
Begin
Result := ARecord;
Exit;
End;
// Only AName parameter exist...
If Pos(AName,ARecord) > 0 Then
Begin
// retrieve AValue up to (but not including) the
// delimiter or to the end of the string
AFullLength := Length(ARecord);
//AValuePos is the starting point of the AValue substring
AnOldValue := '';
AValuePos := Pos(AName,ARecord) + Length(AName);
Finished := False;
Repeat
AnOldValue := AnOldValue + ARecord[AValuePos];
Inc(AValuePos);
// Delimiter encountered or end of string reached...
If (AValuePos = AFullLength + 1) Or
(ARecord[AValuePos] = DeLimiter) Then
Finished := True;
Until Finished;
Result := AnOldValue;
End;
End;
{..............................................................................}
{..............................................................................}
Function UpdateOrInsertNameValue(ARecord : String; AName : String; AValue : String) : String;
Var
Temp : String;
ExistingValue : String;
AnOldValue : String;
RetrievedValue : String;
OldPattern : String;
NewPattern : String;
Begin
If ARecord = '' Then Exit;
If AName = '' Then Exit;
If AValue = '' Then Exit;
AName := UpperCase(AName);
AValue := UpperCase(AValue);
AnOldValue := '';
RetrievedValue := WithNameCheckValue(ARecord,AName,AnOldValue);
AnOldValue := '';
RetrievedValue := WithNameCheckValue(ARecord,AName,AnOldValue);
If RetrievedValue <> '' Then
Begin
//1. Old Value exists, replace that with the new value.
OldPattern := AName + '=' + RetrievedValue;
NewPattern := AName + '=' + AValue;
Result := StringReplace(ARecord,OldPattern,NewPattern,MkSet(rfReplaceAll));
End
Else
Begin
// 2. the AName doesnt exist in the record, thus append AName = AValue to the record string
Result := ARecord + ' | ' + AName + '=' + AValue;
End;
End;
{..............................................................................}
{..............................................................................}
|
unit UDBorder;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32, UCrpeClasses;
type
TCrpeBorderDlg = class(TForm)
gbLineStyle: TGroupBox;
cbLeft: TComboBox;
lblLeft: TLabel;
lblRight: TLabel;
cbRight: TComboBox;
cbTop: TComboBox;
lblTop: TLabel;
lblBottom: TLabel;
cbBottom: TComboBox;
sbFormulaRed: TSpeedButton;
sbFormulaBlue: TSpeedButton;
sbLeft: TSpeedButton;
sbRight: TSpeedButton;
sbTop: TSpeedButton;
sbBottom: TSpeedButton;
pnlTightHorizontal: TPanel;
pnlDropShadow: TPanel;
cbTightHorizontal: TCheckBox;
cbDropShadow: TCheckBox;
sbDropShadow: TSpeedButton;
gbColor: TGroupBox;
ColorDialog1: TColorDialog;
lblForeColor: TLabel;
sbForeColor: TSpeedButton;
sbBackgroundColor: TSpeedButton;
btnOk: TButton;
btnCancel: TButton;
btnClear: TButton;
lblBackgroundColor: TLabel;
sbTightHorizontal: TSpeedButton;
cbForeColor: TColorBox;
cbBackgroundColor: TColorBox;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnClearClick(Sender: TObject);
procedure FormulaButtonClick(Sender: TObject);
procedure UpdateBorder;
private
{ Private declarations }
public
Border : TCrpeBorder; {reference to TCrpeBorder}
end;
var
CrpeBorderDlg: TCrpeBorderDlg;
bBorder : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UDFormulaEdit;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeBorderDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
bBorder := True;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeBorderDlg.FormShow(Sender: TObject);
begin
UpdateBorder;
end;
{------------------------------------------------------------------------------}
{ UpdateBorder }
{------------------------------------------------------------------------------}
procedure TCrpeBorderDlg.UpdateBorder;
procedure SetFormulaButton(sb: TSpeedButton; sList: TStrings);
begin
if IsStringListEmpty(sList) then
begin
if sb.Tag <> 0 then
begin
sb.Glyph := sbFormulaBlue.Glyph;
sb.Tag := 0;
end;
end
else
begin
if sb.Tag <> 1 then
begin
sb.Glyph := sbFormulaRed.Glyph;
sb.Tag := 1;
end;
end;
end;
begin
{ForeColor}
cbForeColor.Selected := Border.ForeColor;
{BackgroundColor}
cbBackgroundColor.Selected := Border.BackgroundColor;
{Left}
SetFormulaButton(sbLeft, Border.Formulas.Left);
{Right}
SetFormulaButton(sbRight, Border.Formulas.Right);
{Top}
SetFormulaButton(sbTop, Border.Formulas.Top);
{Bottom}
SetFormulaButton(sbBottom, Border.Formulas.Bottom);
{TightHorizontal}
SetFormulaButton(sbTightHorizontal, Border.Formulas.TightHorizontal);
{DropShadow}
SetFormulaButton(sbDropShadow, Border.Formulas.DropShadow);
{Color}
SetFormulaButton(sbForeColor, Border.Formulas.ForeColor);
{BackgroundColor}
SetFormulaButton(sbBackgroundColor, Border.Formulas.BackgroundColor);
cbLeft.ItemIndex := Ord(Border.Left);
cbRight.ItemIndex := Ord(Border.Right);
cbTop.ItemIndex := Ord(Border.Top);
cbBottom.ItemIndex := Ord(Border.Bottom);
cbTightHorizontal.Checked := Border.TightHorizontal;
cbDropShadow.Checked := Border.DropShadow;
end;
{------------------------------------------------------------------------------}
{ FormulaButtonClick }
{------------------------------------------------------------------------------}
procedure TCrpeBorderDlg.FormulaButtonClick(Sender: TObject);
var
CRFF : TStrings;
begin
if not (Sender is TSpeedButton) then
Exit;
{Set Crpe Formulas to chosen item}
if TSpeedButton(Sender) = sbLeft then
CRFF := Border.Formulas.Left
else if TSpeedButton(Sender) = sbRight then
CRFF := Border.Formulas.Right
else if TSpeedButton(Sender) = sbTop then
CRFF := Border.Formulas.Top
else if TSpeedButton(Sender) = sbBottom then
CRFF := Border.Formulas.Bottom
else if TSpeedButton(Sender) = sbTightHorizontal then
CRFF := Border.Formulas.TightHorizontal
else if TSpeedButton(Sender) = sbDropShadow then
CRFF := Border.Formulas.DropShadow
else if TSpeedButton(Sender) = sbForeColor then
CRFF := Border.Formulas.ForeColor
else if TSpeedButton(Sender) = sbBackgroundColor then
CRFF := Border.Formulas.BackgroundColor
else
CRFF := Border.Formulas.Left;
{Create the Formula editing form}
CrpeFormulaEditDlg := TCrpeFormulaEditDlg.Create(Application);
CrpeFormulaEditDlg.SenderList := CRFF;
CrpeFormulaEditDlg.Caption := TSpeedButton(Sender).Hint;
CrpeFormulaEditDlg.ShowModal;
{Update the form}
UpdateBorder;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeBorderDlg.btnOkClick(Sender: TObject);
begin
Border.Left := TCrLineStyle(cbLeft.ItemIndex);
Border.Right := TCrLineStyle(cbRight.ItemIndex);
Border.Top := TCrLineStyle(cbTop.ItemIndex);
Border.Bottom := TCrLineStyle(cbBottom.ItemIndex);
Border.TightHorizontal := cbTightHorizontal.Checked;
Border.DropShadow := cbDropShadow.Checked;
Border.ForeColor := cbForeColor.Selected;
Border.BackgroundColor := cbBackgroundColor.Selected;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeBorderDlg.btnClearClick(Sender: TObject);
begin
Border.Clear;
UpdateBorder;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeBorderDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bBorder := False;
Release;
end;
end.
|
{-------------------------------------------------------------------------------
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/.
-------------------------------------------------------------------------------}
{===============================================================================
Counted Dynamic Arrays
Counted dynamic array of UnicodeChar values
Version 1.2.1 (2019-08-19)
Last changed 2019-08-19
©2018-2019 František Milt
Contacts:
František Milt: frantisek.milt@gmail.com
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.AuxClasses
Dependencies:
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
ListSorters - github.com/TheLazyTomcat/Lib.ListSorters
StrRect - github.com/TheLazyTomcat/Lib.StrRect
===============================================================================}
unit CountedDynArrayUnicodeChar;
{$INCLUDE '.\CountedDynArrays_defs.inc'}
{$DEFINE CDA_CaseSensitiveBaseType}
{$DEFINE CDA_FuncOverride_ItemCompare}
interface
uses
AuxTypes,
CountedDynArrays;
type
TCDABaseType = UnicodeChar;
PCDABaseType = ^TCDABaseType;
TCountedDynArrayUnicodeChar = record
{$DEFINE CDA_Structure}
{$INCLUDE '.\CountedDynArrays.inc'}
{$UNDEF CDA_Structure}
end;
PCountedDynArrayUnicodeChar = ^TCountedDynArrayUnicodeChar;
// aliases
TCountedDynArrayOfUnicodeChar = TCountedDynArrayUnicodeChar;
PCountedDynArrayOfUnicodeChar = PCountedDynArrayUnicodeChar;
TUnicodeCharCountedDynArray = TCountedDynArrayUnicodeChar;
PUnicodeCharCountedDynArray = PCountedDynArrayUnicodeChar;
TCDAArrayType = TCountedDynArrayUnicodeChar;
PCDAArrayType = PCountedDynArrayUnicodeChar;
{$DEFINE CDA_Interface}
{$INCLUDE '.\CountedDynArrays.inc'}
{$UNDEF CDA_Interface}
implementation
uses
SysUtils,
ListSorters, StrRect;
{$INCLUDE '.\CountedDynArrays_msgdis.inc'}
Function CDA_ItemCompare(const A,B: TCDABaseType; CaseSensitive: Boolean): Integer;{$IFDEF CanInline} inline;{$ENDIF}
begin
Result := -UnicodeStringCompare(A,B,CaseSensitive);
end;
//------------------------------------------------------------------------------
{$DEFINE CDA_Implementation}
{$INCLUDE '.\CountedDynArrays.inc'}
{$UNDEF CDA_Implementation}
end.
|
unit uMkvExtractor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StrUtils, StdCtrls, ComCtrls;
const
WM_EXTRACTIONCOMPLETE = WM_USER + $01;
WM_CONSOLEDATA = WM_USER + $02;
type
TfrmMkvExtractor = class(TForm)
Label1: TLabel;
ProgressBar1: TProgressBar;
btnCancel: TButton;
lblProgress: TLabel;
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
FMKVFilename: String;
FSubtitleFilename: String;
FStopEverything: Boolean;
procedure OnExtractionComplete(var msg: TMessage); message WM_EXTRACTIONCOMPLETE;
procedure OnConsoleData(var msg: TMessage); message WM_CONSOLEDATA;
function ExtractSubtitlesTrack(const filename: String; track_num: Integer;
window_handle: THandle): String;
function GetEnglishSubTrackNum(const filename: String): Integer;
procedure OpenVideo;
public
function SubtitleWorthy(const filename: String): Boolean;
function StartExtractionAndGetFilename(const filename: String): String;
end;
var
frmMkvExtractor: TfrmMkvExtractor;
mkvtoolnix_path: String = 'mkvtoolnix\';
implementation
uses Unit1;
procedure ExecuteConsoleApp(const CommandLine: String;
var Output: TStringList; Errors: TStringList;
CallBackWindowHandle: THandle = 0);
var
sa: TSECURITYATTRIBUTES;
si: TSTARTUPINFO;
pi: TPROCESSINFORMATION;
hPipeOutputRead: THandle;
hPipeOutputWrite: THandle;
hPipeErrorsRead: THandle;
hPipeErrorsWrite: THandle;
Res, bTest: boolean;
szBuffer: array [0 .. 255] of AnsiChar;
dwNumberOfBytesRead: dword;
Stream: TMemoryStream;
begin
sa.nLength := sizeof(sa);
sa.bInheritHandle := true;
sa.lpSecurityDescriptor := nil;
CreatePipe(hPipeOutputRead, hPipeOutputWrite, @sa, 0);
CreatePipe(hPipeErrorsRead, hPipeErrorsWrite, @sa, 0);
ZeroMemory(@si, sizeof(si));
ZeroMemory(@pi, sizeof(pi));
si.cb := sizeof(si);
si.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
si.wShowWindow := SW_HIDE;
si.hStdInput := 0;
si.hStdOutput := hPipeOutputWrite;
si.hStdError := hPipeErrorsWrite;
(* Remember that if you want to execute an app with no parameters you nil the
second parameter and use the first, you can also leave it as is with no
problems. *)
Res := CreateProcess(nil, PChar(CommandLine), nil, nil, true,
CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, si, pi);
// Procedure will exit if CreateProcess fail
if not Res then
begin
CloseHandle(hPipeOutputRead);
CloseHandle(hPipeOutputWrite);
CloseHandle(hPipeErrorsRead);
CloseHandle(hPipeErrorsWrite);
Exit;
end;
CloseHandle(hPipeOutputWrite);
CloseHandle(hPipeErrorsWrite);
// Read output pipe
Stream := TMemoryStream.Create;
try
while true do
begin
bTest := ReadFile(hPipeOutputRead, szBuffer, sizeof(szBuffer), dwNumberOfBytesRead, nil);
if not bTest then
break;
Stream.Write(szBuffer, dwNumberOfBytesRead);
if (CallBackWindowHandle <> 0) then
begin
if SendMessage(CallBackWindowHandle, WM_CONSOLEDATA,
dwNumberOfBytesRead, lParam(@szBuffer[0])) <> 0 then
begin
//stop everything
TerminateProcess(pi.hProcess, 0);
end;
end;
end;
Stream.Position := 0;
Output.LoadFromStream(Stream);
finally
Stream.Free;
end;
// Read error pipe
Stream := TMemoryStream.Create;
try
while true do
begin
bTest := ReadFile(hPipeErrorsRead, szBuffer, sizeof(szBuffer), dwNumberOfBytesRead, nil);
if not bTest then
break;
Stream.Write(szBuffer, dwNumberOfBytesRead);
end;
Stream.Position := 0;
Errors.LoadFromStream(Stream);
finally
Stream.Free;
end;
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(hPipeOutputRead);
CloseHandle(hPipeErrorsRead);
end;
function TfrmMkvExtractor.GetEnglishSubTrackNum(const filename: String): Integer;
const
STR_ID_ENG = 'language:eng';
STR_ID_TRACK_NUM = 'Track ID ';
STR_ID_TRACK_NUM_END = ':';
STR_ID_SUBTITLES = '(S_TEXT/UTF8)';
var
output, errors: TStringList;
i, j, k: Integer;
s: String;
begin
Result := -1;
output := TStringList.Create;
errors := TStringList.Create;
try
//get info from mkv file
ExecuteConsoleApp(mkvtoolnix_path + 'mkvmerge.exe -I "' + filename + '"',
output, errors);
if errors.Count > 0 then
Exit;
for i := 0 to output.Count - 1 do
begin
//find english track
if Pos(STR_ID_ENG, output[i]) > 0 then
begin
//get track number position
j := Pos(STR_ID_TRACK_NUM, output[i]);
//if this track is a subtitle track
if (j > 0) AND (Pos(STR_ID_SUBTITLES, output[i]) > 0) then
begin
//move to last char of STR_ID_TRACK_NUM
j := j + Length(STR_ID_TRACK_NUM);
//extract number
k := PosEx(STR_ID_TRACK_NUM_END, output[i], j);
if k > 0 then
begin
s := Copy(output[i], j, k - j);
if NOT TryStrToInt(s, Result) then
Result := -1
else
Break;
end;
end;
end;
end;
finally
errors.Free;
output.Free;
end;
end;
function TfrmMkvExtractor.ExtractSubtitlesTrack(const filename: String; track_num: Integer;
window_handle: THandle): String;
//type for thread params
type
TExtractorThreadParams = record
tracknum: Integer;
WindowHandle: THandle;
EventHandle: THandle;
filename: String;
subtitle_filename: String;
end;
PExtractorThreadParams = ^TExtractorThreadParams;
procedure ExtractThread(p: PExtractorThreadParams); stdcall;
var
filename, subtitle_filename: String;
tracknum: Integer;
WindowHandle: Integer;
output, errors: TStringList;
command: String;
begin
//save params
filename := p^.filename;
subtitle_filename := p^.subtitle_filename;
tracknum := p^.tracknum;
WindowHandle := p^.WindowHandle;
//signal main thread as soon as params saved
SetEvent(p^.EventHandle);
output := TStringList.Create;
errors := TStringList.Create;
try
command := Format('%smkvextract.exe tracks "%s" -c cp1251 %d:"%s"',
[mkvtoolnix_path, filename, tracknum, subtitle_filename]);
//start extraction with reportings (WM_COPYDATA)
ExecuteConsoleApp(command, output, errors, WindowHandle);
if errors.Count = 0 then
begin
//send message at the end
SendMessage(WindowHandle, WM_EXTRACTIONCOMPLETE, 0, 0);
end;
finally
errors.Free;
output.Free;
end;
end;
var
subtitle_filename: String;
extraction_params: TExtractorThreadParams;
thread_id: DWORD;
hThread: THandle;
begin
Result := '';
if (track_num < 0) then
Exit;
//name for subtitle file. Just change extension to SRT
subtitle_filename := ChangeFileExt(filename, '.SRT');
//save it to global var
//in case if user will interrupt the extraction process
//we should erase the file
FSubtitleFilename := subtitle_filename;
//params for thread
extraction_params.filename := filename;
extraction_params.subtitle_filename := subtitle_filename;
extraction_params.tracknum := track_num;
extraction_params.WindowHandle := window_handle;
//create event for thread
extraction_params.EventHandle := CreateEvent(nil, True, False, 'extraction params read event');
if (extraction_params.EventHandle <> 0) then
begin
//start thread
hThread := CreateThread(nil, 0, @ExtractThread, @extraction_params, 0, thread_id);
if (hThread = 0) then
begin
CloseHandle(extraction_params.EventHandle);
Exit;
end;
//wait while thread reads parameters
WaitForSingleObject(extraction_params.EventHandle, 4000); //4 seconds
CloseHandle(extraction_params.EventHandle);
CloseHandle(hThread);
Result := subtitle_filename;
end;
end;
{$R *.dfm}
{ TfrmMkvExtractor }
procedure TfrmMkvExtractor.OnConsoleData(var msg: TMessage);
const
STR_ID_PROGRESS = 'Progress: ';
STR_ID_END = '%';
var
data: String;
i, j, k: Integer;
begin
//check for interrupt
if FStopEverything then
msg.Result := -1
else
msg.Result := 0;
data := Copy(PChar(msg.lParam), 1, msg.WParam);
i := Pos(STR_ID_PROGRESS, data);
j := Pos(STR_ID_END, data);
if (i > 0) AND (j > 0) then
begin
i := i + Length(STR_ID_PROGRESS);
if TryStrToInt(Copy(data, i, j - i), k) then
begin
ProgressBar1.Position := k;
lblProgress.Caption := Format('%.2d%% complete', [k]) ;
end;
end;
end;
procedure TfrmMkvExtractor.OnExtractionComplete(var msg: TMessage);
begin
if NOT FStopEverything then
begin
OpenVideo;
Close;
end;
end;
function TfrmMkvExtractor.SubtitleWorthy(const filename: String): Boolean;
begin
FStopEverything := False;
Result := GetEnglishSubTrackNum(filename) >= 0;
end;
function TfrmMkvExtractor.StartExtractionAndGetFilename(
const filename: String): String;
begin
FStopEverything := False;
Show;
FMKVFilename := filename;
Result := ExtractSubtitlesTrack(filename,
GetEnglishSubTrackNum(filename), Handle);
end;
procedure TfrmMkvExtractor.btnCancelClick(Sender: TObject);
var
i: Integer;
begin
frmMain.FSkipNextMKVSubtitleCheck := True;
FStopEverything := True;
i := 0;
//TODO: fix this unreliable code
while FileExists(FSubtitleFilename) do
begin
Application.ProcessMessages;
DeleteFile(FSubtitleFilename);
//wait some time while extraction process stops
Sleep(100);
Inc(i);
if (i > 100) then
Break;
end;
OpenVideo;
Close;
end;
procedure TfrmMkvExtractor.OpenVideo;
var
filenames: TStringList;
begin
//reopen file after extraction
filenames := TStringList.Create;
try
filenames.Add(FMKVFilename);
frmMain.OpenFileUI(filenames);
finally
filenames.Free;
end;
end;
end.
|
{..............................................................................}
{ Summary PCB Color Scheme - Demo changing PCB Colors for a PCB document }
{ Copyright (c) 2003 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure SetSchemeDefaults;
Begin
ResetParameters;
AddStringParameter ('TopSignalColor' , '255' );
AddStringParameter ('Mid1Color' , '128' );
AddStringParameter ('Mid2Color' , '32768' );
AddStringParameter ('Mid3Color' , '65280' );
AddStringParameter ('Mid4Color' , '8388608' );
AddStringParameter ('Mid5Color' , '16776960' );
AddStringParameter ('Mid6Color' , '8388736' );
AddStringParameter ('Mid7Color' , '16711935' );
AddStringParameter ('Mid8Color' , '32896' );
AddStringParameter ('Mid9Color' , '65535' );
AddStringParameter ('Mid10Color' , '8421504' );
AddStringParameter ('Mid11Color' , '32768' );
AddStringParameter ('Mid12Color' , '8388736' );
AddStringParameter ('Mid13Color' , '8421376' );
AddStringParameter ('Mid14Color' , '12632256' );
AddStringParameter ('Mid15Color' , '128' );
AddStringParameter ('Mid16Color' , '32768' );
AddStringParameter ('Mid17Color' , '65280' );
AddStringParameter ('Mid18Color' , '8388608' );
AddStringParameter ('Mid19Color' , '16776960' );
AddStringParameter ('Mid20Color' , '8388736' );
AddStringParameter ('Mid21Color' , '16711935' );
AddStringParameter ('Mid22Color' , '32896' );
AddStringParameter ('Mid23Color' , '65535' );
AddStringParameter ('Mid24Color' , '8421504' );
AddStringParameter ('Mid25Color' , '32768' );
AddStringParameter ('Mid26Color' , '8388736' );
AddStringParameter ('Mid27Color' , '8421376' );
AddStringParameter ('Mid28Color' , '12632256' );
AddStringParameter ('Mid29Color' , '128' );
AddStringParameter ('Mid30Color' , '32768' );
AddStringParameter ('BottomSignalColor' , '16711680' );
AddStringParameter ('TopOverlayColor' , '32768' );
AddStringParameter ('BottomOverlayColor' , '7585984' );
AddStringParameter ('TopPasteColor' , '8388736' );
AddStringParameter ('BottomPasteColor' , '128' );
AddStringParameter ('TopSolderColor' , '3162822' );
AddStringParameter ('BottomSolderColor' , '7307173' );
AddStringParameter ('Plane1Color' , '32768' );
AddStringParameter ('Plane2Color' , '128' );
AddStringParameter ('Plane3Color' , '8388736' );
AddStringParameter ('Plane4Color' , '8421376' );
AddStringParameter ('Plane5Color' , '32768' );
AddStringParameter ('Plane6Color' , '128' );
AddStringParameter ('Plane7Color' , '8388736' );
AddStringParameter ('Plane8Color' , '8421376' );
AddStringParameter ('Plane9Color' , '32768' );
AddStringParameter ('Plane10Color' , '128' );
AddStringParameter ('Plane11Color' , '8388736' );
AddStringParameter ('Plane12Color' , '8421376' );
AddStringParameter ('Plane13Color' , '32768' );
AddStringParameter ('Plane14Color' , '128' );
AddStringParameter ('Plane15Color' , '8388736' );
AddStringParameter ('Plane16Color' , '8421376' );
AddStringParameter ('DrillGuideColor' , '128' );
AddStringParameter ('KeepOutColor' , '8388736' );
AddStringParameter ('Mechanical1Color' , '8388736' );
AddStringParameter ('Mechanical2Color' , '8421376' );
AddStringParameter ('Mechanical3Color' , '32768' );
AddStringParameter ('Mechanical4Color' , '0' );
AddStringParameter ('Mechanical5Color' , '8388736' );
AddStringParameter ('Mechanical6Color' , '8421376' );
AddStringParameter ('Mechanical7Color' , '32768' );
AddStringParameter ('Mechanical8Color' , '0' );
AddStringParameter ('Mechanical9Color' , '8388736' );
AddStringParameter ('Mechanical10Color' , '8421376' );
AddStringParameter ('Mechanical11Color' , '32768' );
AddStringParameter ('Mechanical12Color' , '0' );
AddStringParameter ('Mechanical13Color' , '8388736' );
AddStringParameter ('Mechanical14Color' , '8421376' );
AddStringParameter ('Mechanical15Color' , '32768' );
AddStringParameter ('Mechanical16Color' , '0' );
AddStringParameter ('DrillDrawingColor' , '3408013' );
AddStringParameter ('MultiLayerColor' , '8421504' );
AddStringParameter ('ConnectLayerColor' , '7709086' );
AddStringParameter ('BackgroundColor' , '0' );
AddStringParameter ('DRCErrorColor' , '65280' );
AddStringParameter ('SelectionColor' , '65535' );
AddStringParameter ('VisibleGrid1Color' , '12632256' );
AddStringParameter ('VisibleGrid2Color' , '11913679' );
AddStringParameter ('PadHoleColor' , '6899487' );
AddStringParameter ('ViaHoleColor' , '9279142' );
RunProcess ('Pcb:SetupPreferences');
End;
{..............................................................................}
{..............................................................................}
Procedure SetSchemeClassic;
Begin
ResetParameters;
AddStringParameter ('TopSignalColor' , '255' );
AddStringParameter ('Mid1Color' , '128' );
AddStringParameter ('Mid2Color' , '32768' );
AddStringParameter ('Mid3Color' , '65280' );
AddStringParameter ('Mid4Color' , '8388608' );
AddStringParameter ('Mid5Color' , '16776960' );
AddStringParameter ('Mid6Color' , '8388736' );
AddStringParameter ('Mid7Color' , '16711935' );
AddStringParameter ('Mid8Color' , '32896' );
AddStringParameter ('Mid9Color' , '65535' );
AddStringParameter ('Mid10Color' , '8421504' );
AddStringParameter ('Mid11Color' , '16777215' );
AddStringParameter ('Mid12Color' , '8388736' );
AddStringParameter ('Mid13Color' , '8421376' );
AddStringParameter ('Mid14Color' , '12632256' );
AddStringParameter ('Mid15Color' , '128' );
AddStringParameter ('Mid16Color' , '32768' );
AddStringParameter ('Mid17Color' , '65280' );
AddStringParameter ('Mid18Color' , '8388608' );
AddStringParameter ('Mid19Color' , '16776960' );
AddStringParameter ('Mid20Color' , '8388736' );
AddStringParameter ('Mid21Color' , '16711935' );
AddStringParameter ('Mid22Color' , '32896' );
AddStringParameter ('Mid23Color' , '65535' );
AddStringParameter ('Mid24Color' , '8421504' );
AddStringParameter ('Mid25Color' , '16777215' );
AddStringParameter ('Mid26Color' , '8388736' );
AddStringParameter ('Mid27Color' , '8421376' );
AddStringParameter ('Mid28Color' , '12632256' );
AddStringParameter ('Mid29Color' , '128' );
AddStringParameter ('Mid30Color' , '32768' );
AddStringParameter ('BottomSignalColor' , '16711680' );
AddStringParameter ('TopOverlayColor' , '65535' );
AddStringParameter ('BottomOverlayColor' , '32896' );
AddStringParameter ('TopPasteColor' , '8421504' );
AddStringParameter ('BottomPasteColor' , '128' );
AddStringParameter ('TopSolderColor' , '8388736' );
AddStringParameter ('BottomSolderColor' , '16711935' );
AddStringParameter ('Plane1Color' , '32768' );
AddStringParameter ('Plane2Color' , '128' );
AddStringParameter ('Plane3Color' , '8388736' );
AddStringParameter ('Plane4Color' , '8421376' );
AddStringParameter ('Plane5Color' , '32768' );
AddStringParameter ('Plane6Color' , '128' );
AddStringParameter ('Plane7Color' , '8388736' );
AddStringParameter ('Plane8Color' , '8421376' );
AddStringParameter ('Plane9Color' , '32768' );
AddStringParameter ('Plane10Color' , '128' );
AddStringParameter ('Plane11Color' , '8388736' );
AddStringParameter ('Plane12Color' , '8421376' );
AddStringParameter ('Plane13Color' , '32768' );
AddStringParameter ('Plane14Color' , '128' );
AddStringParameter ('Plane15Color' , '8388736' );
AddStringParameter ('Plane16Color' , '8421376' );
AddStringParameter ('DrillGuideColor' , '128' );
AddStringParameter ('KeepOutColor' , '16711935' );
AddStringParameter ('Mechanical1Color' , '16711935' );
AddStringParameter ('Mechanical2Color' , '8388736' );
AddStringParameter ('Mechanical3Color' , '32768' );
AddStringParameter ('Mechanical4Color' , '32896' );
AddStringParameter ('Mechanical5Color' , '16711935' );
AddStringParameter ('Mechanical6Color' , '8388736' );
AddStringParameter ('Mechanical7Color' , '32768' );
AddStringParameter ('Mechanical8Color' , '32896' );
AddStringParameter ('Mechanical9Color' , '16711935' );
AddStringParameter ('Mechanical10Color' , '8388736' );
AddStringParameter ('Mechanical11Color' , '32768' );
AddStringParameter ('Mechanical12Color' , '32896' );
AddStringParameter ('Mechanical13Color' , '16711935' );
AddStringParameter ('Mechanical14Color' , '8388736' );
AddStringParameter ('Mechanical15Color' , '32768' );
AddStringParameter ('Mechanical16Color' , '0' );
AddStringParameter ('DrillDrawingColor' , '2752767' );
AddStringParameter ('MultiLayerColor' , '12632256' );
AddStringParameter ('ConnectLayerColor' , '7709086' );
AddStringParameter ('BackgroundColor' , '0' );
AddStringParameter ('DRCErrorColor' , '65280' );
AddStringParameter ('SelectionColor' , '16777215' );
AddStringParameter ('VisibleGrid1Color' , '6049101' );
AddStringParameter ('VisibleGrid2Color' , '9473425' );
AddStringParameter ('PadHoleColor' , '15461320' );
AddStringParameter ('ViaHoleColor' , '11599871' );
RunProcess ('Pcb:SetupPreferences');
End;
{..............................................................................}
{..............................................................................}
|
unit Demo.Miscellaneous.AxisNumberFormat;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_Miscellaneous_AxisNumberFormat = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_Miscellaneous_AxisNumberFormat.GenerateChart;
procedure SetCommonOptions(Options: TcfsGChartOptions);
begin
Options.Legend('position', 'none');
Options.ChartArea('width', '50%');
Options.Bar('groupWidth', '95%');
Options.DataOpacity(0.3);
Options.VAxis('gridlines', '{ count: 4 }');
Options.VAxis('textStyle', TcfsGChartOptions.TextStyleToJSObject('#0059b3', 12, True, false));
Options.HAxis('textStyle', TcfsGChartOptions.TextStyleToJSObject('Silver', 10, false, false));
end;
var
Data: IcfsGChartData;
Chart1, Chart2, Chart3, Chart4, Chart5, Chart6, Chart7, Chart8: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
// Data
Data := TcfsGChartData.Create;
Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Country'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'GDP')
]);
Data.AddRow(['US', 16768100]);
Data.AddRow(['China', 9181204]);
Data.AddRow(['Japan', 4898532]);
Data.AddRow(['Germany', 3730261]);
Data.AddRow(['France', 2678455]);
// Currency Format
Chart1 := TcfsGChartProducer.Create;
Chart1.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Chart1.Data.Assign(Data);
SetCommonOptions(Chart1.Options);
Chart1.Options.Title('Currency Format');
Chart1.Options.VAxis('format', 'currency');
// Decimal Format
Chart2 := TcfsGChartProducer.Create;
Chart2.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Chart2.Data.Assign(Data);
SetCommonOptions(Chart2.Options);
Chart2.Options.Title('Decimal Format');
Chart2.Options.VAxis('format', 'decimal');
// Long Format
Chart3 := TcfsGChartProducer.Create;
Chart3.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Chart3.Data.Assign(Data);
SetCommonOptions(Chart3.Options);
Chart3.Options.Title('Long Format');
Chart3.Options.VAxis('format', 'long');
// Short Format
Chart4 := TcfsGChartProducer.Create;
Chart4.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Chart4.Data.Assign(Data);
SetCommonOptions(Chart4.Options);
Chart4.Options.Title('Short Format');
Chart4.Options.VAxis('format', 'short');
// Custom Format
Chart5 := TcfsGChartProducer.Create;
Chart5.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Chart5.Data.Assign(Data);
SetCommonOptions(Chart5.Options);
Chart5.Options.Title('Custom Format (0,000.00 $)');
Chart5.Options.VAxis('format', '0,000.00 $');
// Scientific Format
Chart6 := TcfsGChartProducer.Create;
Chart6.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Chart6.Data.Assign(Data);
SetCommonOptions(Chart6.Options);
Chart6.Options.Title('Scientific Format');
Chart6.Options.VAxis('format', 'scientific');
// Percent Format
Chart7 := TcfsGChartProducer.Create;
Chart7.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Chart7.Data.Assign(Data);
SetCommonOptions(Chart7.Options);
Chart7.Options.Title('Percent Format');
Chart7.Options.VAxis('format', 'percent');
// Empty Format
Chart8 := TcfsGChartProducer.Create;
Chart8.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
Chart8.Data.Assign(Data);
SetCommonOptions(Chart8.Options);
Chart8.Options.Title('Empty Format');
Chart8.Options.VAxis('format', '');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div style="display: flex; width: 100%; height: 50%;">'
+ '<div id="Chart1" style="width: 50%"></div>'
+ '<div id="Chart2" style="width: 50%"></div>'
+ '<div id="Chart3" style="width: 50%"></div>'
+ '<div id="Chart4" style="width: 50%"></div>'
+ '</div>'
+ '<div style="display: flex; width: 100%; height: 50%;">'
+ '<div id="Chart5" style="width: 50%"></div>'
+ '<div id="Chart6" style="width: 50%"></div>'
+ '<div id="Chart7" style="width: 50%"></div>'
+ '<div id="Chart8" style="width: 50%"></div>'
+ '</div>'
);
GChartsFrame.DocumentGenerate('Chart1', Chart1);
GChartsFrame.DocumentGenerate('Chart2', Chart2);
GChartsFrame.DocumentGenerate('Chart3', Chart3);
GChartsFrame.DocumentGenerate('Chart4', Chart4);
GChartsFrame.DocumentGenerate('Chart5', Chart5);
GChartsFrame.DocumentGenerate('Chart6', Chart5);
GChartsFrame.DocumentGenerate('Chart6', Chart6);
GChartsFrame.DocumentGenerate('Chart7', Chart7);
GChartsFrame.DocumentGenerate('Chart8', Chart8);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_Miscellaneous_AxisNumberFormat);
end.
|
unit WarodaiMarkers;
{
Функции разбора строки.
Решают, какие в строке встречаются "флаги" (какие маркеры добавлять),
и какие из этих флагов нужно выбросить.
(А какие, возможно, заменить).
Отвечают за разбор:
- Маркеров (<i>кн. уст.</i>)
- Неявных макеров (<i>счётный суф. для круглых предметов</i>)
- Языка (<i>англ. leadership</i>)
- Ссылок (<i>см.</i> <a href="#1-177-2-17">じはつせい</a>)
и связей (<i>ант.</i> <a href="#1-268-2-42">いん【陰】</a>)
Известные типы связей
<i>см.</i> <a href="#1-604-2-61">みしり</a>
<i>ср.</i> <a href="#1-737-1-59">おおみそか</a>
<i>ант.</i> <a href="#1-268-2-42">いん【陰】</a>
Флаги могут идти в любом порядке внутри блока <i></i> либо через пробелы, либо в отд. блоках:
<i>юр.</i>
<i>уст. вежл.</i>
<i>ономат.</i> <i>устар.</i>
Флаги могут смешиваться в одном блоке с не флагами:
<i>кн. см.</i> (номер статьи)
Список известных флагов есть в файле warodai_abrv.dsl, который включён в DSL-сборку словаря.
}
interface
uses Warodai;
{$INCLUDE 'Warodai.inc'}
{
Частицы.
Список частиц вародая доступен в файле warodai_abrv.dsl в DSL-версии словаря,
но не все из них надо считать флагами.
Некоторые остаются в тексте, напр.:
(англ. apple pie) яблочный пирог
Кроме того, нужно детектировать теги с большой осторожностью; напр. встречаются
такие фразы:
<i>после гл. в буд. вр. и наречной формы прил.</i> если даже, хотя бы;
Ни тега "гл." (глагол), ни тега "буд." (буддизм) здесь нет.
Поэтому удаляются только те слова, которые находятся в скобках, где все прочие
слова также определены как теги (не обязательно для удаления).
}
type
TWarodaiTagFlag = (
tfLang, //задаёт язык-источник
tfField, //задаёт область применения
tfLink //задаёт ссылку на другую статью
);
TWarodaiTagFlags = set of TWarodaiTagFlag;
TWarodaiTagDefinition = record
abbr: string;
desc: string;
fl: TWarodaiTagFlags;
edict: string; //в какой тег едикта переводить
end;
const
WD_FLAGS: array[0..166] of TWarodaiTagDefinition = (
(abbr: 'ав.'; desc: 'авиация'; fl: [tfField]; edict: ''),
(abbr: 'авт.'; desc: 'автомобильное дело'; fl: [tfField]; edict: ''),
(abbr: 'альп.'; desc: 'альпинизм'; fl: [tfField]; edict: ''),
(abbr: 'амер.'; desc: 'американизм'; fl: [tfLang]; edict: ''),
(abbr: 'анат.'; desc: 'анатомия'; fl: [tfField]; edict: ''),
(abbr: 'англ.'; desc: 'английский язык'; fl: [tfLang]; edict: ''),
(abbr: 'ант.'; desc: 'антоним'; fl: []; edict: ''),
(abbr: 'антр.'; desc: 'антропология'; fl: [tfField]; edict: ''),
(abbr: 'археол.'; desc: 'археология'; fl: [tfField]; edict: ''),
(abbr: 'архит.'; desc: 'архитектура'; fl: [tfField]; edict: ''),
(abbr: 'астр.'; desc: 'астрономия'; fl: [tfField]; edict: ''),
(abbr: 'биол.'; desc: 'биология'; fl: [tfField]; edict: ''),
(abbr: 'биохим.'; desc: 'биохимия'; fl: [tfField]; edict: ''),
(abbr: 'бирж.'; desc: 'биржевой термин'; fl: [tfField]; edict: ''),
(abbr: 'бот.'; desc: 'ботаника'; fl: [tfField]; edict: ''),
(abbr: 'бран.'; desc: 'бранное слово'; fl: []; edict: 'X'),
(abbr: 'буд.'; desc: 'буддизм'; fl: [tfField]; edict: 'Buddh'),
(abbr: 'букв.'; desc: 'буквально'; fl: []; edict: ''),
(abbr: 'бухг.'; desc: 'бухгалтерия'; fl: [tfField]; edict: ''),
(abbr: 'вежл.'; desc: 'вежливое слово'; fl: []; edict: 'pol'),
(abbr: 'венг.'; desc: 'венгерский язык'; fl: [tfLang]; edict: ''),
(abbr: 'воен.'; desc: 'военный термин'; fl: [tfField]; edict: 'mil'),
(abbr: 'вопр.'; desc: 'вопросительная частица'; fl: []; edict: 'part'), //потеря смысла!
(abbr: 'воскл.'; desc: 'восклицательная частица'; fl: []; edict: 'part'), //потеря смысла!
(abbr: 'геогр.'; desc: 'география'; fl: [tfField]; edict: ''),
(abbr: 'геод.'; desc: 'геодезия'; fl: [tfField]; edict: ''),
(abbr: 'геол.'; desc: 'геология'; fl: [tfField]; edict: ''),
(abbr: 'геом.'; desc: 'геометрия'; fl: [tfField]; edict: 'geom'),
(abbr: 'гидр.'; desc: 'гидрология, гидротехника'; fl: [tfField]; edict: ''),
(abbr: 'гл.'; desc: 'глагол'; fl: []; edict: ''), //TODO: нужно хотя бы пытаться угадать edict-форму глагола по его смыслу
(abbr: 'гол.'; desc: 'голландский язык'; fl: [tfLang]; edict: ''),
(abbr: 'голл.'; desc: 'голландский язык'; fl: [tfLang]; edict: ''),
(abbr: 'горн.'; desc: 'горное дело'; fl: [tfField]; edict: ''),
(abbr: 'грам.'; desc: 'грамматика'; fl: []; edict: 'gram'),
(abbr: 'греч.'; desc: 'греческий язык'; fl: [tfLang]; edict: ''),
(abbr: 'груб.'; desc: 'грубое слово'; fl: []; edict: 'X'),
(abbr: 'дет.'; desc: 'детская речь'; fl: []; edict: 'chn'),
(abbr: 'диал.'; desc: 'диалектизм'; fl: []; edict: ''),
(abbr: 'дип.'; desc: 'дипломатический термин'; fl: [tfField]; edict: ''),
(abbr: 'жарг.'; desc: 'жаргонное слово'; fl: []; edict: 'sl'),
(abbr: 'ж.-д.'; desc: 'железнодорожное дело'; fl: [tfField]; edict: ''),
(abbr: 'женск.'; desc: 'женская речь'; fl: []; edict: 'fem'),
(abbr: 'жив.'; desc: 'живопись'; fl: [tfField]; edict: ''),
(abbr: 'зоол.'; desc: 'зоология'; fl: [tfField]; edict: ''),
(abbr: 'ирон.'; desc: 'в ироническом смысле'; fl: []; edict: ''),
(abbr: 'иск.'; desc: 'искусство'; fl: [tfField]; edict: ''),
(abbr: 'искаж.'; desc: 'искажение'; fl: []; edict: ''),
(abbr: 'исп.'; desc: 'испанский язык'; fl: [tfLang]; edict: ''),
(abbr: 'ист.'; desc: 'исторический термин'; fl: [tfField]; edict: ''),
(abbr: 'ит.'; desc: 'итальянский язык'; fl: [tfLang]; edict: ''),
(abbr: 'итал.'; desc: 'итальянский язык'; fl: [tfLang]; edict: ''),
(abbr: 'ихт.'; desc: 'ихтиология'; fl: [tfField]; edict: ''),
(abbr: 'как опред.'; desc: 'в функции определения'; {修飾語} fl: []; edict: ''),
(abbr: 'как сказ.'; desc: 'в функции сказуемого'; {述語} fl: []; edict: ''),
(abbr: 'карт.'; desc: 'карточный термин'; fl: [tfField]; edict: ''),
(abbr: 'кино'; desc: 'кинематография'; fl: [tfField]; edict: ''),
(abbr: 'кит.'; desc: 'китайский язык'; fl: [tfLang]; edict: ''),
(abbr: 'кн.'; desc: 'книжный стиль'; fl: []; edict: ''),
(abbr: 'ком.'; desc: 'коммерческий термин'; fl: [tfField]; edict: ''),
(abbr: 'кор.'; desc: 'корейский язык'; fl: [tfLang]; edict: ''),
(abbr: 'кул.'; desc: 'кулинария'; fl: [tfField]; edict: 'food'),
(abbr: 'лат.'; desc: 'латинский язык'; fl: [tfLang]; edict: ''),
(abbr: 'лес.'; desc: 'лесное дело'; fl: [tfField]; edict: ''),
(abbr: 'лингв.'; desc: 'лингвистика'; fl: [tfField]; edict: 'ling'),
(abbr: 'лит.'; desc: 'литературоведение'; fl: [tfField]; edict: ''),
(abbr: 'лог.'; desc: 'логика'; fl: [tfField]; edict: ''),
(abbr: 'малайск.'; desc: 'малайский язык'; fl: [tfLang]; edict: ''),
(abbr: 'мат.'; desc: 'математика'; fl: [tfField]; edict: 'math'),
(abbr: 'мед.'; desc: 'медицина'; fl: [tfField]; edict: ''),
(abbr: 'межд.'; desc: 'междометие'; {感動詞} fl: []; edict: 'int'),
(abbr: 'мест.'; desc: 'местоимение'; {代名詞} fl: []; edict: 'pn'),
(abbr: 'метал.'; desc: 'металлургия'; fl: [tfField]; edict: ''),
(abbr: 'метеор.'; desc: 'метеорология'; fl: [tfField]; edict: ''),
(abbr: 'мин.'; desc: 'минералогия'; fl: [tfField]; edict: ''),
(abbr: 'миф.'; desc: 'мифология'; fl: [tfField]; edict: ''),
(abbr: 'мор.'; desc: 'морской термин'; fl: [tfField]; edict: ''),
(abbr: 'муз.'; desc: 'музыка'; fl: [tfField]; edict: ''),
(abbr: 'назв.'; desc: 'название'; fl: []; edict: ''),
(abbr: 'нареч.'; desc: 'наречие'; {副詞} fl: []; edict: 'adv'),
(abbr: 'нем.'; desc: 'немецкий язык'; fl: [tfLang]; edict: ''),
(abbr: 'неперех.'; desc: 'непереходный глагол'; {自動詞} fl: []; edict: 'vi'),
(abbr: 'обр.'; desc: 'образное выражение'; fl: []; edict: 'id'),
(abbr: 'ономат.'; desc: 'ономатопоэтическое слово'; {擬声語} fl: []; edict: 'on-mim'),
(abbr: 'опт.'; desc: 'оптика'; fl: [tfField]; edict: ''),
(abbr: 'орнит.'; desc: 'орнитология'; fl: [tfField]; edict: ''),
(abbr: 'отриц.'; desc: 'отрицание'; fl: []; edict: ''),
(abbr: 'палеонт.'; desc: 'палеонтология'; fl: [tfField]; edict: ''),
(abbr: 'перен.'; desc: 'в переносном значении'; fl: []; edict: 'id'), //потеря смысла!
(abbr: 'перех.'; desc: 'переходный глагол'; {他動詞} fl: []; edict: 'vt'),
(abbr: 'побуд.'; desc: 'побудительный залог'; {使役相} fl: []; edict: ''),
(abbr: 'повел.'; desc: 'повелительное наклонение'; {命令法} fl: []; edict: ''),
(abbr: 'погов.'; desc: 'поговорка'; fl: []; edict: 'expr'), //потеря смысла!
(abbr: 'полигр.'; desc: 'полиграфия'; fl: [tfField]; edict: ''),
(abbr: 'полит.'; desc: 'политический термин'; fl: [tfField]; edict: ''),
(abbr: 'португ.'; desc: 'португальский язык'; fl: [tfLang]; edict: ''),
(abbr: 'посл.'; desc: 'пословица'; fl: []; edict: 'expr'), //потеря смысла!
(abbr: 'постпоз.'; desc: 'постпозиционно'; fl: []; edict: ''),
(abbr: 'постпозиц.'; desc: 'постпозиционно'; fl: []; edict: ''),
(abbr: 'поэт.'; desc: 'поэтическое слово'; fl: []; edict: 'poet'),
(abbr: 'предл.'; desc: 'предложение'; fl: []; edict: 'expr'),
(abbr: 'презр.'; desc: 'презрительно'; fl: []; edict: 'derog'),
(abbr: 'презрит.'; desc: 'презрительно'; fl: []; edict: 'derog'),
(abbr: 'пренебр.'; desc: 'пренебрежительно'; fl: []; edict: 'derog'),
(abbr: 'преф.'; desc: 'префикс'; {接頭辞} fl: []; edict: 'pref'),
(abbr: 'прил.'; desc: 'прилагательное'; fl: []; edict: 'adj'),
(abbr: 'прост.'; desc: 'просторечие'; fl: []; edict: 'vulg'),
(abbr: 'противит.'; desc: 'противительный союз'; {逆説的接続詞} fl: []; edict: ''),
(abbr: 'противоп.'; desc: 'противоположное значение'; fl: []; edict: ''),
(abbr: 'псих.'; desc: 'психология'; fl: [tfField]; edict: ''),
(abbr: 'психол.'; desc: 'психология'; fl: [tfField]; edict: ''),
(abbr: 'радио'; desc: 'радиотехника'; fl: [tfField]; edict: ''),
(abbr: 'разг.'; desc: 'разговорное слово'; fl: []; edict: 'col'),
(abbr: 'рел.'; desc: 'религия'; fl: [tfField]; edict: ''),
(abbr: 'редко'; desc: 'редко'; fl: []; edict: 'rare'),
(abbr: 'русск.'; desc: 'русский язык'; fl: [tfLang]; edict: ''),
(abbr: 'санскр.'; desc: 'санскритский язык'; fl: [tfLang]; edict: ''),
(abbr: 'связ.'; desc: 'связанное употребление'; fl: [tfLink]; edict: ''),
(abbr: 'синт.'; desc: 'относящийся к синтоизму'; fl: [tfField]; edict: ''),
(abbr: 'сказ.'; desc: 'сказуемое'; {述語} fl: []; edict: ''),
(abbr: 'в слож. сл.'; desc: 'в сложных словах'; fl: []; edict: ''),
(abbr: 'в сложн. сл.'; desc: 'в сложных словах'; fl: []; edict: ''),
(abbr: 'сложн. сл.'; desc: 'сложное слово'; fl: []; edict: ''),
(abbr: 'см.'; desc: 'смотри'; fl: [tfLink]; edict: ''),
(abbr: 'соед.'; desc: 'соединительный союз'; {並立的接続詞} fl: []; edict: ''),
(abbr: 'сокр.'; desc: 'сокращение'; fl: []; edict: 'abbr'),
(abbr: 'спорт.'; desc: 'физкультура и спорт'; fl: [tfField]; edict: ''),
(abbr: 'ср.'; desc: 'сравни'; fl: [tfLink]; edict: ''),
(abbr: 'стр.'; desc: 'строительное дело'; fl: [tfField]; edict: ''),
(abbr: 'страд.'; desc: 'страдательный залог'; fl: []; edict: ''),
(abbr: 'студ.'; desc: 'студенческое слово'; fl: [tfField]; edict: ''),
(abbr: 'суф.'; desc: 'суффикс'; {接尾語} fl: []; edict: 'suf'),
(abbr: 'сущ.'; desc: 'имя существительное'; fl: []; edict: 'n'),
(abbr: 'с.-х.'; desc: 'сельское хозяйство'; fl: [tfField]; edict: ''),
(abbr: 'твор.'; desc: 'творительный падеж'; fl: []; edict: ''),
(abbr: 'театр.'; desc: 'театр'; fl: [tfField]; edict: ''),
(abbr: 'телев.'; desc: 'телевидение'; fl: [tfField]; edict: ''),
(abbr: 'телевид.'; desc: 'телевидение'; fl: [tfField]; edict: ''),
(abbr: 'тех.'; desc: 'техника'; fl: [tfField]; edict: ''),
(abbr: 'тж.'; desc: 'также'; fl: [tfLink]; edict: ''),
(abbr: 'топ.'; desc: 'топография'; fl: [tfField]; edict: ''),
(abbr: 'тур.'; desc: 'турецкий язык'; fl: [tfLang]; edict: ''),
(abbr: 'указ.'; desc: 'указательное местоимение'; {指示代名詞} fl: []; edict: ''),
(abbr: 'усил.'; desc: 'усилительная частица'; {強調の助辞} fl: []; edict: ''),
(abbr: 'уст.'; desc: 'устаревшее слово'; fl: []; edict: 'obs'),
(abbr: 'уступ.'; desc: 'уступительная частица'; {譲歩の助辞} fl: []; edict: ''),
(abbr: 'утверд.'; desc: 'утвердительная частица'; {肯定の助辞} fl: []; edict: ''),
(abbr: 'фарм.'; desc: 'фармацевтика'; fl: [tfField]; edict: ''),
(abbr: 'физ.'; desc: 'физика'; fl: [tfField]; edict: 'physics'),
(abbr: 'физиол.'; desc: 'физиология'; fl: [tfField]; edict: ''),
(abbr: 'фил.'; desc: 'философия'; fl: [tfField]; edict: ''),
(abbr: 'филос.'; desc: 'философия'; fl: [tfField]; edict: ''),
(abbr: 'фин.'; desc: 'финансовый термин'; fl: [tfField]; edict: ''),
(abbr: 'фото'; desc: 'фотография'; fl: [tfField]; edict: ''),
(abbr: 'фр.'; desc: 'французский язык'; fl: [tfLang]; edict: ''),
(abbr: 'франц.'; desc: 'французский язык'; fl: [tfLang]; edict: ''),
(abbr: 'хим.'; desc: 'химия'; fl: [tfField]; edict: ''),
(abbr: 'часто'; desc: 'часто'; fl: []; edict: 'pop'), //не уверен
(abbr: 'част.'; desc: 'частица'; {助辞} fl: []; edict: 'prt'),
(abbr: 'числ.'; desc: 'имя числительное'; {数詞} fl: []; edict: 'num'), //не уверен
(abbr: 'числит.'; desc: 'имя числительное'; fl: []; edict: 'num'), //не уверен
(abbr: 'шахм.'; desc: 'термин из шахмат'; fl: [tfField]; edict: ''),
(abbr: 'школ.'; desc: 'школьное слово'; fl: [tfField]; edict: ''),
(abbr: 'эк.'; desc: 'экономика'; fl: [tfField]; edict: ''),
(abbr: 'эл.'; desc: 'электротехника'; fl: [tfField]; edict: ''),
(abbr: 'энт.'; desc: 'энтомология'; fl: [tfField]; edict: ''),
(abbr: 'эпист.'; desc: 'эпистолярный стиль'; fl: []; edict: ''),
(abbr: 'юр.'; desc: 'юридический термин'; fl: [tfField]; edict: '')
);
{
RemoveFormatting()
Удаляет всё html-форматирование из строки, превращая её в голый текст.
}
function RemoveFormatting(const s: string): string;
implementation
uses StrUtils, UniStrUtils;
{
Разбор флагов.
}
type
TBlock = record
i_start: integer; //первый открывающий символ
i_end: integer; //последний закрывающий символ
contents: string;
end;
{ Находит следующий после i_beg блок <s_op...s_ed> в строке и возвращает его. }
function FindNextBlock(const s: string; const s_op, s_ed: string; i_beg: integer; out block: TBlock): boolean;
var i_len: integer;
begin
block.i_start := posex(s_op, s, i_beg);
if block.i_start<=0 then begin
Result := false;
exit;
end;
block.i_end := posex(s_ed, s, block.i_start);
if block.i_end<=0 then begin
Result := false;
exit;
end;
i_len := block.i_end-(block.i_start+Length(s_op));
block.contents := copy(s, block.i_start+Length(s_op), i_len);
block.i_end := block.i_end + Length(s_ed) - 1;
Result := true;
end;
{ Удаляет логический элемент строки с i_op по i_ed включительно. Схлопывает
пробелы и т.п.
Вызывать можно не только для блоков, полученных из FindNextBlock. }
procedure DeleteBlock(var s: string; i_op, i_ed: integer);
var had_spaces: boolean;
begin
//Удаляем пробелы по обе стороны от вырезанного куска, чтобы не получалось длинных дыр
had_spaces := false;
while (i_op>1) and (s[i_op-1]=' ') do begin
had_spaces := true;
Dec(i_op);
end;
while (i_ed<Length(s)) and (s[i_ed+1]=' ') do begin
had_spaces := true;
Inc(i_ed);
end;
//оставляем один пробел, если только блок не впритык к краю (там пробелов не нужно)
if had_spaces and (i_op<>1) and (i_ed<>Length(s)) then
if (s[i_op]=' ') then Inc(i_op) else Dec(i_ed);
delete(s, i_op, i_ed-i_op+1);
end;
procedure SkipSpaces(const s: string; var i_pos: integer);
begin
while (i_pos<=Length(s)) and (s[i_pos]=' ') do
Inc(i_pos);
end;
{ Находит самое длинное совпадение среди флагов для текста, идущего в строке s
начиная с положения i_pos.
Пробелы пропускает.
Возвращает -1, если дальнейших совпадений нет. }
function FindNextFlag(const s: string; var i_pos: integer): integer;
var i: integer;
max_len: integer;
begin
Result := -1;
max_len := 0;
SkipSpaces(s, i_pos);
if i_pos>Length(s) then exit;
for i := 0 to Length(WD_FLAGS) - 1 do
if StrMatch(PChar(@s[i_pos]), PChar(WD_FLAGS[i].abbr))=Length(WD_FLAGS[i].abbr) then
if (Result<0) or (max_len<Length(WD_FLAGS[i].abbr)) then
begin
Result := i;
max_len := Length(WD_FLAGS[i].abbr);
end;
if Result>=0 then begin
i_pos := i_pos + Length(WD_FLAGS[Result].abbr);
SkipSpaces(s, i_pos); //на случай если там завершающие пробелы
end;
end;
{ True, если это был флаг-блок, мы все флаги разобрали, и блок надо удалить.
False, если разобрать блок не получилось, его надо оставить в покое, а fl не использовать }
{
function ParseFlags(const s: string; out fl: TFlags): boolean;
var block_pos: integer;
flag: integer;
flags_this_block
begin
SetLength(fl, 0);
if Trim(s)='' then begin
Result := true;
exit;
end;
flags_this_block := 0;
block_pos := 1;
flag := FindNextFlag(block.contents, block_pos);
while flag>=0 do begin
end;
end;
function ExtractFlags(var s: string): TFlags;
var block: TBlock;
i_pos: integer;
fl: TFlags;
i: integer;
begin
SetLength(Result, 0);
i_pos := 1;
while FindNextBlock(s, '<i>', '</i>', i_pos, block) do begin
if ParseFlags(block.contents, fl) then begin
SetLength(Result, Length(Result)+Length(flags));
for i := 0 to Length(fl) - 1 do
DeleteBlock(block.i_start, block.i_end);
end else
i_pos := block.i_end+1;
end;
end;
}
{ Находит блок, удаляет его и возвращает содержимое }
function RemoveBlock(var s: string; const s_op, s_ed: string; i_beg: integer; out contents: string): boolean;
var block: TBlock;
begin
Result := FindNextBlock(s, s_op, s_ed, i_beg, block);
if not Result then exit;
contents := block.contents;
DeleteBlock(s, block.i_start, block.i_end);
Result := true;
end;
function RemoveFormatting(const s: string): string;
var tag: string;
begin
Result := s;
while RemoveBlock(Result, '<', '>', 1, tag) do begin end;
end;
end.
|
unit LazyInitLib;
interface
uses
System.SysUtils, System.Generics.Collections, System.Classes;
type
ILazyInit<T> = interface
['{C2ECA0DA-B938-4015-813D-8D8709BF2D64}']
function Value: T;
end;
ILazyInitializing = interface
['{CE406453-7C8F-4DB8-85CF-F8E2A3634AFC}']
procedure DoInitialize;
end;
ILazyGroup = interface
['{5BA3B0DD-39AD-4623-B939-CAD25BAEC49F}']
procedure DoInitialize;
procedure RegisterLazy(lazy: ILazyInitializing);
end;
TLazyInit<T> = class(TInterfacedObject, ILazyInit<T>, ILazyInitializing)
private
FIsInit: Boolean;
FValue: T;
FGetValueFunction: TFunc<T>;
FGroup: ILazyGroup;
procedure DoInitialize;
public
constructor Create(GetValueFunc: TFunc<T>);overload;
constructor Create(GetValueFunc: TFunc<T>; group: ILazyGroup);overload;
destructor Destroy; override;
function Value: T;
end;
TInternalThread<T> = class(TThread)
private
FLoadFunction: TFunc<T>;
FOnDone: TProc<T>;
public
constructor Create(Load: TFunc<T>; OnDone: TProc<T>);
procedure Execute; override;
end;
TLazyInitAsync<T> = class(TInterfacedObject, ILazyInit<T>)
private
FInitThread: TInternalThread<T>;
FValue: T;
FGetValueFunction: TFunc<T>;
public
constructor Create(GetValueFunc: TFunc<T>);
destructor Destroy; override;
function Value: T;
end;
LazyFactory = record
class function NewGroup: ILazyGroup; static;
end;
implementation
type
TLazyGroup = class(TInterfacedObject, ILazyGroup)
private
FLazys: TList<ILazyInitializing>;
public
constructor Create;
destructor Destroy; override;
procedure DoInitialize;
procedure RegisterLazy(lazy: ILazyInitializing);
end;
{ TLazyInit<T> }
constructor TLazyInit<T>.Create(GetValueFunc: TFunc<T>);
begin
FGetValueFunction := GetValueFunc;
FIsInit := false;
FGroup := nil;
end;
constructor TLazyInit<T>.Create(GetValueFunc: TFunc<T>; group: ILazyGroup);
begin
Create(GetValueFunc);
FGroup := group;
FGroup.RegisterLazy(Self);
end;
destructor TLazyInit<T>.Destroy;
begin
FGroup := nil;
inherited;
end;
procedure TLazyInit<T>.DoInitialize;
begin
if not FIsInit then
begin
FValue := FGetValueFunction;
FIsInit := true;
if FGroup <> nil then FGroup.DoInitialize;
end;
end;
function TLazyInit<T>.Value: T;
begin
DoInitialize;
Result := FValue;
end;
{ TLazyGroup }
constructor TLazyGroup.Create;
begin
FLazys := TList<ILazyInitializing>.Create;
end;
destructor TLazyGroup.Destroy;
begin
FLazys.Free;
inherited;
end;
procedure TLazyGroup.DoInitialize;
var
lazy: ILazyInitializing;
begin
for lazy in FLazys do
begin
lazy.DoInitialize;
end;
FLazys.Clear;
end;
procedure TLazyGroup.RegisterLazy(lazy: ILazyInitializing);
begin
FLazys.Add(lazy);
end;
{ LazyFactory }
class function LazyFactory.NewGroup: ILazyGroup;
begin
Result := TLazyGroup.Create;
end;
{ TLazyInitAsync<T> }
constructor TLazyInitAsync<T>.Create(GetValueFunc: TFunc<T>);
begin
FGetValueFunction := GetValueFunc;
FInitThread := TInternalThread<T>.Create(FGetValueFunction,
procedure(value: T)
begin
FValue := value;
end);
end;
destructor TLazyInitAsync<T>.Destroy;
begin
FInitThread.Free;
inherited;
end;
function TLazyInitAsync<T>.Value: T;
begin
if not FInitThread.Finished then FInitThread.WaitFor;
Result := FValue;
end;
{ TInternalThread<T> }
constructor TInternalThread<T>.Create(Load: TFunc<T>; OnDone: TProc<T>);
begin
inherited Create(false);
FLoadFunction := Load;
FOnDone := OnDone;
end;
procedure TInternalThread<T>.Execute;
var
tmpValue: T;
begin
inherited;
tmpValue := FLoadFunction;
Queue(
procedure
begin
FOnDone(tmpValue);
end);
end;
end.
|
unit LrActionController;
interface
uses
SysUtils, Classes, ActnList, ImgList, Controls, Dialogs,
PngImageList,
LrDocument;
type
TLrActionControllerModule = class(TDataModule)
ActionList: TActionList;
PngImageList: TPngImageList;
LrOpenAction: TAction;
LrNewAction: TAction;
LrSaveAction: TAction;
LrSaveAsAction: TAction;
LrCloseAction: TAction;
LrCloseAll: TAction;
SaveDialog: TSaveDialog;
OpenDialog: TOpenDialog;
procedure LrSaveActionUpdate(Sender: TObject);
procedure LrSaveActionExecute(Sender: TObject);
procedure LrSaveAsActionExecute(Sender: TObject);
procedure LrCloseActionExecute(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure LrOpenActionExecute(Sender: TObject);
private
{ Private declarations }
FDocumentTypes: TStringList;
function BuildFileFilter: string;
function GetDocument: TLrDocument;
procedure SaveDocumentAs;
public
{ Public declarations }
property Document: TLrDocument read GetDocument;
procedure RegisterDocument(inDocumentType: TLrDocumentClass);
end;
var
LrActionControllerModule: TLrActionControllerModule;
implementation
uses
LrOpenDocumentsController;
{$R *.dfm}
procedure TLrActionControllerModule.DataModuleCreate(Sender: TObject);
begin
FDocumentTypes := TStringList.Create;
end;
procedure TLrActionControllerModule.DataModuleDestroy(Sender: TObject);
begin
FDocumentTypes.Free;
end;
procedure TLrActionControllerModule.RegisterDocument(
inDocumentType: TLrDocumentClass);
begin
FDocumentTypes.AddObject(inDocumentType.GetExt, TObject(inDocumentType));
end;
function TLrActionControllerModule.GetDocument: TLrDocument;
begin
Result := LrOpenDocuments.Current;
end;
procedure TLrActionControllerModule.SaveDocumentAs;
begin
Document.SaveAs(SaveDialog);
end;
procedure TLrActionControllerModule.LrSaveActionUpdate(Sender: TObject);
begin
TAction(Sender).Enabled := Document.Modified;
end;
procedure TLrActionControllerModule.LrSaveActionExecute(Sender: TObject);
begin
if Document.Untitled then
SaveDocumentAs
else
Document.Save;
end;
procedure TLrActionControllerModule.LrSaveAsActionExecute(Sender: TObject);
begin
SaveDocumentAs;
end;
procedure TLrActionControllerModule.LrCloseActionExecute(Sender: TObject);
begin
LrOpenDocuments.CloseCurrent;
end;
function TLrActionControllerModule.BuildFileFilter: string;
var
i: Integer;
e, exts: string;
begin
Result := '';
exts := '';
with FDocumentTypes do
for i := 0 to Pred(Count) do
begin
e := '*.' + Strings[i];
exts := exts + e + ';';
Result := Result + Format('%s (%s)|%1:s|',
[ TLrDocumentClass(Objects[i]).GetDescription, e ]);
end;
Result := Format('IDE Documents (%s)|%0:s|', [ exts ]) + Result;
end;
procedure TLrActionControllerModule.LrOpenActionExecute(Sender: TObject);
begin
OpenDialog.Filter := BuildFileFilter;
with OpenDialog do
if Execute then
begin
end;
end;
end.
|
unit uDMImportPetTextFile;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDMImportTextFile, uDMImportPet, uPetClasses, DB, DBClient,
ADODB;
type
TDMImportPetTextFile = class(TDMImportTextFile)
cdsPetTreatment: TClientDataSet;
cdsPetTreatmentSKU: TStringField;
cdsPetTreatmentMicrochip: TStringField;
cdsPetTreatmentCollar: TStringField;
cdsPetTreatmentTreatment: TStringField;
cdsPetTreatmentTreatmentType: TIntegerField;
cdsPetTreatmentMfg: TStringField;
cdsPetTreatmentTreatmentLotSize: TIntegerField;
cdsPetTreatmentLotNumber: TStringField;
cdsPetTreatmentLotExpirationDate: TDateTimeField;
cdsPetTreatmentIDUser: TIntegerField;
cdsPetTreatmentDosesUsed: TIntegerField;
cdsPetTreatmentTreatExpirationDate: TDateTimeField;
cdsPetTreatmentTreatmentDate: TDateTimeField;
cdsPetTreatmentNotes: TStringField;
cdsPetTreatmentSpecies: TStringField;
procedure DataModuleDestroy(Sender: TObject);
private
FDMImportPet : TDMImportPet;
function GetPetTreatmen(ACollar, AMicrochip : String) : TStringList;
protected
procedure BeforeImport; override;
procedure ImportLine; override;
public
{ Public declarations }
end;
implementation
{$R *.dfm}
{ TDMImportPetTextFile }
procedure TDMImportPetTextFile.BeforeImport;
begin
inherited;
FDMImportPet := TDMImportPet.Create(self);
FDMImportPet.SQLConnection := Self.SQLConnection;
end;
procedure TDMImportPetTextFile.ImportLine;
var
FPetImportInfo : TPetImportInfo;
begin
inherited;
FPetImportInfo := TPetImportInfo.Create;
try
with FPetImportInfo do
begin
SKU := VarToStr(GetParamValue('SKU'));
Species := VarToStr(GetParamValue('Species'));
Sex := VarToStr(GetParamValue('Sex'));
Breed := VarToStr(GetParamValue('Breed'));
Breeder := VarToStr(GetParamValue('Breeder'));
BreederAddress := VarToStr(GetParamValue('BreederAddress'));
BreederCity := VarToStr(GetParamValue('BreederCity'));
BreederState := VarToStr(GetParamValue('BreederState'));
BreederZip := VarToStr(GetParamValue('BreederZip'));
MicrochipBrand := VarToStr(GetParamValue('MicrochipBrand'));
Microchip := VarToStr(GetParamValue('Microchip'));
PenNumber := VarToStr(GetParamValue('PenNumber'));
VendorCost := GetParamCurrency('VendorCost');
MSRP := GetParamCurrency('MSRP');
SalePrice := GetParamCurrency('SalePrice');
PromoPrice := GetParamCurrency('PromoPrice');
Whelpdate := GetParamDateTime('Whelpdate');
PurchaseDate := GetParamDateTime('PurchaseDate');
WeightDate := GetParamDateTime('WeightDate');
USDA := VarToStr(GetParamValue('USDA'));
Collar := VarToStr(GetParamValue('Collar'));
Sire := VarToStr(GetParamValue('Sire'));
Dam := VarToStr(GetParamValue('Dam'));
Notes := VarToStr(GetParamValue('Notes'));
Color := VarToStr(GetParamValue('Color'));
Status := VarToStr(GetParamValue('Status'));
Weight := GetParamCurrency('Weight');
Registry := VarToStr(GetParamValue('Registry'));
RegistryNumber := VarToStr(GetParamValue('RegistryNumber'));
TreatmentList := GetPetTreatmen(Collar, Microchip);
end;
FDMImportPet.ImportPetInfo(FPetImportInfo);
finally
FreeAndNil(FPetImportInfo.TreatmentList);
FreeAndNil(FPetImportInfo);
end;
end;
procedure TDMImportPetTextFile.DataModuleDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FDMImportPet);
end;
function TDMImportPetTextFile.GetPetTreatmen(ACollar,
AMicrochip: String): TStringList;
var
FAnimalTreatment : TAnimalTreatment;
begin
Result := TStringList.Create;
try
cdsPetTreatment.Filter := 'Collar = ' + QuotedStr(ACollar);
cdsPetTreatment.Filtered := True;
if not cdsPetTreatment.IsEmpty then
begin
cdsPetTreatment.First;
while not cdsPetTreatment.Eof do
begin
FAnimalTreatment := TAnimalTreatment.Create;
FAnimalTreatment.Treatment := cdsPetTreatment.FieldByName('Treatment').AsString;
FAnimalTreatment.TreatmentType := cdsPetTreatment.FieldByName('TreatmentType').AsInteger;
FAnimalTreatment.Mfg := cdsPetTreatment.FieldByName('Mfg').AsString;
FAnimalTreatment.TreatmentLotSize := cdsPetTreatment.FieldByName('TreatmentLotSize').AsInteger;
FAnimalTreatment.IDUser := cdsPetTreatment.FieldByName('IDUser').AsInteger;
FAnimalTreatment.Notes := cdsPetTreatment.FieldByName('Notes').AsString;
FAnimalTreatment.TreatmentDate := cdsPetTreatment.FieldByName('TreatmentDate').AsDateTime;
if (cdsPetTreatment.FieldByName('LotNumber').AsString <> '') then
begin
FAnimalTreatment.AnimalTreatmentLot := TAnimalTreatmentLot.Create;
FAnimalTreatment.AnimalTreatmentLot.LotNumber := cdsPetTreatment.FieldByName('LotNumber').AsString;
FAnimalTreatment.AnimalTreatmentLot.ExpirationDate := cdsPetTreatment.FieldByName('LotExpirationDate').AsDateTime;
end;
Result.AddObject('', FAnimalTreatment);
cdsPetTreatment.Next;
end;
end;
finally
cdsPetTreatment.Filtered := False;
cdsPetTreatment.Filter := '';
end;
end;
end.
|
unit Unit_PeoplePriv_Consts;
interface
resourcestring
//Общее
FZ_PeoplePriv_Caption = 'Що користуються льготами';
FZ_PeoplePriv_InsertChildBtn_Caption = 'Додати';
FZ_PeoplePriv_UpdateChildBtn_Caption = 'Редагувати';
FZ_PeoplePriv_DeleteChildBtn_Caption = 'Видалити';
FZ_PeoplePriv_DetailChildBtn_Caption = 'Перегляд';
FZ_PeoplePriv_OtherBtn_Caption = 'Додати особу';
FZ_PeoplePriv_RefreshBtn_Caption = 'Поновити';
FZ_PeoplePriv_ExitBtn_Caption = 'Вийти';
FZ_PeoplePriv_Page_Idman_Caption = 'Льготи обраної фізичної особи';
FZ_PeoplePriv_Error_Caption = 'Помилка';
FZ_PeoplePriv_Grid_FIO_ColumnTn_Caption = 'Т.н.';
FZ_PeoplePriv_Grid_FIO_ColumnFIO_Caption = 'Прізвище, ім''я, по-батькові';
FZ_PeoplePriv_Grid_PeoplePriv_Column_PrivKod_Caption = 'Код';
FZ_PeoplePriv_Grid_PeoplePriv_Column_Privname_Caption = 'Назва льготи';
FZ_PeoplePriv_Grid_PeoplePriv_Column_DateBeg_Caption = 'Початок';
FZ_PeoplePriv_Grid_PeoplePriv_Column_DateEnd_Caption = 'Закінчення';
FZ_PeoplePriv_Grid_PeoplePriv_Column_Expense_Caption = 'Кількість';
implementation
end.
|
unit UnitResampleFilters;
interface
uses
Math,
Windows,
Graphics,
SysUtils,
Dmitry.Graphics.Types,
uMath,
uEditorTypes;
// Sample filters for use with Stretch()
function SplineFilter(Value: Single): Single; inline;
function BellFilter(Value: Single): Single; inline;
function TriangleFilter(Value: Single): Single; inline;
function BoxFilter(Value: Single): Single; inline;
function HermiteFilter(Value: Single): Single; inline;
function Lanczos3Filter(Value: Single): Single; inline;
function MitchellFilter(Value: Single): Single; inline;
{$DEFINE USE_SCANLINE}
const
MaxPixelCount = 32768;
// -----------------------------------------------------------------------------
//
// List of Filters
//
// -----------------------------------------------------------------------------
type
TFilterProc = function(Value: Single): Single;
const
ResampleFilters: array[0..6] of record
Name: string; // Filter name
Filter: TFilterProc;// Filter implementation
Width: Single; // Suggested sampling width/radius
end = (
(Name: 'Box'; Filter: BoxFilter; Width: 0.5),
(Name: 'Triangle'; Filter: TriangleFilter; Width: 1.0),
(Name: 'Hermite'; Filter: HermiteFilter; Width: 1.0),
(Name: 'Bell'; Filter: BellFilter; Width: 1.5),
(Name: 'B-Spline'; Filter: SplineFilter; Width: 2.0),
(Name: 'Lanczos3'; Filter: Lanczos3Filter; Width: 3.0),
(Name: 'Mitchell'; Filter: MitchellFilter; Width: 2.0)
);
procedure Strecth(Src, Dst: TBitmap; filter: TFilterProc;
fwidth: single; CallBack : TProgressCallBackProc = nil);
type
// Contributor for a pixel
TContributor = record
pixel: integer; // Source pixel
weight: single; // Pixel weight
end;
TContributorList = array[0..0] of TContributor;
PContributorList = ^TContributorList;
// List of source pixels contributing to a destination pixel
TCList = record
n : integer;
p : PContributorList;
end;
TCListList = array[0..0] of TCList;
PCListList = ^TCListList;
TRGB = packed record
r, g, b : single;
end;
// Physical bitmap pixel
TColorRGB = packed record
r, g, b : BYTE;
end;
PColorRGB = ^TColorRGB;
// Physical bitmap scanline (row)
TRGBList = packed array[0..0] of TColorRGB;
PRGBList = ^TRGBList;
type
TRGBTripleArray = ARRAY[0..MaxPixelCount-1] OF
TRGBTriple;
pRGBTripleArray = ^TRGBTripleArray;
TFColor=record
b,g,r: Byte;
end;
implementation
// Bell filter
function BellFilter(Value: Single): Single;
begin
if Value < 0 then
Value := - Value;
if (Value < 0.5) then
Result := 0.75 - Sqr(Value)
else if (Value < 1.5) then
begin
Value := Value - 1.5;
Result := 0.5 * Sqr(Value);
end else
Result := 0.0;
end;
// Box filter
// a.k.a. "Nearest Neighbour" filter
// anme: I have not been able to get acceptable
// results with this filter for subsampling.
function BoxFilter(Value: Single): Single;
begin
if (Value > -0.5) and (Value <= 0.5) then
Result := 1.0
else
Result := 0.0;
end;
// Hermite filter
function HermiteFilter(Value: Single): Single;
begin
// f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1
if Value < 0 then
Value := - Value;
if (Value < 1.0) then
Result := (2.0 * Value - 3.0) * Sqr(Value) + 1.0
else
Result := 0.0;
end;
// Lanczos3 filter
function Lanczos3Filter(Value: Single): Single;
function SinC(Value: Single): Single; inline;
begin
if (Value <> 0.0) then
begin
Value := Value * Pi;
Result := Sin(Value) / Value
end else
Result := 1.0;
end;
begin
if Value < 0 then
Value := - Value;
if (Value < 3.0) then
Result := SinC(Value) * SinC(Value / 3.0)
else
Result := 0.0;
end;
function MitchellFilter(Value: Single): Single;
const
B = (1.0 / 3.0);
C = (1.0 / 3.0);
var
tt : single;
begin
if Value < 0 then
Value := - Value;
tt := Sqr(Value);
if (Value < 1.0) then
begin
Value := (((12.0 - 9.0 * B - 6.0 * C) * (Value * tt))
+ ((-18.0 + 12.0 * B + 6.0 * C) * tt)
+ (6.0 - 2 * B));
Result := Value / 6.0;
end else
if (Value < 2.0) then
begin
Value := (((-1.0 * B - 6.0 * C) * (Value * tt))
+ ((6.0 * B + 30.0 * C) * tt)
+ ((-12.0 * B - 48.0 * C) * Value)
+ (8.0 * B + 24 * C));
Result := Value / 6.0;
end else
Result := 0.0;
end;
// B-spline filter
function SplineFilter(Value: Single): Single;
var
tt : single;
begin
if Value < 0 then
Value := - Value;
if (Value < 1.0) then
begin
tt := Sqr(Value);
Result := 0.5*tt*Value - tt + 2.0 / 3.0;
end else if (Value < 2.0) then
begin
Value := 2.0 - Value;
Result := 1.0/6.0 * Sqr(Value) * Value;
end else
Result := 0.0;
end;
// Triangle filter
// a.k.a. "Linear" or "Bilinear" filter
function TriangleFilter(Value: Single): Single;
begin
if (Value < 0.0) then
Value := -Value;
if (Value < 1.0) then
Result := 1.0 - Value
else
Result := 0.0;
end;
procedure Strecth(Src, Dst: TBitmap; filter: TFilterProc;
fwidth: single; CallBack : TProgressCallBackProc = nil);
var
xscale, yscale : single; // Zoom scale factors
i, j, k : integer; // Loop variables
center : single; // Filter calculation variables
width, fscale, weight : single; // Filter calculation variables
left, right : integer; // Filter calculation variables
n : integer; // Pixel number
Work : TBitmap;
contrib : PCListList;
rgb : TRGB;
color : TColorRGB;
{$IFDEF USE_SCANLINE}
SourceLine ,
DestLine : PRGBList;
SourcePixel ,
DestPixel : PColorRGB;
Delta ,
DestDelta : integer;
{$ENDIF}
SrcWidth ,
SrcHeight ,
DstWidth ,
DstHeight : integer;
Terminating : boolean;
function Color2RGB(Color: TColor): TColorRGB;
begin
Result.r := Color AND $000000FF;
Result.g := (Color AND $0000FF00) SHR 8;
Result.b := (Color AND $00FF0000) SHR 16;
end;
function RGB2Color(Color: TColorRGB): TColor;
begin
Result := Color.r OR (Color.g SHL 8) OR (Color.b SHL 16);
end;
begin
{$R-}
Terminating:=false;
DstWidth := Dst.Width;
DstHeight := Dst.Height;
SrcWidth := Src.Width;
SrcHeight := Src.Height;
if (SrcWidth < 1) or (SrcHeight < 1) then
raise Exception.Create('Source bitmap too small');
// Create intermediate image to hold horizontal zoom
Work := TBitmap.Create;
try
Work.SetSize(DstWidth, SrcHeight);
// xscale := DstWidth / SrcWidth;
// yscale := DstHeight / SrcHeight;
// Improvement suggested by David Ullrich:
if (SrcWidth = 1) then
xscale:= DstWidth / SrcWidth
else
xscale:= (DstWidth - 1) / (SrcWidth - 1);
if (SrcHeight = 1) then
yscale:= DstHeight / SrcHeight
else
yscale:= (DstHeight - 1) / (SrcHeight - 1);
// This implementation only works on 24-bit images because it uses
// TBitmap.Scanline
{$IFDEF USE_SCANLINE}
Src.PixelFormat := pf24bit;
Dst.PixelFormat := Src.PixelFormat;
Work.PixelFormat := Src.PixelFormat;
{$ENDIF}
// --------------------------------------------
// Pre-calculate filter contributions for a row
// -----------------------------------------------
GetMem(contrib, DstWidth* sizeof(TCList));
// Horizontal sub-sampling
// Scales from bigger to smaller width
if (xscale < 1.0) then
begin
width := fwidth / xscale;
fscale := 1.0 / xscale;
for i := 0 to DstWidth-1 do
begin
contrib^[i].n := 0;
GetMem(contrib^[i].p, FastTrunc(width * 2.0 + 1) * sizeof(TContributor));
center := i / xscale;
// Original code:
// left := FastCeil(center - width);
// right := FastFloor(center + width);
left := FastFloor(center - width);
right := FastCeil(center + width);
for j := left to right do
begin
weight := filter((center - j) / fscale) / fscale;
if (weight = 0.0) then
continue;
if (j < 0) then
n := -j
else if (j >= SrcWidth) then
n := SrcWidth - j + SrcWidth - 1
else
n := j;
k := contrib^[i].n;
contrib^[i].n := contrib^[i].n + 1;
contrib^[i].p^[k].pixel := n;
contrib^[i].p^[k].weight := weight;
end;
end;
end else
// Horizontal super-sampling
// Scales from smaller to bigger width
begin
for i := 0 to DstWidth-1 do
begin
contrib^[i].n := 0;
GetMem(contrib^[i].p, FastTrunc(fwidth * 2.0 + 1) * sizeof(TContributor));
center := i / xscale;
// Original code:
// left := FastCeil(center - fwidth);
// right := FastFloor(center + fwidth);
left := FastFloor(center - fwidth);
right := FastCeil(center + fwidth);
for j := left to right do
begin
weight := filter(center - j);
if (weight = 0.0) then
continue;
if (j < 0) then
n := -j
else if (j >= SrcWidth) then
n := SrcWidth - j + SrcWidth - 1
else
n := j;
k := contrib^[i].n;
contrib^[i].n := contrib^[i].n + 1;
contrib^[i].p^[k].pixel := n;
contrib^[i].p^[k].weight := weight;
end;
end;
end;
// ----------------------------------------------------
// Apply filter to sample horizontally from Src to Work
// ----------------------------------------------------
for k := 0 to SrcHeight-1 do
begin
{$IFDEF USE_SCANLINE}
SourceLine := Src.ScanLine[k];
DestPixel := Work.ScanLine[k];
{$ENDIF}
for i := 0 to DstWidth-1 do
begin
rgb.r := 0.0;
rgb.g := 0.0;
rgb.b := 0.0;
for j := 0 to contrib^[i].n-1 do
begin
{$IFDEF USE_SCANLINE}
color := SourceLine^[contrib^[i].p^[j].pixel];
{$ELSE}
color := Color2RGB(Src.Canvas.Pixels[contrib^[i].p^[j].pixel, k]);
{$ENDIF}
weight := contrib^[i].p^[j].weight;
if (weight = 0.0) then
continue;
rgb.r := rgb.r + color.r * weight;
rgb.g := rgb.g + color.g * weight;
rgb.b := rgb.b + color.b * weight;
end;
if (rgb.r > 255.0) then
color.r := 255
else if (rgb.r < 0.0) then
color.r := 0
else
color.r := Round(rgb.r);
if (rgb.g > 255.0) then
color.g := 255
else if (rgb.g < 0.0) then
color.g := 0
else
color.g := Round(rgb.g);
if (rgb.b > 255.0) then
color.b := 255
else if (rgb.b < 0.0) then
color.b := 0
else
color.b := Round(rgb.b);
{$IFDEF USE_SCANLINE}
// Set new pixel value
DestPixel^ := color;
// Move on to next column
inc(DestPixel);
{$ELSE}
Work.Canvas.Pixels[i, k] := RGB2Color(color);
{$ENDIF}
end;
if K mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(50 * K / SrcHeight), Terminating);
if Terminating then
Break;
end;
// Free the memory allocated for horizontal filter weights
for i := 0 to DstWidth-1 do
FreeMem(contrib^[i].p);
FreeMem(contrib);
// -----------------------------------------------
// Pre-calculate filter contributions for a column
// -----------------------------------------------
GetMem(contrib, DstHeight* sizeof(TCList));
// Vertical sub-sampling
// Scales from bigger to smaller height
if (yscale < 1.0) then
begin
width := fwidth / yscale;
fscale := 1.0 / yscale;
for i := 0 to DstHeight-1 do
begin
contrib^[i].n := 0;
GetMem(contrib^[i].p, FastTrunc(width * 2.0 + 1) * sizeof(TContributor));
center := i / yscale;
// Original code:
// left := FastCeil(center - width);
// right := FastFloor(center + width);
left := FastFloor(center - width);
right := FastCeil(center + width);
for j := left to right do
begin
weight := filter((center - j) / fscale) / fscale;
if (weight = 0.0) then
continue;
if (j < 0) then
n := -j
else if (j >= SrcHeight) then
n := SrcHeight - j + SrcHeight - 1
else
n := j;
k := contrib^[i].n;
contrib^[i].n := contrib^[i].n + 1;
contrib^[i].p^[k].pixel := n;
contrib^[i].p^[k].weight := weight;
end;
end
end else
// Vertical super-sampling
// Scales from smaller to bigger height
begin
for i := 0 to DstHeight-1 do
begin
contrib^[i].n := 0;
GetMem(contrib^[i].p, FastTrunc(fwidth * 2.0 + 1) * sizeof(TContributor));
center := i / yscale;
// Original code:
// left := FastCeil(center - fwidth);
// right := FastFloor(center + fwidth);
left := FastFloor(center - fwidth);
right := FastCeil(center + fwidth);
for j := left to right do
begin
weight := filter(center - j);
if (weight = 0.0) then
continue;
if (j < 0) then
n := -j
else if (j >= SrcHeight) then
n := SrcHeight - j + SrcHeight - 1
else
n := j;
k := contrib^[i].n;
contrib^[i].n := contrib^[i].n + 1;
contrib^[i].p^[k].pixel := n;
contrib^[i].p^[k].weight := weight;
end;
if K mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(50 * K / DstHeight), Terminating);
if Terminating then
Break;
end;
end;
// --------------------------------------------------
// Apply filter to sample vertically from Work to Dst
// --------------------------------------------------
{$IFDEF USE_SCANLINE}
SourceLine := Work.ScanLine[0];
Delta := 0;
if Work.Height > 1 then
Delta := NativeInt(Work.ScanLine[1]) - NativeInt(SourceLine);
DestLine := Dst.ScanLine[0];
DestDelta := 0;
if Dst.Height > 1 then
DestDelta := NativeInt(Dst.ScanLine[1]) - NativeInt(DestLine);
{$ENDIF}
for k := 0 to DstWidth-1 do
begin
{$IFDEF USE_SCANLINE}
DestPixel := pointer(DestLine);
{$ENDIF}
for i := 0 to DstHeight-1 do
begin
rgb.r := 0;
rgb.g := 0;
rgb.b := 0;
// weight := 0.0;
for j := 0 to contrib^[i].n-1 do
begin
{$IFDEF USE_SCANLINE}
color := PColorRGB(NativeInt(SourceLine)+contrib^[i].p^[j].pixel*Delta)^;
{$ELSE}
color := Color2RGB(Work.Canvas.Pixels[k, contrib^[i].p^[j].pixel]);
{$ENDIF}
weight := contrib^[i].p^[j].weight;
if (weight = 0.0) then
continue;
rgb.r := rgb.r + color.r * weight;
rgb.g := rgb.g + color.g * weight;
rgb.b := rgb.b + color.b * weight;
end;
if (rgb.r > 255.0) then
color.r := 255
else if (rgb.r < 0.0) then
color.r := 0
else
color.r := Round(rgb.r);
if (rgb.g > 255.0) then
color.g := 255
else if (rgb.g < 0.0) then
color.g := 0
else
color.g := Round(rgb.g);
if (rgb.b > 255.0) then
color.b := 255
else if (rgb.b < 0.0) then
color.b := 0
else
color.b := Round(rgb.b);
{$IFDEF USE_SCANLINE}
DestPixel^ := color;
inc(NativeInt(DestPixel), DestDelta);
{$ELSE}
Dst.Canvas.Pixels[k, i] := RGB2Color(color);
{$ENDIF}
end;
{$IFDEF USE_SCANLINE}
Inc(SourceLine, 1);
Inc(DestLine, 1);
{$ENDIF}
if K mod 50 = 0 then
if Assigned(CallBack) then
CallBack(Round(50 + 50 * K / DstHeight), Terminating);
if Terminating then
Break;
end;
// Free the memory allocated for vertical filter weights
for i := 0 to DstHeight-1 do
FreeMem(contrib^[i].p);
FreeMem(contrib);
finally
Work.Free;
end;
end;
end.
|
Unit TPWinTime;
Interface
uses Global;
Function SortingTime(Sort:TProc):word;
implementation
uses ArContain;
type
{ Тип Int64 служить для зчитування значень
таймера у тактах}
Int64 = array[0..3] of Word;
var
{ масив time_64 містить 2 елементи для запису
значення часу
до і після виконання алгоритму, а також для
запису різниці між ними }
{в елементі time_64[1] }
time_64: array[0..1] of Int64;
const
{ Типізована константа-вказівник ptime служить
для зчитування результату заміру часу (різниці між
кінцевим та початковим значеннями таймера)
із другого елемента масиву time_64[1]}
ptime: ^LongInt = @time_64[1];
{ Процедура rdtsc зчитує поточне значення таймера в
тактах у параметр int_64 }
{ Оскільки ця процедура написана на асемблері, то
результат буде доступний у процедурі, де був
зроблений виклик. }
procedure rdtsc(int_64: Int64); assembler;
asm
push es
db $0f,$31
les di,int_64
db $66; mov [di],ax
db $66; mov [di][4],dx
pop es
end;
{ Процедура sub_int64 обчислює різницю між значеннями
параметрів op1 і op2, а також записує різницю у
параметр op1}
procedure sub_int64(op1, op2: Int64); assembler;
asm
push es
push ds
les di,op1
lds bx,op2
db $66; mov ax,[bx]
db $66; sub [di],ax
db $66; mov ax,[bx][4]
db $66; sbb [di][4],ax
pop ds
pop es
end;
Function SortTime(Sort:TProc):word;
begin
rdtsc(time_64[0]);
Sort(A);
rdtsc(time_64[1]);
sub_int64(time_64[1],time_64[0]);
end;
function SortingTime(Sort: TProc): word; {врахування похибки}
var
CurTime: array [1..count] of word;
i, min, max: word;
begin
SortTime(Sort);
SortTime(Sort);
for i := 1 to count do
begin
SortTime(Sort);
CurTime[i] := ptime^;
end;
min := 1;
max := 1;
for i := 2 to count do
begin
if CurTime[i] < CurTime[min] then
min := i
else
if CurTime[i] > CurTime[max] then
max := i;
end;
CurTime[min] := 0;
CurTime[max] := 0;
for i := 2 to count do
CurTime[1] := CurTime[1] + CurTime[i];
SortingTime := CurTime[1] div (Count - 2);
end;
end.
|
unit ippvm17;
interface
{
Intel(R) Integrated Performance Primitives
Vector Math (ippVM)
}
{ ----------------------------------------------------------------------------
Functions declarations
{ ----------------------------------------------------------------------------
Name: ippvmGetLibVersion
Purpose: getting of the library version
Returns: the structure of information about version
of ippVM library
Parameters:
Notes: not necessary to release the returned structure
function ippvmGetLibVersion: IppLibraryVersionPtr; stdcall;
}
uses windows,math,
util1, ippdefs17;
var
ippsAbs_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAbs_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAdd_32f_A24: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAdd_64f_A53: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSub_32f_A24: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSub_64f_A53: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsMul_32f_A24: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsMul_64f_A53: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInv_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInv_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInv_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInv_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInv_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInv_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsDiv_32f_A11: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsDiv_32f_A21: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsDiv_32f_A24: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsDiv_64f_A26: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsDiv_64f_A50: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsDiv_64f_A53: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSqrt_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSqrt_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSqrt_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSqrt_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSqrt_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSqrt_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInvSqrt_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInvSqrt_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInvSqrt_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInvSqrt_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInvSqrt_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInvSqrt_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCbrt_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCbrt_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCbrt_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCbrt_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCbrt_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCbrt_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInvCbrt_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInvCbrt_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInvCbrt_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsInvCbrt_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInvCbrt_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsInvCbrt_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow_32f_A11: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow_32f_A21: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow_32f_A24: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow_64f_A26: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow_64f_A50: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow_64f_A53: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow2o3_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow2o3_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow2o3_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow2o3_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow2o3_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow2o3_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow3o2_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow3o2_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow3o2_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPow3o2_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow3o2_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPow3o2_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSqr_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSqr_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPowx_32f_A11: function( a : Psingle ; const b : Ipp32f ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPowx_32f_A21: function( a : Psingle ; const b : Ipp32f ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPowx_32f_A24: function( a : Psingle ; const b : Ipp32f ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsPowx_64f_A26: function( a : Pdouble ; const b : Ipp64f ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPowx_64f_A50: function( a : Pdouble ; const b : Ipp64f ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsPowx_64f_A53: function( a : Pdouble ; const b : Ipp64f ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsExp_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsExp_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsExp_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsExp_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsExp_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsExp_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsExpm1_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsExpm1_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsExpm1_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsExpm1_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsExpm1_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsExpm1_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLn_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLn_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLn_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLn_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLn_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLn_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLog10_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLog10_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLog10_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLog10_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLog10_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLog10_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLog1p_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLog1p_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLog1p_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsLog1p_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLog1p_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsLog1p_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCos_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCos_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCos_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCos_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCos_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCos_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSin_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSin_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSin_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSin_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSin_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSin_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSinCos_32f_A11: function( a : Psingle ; r1 : Psingle ;r2 : Psingle ; n : longint ): IppStatus; stdcall;
ippsSinCos_32f_A21: function( a : Psingle ; r1 : Psingle ;r2 : Psingle ; n : longint ): IppStatus; stdcall;
ippsSinCos_32f_A24: function( a : Psingle ; r1 : Psingle ;r2 : Psingle ; n : longint ): IppStatus; stdcall;
ippsSinCos_64f_A26: function( a : Pdouble ; r1 : Pdouble ;r2 : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSinCos_64f_A50: function( a : Pdouble ; r1 : Pdouble ;r2 : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSinCos_64f_A53: function( a : Pdouble ; r1 : Pdouble ;r2 : Pdouble ; n : longint ): IppStatus; stdcall;
ippsTan_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsTan_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsTan_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsTan_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsTan_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsTan_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAcos_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAcos_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAcos_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAcos_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAcos_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAcos_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAsin_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAsin_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAsin_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAsin_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAsin_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAsin_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtan_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtan_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtan_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtan_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtan_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtan_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtan2_32f_A11: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtan2_32f_A21: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtan2_32f_A24: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtan2_64f_A26: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtan2_64f_A50: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtan2_64f_A53: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCosh_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCosh_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCosh_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCosh_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCosh_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCosh_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSinh_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSinh_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSinh_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsSinh_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSinh_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsSinh_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsTanh_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsTanh_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsTanh_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsTanh_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsTanh_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsTanh_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAcosh_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAcosh_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAcosh_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAcosh_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAcosh_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAcosh_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAsinh_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAsinh_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAsinh_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAsinh_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAsinh_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAsinh_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtanh_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtanh_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtanh_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAtanh_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtanh_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAtanh_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErf_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErf_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErf_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErf_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErf_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErf_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfInv_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfInv_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfInv_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfInv_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfInv_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfInv_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfc_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfc_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfc_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfc_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfc_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfc_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfcInv_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfcInv_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfcInv_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsErfcInv_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfcInv_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsErfcInv_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCdfNorm_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCdfNorm_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCdfNorm_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCdfNorm_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCdfNorm_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCdfNorm_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCdfNormInv_32f_A11: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCdfNormInv_32f_A21: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCdfNormInv_32f_A24: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCdfNormInv_64f_A26: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCdfNormInv_64f_A50: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCdfNormInv_64f_A53: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsHypot_32f_A11: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsHypot_32f_A21: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsHypot_32f_A24: function( a : Psingle ; b : Psingle ;r : Psingle ; n : longint ): IppStatus; stdcall;
ippsHypot_64f_A26: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsHypot_64f_A50: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsHypot_64f_A53: function( a : Pdouble ; b : Pdouble ;r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAbs_32fc_A11: function( a : PsingleComp ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAbs_32fc_A21: function( a : PsingleComp ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAbs_32fc_A24: function( a : PsingleComp ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsAbs_64fc_A26: function( a : PdoubleComp ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAbs_64fc_A50: function( a : PdoubleComp ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAbs_64fc_A53: function( a : PdoubleComp ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsArg_32fc_A11: function( a : PsingleComp ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsArg_32fc_A21: function( a : PsingleComp ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsArg_32fc_A24: function( a : PsingleComp ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsArg_64fc_A26: function( a : PdoubleComp ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsArg_64fc_A50: function( a : PdoubleComp ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsArg_64fc_A53: function( a : PdoubleComp ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsAdd_32fc_A24: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAdd_64fc_A53: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSub_32fc_A24: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSub_64fc_A53: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsMul_32fc_A11: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsMul_32fc_A21: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsMul_32fc_A24: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsMul_64fc_A26: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsMul_64fc_A50: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsMul_64fc_A53: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsDiv_32fc_A11: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsDiv_32fc_A21: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsDiv_32fc_A24: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsDiv_64fc_A26: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsDiv_64fc_A50: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsDiv_64fc_A53: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCIS_32fc_A11: function( a : Psingle ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCIS_32fc_A21: function( a : Psingle ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCIS_32fc_A24: function( a : Psingle ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCIS_64fc_A26: function( a : Pdouble ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCIS_64fc_A50: function( a : Pdouble ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCIS_64fc_A53: function( a : Pdouble ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsConj_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsConj_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsMulByConj_32fc_A11: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsMulByConj_32fc_A21: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsMulByConj_32fc_A24: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsMulByConj_64fc_A26: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsMulByConj_64fc_A50: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsMulByConj_64fc_A53: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCos_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCos_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCos_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCos_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCos_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCos_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSin_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSin_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSin_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSin_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSin_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSin_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsTan_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsTan_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsTan_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsTan_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsTan_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsTan_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCosh_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCosh_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCosh_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsCosh_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCosh_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsCosh_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSinh_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSinh_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSinh_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSinh_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSinh_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSinh_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsTanh_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsTanh_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsTanh_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsTanh_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsTanh_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsTanh_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAcos_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAcos_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAcos_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAcos_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAcos_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAcos_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAsin_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAsin_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAsin_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAsin_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAsin_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAsin_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAtan_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAtan_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAtan_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAtan_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAtan_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAtan_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAcosh_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAcosh_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAcosh_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAcosh_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAcosh_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAcosh_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAsinh_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAsinh_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAsinh_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAsinh_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAsinh_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAsinh_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAtanh_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAtanh_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAtanh_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsAtanh_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAtanh_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsAtanh_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsExp_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsExp_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsExp_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsExp_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsExp_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsExp_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsLn_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsLn_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsLn_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsLn_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsLn_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsLn_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsLog10_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsLog10_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsLog10_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsLog10_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsLog10_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsLog10_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSqrt_32fc_A11: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSqrt_32fc_A21: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSqrt_32fc_A24: function( a : PsingleComp ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsSqrt_64fc_A26: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSqrt_64fc_A50: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsSqrt_64fc_A53: function( a : PdoubleComp ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsPow_32fc_A11: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsPow_32fc_A21: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsPow_32fc_A24: function( a : PsingleComp ; b : PsingleComp ;r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsPow_64fc_A26: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsPow_64fc_A50: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsPow_64fc_A53: function( a : PdoubleComp ; b : PdoubleComp ;r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsPowx_32fc_A11: function( a : PsingleComp ; const b : Ipp32fc ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsPowx_32fc_A21: function( a : PsingleComp ; const b : Ipp32fc ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsPowx_32fc_A24: function( a : PsingleComp ; const b : Ipp32fc ; r : PsingleComp ; n : longint ): IppStatus; stdcall;
ippsPowx_64fc_A26: function( a : PdoubleComp ; const b : Ipp64fc ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsPowx_64fc_A50: function( a : PdoubleComp ; const b : Ipp64fc ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsPowx_64fc_A53: function( a : PdoubleComp ; const b : Ipp64fc ; r : PdoubleComp ; n : longint ): IppStatus; stdcall;
ippsFloor_32f: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsFloor_64f: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsCeil_32f: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsCeil_64f: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsTrunc_32f: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsTrunc_64f: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsRound_32f: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsRound_64f: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsRint_32f: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsRint_64f: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsNearbyInt_32f: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsNearbyInt_64f: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
ippsModf_32f: function( a : Psingle ; r1 : Psingle ;r2 : Psingle ; n : longint ): IppStatus; stdcall;
ippsModf_64f: function( a : Pdouble ; r1 : Pdouble ;r2 : Pdouble ; n : longint ): IppStatus; stdcall;
ippsFrac_32f: function( a : Psingle ; r : Psingle ; n : longint ): IppStatus; stdcall;
ippsFrac_64f: function( a : Pdouble ; r : Pdouble ; n : longint ): IppStatus; stdcall;
{ AvO, deprecated or removed (incomplete)
ippiRGBToYCbCr_JPEG_8u_P3R: function( pSrc : Ipp8u_3Ptr ; srcStep : Int32 ; pDst : Ipp8u_3Ptr ; dstStep : Int32 ; roiSize : IppiSize ): IppStatus; stdcall;
ippiRGBToYCbCr_JPEG_8u_C3P3R: function( pSrc : Ipp8uPtr ; srcStep : Int32 ; pDst : Ipp8u_3Ptr ; dstStep : Int32 ; roiSize : IppiSize): IppStatus; stdcall;
ippiRGBToYCbCr_JPEG_8u_C4P3R: function( pSrc : Ipp8uPtr ; srcStep : Int32 ; pDst : Ipp8u_3Ptr ; dstStep : Int32 ; roiSize : IppiSize): IppStatus; stdcall;
ippiYCbCrToRGB_JPEG_8u_P3R: function( pSrc : Ipp8u_3Ptr ; srcStep : Int32 ; pDst : Ipp8u_3Ptr ; dstStep : Int32 ; roiSize : IppiSize): IppStatus; stdcall;
ippiYCbCrToRGB_JPEG_8u_P3C3R: function( pSrc : Ipp8u_3Ptr ; srcStep : Int32 ; pDst : Ipp8uPtr ; dstStep : Int32 ; roiSize : IppiSize): IppStatus; stdcall;
ippiYCbCrToRGB_JPEG_8u_P3C4R: function( pSrc : Ipp8u_3Ptr ; srcStep : Int32 ; pDst : Ipp8uPtr ; dstStep : Int32 ; roiSize : IppiSize ; aval : Ipp8u ): IppStatus; stdcall;
}
function fonctionErf(w: double):double;pascal;
function fonctionErfc(w: double):double;pascal;
function Erf(w: double):double;
function Erfc(w: double):double;
implementation
uses ncdef2;
Const
DLLname1='ippvm.dll';
var
hh: intG;
function InitIPPVM:boolean;
begin
result:=true;
if hh<>0 then exit;
hh:=GloadLibrary(AppDir+'IPP\'+DLLname1);
result:=(hh<>0);
if not result then exit;
// model ippsAbs_32f_A24:= getProc(hh, 'ippsAbs_32f_A24');
ippsAbs_32f_A24:= getProc(hh,'ippsAbs_32f_A24');
ippsAbs_64f_A53:= getProc(hh,'ippsAbs_64f_A53');
ippsAdd_32f_A24:= getProc(hh,'ippsAdd_32f_A24');
ippsAdd_64f_A53:= getProc(hh,'ippsAdd_64f_A53');
ippsSub_32f_A24:= getProc(hh,'ippsSub_32f_A24');
ippsSub_64f_A53:= getProc(hh,'ippsSub_64f_A53');
ippsMul_32f_A24:= getProc(hh,'ippsMul_32f_A24');
ippsMul_64f_A53:= getProc(hh,'ippsMul_64f_A53');
ippsInv_32f_A11:= getProc(hh,'ippsInv_32f_A11');
ippsInv_32f_A21:= getProc(hh,'ippsInv_32f_A21');
ippsInv_32f_A24:= getProc(hh,'ippsInv_32f_A24');
ippsInv_64f_A26:= getProc(hh,'ippsInv_64f_A26');
ippsInv_64f_A50:= getProc(hh,'ippsInv_64f_A50');
ippsInv_64f_A53:= getProc(hh,'ippsInv_64f_A53');
ippsDiv_32f_A11:= getProc(hh,'ippsDiv_32f_A11');
ippsDiv_32f_A21:= getProc(hh,'ippsDiv_32f_A21');
ippsDiv_32f_A24:= getProc(hh,'ippsDiv_32f_A24');
ippsDiv_64f_A26:= getProc(hh,'ippsDiv_64f_A26');
ippsDiv_64f_A50:= getProc(hh,'ippsDiv_64f_A50');
ippsDiv_64f_A53:= getProc(hh,'ippsDiv_64f_A53');
ippsSqrt_32f_A11:= getProc(hh,'ippsSqrt_32f_A11');
ippsSqrt_32f_A21:= getProc(hh,'ippsSqrt_32f_A21');
ippsSqrt_32f_A24:= getProc(hh,'ippsSqrt_32f_A24');
ippsSqrt_64f_A26:= getProc(hh,'ippsSqrt_64f_A26');
ippsSqrt_64f_A50:= getProc(hh,'ippsSqrt_64f_A50');
ippsSqrt_64f_A53:= getProc(hh,'ippsSqrt_64f_A53');
ippsInvSqrt_32f_A11:= getProc(hh,'ippsInvSqrt_32f_A11');
ippsInvSqrt_32f_A21:= getProc(hh,'ippsInvSqrt_32f_A21');
ippsInvSqrt_32f_A24:= getProc(hh,'ippsInvSqrt_32f_A24');
ippsInvSqrt_64f_A26:= getProc(hh,'ippsInvSqrt_64f_A26');
ippsInvSqrt_64f_A50:= getProc(hh,'ippsInvSqrt_64f_A50');
ippsInvSqrt_64f_A53:= getProc(hh,'ippsInvSqrt_64f_A53');
ippsCbrt_32f_A11:= getProc(hh,'ippsCbrt_32f_A11');
ippsCbrt_32f_A21:= getProc(hh,'ippsCbrt_32f_A21');
ippsCbrt_32f_A24:= getProc(hh,'ippsCbrt_32f_A24');
ippsCbrt_64f_A26:= getProc(hh,'ippsCbrt_64f_A26');
ippsCbrt_64f_A50:= getProc(hh,'ippsCbrt_64f_A50');
ippsCbrt_64f_A53:= getProc(hh,'ippsCbrt_64f_A53');
ippsInvCbrt_32f_A11:= getProc(hh,'ippsInvCbrt_32f_A11');
ippsInvCbrt_32f_A21:= getProc(hh,'ippsInvCbrt_32f_A21');
ippsInvCbrt_32f_A24:= getProc(hh,'ippsInvCbrt_32f_A24');
ippsInvCbrt_64f_A26:= getProc(hh,'ippsInvCbrt_64f_A26');
ippsInvCbrt_64f_A50:= getProc(hh,'ippsInvCbrt_64f_A50');
ippsInvCbrt_64f_A53:= getProc(hh,'ippsInvCbrt_64f_A53');
ippsPow_32f_A11:= getProc(hh,'ippsPow_32f_A11');
ippsPow_32f_A21:= getProc(hh,'ippsPow_32f_A21');
ippsPow_32f_A24:= getProc(hh,'ippsPow_32f_A24');
ippsPow_64f_A26:= getProc(hh,'ippsPow_64f_A26');
ippsPow_64f_A50:= getProc(hh,'ippsPow_64f_A50');
ippsPow_64f_A53:= getProc(hh,'ippsPow_64f_A53');
ippsPow2o3_32f_A11:= getProc(hh,'ippsPow2o3_32f_A11');
ippsPow2o3_32f_A21:= getProc(hh,'ippsPow2o3_32f_A21');
ippsPow2o3_32f_A24:= getProc(hh,'ippsPow2o3_32f_A24');
ippsPow2o3_64f_A26:= getProc(hh,'ippsPow2o3_64f_A26');
ippsPow2o3_64f_A50:= getProc(hh,'ippsPow2o3_64f_A50');
ippsPow2o3_64f_A53:= getProc(hh,'ippsPow2o3_64f_A53');
ippsPow3o2_32f_A11:= getProc(hh,'ippsPow3o2_32f_A11');
ippsPow3o2_32f_A21:= getProc(hh,'ippsPow3o2_32f_A21');
ippsPow3o2_32f_A24:= getProc(hh,'ippsPow3o2_32f_A24');
ippsPow3o2_64f_A26:= getProc(hh,'ippsPow3o2_64f_A26');
ippsPow3o2_64f_A50:= getProc(hh,'ippsPow3o2_64f_A50');
ippsPow3o2_64f_A53:= getProc(hh,'ippsPow3o2_64f_A53');
ippsSqr_32f_A24:= getProc(hh,'ippsSqr_32f_A24');
ippsSqr_64f_A53:= getProc(hh,'ippsSqr_64f_A53');
ippsPowx_32f_A11:= getProc(hh,'ippsPowx_32f_A11');
ippsPowx_32f_A21:= getProc(hh,'ippsPowx_32f_A21');
ippsPowx_32f_A24:= getProc(hh,'ippsPowx_32f_A24');
ippsPowx_64f_A26:= getProc(hh,'ippsPowx_64f_A26');
ippsPowx_64f_A50:= getProc(hh,'ippsPowx_64f_A50');
ippsPowx_64f_A53:= getProc(hh,'ippsPowx_64f_A53');
ippsExp_32f_A11:= getProc(hh,'ippsExp_32f_A11');
ippsExp_32f_A21:= getProc(hh,'ippsExp_32f_A21');
ippsExp_32f_A24:= getProc(hh,'ippsExp_32f_A24');
ippsExp_64f_A26:= getProc(hh,'ippsExp_64f_A26');
ippsExp_64f_A50:= getProc(hh,'ippsExp_64f_A50');
ippsExp_64f_A53:= getProc(hh,'ippsExp_64f_A53');
ippsExpm1_32f_A11:= getProc(hh,'ippsExpm1_32f_A11');
ippsExpm1_32f_A21:= getProc(hh,'ippsExpm1_32f_A21');
ippsExpm1_32f_A24:= getProc(hh,'ippsExpm1_32f_A24');
ippsExpm1_64f_A26:= getProc(hh,'ippsExpm1_64f_A26');
ippsExpm1_64f_A50:= getProc(hh,'ippsExpm1_64f_A50');
ippsExpm1_64f_A53:= getProc(hh,'ippsExpm1_64f_A53');
ippsLn_32f_A11:= getProc(hh,'ippsLn_32f_A11');
ippsLn_32f_A21:= getProc(hh,'ippsLn_32f_A21');
ippsLn_32f_A24:= getProc(hh,'ippsLn_32f_A24');
ippsLn_64f_A26:= getProc(hh,'ippsLn_64f_A26');
ippsLn_64f_A50:= getProc(hh,'ippsLn_64f_A50');
ippsLn_64f_A53:= getProc(hh,'ippsLn_64f_A53');
ippsLog10_32f_A11:= getProc(hh,'ippsLog10_32f_A11');
ippsLog10_32f_A21:= getProc(hh,'ippsLog10_32f_A21');
ippsLog10_32f_A24:= getProc(hh,'ippsLog10_32f_A24');
ippsLog10_64f_A26:= getProc(hh,'ippsLog10_64f_A26');
ippsLog10_64f_A50:= getProc(hh,'ippsLog10_64f_A50');
ippsLog10_64f_A53:= getProc(hh,'ippsLog10_64f_A53');
ippsLog1p_32f_A11:= getProc(hh,'ippsLog1p_32f_A11');
ippsLog1p_32f_A21:= getProc(hh,'ippsLog1p_32f_A21');
ippsLog1p_32f_A24:= getProc(hh,'ippsLog1p_32f_A24');
ippsLog1p_64f_A26:= getProc(hh,'ippsLog1p_64f_A26');
ippsLog1p_64f_A50:= getProc(hh,'ippsLog1p_64f_A50');
ippsLog1p_64f_A53:= getProc(hh,'ippsLog1p_64f_A53');
ippsCos_32f_A11:= getProc(hh,'ippsCos_32f_A11');
ippsCos_32f_A21:= getProc(hh,'ippsCos_32f_A21');
ippsCos_32f_A24:= getProc(hh,'ippsCos_32f_A24');
ippsCos_64f_A26:= getProc(hh,'ippsCos_64f_A26');
ippsCos_64f_A50:= getProc(hh,'ippsCos_64f_A50');
ippsCos_64f_A53:= getProc(hh,'ippsCos_64f_A53');
ippsSin_32f_A11:= getProc(hh,'ippsSin_32f_A11');
ippsSin_32f_A21:= getProc(hh,'ippsSin_32f_A21');
ippsSin_32f_A24:= getProc(hh,'ippsSin_32f_A24');
ippsSin_64f_A26:= getProc(hh,'ippsSin_64f_A26');
ippsSin_64f_A50:= getProc(hh,'ippsSin_64f_A50');
ippsSin_64f_A53:= getProc(hh,'ippsSin_64f_A53');
ippsSinCos_32f_A11:= getProc(hh,'ippsSinCos_32f_A11');
ippsSinCos_32f_A21:= getProc(hh,'ippsSinCos_32f_A21');
ippsSinCos_32f_A24:= getProc(hh,'ippsSinCos_32f_A24');
ippsSinCos_64f_A26:= getProc(hh,'ippsSinCos_64f_A26');
ippsSinCos_64f_A50:= getProc(hh,'ippsSinCos_64f_A50');
ippsSinCos_64f_A53:= getProc(hh,'ippsSinCos_64f_A53');
ippsTan_32f_A11:= getProc(hh,'ippsTan_32f_A11');
ippsTan_32f_A21:= getProc(hh,'ippsTan_32f_A21');
ippsTan_32f_A24:= getProc(hh,'ippsTan_32f_A24');
ippsTan_64f_A26:= getProc(hh,'ippsTan_64f_A26');
ippsTan_64f_A50:= getProc(hh,'ippsTan_64f_A50');
ippsTan_64f_A53:= getProc(hh,'ippsTan_64f_A53');
ippsAcos_32f_A11:= getProc(hh,'ippsAcos_32f_A11');
ippsAcos_32f_A21:= getProc(hh,'ippsAcos_32f_A21');
ippsAcos_32f_A24:= getProc(hh,'ippsAcos_32f_A24');
ippsAcos_64f_A26:= getProc(hh,'ippsAcos_64f_A26');
ippsAcos_64f_A50:= getProc(hh,'ippsAcos_64f_A50');
ippsAcos_64f_A53:= getProc(hh,'ippsAcos_64f_A53');
ippsAsin_32f_A11:= getProc(hh,'ippsAsin_32f_A11');
ippsAsin_32f_A21:= getProc(hh,'ippsAsin_32f_A21');
ippsAsin_32f_A24:= getProc(hh,'ippsAsin_32f_A24');
ippsAsin_64f_A26:= getProc(hh,'ippsAsin_64f_A26');
ippsAsin_64f_A50:= getProc(hh,'ippsAsin_64f_A50');
ippsAsin_64f_A53:= getProc(hh,'ippsAsin_64f_A53');
ippsAtan_32f_A11:= getProc(hh,'ippsAtan_32f_A11');
ippsAtan_32f_A21:= getProc(hh,'ippsAtan_32f_A21');
ippsAtan_32f_A24:= getProc(hh,'ippsAtan_32f_A24');
ippsAtan_64f_A26:= getProc(hh,'ippsAtan_64f_A26');
ippsAtan_64f_A50:= getProc(hh,'ippsAtan_64f_A50');
ippsAtan_64f_A53:= getProc(hh,'ippsAtan_64f_A53');
ippsAtan2_32f_A11:= getProc(hh,'ippsAtan2_32f_A11');
ippsAtan2_32f_A21:= getProc(hh,'ippsAtan2_32f_A21');
ippsAtan2_32f_A24:= getProc(hh,'ippsAtan2_32f_A24');
ippsAtan2_64f_A26:= getProc(hh,'ippsAtan2_64f_A26');
ippsAtan2_64f_A50:= getProc(hh,'ippsAtan2_64f_A50');
ippsAtan2_64f_A53:= getProc(hh,'ippsAtan2_64f_A53');
ippsCosh_32f_A11:= getProc(hh,'ippsCosh_32f_A11');
ippsCosh_32f_A21:= getProc(hh,'ippsCosh_32f_A21');
ippsCosh_32f_A24:= getProc(hh,'ippsCosh_32f_A24');
ippsCosh_64f_A26:= getProc(hh,'ippsCosh_64f_A26');
ippsCosh_64f_A50:= getProc(hh,'ippsCosh_64f_A50');
ippsCosh_64f_A53:= getProc(hh,'ippsCosh_64f_A53');
ippsSinh_32f_A11:= getProc(hh,'ippsSinh_32f_A11');
ippsSinh_32f_A21:= getProc(hh,'ippsSinh_32f_A21');
ippsSinh_32f_A24:= getProc(hh,'ippsSinh_32f_A24');
ippsSinh_64f_A26:= getProc(hh,'ippsSinh_64f_A26');
ippsSinh_64f_A50:= getProc(hh,'ippsSinh_64f_A50');
ippsSinh_64f_A53:= getProc(hh,'ippsSinh_64f_A53');
ippsTanh_32f_A11:= getProc(hh,'ippsTanh_32f_A11');
ippsTanh_32f_A21:= getProc(hh,'ippsTanh_32f_A21');
ippsTanh_32f_A24:= getProc(hh,'ippsTanh_32f_A24');
ippsTanh_64f_A26:= getProc(hh,'ippsTanh_64f_A26');
ippsTanh_64f_A50:= getProc(hh,'ippsTanh_64f_A50');
ippsTanh_64f_A53:= getProc(hh,'ippsTanh_64f_A53');
ippsAcosh_32f_A11:= getProc(hh,'ippsAcosh_32f_A11');
ippsAcosh_32f_A21:= getProc(hh,'ippsAcosh_32f_A21');
ippsAcosh_32f_A24:= getProc(hh,'ippsAcosh_32f_A24');
ippsAcosh_64f_A26:= getProc(hh,'ippsAcosh_64f_A26');
ippsAcosh_64f_A50:= getProc(hh,'ippsAcosh_64f_A50');
ippsAcosh_64f_A53:= getProc(hh,'ippsAcosh_64f_A53');
ippsAsinh_32f_A11:= getProc(hh,'ippsAsinh_32f_A11');
ippsAsinh_32f_A21:= getProc(hh,'ippsAsinh_32f_A21');
ippsAsinh_32f_A24:= getProc(hh,'ippsAsinh_32f_A24');
ippsAsinh_64f_A26:= getProc(hh,'ippsAsinh_64f_A26');
ippsAsinh_64f_A50:= getProc(hh,'ippsAsinh_64f_A50');
ippsAsinh_64f_A53:= getProc(hh,'ippsAsinh_64f_A53');
ippsAtanh_32f_A11:= getProc(hh,'ippsAtanh_32f_A11');
ippsAtanh_32f_A21:= getProc(hh,'ippsAtanh_32f_A21');
ippsAtanh_32f_A24:= getProc(hh,'ippsAtanh_32f_A24');
ippsAtanh_64f_A26:= getProc(hh,'ippsAtanh_64f_A26');
ippsAtanh_64f_A50:= getProc(hh,'ippsAtanh_64f_A50');
ippsAtanh_64f_A53:= getProc(hh,'ippsAtanh_64f_A53');
ippsErf_32f_A11:= getProc(hh,'ippsErf_32f_A11');
ippsErf_32f_A21:= getProc(hh,'ippsErf_32f_A21');
ippsErf_32f_A24:= getProc(hh,'ippsErf_32f_A24');
ippsErf_64f_A26:= getProc(hh,'ippsErf_64f_A26');
ippsErf_64f_A50:= getProc(hh,'ippsErf_64f_A50');
ippsErf_64f_A53:= getProc(hh,'ippsErf_64f_A53');
ippsErfInv_32f_A11:= getProc(hh,'ippsErfInv_32f_A11');
ippsErfInv_32f_A21:= getProc(hh,'ippsErfInv_32f_A21');
ippsErfInv_32f_A24:= getProc(hh,'ippsErfInv_32f_A24');
ippsErfInv_64f_A26:= getProc(hh,'ippsErfInv_64f_A26');
ippsErfInv_64f_A50:= getProc(hh,'ippsErfInv_64f_A50');
ippsErfInv_64f_A53:= getProc(hh,'ippsErfInv_64f_A53');
ippsErfc_32f_A11:= getProc(hh,'ippsErfc_32f_A11');
ippsErfc_32f_A21:= getProc(hh,'ippsErfc_32f_A21');
ippsErfc_32f_A24:= getProc(hh,'ippsErfc_32f_A24');
ippsErfc_64f_A26:= getProc(hh,'ippsErfc_64f_A26');
ippsErfc_64f_A50:= getProc(hh,'ippsErfc_64f_A50');
ippsErfc_64f_A53:= getProc(hh,'ippsErfc_64f_A53');
ippsErfcInv_32f_A11:= getProc(hh,'ippsErfcInv_32f_A11');
ippsErfcInv_32f_A21:= getProc(hh,'ippsErfcInv_32f_A21');
ippsErfcInv_32f_A24:= getProc(hh,'ippsErfcInv_32f_A24');
ippsErfcInv_64f_A26:= getProc(hh,'ippsErfcInv_64f_A26');
ippsErfcInv_64f_A50:= getProc(hh,'ippsErfcInv_64f_A50');
ippsErfcInv_64f_A53:= getProc(hh,'ippsErfcInv_64f_A53');
ippsCdfNorm_32f_A11:= getProc(hh,'ippsCdfNorm_32f_A11');
ippsCdfNorm_32f_A21:= getProc(hh,'ippsCdfNorm_32f_A21');
ippsCdfNorm_32f_A24:= getProc(hh,'ippsCdfNorm_32f_A24');
ippsCdfNorm_64f_A26:= getProc(hh,'ippsCdfNorm_64f_A26');
ippsCdfNorm_64f_A50:= getProc(hh,'ippsCdfNorm_64f_A50');
ippsCdfNorm_64f_A53:= getProc(hh,'ippsCdfNorm_64f_A53');
ippsCdfNormInv_32f_A11:= getProc(hh,'ippsCdfNormInv_32f_A11');
ippsCdfNormInv_32f_A21:= getProc(hh,'ippsCdfNormInv_32f_A21');
ippsCdfNormInv_32f_A24:= getProc(hh,'ippsCdfNormInv_32f_A24');
ippsCdfNormInv_64f_A26:= getProc(hh,'ippsCdfNormInv_64f_A26');
ippsCdfNormInv_64f_A50:= getProc(hh,'ippsCdfNormInv_64f_A50');
ippsCdfNormInv_64f_A53:= getProc(hh,'ippsCdfNormInv_64f_A53');
ippsHypot_32f_A11:= getProc(hh,'ippsHypot_32f_A11');
ippsHypot_32f_A21:= getProc(hh,'ippsHypot_32f_A21');
ippsHypot_32f_A24:= getProc(hh,'ippsHypot_32f_A24');
ippsHypot_64f_A26:= getProc(hh,'ippsHypot_64f_A26');
ippsHypot_64f_A50:= getProc(hh,'ippsHypot_64f_A50');
ippsHypot_64f_A53:= getProc(hh,'ippsHypot_64f_A53');
ippsAbs_32fc_A11:= getProc(hh,'ippsAbs_32fc_A11');
ippsAbs_32fc_A21:= getProc(hh,'ippsAbs_32fc_A21');
ippsAbs_32fc_A24:= getProc(hh,'ippsAbs_32fc_A24');
ippsAbs_64fc_A26:= getProc(hh,'ippsAbs_64fc_A26');
ippsAbs_64fc_A50:= getProc(hh,'ippsAbs_64fc_A50');
ippsAbs_64fc_A53:= getProc(hh,'ippsAbs_64fc_A53');
ippsArg_32fc_A11:= getProc(hh,'ippsArg_32fc_A11');
ippsArg_32fc_A21:= getProc(hh,'ippsArg_32fc_A21');
ippsArg_32fc_A24:= getProc(hh,'ippsArg_32fc_A24');
ippsArg_64fc_A26:= getProc(hh,'ippsArg_64fc_A26');
ippsArg_64fc_A50:= getProc(hh,'ippsArg_64fc_A50');
ippsArg_64fc_A53:= getProc(hh,'ippsArg_64fc_A53');
ippsAdd_32fc_A24:= getProc(hh,'ippsAdd_32fc_A24');
ippsAdd_64fc_A53:= getProc(hh,'ippsAdd_64fc_A53');
ippsSub_32fc_A24:= getProc(hh,'ippsSub_32fc_A24');
ippsSub_64fc_A53:= getProc(hh,'ippsSub_64fc_A53');
ippsMul_32fc_A11:= getProc(hh,'ippsMul_32fc_A11');
ippsMul_32fc_A21:= getProc(hh,'ippsMul_32fc_A21');
ippsMul_32fc_A24:= getProc(hh,'ippsMul_32fc_A24');
ippsMul_64fc_A26:= getProc(hh,'ippsMul_64fc_A26');
ippsMul_64fc_A50:= getProc(hh,'ippsMul_64fc_A50');
ippsMul_64fc_A53:= getProc(hh,'ippsMul_64fc_A53');
ippsDiv_32fc_A11:= getProc(hh,'ippsDiv_32fc_A11');
ippsDiv_32fc_A21:= getProc(hh,'ippsDiv_32fc_A21');
ippsDiv_32fc_A24:= getProc(hh,'ippsDiv_32fc_A24');
ippsDiv_64fc_A26:= getProc(hh,'ippsDiv_64fc_A26');
ippsDiv_64fc_A50:= getProc(hh,'ippsDiv_64fc_A50');
ippsDiv_64fc_A53:= getProc(hh,'ippsDiv_64fc_A53');
ippsCIS_32fc_A11:= getProc(hh,'ippsCIS_32fc_A11');
ippsCIS_32fc_A21:= getProc(hh,'ippsCIS_32fc_A21');
ippsCIS_32fc_A24:= getProc(hh,'ippsCIS_32fc_A24');
ippsCIS_64fc_A26:= getProc(hh,'ippsCIS_64fc_A26');
ippsCIS_64fc_A50:= getProc(hh,'ippsCIS_64fc_A50');
ippsCIS_64fc_A53:= getProc(hh,'ippsCIS_64fc_A53');
ippsConj_32fc_A24:= getProc(hh,'ippsConj_32fc_A24');
ippsConj_64fc_A53:= getProc(hh,'ippsConj_64fc_A53');
ippsMulByConj_32fc_A11:= getProc(hh,'ippsMulByConj_32fc_A11');
ippsMulByConj_32fc_A21:= getProc(hh,'ippsMulByConj_32fc_A21');
ippsMulByConj_32fc_A24:= getProc(hh,'ippsMulByConj_32fc_A24');
ippsMulByConj_64fc_A26:= getProc(hh,'ippsMulByConj_64fc_A26');
ippsMulByConj_64fc_A50:= getProc(hh,'ippsMulByConj_64fc_A50');
ippsMulByConj_64fc_A53:= getProc(hh,'ippsMulByConj_64fc_A53');
ippsCos_32fc_A11:= getProc(hh,'ippsCos_32fc_A11');
ippsCos_32fc_A21:= getProc(hh,'ippsCos_32fc_A21');
ippsCos_32fc_A24:= getProc(hh,'ippsCos_32fc_A24');
ippsCos_64fc_A26:= getProc(hh,'ippsCos_64fc_A26');
ippsCos_64fc_A50:= getProc(hh,'ippsCos_64fc_A50');
ippsCos_64fc_A53:= getProc(hh,'ippsCos_64fc_A53');
ippsSin_32fc_A11:= getProc(hh,'ippsSin_32fc_A11');
ippsSin_32fc_A21:= getProc(hh,'ippsSin_32fc_A21');
ippsSin_32fc_A24:= getProc(hh,'ippsSin_32fc_A24');
ippsSin_64fc_A26:= getProc(hh,'ippsSin_64fc_A26');
ippsSin_64fc_A50:= getProc(hh,'ippsSin_64fc_A50');
ippsSin_64fc_A53:= getProc(hh,'ippsSin_64fc_A53');
ippsTan_32fc_A11:= getProc(hh,'ippsTan_32fc_A11');
ippsTan_32fc_A21:= getProc(hh,'ippsTan_32fc_A21');
ippsTan_32fc_A24:= getProc(hh,'ippsTan_32fc_A24');
ippsTan_64fc_A26:= getProc(hh,'ippsTan_64fc_A26');
ippsTan_64fc_A50:= getProc(hh,'ippsTan_64fc_A50');
ippsTan_64fc_A53:= getProc(hh,'ippsTan_64fc_A53');
ippsCosh_32fc_A11:= getProc(hh,'ippsCosh_32fc_A11');
ippsCosh_32fc_A21:= getProc(hh,'ippsCosh_32fc_A21');
ippsCosh_32fc_A24:= getProc(hh,'ippsCosh_32fc_A24');
ippsCosh_64fc_A26:= getProc(hh,'ippsCosh_64fc_A26');
ippsCosh_64fc_A50:= getProc(hh,'ippsCosh_64fc_A50');
ippsCosh_64fc_A53:= getProc(hh,'ippsCosh_64fc_A53');
ippsSinh_32fc_A11:= getProc(hh,'ippsSinh_32fc_A11');
ippsSinh_32fc_A21:= getProc(hh,'ippsSinh_32fc_A21');
ippsSinh_32fc_A24:= getProc(hh,'ippsSinh_32fc_A24');
ippsSinh_64fc_A26:= getProc(hh,'ippsSinh_64fc_A26');
ippsSinh_64fc_A50:= getProc(hh,'ippsSinh_64fc_A50');
ippsSinh_64fc_A53:= getProc(hh,'ippsSinh_64fc_A53');
ippsTanh_32fc_A11:= getProc(hh,'ippsTanh_32fc_A11');
ippsTanh_32fc_A21:= getProc(hh,'ippsTanh_32fc_A21');
ippsTanh_32fc_A24:= getProc(hh,'ippsTanh_32fc_A24');
ippsTanh_64fc_A26:= getProc(hh,'ippsTanh_64fc_A26');
ippsTanh_64fc_A50:= getProc(hh,'ippsTanh_64fc_A50');
ippsTanh_64fc_A53:= getProc(hh,'ippsTanh_64fc_A53');
ippsAcos_32fc_A11:= getProc(hh,'ippsAcos_32fc_A11');
ippsAcos_32fc_A21:= getProc(hh,'ippsAcos_32fc_A21');
ippsAcos_32fc_A24:= getProc(hh,'ippsAcos_32fc_A24');
ippsAcos_64fc_A26:= getProc(hh,'ippsAcos_64fc_A26');
ippsAcos_64fc_A50:= getProc(hh,'ippsAcos_64fc_A50');
ippsAcos_64fc_A53:= getProc(hh,'ippsAcos_64fc_A53');
ippsAsin_32fc_A11:= getProc(hh,'ippsAsin_32fc_A11');
ippsAsin_32fc_A21:= getProc(hh,'ippsAsin_32fc_A21');
ippsAsin_32fc_A24:= getProc(hh,'ippsAsin_32fc_A24');
ippsAsin_64fc_A26:= getProc(hh,'ippsAsin_64fc_A26');
ippsAsin_64fc_A50:= getProc(hh,'ippsAsin_64fc_A50');
ippsAsin_64fc_A53:= getProc(hh,'ippsAsin_64fc_A53');
ippsAtan_32fc_A11:= getProc(hh,'ippsAtan_32fc_A11');
ippsAtan_32fc_A21:= getProc(hh,'ippsAtan_32fc_A21');
ippsAtan_32fc_A24:= getProc(hh,'ippsAtan_32fc_A24');
ippsAtan_64fc_A26:= getProc(hh,'ippsAtan_64fc_A26');
ippsAtan_64fc_A50:= getProc(hh,'ippsAtan_64fc_A50');
ippsAtan_64fc_A53:= getProc(hh,'ippsAtan_64fc_A53');
ippsAcosh_32fc_A11:= getProc(hh,'ippsAcosh_32fc_A11');
ippsAcosh_32fc_A21:= getProc(hh,'ippsAcosh_32fc_A21');
ippsAcosh_32fc_A24:= getProc(hh,'ippsAcosh_32fc_A24');
ippsAcosh_64fc_A26:= getProc(hh,'ippsAcosh_64fc_A26');
ippsAcosh_64fc_A50:= getProc(hh,'ippsAcosh_64fc_A50');
ippsAcosh_64fc_A53:= getProc(hh,'ippsAcosh_64fc_A53');
ippsAsinh_32fc_A11:= getProc(hh,'ippsAsinh_32fc_A11');
ippsAsinh_32fc_A21:= getProc(hh,'ippsAsinh_32fc_A21');
ippsAsinh_32fc_A24:= getProc(hh,'ippsAsinh_32fc_A24');
ippsAsinh_64fc_A26:= getProc(hh,'ippsAsinh_64fc_A26');
ippsAsinh_64fc_A50:= getProc(hh,'ippsAsinh_64fc_A50');
ippsAsinh_64fc_A53:= getProc(hh,'ippsAsinh_64fc_A53');
ippsAtanh_32fc_A11:= getProc(hh,'ippsAtanh_32fc_A11');
ippsAtanh_32fc_A21:= getProc(hh,'ippsAtanh_32fc_A21');
ippsAtanh_32fc_A24:= getProc(hh,'ippsAtanh_32fc_A24');
ippsAtanh_64fc_A26:= getProc(hh,'ippsAtanh_64fc_A26');
ippsAtanh_64fc_A50:= getProc(hh,'ippsAtanh_64fc_A50');
ippsAtanh_64fc_A53:= getProc(hh,'ippsAtanh_64fc_A53');
ippsExp_32fc_A11:= getProc(hh,'ippsExp_32fc_A11');
ippsExp_32fc_A21:= getProc(hh,'ippsExp_32fc_A21');
ippsExp_32fc_A24:= getProc(hh,'ippsExp_32fc_A24');
ippsExp_64fc_A26:= getProc(hh,'ippsExp_64fc_A26');
ippsExp_64fc_A50:= getProc(hh,'ippsExp_64fc_A50');
ippsExp_64fc_A53:= getProc(hh,'ippsExp_64fc_A53');
ippsLn_32fc_A11:= getProc(hh,'ippsLn_32fc_A11');
ippsLn_32fc_A21:= getProc(hh,'ippsLn_32fc_A21');
ippsLn_32fc_A24:= getProc(hh,'ippsLn_32fc_A24');
ippsLn_64fc_A26:= getProc(hh,'ippsLn_64fc_A26');
ippsLn_64fc_A50:= getProc(hh,'ippsLn_64fc_A50');
ippsLn_64fc_A53:= getProc(hh,'ippsLn_64fc_A53');
ippsLog10_32fc_A11:= getProc(hh,'ippsLog10_32fc_A11');
ippsLog10_32fc_A21:= getProc(hh,'ippsLog10_32fc_A21');
ippsLog10_32fc_A24:= getProc(hh,'ippsLog10_32fc_A24');
ippsLog10_64fc_A26:= getProc(hh,'ippsLog10_64fc_A26');
ippsLog10_64fc_A50:= getProc(hh,'ippsLog10_64fc_A50');
ippsLog10_64fc_A53:= getProc(hh,'ippsLog10_64fc_A53');
ippsSqrt_32fc_A11:= getProc(hh,'ippsSqrt_32fc_A11');
ippsSqrt_32fc_A21:= getProc(hh,'ippsSqrt_32fc_A21');
ippsSqrt_32fc_A24:= getProc(hh,'ippsSqrt_32fc_A24');
ippsSqrt_64fc_A26:= getProc(hh,'ippsSqrt_64fc_A26');
ippsSqrt_64fc_A50:= getProc(hh,'ippsSqrt_64fc_A50');
ippsSqrt_64fc_A53:= getProc(hh,'ippsSqrt_64fc_A53');
ippsPow_32fc_A11:= getProc(hh,'ippsPow_32fc_A11');
ippsPow_32fc_A21:= getProc(hh,'ippsPow_32fc_A21');
ippsPow_32fc_A24:= getProc(hh,'ippsPow_32fc_A24');
ippsPow_64fc_A26:= getProc(hh,'ippsPow_64fc_A26');
ippsPow_64fc_A50:= getProc(hh,'ippsPow_64fc_A50');
ippsPow_64fc_A53:= getProc(hh,'ippsPow_64fc_A53');
ippsPowx_32fc_A11:= getProc(hh,'ippsPowx_32fc_A11');
ippsPowx_32fc_A21:= getProc(hh,'ippsPowx_32fc_A21');
ippsPowx_32fc_A24:= getProc(hh,'ippsPowx_32fc_A24');
ippsPowx_64fc_A26:= getProc(hh,'ippsPowx_64fc_A26');
ippsPowx_64fc_A50:= getProc(hh,'ippsPowx_64fc_A50');
ippsPowx_64fc_A53:= getProc(hh,'ippsPowx_64fc_A53');
ippsFloor_32f:= getProc(hh,'ippsFloor_32f');
ippsFloor_64f:= getProc(hh,'ippsFloor_64f');
ippsCeil_32f:= getProc(hh,'ippsCeil_32f');
ippsCeil_64f:= getProc(hh,'ippsCeil_64f');
ippsTrunc_32f:= getProc(hh,'ippsTrunc_32f');
ippsTrunc_64f:= getProc(hh,'ippsTrunc_64f');
ippsRound_32f:= getProc(hh,'ippsRound_32f');
ippsRound_64f:= getProc(hh,'ippsRound_64f');
ippsRint_32f:= getProc(hh,'ippsRint_32f');
ippsRint_64f:= getProc(hh,'ippsRint_64f');
ippsNearbyInt_32f:= getProc(hh,'ippsNearbyInt_32f');
ippsNearbyInt_64f:= getProc(hh,'ippsNearbyInt_64f');
ippsModf_32f:= getProc(hh,'ippsModf_32f');
ippsModf_64f:= getProc(hh,'ippsModf_64f');
ippsFrac_32f:= getProc(hh,'ippsFrac_32f');
ippsFrac_64f:= getProc(hh,'ippsFrac_64f');
{ AvO, deprecated or removed (incomplete)
ippiRGBToYCbCr_JPEG_8u_P3R:= getProc(hh,'ippiRGBToYCbCr_JPEG_8u_P3R');
ippiRGBToYCbCr_JPEG_8u_C3P3R:= getProc(hh,'ippiRGBToYCbCr_JPEG_8u_C3P3R');
ippiRGBToYCbCr_JPEG_8u_C4P3R:= getProc(hh,'ippiRGBToYCbCr_JPEG_8u_C4P3R');
ippiYCbCrToRGB_JPEG_8u_P3R:= getProc(hh,'ippiYCbCrToRGB_JPEG_8u_P3R');
ippiYCbCrToRGB_JPEG_8u_P3C3R:= getProc(hh,'ippiYCbCrToRGB_JPEG_8u_P3C3R');
ippiYCbCrToRGB_JPEG_8u_P3C4R:= getProc(hh,'ippiYCbCrToRGB_JPEG_8u_P3C4R');
}
end;
procedure IPPVMtest;
Const
First:boolean=true;
begin
// FPUmask:=getExceptionMask;
if not initIPPVM then
begin
if First then
begin
messageCentral('Unable to initialize IPP library');
First:=false;
end;
sortieErreur('Unable to initialize IPP library');
end;
end;
procedure IPPVMend;
begin
setPrecisionMode(pmExtended);
//SetExceptionMask([exInvalidOp, exDenormalized, exUnderflow])
end;
//*******************************************************************************************************
function fonctionErf(w: double):double;
var
res:double;
begin
IPPVMtest;
if ippsErf_64f_A53( @w, @res,1)<>0 then sortieErreur('Erf error');
result:=res;
IPPVMend;
end;
function fonctionErfc(w: double):double;
var
res:double;
begin
IPPVMtest;
if ippsErfc_64f_A53( @w, @res,1)<>0 then sortieErreur('Erf error');
result:=res;
IPPVMend;
end;
function Erf(w: double):double;
begin
result:= fonctionErf(w);
end;
function Erfc(w: double):double;
begin
result:= fonctionErfc(w);
end;
end.
|
unit NotesManagerU;
interface
uses System.Classes, System.SysUtils, System.IniFiles, System.Generics.Collections,
NoteTypesU;
type
TNotesManager = class
private
FIniFile: TIniFile;
FUserID: string;
function DecodeMultilineText(const AText: string): string;
function EncodeMultilineText(const AText: string): string;
public
constructor Create(const ADirectory: string; const AUserID: string);
destructor Destroy; override;
function GetNotes: TArray<TNote>;
function GetNote(const ATitle: string): TNote;
procedure UpdateNote(const ATitle: string; const ANote: TNote);
procedure AddNote(const ANote: TNote);
procedure DeleteNote(const ATitle: string);
function NoteExists(const ATitle: string): Boolean;
end;
ENoteError = class(Exception);
ENoteNotFound = class(ENoteError);
ENoteDuplicate = class(ENoteError);
ENoteMissingTitle = class(ENoteError);
implementation
{ TNotesManager }
procedure TNotesManager.AddNote(const ANote: TNote);
begin
if ANote.Title = '' then
raise ENoteMissingTitle.Create('Note title required');
if NoteExists(ANote.Title) then
raise ENoteDuplicate.CreateFmt('"%s" already exists', [ANote.Title]);
FIniFile.WriteString(FUserID, ANote.Title, EncodeMultilineText( ANote.Text));
end;
constructor TNotesManager.Create(const ADirectory: string; const AUserID: string);
var
LPath: string;
begin
FUserID := AUserID;
LPath := IncludeTrailingPathDelimiter(ExpandFileName(ADirectory)) + 'notes.ini';
FIniFile := TIniFile.Create(LPath);
end;
function TNotesManager.NoteExists(const ATitle: string): Boolean;
begin
Result := FIniFile.ValueExists(FUserID, ATitle);
end;
procedure TNotesManager.DeleteNote(const ATitle: string);
begin
if not NoteExists(ATitle) then
raise ENoteNotFound.CreateFmt('"%s" not found', [ATitle]);
FIniFile.DeleteKey(FUserID, ATitle);
end;
destructor TNotesManager.Destroy;
begin
FIniFile.Free;
inherited;
end;
function TNotesManager.EncodeMultilineText(const AText: string): string;
var
LBuilder: TStringBuilder;
S: Char;
begin
LBuilder := TStringBuilder.Create;
try
for S in AText do
begin
case S of
#10:
LBuilder.Append('\n');
#13:
LBuilder.Append('\r');
'\':
LBuilder.Append('\\');
else
LBuilder.Append(S);
end;
end;
Result := LBuilder.ToString;
finally
LBuilder.Free;
end;
end;
function TNotesManager.DecodeMultilineText(const AText: string): string;
var
LBuilder: TStringBuilder;
I: Integer;
S: Char;
begin
LBuilder := TStringBuilder.Create;
try
I := 0;
while I < AText.Length do
begin
S := AText.Chars[I];
if (S = '\') and (I+1 < AText.Length) then
case AText.Chars[I+1] of
'n':
begin
Inc(I);
S := #10;
end;
'r':
begin
Inc(I);
S := #13;
end;
'\':
begin
Inc(I);
S := '\';
end
end;
LBuilder.Append(S);
Inc(I);
end;
Result := LBuilder.ToString;
finally
LBuilder.Free;
end;
end;
function TNotesManager.GetNote(const ATitle: string): TNote;
var
LText: string;
begin
if not NoteExists(ATitle) then
raise ENoteNotFound.CreateFmt('"%s" not found', [ATitle]);
LText := DecodeMultilineText(FIniFile.ReadString(FUserID, ATitle, ''));
Result := TNote.Create(ATitle, LText);
end;
function TNotesManager.GetNotes: TArray<TNote>;
var
LList: TList<TNote>;
LNote: TNote;
LSection: TStrings;
I: Integer;
begin
LSection := nil;
LList := nil;
try
LSection := TStringList.Create;
LList := TList<TNote>.Create;
FIniFile.ReadSectionValues(FUserID, LSection);
for I := 0 to LSection.Count - 1 do
begin
LNote := TNote.Create(LSection.Names[I],
DecodeMultilineText(LSection.ValueFromIndex[I]));
LList.Add(LNote);
end;
Result := LList.ToArray;
finally
LList.Free;
LSection.Free;
end;
end;
procedure TNotesManager.UpdateNote(const ATitle: string; const ANote: TNote);
begin
if not NoteExists(ATitle) then
raise ENoteNotFound.CreateFmt('"%s" not found', [ATitle]);
FIniFile.WriteString(FUserID, ATitle, EncodeMultilineText(ANote.Text));
end;
end.
|
unit matmath;
{$IFDEF FPC}
{$mode objfpc}{$ENDIF}{$H+}
interface
uses
Classes, SysUtils, define_types, math;
function pt4f(x,y,z,w: single): TPoint4f; //create float vector
function ptf(x,y,z: single): TPoint3f; //create float vector
function pti(x,y,z: integer): TPoint3i; //create integer vector
function getSurfaceNormal(v1, v2, v3: TPoint3f): TPoint3f;
function normalDirection(v1, v2: TPoint3f): TPoint3f;
function crossProduct(v1, v2: TPoint3f): TPoint3f;
procedure vectorTransform(var v: TPoint3f; mat: TMat44);
procedure vectorNormalize(var v: TPoint3f); inline;
procedure vectorReciprocal(var v: TPoint3f);
function vectorAbs(var v: TPoint3f): TPoint3f;
function vectorDot (A: TPoint3f; B: TPoint3f): single;
procedure vectorAdd (var A: TPoint3f; B: TPoint3f); inline; overload;
function vectorAdd (A: TPoint3i; B: integer): TPoint3i; inline; overload;
procedure vectorSubtract (var A: TPoint3f; B: TPoint3f); inline;
function vectorSubtractF (A: TPoint3f; B: TPoint3f): TPoint3f; inline;
procedure minMax(var v, mn, mx: TPoint3f); overload;
procedure minMax(var v, mn, mx: TPoint3i); overload;
procedure minMax(var v: TPoint3i; var mn, mx: integer); overload;
function vectorLength(pt1, pt2: TPoint3F): single;
function vectorSame(pt1, pt2: TPoint3f): boolean;
function matrixMult(a, b: TMat33): TMat33; overload;
function matrixMult(a, b: TMat44): TMat44; overload;
function matrixEye: TMat44; overload;
function matrixSet(a,b,c, d,e,f, g,h,i: single): TMat33; overload;
function matrixSet(r1c1, r1c2, r1c3, r1c4, r2c1, r2c2, r2c3, r2c4, r3c1, r3c2, r3c3, r3c4: single): TMat44; overload;
function matrixInvert(a: TMat33): TMat33;
procedure matrixNegate(var a: TMat33);
procedure matrixTranspose(var a: TMat33); overload;
procedure matrixTranspose(var a: TMat44); overload;
//function vectorMult (var A: TPoint3f; B: single): TPoint3f; inline; //same as vectorScale
procedure vectorNegate(var v: TPoint3f); inline;
//function AlignVector(alignmentVector: TPoint3f): TMat33;
function vectorDistance(A,B: TPoint3f): single; //[euclidean distance] = sqrt(dX^2+dY^2+dZ^2)
function vectorDistanceSqr(A,B: TPoint3f): single; inline;//[fast as no sqrt] = (dX^2+dY^2+dZ^2)
function vectorScale(A: TPoint3f; Scale: single): TPoint3f; overload; //same as vectorMult
function vectorScale(A: TPoint3f; Scale: TPoint3f): TPoint3f; overload;
procedure MakeCylinder(radius: single; start, dest: TPoint3f; var faces: TFaces; var vertices: TVertices; slices: integer = 20); overload;
procedure MakeCylinder( radius, len: single; var faces: TFaces; var vertices: TVertices; slices: integer = 20); overload;
procedure makeCylinderEnd(radius: single; prevPos, Pos, nextPos: TPoint3f; var vertices: TVertices; var B: TPoint3f; slices: integer = 20);
implementation
procedure vectorReciprocal(var v: TPoint3f);
begin
if v.X <> 0 then v.X := 1/v.X;
if v.Y <> 0 then v.Y := 1/v.Y;
if v.Z <> 0 then v.Z := 1/v.Z;
end;
function vectorDistanceSqr(A,B: TPoint3f): single; inline;
//do not apply sqrt for dramatic speedup!
begin
//result := sqrt(sqr(A.X-B.X)+ sqr(A.Y-B.Y) + sqr(A.Z-B.Z));
result := (sqr(A.X-B.X)+ sqr(A.Y-B.Y) + sqr(A.Z-B.Z));
end;
(* //now called vectorScale()
function vectorMult (var A: TPoint3f; B: single): TPoint3f; inline;
begin
result.X := A.X * B;
result.Y := A.Y * B;
result.Z := A.Z * B;
end;*)
procedure vectorTransform(var v: TPoint3f; mat : TMat44);
var
vx: TPoint3f;
begin
vx := v;
v.X := vx.X*mat[1,1] + vx.Y*mat[1,2] + vx.Z*mat[1,3] + mat[1,4];
v.Y := vx.X*mat[2,1] + vx.Y*mat[2,2] + vx.Z*mat[2,3] + mat[2,4];
v.Z := vx.X*mat[3,1] + vx.Y*mat[3,2] + vx.Z*mat[3,3] + mat[3,4];
end;
function vectorScale(A: TPoint3f; Scale: single): TPoint3f; overload;
begin
result.X := A.X * Scale;
result.Y := A.Y * Scale;
result.Z := A.Z * Scale;
end;
function vectorScale(A: TPoint3f; Scale: TPoint3f): TPoint3f; overload;
begin
result.X := A.X * Scale.X;
result.Y := A.Y * Scale.Y;
result.Z := A.Z * Scale.Z;
end;
function vectorAdd (A: TPoint3i; B: integer): TPoint3i; inline; overload;
begin
result.X := A.X + B;
result.Y := A.Y + B;
result.Z := A.Z + B;
end;
function vectorDistance(A,B: TPoint3f): single;
begin
result := sqrt(sqr(A.X-B.X)+ sqr(A.Y-B.Y) + sqr(A.Z-B.Z));
end;
function distance(A,B: TPoint3f): single;
begin
result := sqrt(sqr(A.X-B.X)+ sqr(A.Y-B.Y) + sqr(A.Z-B.Z));
end;
{$DEFINE NEWCYL}
{$IFDEF NEWCYL}
function Vec3(x,y,z: single): TPoint3f;
begin
result := ptf(x,y, z);
end;
function vectorAdd2 (var A,B: TPoint3f): TPoint3f;
//sum two vectors
begin
result.X := A.X + B.X;
result.Y := A.Y + B.Y;
result.Z := A.Z + B.Z;
end; // vectorAdd()
function getFirstPerpVector(v1: TPoint3f): TPoint3f;
//https://stackoverflow.com/questions/1878257/how-can-i-draw-a-cylinder-that-connects-two-points-in-opengl
//return a vector that is perpendicular to the first
begin
result := Vec3(0.0,0.0,0.0);
if ((v1.x = 0.0) or (v1.y = 0.0) or (v1.z = 0.0)) then begin
if (v1.x = 0.0) then
result.x := 1.0
else if (v1.y = 0.0) then
result.y := 1.0
else
result.z := 1.0;
end else begin
// If xyz is all set, we set the z coordinate as first and second argument .
// As the scalar product must be zero, we add the negated sum of x and y as third argument
result.x := v1.z; //scalp = z*x
result.y := v1.z; //scalp = z*(x+y)
result.z := -(v1.x+v1.y); //scalp = z*(x+y)-z*(x+y) = 0
// Normalize vector
vectorNormalize(result);//result := result.Normalize;
end;
end;
procedure makeCylinder(radius: single; start, dest: TPoint3f; var faces: TFaces; var vertices: TVertices; slices: integer = 20); overload;
//https://stackoverflow.com/questions/1878257/how-can-i-draw-a-cylinder-that-connects-two-points-in-opengl
var
v1, v2, v3, pt: TPoint3f;
c, s: single;
i, num_v, num_f: integer;
begin
//v1 := (dest - start).Normalize; //principle axis of cylinder
v1 := dest;
vectorSubtract(v1, start);
vectorNormalize(v1);
v2 := getFirstPerpVector(v1); //a unit length vector orthogonal to v1
// Get the second perp vector by cross product
v3 := crossProduct(v1,v2); vectorNormalize(v3); //(v1.Cross(v2)).Normalize; //a unit length vector orthogonal to v1 and v2
num_v := 2 * slices;
num_f := 2 * slices;
setlength(faces, num_f);
setlength(vertices, num_v);
for i := 0 to (slices-1) do begin
c := cos(i/slices * 2 *PI);
s := sin(i/slices * 2 * PI);
pt.x := (radius*(c*v2.x+s*v3.x));
pt.y := (radius*(c*v2.y+s*v3.y));
pt.z := (radius*(c*v2.z+s*v3.z));
vertices[i] := vectorAdd2(start,pt);
vertices[i + slices] := vectorAdd2(dest,pt);
if i < (slices-1) then begin
faces[i * 2] := pti( i, i + 1, i+slices);
faces[(i * 2)+1] := pti( i+1, i + slices + 1, i + slices);
end else begin
faces[i * 2] := pti( i, 0, i+slices);
faces[i * 2 + 1] := pti( 0, 0 + slices, i + slices);
end;
end;
end;
procedure MakeCylinder( radius, len: single; var faces: TFaces; var vertices: TVertices; slices : integer = 20); overload;
//procedure MakeCylinder( radius, len: single; var faces: TFaces; var vertices: TVertices); Overload;
//make a triangular mesh cylinder of specified radius and length. length is in X-dimension, so center is from (0,0,0)..(len,0,0)
var
start, dest: TPoint3f;
begin
start := Vec3(0.0,0.0,0.0);
dest := Vec3(len,0.0,0.0);
makeCylinder(radius, start, dest, faces, vertices, slices);
end;
{$ELSE}
function lengthCross (A,B: TPoint3f): single;
var
v: TPoint3f;
begin
v := crossProduct(A, B);
result := sqrt(sqr(v.X)+ sqr(v.Y) + sqr(v.Z));
end;
function AlignVector(alignmentVector: TPoint3f): TMat33;
//http://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d
//much simpler and 20% faster than
// http://www.mathworks.com/matlabcentral/fileexchange/12285-3d-quiver-with-volumized-arrows/content/quiver3D_pub/arrow3D.m
var
A, B, crossBA, vx: TPoint3f;
GG, FFi, invFFi, UU: TMat33;
dotAB: single;
begin
if (alignmentVector.Y = 0.0) and (alignmentVector.Z = 0.0) then begin
alignmentVector.Y := 0.0001;
alignmentVector.Z := 0.0001;
end;
A := ptf(-1, 0, 0);
B := alignmentVector;
GG := matrixSet( vectorDot(A,B), -lengthCross(A,B), 0,
lengthCross(A,B), vectorDot(A,B), 0,
0, 0, 1);
crossBA := crossProduct(B,A);
dotAB := vectorDot(A,B);
vx.X :=B.X - A.X * dotAB;
vx.Y :=B.Y - A.Y * dotAB;
vx.Z :=B.Z - A.Z * dotAB;
vectorNormalize(vx);
FFi := matrixSet(A.X, vx.X, crossBA.X,
A.Y, vx.Y, crossBA.Y,
A.Z, vx.Z, crossBA.Z);
invFFi := matrixInvert(FFi);
UU := matrixMult(FFi, GG);
result := matrixMult(UU,invFFi);
matrixNegate(result);
matrixTranspose(result);
end; //AlignVector
procedure MakeCylinder( radius, len: single; var faces: TFaces; var vertices: TVertices; slices : integer = 20); overload;
//procedure MakeCylinder( radius, len: single; var faces: TFaces; var vertices: TVertices); Overload;
//make a triangular mesh cylinder of specified radius and length. length is in X-dimension, so center is from (0,0,0)..(len,0,0)
var
i, num_v, num_f: integer;
x,y: single;
begin
num_v := 2 * slices;
num_f := 2 * slices;
setlength(vertices, num_v);
setlength(faces, num_f);
for i := 0 to (slices-1) do begin
y := radius * cos(i/slices * 2 *PI);
x := radius * sin(i/slices * 2 * PI);
vertices[i] := ptf(0,x, y);
vertices[i + slices] := ptf(len, x, y);
if i < (slices-1) then begin
faces[i * 2] := pti( i, i + 1, i+slices);
faces[(i * 2)+1] := pti( i+1, i + slices + 1, i + slices);
end else begin
faces[i * 2] := pti( i, 0, i+slices);
faces[i * 2 + 1] := pti( 0, 0 + slices, i + slices);
end;
end;
end; // MakeCylinder()
procedure makeCylinder(radius: single; start, dest: TPoint3f; var faces: TFaces; var vertices: TVertices; slices: integer = 20); overload;
var
alignmentVector, v: TPoint3f;
i: integer;
m: TMat33;
len: single;
begin
len := vectorLength(start, dest);
MakeCylinder(radius, len, faces, vertices, slices);
//rotate
if length(vertices) < 1 then exit;
alignmentVector := dest;
vectorSubtract(alignmentVector, start);
vectorNormalize(alignmentVector);
m := AlignVector(alignmentVector);
for i := 0 to (length(vertices)-1) do begin
v := vertices[i];
vertices[i].X := v.X * m[1,1] + v.Y * m[2,1] + v.Z * m[3,1] + start.X;
vertices[i].Y := v.X * m[1,2] + v.Y * m[2,2] + v.Z * m[3,2] + start.Y;
vertices[i].Z := v.X * m[1,3] + v.Y * m[2,3] + v.Z * m[3,3] + start.Z;
end;
end; // makeCylinder()
{$ENDIF}
function perp_hm(u: TPoint3f): TPoint3f;
//given vector u return an perpendicular (orthogonal) vector
// http://blog.selfshadow.com/2011/10/17/perp-vectors/
var
a: TPoint3f;
begin
a := vectorAbs(u);
if (a.x <= a.y) and (a.x <= a.z) then
result := ptf(0, -u.z, u.y)
else if (a.y <= a.x) and (a.y <= a.z) then
result := ptf(-u.z, 0, u.x)
else
result := ptf(-u.y, u.x, 0);
end; //perp_hm()
procedure frenet(prevPos, nextPos: TPoint3f; out N,B: TPoint3f);
//Compute (N)ormal and (B)inormal of a line
//https://en.wikipedia.org/wiki/Frenet–Serret_formulas
var
T : TPoint3f; //Tangent
begin
//compute Normal and Binormal for each tangent
N := ptf(0,0,0);
B := N;
T := nextPos;
vectorSubtract(T, prevPos); //line tangent
vectorNormalize(T); //unit length
N := perp_hm(T); //normal
B := crossProduct(N,T); //binormal
end; //frenet()
procedure sloan(prevPos, nextPos: TPoint3f; var N,B: TPoint3f);
//Compute (N)ormal and (B)inormal of a line using prior binormal
// https://en.wikipedia.org/wiki/Frenet–Serret_formulas
// http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
// Bloomenthal Graphics Gems 1, "Calculation of Reference Frames along a Space Curve"
// http://webhome.cs.uvic.ca/~blob/courses/305/notes/pdf/ref-frames.pdf
// As noted by Bloomenthal, this is undefined if T1 = B0 (e.g. precise 90-degree joint)
// In this special case we will resort to Frenet
var
T : TPoint3f; //Tangent
begin
//compute Normal and Binormal for each tangent
T := nextPos;
vectorSubtract(T, prevPos); //line tangent
vectorNormalize(T); //unit length
if abs(vectorDot(T,B)) > 0.98 then begin
//hack for Bloomenthal's critique of Sloan's solution :
// if joint is ~90-degrees default to frenet frames
// note that this can lead to some twisting
// however, 90-degree joints are not physiologically plausible in DTI
frenet(prevPos, nextPos, N,B);
exit;
end;
//vectorNegate(B);
//N := crossProduct(B,T); //normal
N := crossProduct(T,B); //normal
vectorNormalize(N); //unit length
B := crossProduct(N,T); //binormal
end; //sload()
procedure makeCylinderEnd(radius: single; prevPos, Pos, nextPos: TPoint3f; var vertices: TVertices; var B: TPoint3f; slices: integer = 20);
// http://www.lab4games.net/zz85/blog/2012/04/24/spline-extrusions-tubes-and-knots-of-sorts/
//make an end cap disk located at Pos and oriented along the axis of the previous and next entry
//Use Ken Sloan's trick to stabilize orientation
// http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
var
i: integer;
cosT, sinT: single;
N: TPoint3f;
begin
if (B.x = 0) and (B.y = 0) and (B.z = 0) then //if first cylinder (so no prior binormal)
frenet(prevPos, nextPos, N,B)
else
sloan(prevPos, nextPos, N,B);
setlength(vertices, slices);
for i := 0 to (slices-1) do begin
cosT := radius * -cos(i/slices * 2 *PI);
sinT := radius * sin(i/slices * 2 * PI);
vertices[i].X := n.X * cosT + b.X * sinT + Pos.X;
vertices[i].Y := n.Y * cosT + b.Y * sinT + Pos.Y;
vertices[i].Z := n.Z * cosT + b.Z * sinT + Pos.Z;
end;
end; // makeCylinderEnd()
(*procedure makeCylinderEnd(radius: single; prevPos, Pos, nextPos: TPoint3f; var vertices: TVertices; slices: integer = 20);
//make an end cap disk located at Pos and oriented along the axis of the previous and next entry
var
i: integer;
x,y: single;
alignmentVector, v: TPoint3f;
m: TMat33;
begin
setlength(vertices, slices);
for i := 0 to (slices-1) do begin
y := radius * cos(i/slices * 2 *PI);
x := radius * sin(i/slices * 2 * PI);
vertices[i] := ptf(0,x, y);
end;
alignmentVector := nextPos;
vectorSubtract(alignmentVector, prevPos);
vectorNormalize(alignmentVector);
m := AlignVector(alignmentVector);
for i := 0 to (slices-1) do begin
v := vertices[i];
vertices[i].X := v.X * m[1,1] + v.Y * m[2,1] + v.Z * m[3,1] + Pos.X;
vertices[i].Y := v.X * m[1,2] + v.Y * m[2,2] + v.Z * m[3,2] + Pos.Y;
vertices[i].Z := v.X * m[1,3] + v.Y * m[2,3] + v.Z * m[3,3] + Pos.Z;
end;
end; // makeCylinderEnd() *)
(*procedure matrixEye(var a: TMat33);
var
i,j: integer;
begin
for i := 1 to 3 do
for j := 1 to 3 do
a[i,j] := 0;
a[1,1] := 1.0;
a[2,2] := 1.0;
a[3,3] := 1.0;
end; // matrixEve() *)
procedure matrixTranspose(var a: TMat44); overload;
var
b: TMat44;
i,j: integer;
begin
b := a;
for i := 1 to 4 do
for j := 1 to 4 do
a[i,j] := b[j,i];
end; // matrixTranspose()
procedure matrixTranspose(var a: TMat33); overload;
var
b: TMat33;
i,j: integer;
begin
b := a;
for i := 1 to 3 do
for j := 1 to 3 do
a[i,j] := b[j,i];
end; // matrixTranspose()
procedure matrixNegate(var a: TMat33);
var
i,j: integer;
begin
for i := 1 to 3 do
for j := 1 to 3 do
a[i,j] := -a[i,j];
end; // matrixNegate()
function matrixInvert( a: TMat33): TMat33;
//Translated by Chris Rorden, from C function "nifti_mat33_inverse"
// Authors: Bob Cox, revised by Mark Jenkinson and Rick Reynolds
// License: public domain
// http://niftilib.sourceforge.net
//Note : For higher performance we could assume the matrix is orthonormal and simply Transpose
//Note : We could also compute Gauss-Jordan here
var
r11,r12,r13,r21,r22,r23,r31,r32,r33, deti : double;
begin
r11 := a[1,1]; r12 := a[1,2]; r13 := a[1,3]; // [ r11 r12 r13 ]
r21 := a[2,1]; r22 := a[2,2]; r23 := a[2,3]; // [ r21 r22 r23 ]
r31 := a[3,1]; r32 := a[3,2]; r33 := a[3,3]; // [ r31 r32 r33 ]
deti := r11*r22*r33-r11*r32*r23-r21*r12*r33
+r21*r32*r13+r31*r12*r23-r31*r22*r13 ;
if( deti <> 0.0 ) then
deti := 1.0 / deti ;
result[1,1] := deti*( r22*r33-r32*r23) ;
result[1,2] := deti*(-r12*r33+r32*r13) ;
result[1,3] := deti*( r12*r23-r22*r13) ;
result[2,1] := deti*(-r21*r33+r31*r23) ;
result[2,2] := deti*( r11*r33-r31*r13) ;
result[2,3] := deti*(-r11*r23+r21*r13) ;
result[3,1] := deti*( r21*r32-r31*r22) ;
result[3,2] := deti*(-r11*r32+r31*r12) ;
result[3,3] := deti*( r11*r22-r21*r12) ;
end; // matrixInvert()
function vectorDot (A: TPoint3f; B: TPoint3f): single;
begin //dot product
result := A.X*B.X + A.Y*B.Y + A.Z*B.Z;
end; // vectorDot()
function matrixSet(r1c1, r1c2, r1c3, r1c4, r2c1, r2c2, r2c3, r2c4, r3c1, r3c2, r3c3, r3c4: single): TMat44; overload;
begin
result[1,1]:=r1c1; result[1,2]:=r1c2; result[1,3]:=r1c3; result[1,4]:=r1c4;
result[2,1]:=r2c1; result[2,2]:=r2c2; result[2,3]:=r2c3; result[2,4]:=r2c4;
result[3,1]:=r3c1; result[3,2]:=r3c2; result[3,3]:=r3c3; result[3,4]:=r3c4;
result[4,1]:=0; result[4,2]:=0; result[4,3]:=0; result[4,4]:=1;
end;
function matrixEye: TMat44;
begin
result := matrixSet(1,0,0,0, 0,1,0,0, 0,0,1,0);
end;
function matrixSet(a,b,c, d,e,f, g,h,i: single): TMat33; overload;
begin
result[1,1]:=a; result[1,2]:=b; result[1,3]:=c;
result[2,1]:=d; result[2,2]:=e; result[2,3]:=f;
result[3,1]:=g; result[3,2]:=h; result[3,3]:=i;
end; // matrixSet()
function matrixMult(a, b: TMat44): TMat44; overload;
var i,j: integer;
begin
for i := 1 to 4 do begin
for j := 1 to 4 do begin
result[i, j] := A[i, 1] * B[1,j]
+ A[i, 2] * B[2, j]
+ A[i, 3] * B[3, j]
+ A[i, 4] * B[4, j];
end; //for j
end; //for i
end; //multiplymatrices()
function matrixMult(a, b: TMat33): TMat33; overload;
var i,j: integer;
begin
for i := 1 to 3 do begin
for j := 1 to 3 do begin
result[i, j] := A[i, 1] * B[1,j]
+ A[i, 2] * B[2, j]
+ A[i, 3] * B[3, j];
end; //for j
end; //for i
end; //multiplymatrices()
function pt4f(x,y,z, w: single): TPoint4f; //create float vector
begin
result.X := x;
result.Y := y;
result.Z := z;
result.W := w;
end; // pt4f()
function ptf(x,y,z: single): TPoint3f; //create float vector
begin
result.X := x;
result.Y := y;
result.Z := z;
end; // ptf()
function pti(x,y,z: integer): TPoint3i; //create integer vector
begin
result.X := x;
result.Y := y;
result.Z := z;
end; // pti()
procedure minMax(var v, mn, mx: TPoint3f); overload;
begin
if v.X > mx.X then
mx.X := v.X;
if v.X < mn.X then
mn.X := v.X;
if v.Y > mx.Y then
mx.Y := v.Y;
if v.Y < mn.Y then
mn.Y := v.Y;
if v.Z > mx.Z then
mx.Z := v.Z;
if v.Z < mn.Z then
mn.Z := v.Z;
end; // minMax()
procedure minMax(var v, mn, mx: TPoint3i); overload;
begin
if v.X > mx.X then
mx.X := v.X;
if v.X < mn.X then
mn.X := v.X;
if v.Y > mx.Y then
mx.Y := v.Y;
if v.Y < mn.Y then
mn.Y := v.Y;
if v.Z > mx.Z then
mx.Z := v.Z;
if v.Z < mn.Z then
mn.Z := v.Z;
end; // minMax()
procedure minMax(var v: TPoint3i; var mn, mx: integer); overload;
begin
if v.X > mx then
mx := v.X
else if v.X < mn then
mn := v.X;
if v.Y > mx then
mx := v.Y
else if v.Y < mn then
mn := v.Y;
if v.Z > mx then
mx := v.Z
else if v.Z < mn then
mn := v.Z;
end; // minMax()
function crossProduct(v1, v2: TPoint3f): TPoint3f;
// http://openinggl.blogspot.com/2012/04/adding-lighting-normals.html
begin
result := ptf(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z,
v1.x * v2.y - v1.y * v2.x);
end; // CrossProduct()
function vectorAbs(var v: TPoint3f): TPoint3f;
begin
result.X := abs(v.X);
result.Y := abs(v.Y);
result.Z := abs(v.Z);
end; // abs()
procedure vectorNormalize(var v: TPoint3f); inline;
var
len: single;
begin
len := sqrt( (v.X*v.X) + (v.Y*v.Y) + (v.Z*v.Z) );
if len <= 0 then exit;
v.X := v.X / len;
v.Y := v.Y / len;
v.Z := v.Z / len;
end; // normalize()
function normalDirection(v1, v2: TPoint3f): TPoint3f;
begin
result.X := v2.X - v1.X;
result.Y := v2.Y - v1.Y;
result.Z := v2.Z - v1.Z;
vectorNormalize(result);
end; // normalDirection()
procedure vectorAdd (var A: TPoint3f; B: TPoint3f); inline;
//sum two vectors
begin
A.X := A.X + B.X;
A.Y := A.Y + B.Y;
A.Z := A.Z + B.Z;
end; // vectorAdd()
function vectorLength(pt1, pt2: TPoint3F): single;
begin
result := sqrt (sqr(pt1.X - pt2.X) + sqr(pt1.Y - pt2.Y) + sqr(pt1.Z - pt2.Z) );
end; // vectorLength()
function vectorSame(pt1, pt2: TPoint3F): boolean;
//returns true if pt1 = pt2
// faster than "vectorLength(pt1, pt2) <> 0"
begin
result := false;
if SameValue(pt1.X, pt2.X) and SameValue(pt1.Y, pt2.Y) and SameValue(pt1.Z, pt2.Z) then
result := true;
end; // vectorLength()
procedure vectorNegate(var v: TPoint3f); inline;
begin
v.X := -v.X;
v.Y := -v.Y;
v.Z := -v.Z;
end; // vectorNegate()
function vectorSubtractF (A: TPoint3f; B: TPoint3f): TPoint3f; inline;
begin
result.X := A.X - B.X;
result.Y := A.Y - B.Y;
result.Z := A.Z - B.Z;
end;
procedure vectorSubtract (var A: TPoint3f; B: TPoint3f); inline;
//sum two vectors
begin
A.X := A.X - B.X;
A.Y := A.Y - B.Y;
A.Z := A.Z - B.Z;
end; // vectorSubtract()
function getSurfaceNormal(v1, v2, v3: TPoint3f): TPoint3f;
var
polyVector1, polyVector2: TPoint3f;
begin
polyVector1 := ptf(v2.x - v1.x, v2.y - v1.y, v2.z - v1.z);
polyVector2 := ptf(v3.x - v1.x, v3.y - v1.y, v3.z - v1.z);
result := crossProduct(polyVector1, polyVector2);
//make sure to normalize(result) !
end; // getSurfaceNormal()
end.
|
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0035.PAS
Description: LongInt to HEX
Author: GREG VIGNEAULT
Date: 11-02-93 05:52
*)
{
GREG VIGNEAULT
> So to assign the File I will need the HEX in String format.
}
Type
String8 = String[8];
Var
MyStr : String8;
ALong : LongInt;
{ convert a LongInt value to an 8-Character String, using hex digits }
{ (using all 8 Chars will allow correct order in a sorted directory) }
Procedure LongToHex(AnyLong : LongInt; Var HexString : String8);
Var
ch : Char;
Index : Byte;
begin
HexString := '00000000'; { default to zero }
Index := Length(HexString); { String length }
While AnyLong <> 0 do
begin { loop 'til done }
ch := Chr(48 + Byte(AnyLong) and $0F); { 0..9 -> '0'..'9' }
if ch > '9' then
Inc(ch, 7); { 10..15 -> 'A'..'F'}
HexString[Index] := ch; { insert Char }
Dec(Index); { adjust chr Index }
AnyLong := AnyLong SHR 4; { For next nibble }
end;
end;
begin
ALong := $12A45678; { a LongInt value }
LongToHex(ALong, MyStr); { convert to hex str}
WriteLn;
WriteLn('$', MyStr); { display the String}
WriteLn;
end.
|
unit uFrmCargo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmCrudBase, DB, DBClient, StdCtrls, Grids, DBGrids, Buttons,
ExtCtrls, uCargoDAOClient, Cargo;
type
TFrmCargo = class(TFrmCrudBase)
cdsCrudID: TIntegerField;
cdsCrudDESCRICAO: TStringField;
private
{ Private declarations }
DAOClient: TCargoDAOClient;
protected
procedure CreateDAOClient; override;
procedure DestroyDAOClient; override;
procedure OnShow; override;
procedure OnInsert; override;
procedure OnEdit; override;
procedure OnDelete; override;
procedure OnPesquisar; override;
public
{ Public declarations }
end;
var
FrmCargo: TFrmCargo;
implementation
uses DataUtils, MensagensUtils, uFrmDadosCargo, TypesUtils;
{$R *.dfm}
{ TFrmCargo }
procedure TFrmCargo.CreateDAOClient;
begin
inherited;
DAOClient := TCargoDAOClient.Create(DBXConnection);
end;
procedure TFrmCargo.DestroyDAOClient;
begin
DAOClient.Free;
inherited;
end;
procedure TFrmCargo.OnDelete;
begin
inherited;
if (Confirma('Deseja excluir este cargo?')) then
if (DAOClient.Delete(TCargo.Create(cdsCrudID.AsInteger))) then
cdsCrud.Delete
else
Erro('Ocorreu algum erro durante a exlusão.');
end;
procedure TFrmCargo.OnEdit;
var
f: TFrmDadosCargo;
begin
inherited;
f := TFrmDadosCargo.Create(Self);
try
f.Cargo.Id := cdsCrudID.AsInteger;
f.Cargo.Descricao := cdsCrudDESCRICAO.AsString;
f.Operacao := opEdit;
f.ShowModal;
finally
f.Free;
end;
end;
procedure TFrmCargo.OnInsert;
var
f: TFrmDadosCargo;
begin
inherited;
f := TFrmDadosCargo.Create(Self);
try
f.Operacao := opInsert;
f.ShowModal;
finally
f.Free;
end;
end;
procedure TFrmCargo.OnPesquisar;
begin
inherited;
cdsCrud.Filtered := False;
cdsCrud.Filter := 'UPPER(DESCRICAO) LIKE ' + QuotedStr('%'+UpperCase(edtPesquisar.Text)+'%');
cdsCrud.Filtered := True;
end;
procedure TFrmCargo.OnShow;
begin
inherited;
CopyReaderToClientDataSet(DAOClient.List, cdsCrud);
end;
end.
|
unit ProjectView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ImgList,
PngImageList,
LrProject, Project;
type
TProjectForm = class(TForm)
ProjectImages: TPngImageList;
ProjectMenu: TPopupMenu;
AddExistingPage1: TMenuItem;
OpenDialog: TOpenDialog;
Generate1: TMenuItem;
SetupServers1: TMenuItem;
SetupDatabases1: TMenuItem;
AddFolder1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure AddExistingPage1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Generate1Click(Sender: TObject);
procedure ProjectMenuPopup(Sender: TObject);
procedure AddFolder1Click(Sender: TObject);
private
{ Private declarations }
function GetProject: TProject;
procedure GetImageIndex(inItem: TLrProjectItem;
var ImageIndex: Integer);
procedure GetOverlayIndex(inItem: TLrProjectItem;
var ImageIndex: Integer);
procedure ProjectCanDrag(inItem: TLrProjectItem;
var inAllowed: Boolean);
procedure ProjectCanDrop(inDragItem, inDropItem: TLrProjectItem;
inShift: TShiftState; var inAccept: Boolean);
procedure ProjectCanEdit(inItem: TLrProjectItem;
var inAllowed: Boolean);
procedure ProjectDragDrop(inDragItem, inDropItem: TLrProjectItem;
inShift: TShiftState);
procedure ProjectNewText(inItem: TLrProjectItem;
const inNewText: WideString);
procedure SetProject(const Value: TProject);
public
{ Public declarations }
procedure OpenItem(inItem: TLrProjectItem);
property Project: TProject read GetProject write SetProject;
end;
var
ProjectForm: TProjectForm;
implementation
uses
LrUtils, LrDocument, LrProjectView,
htDatabases,
Globals, Config, Controller, Servers, Documents, TurboPhpDocument;
const
cColWidthValue = 'PrjColumn0Width';
{$R *.dfm}
procedure TProjectForm.FormCreate(Sender: TObject);
begin
AddForm(LrProjectForm, TLrProjectForm, Self);
LrProjectForm.Tree.Images := ProjectImages;
LrProjectForm.Tree.PopupMenu := ProjectMenu;
LrProjectForm.OnOpenItem := OpenItem;
LrProjectForm.OnGetImageIndex := GetImageIndex;
LrProjectForm.OnGetOverlayIndex := GetOverlayIndex;
LrProjectForm.OnCanDrag := ProjectCanDrag;
LrProjectForm.OnCanDrop := ProjectCanDrop;
LrProjectForm.OnDragDrop := ProjectDragDrop;
LrProjectForm.OnCanEdit := ProjectCanEdit;
LrProjectForm.OnNewText := ProjectNewText;
OpenDialog.Filter := MakeFilter(cTurboPhpDocuments,
'*' + TTurboPhpDocument.DocumentExt + ';' +
'*' + cPhpExt + ';' +
GraphicFileMask(TGraphic));
OpenDialog.InitialDir := ProjectsHome;
ProjectImages.Overlay(7, 0);
ProjectImages.Overlay(11, 1);
end;
procedure TProjectForm.FormDestroy(Sender: TObject);
begin
Configuration.Integers[cColWidthValue] :=
LrProjectForm.Tree.Header.Columns[0].Width;
end;
function TProjectForm.GetProject: TProject;
begin
Result := TProject(LrProjectForm.Project);
end;
procedure TProjectForm.SetProject(const Value: TProject);
begin
LrProjectForm.Project := Value;
with LrProjectForm.Tree.Header.Columns[0] do
Width := Configuration.GetIntegerDef(cColWidthValue, Width);
end;
procedure TProjectForm.GetImageIndex(inItem: TLrProjectItem;
var ImageIndex: Integer);
begin
if inItem is TServerItem then
// if Project.Servers.DefaultServer = inItem then
// ImageIndex := 7
// else
ImageIndex := 1
else if inItem is ThtDatabaseItem then
ImageIndex := 3;
end;
procedure TProjectForm.GetOverlayIndex(inItem: TLrProjectItem;
var ImageIndex: Integer);
//var
// d: TLrDocument;
begin
if inItem is TServerItem then
begin
if Project.Servers.DefaultServer = inItem then
ImageIndex := 1
{
end else if inItem is TDocumentItem then
begin
d := Desktop.FindDocument(inItem.Source);
if (d <> nil) and (d.Modified) then
ImageIndex := 0;
}
end;
end;
procedure TProjectForm.ProjectCanDrag(inItem: TLrProjectItem;
var inAllowed: Boolean);
begin
inAllowed := LrProjectForm.FolderItem[inItem] is TLrFolderItem;
end;
procedure TProjectForm.ProjectCanDrop(inDragItem, inDropItem: TLrProjectItem;
inShift: TShiftState; var inAccept: Boolean);
begin
inAccept := (inDropItem = nil) or
(LrProjectForm.FolderItem[inDropItem] is TLrFolderItem);
end;
procedure TProjectForm.ProjectDragDrop(inDragItem, inDropItem: TLrProjectItem;
inShift: TShiftState);
var
folder: TLrProjectItem;
begin
Project.Items.BeginUpdate;
try
folder := LrProjectForm.FolderItem[inDragItem.Parent];
folder.Remove(inDragItem);
folder := LrProjectForm.FolderItem[inDropItem];
folder.Add(inDragItem);
finally
Project.Items.EndUpdate;
end;
end;
procedure TProjectForm.ProjectCanEdit(inItem: TLrProjectItem;
var inAllowed: Boolean);
begin
inAllowed := (inItem is TLrFolderItem);
end;
procedure TProjectForm.ProjectNewText(inItem: TLrProjectItem;
const inNewText: WideString);
begin
inItem.Source := inNewText;
end;
procedure TProjectForm.ProjectMenuPopup(Sender: TObject);
begin
with LrProjectForm do
begin
if SelectedItem <> nil then
begin
AddExistingPage1.Visible := (SelectedItem is TDocumentItem)
or (SelectedItem = Self.Project.Documents);
Generate1.Visible := SelectedItem is TDocumentItem;
SetupServers1.Visible := (SelectedItem is TServersItem)
or (SelectedItem is TServerItem);
SetupDatabases1.Visible := (SelectedItem is ThtDatabasesItem)
or (SelectedItem is ThtDatabaseItem);
end;
AddFolder1.Visible := SelectedFolderItem is TLrFolderItem;
end;
end;
procedure TProjectForm.AddExistingPage1Click(Sender: TObject);
begin
with OpenDialog do
if Execute then
Project.AddDocumentItem(ControllerModule.Open(Filename).Filename);
end;
procedure TProjectForm.OpenItem(inItem: TLrProjectItem);
begin
if inItem is TDocumentItem then
ControllerModule.Open(inItem.Source)
else if inItem is TServerItem then
begin
Project.Servers.DefaultServer := TServerItem(inItem);
Project.Modify;
end;
end;
procedure TProjectForm.Generate1Click(Sender: TObject);
begin
if LrProjectForm.SelectedItem is TDocumentItem then
Project.PublishDocument(LrProjectForm.SelectedItem.Source);
end;
procedure TProjectForm.AddFolder1Click(Sender: TObject);
var
folder: TLrFolderItem;
begin
folder := TLrFolderItem.Create;
folder.Source := 'New Folder';
LrProjectForm.SelectedFolderItem.Add(folder);
end;
end.
|
namespace Sequences_and_Queries;
interface
uses
System.Collections.Generic,
System.Windows.Forms,
System.Drawing,
System.Linq, System.Data;
type
/// <summary>
/// Summary description for MainForm.
/// </summary>
MainForm = partial class(System.Windows.Forms.Form)
private
method MainForm_Load(sender: System.Object; e: System.EventArgs);
method buttonExecute_Click(sender: System.Object; e: System.EventArgs);
method buttonRefresh_Click(sender: System.Object; e: System.EventArgs);
method loadData;
method filterData : sequence of Customer;
method orderData: sequence of Customer;
method reverseData: sequence of Customer;
method takeData: sequence of Customer;
method skipData: sequence of Customer;
method drillIntoDetails: sequence of Customer;
method distinctData (seq : sequence of Customer) : sequence of Customer;
method selectSubset;
method useIntermediateVariable : sequence of Customer;
method joinData;
method groupData;
method showGroup;
method buttonNext_Click(sender: System.Object; e: System.EventArgs);
method buttonPrev_Click(sender: System.Object; e: System.EventArgs);
method listBoxQueries_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
protected
method Dispose(disposing: Boolean); override;
var
MyCustomers: sequence of Customer;
groupIndex: Integer;
Descriptions : sequence of String;
public
constructor;
end;
type
Customer = public class
public
property CustomerId: String;
property CompanyName: String;
property Address: String;
property City: String;
property Country: String;
property OrdersList: sequence of Orders;
constructor;
constructor (setCustomerId:String; setCompanyName:String; setAddress:String; setCity:String; setCountry:String; setOrdersList:sequence of Orders);
end;
Orders = public class
property OrderID: Integer;
property OrderDate: DateTime;
property Freight: Double;
constructor (setOrderId:Integer; setOrderDate:DateTime; setFreight:Double);
end;
Company = public class
property CompanyName: String;
property ContactName: String;
property ContactTitle: String;
constructor (setCompanyName: String; setContactName: String; setContactTitle: String);
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
end;
method MainForm.Dispose(disposing: Boolean);
begin
if disposing then begin
if assigned(components) then
components.Dispose();
//
// TODO: Add custom disposition code here
//
end;
inherited Dispose(disposing);
end;
constructor Customer;
begin
end;
constructor Customer (setCustomerId:String; setCompanyName:String; setAddress:String; setCity:String; setCountry:String; setOrdersList:sequence of Orders);
begin
self.CustomerId := setCustomerId;
self.CompanyName := setCompanyName;
self.Address := setAddress;
self.City := setCity;
self.Country:= setCountry;
self.OrdersList := setOrdersList;
end;
constructor Orders (setOrderId:Integer; setOrderDate:DateTime; setFreight:Double);
begin
self.OrderID := setOrderId;
self.OrderDate := setOrderDate;
self.Freight := setFreight;
end;
constructor Company (setCompanyName: String; setContactName: String; setContactTitle: String);
begin
self.CompanyName := setCompanyName;
self.ContactName := setContactName;
self.ContactTitle := setContactTitle;
end;
{$ENDREGION}
method MainForm.MainForm_Load(sender: System.Object; e: System.EventArgs);
begin
loadData();
Descriptions := Helper.FillDescriptions;
listBoxQueries.DataSource := Helper.FillQueries();
end;
method MainForm.buttonExecute_Click(sender: System.Object; e: System.EventArgs);
begin
buttonNext.Visible := false;
buttonPrev.Visible := false;
case listBoxQueries.SelectedIndex of
-1 : MessageBox.Show('Please, select query.', 'Query', MessageBoxButtons.OK, MessageBoxIcon.Warning);
0 : dataGridViewData.DataSource := filterData.ToArray;
1 : dataGridViewData.DataSource := orderData.ToArray;
2 : dataGridViewData.DataSource := reverseData.ToArray;
3 : dataGridViewData.DataSource := takeData.ToArray;
4 : dataGridViewData.DataSource := skipData.ToArray;
5 : selectSubset;
6 : dataGridViewData.DataSource := distinctData(drillIntoDetails).ToArray;
7 : groupData;
8 : joinData;
9 : dataGridViewData.DataSource := useIntermediateVariable.ToArray;
end;
try
dataGridViewData.Columns['OrdersList'].Visible := false;
except
end;
end;
method MainForm.listBoxQueries_SelectedIndexChanged(sender: System.Object; e: System.EventArgs);
begin
textBoxDescription.Text := Descriptions.ElementAt(listBoxQueries.SelectedIndex);
end;
method MainForm.buttonRefresh_Click(sender: System.Object; e: System.EventArgs);
begin
loadData();
end;
method MainForm.buttonNext_Click(sender: System.Object; e: System.EventArgs);
begin
groupIndex := groupIndex + 1;
showGroup;
end;
method MainForm.buttonPrev_Click(sender: System.Object; e: System.EventArgs);
begin
groupIndex := groupIndex - 1;
showGroup;
end;
method MainForm.showGroup;
begin
var groupList := from c in MyCustomers group by c.Country;
dataGridViewData.DataSource := groupList.ElementAt(groupIndex).ToArray;
if groupIndex <> groupList.Count-1 then
buttonNext.Enabled := true
else
buttonNext.Enabled := false;
if groupIndex <> 0 then
buttonPrev.Enabled := true
else
buttonPrev.Enabled := false;
end;
method MainForm.loadData;
begin
MyCustomers := Helper.FillCustomers();
dataGridViewData.DataSource := MyCustomers.ToArray;
dataGridViewData.Columns['OrdersList'].Visible := false;
buttonNext.Visible := false;
buttonPrev.Visible := false;
end;
method MainForm.filterData: sequence of Customer;
begin
result := from c in MyCustomers where c.City = 'London';
end;
method MainForm.orderData: sequence of Customer;
begin
result := from c in MyCustomers order by c.CompanyName desc;
end;
method MainForm.reverseData: sequence of Customer;
begin
result := from c in MyCustomers reverse;
end;
method MainForm.takeData: sequence of Customer;
begin
result := from c in MyCustomers take 7;
end;
method MainForm.skipData: sequence of Customer;
begin
result := from c in MyCustomers skip 7;
end;
method MainForm.groupData;
begin
groupIndex := 0;
buttonNext.Visible := true;
buttonPrev.Visible := true;
showGroup;
end;
method MainForm.selectSubset;
begin
dataGridViewData.DataSource := (from c in MyCustomers select new class (c.CustomerId, Location := c.City + ', ' +c.Country)).ToArray;
end;
method MainForm.drillIntoDetails: sequence of Customer;
begin
result := from c in MyCustomers where c.City = 'London' from o in c.OrdersList order by o.OrderDate select c;
end;
method MainForm.distinctData (seq : sequence of Customer) : sequence of Customer;
begin
result := from c in seq distinct;
end;
method MainForm.joinData;
begin
var Companies := Helper.FillCompanies;
dataGridViewData.DataSource := (from cust in MyCustomers join comp in Companies on cust.CompanyName equals comp.CompanyName
select new class (cust.CompanyName, cust.City, Contact:= comp.ContactName + ', ' + comp.ContactTitle)).ToArray;
end;
method MainForm.useIntermediateVariable: sequence of Customer;
begin
result := from c in MyCustomers with Address := c.City+', '+c.Address where Address.Contains('London') select c;
end;
end. |
(********************************************************)
(* *)
(* Bare Game Library *)
(* http://www.baregame.org *)
(* 0.5.0.0 Released under the LGPL license 2013 *)
(* *)
(********************************************************)
{ <include docs/bare.text.txt> }
unit Bare.Text;
{$i bare.inc}
interface
uses
Bare.System,
Bare.Types;
const
DefaultValueSeparator = '=';
type
TStringList = class;
IStringEnumerator = interface(IEnumerator<string>)
end;
TStringKeys = class
private
FStrings: TStringList;
public
function GetEnumerator: IStringEnumerator;
procedure Add(const Key, Value: string);
procedure Remove(const Key: string);
function IndexOf(Key: string): Integer;
function Find(Key: string): Boolean;
function Key(Index: Integer): string;
function Value(Index: Integer): string;
function GetValue(Key: string): string;
procedure SetValue(Key: string; const Value: string);
property Values[const Key: string]: string read GetValue write SetValue; default;
end;
TStringList = class(TIndexedList<string>)
private
FCaseSensitive: Boolean;
FKeys: TStringKeys;
FValueSeparator: string;
function GetKeys: TStringKeys;
function GetText: string;
procedure SetText(const Value: string);
protected
procedure AddItem(constref Item: string); override;
public
constructor Create;
destructor Destroy; override;
procedure LoadFromFile(const FileName: string);
procedure SaveToFile(const FileName: string);
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
function IndexOf(const Item: TItem): Integer; override;
property CaseSensitive: Boolean read FCaseSensitive write FCaseSensitive;
property Text: string read GetText write SetText;
property Keys: TStringKeys read GetKeys;
property ValueSeparator: string read FValueSeparator write FValueSeparator;
end;
TEncodeMethod = (emHex, emBase64);
IBuffer = interface
['{62C3AEC2-A51F-468C-9664-6027FF8722E6}']
function GetData: Pointer;
function GetSize: LongWord;
procedure SetSize(Value: LongWord);
property Data: Pointer read GetData;
property Size: LongWord read GetSize write SetSize;
end;
{ TBuffer manages encoding/decoding binary data }
TBuffer = record
private
FBuffer: IBuffer;
function GetData: Pointer;
function GetSize: LongWord;
procedure SetSize(Value: LongWord);
public
class function Create(Size: LongWord): TBuffer; static;
class operator Implicit(const Value: TBuffer): Pointer;
property Data: Pointer read GetData;
property Size: LongWord read GetSize write SetSize;
function Encode(Method: TEncodeMethod = emBase64): string;
end;
{ Hex routines }
function HexEncode(Buffer: Pointer; Size: LongWord): string; overload;
function HexEncode(const Buffer: TBuffer): string; overload;
function HexEncode(const S: string): string; overload;
function HexDecode(const S: string): TBuffer;
{ Base64 routines }
function Base64Encode(Buffer: Pointer; Size: LongWord): string; overload;
function Base64Encode(const Buffer: TBuffer): string; overload;
function Base64Encode(const S: string): string; overload;
function Base64Decode(const S: string): TBuffer;
implementation
type
TStringEnumerator = class(TInterfacedObject, IStringEnumerator)
private
FStrings: TStringList;
FPosition: Integer;
public
constructor Create(Strings: TStringList);
function GetCurrent: string;
function MoveNext: Boolean;
end;
constructor TStringEnumerator.Create(Strings: TStringList);
begin
inherited Create;
FStrings := Strings;
FPosition := -1;
end;
function TStringEnumerator.GetCurrent: string;
begin
Result := StrFirstOf(FStrings[FPosition], FStrings.FValueSeparator);
end;
function TStringEnumerator.MoveNext: Boolean;
var
S: string;
begin
Result := False;
repeat
Inc(FPosition);
if FPosition = FStrings.Count then
Exit(False);
S := StrTrim(FStrings[FPosition]);
if S = '' then
Continue;
until Result;
end;
{ TStringKeys }
function TStringKeys.GetEnumerator: IStringEnumerator;
begin
Result := TStringEnumerator.Create(FStrings);
end;
procedure TStringKeys.Add(const Key, Value: string);
begin
SetValue(Key, Value);
end;
procedure TStringKeys.Remove(const Key: string);
var
I: Integer;
begin
I := IndexOf(Key);
if I > -1 then
FStrings.Delete(I);
end;
function TStringKeys.IndexOf(Key: string): Integer;
var
S: string;
I: Integer;
begin
Result := -1;
Key := StrTrim(Key);
if Key = '' then
Exit;
if not FStrings.FCaseSensitive then
Key := StrUpper(Key);
for I := 0 to FStrings.Count - 1 do
begin
S := StrTrim(FStrings[I]);
S := StrFirstOf(S, FStrings.FValueSeparator);
if S = '' then
Continue;
if not FStrings.FCaseSensitive then
S := StrUpper(S);
if S = Key then
Exit(I);
end;
end;
function TStringKeys.Find(Key: string): Boolean;
begin
Result := IndexOf(Key) > -1;
end;
function TStringKeys.Key(Index: Integer): string;
begin
Result := StrFirstOf(FStrings[Index], FStrings.FValueSeparator);
Result := StrTrim(Result);
end;
function TStringKeys.Value(Index: Integer): string;
begin
Result := StrSecondOf(FStrings[Index], FStrings.FValueSeparator);
Result := StrTrim(Result);
end;
function TStringKeys.GetValue(Key: string): string;
var
I: Integer;
begin
I := IndexOf(Key);
if I < 0 then
Result := ''
else
Result := StrTrim(StrSecondOf(FStrings[I], FStrings.FValueSeparator));
end;
procedure TStringKeys.SetValue(Key: string; const Value: string);
var
I: Integer;
begin
Key := StrTrim(Key);
if (Key = '') or (Key = FStrings.FValueSeparator) then
Exit;
I := IndexOf(Key);
if I < 0 then
FStrings.Add(Key + FStrings.FValueSeparator + StrTrim(Value))
else
FStrings[I] := Key + FStrings.FValueSeparator + StrTrim(Value);
end;
{ TStringList }
constructor TStringList.Create;
begin
inherited Create;
FCaseSensitive := True;
FValueSeparator := DefaultValueSeparator;
end;
destructor TStringList.Destroy;
begin
FKeys.Free;
inherited Destroy;
end;
procedure TStringList.AddItem(constref Item: TItem);
var
Lines: IntArray;
S, B, L: string;
I, J: Integer;
begin
S := StrAdjustLineBreaks(Item);
B := LineEnding;
Lines := StrFindIndex(S, B);
if Length(Lines) < 1 then
begin
inherited AddItem(S);
Exit;
end;
J := 1;
for I := Low(Lines) to High(Lines) do
begin
L := StrCopy(S, J, Lines[I] - J);
inherited AddItem(L);
Inc(J, Length(L) + Length(B));
end;
L := StrCopy(S, J, Length(S) + 1);
inherited AddItem(L);
end;
procedure TStringList.LoadFromFile(const FileName: string);
var
Stream: TStream;
I: Integer;
begin
Clear;
Stream := TFileStream.Create(FileName, fmOpen);
try
I := Stream.Size;
if I < 1 then
Exit;
Text := Stream.ReadStr(I);
finally
Stream.Free;
end;
end;
procedure TStringList.SaveToFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
Stream.WriteStr(Text);
finally
Stream.Free;
end;
end;
procedure TStringList.LoadFromStream(Stream: TStream);
var
I: Integer;
begin
Clear;
if Stream.Cancelled then
Exit;
I := Stream.Position - Stream.Size;
if I < 1 then
Exit;
Text := Stream.ReadStr(I);
end;
procedure TStringList.SaveToStream(Stream: TStream);
begin
if not Stream.Cancelled then
Stream.WriteStr(Text);
end;
function FindStringI(const A, B: string): Integer;
begin
if A < B then
Result := -1
else if A > B then
Result := 1
else
Result := 0;
end;
function FindString(const A, B: string): Integer;
begin
Result := FindStringI(A, StrUpper(B));
end;
function TStringList.IndexOf(const Item: TItem): Integer;
begin
if FCaseSensitive then
Result := Find(FindString, StrUpper(Item))
else
Result := Find(FindStringI, Item);
end;
function TStringList.GetKeys: TStringKeys;
begin
if FKeys = nil then
begin
FKeys := TStringKeys.Create;
FKeys.FStrings := Self;
end;
Result := FKeys;
end;
function TStringList.GetText: string;
var
S, B: string;
P: PChar;
I, J: Integer;
begin
if Count = 0 then
Exit('');
if Count = 1 then
Exit(Item[0]);
I := 0;
J := -1;
for S in Self do
begin
Inc(I, Length(S));
Inc(J);
end;
B := LineEnding;
SetLength(Result, I + J * Length(B));
P := PChar(Result);
for S in Self do
begin
Move(PChar(S)^, P^, Length(S));
Inc(P, Length(S));
if J > 0 then
begin
Move(PChar(B)^, P^, Length(S));
Inc(P, Length(B));
end;
Dec(J);
end;
end;
procedure TStringList.SetText(const Value: string);
begin
Clear;
if Value = '' then
Exit;
Add(Value);
end;
{ TBufferObject }
type
TBufferObject = class(TInterfacedObject, IBuffer)
private
FData: Pointer;
FSize: LongWord;
public
constructor Create(Size: LongWord);
destructor Destroy; override;
function GetData: Pointer;
function GetSize: LongWord;
procedure SetSize(Value: LongWord);
end;
constructor TBufferObject.Create(Size: LongWord);
begin
inherited Create;
FSize := Size;
if FSize > 0 then
GetMem(FData, FSize)
else
FData := nil;
end;
destructor TBufferObject.Destroy;
begin
if FData <> nil then
FreeMem(FData);
inherited Destroy;
end;
function TBufferObject.GetData: Pointer;
begin
Result := FData;
end;
function TBufferObject.GetSize: LongWord;
begin
Result := FSize;
end;
procedure TBufferObject.SetSize(Value: LongWord);
begin
if Value <> FSize then
begin
FSize := Value;
if FSize > 0 then
begin
if FData <> nil then
ReallocMem(FData, FSize)
else
GetMem(FData, FSize);
end
else
begin
if FData <> nil then
FreeMem(FData);
FData := nil;
end;
end;
end;
{ TBuffer }
class function TBuffer.Create(Size: LongWord): TBuffer;
begin
if Size > 0 then
Result.FBuffer := TBufferObject.Create(Size)
else
Result.FBuffer := nil;
end;
class operator TBuffer.Implicit(const Value: TBuffer): Pointer;
begin
if Value.FBuffer = nil then
Result := nil
else
Result := Value.FBuffer.Data;
end;
function TBuffer.Encode(Method: TEncodeMethod = emBase64): string;
begin
case Method of
emHex: Result := HexEncode(Data, Size);
emBase64: Result := Base64Encode(Data, Size);
else
Result := '';
end;
end;
function TBuffer.GetData: Pointer;
begin
if FBuffer = nil then
Result := nil
else
Result := FBuffer.Data;
end;
function TBuffer.GetSize: LongWord;
begin
if FBuffer = nil then
Result := 0
else
Result := FBuffer.Size;
end;
procedure TBuffer.SetSize(Value: LongWord);
begin
if FBuffer = nil then
FBuffer := TBufferObject.Create(Value);
FBuffer.Size := Value;
end;
{ Hex routines }
function HexEncode(Buffer: Pointer; Size: LongWord): string;
const
Hex: PChar = '0123456789ABCDEF';
var
B: PByte;
C: PChar;
begin
if Size = 0 then
Exit('');
SetLength(Result, Size shl 1);
B := PByte(Buffer);
C := PChar(Result);
while Size > 0 do
begin
C^ := Hex[B^ shr $4];
Inc(C);
C^ := Hex[B^ and $F];
Inc(C);
Inc(B);
Dec(Size);
end;
end;
function HexEncode(const Buffer: TBuffer): string;
begin
Result := HexEncode(Buffer.Data, Buffer.Size);
end;
function HexEncode(const S: string): string;
begin
Result := HexEncode(Pointer(S), Length(S));
end;
function HexDecode(const S: string): TBuffer;
const
Digit0 = Ord('0');
DigitA = Ord('A');
var
B: PByte;
C: PChar;
I: Integer;
begin
I := Length(S);
if Odd(I) or (I = 0) then
Exit(TBuffer.Create(0));
Result := TBuffer.Create(I shr 1);
B := Result.Data;
C := PChar(S);
I := 0;
repeat
if C[I] in ['0'..'9'] then
B^ := (Ord(C[I]) - Digit0) shl $4
else if C[I] in ['A'..'F'] then
B^ := (Ord(C[I]) - DigitA + $A) shl $4
else
Exit(TBuffer.Create(0));
Inc(I);
if C[I] in ['0'..'9'] then
B^ := B^ or (Ord(C[I]) - Digit0)
else if C[I] in ['A'..'F'] then
B^ := B^ or (Ord(C[I]) - DigitA + $A)
else
Exit(TBuffer.Create(0));
Inc(B);
Inc(I);
until C[I] = #0;
end;
{ Base64 routines }
function Base64EncodedSize(Size: LongWord): Cardinal;
begin
Result := (Size div 3) shl 2;
if (Size mod 3) > 0 then
Inc(Result, 4);
end;
function Base64Encode(Buffer: Pointer; Size: LongWord): string;
const
Base64: PChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
Fill: Char = '=';
var
B: PByte;
C: Byte;
I: LongWord;
J: LongWord;
begin
SetLength(Result, Base64EncodedSize(Size));
B := Buffer;
I := 0;
J := 0;
while I < Size do
begin
C := (B[I] shr 2) and $3F;
Inc(J);
Result[J] := Base64[C];
C := (B[I] shl 4) and $3f;
Inc(I);
if I < Size then
C := C or ((B[I] shr 4) and $0F);
Inc(J);
Result[J] := Base64[C];
if I < Size then
begin
C := (B[I] shl 2) and $3F;
Inc(I);
if I < Size then
C := C or ((B[I] shr 6) and $03);
Inc(J);
Result[J] := Base64[C];
end
else
begin
Inc(I);
Inc(J);
Result[J] := Fill;
end;
if I < Size then
begin
C := B[I] and $3F;
Inc(J);
Result[J] := Base64[C];
end
else
begin
Inc(J);
Result[J] := Fill;
end;
Inc(I);
end;
end;
function Base64Encode(const Buffer: TBuffer): string;
begin
Result := Base64Encode(Buffer, Buffer.Size);
end;
function Base64Encode(const S: string): string;
begin
Result := Base64Encode(Pointer(S), Length(S));
end;
function Base64Decode(const S: string): TBuffer;
procedure Zero(out Sextext, Index: LongWord); inline;
begin
Sextext := 0;
Inc(Index);
end;
function Search(out Sextext, Index: LongWord): Boolean;
const
Base64: PChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var
C: Char;
I: Integer;
begin
Sextext := 0;
C := S[Index];
Inc(Index);
for I := 0 to 63 do
if C = Base64[I] then
begin
Sextext := I;
Exit(True);
end;
Result := False;
end;
type
TOutput = array[0..0] of Byte;
POutput = ^TOutput;
var
Buffer: TBuffer;
Output: POutput;
InLen, OutLen, A, B, C, D, E, I, J: LongWord;
begin
Result := TBuffer.Create(0);
InLen := Length(S);
if (InLen < 1) or (InLen mod 4 <> 0) then
Exit;
OutLen := InLen div 4 * 3;
if S[InLen] = '=' then
Dec(OutLen);
if S[InLen - 1] = '=' then
Dec(OutLen);
if OutLen < 1 then
Exit;
Buffer := TBuffer.Create(OutLen);
Output := Buffer.Data;
J := 0;
I := 1;
Inc(InLen);
while I < InLen do
begin
if S[I] = '=' then Zero(A, I) else if not Search(A, I) then Exit;
if S[I] = '=' then Zero(B, I) else if not Search(B, I) then Exit;
if S[I] = '=' then Zero(C, I) else if not Search(C, I) then Exit;
if S[I] = '=' then Zero(D, I) else if not Search(D, I) then Exit;
E := A shl 18 + B shl 12 + C shl 6 + D;
if J = OutLen then Break;
Output[J] := E shr 16 and $FF; Inc(J);
if J = OutLen then Break;
Output[J] := E shr 8 and $FF; Inc(J);
if J = OutLen then Break;
Output[J] := E and $FF; Inc(J);
end;
Result := Buffer;
end;
end.
|
unit DPM.IDE.ProjectTree.Containers;
interface
uses
System.Classes,
System.Rtti;
type
//we don't actually need to implement these, just need them to get the TContainer right
//NOTE : The guids were discovered via RTTI - do not change unless they change in a later IDE version
IModelContainer = interface
['{DAA1E441-B99A-11D1-931D-00C04FB17A5E}']
end;
IGraphLocation = interface
['{2EEFC3B0-01CF-11D1-9ADA-0000C0091B45}']
end;
IGraphData = interface
['{F0DDFBA3-8EA2-491E-B63D-C6023955E3F6}']
end;
ICustomProjectGroupProject = interface
['{F567E16A-DA4E-459F-9718-9A51559FFA0B}']
end;
//Since we don't have dcu's or dcp for the container classes, we are doing a direct
//cast to our container class below, and using RTTI to access the private fields.
//hacky but works!
{
The class heirachy looks like this
TInterfacedObject
TBaseContainer
TStdContainer
TStdFileContainer
TStdProjectContainer
TStdDelphiProjectContainer
TStdContainerCategory
The idea here is to match the public interface of container classes which we got via RTTI.
This is actually TStdProjectContainer but we can use it for other container types
provided we don't use props that don't exist.
Seems to work fine in XE7 at least!
}
TProjectTreeContainer = class(TInterfacedObject)
private
class var
FRttiContext : TRttiContext;
FCategoryRttiType : TRttiInstanceType;
FContainerConstructor : TRttiMethod;
private
function GetImageIndex : Integer;
procedure SetImageIndex(const Value : Integer);
function GetDisplayName : string;
class constructor Create;
function GetChildren : IInterfaceList;
function GetModelContainer : IModelContainer;
function GetGraphLocation : IGraphLocation;
function GetGraphData : IGraphData;
function GetParent : IGraphLocation;
function GetProject : ICustomProjectGroupProject;
procedure SetChildren(const Value : IInterfaceList);
function GetFileName : string;
procedure SetFileName(const Value : string);
public
class function CreateNewContainer(const parentContainer : TProjectTreeContainer; const displayName : string; const identifier : string; const childId : string = '') : TProjectTreeContainer;
property FileName : string read GetFileName write SetFileName;
property ModelContainer : IModelContainer read GetModelContainer;
property Parent : IGraphLocation read GetParent;
property Project : ICustomProjectGroupProject read GetProject;
property ImageIndex : Integer read GetImageIndex write SetImageIndex;
property DisplayName : string read GetDisplayName;
property Children : IInterfaceList read GetChildren write SetChildren;
property GraphLocation : IGraphLocation read GetGraphLocation;
property GraphData : IGraphData read GetGraphData;
end;
implementation
uses
System.SysUtils,
WinApi.Windows;
const
//used GExperts PE Information to find all the container classes
//this one looks the most likely - couldn't get TStdContainer to work
cCategoryContainerClass = 'Containers.TStdContainerCategory';
class constructor TProjectTreeContainer.Create;
var
rttiMethod : TRttiMethod;
begin
FRttiContext := TRttiContext.Create;
FContainerConstructor := nil;
//find the class we will use to create new containers.. not 100% on correct class to use here.
FCategoryRttiType := FRttiContext.FindType(cCategoryContainerClass).AsInstance;
Assert(FCategoryRttiType <> nil);
//find the constructor and cache it for later.
for rttiMethod in FCategoryRttiType.GetMethods do
begin
if rttiMethod.IsConstructor then
begin
FContainerConstructor := rttiMethod;
exit;
end;
end;
end;
class function TProjectTreeContainer.CreateNewContainer(const parentContainer : TProjectTreeContainer; const displayName, identifier, childId : string) : TProjectTreeContainer;
var
params : TArray<TRttiParameter>;
locationParam, projectParam, modelParam : TValue;
model : IInterface; //note this can't be more specific
project : IInterface;
graphLocation : IInterface;
begin
Assert(FContainerConstructor <> nil);
params := FContainerConstructor.GetParameters;
//from GExperts PE information on XE7
//@Containers@TStdContainerCategory@$bctr$qqrx54System@%DelphiInterface$27Projectintf@IModelContainer%x61System@%DelphiInterface$34Codemgr@ICustomProjectGroupProject%x50System@%DelphiInterface$23Idemodel@IGraphLocation%x20System@UnicodeStringt4t4
// GetParameters gives more information about the parameters
//
// 0 : AModelContainer : IModelContainer
// 1 : AProject : ICustomProjectGroupProject
// 2 : AGraphParent : IGraphLocation // parent graph node
// 3 : ACategoryName : string // display name
// 4 : ACategoryIdent : string // tools api ident is typically just a unique string
// 5 : AChildItemID : string //dunno what this is meant to be but seems to work with ''
model := parentContainer.ModelContainer;
TValue.Make(@model, params[0].ParamType.Handle, modelParam);
project := parentContainer.Project;
TValue.Make(@project, params[1].ParamType.Handle, projectParam);
graphLocation := TInterfacedObject(parentContainer) as IGraphLocation;
TValue.Make(@graphLocation, params[2].ParamType.Handle, locationParam);
Result := TProjectTreeContainer(FContainerConstructor.Invoke(FCategoryRttiType.MetaclassType, [modelParam, projectParam, locationParam, displayName, identifier, childId]).AsObject);
end;
function TProjectTreeContainer.GetChildren : IInterfaceList;
begin
Result := IInterfaceList(FRttiContext.GetType(ClassType).GetField('FChildren').GetValue(Self).AsInterface);
end;
function TProjectTreeContainer.GetDisplayName : string;
begin
Result := FRttiContext.GetType(ClassType).GetField('FDisplayName').GetValue(Self).AsString;
end;
function TProjectTreeContainer.GetFileName : string;
begin
Result := FRttiContext.GetType(ClassType).GetField('FFileName').GetValue(Self).AsString;
end;
function TProjectTreeContainer.GetImageIndex : Integer;
begin
Result := FRttiContext.GetType(ClassType).GetField('FImageIndex').GetValue(Self).AsInteger;
end;
function TProjectTreeContainer.GetModelContainer : IModelContainer;
begin
// Result := FRttiContext.GetType(ClassType).GetField('FModelContainer').GetValue(Self).AsType<IModelContainer>; //gets typecast error
Result := IModelContainer(FRttiContext.GetType(ClassType).GetField('FModelContainer').GetValue(Self).AsInterface);
end;
function TProjectTreeContainer.GetGraphLocation : IGraphLocation;
begin
result := TInterfacedObject(Self) as IGraphLocation;
end;
function TProjectTreeContainer.GetGraphData : IGraphData;
begin
result := TInterfacedObject(Self) as IGraphData;
end;
function TProjectTreeContainer.GetParent : IGraphLocation;
begin
Result := IGraphLocation(FRttiContext.GetType(ClassType).GetField('FGraphParent').GetValue(Self).AsInterface);
end;
function TProjectTreeContainer.GetProject : ICustomProjectGroupProject;
begin
Result := ICustomProjectGroupProject(FRttiContext.GetType(ClassType).GetField('FProject').GetValue(Self).AsInterface);
end;
procedure TProjectTreeContainer.SetChildren(const Value : IInterfaceList);
begin
FRttiContext.GetType(ClassType).GetField('FChildren').SetValue(Self, TValue.From(Value));
end;
procedure TProjectTreeContainer.SetFileName(const Value : string);
begin
FRttiContext.GetType(ClassType).GetField('FFileName').SetValue(Self, TValue.From(Value));
end;
procedure TProjectTreeContainer.SetImageIndex(const Value : Integer);
begin
FRttiContext.GetType(ClassType).GetField('FImageIndex').SetValue(Self, Value);
end;
end.
|
unit FMX.ISEditEx;
interface
uses
System.SysUtils, System.Classes, System.Types, System.UITypes, System.DateUtils, System.Generics.Collections, FMX.Utils, FMX.Types, FMX.Controls, FMX.Objects, FMX.StdCtrls, FMX.Graphics, FMX.MultiResBitmap,
FMX.Ani, FMX.Effects, System.Actions, FMX.ActnList, FMX.Layouts, FMX.Filter.Effects, System.Rtti,
FMX.Controls.Presentation,
FMX.Styles.Objects,
FMX.Edit,
FMX.IS_Base;
Type
TIS_Edit = Class(TEdit)
Private
FEnter : TNotifyEvent;
FExit : TNotifyEvent;
Protected
Procedure DoEnter; Override;
Procedure DoExit; Override;
Procedure ApplyStyleLookup; Override;
Property ISOnEnter : TNotifyEvent Read FEnter Write FEnter;
property ISOnExit : TNotifyEvent Read FExit Write FExit;
Public
End;
[ComponentPlatformsAttribute (pidWin32 or pidWin64 or pidOSX32 or pidiOSDevice32 or pidiOSDevice64 or pidAndroid)]
TIS_EditEx = Class(TIS_Control)
Private
CLabel : TLabel;
CEdit : TIS_Edit;
function GetKeyBoardType : TVirtualKeyBoardType;
function GetMaxLength : Integer;
function GetText : String;
function GetTextColor : TAlphaColor;
function GetTextFont : TFont;
function GetPrompt : String;
function GetPromptColor : TAlphaColor;
procedure SetKeyBoardType(const Value: TVirtualKeyBoardType);
procedure SetMaxLength (const Value: Integer);
procedure SetPrompt (const Value: String);
procedure SetPromptColor (const Value: TAlphaColor);
procedure SetText (const Value: String);
procedure SetTextColor (const Value: TAlphaColor);
procedure SetTextFont (const Value: TFont);
procedure LabelDown;
procedure LabelUp;
Procedure EnterEdit (Sender : TObject);
Procedure ExitEdit (Sender : TObject);
Protected
procedure Clicked; Override;
procedure Resize; Override;
Public
Constructor Create(aOwner : TComponent); Override;
Published
Property Edit : TIS_Edit Read CEdit Write CEdit;
Property Text : String Read GetText Write SetText;
Property TextColor : TAlphaColor Read GetTextColor Write SetTextColor;
Property TextFont : TFont Read GetTextFont Write SetTextFont;
Property KeyBoardType : TVirtualKeyBoardType Read GetKeyBoardType Write SetKeyBoardType;
Property MaxLength : Integer Read GetMaxLength Write SetMaxLength;
Property Prompt : String Read GetPrompt Write SetPrompt;
Property PromptColor : TAlphaColor Read GetPromptColor Write SetPromptColor;
End;
Procedure Register;
implementation
Procedure Register;
Begin
RegisterComponents('Imperium Software', [TIS_EditEx]);
End;
{ TISEdit }
procedure TIS_Edit.DoEnter;
begin
inherited;
if Assigned(ISOnEnter) then ISOnEnter(Self);
end;
procedure TIS_Edit.DoExit;
begin
inherited;
if Assigned(ISOnExit) then ISOnExit(Self);
end;
procedure TIS_Edit.ApplyStyleLookup;
Var
Obj: TFmxObject;
begin
inherited;
Obj := FindStyleResource('background');
If Assigned(Obj) And (Obj is TActiveStyleObject) Then
Begin
TActiveStyleObject(Obj).Align := TAlignLayout.None;
TActiveStyleObject(Obj).Position.Y := -1000;
Obj.DisposeOf;
End;
end;
{ TIS_EditEx }
constructor TIS_EditEx.Create(aOwner: TComponent);
begin
inherited;
CEdit := TIS_edit.Create(Self);
CEdit.Parent := Self;
Cedit.Stored := False;
CEdit.Align := TAlignLayout.None;
CEdit.Height := 22;
CEdit.HitTest := False;
CEdit.StyledSettings := [];
CEdit.Font.Size := 14;
CEdit.ISOnEnter := EnterEdit;
CEdit.ISOnExit := ExitEdit;
CLabel := TLabel .Create(Self);
CLabel.Parent := Self;
CLabel.Stored := False;
CLabel.Text := '';
CLabel.Height := 22;
CLabel.AutoSize := False;
CLabel.StyledSettings := [];
CLabel.Font.Size := 14;
Width := 100;
Height := 30;
end;
procedure TIS_EditEx.Resize;
begin
inherited;
CEdit .Position.X := 4;
CEdit .Position.Y := Self.Height - (CEdit.Height + 4);
CEdit .Width := Self.Width - 8;
CLabel.Position := CEdit.Position;
CLabel.Width := Self.Width - 8;
end;
procedure TIS_EditEx.Clicked;
Begin
Inherited;
TThread.CreateAnonymousThread(
Procedure
Begin
Sleep(20);
TThread.Queue(Nil,
Procedure
Begin
CEdit.BringToFront;
CEdit.SetFocus;
End);
End).Start;
End;
procedure TIS_EditEx.LabelDown;
begin
if Not CLabel.Text.IsEmpty then
Begin
TAnimator.AnimateFloat(Clabel, 'Position.Y', CEdit.Position.Y);
End;
end;
procedure TIS_EditEx.LabelUp;
begin
if Not CLabel.Text.IsEmpty then
Begin
TAnimator.AnimateFloat(Clabel, 'Position.Y', 4);
End;
end;
procedure TIS_EditEx.EnterEdit(Sender: TObject);
begin
if CLabel.Position.Y > 4 Then LabelUp;
end;
procedure TIS_EditEx.ExitEdit(Sender: TObject);
begin
if CEdit.Text.IsEmpty then LabelDown;
end;
function TIS_EditEx.GetKeyBoardType: TVirtualKeyBoardType;
begin
Result := CEdit.KeyboardType;
end;
function TIS_EditEx.GetMaxLength: Integer;
begin
Result := CEdit.MaxLength;
end;
function TIS_EditEx.GetPrompt: String;
begin
Result := CLabel.Text;
end;
function TIS_EditEx.GetPromptColor: TAlphaColor;
begin
Result := CLabel.TextSettings.FontColor;
end;
function TIS_EditEx.GetText: String;
begin
Result := CEdit.Text;
end;
function TIS_EditEx.GetTextColor: TAlphaColor;
begin
Result := CEdit.TextSettings.FontColor;
end;
function TIS_EditEx.GetTextFont: TFont;
begin
Result := CEdit.TextSettings.Font;
end;
procedure TIS_EditEx.SetKeyBoardType(const Value: TVirtualKeyBoardType);
begin
Cedit.KeyboardType := Value;
end;
procedure TIS_EditEx.SetMaxLength(const Value: Integer);
begin
CEdit.MaxLength := Value;
end;
procedure TIS_EditEx.SetPrompt(const Value: String);
begin
CLabel.Text := Value;
if Value.IsEmpty then
Self.Height := CEdit.Height + 8
Else
Self.Height := Cedit.Height + 8 + 20;
end;
procedure TIS_EditEx.SetPromptColor(const Value: TAlphaColor);
begin
CLabel.TextSettings.FontColor := Value;
end;
procedure TIS_EditEx.SetText(const Value: String);
begin
CEdit.Text := Value;
if Value.IsEmpty then
Begin
if CLabel.Position.Y <> CEdit.Position.Y then CLabel.Position.Y := CEdit.Position.Y;
End
Else
Begin
if CLabel.Position.Y = CEdit.Position.Y then CLabel.Position.Y := 4;
End;
end;
procedure TIS_EditEx.SetTextColor(const Value: TAlphaColor);
begin
Cedit.TextSettings.FontColor := Value;
end;
procedure TIS_EditEx.SetTextFont(const Value: TFont);
begin
CEdit.TextSettings.Font := Value;
end;
end.
|
unit uRegREST;
{*******************************************************************************
* *
* Название модуля : *
* *
* uRegREST *
* *
* Назначение модуля : *
* *
* Ведение реестра остатков по заработной плате и стипендии. *
* *
* Copyright © Год 2006, Автор: Найдёнов Е.А *
* *
*******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase,
pFIBDatabase, FIBDataSet, pFIBDataSet, dxBar, dxBarExtItems, ImgList,
cxStyles, Menus, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, dxStatusBar, cxGridCustomPopupMenu,
cxGridPopupMenu, cxContainer, cxRadioGroup, cxSplitter, ExtCtrls,
cxGridBandedTableView, cxGridDBBandedTableView, uneTypes, uneLibrary;
type
TfmRegREST = class(TForm, IneCallExpMethod)
dbWork : TpFIBDatabase;
spcWork : TpFIBStoredProc;
trRead : TpFIBTransaction;
trWrite : TpFIBTransaction;
dstDoc : TpFIBDataSet;
dstRest : TpFIBDataSet;
dsrDoc : TDataSource;
dsrRest : TDataSource;
srpWork : TcxStyleRepository;
pnlRest : TPanel;
pnlRestDesc : TPanel;
splRest : TcxSplitter;
splRestDesc : TcxSplitter;
cxsHeader : TcxStyle;
cxsFooter : TcxStyle;
cxsContent : TcxStyle;
cxHotTrack : TcxStyle;
cxsInactive : TcxStyle;
cxsIndicator : TcxStyle;
cxsSelection : TcxStyle;
cxBackground : TcxStyle;
cxsGroupByBox : TcxStyle;
cxsContentOdd : TcxStyle;
cxsColumnHeader : TcxStyle;
cxsContentEvent : TcxStyle;
cxsColumnHeaderClassic : TcxStyle;
imlToolBar : TImageList;
brmWork : TdxBarManager;
btnAdd : TdxBarLargeButton;
btnEdit : TdxBarLargeButton;
btnExit : TdxBarLargeButton;
btnWatch : TdxBarLargeButton;
btnDelete : TdxBarLargeButton;
btnRefresh : TdxBarLargeButton;
edtYear : TdxBarSpinEdit;
edtMonth : TdxBarCombo;
edtRegUch : TdxBarCombo;
pmnuWork : TPopupMenu;
bpmnWork : TdxBarPopupMenu;
gpmnWork : TcxGridPopupMenu;
sbrWork : TdxStatusBar;
bccTypeDoc : TdxBarControlContainerItem;
gbxTypeDoc : TcxRadioGroup;
gdDoc : TcxGrid;
gdRest : TcxGrid;
lvlDoc : TcxGridLevel;
lvlRest : TcxGridLevel;
tvwDoc : TcxGridDBBandedTableView;
tvwRest : TcxGridDBBandedTableView;
tvwDocDBBandedColumn1 : TcxGridDBBandedColumn;
tvwDocDBBandedColumn2 : TcxGridDBBandedColumn;
tvwDocDBBandedColumn3 : TcxGridDBBandedColumn;
tvwDocDBBandedColumn4 : TcxGridDBBandedColumn;
tvwRestDBBandedColumn1 : TcxGridDBBandedColumn;
tvwRestDBBandedColumn2 : TcxGridDBBandedColumn;
tvwRestDBBandedColumn3 : TcxGridDBBandedColumn;
tvwRestDBBandedColumn4 : TcxGridDBBandedColumn;
tvwRestDBBandedColumn5 : TcxGridDBBandedColumn;
tvwRestDBBandedColumn6 : TcxGridDBBandedColumn;
private
{ Private declarations }
FResultExpMethod : TneGetExpMethod;
public
{ Public declarations }
property pResultExpMethod : TneGetExpMethod read FResultExpMethod implements IneCallExpMethod;
end;
implementation
{$R *.dfm}
end.
|
unit SDUFileIterator_U;
// Description: File Iterator
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
SDUDirIterator_U;
type
TSDUFileIterator = class(TComponent)
private
currDir: string;
currDirsFiles: TStringList;
currFileIdx: integer;
dirIterator: TSDUDirIterator;
procedure ReadFilenames(theDir: string);
protected
FRootDirectory: string;
FFileMask: string;
FSorted: boolean;
FRecurseSubDirs: boolean;
FOmitStartDirPrefix: boolean;
FIncludeDirNames: boolean;
function SlashSep(const Path, S: String): String;
procedure SetRootDirectory(const theDir: string);
procedure SetFileMask(const theFileMask: string);
procedure SortedFilenames(sort: boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure Reset();
function Next(): string;
function Count(): integer;
published
property Directory: string read FRootDirectory write SetRootDirectory;
property FileMask: string read FFileMask write SetFileMask;
property Sorted: boolean read FSorted write SortedFilenames;
property RecurseSubDirs: boolean read FRecurseSubDirs write FRecurseSubDirs;
property OmitStartDirPrefix: boolean read FOmitStartDirPrefix write FOmitStartDirPrefix;
// If this is set, the directory names will be output, as well as filenames
// Set to FALSE by default
property IncludeDirNames: boolean read FIncludeDirNames write FIncludeDirNames;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('SDeanUtils', [TSDUFileIterator]);
end;
constructor TSDUFileIterator.Create(AOwner: TComponent);
begin
inherited;
currDirsFiles := TStringList.Create();
currFileIdx:=0;
FRootDirectory := '.';
FFileMask := '*.*';
FOmitStartDirPrefix := FALSE;
FIncludeDirNames := FALSE;
dirIterator:= TSDUDirIterator.Create(nil);
end;
destructor TSDUFileIterator.Destroy();
begin
dirIterator.Free();
currDirsFiles.Free();
inherited;
end;
procedure TSDUFileIterator.Reset();
begin
dirIterator.Directory := FRootDirectory;
dirIterator.Reset();
ReadFilenames(dirIterator.Next());
end;
function TSDUFileIterator.Count(): integer;
var
cnt: integer;
begin
cnt := 0;
Reset();
while (Next() <> '') do
begin
inc(cnt);
end;
Reset();
Result := cnt;
end;
function TSDUFileIterator.Next(): string;
var
nextDir: string;
returnFilename: string;
begin
Result := '';
while currFileIdx>=currDirsFiles.count do
begin
if not(RecurseSubDirs) then
begin
exit;
end;
nextDir := dirIterator.Next();
if nextDir='' then
begin
// No more directories to process; exit while return value is still ''
exit;
end
else
begin
ReadFilenames(nextDir);
end;
end;
// At this point, we know that there's a file to return
returnFilename := SlashSep(currDir, currDirsFiles[currFileIdx]);
inc(currFileIdx);
//xxx - if (returnFilename = SlashSep(Directory, '')) then
//xxx - begin
//xxx - Result := Next();
//xxx - exit;
//xxx - end;
// If we are to omit the starting directory from items returned, remove it
// now.
if OmitStartDirPrefix then
begin
Delete(returnFilename, 1, Length(Directory));
// Remove any starting slash
if (returnFilename[1] = '\') then
begin
Delete(returnFilename, 1, 1);
end;
// If the result is an empty string, then
if (returnFilename = '') then
begin
returnFilename := 'ZZZZ';
end;
end;
Result := returnFilename;
end;
function TSDUFileIterator.SlashSep(const Path, S: String): String;
begin
if AnsiLastChar(Path)^ <> '\' then
Result := Path + '\' + S
else
Result := Path + S;
end;
procedure TSDUFileIterator.ReadFilenames(theDir: string);
var
SearchRec: TSearchRec;
Status: integer;
begin
currDirsFiles.Clear();
if theDir<>'' then
begin
Status := FindFirst(SlashSep(theDir, FFileMask), faAnyFile, SearchRec);
while (Status=0) do
begin
if (FIncludeDirNames or ((SearchRec.Attr AND faDirectory) <> faDirectory)) then
begin
// Ignore "." and ".." entries
if ((SearchRec.Name <> '.') and (SearchRec.Name <> '..')) then
begin
currDirsFiles.add(SearchRec.Name);
end;
end;
Status := FindNext(SearchRec);
end;
FindClose(SearchRec);
end;
currDirsFiles.Sorted := FSorted;
currFileIdx:=0;
currDir := theDir;
end;
procedure TSDUFileIterator.SetRootDirectory(const theDir: string);
begin
FRootDirectory := theDir;
Reset();
end;
procedure TSDUFileIterator.SetFileMask(const theFileMask: string);
var
tmpDir: string;
begin
tmpDir := ExtractFilePath(theFileMask);
if (tmpDir <> '') then
begin
Directory := tmpDir;
end;
FFileMask := ExtractFileName(theFileMask);
Reset();
end;
procedure TSDUFileIterator.SortedFilenames(sort: boolean);
begin
FSorted:= sort;
currDirsFiles.Sorted := FSorted;
end;
END.
|
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Printers,
Vcl.StdCtrls;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
Button2: TButton;
Button1: TButton;
Memo1: TMemo;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
printDialog : TPrintDialog;
LocalPrinter: TPrinter;
begin
// Create a printer selection dialog
printDialog := TPrintDialog.Create(Form1);
// If the user has selected a printer (or default), then print!
if printDialog.Execute then
begin
// Use the Printer function to get access to the
// global TPrinter object.
// All references below are to the TPrinter object
LocalPrinter := printer;
with LocalPrinter do
begin
// Start printing
BeginDoc;
// Set up a large blue font
Canvas.Font.Size := 20;
Canvas.Font.Color := clBlue;
// Write out the page size
Canvas.TextOut(20, 20, 'Page width = ' + IntToStr(PageWidth));
Canvas.TextOut(20, 150, 'Page height = ' + IntToStr(PageHeight));
Canvas.Font.Name := 'Cambria';
Canvas.Font.Size := 8;
Canvas.Font.Color := clBlack;
Canvas.TextOut(10, 300, 'data');
Canvas.TextOut(10, 600, 'makan');
// Finish printing
EndDoc;
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
bmp: TBitmap;
begin
{Create Component Images}
try
bmp := TBitmap.Create;
try
bmp.Width := 400;
bmp.Height := 400;
// your Barcode - Code here
bmp.LoadFromFile(ExtractFileDir(Application.ExeName)+'/picture.bmp');
bmp.Canvas.Ellipse(10, 10, 300, 300);
printer.BeginDoc;
printer.Canvas.Draw(10, 10, bmp);
printer.EndDoc;
finally
{Release Component when Finish Code}
bmp.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
printDialog : TPrintDialog;
LocalPrinter: TPrinter;
begin
try
// Create a printer selection dialog
printDialog := TPrintDialog.Create(Form1);
// If the user has selected a printer (or default), then print!
if printDialog.Execute then
begin
// Use the Printer function to get access to the
// global TPrinter object.
// All references below are to the TPrinter object
LocalPrinter := printer;
with LocalPrinter do
begin
// Start printing
BeginDoc;
// Set up a large blue font
Canvas.Font.Size := 10;
Canvas.Font.Color := clBlack;
// Write out the page size
// Canvas.TextOut(10, 10, '12345678910' );
Canvas.TextOut(0, 0, Memo1.Lines.Text);
Canvas.Font.Size := 20;
Canvas.Font.Color := clBlack;
Canvas.Font.Name := 'Cambria';
Canvas.Font.Style := [fsBold];
Canvas.TextOut(0, 20, Memo1.Lines.Text);
// Finish printing
EndDoc;
end;
end;
finally
printDialog.Free;
end;
end;
end.
|
unit MainUnit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
CalcButton: TButton;
CircleButton: TButton;
RadiusEdit: TEdit;
XWidthEdit: TEdit;
YHeightEdit: TEdit;
XPosEdit: TEdit;
YPosEdit: TEdit;
Label1: TLabel;
Label10: TLabel;
Label11: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
AlphaLabel: TLabel;
BetaLabel: TLabel;
Shape: TShape;
procedure CalcButtonClick(Sender: TObject);
procedure CircleButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ShapePaint(Sender: TObject);
private
{ private declarations }
candraw: boolean;
radius, X, Y, XWidth, YHeight, alpha, beta: double;
procedure Calc;
function GetParameters: Boolean;
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.Calc;
begin
alpha := (Y - X) / radius;
beta := (-Y - X) / radius;
candraw := true;
self.Invalidate;
end;
function TForm1.GetParameters: Boolean;
begin
result := true;
radius := StrToFloat(RadiusEdit.Text);
XWidth := StrToFloat(XWidthEdit.Text);
YHeight := StrToFloat(YHeightEdit.Text);
X := StrToFloat(XPosEdit.Text);
Y := StrToFloat(YPosEdit.Text);
if (abs(X) > ((XWidth / 2) - (6 * radius))) then
begin
Application.MessageBox('X out of range', 'Error', 0);
result := false;
end;
if (abs(Y) > ((YHeight / 2) - (6 * radius))) then
begin
Application.MessageBox('Y out of range', 'Error', 0);
result := false;
end;
end;
procedure TForm1.CalcButtonClick(Sender: TObject);
begin
if (not GetParameters) then exit;
Calc;
AlphaLabel.Caption := FloatToStrF(alpha, ffFixed, 10,2);
BetaLabel.Caption := FloatToStrF(beta, ffFixed, 10,2);
end;
procedure TForm1.CircleButtonClick(Sender: TObject);
var angle: double;
begin
if (not GetParameters) then exit;
angle := 0;
while (angle <= PI*2) do
begin
X := 180 * cos(angle);
Y := 180 * sin(angle);
Calc;
XPosEdit.Text := FloatToStr(X);
YPosEdit.Text := FloatToStr(Y);
AlphaLabel.Caption := FloatToStrF(alpha, ffFixed, 10,2);
BetaLabel.Caption := FloatToStrF(beta, ffFixed, 10,2);
self.Repaint;
sleep(100);
angle := angle + 0.1;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
candraw := false;
end;
procedure TForm1.ShapePaint(Sender: TObject);
var scale, scalex, scaley: double;
offx, offy: longint;
w, h: longint;
xw, yh: double;
gx, gy: longint;
gw: longint;
tw, th: longint;
tx, ty: longint;
rrx, rry, lrx, lry: longint;
sr: longint;
begin
if (not candraw) then
exit;
// Drawing scale
scalex := Shape.Width / XWidth;
scaley := Shape.Height / (2 * YHeight);
if (scalex < scaley) then
scale := scalex
else
scale := scaley;
w := Shape.Width;
h := Shape.Height;
xw := XWidth;
yh := YHeight;
sr := trunc(scale*radius);
// Drawing offset from edges
offx := (w - trunc(scale * xw)) div 2;
offy := (h - trunc(scale * 2 * yh)) div 2;
// X roller positions
rrx := offx + 0;
rry := offy + h div 2;
lrx := offx + trunc(scale * xw);
lry := offy + h div 2;
// Gantry width and position
gw := trunc(scale*2*radius);
gx := rrx + trunc(scale * (xw/2 + x)) ;
gy := rry;
// Tool width and height
tw := gw - sr;
th := gw div 2;
// Tool position
tx := rrx + trunc(scale * (xw/2 + x));
ty := rry + trunc(scale * 2 * radius) + trunc(scale * (yh/2 - y));
with Shape.Canvas do
begin
Pen.Color := clBlack;
Pen.Width := 1;
Pen.Style := psSolid;
Brush.Color := clBlue;
// Left and right rollers
Ellipse(rrx - sr, rry - sr, rrx + sr, rry + sr);
Ellipse(lrx - sr, lry - sr, lrx + sr, lry + sr);
Brush.Color := clGreen;
// Gantry
Rectangle(gx-gw, gy-gw, gx+gw, gy+gw);
// Gantry rollers
Ellipse(gx-gw-sr, gy-gw-sr,gx-gw+sr,gy-gw+sr);
Ellipse(gx+gw-sr, gy-gw-sr,gx+gw+sr,gy-gw+sr);
Ellipse(gx-gw-sr, gy+gw-sr,gx-gw+sr,gy+gw+sr);
Ellipse(gx+gw-sr, gy+gw-sr,gx+gw+sr,gy+gw+sr);
Brush.Color := clRed;
// Top Y arm roller
Ellipse(tx-sr, ty-sr-trunc(scale*yh), tx+sr,ty+sr-trunc(scale*yh));
// Tool
Rectangle(tx-tw, ty-th, tx+tw, ty+th);
Line(tx-tw, ty+th, gx-gw+sr, gy+gw-sr);
Line(gx-gw, gy+gw-sr, rrx, rry+sr);
Line(rrx, rry-sr, gx-gw,gy-gw+sr);
Line(gx-gw+sr, gy-gw, tx-sr,ty-trunc(scale*yh));
Line(tx+sr,ty-trunc(scale*yh), gx+gw-sr, gy-gw);
Line(gx+gw-sr, gy-gw+sr,lrx,lry-sr);
Line(lrx,lry+sr,gx+gw-sr, gy+gw-sr);
Line(gx+gw-sr, gy+gw-sr,tx+tw, ty+th);
end;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Command.Factory;
interface
uses
Spring.Container,
DPM.Console.Types,
DPM.Console.Command;
type
TCommandFactory = class(TInterfacedObject,ICommandFactory)
private
FContainer : TContainer;
protected
function CreateCommand(const command : TDPMCommand) : ICommandHandler;
public
constructor Create(const container : TContainer);
end;
implementation
uses
System.SysUtils;
{ TCommandFactory }
constructor TCommandFactory.Create(const container: TContainer);
begin
FContainer := container;
end;
function TCommandFactory.CreateCommand(const command: TDPMCommand): ICommandHandler;
var
commandName : string;
begin
result := nil;
commandName := 'command.' + LowerCase(CommandString[command]);
result := FContainer.Resolve<ICommandHandler>(commandName);
end;
end.
|
UNIT TAU_WINDOW;
{$MODE OBJFPC}
{$H+}
INTERFACE
USES
SDL;
TYPE
pTTauWindow = ^TTauWindow;
TTauWindow = CLASS
PRIVATE
b_ok : boolean;
surf_win: PSDL_Surface;
PUBLIC
CONSTRUCTOR Create(w, h: integer);
DESTRUCTOR Destroy(); OVERRIDE;
FUNCTION IsOk(): boolean;
FUNCTION GetPWin(): PSDL_Surface;
PROCEDURE Tick();
END;
IMPLEMENTATION
CONSTRUCTOR TTauWindow.Create(w, h: integer);
BEGIN
b_ok := TRUE;
surf_win := SDL_SetVideoMode(
w,
h,
0,
SDL_HWSURFACE
);
IF (surf_win = NIL) THEN
BEGIN
b_ok := FALSE;
END;
END;
DESTRUCTOR TTauWindow.Destroy();
BEGIN
END;
FUNCTION TTauWindow.IsOk(): boolean;
BEGIN
IsOk := b_ok;
END;
FUNCTION TTauWindow.GetPWin(): PSDL_Surface;
BEGIN
GetPWin := surf_win;
END;
PROCEDURE TTauWindow.Tick();
BEGIN
IF (SDL_Flip(surf_win) <> 0) THEN
BEGIN
WriteLn('! WIN ' + SDL_GetError());
END;
END;
END.
|
unit ibSHGenerator;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTGenerator = class(TibBTDBObject, IibSHGenerator)
private
FShowSetClause: Boolean;
FValue: Integer;
function GetShowSetClause: Boolean;
procedure SetShowSetClause(Value: Boolean);
function GetValue: Integer;
procedure SetValue(Value: Integer);
public
constructor Create(AOwner: TComponent); override;
property ShowSetClause: Boolean read GetShowSetClause write SetShowSetClause;
published
property Value: Integer read GetValue {write SetValue};
end;
implementation
uses
ibSHConsts, ibSHSQLs;
{ TibBTGenerator }
constructor TibBTGenerator.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FShowSetClause := True;
end;
function TibBTGenerator.GetShowSetClause: Boolean;
begin
Result := FShowSetClause;
end;
procedure TibBTGenerator.SetShowSetClause(Value: Boolean);
begin
FShowSetClause := Value;
end;
function TibBTGenerator.GetValue: Integer;
begin
Result := FValue;
end;
procedure TibBTGenerator.SetValue(Value: Integer);
begin
FValue := Value;
end;
end.
|
unit UfrmCadProduto;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TFrmCadProduto = class(TForm)
EdCodigo: TEdit;
EdDescr: TEdit;
Label1: TLabel;
Label2: TLabel;
BtNovo: TButton;
BtGravar: TButton;
BtCons: TButton;
Label3: TLabel;
EdValor: TEdit;
CheckBoxContrl: TCheckBox;
BtEditar: TButton;
BtExcluir: TButton;
PnlCons: TPanel;
Label4: TLabel;
EdConsProd: TEdit;
EdTecA: TEdit;
Label5: TLabel;
BtnOk: TButton;
procedure Limpar;
procedure AtivaCampos;
procedure DesativaCampos;
procedure BtNovoClick(Sender: TObject);
procedure BtConsClick(Sender: TObject);
procedure BtExcluirClick(Sender: TObject);
procedure BtEditarClick(Sender: TObject);
procedure BtGravarClick(Sender: TObject);
procedure CheckBoxContrlClick(Sender: TObject);
procedure BtnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmCadProduto: TFrmCadProduto;
Acao: string;
implementation
uses Uproduto, Ucadastroproduto, Urepositorioproduto;
{$R *.dfm}
procedure TFrmCadProduto.AtivaCampos;
begin
if Acao <> 'Editar' then
EdCodigo.Enabled:=true
else
EdCodigo.Enabled:=false;
EdDescr.Enabled:=true;
EdValor.Enabled:=true ;
EdTecA.Enabled:= true;
end;
procedure TFrmCadProduto.BtConsClick(Sender: TObject);
begin
Limpar;
PnlCons.Visible:= true;
EdConsProd.SetFocus;
end;
procedure TFrmCadProduto.BtEditarClick(Sender: TObject);
begin
if Acao = 'Consulta' then
begin
Acao:='Editar';
AtivaCampos;
EdDescr.SetFocus;
end;
end;
procedure TFrmCadProduto.BtExcluirClick(Sender: TObject);
var Produto: Tproduto;
CadProduto : TCadastroProduto;
begin
if Acao = 'Consulta' then
begin
If MessageDlg('Você tem certeza que deseja excluir este Produto?',mtConfirmation,[mbyes,mbno],0)=mryes then
begin
Produto:= Tproduto.Create;
CadProduto:= TCadastroProduto.Create;
try
Produto.CODIGO:= EdCodigo.Text;
try
CadProduto.Delete(Produto);
except
on E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
finally
FreeAndNil(Produto);
FreeAndNil(CadProduto);
end;
ShowMessage('Produto Excluído com Sucesso!');
Limpar;
DesativaCampos;
end;
end;
end;
procedure TFrmCadProduto.BtGravarClick(Sender: TObject);
var Produto: TProduto ;
CadProduto : TCadastroProduto;
begin
if (Acao = 'Novo') or (Acao = 'Editar') then
begin
if (CheckBoxContrl.Checked)and (trim(EdTecA.Text)= '') then
begin
ShowMessage('Informe o registro do Técnico agrícula!');
EdTecA.SetFocus;
Exit;
end;
if (trim(EdCodigo.Text)='') or (trim(EdDescr.text)='') or (trim(EdValor.text)='') then
begin
ShowMessage('Informe o código do produto, Descrição e valor!');
EdCodigo.SetFocus;
Exit;
end;
Produto:= TProduto.Create;
CadProduto:= TCadastroProduto.Create;
try
Produto.CODIGO:= EdCodigo.Text;
Produto.DESCRICAO:= EdDescr.Text;
produto.PRECO:= StrToFloat(EdValor.Text);
if CheckBoxContrl.Checked then
Produto.CONTROLE:= EdTecA.Text;
if Acao = 'Novo' then
CadProduto.Insert(Produto)
else
if Acao = 'Editar' then
begin
CadProduto.Update(Produto);
end;
finally
FreeAndNil(CadProduto);
FreeAndNil(CadProduto);
end;
Limpar;
DesativaCampos;
Acao:= '';
ShowMessage('Gravado com Sucesso!');
end;
end;
procedure TFrmCadProduto.BtnOkClick(Sender: TObject);
var Produto: TProduto ;
RepProduto : TRepositorioProduto;
begin
if trim (EdConsProd.Text) <> ''then
begin
Produto:= TProduto.Create;
RepProduto:= TRepositorioProduto.Create;
try
try
Produto:= RepProduto.getProduto(EdConsProd.Text);
except
on E: Exception do
begin
raise Exception.Create(E.Message);
end;
end;
EdCodigo.Text:= Produto.CODIGO;
EdDescr.Text := Produto.DESCRICAO;
EdValor.Text := FloatToStr(produto.PRECO);
EdTecA.Text := Produto.CONTROLE;
if trim(EdTecA.Text) <> '' then
CheckBoxContrl.Checked:=true;
finally
FreeAndNil(Produto);
FreeAndNil(RepProduto);
end;
DesativaCampos;
Acao:= 'Consulta'
end;
end;
procedure TFrmCadProduto.BtNovoClick(Sender: TObject);
begin
DesativaCampos;
AtivaCampos;
Limpar;
EdCodigo.SetFocus;
Acao:='Novo';
end;
procedure TFrmCadProduto.CheckBoxContrlClick(Sender: TObject);
begin
if CheckBoxContrl.Checked then
begin
EdTecA.Enabled:= true;
EdTecA.SetFocus;
end
else
begin
EdTecA.Enabled:= false;
EdTecA.Clear;
end;
end;
procedure TFrmCadProduto.DesativaCampos;
begin
EdCodigo.Enabled:=false;
EdDescr.Enabled:=false;
EdValor.Enabled:=false ;
PnlCons.Visible:= false;
EdTecA.Enabled:= false;
end;
procedure TFrmCadProduto.FormCreate(Sender: TObject);
begin
DesativaCampos;
end;
procedure TFrmCadProduto.Limpar;
begin
EdCodigo.Clear;
EdDescr.Clear;
EdValor.Clear;
EdConsProd.Clear;
CheckBoxContrl.Checked:=false;
EdTecA.Clear;
end;
end.
|
unit Lib.HTTPContent;
interface
uses
System.SysUtils,
System.Classes,
System.IOUtils,
Lib.HTTPConsts,
Lib.HTTPUtils,
Lib.HTTPHeaders;
type
TContent = class abstract
protected type
TState = (stNone,stHeader,stContentLength,stChunked,stUnknownLength);
private
FState: TState;
FHeaderLength: Integer;
FContentLength: Integer;
FContentReaded: Integer;
FContentType: string;
FHeaders: THeaders;
FOnHeader: TNotifyEvent;
FOnContent: TNotifyEvent;
FOnComplete: TNotifyEvent;
procedure DoBeginRead;
protected
FComposes: string;
procedure DoHeader; virtual;
procedure DoContent; virtual;
procedure DoComplete; virtual;
procedure ComposeHeaders;
public
Protocol: string;
Content: TBytes;
ResourceName: string;
LocalResource: string;
Description: string;
constructor Create; virtual;
destructor Destroy; override;
procedure AddContentText(const Text: string); overload;
procedure AddContentText(const Text,ContentType: string); overload;
procedure AddContentJson(const Text: string);
procedure AddContentFile(const FileName: string); overload;
procedure AddContentFile(const FileName,ContentType: string); overload;
procedure AddContentFile(const FileName: string; const Bytes: TBytes); overload;
procedure AddContentFile(const FileName,ContentType: string; const Bytes: TBytes); overload;
property Headers: THeaders read FHeaders;
public
procedure Reset; virtual;
procedure Assign(Source: TContent); virtual;
function DoRead(const B: TBytes): Integer;
property Composes: string read FComposes;
public
property ContentLength: Integer read FContentLength;
property ContentReaded: Integer read FContentReaded;
property OnReadHeader: TNotifyEvent write FOnHeader;
property OnReadContent: TNotifyEvent write FOnContent;
property OnReadComplete: TNotifyEvent write FOnComplete;
end;
TRequest = class(TContent)
protected
procedure DoHeader; override;
public
Host: string;
Scheme: string;
Method: string;
Resource: string;
Query: string;
Fragment: string;
procedure Reset; override;
procedure Assign(Source: TContent); override;
procedure DecomposeURL(const URL: string);
function Compose: string;
procedure Merge;
end;
TResponse = class(TContent)
protected
procedure DoHeader; override;
public
ResultCode: Integer;
ResultText: string;
procedure Reset; override;
procedure Assign(Source: TContent); override;
function Compose: string;
procedure SetResult(Code: Integer; const Text: string);
procedure SetResultOK;
procedure Merge(Request: TRequest);
end;
implementation
function ContentSizeToString(const Content: TBytes): string;
begin
Result:=Length(Content).ToString+' bytes';
end;
constructor TContent.Create;
begin
FHeaders:=THeaders.Create;
Reset;
end;
destructor TContent.Destroy;
begin
FHeaders.Free;
Content:=nil;
inherited;
end;
procedure TContent.Reset;
begin
FState:=stNone;
FHeaderLength:=0;
FContentReaded:=0;
FContentLength:=0;
FContentType:='';
FComposes:='';
FHeaders.Clear;
Content:=nil;
Protocol:='';
ResourceName:='';
LocalResource:='';
Description:='';
end;
procedure TContent.Assign(Source: TContent);
begin
Headers.Assign(Source.Headers);
FContentType:=Source.FContentType;
Content:=Source.Content;
Protocol:=Source.Protocol;
ResourceName:=Source.ResourceName;
LocalResource:=Source.LocalResource;
Description:=Source.Description;
end;
procedure TContent.AddContentText(const Text: string);
begin
AddContentText(Text,HTTPGetMIMEType('.txt'));
end;
procedure TContent.AddContentText(const Text,ContentType: string);
begin
Content:=TEncoding.UTF8.GetBytes(Text);
FContentType:=ContentType+'; charset=utf-8';
Description:=Text;
end;
procedure TContent.AddContentJson(const Text: string);
begin
AddContentText(Text,'application/json');
end;
procedure TContent.AddContentFile(const FileName: string);
begin
AddContentFile(FileName,HTTPGetMIMEType(ExtractFileExt(FileName)));
end;
procedure TContent.AddContentFile(const FileName,ContentType: string);
begin
AddContentFile(FileName,ContentType,TFile.ReadAllBytes(FileName));
end;
procedure TContent.AddContentFile(const FileName: string; const Bytes: TBytes);
begin
AddContentFile(FileName,HTTPGetMIMEType(ExtractFileExt(FileName)),Bytes);
end;
procedure TContent.AddContentFile(const FileName,ContentType: string; const Bytes: TBytes);
begin
Content:=Bytes;
FContentType:=ContentType;
Description:=FileName+' ('+ContentSizeToString(Content)+')';
end;
procedure TContent.DoBeginRead;
begin
Reset;
FState:=stHeader;
end;
function TContent.DoRead(const B: TBytes): Integer;
var L: Integer; Over: TBytes;
begin
Over:=nil;
Result:=Length(B);
if FState<>stUnknownLength then
begin
if Result=0 then Exit;
if FState=stNone then DoBeginRead; // начало чтения запроса (ответа)
end;
L:=Result;
SetLength(Content,FContentReaded+L);
Move(B[0],Content[FContentReaded],L);
Inc(FContentReaded,L);
if FState=stHeader then
begin
FHeaderLength:=HTTPGetHeaderLength(Content);
if FHeaderLength>0 then
begin
Headers.Text:=TEncoding.ANSI.GetString(Content,0,FHeaderLength);
DoHeader;
L:=FContentReaded-FHeaderLength-4;
Move(Content[FContentReaded-L],Content[0],L);
SetLength(Content,L);
FContentReaded:=L;
if TryStrToInt(Headers.GetValue('Content-Length'),FContentLength) then
FState:=stContentLength
else
if Headers.GetValue('Transfer-Encoding')='chunked' then
FState:=stChunked
else
FState:=stUnknownLength;
end else
if HTTPIsInvalidHeaderData(Content) then
begin
FState:=stNone;
Result:=0;
end;
end;
if FState=stContentLength then
begin
if FContentReaded>=FContentLength then
begin
if FContentReaded>FContentLength then
begin
Over:=Copy(Content,FContentLength,FContentReaded-FContentLength);
SetLength(Content,FContentLength);
end;
DoContent;
FState:=stNone;
end;
end;
if FState=stChunked then
begin
if HTTPEndedChunked(Content) then
begin
Content:=HTTPBytesFromChunked(Content);
DoContent;
FState:=stNone;
end;
end;
if FState=stUnknownLength then
begin
if L=0 then
begin
DoContent;
FState:=stNone;
end;
end;
if FState=stNone then DoComplete;
DoRead(Over);
end;
procedure TContent.DoHeader;
begin
if Assigned(FOnHeader) then FOnHeader(Self);
end;
procedure TContent.DoContent;
begin
if Assigned(FOnContent) then FOnContent(Self);
end;
procedure TContent.DoComplete;
begin
if Assigned(FOnComplete) then FOnComplete(Self);
end;
procedure TContent.ComposeHeaders;
begin
if (Length(Content)>0) and (FContentType<>'') then
Headers.SetValue('Content-Type',FContentType);
Headers.SetValue('Content-Length',Length(Content).ToString);
end;
{ TRequest }
procedure TRequest.Reset;
begin
inherited;
Host:='';
Scheme:='';
Method:='';
Resource:='';
Query:='';
Fragment:='';
end;
procedure TRequest.Assign(Source: TContent);
var S: TRequest;
begin
inherited;
if Source is TRequest then
begin
S:=TRequest(Source);
Host:=S.Host;
Scheme:=S.Scheme;
Method:=S.Method;
Resource:=S.Resource;
Query:=S.Query;
Fragment:=S.Fragment
end;
end;
procedure TRequest.DecomposeURL(const URL: string);
begin
HTTPSplitURL(URL,Scheme,Host,Resource);
end;
function TRequest.Compose: string;
begin
ComposeHeaders;
FComposes:=Method+' '+HTTPEncodeResource(Resource)+' '+Protocol+CRLF+
Headers.Text;
Result:=FComposes+CRLF;
end;
procedure TRequest.DoHeader;
begin
FComposes:=Headers.Text;
if HTTPTrySplitRequest(Headers.FirstLine,Method,Resource,Protocol) then
begin
Headers.DeleteFirstLine;
end;
inherited;
end;
procedure TRequest.Merge;
begin
ResourceName:=HTTPExtractResourceName(HTTPDecodeResource(Resource));
Description:=Headers.ContentType+' ('+ContentSizeToString(Content)+')';
end;
{ TResponse }
procedure TResponse.Reset;
begin
inherited;
Protocol:='';
ResultCode:=0;
ResultText:='';
end;
procedure TResponse.Assign(Source: TContent);
var S: TResponse;
begin
inherited;
if Source is TResponse then
begin
S:=TResponse(Source);
Protocol:=S.Protocol;
ResultCode:=S.ResultCode;
ResultText:=S.ResultText;
end;
end;
procedure TResponse.SetResult(Code: Integer; const Text: string);
begin
ResultCode:=Code;
ResultText:=Text;
end;
procedure TResponse.SetResultOK;
begin
ResultCode:=HTTPCODE_SUCCESS;
ResultText:='OK';
end;
function TResponse.Compose: string;
begin
ComposeHeaders;
FComposes:=Protocol+' '+ResultCode.ToString+' '+ResultText+CRLF+
Headers.Text;
Result:=FComposes+CRLF;
end;
procedure TResponse.DoHeader;
begin
FComposes:=Headers.Text;
if HTTPTrySplitResponseResult(Headers.FirstLine,Protocol,ResultCode,ResultText) then
begin
Headers.DeleteFirstLine;
end;
inherited;
end;
procedure TResponse.Merge(Request: TRequest);
var ContentDispositionFileName: string;
begin
ResourceName:=
HTTPExtractResourceName(
HTTPDecodeResource(Request.Resource));
LocalResource:=ResourceName;
ContentDispositionFileName:=
HTTPGetTagValue(
HTTPGetTag(
Headers.GetValue('Content-Disposition'),'filename'));
if ResultCode<>HTTPCODE_SUCCESS then
LocalResource:='error'+ResultCode.ToString
else
if LocalResource='' then
LocalResource:='file'
else
if LocalResource='/' then
LocalResource:='page';
LocalResource:=
HTTPResourceNameToLocal(
HTTPChangeResourceNameExt(LocalResource,Headers.ContentType));
if ContentDispositionFileName<>'' then
LocalResource:=ExtractFilePath(LocalResource)+ContentDispositionFileName;
Description:=ResourceName+' ('+ContentSizeToString(Content)+')';
end;
end.
|
unit uNewBarangStockSirkulasi;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
uNewUnit, uNewBarang, uNewUOM;
type
TBarangStockSirkulasiItem = class(TCollectionItem)
private
FHargaTransaksi: Double;
FHargaLastCost: Double;
FHEADERFLAG: Integer;
FID: Integer;
FISBONUSFORBONUS: Integer;
FIsEOD: Integer;
FITEM_ID: Integer;
FKeterangan: string;
FNewBarang: TNewBarang;
FNewBarangKode: string;
FNewUnit: TUnit;
FNewUnitID: string;
FNewUOM: TNewUOM;
FNewUOMKode: string;
FNoBukti: string;
FQty: Double;
FTglBukti: TDateTime;
FTypeTransaksi: string;
FUOMUnit: TUnit;
function GetNewBarang: TNewBarang;
function GetNewUnit: TUnit;
function GetNewUOM: TNewUOM;
function GetUOMUnit: TUnit;
public
constructor Create(aCollection : TCollection); override;
destructor destroy; override;
procedure ClearProperties;
function CustomTableName: string;
function ExecuteGenerateSQL(aHeaderNo : string; aID : Integer; aUnitID :
Integer): Boolean;
function GetFieldNameFor_HargaTransaksi: string;
function GetFieldNameFor_HargaLastCost: string;
function GetFieldNameFor_HeaderFlag: string; dynamic;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_IsBonusForBonus: string; dynamic;
function GetFieldNameFor_IsEOD: string; dynamic;
function GetFieldNameFor_ItemID: string; dynamic;
function GetFieldNameFor_Keterangan: string; dynamic;
function GetFieldNameFor_NewBarang: string; dynamic;
function GetFieldNameFor_NewUnit: string; dynamic;
function GetFieldNameFor_NewUOM: string; dynamic;
function GetFieldNameFor_NoBukti: string; dynamic;
function GetFieldNameFor_Qty: string; dynamic;
function GetFieldNameFor_Tanggal: string; dynamic;
function GetFieldNameFor_TypeTransaksi: string; dynamic;
function GetGeneratorName: string;
class function RemoveFromDB(aID : Integer; aUnitId : Integer): string;
procedure UpdateData(aHeaderFlag, aID, aIsEOD, aItemID: Integer; aKeterangan,
aNewBArangKode, aNewUnitID, aNewUOMKode, aNoBukti: string; aQty: Double;
aTanggal: TDateTime; ATypeTransaksi: string; aIsBonusForBonus: Integer;
aHargaTransaksi: Double = 0; aHargaLastCost: Double = 0);
property HargaTransaksi: Double read FHargaTransaksi write FHargaTransaksi;
property HargaLastCost: Double read FHargaLastCost write FHargaLastCost;
property HEADERFLAG: Integer read FHEADERFLAG write FHEADERFLAG;
property ID: Integer read FID write FID;
property ISBONUSFORBONUS: Integer read FISBONUSFORBONUS write FISBONUSFORBONUS;
property IsEOD: Integer read FIsEOD write FIsEOD;
property ITEM_ID: Integer read FITEM_ID write FITEM_ID;
property Keterangan: string read FKeterangan write FKeterangan;
property NewBarang: TNewBarang read GetNewBarang write FNewBarang;
property NewUnit: TUnit read GetNewUnit write FNewUnit;
property NewUOM: TNewUOM read GetNewUOM write FNewUOM;
property NoBukti: string read FNoBukti write FNoBukti;
property Qty: Double read FQty write FQty;
property TglBukti: TDateTime read FTglBukti write FTglBukti;
property TypeTransaksi: string read FTypeTransaksi write FTypeTransaksi;
property UOMUnit: TUnit read GetUOMUnit write FUOMUnit;
property KodeBarang: string read FNewBarangKode;
property KodeUom: string read FNewUOMKode;
property UnitID: string read FNewUnitID;
end;
TBarangStockSirkulasiItems = class(TCollection)
private
function GetBarangStockSirkulasiItem(Index: Integer):
TBarangStockSirkulasiItem;
procedure SetBarangStockSirkulasiItem(Index: Integer; Value:
TBarangStockSirkulasiItem);
public
function Add: TBarangStockSirkulasiItem;
function CustomTableName: string;
function CekBarangStockSirkulasi(aHeaderNo : string;aUnitID: Integer): Boolean;
function GetHeaderFlag: Integer;
procedure LoadByID(aID : Integer; aUnitID : Integer);
procedure LoadByNoBukti(aNoBukti : String; aUnitID : Integer; aHeaderFlag :
Integer);
class function RemoveByDocNo(aDocNo : String; aUnitID : Integer; aTipe :
String): Boolean;
function SaveToDatabase(aHeaderNo : string; aUnitID : Integer): Boolean;
property BarangStockSirkulasiItem[Index: Integer]:
TBarangStockSirkulasiItem read GetBarangStockSirkulasiItem write
SetBarangStockSirkulasiItem; default;
end;
implementation
uses DB, dateutils, udmMain, uAppUtils;
{
************************** TBarangStockSirkulasiItem ***************************
}
constructor TBarangStockSirkulasiItem.Create(aCollection : TCollection);
begin
inherited create(aCollection);
end;
destructor TBarangStockSirkulasiItem.destroy;
begin
// FNewBarang.free;
//FNewBarangUnit.free;
// FNewUnit.free;
// FNewUOM.free;
// FUOMUnit.free;
inherited Destroy;
end;
procedure TBarangStockSirkulasiItem.ClearProperties;
begin
//HEADER_FLAG := '';
ID := 0;
IsEOD := 0;
Keterangan := '';
FNewBarangKode := '';
if FNewBarang <> nil then
FreeAndNil(FNewBarang);
FNewUnitID := '';
if FNewUnit <> nil then
FreeAndNil(FNewUnit);
FNewUOMKode := '';
if FNewUOM <> nil then
FreeAndNil(FNewUOM);
NoBukti := '';
Qty := 0;
TglBukti := cGetServerDateTime;
TypeTransaksi := '';
if FUOMUnit <> nil then
FreeAndNil(fUOMUnit);
end;
function TBarangStockSirkulasiItem.CustomTableName: string;
begin
result := 'BARANG_STOK_SIRKULASI';
end;
function TBarangStockSirkulasiItem.ExecuteGenerateSQL(aHeaderNo : string; aID :
Integer; aUnitID : Integer): Boolean;
var
iMiliSecond: Word;
iSecond: Word;
iMinute: Word;
iHour: Word;
iDay: Word;
iMonth: Word;
iYear: Word;
S: string;
dLastCost : Double;
begin
//Result := False;
DecodeDateTime(cGetServerDateTime, iYear,iMonth,iDay,iHour,iMinute,iSecond,iMiliSecond);
FTglBukti := EncodeDateTime(YearOf(FTglBukti), MonthOf(FTglBukti), DayOf(FTglBukti),iHour,iMinute,iSecond,iMiliSecond);
IF Qty <> 0 then
begin
FID := aID;
FNoBukti := aHeaderNo;
if FID <= 0 then
begin
if FHargaLastCost = 0 then
dLastCost := NewBarang.HargaLastCost * TNewBarang.GetUOMValue(FNewBarangKode, FNewUOMKode)
else
dLastCost := FHargaLastCost;
ID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
S := 'Insert into ' + CustomTableName + ' ( '
+ GetFieldNameFor_ID + ', '
+ GetFieldNameFor_IsEOD + ', '
+ GetFieldNameFor_Keterangan + ', '
+ GetFieldNameFor_NewBarang + ', '
+ GetFieldNameFor_NewUnit + ', '
+ GetFieldNameFor_NewUOM + ', '
+ GetFieldNameFor_NoBukti + ', '
+ GetFieldNameFor_Qty + ', '
+ GetFieldNameFor_Tanggal + ', '
+ GetFieldNameFor_TypeTransaksi + ', '
+ GetFieldNameFor_HeaderFlag + ' , '
+ GetFieldNameFor_ItemID + ', '
+ GetFieldNameFor_IsBonusForBonus + ','
+ GetFieldNameFor_HargaTransaksi
+ ', ' + GetFieldNameFor_HargaLastCost +
') values ('
+ IntToStr( FID) + ', '
+ IntToStr( FIsEOD) + ', '
+ QuotedStr(FKeterangan ) + ','
+ QuotedStr(FNewBarangKode) + ', '
+ QuotedStr(FNewUnitID) + ', '
+ QuotedStr(FNewUOMKode) + ', '
+ QuotedStr(aHeaderNo ) + ','
+ FormatFloat('0.000', FQty) + ', '
+ TAppUtils.Quotdt( FTglBukti ) + ', '
+ QuotedStr(FTypeTransaksi ) + ','
+ IntToStr(FHEADERFLAG) + ', '
+ IntToStr(FITEM_ID) + ', '
+ IntToStr(FISBONUSFORBONUS) + ','
+ FormatFloat('0.00', FHargaTransaksi)
+ ', ' + FormatFloat('0.00', dLastCost)
+ ');';
end
else begin
//FID := aID;
S := 'Update ' + CustomTableName
+ ' set ' + GetFieldNameFor_NewBarang + ' = ' + QuotedStr(FNewBarangKode) + ', '
+ GetFieldNameFor_IsBonusForBonus + ' = ' + IntToStr(FISBONUSFORBONUS) + ', '
+ GetFieldNameFor_NewUOM + ' = ' + QuotedStr(FNewUOMKode) + ', '
+ GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID) + ', '
+ GetFieldNameFor_IsEOD + ' = ' + IntToStr(FIsEOD)+ ', '
+ GetFieldNameFor_ItemID + ' = ' + IntToStr(FITEM_ID) + ', '
+ GetFieldNameFor_Keterangan + ' = ' + QuotedStr(FKeterangan) + ', '
+ GetFieldNameFor_Qty + ' = ' + FormatFloat('0.000', FQty) + ', '
+ GetFieldNameFor_HargaTransaksi + ' = ' + FormatFloat('0.00', FHargaTransaksi) + ', '
+ GetFieldNameFor_Tanggal + ' = ' + TAppUtils.QuotDt(FTglBukti) + ', '
+ GetFieldNameFor_TypeTransaksi + ' = ' + QuotedStr(FTypeTransaksi)
+ ' where '+ GetFieldNameFor_NoBukti +' = ' + QuotedStr(aHeaderNo)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(FNewUnitID)
+ ' and ' + GetFieldNameFor_HeaderFlag + ' = ' + IntToStr(FHeaderflag)
+ ' and ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID)
+ ';';
end;
if not cExecSQL(s,dbtPOS, False) then
begin
cRollbackTrans;
raise Exception.Create('ATTENTION ' + s + ' is not valid SQL statement ');
end else
Result := True;
end else
Result := True;
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_HargaTransaksi: string;
begin
// TODO -cMM: TBarangStockSirkulasiItem.GetFieldNameFor_HargaTransaksi default body inserted
Result := 'BSS_HARGA_TRANSAKSI';
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_HargaLastCost: string;
begin
// TODO -cMM: TBarangStockSirkulasiItem.GetFieldNameFor_HargaTransaksi default body inserted
Result := 'BSS_LASTCOST';
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_HeaderFlag: string;
begin
Result :='HEADERFLAG' ;
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_ID: string;
begin
Result := 'BSS_ID';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_IsBonusForBonus: string;
begin
// TODO -cMM: TBarangStockSirkulasiItem.GetFieldNameFor_IsBonusForBonus default body inserted
Result := 'ISBONUSFORBONUS';
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_IsEOD: string;
begin
Result := 'BSS_IS_EOD';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_ItemID: string;
begin
// TODO -cMM: TBarangStockSirkulasiItem.GetFieldNameFor_ItemID default body inserted
Result := 'ITEM_ID';
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_Keterangan: string;
begin
Result := 'BSS_DESCRIPTION';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_NewBarang: string;
begin
Result := 'BSS_BRG_CODE';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_NewUnit: string;
begin
Result := 'BSS_UNT_ID';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_NewUOM: string;
begin
Result := 'BSS_SAT_CODE';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_NoBukti: string;
begin
Result := 'BSS_DOC_NO';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_Qty: string;
begin
Result := 'BSS_QTY';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_Tanggal: string;
begin
Result := 'BSS_DATE';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetFieldNameFor_TypeTransaksi: string;
begin
Result := 'BSS_TYPE';// <<-- Rubah string ini untuk mapping
end;
function TBarangStockSirkulasiItem.GetGeneratorName: string;
begin
Result := 'GEN_BARANG_STOK_SIRKULASI_ID';
end;
function TBarangStockSirkulasiItem.GetNewBarang: TNewBarang;
begin
if FNewBarang = nil then
begin
FNewBarang := TNewBarang.Create(Application);
FNewBarang.LoadByKode(FNewBarangKode);
end;
Result := FNewBarang;
end;
function TBarangStockSirkulasiItem.GetNewUnit: TUnit;
begin
if FNewUnit = nil then
begin
FNewUnit := TUnit.Create(Application) ;
FNewUnit.loadByID(FNewUnitID);
end;
Result := FNewUnit;
end;
function TBarangStockSirkulasiItem.GetNewUOM: TNewUOM;
begin
if FNewUOM = nil then
begin
FNewUOM :=TNewUOM.Create(Application);
FNewUOM.LoadByUOM(FNewUOMKode);
end;
Result := FNewUOM;
end;
function TBarangStockSirkulasiItem.GetUOMUnit: TUnit;
begin
if FUOMUnit = nil then
begin
FUOMUnit :=TUnit.Create(Application);
FUOMUnit.LoadByID(FNewUnitID);
end;
Result := FUOMUnit;
end;
class function TBarangStockSirkulasiItem.RemoveFromDB(aID : Integer; aUnitId :
Integer): string;
begin
Result := 'delete '
+ ' from BARANG_STOK_SIRKULASI'
+ ' where BSS_ID = ' + IntToStr(aID)
+ ' and BSS_UNT_ID = ' + IntToStr(aUnitID);
end;
procedure TBarangStockSirkulasiItem.UpdateData(aHeaderFlag, aID, aIsEOD,
aItemID: Integer; aKeterangan, aNewBArangKode, aNewUnitID, aNewUOMKode,
aNoBukti: string; aQty: Double; aTanggal: TDateTime; ATypeTransaksi:
string; aIsBonusForBonus: Integer; aHargaTransaksi: Double = 0;
aHargaLastCost: Double = 0);
begin
FHEADERFLAG := aHeaderFlag;
FID := aID;
FIsEOD := aIsEOD;
FITEM_ID := aItemID;
FKeterangan := aKeterangan;
FNewBarangKode := aNewBArangKode;
FNewUnitID := aNewUnitID;
FNewUOMKode := aNewUOMKode;
FNoBukti := aNoBukti;
FQty := aQty;
FTglBukti := aTanggal;
FTypeTransaksi := ATypeTransaksi;
FISBONUSFORBONUS := aIsBonusForBonus;
HargaTransaksi := aHargaTransaksi;
FHargaLastCost := aHargaLastCost
end;
function TBarangStockSirkulasiItems.Add: TBarangStockSirkulasiItem;
begin
Result := (inherited Add) as TBarangStockSirkulasiItem;
end;
{
************************** TBarangStockSirkulasiItems **************************
}
function TBarangStockSirkulasiItems.CustomTableName: string;
begin
result := 'BARANG_STOK_SIRKULASI';
end;
function TBarangStockSirkulasiItems.CekBarangStockSirkulasi(aHeaderNo : string;
aUnitID: Integer): Boolean;
var
IsAda: Boolean;
SS: TStrings;
i: Integer;
sSQL: String;
begin
result := False;
sSQL := 'select BSS_ID, BSS_UNT_ID'
+ ' from BARANG_STOK_SIRKULASI '
+ ' where BSS_DOC_NO = ' + QuotedStr(aHeaderNo)
+ ' and BSS_UNT_ID = '+ IntToStr(aUnitID);
with cOpenQuery(sSQL) do
begin
SS := TStringList.Create;
try
if Fields[0].IsNull then
begin
Result := True // kalo null berarti insert baru
end else begin
while not Eof do
begin
IsAda := False;
for i := 0 to Self.Count - 1 do
begin
if (Self[i].FNewUnitID = FieldByName('BSS_UNT_ID').AsString) and
(Self[i].ID = FieldByName('BSS_ID').AsInteger) then
begin
IsAda := True;
Break;
end;
end;
if not IsAda then
SS.Add(TBarangStockSirkulasiItem.RemoveFromDB(FieldByName('BSS_ID').AsInteger, FieldByName('BSS_UNT_ID').AsInteger));
Next;
end;
SS.SaveToFile(cGetAppPath + 'DeleteBarangStockSirkulasi.txt');
if not cExecSQL(SS) then
begin
cRollbackTrans;
raise Exception.Create('Gagal Menghapus Data Di Barang Stock Sirkulasi');
Result := False;
Exit;
end;
end;
finally
Free;
SS.Free;
end;
end;
end;
function TBarangStockSirkulasiItems.GetBarangStockSirkulasiItem(Index:
Integer): TBarangStockSirkulasiItem;
begin
Result := (inherited Items[index]) as TBarangStockSirkulasiItem;
end;
function TBarangStockSirkulasiItems.GetHeaderFlag: Integer;
begin
Result := 9696;
end;
procedure TBarangStockSirkulasiItems.LoadByID(aID : Integer; aUnitID : Integer);
var
S: string;
begin
S := 'Select * from ' + CustomTableName + ' Where BSS_ID = ' + IntToStr(aID)
+ ' and BSS_UNT_ID = ' + IntToStr(aUnitID);
with cOpenQuery(S) do
Begin
while not eof do
begin
with self.add do
begin
FID := FieldByName(GetFieldNameFor_ID).asInteger;
FIsEOD := FieldByName(GetFieldNameFor_IsEOD).asInteger;
FKeterangan := FieldByName(GetFieldNameFor_Keterangan).asString;
FNewBarangKode := FieldByName(GetFieldNameFor_NewBarang).AsString;
FNewUnitID := FieldByName(GetFieldNameFor_NewUnit).AsString;
FNewUOMKode := FieldByName(GetFieldNameFor_NewUOM).AsString;
FNoBukti := FieldByName(GetFieldNameFor_NoBukti).asString;
FQty := FieldByName(GetFieldNameFor_Qty).asFloat;
FHargaTransaksi := FieldByName(GetFieldNameFor_HargaTransaksi).asFloat;
FHargaLastCost := FieldByName(GetFieldNameFor_HargaLastCost).asFloat;
FTglBukti := FieldByName(GetFieldNameFor_Tanggal).asDateTime;
FTypeTransaksi := FieldByName(GetFieldNameFor_TypeTransaksi).asString;
FISBONUSFORBONUS := FieldByName(GetFieldNameFor_IsBonusForBonus).AsInteger;
end;
next;
end;
free;
End;
end;
procedure TBarangStockSirkulasiItems.LoadByNoBukti(aNoBukti : String; aUnitID :
Integer; aHeaderFlag : Integer);
var
S: string;
begin
S := 'Select * from ' + CustomTableName + ' Where BSS_DOC_NO = ' + QuotedStr(aNoBukti)
+ ' and BSS_UNT_ID = ' + IntToStr(aUnitID);
//+ ' and HEADERFLAG = ' + IntToStr(aHeaderFlag);
with cOpenQuery(S) do
Begin
try
while not eof do
begin
with self.add do
begin
FID := FieldByName(GetFieldNameFor_ID).asInteger;
FIsEOD := FieldByName(GetFieldNameFor_IsEOD).asInteger;
FKeterangan := FieldByName(GetFieldNameFor_Keterangan).asString;
FNewBarangKode := FieldByName(GetFieldNameFor_NewBarang).AsString;
FNewUnitID := FieldByName(GetFieldNameFor_NewUnit).AsString;
FNewUOMKode := FieldByName(GetFieldNameFor_NewUOM).AsString;
FNoBukti := FieldByName(GetFieldNameFor_NoBukti).asString;
FQty := FieldByName(GetFieldNameFor_Qty).asFloat;
FTglBukti := FieldByName(GetFieldNameFor_Tanggal).asDateTime;
FTypeTransaksi := FieldByName(GetFieldNameFor_TypeTransaksi).asString;
FISBONUSFORBONUS := FieldByName(GetFieldNameFor_IsBonusForBonus).AsInteger;
FHargaTransaksi := FieldByName(GetFieldNameFor_HargaTransaksi).asFloat;
FHargaLastCost := FieldByName(GetFieldNameFor_HargaLastCost).asFloat;
end;
next;
end;
finally
free;
end;
End;
end;
class function TBarangStockSirkulasiItems.RemoveByDocNo(aDocNo : String;
aUnitID : Integer; aTipe : String): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := ' delete '
+ ' from barang_stok_sirkulasi '
+ ' where bss_doc_no = ' + QuotedStr(aDocNo)
+ ' and BSS_UNT_ID = ' + IntToStr(aUnitID)
+ ' and BSS_TYPE = ' + QuotedStr(aTipe);
if cExecSQL(sSQL,dbtPOS,False) then
Result := True; // SimpanBlob(sSQL, 1);
end;
function TBarangStockSirkulasiItems.SaveToDatabase(aHeaderNo : string; aUnitID
: Integer): Boolean;
var
x: Integer;
i: Integer;
begin
Result := False;
x := Count - 1;
for i := 0 to x do
begin
if not BarangStockSirkulasiItem[i].ExecuteGenerateSQL(aHeaderNo,BarangStockSirkulasiItem[i].ID,aUnitID) then
begin
cRollbackTrans;
Exit;
end;
end;
if not CekBarangStockSirkulasi(aHeaderNo, aUnitID) then
begin
cRollbackTrans;
raise Exception.Create('Cek Fungsi CekBarangStockSirkulasi');
Exit;
end;
Result := True;
end;
procedure TBarangStockSirkulasiItems.SetBarangStockSirkulasiItem(Index: Integer;
Value: TBarangStockSirkulasiItem);
begin
inherited Items[Index] := Value
end;
end.
|
// Common stuff for SFNT-based fonts
unit fi_sfnt;
interface
uses
fi_common,
classes;
const
SFNT_TAG_BASE = $42415345;
SFNT_TAG_FVAR = $66766172;
SFNT_TAG_GDEF = $47444546;
SFNT_TAG_GLYF = $676c7966;
SFNT_TAG_GPOS = $47504f53;
SFNT_TAG_GSUB = $47535542;
SFNT_TAG_JSTF = $4a535446;
SFNT_TAG_LOCA = $6c6f6361;
SFNT_TAG_NAME = $6e616d65;
SFNT_COLLECTION_SIGN = $74746366; // 'ttcf'
function SFNT_IsLayoutTable(tag: LongWord): Boolean;
function SFNT_GetFormatSting(
sign: LongWord; hasLayoutTables: Boolean): String;
type
TSFNTTableReader = procedure(stream: TStream; var info: TFontInfo);
function SFNT_FindTableReader(tag: LongWord): TSFNTTableReader;
{
Helper for TSFNTTableReader that restores the initial stream
position after reading at the given offset. Does nothing if reader
is NIL.
}
procedure SFNT_ReadTable(
reader: TSFNTTableReader;
stream: TStream;
var info: TFontInfo;
offset: LongWord);
{
Common parser for TTF, TTC, OTF, OTC, and EOT.
fontOffset is necessary for EOT since its EMBEDDEDFONT structure
is not treated as part of the font data.
}
procedure SFNT_ReadCommonInfo(
stream: TStream; var info: TFontInfo; fontOffset: LongWord = 0);
implementation
uses
fi_info_reader,
fi_utils,
streamex,
sysutils;
const
SFNT_TTF_SIGN1 = $00010000;
SFNT_TTF_SIGN2 = $00020000;
SFNT_TTF_SIGN3 = $74727565; // 'true'
SFNT_TTF_SIGN4 = $74797031; // 'typ1'
SFNT_OTF_SIGN = $4f54544f; // 'OTTO'
function SFNT_IsLayoutTable(tag: LongWord): Boolean;
begin
case tag of
SFNT_TAG_BASE,
SFNT_TAG_GDEF,
SFNT_TAG_GPOS,
SFNT_TAG_GSUB,
SFNT_TAG_JSTF:
result := TRUE;
else
result := FALSE;
end;
end;
function SFNT_GetFormatSting(
sign: LongWord; hasLayoutTables: Boolean): String;
begin
if sign = SFNT_OTF_SIGN then
result := 'OT PS'
else if hasLayoutTables then
result := 'OT TT'
else
result := 'TT';
end;
procedure SFNT_ReadTable(
reader: TSFNTTableReader;
stream: TStream;
var info: TFontInfo;
offset: LongWord);
var
start: Int64;
begin
if reader = NIL then
exit;
start := stream.Position;
stream.Seek(offset, soBeginning);
reader(stream, info);
stream.Seek(start, soBeginning);
end;
procedure ReadNameTable(stream: TStream; var info: TFontInfo);
const
PLATFORM_ID_MAC = 1;
PLATFORM_ID_WIN = 3;
LANGUAGE_ID_MAC_ENGLISH = 0;
LANGUAGE_ID_WIN_ENGLISH_US = $0409;
ENCODING_ID_MAC_ROMAN = 0;
ENCODING_ID_WIN_UCS2 = 1;
type
TNamingTable = packed record
version,
count,
storageOffset: Word;
end;
TNameRecord = packed record
platformId,
encodingId,
languageId,
nameId,
length,
stringOffset: Word;
end;
var
start: Int64;
namingTable: TNamingTable;
storagePos,
offset: Int64;
i: LongInt;
nameRec: TNameRecord;
name: UnicodeString;
dst: PString;
begin
start := stream.Position;
stream.ReadBuffer(namingTable, SizeOf(namingTable));
{$IFDEF ENDIAN_LITTLE}
with namingTable do
begin
version := SwapEndian(version);
count := SwapEndian(count);
storageOffset := SwapEndian(storageOffset);
end;
{$ENDIF}
if namingTable.count = 0 then
raise EStreamError.Create('Naming table has no records');
storagePos := start + namingTable.storageOffset;
for i := 0 to namingTable.count - 1 do
begin
stream.ReadBuffer(nameRec, SizeOf(nameRec));
{$IFDEF ENDIAN_LITTLE}
with nameRec do
begin
platformId := SwapEndian(platformId);
encodingId := SwapEndian(encodingId);
languageId := SwapEndian(languageId);
nameId := SwapEndian(nameId);
length := SwapEndian(length);
stringOffset := SwapEndian(stringOffset);
end;
{$ENDIF}
if nameRec.length = 0 then
continue;
case nameRec.platformId of
PLATFORM_ID_MAC:
if (nameRec.encodingId <> ENCODING_ID_MAC_ROMAN)
or (nameRec.languageId <> LANGUAGE_ID_MAC_ENGLISH) then
continue;
PLATFORM_ID_WIN:
// Entries in the Name Record are sorted by ids so we can
// stop parsing after we finished reading all needed
// records.
if (nameRec.encodingId > ENCODING_ID_WIN_UCS2)
or (nameRec.languageId > LANGUAGE_ID_WIN_ENGLISH_US) then
break
else if (nameRec.encodingId <> ENCODING_ID_WIN_UCS2)
or (nameRec.languageId <> LANGUAGE_ID_WIN_ENGLISH_US) then
continue;
else
// We don't break in case id > PLATFORM_ID_WIN so that we
// can read old buggy TTFs produced by the AllType program.
// The first record in such fonts has random number as id.
continue;
end;
case nameRec.nameId of
0: dst := @info.copyright;
1: dst := @info.family;
2: dst := @info.style;
3: dst := @info.uniqueId;
4: dst := @info.fullName;
5: dst := @info.version;
6: dst := @info.psName;
7: dst := @info.trademark;
8: dst := @info.manufacturer;
9: dst := @info.designer;
10: dst := @info.description;
11: dst := @info.vendorUrl;
12: dst := @info.designerUrl;
13: dst := @info.license;
14: dst := @info.licenseUrl;
15: continue; // Reserved
16: dst := @info.family; // Typographic Family
17: dst := @info.style; // Typographic Subfamily
else
// We can only break early in case of Windows platform id.
// There are fonts (like Trattatello.ttf) where mostly
// non-standard Macintosh names (name id >= 256) are followed
// by standard Windows names.
if nameRec.platformId >= PLATFORM_ID_WIN then
break
else
continue;
end;
offset := stream.Position;
stream.Seek(storagePos + nameRec.stringOffset, soBeginning);
case nameRec.platformId of
PLATFORM_ID_MAC:
begin
SetLength(dst^, nameRec.length);
stream.ReadBuffer(dst^[1], nameRec.length);
dst^ := MacOSRomanToUTF8(dst^);
end;
PLATFORM_ID_WIN:
begin
SetLength(name, nameRec.length div SizeOf(WideChar));
stream.ReadBuffer(name[1], nameRec.length);
{$IFDEF ENDIAN_LITTLE}
SwapUnicodeEndian(name);
{$ENDIF}
dst^ := UTF8Encode(name);
end;
end;
stream.Seek(offset, soBeginning);
end;
end;
procedure ReadFvarTable(stream: TStream; var info: TFontInfo);
var
start: Int64;
axesArrayOffset,
axisCount,
axisSize: Word;
i: LongInt;
begin
start := stream.Position;
// Skip majorVersion and minorVersion.
stream.Seek(SizeOf(Word) * 2 , soCurrent);
axesArrayOffset := stream.ReadWordBE;
// Skip reserved.
stream.Seek(SizeOf(Word) , soCurrent);
axisCount := stream.ReadWordBE;
// Specs say that the font must be treated as non-variable if
// axisCount is zero.
if axisCount = 0 then
exit;
axisSize := stream.ReadWordBE;
SetLength(info.variationAxisTags, axisCount);
for i := 0 to axisCount - 1 do
begin
stream.Seek(start + axesArrayOffset + axisSize * i, soBeginning);
// Note that we don't check the variation axis record flags, since
// we want to include even those axes that were marked as hidden
// by the font designer.
info.variationAxisTags[i] := stream.ReadDWordBE;
end;
// Variation axis records are not required to be sorted.
specialize SortArray<LongWord>(info.variationAxisTags);
end;
const
TABLE_READERS: array [0..1] of record
tag: LongWord;
reader: TSFNTTableReader;
end = (
(tag: SFNT_TAG_FVAR; reader: @ReadFvarTable),
(tag: SFNT_TAG_NAME; reader: @ReadNameTable)
);
function SFNT_FindTableReader(tag: LongWord): TSFNTTableReader;
var
i: SizeInt;
begin
for i := 0 to High(TABLE_READERS) do
if TABLE_READERS[i].tag = tag then
exit(TABLE_READERS[i].reader);
result := NIL;
end;
procedure SFNT_ReadCommonInfo(
stream: TStream; var info: TFontInfo; fontOffset: LongWord);
type
TOffsetTable = packed record
version: LongWord;
numTables: Word;
//searchRange,
//entrySelector,
//rangeShift: Word;
end;
TTableDirEntry = packed record
tag,
checksumm,
offset,
length: LongWord;
end;
var
offsetTable: TOffsetTable;
i: LongInt;
dir: TTableDirEntry;
hasLayoutTables: Boolean = FALSE;
begin
stream.ReadBuffer(offsetTable, SizeOf(offsetTable));
{$IFDEF ENDIAN_LITTLE}
with offsetTable do
begin
version := SwapEndian(version);
numTables := SwapEndian(numTables);
end;
{$ENDIF}
if (offsetTable.version <> SFNT_TTF_SIGN1)
and (offsetTable.version <> SFNT_TTF_SIGN2)
and (offsetTable.version <> SFNT_TTF_SIGN3)
and (offsetTable.version <> SFNT_TTF_SIGN4)
and (offsetTable.version <> SFNT_OTF_SIGN) then
raise EStreamError.Create('Not a SFNT-based font');
if offsetTable.numTables = 0 then
raise EStreamError.Create('Font has no tables');
stream.Seek(SizeOf(Word) * 3, soCurrent);
for i := 0 to offsetTable.numTables - 1 do
begin
stream.ReadBuffer(dir, SizeOf(dir));
{$IFDEF ENDIAN_LITTLE}
with dir do
begin
tag := SwapEndian(tag);
checksumm := SwapEndian(checksumm);
offset := SwapEndian(offset);
length := SwapEndian(length);
end;
{$ENDIF}
SFNT_ReadTable(
SFNT_FindTableReader(dir.tag),
stream,
info,
fontOffset + dir.offset);
hasLayoutTables := (
hasLayoutTables or SFNT_IsLayoutTable(dir.tag));
end;
info.format := SFNT_GetFormatSting(
offsetTable.version, hasLayoutTables);
end;
end.
|
unit uContaReceberDAOClient;
interface
uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Generics.Collections, DBXJSONReflect, ContaReceber;
type
TContaReceberDAOClient = class(TDSAdminClient)
private
FListCommand: TDBXCommand;
FInsertCommand: TDBXCommand;
FUpdateCommand: TDBXCommand;
FDeleteCommand: TDBXCommand;
FBaixarContaCommand: TDBXCommand;
FRelatorioCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function List: TDBXReader;
function Insert(ContaReceber: TContaReceber): Boolean;
function Update(ContaReceber: TContaReceber): Boolean;
function Delete(ContaReceber: TContaReceber): Boolean;
function BaixarConta(ContaReceber: TContaReceber; Data: TDateTime; Valor: Currency; FormaPagamento: Integer): Boolean;
function Relatorio(DataInicial, DataFinal: TDateTime; ClienteCodigo: string; Situacao: Integer): TDBXReader;
end;
implementation
function TContaReceberDAOClient.List: TDBXReader;
begin
if FListCommand = nil then
begin
FListCommand := FDBXConnection.CreateCommand;
FListCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListCommand.Text := 'TContaReceberDAO.List';
FListCommand.Prepare;
end;
FListCommand.ExecuteUpdate;
Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TContaReceberDAOClient.Relatorio(DataInicial, DataFinal: TDateTime; ClienteCodigo: string; Situacao: Integer): TDBXReader;
begin
if FRelatorioCommand = nil then
begin
FRelatorioCommand := FDBXConnection.CreateCommand;
FRelatorioCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FRelatorioCommand.Text := 'TContaReceberDAO.Relatorio';
FRelatorioCommand.Prepare;
end;
FRelatorioCommand.Parameters[0].Value.AsDateTime := DataInicial;
FRelatorioCommand.Parameters[1].Value.AsDateTime := DataFinal;
FRelatorioCommand.Parameters[2].Value.AsString := ClienteCodigo;
FRelatorioCommand.Parameters[3].Value.AsInt32 := Situacao;
FRelatorioCommand.ExecuteUpdate;
Result := FRelatorioCommand.Parameters[4].Value.GetDBXReader(FInstanceOwner);
end;
function TContaReceberDAOClient.Insert(ContaReceber: TContaReceber): Boolean;
begin
if FInsertCommand = nil then
begin
FInsertCommand := FDBXConnection.CreateCommand;
FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsertCommand.Text := 'TContaReceberDAO.Insert';
FInsertCommand.Prepare;
end;
if not Assigned(ContaReceber) then
FInsertCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ContaReceber), True);
if FInstanceOwner then
ContaReceber.Free
finally
FreeAndNil(FMarshal)
end
end;
FInsertCommand.ExecuteUpdate;
Result := FInsertCommand.Parameters[1].Value.GetBoolean;
end;
function TContaReceberDAOClient.Update(ContaReceber: TContaReceber): Boolean;
begin
if FUpdateCommand = nil then
begin
FUpdateCommand := FDBXConnection.CreateCommand;
FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FUpdateCommand.Text := 'TContaReceberDAO.Update';
FUpdateCommand.Prepare;
end;
if not Assigned(ContaReceber) then
FUpdateCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ContaReceber), True);
if FInstanceOwner then
ContaReceber.Free
finally
FreeAndNil(FMarshal)
end
end;
FUpdateCommand.ExecuteUpdate;
Result := FUpdateCommand.Parameters[1].Value.GetBoolean;
end;
function TContaReceberDAOClient.Delete(ContaReceber: TContaReceber): Boolean;
begin
if FDeleteCommand = nil then
begin
FDeleteCommand := FDBXConnection.CreateCommand;
FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDeleteCommand.Text := 'TContaReceberDAO.Delete';
FDeleteCommand.Prepare;
end;
if not Assigned(ContaReceber) then
FDeleteCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FDeleteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FDeleteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ContaReceber), True);
if FInstanceOwner then
ContaReceber.Free
finally
FreeAndNil(FMarshal)
end
end;
FDeleteCommand.ExecuteUpdate;
Result := FDeleteCommand.Parameters[1].Value.GetBoolean;
end;
constructor TContaReceberDAOClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
function TContaReceberDAOClient.BaixarConta(ContaReceber: TContaReceber; Data: TDateTime; Valor: Currency; FormaPagamento: Integer): Boolean;
begin
if FBaixarContaCommand = nil then
begin
FBaixarContaCommand := FDBXConnection.CreateCommand;
FBaixarContaCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FBaixarContaCommand.Text := 'TContaReceberDAO.BaixarConta';
FBaixarContaCommand.Prepare;
end;
if not Assigned(ContaReceber) then
FBaixarContaCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FBaixarContaCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FBaixarContaCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ContaReceber), True);
if FInstanceOwner then
ContaReceber.Free
finally
FreeAndNil(FMarshal)
end
end;
FBaixarContaCommand.Parameters[1].Value.AsDateTime := Data;
FBaixarContaCommand.Parameters[2].Value.AsCurrency := Valor;
FBaixarContaCommand.Parameters[3].Value.AsInt32 := FormaPagamento;
FBaixarContaCommand.ExecuteUpdate;
Result := FBaixarContaCommand.Parameters[4].Value.GetBoolean;
end;
constructor TContaReceberDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TContaReceberDAOClient.Destroy;
begin
FreeAndNil(FListCommand);
FreeAndNil(FInsertCommand);
FreeAndNil(FUpdateCommand);
FreeAndNil(FDeleteCommand);
FreeAndNil(FBaixarContaCommand);
FreeAndNil(FRelatorioCommand);
inherited;
end;
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2009 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
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/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox 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. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_StreamUtils;
interface
uses SysUtils, Classes;
const
Base64Chars: string =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// You can implement non-standard variants to base64 transformation,
// by passing a string like the above one into the base64 transform functions
// below.
type
TInverseBaseTransform = array[Byte] of byte;
TDesalinationWriteStream = class( TStream)
private
FFreshwaterStream: TStream;
FSaltVolume: integer;
protected
function GetSize: Int64; override;
procedure SetSize( const NewSize: Int64); override;
public
function Read( var Buffer; Count: Longint): Longint; override;
function Write( const Buffer; Count: Longint): Longint; override;
function Seek( const Offset: Int64; Origin: TSeekOrigin): Int64; override;
property FreshwaterStream: TStream read FFreshwaterStream write FFreshwaterStream;
property SaltVolume: integer read FSaltVolume write FSaltVolume;
end;
function CloneMemoryStream( Original: TMemoryStream): TMemoryStream;
procedure CopyMemoryStream( Source, Destination: TMemoryStream);
procedure BurnMemoryStream( Destructo: TMemoryStream);
procedure BurnMemory( var Buff; BuffLen: integer);
procedure ZeroFillStream( Stream: TMemoryStream);
procedure RandomFillStream( Stream: TMemoryStream);
procedure XOR_Streams2( Dest, Srce: TMemoryStream); // Dest := Dest xor Srce
procedure XOR_Streams3( Dest, SrceA, SrceB: TMemoryStream); // Dest := SrceB xor SrceB
function CompareMemoryStreams( S1, S2: TMemoryStream): boolean;
function Stream_to_Base64(ASource: TStream; const ATransform: TBytes = nil): TBytes;
procedure Base64_to_stream( const Base64: TBytes; Destin: TStream);
procedure CustomBase64_to_stream( const Base64: TBytes; Destin: TStream;
const InverseTransform: TInverseBaseTransform);
function Stream_to_Bytes(Source: TStream): TBytes;
procedure AnsiString_to_stream( const Value: TBytes; Destin: TStream);
function CompareFiles( const FN1, FN2: string;
Breathe: TNotifyEvent; BreathingSender: TObject): boolean;
function FileSize( const FileName: string): int64;
// For debug purposes ONLY:
function Stream_to_decimalbytes( Source: TStream): string;
function DisplayStream( Stream: TStream): string;
implementation
uses Math, uTPLb_Random, uTPLb_IntegerUtils, uTPLb_StrUtils;
var
Inverse_Base64Chars: TInverseBaseTransform;
procedure Invert_Base64Chars; forward;
procedure InitUnit_StreamUtils;
begin
Invert_Base64Chars;
end;
procedure DoneUnit_StreamUtils;
begin
end;
procedure BurnMemory( var Buff; BuffLen: integer);
begin
FillChar( Buff, BuffLen, 0)
end;
procedure ZeroFillStream( Stream: TMemoryStream);
var
L: integer;
begin
if assigned( Stream) then
L := Stream.Size
else
L := 0;
if L <= 0 then exit;
FillChar( Stream.Memory^, L, 0)
end;
procedure RandomFillStream( Stream: TMemoryStream);
begin
if assigned( Stream) and (Stream.Size > 0) then
TRandomStream.Instance.Read( Stream.Memory^, Stream.Size)
end;
function CloneMemoryStream( Original: TMemoryStream): TMemoryStream;
var
L: integer;
begin
if assigned( Original) then
L := Original.Size
else
L := 0;
result := TMemoryStream.Create;
result.Size := L;
if L <= 0 then exit;
Move( Original.Memory^, result.Memory^, L);
result.Position := Original.Position
end;
procedure BurnMemoryStream( Destructo: TMemoryStream);
var
L: integer;
begin
if not assigned( Destructo) then exit;
L := Destructo.Size;
if L <= 0 then exit;
BurnMemory( Destructo.Memory^, L);
Destructo.Size := 0
end;
procedure XOR_Streams2( Dest, Srce: TMemoryStream); // Dest := Dest xor Srce
var
L: integer;
j: Integer;
DestP, SrceP: PByte;
DestP32, SrceP32: ^uint32;
begin
if assigned( Dest) and assigned( Srce) then
L := Min( Dest.Size, Srce.Size)
else
L := 0;
if L <= 0 then exit;
DestP32 := Dest.Memory;
SrceP32 := Srce.Memory;
for j := 0 to (L div 4) - 1 do
begin // Do as much as we can in 32 bit. It is faster.
DestP32^ := DestP32^ xor SrceP32^;
Inc( DestP32);
Inc( SrceP32)
end;
DestP := PByte( DestP32);
SrceP := PByte( SrceP32);
for j := 0 to (L mod 4) - 1 do
begin // And the remainder in 8 bit.
DestP^ := DestP^ xor SrceP^;
Inc( DestP);
Inc( SrceP)
end
end;
procedure XOR_Streams3( Dest, SrceA, SrceB: TMemoryStream); // Dest := SrceB xor SrceB
var
L: integer;
j: Integer;
DestP, SrceAP, SrceBP: PByte;
DestP32, SrceAP32, SrceBP32: ^uint32;
begin
if assigned( Dest) and assigned( SrceA) and assigned( SrceB) then
L := Min( Min( Dest.Size, SrceA.Size), SrceB.Size)
else
L := 0;
if L <= 0 then exit;
DestP32 := Dest.Memory;
SrceAP32 := SrceA.Memory;
SrceBP32 := SrceB.Memory;
for j := 0 to (L div 4) - 1 do
begin // Do as much as we can in 32 bit. It is faster.
DestP32^ := SrceAP32^ xor SrceBP32^;
Inc( DestP32);
Inc( SrceAP32);
Inc( SrceBP32)
end;
DestP := PByte( DestP32);
SrceAP := PByte( SrceAP32);
SrceBP := PByte( SrceBP32);
for j := 0 to (L mod 4) - 1 do
begin
DestP^ := SrceAP^ xor SrceBP^;
Inc( DestP);
Inc( SrceAP);
Inc( SrceBP)
end
end;
function CompareMemoryStreams( S1, S2: TMemoryStream): boolean;
var
L: integer;
begin
L := S1.Size;
result := (L = S2.Size) and ((L = 0) or (CompareMem( S1.Memory, S2.Memory, L)))
end;
procedure CopyMemoryStream( Source, Destination: TMemoryStream);
var
L: integer;
begin
L := Source.Size;
Destination.Size := L;
if L > 0 then
Move( Source.Memory^, Destination.Memory^, L)
end;
function Stream_to_Base64(ASource: TStream; const ATransform: TBytes = nil): TBytes;
var
pThreeBytes: packed array[ 0..2 ] of byte;
iBytesRead: integer;
P, j, i: integer;
pBase64Transform: TBytes;
begin
pBase64Transform := ATransform;
if pBase64Transform = nil then
pBase64Transform := AnsiBytesOf(Base64Chars);
SetLength(Result, (ASource.Size + 2) div 3 * 4);
ASource.Position := 0;
P := 0;
repeat
iBytesRead := ASource.Read( pThreeBytes, 3);
if iBytesRead = 0 then break;
for j := iBytesRead to 2 do
pThreeBytes[j] := 0;
for j := 0 to iBytesRead do
begin
result[ P ] := pBase64Transform[ ( pThreeBytes[0] shr 2) + 0];
Inc( P);
for i := 0 to 1 do
pThreeBytes[i] := (pThreeBytes[i] shl 6) + (pThreeBytes[i+1] shr 2);
pThreeBytes[ 2] := pThreeBytes[ 2] shl 6
end
until iBytesRead < 3;
if iBytesRead > 0 then
for j := iBytesRead to 2 do
begin
result[P] := Ord('=');
Inc( P)
end
end;
procedure Base64_to_stream( const Base64: TBytes; Destin: TStream);
begin
CustomBase64_to_stream( Base64, Destin, Inverse_Base64Chars)
end;
procedure CustomBase64_to_stream( const Base64: TBytes; Destin: TStream;
const InverseTransform: TInverseBaseTransform);
var
P, j, i: integer;
Ch: Byte;
Bits6: byte;
ThreeBytes: packed array[ 0..2 ] of byte;
ByteIdx, BitIdx: integer;
// ShrN: integer;
Addend: byte;
begin
// Assume Destin is already at the desired postion and size.
for P := 0 to (Length( Base64) div 4) - 1 do
begin
for i := 0 to 2 do ThreeBytes[i] := 0;
ByteIdx := 0;
BitIdx := 0;
for j := 1 to 4 do
begin
Ch := Base64[ P * 4 + j - 1];
if Ch = Ord('=') then break;
Bits6 := InverseTransform[ Ch];
// ShrN := BitIdx - 2;
if BitIdx > 2 then
Addend := Bits6 shr (BitIdx - 2)
else if BitIdx = 2 then
Addend := Bits6
else
Addend := Bits6 shl (2 - BitIdx);
ThreeBytes[ ByteIdx ] := ThreeBytes[ ByteIdx ] + Addend;
Inc( BitIdx, 6);
if BitIdx >= 8 then
begin
Dec( BitIdx, 8);
Inc( ByteIdx);
if BitIdx > 0 then
ThreeBytes[ByteIdx] := ThreeBytes[ByteIdx] + (Bits6 shl (8 - BitIdx));
end
end;
Destin.WriteBuffer( ThreeBytes, ByteIdx)
end
end;
procedure Invert_Base64Chars;
var
j: integer;
ch: Byte;
pBase64: TBytes;
begin
for ch := Low( Inverse_Base64Chars) to High( Inverse_Base64Chars) do
Inverse_Base64Chars[ ch] := 255;
pBase64 := AnsiBytesOf(Base64Chars);
for j := 1 to Length( pBase64) do
begin
ch := pBase64[j - 1];
Inverse_Base64Chars[ ch] := j - 1
end
end;
function Stream_to_Bytes(Source: TStream): TBytes;
begin
SetLength(Result, Source.Size);
if Result <> nil then
Source.ReadBuffer(Result[0], Length(Result));
end;
procedure AnsiString_to_stream( const Value: TBytes; Destin: TStream);
begin
if Value <> nil then
Destin.WriteBuffer( Value[0], Length( Value))
end;
{ TDesalinationWriteStream }
function TDesalinationWriteStream.GetSize: Int64;
begin
result := 0
end;
function TDesalinationWriteStream.Read( var Buffer; Count: Integer): Longint;
begin
result := 0
end;
function TDesalinationWriteStream.Seek(
const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
if assigned( FFreshwaterStream) then
result := FFreshwaterStream.Seek( Offset, Origin)
else
result := 0
end;
procedure TDesalinationWriteStream.SetSize( const NewSize: Int64);
begin
end;
function TDesalinationWriteStream.Write( const Buffer; Count: Integer): Longint;
var
P: PByte;
C: integer;
SaltConsumption: integer;
begin
result := 0;
P := @Buffer;
C := Count;
if C <= 0 then exit;
SaltConsumption := Min( FSaltVolume, C);
if SaltConsumption > 0 then
begin
Dec( FSaltVolume, SaltConsumption);
Inc( P, SaltConsumption);
Dec( C, SaltConsumption);
result := SaltConsumption
end;
if (C > 0) and assigned( FFreshwaterStream) then
Inc( result, FFreshwaterStream.Write( P^, C))
end;
function Stream_to_decimalbytes( Source: TStream): string;
var
b: byte;
begin
Source.Position := 0;
result := '';
while Source.Read( b, 1) > 0 do
begin
if result <> '' then
result := result + ', ';
result := result + Format( '%d', [b])
end
end;
function CompareFiles( const FN1, FN2: string;
Breathe: TNotifyEvent; BreathingSender: TObject): boolean;
const
BufferSizeInBytes = 1024;
var
Stream1, Stream2: TStream;
{$IF CompilerVersion >= 21}
Buffer1, Buffer2: TBytes;
{$ELSE}
Buffer1, Buffer2: ansistring;
{$IFEND}
Count1, Count2, L: integer;
begin
Stream1 := TFileStream.Create( FN1, fmOpenRead);
Stream2 := TFileStream.Create( FN2, fmOpenRead);
try
result := Stream1.Size = Stream2.Size;
L := BufferSizeInBytes;
SetLength( Buffer1, L);
SetLength( Buffer2, L);
if result then
repeat
Count1 := Stream1.Read( Buffer1[0], L);
Count2 := Stream2.Read( Buffer2[0], L);
result := (Count1 = Count2) and CompareMem(@Buffer1[0], @Buffer2[0], Count1);
if assigned( Breathe) then
Breathe( BreathingSender)
// Breathe should do something like Application.ProcessMessages();
until (not result) or (Count1 < L)
finally
Stream1.Free;
Stream2.Free
end
end;
function FileSize( const FileName: string): int64;
var
FileStream: TStream;
begin
if not FileExists( FileName) then
result := 0
else
try
FileStream := TFileStream.Create( FileName, fmOpenRead);
try
result := FileStream.Size
finally
FileStream.Free
end
except
result := 0
end;
end;
function DisplayStream( Stream: TStream): string;
var
P, Sz: integer;
aByte: byte;
s: string;
begin
if not assigned( Stream) then
result := 'nil'
else
begin
P := Stream.Position;
Sz := Stream.Size;
Stream.Position := 0;
result := Format( 'stream[%d]=', [Sz]);
while Stream.Read( aByte, 1) = 1 do
begin
s := Format( '%2x', [aByte]);
if s[1]=' ' then
s[1] := '0';
result := result + ' ' + s
end;
Stream.Position := P
end
end;
initialization
InitUnit_StreamUtils;
finalization
DoneUnit_StreamUtils;
end.
|
{-------------------------------------------------------------------------------
Unit Name: frmAxes
Author: HochwimmerA
Purpose: Axes information...
$Id: frmAxes.pas,v 1.5 2003/09/21 19:07:43 hochwimmera Exp $
-------------------------------------------------------------------------------}
unit frmAxes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
StdCtrls, geFloatEdit, ExtCtrls,cGLCoordinateAxes;
type
TformAxes = class(TForm)
ActionManager1: TActionManager;
ActionToolBar_Axes: TActionToolBar;
ImageList: TImageList;
acAxesVisible: TAction;
acAxesX: TAction;
acAxesY: TAction;
acAxesZ: TAction;
acAxesXYGrid: TAction;
acAxesYZGrid: TAction;
acAxesXZGrid: TAction;
pnlAxesSettings: TPanel;
lblAxesXOrigin: TLabel;
lblAxesYOrigin: TLabel;
lblAxesZOrigin: TLabel;
lblAxesXLength: TLabel;
lblAxesYLength: TLabel;
lblAxesZLength: TLabel;
cbxAxesXN: TCheckBox;
cbxAxesYN: TCheckBox;
cbxAxesZN: TCheckBox;
cbxAxesZP: TCheckBox;
cbxAxesYP: TCheckBox;
cbxAxesXP: TCheckBox;
geAxesXOrigin: TGEFloatEdit;
geAxesYOrigin: TGEFloatEdit;
geAxesZOrigin: TGEFloatEdit;
geAxesXLength: TGEFloatEdit;
geAxesYLength: TGEFloatEdit;
geAxesZLength: TGEFloatEdit;
pnlAxesLabels: TPanel;
lblAxesLabels: TLabel;
lblAxesXStart: TLabel;
lblAxesXStep: TLabel;
lblAxesXStop: TLabel;
lblAxesYStart: TLabel;
lblAxesYStep: TLabel;
lblAxesYStop: TLabel;
lblAxesZStart: TLabel;
lblAxesZStep: TLabel;
lblAxesZStop: TLabel;
geAxesXStart: TGEFloatEdit;
geAxesXStep: TGEFloatEdit;
geAxesXStop: TGEFloatEdit;
bAxesUpdate: TButton;
geAxesYStart: TGEFloatEdit;
geAxesYStep: TGEFloatEdit;
geAxesYStop: TGEFloatEdit;
geAxesZStart: TGEFloatEdit;
geAxesZStep: TGEFloatEdit;
geAxesZStop: TGEFloatEdit;
geAxesXRadius: TGEFloatEdit;
lblAxesXRadius: TLabel;
lblAxesYRadius: TLabel;
geAxesYRadius: TGEFloatEdit;
lblAxesZRadius: TLabel;
geAxesZRadius: TGEFloatEdit;
pnlXAxesColour: TPanel;
lblAxesXColour: TLabel;
ColourDialog: TColorDialog;
lblAxesYColour: TLabel;
pnlYAxesColour: TPanel;
Label1: TLabel;
pnlZAxesColour: TPanel;
Label2: TLabel;
pnlXLabelColour: TPanel;
pnlYLabelColour: TPanel;
pnlZLabelColour: TPanel;
procedure acAxesVisibleExecute(Sender: TObject);
procedure acAxesXExecute(Sender: TObject);
procedure acAxesYExecute(Sender: TObject);
procedure acAxesZExecute(Sender: TObject);
procedure acAxesXYGridExecute(Sender: TObject);
procedure acAxesYZGridExecute(Sender: TObject);
procedure acAxesXZGridExecute(Sender: TObject);
procedure cbxAxesXNClick(Sender: TObject);
procedure cbxAxesXPClick(Sender: TObject);
procedure cbxAxesYNClick(Sender: TObject);
procedure cbxAxesYPClick(Sender: TObject);
procedure cbxAxesZNClick(Sender: TObject);
procedure cbxAxesZPClick(Sender: TObject);
procedure geAxesXOriginExit(Sender: TObject);
procedure geAxesYOriginExit(Sender: TObject);
procedure geAxesZOriginExit(Sender: TObject);
procedure geAxesXLengthExit(Sender: TObject);
procedure geAxesYLengthExit(Sender: TObject);
procedure geAxesZLengthExit(Sender: TObject);
procedure bAxesUpdateClick(Sender: TObject);
procedure geAxesXRadiusExit(Sender: TObject);
procedure geAxesYRadiusExit(Sender: TObject);
procedure geAxesZRadiusExit(Sender: TObject);
procedure pnlXAxesColourClick(Sender: TObject);
procedure pnlYAxesColourClick(Sender: TObject);
procedure pnlZAxesColourClick(Sender: TObject);
procedure pnlXLabelColourClick(Sender: TObject);
procedure pnlYLabelColourClick(Sender: TObject);
procedure pnlZLabelColourClick(Sender: TObject);
private
public
procedure SetAxesProperties(aaxes:TGLCoordinateAxes);
end;
var
formAxes: TformAxes;
implementation
uses
frmMain;
{$R *.dfm}
procedure TformAxes.SetAxesProperties(aaxes:TGLCoordinateAxes);
begin
geAxesXOrigin.Value := formMain.GLDAxes.Position.X/aaxes.scalex;
geAxesYOrigin.Value := formMain.GLDAxes.Position.Y/aaxes.scaley;
geAxesZOrigin.Value := formMain.GLDAxes.Position.Z/aaxes.scalez;
geAxesXLength.Value := aaxes.XLength;
geAxesXRadius.Value := aaxes.XRadius;
pnlXAxesColour.Color := aaxes.XAxisColour;
geAxesYLength.Value := aaxes.YLength;
geAxesYRadius.Value := aaxes.YRadius;
pnlYAxesColour.Color := aaxes.YAxisColour;
geAxesZLength.Value := aaxes.ZLength;
geAxesZRadius.Value := aaxes.ZRadius;
pnlZAxesColour.Color := aaxes.ZAxisColour;
geAxesXStart.Value := aaxes.XLabelStart;
geAxesXStep.Value := aaxes.XLabelStep;
geAxesXStop.Value := aaxes.XLabelStop;
geAxesYStart.Value := aaxes.YLabelStart;
geAxesYStep.Value := aaxes.YLabelStep;
geAxesYStop.Value := aaxes.YLabelStop;
geAxesZStart.Value := aaxes.ZLabelStart;
geAxesZStep.Value := aaxes.ZLabelStep;
geAxesZStop.Value := aaxes.ZLabelStop;
acAxesVisible.Checked := aaxes.IsVisible;
acAxesX.Checked := aaxes.XLabelVisible;
acAxesY.Checked := aaxes.YLabelVisible;
acAxesZ.Checked := aaxes.ZLabelVisible;
acAxesXYGrid.Checked := aaxes.XYGrid.Visible;
acAxesYZGrid.Checked := aaxes.YZGrid.Visible;
acAxesXZGrid.Checked := aaxes.XZGrid.Visible;
// axes parts:
cbxAxesXN.Checked := apXN in aaxes.Parts;
cbxAxesXP.Checked := apXP in aaxes.Parts;
cbxAxesYN.Checked := apYN in aaxes.Parts;
cbxAxesYP.Checked := apYP in aaxes.Parts;
cbxAxesZN.Checked := apZN in aaxes.Parts;
cbxAxesZP.Checked := apZP in aaxes.Parts;
bAxesUpdateClick(nil);
end;
// ----- TformAxes.acAxesVisibleExecute ----------------------------------------
procedure TformAxes.acAxesVisibleExecute(Sender: TObject);
begin
formMain.axes.ShowAxes(acAxesVisible.Checked);
end;
// ----- TformAxes.acAxesXExecute ----------------------------------------------
procedure TformAxes.acAxesXExecute(Sender: TObject);
begin
formmain.axes.XLabelVisible := acAxesX.Checked;
end;
// ----- TformAxes.acAxesYExecute ----------------------------------------------
procedure TformAxes.acAxesYExecute(Sender: TObject);
begin
formMain.axes.YLabelVisible := acAxesY.Checked;
end;
// ----- TformAxes.acAxesZExecute ----------------------------------------------
procedure TformAxes.acAxesZExecute(Sender: TObject);
begin
formMain.axes.ZLabelVisible := acAxesZ.Checked;
end;
// ----- TformAxes.acAxesXYGridExecute -----------------------------------------
procedure TformAxes.acAxesXYGridExecute(Sender: TObject);
begin
formMain.axes.XYGrid.Visible := acAxesXYGrid.Checked;
end;
// ----- TformAxes.acAxesYZGridExecute -----------------------------------------
procedure TformAxes.acAxesYZGridExecute(Sender: TObject);
begin
formMain.axes.YZGrid.Visible := acAxesYZGrid.Checked;
end;
// ----- TformAxes.acAxesXZGridExecute -----------------------------------------
procedure TformAxes.acAxesXZGridExecute(Sender: TObject);
begin
formMain.axes.XZGrid.Visible := acAxesXZGrid.Checked;
end;
// ----- TformAxes.cbxAxesXNClick ----------------------------------------------
procedure TformAxes.cbxAxesXNClick(Sender: TObject);
begin
formmain.axes.XN := cbxAxesXN.Checked;
end;
// ----- TformAxes.cbxAxesXPClick ----------------------------------------------
procedure TformAxes.cbxAxesXPClick(Sender: TObject);
begin
formmain.axes.XP := cbxAxesXP.Checked;
end;
// ----- TformAxes.cbxAxesYNClick ----------------------------------------------
procedure TformAxes.cbxAxesYNClick(Sender: TObject);
begin
formmain.axes.YN := cbxAxesYN.Checked;
end;
// ----- TformAxes.cbxAxesYPClick ----------------------------------------------
procedure TformAxes.cbxAxesYPClick(Sender: TObject);
begin
formmain.axes.YP := cbxAxesYP.Checked;
end;
// ----- TformAxes.cbxAxesZNClick ----------------------------------------------
procedure TformAxes.cbxAxesZNClick(Sender: TObject);
begin
formmain.axes.ZN := cbxAxesZN.Checked;
end;
// ----- TformAxes.cbxAxesZPClick ----------------------------------------------
procedure TformAxes.cbxAxesZPClick(Sender: TObject);
begin
formmain.axes.ZP := cbxAxesZP.Checked;
end;
// ----- TformAxes.geAxesXOriginExit -------------------------------------------
procedure TformAxes.geAxesXOriginExit(Sender: TObject);
begin
with formMain do
begin
GLDAxes.Position.X := geAxesXOrigin.Value*usersettings.ScaleX;
axes.GenerateXLabels;
end;
end;
// ----- TformAxes.geAxesYOriginExit -------------------------------------------
procedure TformAxes.geAxesYOriginExit(Sender: TObject);
begin
with formMain do
begin
GLDAxes.Position.Y := geAxesYOrigin.Value*usersettings.ScaleY;
axes.GenerateYLabels;
end;
end;
// ----- TformAxes.geAxesZOriginExit -------------------------------------------
procedure TformAxes.geAxesZOriginExit(Sender: TObject);
begin
with formMain do
begin
GLDAxes.Position.Z := geAxesZOrigin.Value*usersettings.ScaleZ;
axes.GenerateZLabels;
end;
end;
// ----- TformAxes.geAxesXLengthExit -------------------------------------------
procedure TformAxes.geAxesXLengthExit(Sender: TObject);
begin
formMain.axes.XLength := geAxesXLength.Value;
end;
// ----- TformAxes.geAxesYLengthExit -------------------------------------------
procedure TformAxes.geAxesYLengthExit(Sender: TObject);
begin
formMain.axes.YLength := geAxesYLength.Value;
end;
// ----- TformAxes.geAxesZLengthExit -------------------------------------------
procedure TformAxes.geAxesZLengthExit(Sender: TObject);
begin
formmain.axes.ZLength := geAxesZLength.Value;
end;
// ----- TformAxes.bAxesUpdateClick --------------------------------------------
procedure Tformaxes.bAxesUpdateClick(Sender: TObject);
begin
with formMain do
begin
axes.XLabelStart := geAxesXStart.Value;
axes.XLabelStep := geAxesXStep.Value;
axes.XLabelStop := geAxesXStop.Value;
axes.GenerateXLabels;
axes.YLabelStart := geAxesYStart.Value;
axes.YLabelStep := geAxesYStep.Value;
axes.YLabelStop := geAxesYStop.Value;
axes.GenerateYLabels;
axes.ZLabelStart := geAxesZStart.Value;
axes.ZLabelStep := geAxesZStep.Value;
axes.ZLabelStop := geAxesZStop.Value;
axes.GenerateZLabels;
end;
end;
// ----- TformAxes.geAxesXRadiusExit -------------------------------------------
procedure TformAxes.geAxesXRadiusExit(Sender: TObject);
begin
formMain.axes.XRadius := geAxesXRadius.Value;
end;
// ----- TformAxes.geAxesYRadiusExit -------------------------------------------
procedure TformAxes.geAxesYRadiusExit(Sender: TObject);
begin
formMain.axes.YRadius := geAxesYRadius.Value;
end;
// ----- TformAxes.geAxesZRadiusExit -------------------------------------------
procedure TformAxes.geAxesZRadiusExit(Sender: TObject);
begin
formMain.axes.ZRadius := geAxesZRadius.Value;
end;
// ----- TformAxes.pnlXAxesColourClick -----------------------------------------
procedure TformAxes.pnlXAxesColourClick(Sender: TObject);
begin
with ColourDialog do
begin
Color := pnlXAxesColour.Color;
if Execute then
begin
pnlXAxesColour.Color := Color;
formMain.axes.XAxisColour := Color;
end;
end;
end;
// ----- TformAxes.pnlYAxesColourClick -----------------------------------------
procedure TformAxes.pnlYAxesColourClick(Sender: TObject);
begin
with ColourDialog do
begin
Color := pnlYAxesColour.Color;
if Execute then
begin
pnlYAxesColour.Color := Color;
formMain.axes.YAxisColour := Color;
end;
end;
end;
// ----- TformAxes.pnlZAxesColourClick -----------------------------------------
procedure TformAxes.pnlZAxesColourClick(Sender: TObject);
begin
with ColourDialog do
begin
Color := pnlZAxesColour.Color;
if Execute then
begin
pnlZAxesColour.Color := Color;
formMain.axes.ZAxisColour := Color;
end;
end;
end;
// ----- TformAxes.pnlXLabelColourClick ----------------------------------------
procedure TformAxes.pnlXLabelColourClick(Sender: TObject);
begin
with ColourDialog do
begin
Color := pnlXLabelColour.Color;
if Execute then
begin
pnlXLabelColour.Color := Color;
formMain.axes.XLabelColour := Color;
end;
end;
end;
// ----- TformAxes.pnlYLabelColourClick ----------------------------------------
procedure TformAxes.pnlYLabelColourClick(Sender: TObject);
begin
with ColourDialog do
begin
Color := pnlYLabelColour.Color;
if Execute then
begin
pnlYLabelColour.Color := Color;
formMain.axes.YLabelColour := Color;
end;
end;
end;
// ----- TformAxes.pnlZLabelColourClick ----------------------------------------
procedure TformAxes.pnlZLabelColourClick(Sender: TObject);
begin
with ColourDialog do
begin
Color := pnlZLabelColour.Color;
if Execute then
begin
pnlZLabelColour.Color := Color;
formMain.axes.ZLabelColour := Color;
end;
end;
end;
// =============================================================================
end.
|
unit Magento.Factory;
interface
uses
Magento.Interfaces;
type
TMagentoFactory = class (TInterfacedObject, iMagentoFactory)
private
public
constructor Create;
destructor Destroy; override;
class function New : iMagentoFactory;
function EntidadeProduto : iMagentoEntidadeProduto;
function ExtensionAttributes(Parent : iMagentoEntidadeProduto) : iMagentoExtensionAttributes;
function Category_Links(Parent : iMagentoExtensionAttributes) : iMagentoCategory_Links;
function Stock_Item(Parent : iMagentoExtensionAttributes) : iMagentoStock_Item;
function Custom_attributes(Parent : iMagentoEntidadeProduto) : iMagnetoCustom_attributes;
function MediaGalleryEntries(Parent : iMagentoEntidadeProduto) : iMagentoMediaGalleryEntries;
function MediaGalleryContent(Parent : iMagentoMediaGalleryEntries) : iMagentoMediaGaleryContent;
function MagentoHTTP : iMagentoHTTP;
function MagentoAttibuteSets : iMagentoAttributeSets;
function MagentoCategories : iMagentoCategories;
function MagentoPedido : iMagentoPedido;
end;
implementation
uses
Magento.ExtensionAttributes, Magento.Category_Links, Magento.Stock_Item,
Magento.Custom_Attributes, Magento.Entidade.Produto, Magento.GalleryContent,
Magento.GalleryTypes, Magento.MediaGalleryEntries, MagentoHTTP,
Magento.AttributeSets, Magento.Categories, Magento.Pedido;
{ TMagentoFactory }
function TMagentoFactory.Category_Links(Parent : iMagentoExtensionAttributes): iMagentoCategory_Links;
begin
Result := TMagentoCategory_Links.New(Parent);
end;
constructor TMagentoFactory.Create;
begin
end;
function TMagentoFactory.Custom_attributes(Parent : iMagentoEntidadeProduto) : iMagnetoCustom_attributes;
begin
Result := TMagnetoCustom_attributes.New(Parent);
end;
destructor TMagentoFactory.Destroy;
begin
inherited;
end;
function TMagentoFactory.EntidadeProduto: iMagentoEntidadeProduto;
begin
Result := TMagentoEntidadeProduto.New;
end;
function TMagentoFactory.ExtensionAttributes(Parent : iMagentoEntidadeProduto): iMagentoExtensionAttributes;
begin
Result := TMagentoExtensionAttributes.New(Parent);
end;
function TMagentoFactory.MagentoAttibuteSets: iMagentoAttributeSets;
begin
Result := TMagentoAttributeSets.New;
end;
function TMagentoFactory.MagentoCategories: iMagentoCategories;
begin
Result := TMagentoCategories.New;
end;
function TMagentoFactory.MagentoHTTP: iMagentoHTTP;
begin
Result := TMagentoHTTP.New;
end;
function TMagentoFactory.MagentoPedido: iMagentoPedido;
begin
Result := TMagentoPedido.New;
end;
function TMagentoFactory.MediaGalleryContent(
Parent: iMagentoMediaGalleryEntries): iMagentoMediaGaleryContent;
begin
Result := TMagentoMediaGaleryContent.New(Parent);
end;
function TMagentoFactory.MediaGalleryEntries(Parent : iMagentoEntidadeProduto) : iMagentoMediaGalleryEntries;
begin
Result := TMagentoMediaGalleryEntries.New(Parent);
end;
class function TMagentoFactory.New: iMagentoFactory;
begin
Result := self.Create;
end;
function TMagentoFactory.Stock_Item(Parent : iMagentoExtensionAttributes) : iMagentoStock_Item;
begin
Result := TMagentoStock_Item.New(Parent);
end;
end.
|
unit uFileFunctions;
interface
uses SysUtils, Windows, Classes, Consts;
type
EInvalidDest = class(EStreamError);
EFCantMove = class(EStreamError);
procedure CopyFile(const FileName, DestName: TFileName; IsNewFile : Boolean);
procedure MoveFile(const FileName, DestName: string);
function GetFileSize(const FileName: string): LongInt;
function FileDateTime(const FileName: string): TDateTime;
function HasAttr(const FileName: string; Attr: Word): Boolean;
function ExecuteFile(const FileName, Params, DefaultDir: string;
ShowCmd: Integer): THandle;
function WaitExecute(sEXE: String) : boolean;
procedure SelfDelete(sEXE:String);
procedure SaveTextFile(sFile, Text:String);
function ReadTextFile(sFile:String):String;
implementation
uses Forms, ShellAPI;
const
SInvalidDest = 'Destination %s does not exist';
SFCantMove = 'Cannot move file %s';
function ReadTextFile(sFile:String):String;
var
F: TextFile;
L: String;
T :TStringList;
begin
Try
T := TStringList.Create;
AssignFile(F, sFile);
Reset(F);
While not Eof(F) do
begin
ReadLn(F, L);
T.Add(L);
end;
Result := Trim(T.Text);
Finally
CloseFile(F);
FreeAndNil(T);
end;
end;
procedure SaveTextFile(sFile, Text:String);
var
f: TextFile;
BatchFile : TStringList;
begin
//FileCreate(sFile);
BatchFile := nil;
Try
BatchFile := TStringList.Create;
BatchFile.Add(Text);
BatchFile.SaveToFile(sFile);
Finally
BatchFile.Free;
end;
{ try
AssignFile(f, sFile);
Append(f);
Writeln(f, Text);
Finally
CloseFile(f);
end;
}
end;
procedure SelfDelete(sEXE:String);
var
BatchFile : TStringList;
BatchName : String;
begin
// create a batchfile to remove the calling App
BatchFile := nil;
Try
BatchName := ChangeFileExt(sEXE, '.bat');
FileSetAttr(sEXE,0); // remove all attributes
BatchFile := TStringList.Create;
BatchFile.Add(':label1');
BatchFile.Add('del "' + sEXE+ '"');
BatchFile.Add('if exist "' + sEXE + '" goto label1');
BatchFile.Add('del ' + sEXE);
BatchFile.Add('del "' + BatchName + '"');
BatchFile.SaveToFile(BatchName);
WinExec(PChar(BatchName), SW_HIDE);
Finally
BatchFile.Free;
end;
end;
function WaitExecute(sEXE: String) : boolean;
var
aTSI : TStartupInfo;
aTPI : TProcessInformation;
iRet : Integer;
cRet : cardinal;
b : boolean;
begin
result := false;
FillChar(aTSI, SizeOf(aTSI), #0);
FillChar(aTPI, SizeOf(aTPI), #0);
aTSI.CB := SizeOf(aTSI);
if not CreateProcess(nil, PChar(sEXE), nil, nil, False,
NORMAL_PRIORITY_CLASS,
nil, nil, aTSI, aTPI) then RaiseLastWin32Error;
repeat
iRet := MsgWaitForMultipleObjects(1, aTPI.hProcess, False, INFINITE, (QS_ALLINPUT));
if iRet <> (WAIT_OBJECT_0) then
Application.ProcessMessages;
until
iRet = (WAIT_OBJECT_0);
b := getExitCodeProcess(aTPI.hProcess,cRet);
if cRet = 0 then
result := true;
CloseHandle(aTPI.hProcess);
end;
procedure CopyFile(const FileName, DestName: TFileName; IsNewFile : Boolean);
var
CopyBuffer: Pointer; { buffer for copying }
BytesCopied: Longint;
Source, Dest: Integer; { handles }
Destination: TFileName; { holder for expanded destination name }
const
ChunkSize: Longint = 8192; { copy in 8K chunks }
begin
Destination := ExpandFileName(DestName); { expand the destination path }
if HasAttr(Destination, faDirectory) and not IsNewFile then { if destination is a directory... }
Destination := Destination + '\' + ExtractFileName(FileName); { ...clone file name }
GetMem(CopyBuffer, ChunkSize); { allocate the buffer }
try
Source := FileOpen(FileName, fmShareDenyWrite); { open source file }
if Source < 0 then raise EFOpenError.CreateFmt(SFOpenError, [FileName]);
try
Dest := FileCreate(Destination); { create output file; overwrite existing }
if Dest < 0 then raise EFCreateError.CreateFmt(SFCreateError, [Destination]);
try
repeat
BytesCopied := FileRead(Source, CopyBuffer^, ChunkSize); { read chunk }
if BytesCopied > 0 then { if we read anything... }
FileWrite(Dest, CopyBuffer^, BytesCopied); { ...write chunk }
until BytesCopied < ChunkSize; { until we run out of chunks }
finally
FileClose(Dest); { close the destination file }
end;
finally
FileClose(Source); { close the source file }
end;
finally
FreeMem(CopyBuffer, ChunkSize); { free the buffer }
end;
end;
{ MoveFile procedure }
{
Moves the file passed in FileName to the directory specified in DestDir.
Tries to just rename the file. If that fails, try to copy the file and
delete the original.
Raises an exception if the source file is read-only, and therefore cannot
be deleted/moved.
}
procedure MoveFile(const FileName, DestName: string);
var
Destination: string;
begin
Destination := ExpandFileName(DestName); { expand the destination path }
if not RenameFile(FileName, Destination) then { try just renaming }
begin
if HasAttr(FileName, faReadOnly) then { if it's read-only... }
raise EFCantMove.Create(Format(SFCantMove, [FileName])); { we wouldn't be able to delete it }
CopyFile(FileName, Destination, False); { copy it over to destination...}
// DeleteFile(FileName); { ...and delete the original }
end;
end;
{ GetFileSize function }
{
Returns the size of the named file without opening the file. If the file
doesn't exist, returns -1.
}
function GetFileSize(const FileName: string): LongInt;
var
SearchRec: TSearchRec;
begin
if FindFirst(ExpandFileName(FileName), faAnyFile, SearchRec) = 0 then
Result := SearchRec.Size
else Result := -1;
end;
function FileDateTime(const FileName: string): System.TDateTime;
begin
Result := FileDateToDateTime(FileAge(FileName));
end;
function HasAttr(const FileName: string; Attr: Word): Boolean;
begin
Result := (FileGetAttr(FileName) and Attr) = Attr;
end;
function ExecuteFile(const FileName, Params, DefaultDir: string;
ShowCmd: Integer): THandle;
var
zFileName, zParams, zDir: array[0..79] of Char;
begin
Result := ShellExecute(Application.MainForm.Handle, nil,
StrPCopy(zFileName, FileName), StrPCopy(zParams, Params),
StrPCopy(zDir, DefaultDir), ShowCmd);
end;
end.
|
unit UHistorico;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.StdCtrls,
Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Mask, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids,
UHistoricoVO, UHistoricoCOntroller, Generics.Collections;
type
TFTelaCadastroHistorico = class(TFTelaCadastro)
LabeledEditDescricao: TLabeledEdit;
Label1: TLabel;
ComboBoxTipo: TComboBox;
GroupBox2: TGroupBox;
RadioButtonDescricao: TRadioButton;
function MontaFiltro: string;
procedure FormCreate(Sender: TObject);
function DoSalvar: boolean; override;
function DoExcluir: boolean; override;
procedure DoConsultar; override;
procedure CarregaObjetoSelecionado; override;
procedure BitBtnNovoClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
procedure GridParaEdits; override;
function EditsToObject(Historico: THistoricoVo): THistoricoVo;
end;
var
FTelaCadastroHistorico: TFTelaCadastroHistorico;
ControllerHistorico : THistoricoController;
implementation
{$R *.dfm}
{ TFTelaCadastroHistorico }
procedure TFTelaCadastroHistorico.BitBtnNovoClick(Sender: TObject);
begin
inherited;
LabeledEditDescricao.SetFocus;
end;
procedure TFTelaCadastroHistorico.CarregaObjetoSelecionado;
begin
if not CDSGrid.IsEmpty then
begin
ObjetoRetornoVO := THistoricoVo.Create;
THistoricoVo(ObjetoRetornoVO).idHistorico := CDSGrid.FieldByName('IDHISTORICO').AsInteger;
THistoricoVo(ObjetoRetornoVO).dsHistorico :=
CDSGrid.FieldByName('DSHISTORICO').AsString;
THistoricoVo(ObjetoRetornoVO).flContaCorrente :=
CDSGrid.FieldByName('FLCONTACORRENTE').AsString;
end;
end;
procedure TFTelaCadastroHistorico.DoConsultar;
var
listaHistorico: TObjectList<THistoricoVo>;
filtro: string;
begin
filtro := MontaFiltro;
listaHistorico := ControllerHistorico.Consultar(filtro);
PopulaGrid<THistoricoVo>(listaHistorico);
end;
function TFTelaCadastroHistorico.DoExcluir: boolean;
var
Historico: THistoricoVo;
begin
try
try
Historico := THistoricoVo.Create;
Historico.idhistorico := CDSGrid.FieldByName('IDHISTORICO').AsInteger;
ControllerHistorico.Excluir(Historico);
except
on E: Exception do
begin
ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 +
E.Message);
Result := false;
end;
end;
finally
end;
end;
function TFTelaCadastroHistorico.DoSalvar: boolean;
var
Historico: THistoricoVo;
begin
Historico:=EditsToObject(THistoricoVO.Create);
try
try
Historico.ValidarCamposObrigatorios();
if (StatusTela = stInserindo) then
begin
ControllerHistorico.Inserir(Historico);
result := true;
end
else if (StatusTela = stEditando) then
begin
Historico := ControllerHistorico.ConsultarPorId(CDSGrid.FieldByName('IDHISTORICO')
.AsInteger);
Historico := EditsToObject(Historico);
ControllerHistorico.Alterar(Historico);
Result := true;
end
except
on E: Exception do
begin
ShowMessage(E.Message);
Result := false;
end;
end;
finally
end;
end;
function TFTelaCadastroHistorico.EditsToObject(
Historico: THistoricoVo): THistoricoVo;
begin
Historico.dsHistorico := LabeledEditDescricao.Text;
Historico.flContaCorrente := IntToStr(comboboxTipo.ItemIndex+1);
Result := Historico;
end;
procedure TFTelaCadastroHistorico.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
FreeAndNil(ControllerHistorico);
end;
procedure TFTelaCadastroHistorico.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := THistoricoVo;
RadioButtonDescricao.Checked := true;
ControllerHistorico := THistoricoController.Create;
inherited;
end;
procedure TFTelaCadastroHistorico.GridParaEdits;
var
Historico: THistoricoVo;
begin
inherited;
if not CDSGrid.IsEmpty then
Historico := ControllerHistorico.ConsultarPorId(CDSGrid.FieldByName('IDHISTORICO')
.AsInteger);
if Assigned(Historico) then
begin
LabeledEditDescricao.text := Historico.DsHistorico;
ComboboxTipo.ItemIndex:= strtoint(HISTORICO.FlContaCorrente)-1;
end;
end;
function TFTelaCadastroHistorico.MontaFiltro: string;
begin
Result := '';
if (RadioButtonDescricao.Checked = true) then
begin
if (editBusca.Text <> '') then
Result := '( UPPER(DSHISTORICO) LIKE ' +
QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) ';
end;
end;
end.
|
unit ibSHTableObjectFrm;
interface
uses
SHDesignIntf, ibSHDesignIntf, ibSHComponentFrm,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ToolWin, ComCtrls, ImgList, ActnList, StrUtils,
SynEdit, pSHSynEdit, AppEvnts, Menus, VirtualTrees, TypInfo;
type
TibSHTableForm = class(TibBTComponentForm, IibSHTableForm, IibSHDDLForm)
private
{ Private declarations }
FDBObjectIntf: IibSHDBObject;
FDBTableIntf: IibSHTable;
FDBViewIntf: IibSHView;
FDBComponent: TSHComponent;
FDBFieldIntf: IibSHField;
FDBConstraintIntf: IibSHConstraint;
FDBIndexIntf: IibSHIndex;
FDBTriggerIntf: IibSHTrigger;
FDDLForm: TForm;
FDDLFormIntf: IibSHDDLForm;
FDBState: TSHDBComponentState;
FMsgPanel: TPanel;
FMsgPanelHeight: Integer;
FMsgSplitter: TSplitter;
FTree: TVirtualStringTree;
FTMPNameList: TStrings;
procedure SetTree(Value: TVirtualStringTree);
protected
procedure RefreshData; virtual;
procedure DoOnGetData; virtual;
procedure ClearDBComponent; virtual;
procedure AssignDBComponent; virtual;
procedure AfterCommit(Sender: TObject); virtual;
procedure ShowDBComponent(AState: TSHDBComponentState); virtual;
function GetCanDestroy: Boolean; override;
{ ISHRunCommands }
function GetCanRun: Boolean; override;
function GetCanPause: Boolean; override;
function GetCanCreate: Boolean; override;
function GetCanAlter: Boolean; override;
function GetCanDrop: Boolean; override;
function GetCanRecreate: Boolean; override;
function GetCanCommit: Boolean; override;
function GetCanRollback: Boolean; override;
function GetCanRefresh: Boolean; override;
procedure Run; override;
procedure Pause; override;
procedure ICreate; override;
procedure Alter; override;
procedure Drop; override;
procedure Recreate; override;
procedure Commit; override;
procedure Rollback; override;
procedure Refresh; override;
{ IibSHTableForm }
function GetDBComponent: TSHComponent;
{ IibSHDDLForm }
function GetDDLText: TStrings;
procedure SetDDLText(Value: TStrings);
function GetOnAfterRun: TNotifyEvent;
procedure SetOnAfterRun(Value: TNotifyEvent);
function GetOnAfterCommit: TNotifyEvent;
procedure SetOnAfterCommit(Value: TNotifyEvent);
function GetOnAfterRollback: TNotifyEvent;
procedure SetOnAfterRollback(Value: TNotifyEvent);
procedure PrepareControls;
procedure ShowDDLText;
{ Tree }
procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure TreePaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
procedure TreeIncrementalSearch(Sender: TBaseVirtualTree;
Node: PVirtualNode; const SearchText: WideString; var Result: Integer);
procedure TreeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TreeDblClick(Sender: TObject);
procedure TreeGetPopupMenu(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; const P: TPoint;
var AskParent: Boolean; var PopupMenu: TPopupMenu);
procedure TreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode;
Column: TColumnIndex; var Result: Integer);
procedure TreeFocusChanging(Sender: TBaseVirtualTree;
OldNode, NewNode: PVirtualNode; OldColumn, NewColumn: TColumnIndex;
var Allowed: Boolean);
procedure TreeFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
procedure CreateDDLForm;
property DBObject: IibSHDBObject read FDBObjectIntf;
property DBTable: IibSHTable read FDBTableIntf;
property DBView: IibSHView read FDBViewIntf;
property DBField: IibSHField read FDBFieldIntf;
property DBConstraint: IibSHConstraint read FDBConstraintIntf;
property DBIndex: IibSHIndex read FDBIndexIntf;
property DBTrigger: IibSHTrigger read FDBTriggerIntf;
property DDLForm: IibSHDDLForm read FDDLFormIntf;
property DBComponent: TSHComponent read FDBComponent;
property DBState: TSHDBComponentState read FDBState write FDBState;
property MsgPanel: TPanel read FMsgPanel write FMsgPanel;
property MsgPanelHeight: Integer read FMsgPanelHeight write FMsgPanelHeight;
property MsgSplitter: TSplitter read FMsgSplitter write FMsgSplitter;
property Tree: TVirtualStringTree read FTree write SetTree;
end;
TibSHTableFormAction_ = class(TSHAction)
public
constructor Create(AOwner: TComponent); override;
function SupportComponent(const AClassIID: TGUID): Boolean; override;
procedure EventExecute(Sender: TObject); override;
procedure EventHint(var HintStr: String; var CanShow: Boolean); override;
procedure EventUpdate(Sender: TObject); override;
end;
TibSHTableFormAction_Run = class(TibSHTableFormAction_)
end;
TibSHTableFormAction_Pause = class(TibSHTableFormAction_)
end;
TibSHTableFormAction_Commit = class(TibSHTableFormAction_)
end;
TibSHTableFormAction_Rollback = class(TibSHTableFormAction_)
end;
TibSHTableFormAction_Create = class(TibSHTableFormAction_)
end;
TibSHTableFormAction_Alter = class(TibSHTableFormAction_)
end;
TibSHTableFormAction_Recreate = class(TibSHTableFormAction_)
end;
TibSHTableFormAction_Drop = class(TibSHTableFormAction_)
end;
TibSHTableFormAction_Refresh = class(TibSHTableFormAction_)
end;
type
PTreeRec = ^TTreeRec;
TTreeRec = record
Number: string;
ImageIndex: Integer;
Name: string;
// Field
Constraints: string;
DataType: string;
Domain: string;
DefaultExpression: string;
NullType: string;
Charset: string;
Collate: string;
ArrayDim: string;
DomainCheck: string;
ComputedSource: string;
// Constraint
ConstraintType: string;
Fields: string;
RefTable: string;
RefFields: string;
OnDelete: string;
OnUpdate: string;
IndexName: string;
IndexSorting: string;
// Index
{Fields: string;} // redeclared
Status: string;
IndexType: string;
Sorting: string;
Statistics: string;
Expression: string;
// Trigger
{Status: string;} // redeclared
TypePrefix: string;
TypeSuffix: string;
Position: string;
Description: string;
Source: string;
OverloadDefault: Boolean;
OverloadNullType: Boolean;
OverloadCollate: Boolean;
end;
procedure Register;
implementation
uses
ibSHConsts, ibSHSQLs, ibSHValues, ibSHStrUtil;
procedure Register;
begin
SHRegisterImage(TibSHTableFormAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterImage(TibSHTableFormAction_Pause.ClassName, 'Button_Stop.bmp');
SHRegisterImage(TibSHTableFormAction_Commit.ClassName, 'Button_TrCommit.bmp');
SHRegisterImage(TibSHTableFormAction_Rollback.ClassName, 'Button_TrRollback.bmp');
SHRegisterImage(TibSHTableFormAction_Create.ClassName, 'Button_Create.bmp');
SHRegisterImage(TibSHTableFormAction_Alter.ClassName, 'Button_Alter.bmp');
SHRegisterImage(TibSHTableFormAction_Recreate.ClassName, 'Button_Recreate.bmp');
SHRegisterImage(TibSHTableFormAction_Drop.ClassName, 'Button_Drop.bmp');
SHRegisterImage(TibSHTableFormAction_Refresh.ClassName, 'Button_Refresh.bmp');
SHRegisterActions([
TibSHTableFormAction_Run,
TibSHTableFormAction_Pause,
TibSHTableFormAction_Commit,
TibSHTableFormAction_Rollback,
TibSHTableFormAction_Create,
TibSHTableFormAction_Alter,
TibSHTableFormAction_Recreate,
TibSHTableFormAction_Drop,
TibSHTableFormAction_Refresh]);
end;
{ TibSHTableForm }
constructor TibSHTableForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
begin
inherited Create(AOwner, AParent, AComponent, ACallString);
Supports(Component, IibSHDBObject, FDBObjectIntf);
Supports(Component, IibSHTable, FDBTableIntf);
Supports(Component, IibSHView, FDBViewIntf);
FTMPNameList := TStringList.Create;
end;
destructor TibSHTableForm.Destroy;
begin
FDDLFormIntf := nil;
FDDLForm.Free;
FDBFieldIntf := nil;
FDBConstraintIntf := nil;
FDBIndexIntf := nil;
FDBTriggerIntf := nil;
FDBComponent.Free;
FTMPNameList.Free;
inherited Destroy;
end;
procedure TibSHTableForm.CreateDDLForm;
var
vClassIID: TGUID;
vComponentClass: TSHComponentClass;
vComponentFormClass: TSHComponentFormClass;
begin
vClassIID := IUnknown;
if Assigned(DBTable) then
begin
if AnsiSameText(CallString, SCallFields) then vClassIID := IibSHField else
if AnsiSameText(CallString, SCallConstraints) then vClassIID := IibSHConstraint else
if AnsiSameText(CallString, SCallIndices) then vClassIID := IibSHIndex else
if AnsiSameText(CallString, SCallTriggers) then vClassIID := IibSHTrigger;
end;
if Assigned(DBView) then
begin
if AnsiSameText(CallString, SCallTriggers) then vClassIID := IibSHTrigger;
end;
if not IsEqualGUID(vClassIID, IUnknown) then
begin
vComponentClass := Designer.GetComponent(vClassIID);
if Assigned(vComponentClass) then
begin
FDBComponent := vComponentClass.Create(nil);
Designer.Components.Remove(FDBComponent);
end;
Supports(DBComponent, IibSHField, FDBFieldIntf);
Supports(DBComponent, IibSHConstraint, FDBConstraintIntf);
Supports(DBComponent, IibSHIndex, FDBIndexIntf);
Supports(DBComponent, IibSHTrigger, FDBTriggerIntf);
if Assigned(DBComponent) then
begin
(DBComponent as IibSHDBObject).OwnerIID := DBObject.OwnerIID;
(DBComponent as IibSHDBObject).State := csSource;
(DBComponent as IibSHDBObject).Embedded := True;
vComponentFormClass := Designer.GetComponentForm(VClassIID, SCallSourceDDL);
if Assigned(vComponentFormClass) then
FDDLForm := vComponentFormClass.Create(MsgPanel, MsgPanel, DBComponent, SCallSourceDDL);
if Assigned(FDDLForm) then
begin
Supports(FDDLForm, IibSHDDLForm, FDDLFormIntf);
DDLForm.OnAfterCommit := AfterCommit;
FDDLForm.Show;
Editor := GetObjectProp(FDDLForm, 'Editor') as TpSHSynEdit;
end;
end;
end else
begin
MsgPanel.Visible := False;
MsgSplitter.Visible := False;
end;
RefreshData;
if Assigned(DBField) then MsgPanel.Height := 80;
if Assigned(DBConstraint) then MsgPanel.Height := 100;
if Assigned(DBIndex) then MsgPanel.Height := 100;
if Assigned(DBTrigger) then MsgPanel.Height := MsgPanel.Parent.ClientHeight div 2;
end;
procedure TibSHTableForm.RefreshData;
begin
try
Screen.Cursor := crHourGlass;
DoOnGetData;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TibSHTableForm.DoOnGetData;
begin
// override
end;
procedure TibSHTableForm.ClearDBComponent;
begin
(DBComponent as ISHDBComponent).Caption := EmptyStr;
(DBComponent as ISHDBComponent).ObjectName := EmptyStr;
(DBComponent as ISHDBComponent).SourceDDL.Clear;
(DBComponent as ISHDBComponent).AlterDDL.Clear;
(DBComponent as ISHDBComponent).DropDDL.Clear;
(DBComponent as ISHDBComponent).RecreateDDL.Clear;
(DBComponent as IibSHDBObject).Fields.Clear;
(DBComponent as IibSHDBObject).BodyText.Clear;
if Assigned(DBField) then
begin
DBField.FieldTypeID := 0;
DBField.SubTypeID := 0;
DBField.CharsetID := 0;
DBField.CollateID := 0;
DBField.ArrayDimID := 0;
DBField.DataType := EmptyStr;
DBField.DataTypeExt := EmptyStr;
DBField.DataTypeField := EmptyStr;
DBField.DataTypeFieldExt := EmptyStr;
DBField.Length := 0;
DBField.Precision := 0;
DBField.Scale := 0;
DBField.NotNull := False;
DBField.NullType := EmptyStr;
DBField.SubType := EmptyStr;
DBField.SegmentSize := 0;
DBField.Charset := EmptyStr;
DBField.Collate := EmptyStr;
DBField.DefaultExpression.Clear;
DBField.CheckConstraint.Clear;
DBField.ArrayDim := EmptyStr;
// For Fields
DBField.Domain := EmptyStr;
DBField.TableName := EmptyStr;
DBField.FieldDefault.Clear;
DBField.FieldNotNull := False;
DBField.FieldNullType := EmptyStr;
DBField.FieldCollateID := 0;
DBField.FieldCollate := EmptyStr;
DBField.ComputedSource.Clear;
// Other (for ibSHDDLGenerator)
DBField.UseCustomValues := False;
DBField.NameWasChanged := False;
DBField.DataTypeWasChanged := False;
DBField.DefaultWasChanged := False;
DBField.CheckWasChanged := False;
DBField.NullTypeWasChanged := False;
DBField.CollateWasChanged := False;
// NEW
DBField.Caption := 'NEW_FIELD';
DBField.ObjectName := DBField.Caption;
DBField.TableName := DBTable.Caption;
DBField.DataType := Format('%s', [DataTypes[0, 1]]);
DBField.DataTypeExt := DBField.DataType;
DBField.DataTypeField := DBField.DataType;
DBField.DataTypeFieldExt := DBField.DataType;
end;
if Assigned(DBConstraint) then
begin
DBConstraint.ConstraintType := EmptyStr;
DBConstraint.TableName := EmptyStr;
DBConstraint.ReferenceTable := EmptyStr;
DBConstraint.ReferenceFields.Clear;
DBConstraint.OnUpdateRule := EmptyStr;
DBConstraint.OnDeleteRule := EmptyStr;
DBConstraint.IndexName := EmptyStr;
DBConstraint.IndexSorting := EmptyStr;
DBConstraint.CheckSource.Clear;
// NEW
DBConstraint.Caption := 'NEW_CONSTRAINT';
DBConstraint.ObjectName := DBConstraint.Caption;
DBConstraint.TableName := DBTable.Caption;
end;
if Assigned(DBIndex) then
begin
DBIndex.IndexTypeID := 0;
DBIndex.SortingID := 0;
DBIndex.StatusID := 0;
DBIndex.IndexType := EmptyStr;
DBIndex.Sorting := EmptyStr;
DBIndex.TableName := EmptyStr;
DBIndex.Expression.Clear;
DBIndex.Status := EmptyStr;
DBIndex.Statistics := EmptyStr;
// NEW
DBIndex.Caption := 'NEW_INDEX';
DBIndex.ObjectName := DBIndex.Caption;
DBIndex.TableName := DBTable.Caption;
end;
if Assigned(DBTrigger) then
begin
DBTrigger.TableName := EmptyStr;
DBTrigger.Status := EmptyStr;
DBTrigger.TypePrefix := EmptyStr;
DBTrigger.TypeSuffix := EmptyStr;
DBTrigger.Position := 0;
// NEW
DBTrigger.Caption := 'NEW_TRIGGER';
DBTrigger.ObjectName := DBTrigger.Caption;
if Assigned(DBTable) then DBTrigger.TableName := DBTable.Caption;
if Assigned(DBView) then DBTrigger.TableName := DBView.Caption;
end;
end;
procedure TibSHTableForm.AssignDBComponent;
var
I: Integer;
begin
I := Tree.FocusedNode.Index;
if Assigned(DBField) then
begin
DBField.Caption := DBTable.GetField(I).Caption;
DBField.ObjectName := DBTable.GetField(I).ObjectName;
DBField.SourceDDL.Assign(DBTable.GetField(I).SourceDDL);
DBField.AlterDDL.Assign(DBTable.GetField(I).AlterDDL);
DBField.DropDDL.Assign(DBTable.GetField(I).DropDDL);
DBField.RecreateDDL.Assign(DBTable.GetField(I).RecreateDDL);
DBField.FieldTypeID := DBTable.GetField(I).FieldTypeID;
DBField.SubTypeID := DBTable.GetField(I).SubTypeID;
DBField.CharsetID := DBTable.GetField(I).CharsetID;
DBField.CollateID := DBTable.GetField(I).CollateID;
DBField.ArrayDimID := DBTable.GetField(I).ArrayDimID;
DBField.DataType := DBTable.GetField(I).DataType;
DBField.DataTypeExt := DBTable.GetField(I).DataTypeExt;
DBField.DataTypeField := DBTable.GetField(I).DataTypeField;
DBField.DataTypeFieldExt := DBTable.GetField(I).DataTypeFieldExt;
DBField.Length := DBTable.GetField(I).Length;
DBField.Precision := DBTable.GetField(I).Precision;
DBField.Scale := DBTable.GetField(I).Scale;
DBField.NotNull := DBTable.GetField(I).NotNull;
DBField.NullType := DBTable.GetField(I).NullType;
DBField.SubType := DBTable.GetField(I).SubType;
DBField.SegmentSize := DBTable.GetField(I).SegmentSize;
DBField.Charset := DBTable.GetField(I).Charset;
DBField.Collate := DBTable.GetField(I).Collate;
DBField.DefaultExpression.Assign(DBTable.GetField(I).DefaultExpression);
DBField.CheckConstraint.Assign(DBTable.GetField(I).CheckConstraint);
DBField.ArrayDim := DBTable.GetField(I).ArrayDim;
// For Fields
DBField.Domain := DBTable.GetField(I).Domain;
DBField.TableName := DBTable.GetField(I).TableName;
DBField.FieldDefault.Assign(DBTable.GetField(I).FieldDefault);
DBField.FieldNotNull := DBTable.GetField(I).FieldNotNull;
DBField.FieldNullType := DBTable.GetField(I).FieldNullType;
DBField.FieldCollateID := DBTable.GetField(I).FieldCollateID;
DBField.FieldCollate := DBTable.GetField(I).FieldCollate;
DBField.ComputedSource.Assign(DBTable.GetField(I).ComputedSource);
// Other (for ibSHDDLGenerator)
DBField.UseCustomValues := DBTable.GetField(I).UseCustomValues;
DBField.NameWasChanged := DBTable.GetField(I).NameWasChanged;
DBField.DataTypeWasChanged := DBTable.GetField(I).DataTypeWasChanged;
DBField.DefaultWasChanged := DBTable.GetField(I).DefaultWasChanged;
DBField.CheckWasChanged := DBTable.GetField(I).CheckWasChanged;
DBField.NullTypeWasChanged := DBTable.GetField(I).NullTypeWasChanged;
DBField.CollateWasChanged := DBTable.GetField(I).CollateWasChanged;
end;
if Assigned(DBConstraint) then
begin
DBConstraint.Caption := DBTable.GetConstraint(I).Caption;
DBConstraint.ObjectName := DBTable.GetConstraint(I).ObjectName;
DBConstraint.SourceDDL.Assign(DBTable.GetConstraint(I).SourceDDL);
DBConstraint.AlterDDL.Assign(DBTable.GetConstraint(I).AlterDDL);
DBConstraint.DropDDL.Assign(DBTable.GetConstraint(I).DropDDL);
DBConstraint.RecreateDDL.Assign(DBTable.GetConstraint(I).RecreateDDL);
DBConstraint.ConstraintType := DBTable.GetConstraint(I).ConstraintType;
DBConstraint.TableName := DBTable.GetConstraint(I).TableName;
DBConstraint.ReferenceTable := DBTable.GetConstraint(I).ReferenceTable;
DBConstraint.ReferenceFields.Assign(DBTable.GetConstraint(I).ReferenceFields);
DBConstraint.OnUpdateRule := DBTable.GetConstraint(I).OnUpdateRule;
DBConstraint.OnDeleteRule := DBTable.GetConstraint(I).OnDeleteRule;
DBConstraint.IndexName := DBTable.GetConstraint(I).IndexName;
DBConstraint.IndexSorting := DBTable.GetConstraint(I).IndexSorting;
DBConstraint.CheckSource.Assign(DBTable.GetConstraint(I).CheckSource);
DBConstraint.Fields.Assign(DBTable.GetConstraint(I).Fields);
end;
if Assigned(DBIndex) then
begin
DBIndex.Caption := DBTable.GetIndex(I).Caption;
DBIndex.ObjectName := DBTable.GetIndex(I).ObjectName;
DBIndex.SourceDDL.Assign(DBTable.GetIndex(I).SourceDDL);
DBIndex.AlterDDL.Assign(DBTable.GetIndex(I).AlterDDL);
DBIndex.DropDDL.Assign(DBTable.GetIndex(I).DropDDL);
DBIndex.RecreateDDL.Assign(DBTable.GetIndex(I).RecreateDDL);
DBIndex.IndexTypeID := DBTable.GetIndex(I).IndexTypeID;
DBIndex.SortingID := DBTable.GetIndex(I).SortingID;
DBIndex.StatusID := DBTable.GetIndex(I).StatusID;
DBIndex.IndexType := DBTable.GetIndex(I).IndexType;
DBIndex.Sorting := DBTable.GetIndex(I).Sorting;
DBIndex.TableName := DBTable.GetIndex(I).TableName;
DBIndex.Expression.Assign(DBTable.GetIndex(I).Expression);
DBIndex.Status := DBTable.GetIndex(I).Status;
DBIndex.Statistics := DBTable.GetIndex(I).Statistics;
DBIndex.Fields.Assign(DBTable.GetIndex(I).Fields);
end;
if Assigned(DBTrigger) then
begin
if Assigned(DBTable) then
begin
DBTrigger.Caption := DBTable.GetTrigger(I).Caption;
DBTrigger.ObjectName := DBTable.GetTrigger(I).ObjectName;
DBTrigger.SourceDDL.Assign(DBTable.GetTrigger(I).SourceDDL);
DBTrigger.AlterDDL.Assign(DBTable.GetTrigger(I).AlterDDL);
DBTrigger.DropDDL.Assign(DBTable.GetTrigger(I).DropDDL);
DBTrigger.RecreateDDL.Assign(DBTable.GetTrigger(I).RecreateDDL);
DBTrigger.TableName := DBTable.GetTrigger(I).TableName;
DBTrigger.Status := DBTable.GetTrigger(I).Status;
DBTrigger.TypePrefix := DBTable.GetTrigger(I).TypePrefix;
DBTrigger.TypeSuffix := DBTable.GetTrigger(I).TypeSuffix;
DBTrigger.Position := DBTable.GetTrigger(I).Position;
DBTrigger.BodyText.Assign(DBTable.GetTrigger(I).BodyText);
end;
if Assigned(DBView) then
begin
DBTrigger.Caption := DBView.GetTrigger(I).Caption;
DBTrigger.ObjectName := DBView.GetTrigger(I).ObjectName;
DBTrigger.SourceDDL.Assign(DBView.GetTrigger(I).SourceDDL);
DBTrigger.AlterDDL.Assign(DBView.GetTrigger(I).AlterDDL);
DBTrigger.DropDDL.Assign(DBView.GetTrigger(I).DropDDL);
DBTrigger.RecreateDDL.Assign(DBView.GetTrigger(I).RecreateDDL);
DBTrigger.TableName := DBView.GetTrigger(I).TableName;
DBTrigger.Status := DBView.GetTrigger(I).Status;
DBTrigger.TypePrefix := DBView.GetTrigger(I).TypePrefix;
DBTrigger.TypeSuffix := DBView.GetTrigger(I).TypeSuffix;
DBTrigger.Position := DBView.GetTrigger(I).Position;
DBTrigger.BodyText.Assign(DBView.GetTrigger(I).BodyText);
end;
end;
end;
procedure TibSHTableForm.AfterCommit(Sender: TObject);
var
I: Integer;
RunCommands: ISHRunCommands;
Node: PVirtualNode;
NodeData: PTreeRec;
NodeIndex: Cardinal;
begin
Pause;
// Node := nil;
// NodeData := nil;
NodeIndex := 0;
if Assigned(Tree.FocusedNode) then NodeIndex := Tree.FocusedNode.Index;
FTMPNameList.Clear;
Node := Tree.GetFirst;
while Assigned(Node) do
begin
NodeData := Tree.GetNodeData(Node);
FTMPNameList.Add(NodeData.Name);
Node := Tree.GetNextSibling(Node);
end;
(FTMPNameList as TStringList).Sort;
for I := 0 to Pred(Component.ComponentForms.Count) do
begin
RunCommands := nil;
Supports(Component.ComponentForms[I], ISHRunCommands, RunCommands);
if AnsiSameText(TSHComponentForm(Component.ComponentForms[I]).CallString, SCallSourceDDL) then
if Assigned(RunCommands) and RunCommands.CanRefresh then RunCommands.Refresh;
end;
RefreshData;
case DBState of
csCreate, csRecreate:
if Assigned(DBField) then
begin
Node := Tree.GetLast(nil);
end else
begin
Node := Tree.GetFirst;
while Assigned(Node) do
begin
NodeData := Tree.GetNodeData(Node);
if FTMPNameList.IndexOf(NodeData.Name) = -1 then Break;
Node := Tree.GetNextSibling(Node);
end;
end;
csAlter, csDrop:
begin
if DBState = csDrop then NodeIndex := Pred(NodeIndex);
Node := Tree.GetFirst;
while Assigned(Node) do
begin
if Node.Index = NodeIndex then Break;
Node := Tree.GetNextSibling(Node);
end;
end;
end;
if Assigned(Node) then
begin
Tree.FocusedNode := Node;
Tree.Selected[Tree.FocusedNode] := True;
if Tree.CanFocus then Tree.SetFocus;
end;
DDLForm.PrepareControls;
MsgPanel.Height := FMsgPanelHeight;
end;
procedure TibSHTableForm.ShowDBComponent(AState: TSHDBComponentState);
begin
DBState := AState;
case DBState of
csSource: Exit;
csCreate: ClearDBComponent;
csAlter, csDrop, csRecreate: AssignDBComponent;
end;
Tree.Enabled := False;
MsgPanelHeight := MsgPanel.Height;
if MsgPanel.Height <= (MsgPanel.Parent.ClientHeight div 2) then
MsgPanel.Height := Trunc(MsgPanel.Parent.ClientHeight * 7/9);
if Assigned(StatusBar) then StatusBar.Top := Self.Height;
(DBComponent as ISHDBComponent).State := DBState;
DDLForm.DDLText.Clear;
(DDLForm as ISHRunCommands).Refresh;
DDLForm.PrepareControls;
Editor.Modified := True;
if Editor.CanFocus then Editor.SetFocus;
// if DBState = csCreate then
// Designer.ShowModal(DBComponent , Format('DDL_WIZARD.%s', [AnsiUpperCase(DBComponent.Association)]));
end;
function TibSHTableForm.GetCanDestroy: Boolean;
begin
Result := True;
if Assigned(DDLForm) then Result := DDLForm.CanDestroy;
end;
{ ISHRunCommands }
function TibSHTableForm.GetCanRun: Boolean;
begin
Result := Assigned(DDLForm) and (DDLForm as ISHRunCommands).CanRun;
end;
function TibSHTableForm.GetCanPause: Boolean;
begin
Result := Assigned(DBComponent) and
((DBComponent as ISHDBComponent).State <> csSource);
end;
function TibSHTableForm.GetCanCreate: Boolean;
begin
Result := Assigned(DBComponent) and Assigned(DBComponent) and
((DBComponent as ISHDBComponent).State = csSource);
end;
function TibSHTableForm.GetCanAlter: Boolean;
begin
Result := Assigned(DBComponent) and Assigned(DBComponent) and Assigned(Tree.FocusedNode) and
((DBComponent as ISHDBComponent).State = csSource) and not GetCanPause;
if Assigned(DBConstraint) then Result := False;
if Assigned(DBIndex) then {override};
end;
function TibSHTableForm.GetCanDrop: Boolean;
begin
Result := GetCanAlter;
if Assigned(DBConstraint) then Result := Assigned(Tree.FocusedNode) and not GetCanPause;
end;
function TibSHTableForm.GetCanRecreate: Boolean;
begin
Result := GetCanDrop;
end;
function TibSHTableForm.GetCanCommit: Boolean;
begin
Result := Assigned(DDLForm) and (DDLForm as ISHRunCommands).CanCommit;
end;
function TibSHTableForm.GetCanRollback: Boolean;
begin
Result := Assigned(DDLForm) and (DDLForm as ISHRunCommands).CanRollback;
end;
function TibSHTableForm.GetCanRefresh: Boolean;
begin
Result := True;
if Assigned(DBComponent) then Result := (DBComponent as ISHDBComponent).State = csSource;
end;
procedure TibSHTableForm.Run;
begin
(DDLForm as ISHRunCommands).Run;
end;
procedure TibSHTableForm.Pause;
begin
Tree.Enabled := True;
(DBComponent as ISHDBComponent).State := csSource;
DDLForm.PrepareControls;
if MsgPanelHeight <> 0 then MsgPanel.Height := MsgPanelHeight;
TreeFocusChanged(Tree, Tree.FocusedNode, 0);
end;
procedure TibSHTableForm.ICreate;
begin
ShowDBComponent(csCreate);
end;
procedure TibSHTableForm.Alter;
begin
ShowDBComponent(csAlter);
end;
procedure TibSHTableForm.Drop;
begin
ShowDBComponent(csDrop);
end;
procedure TibSHTableForm.Recreate;
begin
ShowDBComponent(csRecreate);
end;
procedure TibSHTableForm.Commit;
begin
if Assigned(DDLForm) then (DDLForm as ISHRunCommands).Commit;
end;
procedure TibSHTableForm.Rollback;
begin
if Assigned(DDLForm) then (DDLForm as ISHRunCommands).Rollback;
end;
procedure TibSHTableForm.Refresh;
begin
if Assigned(DBObject) then
begin
DBObject.Refresh;
RefreshData;
end;
end;
function TibSHTableForm.GetDBComponent: TSHComponent;
begin
Result := FDBComponent;
end;
function TibSHTableForm.GetDDLText: TStrings;
begin
Result := nil;
if Assigned(DDLForm) then Result := DDLForm.DDLText;
end;
procedure TibSHTableForm.SetDDLText(Value: TStrings);
begin
if Assigned(DDLForm) then DDLForm.DDLText.Assign(Value);
end;
function TibSHTableForm.GetOnAfterRun: TNotifyEvent;
begin
end;
procedure TibSHTableForm.SetOnAfterRun(Value: TNotifyEvent);
begin
end;
function TibSHTableForm.GetOnAfterCommit: TNotifyEvent;
begin
end;
procedure TibSHTableForm.SetOnAfterCommit(Value: TNotifyEvent);
begin
end;
function TibSHTableForm.GetOnAfterRollback: TNotifyEvent;
begin
end;
procedure TibSHTableForm.SetOnAfterRollback(Value: TNotifyEvent);
begin
end;
procedure TibSHTableForm.PrepareControls;
begin
end;
procedure TibSHTableForm.ShowDDLText;
begin
if Assigned(DDLForm) then DDLForm.ShowDDLText;
end;
{ Tree }
procedure TibSHTableForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TTreeRec);
end;
procedure TibSHTableForm.TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if Assigned(Data) then Finalize(Data^);
end;
procedure TibSHTableForm.TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
//var
// Data: PTreeRec;
begin
// Data := Sender.GetNodeData(Node);
// if (Kind = ikNormal) or (Kind = ikSelected) then
// begin
// case Column of
// 1: if Sender.GetNodeLevel(Node) = 0 then ImageIndex := Data.ImageIndex else ImageIndex := -1;
// else
// ImageIndex := -1;
// end;
// end;
end;
procedure TibSHTableForm.TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if TextType = ttNormal then
begin
if Assigned(DBField) or Assigned(DBView) then
case Column of
0: CellText := Data.Number;
1: CellText := Data.Name;
2: CellText := Data.Constraints;
3: CellText := Data.DataType;
4: CellText := Data.Domain;
5: CellText := Data.DefaultExpression;
6: CellText := Data.NullType;
7: CellText := Data.Charset;
8: CellText := Data.Collate;
9: CellText := Data.ArrayDim;
10: CellText := Data.ComputedSource;
11: CellText := Data.DomainCheck;
12: CellText := Data.Description;
end;
if Assigned(DBConstraint) then
case Column of
0: CellText := Data.Number;
1: CellText := Data.Name;
2: CellText := Data.ConstraintType;
3: CellText := Data.Fields;
4: CellText := Data.RefTable;
5: CellText := Data.RefFields;
6: CellText := Data.OnDelete;
7: CellText := Data.OnUpdate;
8: CellText := Data.IndexName;
9: CellText := Data.IndexSorting;
end;
if Assigned(DBIndex) then
case Column of
0: CellText := Data.Number;
1: CellText := Data.Name;
2:
begin
if Length(Data.Fields)>0 then
CellText := Data.Fields
else
CellText := Data.Expression
end;
3: CellText := Data.Status;
4: CellText := Data.IndexType;
5: CellText := Data.Sorting;
6: CellText := Data.Statistics;
end;
if Assigned(DBTrigger) and (Assigned(DBTable) or Assigned(DBView)) then
case Column of
0: CellText := Data.Number;
1: CellText := Data.Name;
2: CellText := Data.Status;
3: CellText := Data.TypePrefix;
4: CellText := Data.TypeSuffix;
5: CellText := Data.Position;
6: CellText := Data.Description;
end;
end;
end;
procedure TibSHTableForm.TreePaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if TextType = ttNormal then
begin
if Assigned(DBField) or Assigned(DBView) then
case Column of
0: ;// Data.Number;
1: ;// Data.Name;
2:;
3: if not IsSystemDomain(Data.Domain) then
if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
TargetCanvas.Font.Color := clGray;
4: if IsSystemDomain(Data.Domain) then
if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
TargetCanvas.Font.Color := clGray;
5: if not Data.OverloadDefault then
if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
TargetCanvas.Font.Color := clGray;
6: if not Data.OverloadNullType then
if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
TargetCanvas.Font.Color := clGray;
7: if not IsSystemDomain(Data.Domain) then
if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
TargetCanvas.Font.Color := clGray;
8: if not Data.OverloadCollate then
if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
TargetCanvas.Font.Color := clGray;
9: ;// Data.ArrayDim;
10: ;// Data.ComputedSource;
11: if Sender.Focused and (vsSelected in Node.States) then
TargetCanvas.Font.Color := clWindow
else
TargetCanvas.Font.Color := clGray;
12: ;// Data.Description;
end;
end;
end;
procedure TibSHTableForm.TreeIncrementalSearch(Sender: TBaseVirtualTree;
Node: PVirtualNode; const SearchText: WideString; var Result: Integer);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if Pos(AnsiUpperCase(SearchText), AnsiUpperCase(Data.Name)) <> 1 then
Result := 1;
end;
procedure TibSHTableForm.TreeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// if Key = VK_RETURN then ShowDBComponent(csSource);
end;
procedure TibSHTableForm.TreeDblClick(Sender: TObject);
begin
// ShowDBComponent(csSource);
end;
procedure TibSHTableForm.TreeGetPopupMenu(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; const P: TPoint;
var AskParent: Boolean; var PopupMenu: TPopupMenu);
var
HT: THitInfo;
Data: PTreeRec;
begin
if not Enabled then Exit;
PopupMenu := nil;
if Assigned(Sender.FocusedNode) then
begin
Sender.GetHitTestInfoAt(P.X, P.Y, True, HT);
Data := Sender.GetNodeData(Sender.FocusedNode);
if Assigned(Data) and (Sender.GetNodeLevel(Sender.FocusedNode) = 0) and (HT.HitNode = Sender.FocusedNode) and (hiOnItemLabel in HT.HitPositions) then
end;
end;
procedure TibSHTableForm.TreeCompareNodes(
Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode;
Column: TColumnIndex; var Result: Integer);
var
Data1, Data2: PTreeRec;
begin
Data1 := Sender.GetNodeData(Node1);
Data2 := Sender.GetNodeData(Node2);
Result := CompareStr(Data1.Name, Data2.Name);
end;
procedure TibSHTableForm.TreeFocusChanging(Sender: TBaseVirtualTree;
OldNode, NewNode: PVirtualNode; OldColumn, NewColumn: TColumnIndex;
var Allowed: Boolean);
begin
if Assigned(DBComponent) and (Tree.GetNodeLevel(NewNode) = 0) then
begin
Allowed := Assigned(DDLForm) and DDLForm.CanDestroy;
if not Allowed then
begin
Tree.FocusedNode := OldNode;
Tree.Selected[Tree.FocusedNode] := True;
end else
Pause;
end;
end;
procedure TibSHTableForm.TreeFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
var
Data: PTreeRec;
begin
Data := nil;
if Assigned(Node) then
case Tree.GetNodeLevel(Node) of
0: Data := Tree.GetNodeData(Node);
1: Data := Tree.GetNodeData(Node.Parent);
end;
if Assigned(DBComponent) and Assigned(Editor) then
begin
Editor.BeginUpdate;
Editor.Lines.Clear;
if Assigned(Data) then Editor.Lines.Text := Data.Source;
Editor.EndUpdate;
end;
end;
procedure TibSHTableForm.SetTree(Value: TVirtualStringTree);
begin
FTree := Value;
if Assigned(FTree) then
begin
FocusedControl := FTree;
FTree.Images := Designer.ImageList;
FTree.OnGetNodeDataSize := TreeGetNodeDataSize;
FTree.OnFreeNode := TreeFreeNode;
FTree.OnGetImageIndex := TreeGetImageIndex;
FTree.OnGetText := TreeGetText;
FTree.OnPaintText := TreePaintText;
FTree.OnIncrementalSearch := TreeIncrementalSearch;
FTree.OnDblClick := TreeDblClick;
FTree.OnKeyDown := TreeKeyDown;
FTree.OnGetPopupMenu := TreeGetPopupMenu;
FTree.OnCompareNodes := TreeCompareNodes;
FTree.OnFocusChanging := TreeFocusChanging;
FTree.OnFocusChanged := TreeFocusChanged;
end;
end;
{ TibSHTableFormAction_ }
constructor TibSHTableFormAction_.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallType := actCallToolbar;
if Self is TibSHTableFormAction_Run then Tag := 1;
if Self is TibSHTableFormAction_Pause then Tag := 2;
if Self is TibSHTableFormAction_Commit then Tag := 3;
if Self is TibSHTableFormAction_Rollback then Tag := 4;
if Self is TibSHTableFormAction_Create then Tag := 5;
if Self is TibSHTableFormAction_Alter then Tag := 6;
if Self is TibSHTableFormAction_Recreate then Tag := 7;
if Self is TibSHTableFormAction_Drop then Tag := 8;
if Self is TibSHTableFormAction_Refresh then Tag := 9;
case Tag of
0: Caption := '-'; // separator
1:
begin
Caption := Format('%s', ['Run']);
ShortCut := TextToShortCut('Ctrl+Enter');
SecondaryShortCuts.Add('F9');
end;
2:
begin
Caption := Format('%s', ['Stop']);
ShortCut := TextToShortCut('Ctrl+BkSp');
end;
3:
begin
Caption := Format('%s', ['Commit']);
ShortCut := TextToShortCut('Shift+Ctrl+C');
end;
4:
begin
Caption := Format('%s', ['Rollback']);
ShortCut := TextToShortCut('Shift+Ctrl+R');
end;
5:
begin
Caption := Format('%s', ['Create New']);
ShortCut := TextToShortCut('');
end;
6:
begin
Caption := Format('%s', ['Alter']);
ShortCut := TextToShortCut('');
end;
7:
begin
Caption := Format('%s', ['Recreate']);
ShortCut := TextToShortCut('');
end;
8:
begin
Caption := Format('%s', ['Drop']);
ShortCut := TextToShortCut('');
end;
9:
begin
Caption := Format('%s', ['Refresh']);
ShortCut := TextToShortCut('F5');
end;
end;
if Tag <> 0 then Hint := Caption;
end;
function TibSHTableFormAction_.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := IsEqualGUID(AClassIID, IibSHTable) or
IsEqualGUID(AClassIID, IibSHView) or
IsEqualGUID(AClassIID, IibSHSystemTable) or
IsEqualGUID(AClassIID, IibSHSystemTableTmp);
end;
procedure TibSHTableFormAction_.EventExecute(Sender: TObject);
begin
case Tag of
// Run
1: (Designer.CurrentComponentForm as ISHRunCommands).Run;
// Pause
2: (Designer.CurrentComponentForm as ISHRunCommands).Pause;
// Commit
3: (Designer.CurrentComponentForm as ISHRunCommands).Commit;
// Rollback
4: (Designer.CurrentComponentForm as ISHRunCommands).Rollback;
// Create New
5: (Designer.CurrentComponentForm as ISHRunCommands).Create;
// Alter
6: (Designer.CurrentComponentForm as ISHRunCommands).Alter;
// Recreate
7: (Designer.CurrentComponentForm as ISHRunCommands).Recreate;
// Drop
8: (Designer.CurrentComponentForm as ISHRunCommands).Drop;
// Refresh
9: (Designer.CurrentComponentForm as ISHRunCommands).Refresh;
end;
end;
procedure TibSHTableFormAction_.EventHint(var HintStr: String; var CanShow: Boolean);
begin
end;
procedure TibSHTableFormAction_.EventUpdate(Sender: TObject);
begin
if Assigned(Designer.CurrentComponentForm) and
Supports(Designer.CurrentComponent, IibSHDDLInfo) and
Supports(Designer.CurrentComponentForm, IibSHDDLForm) and
(
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallFields) or
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallConstraints) or
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallIndices) or
AnsiSameText(Designer.CurrentComponentForm.CallString, SCallTriggers)
) then
begin
case Tag of
// Separator
0:
begin
Visible := True;
end;
// Run
1:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRun;
end;
// Pause
2:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanPause;
end;
// Commit
3:
begin
Visible := ((Designer.CurrentComponent as IibSHDDLInfo).State <> csSource) and
not (Designer.CurrentComponent as IibSHDDLInfo).BTCLDatabase.DatabaseAliasOptions.DDL.AutoCommit;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanCommit;
end;
// Rollback
4:
begin
Visible := ((Designer.CurrentComponent as IibSHDDLInfo).State <> csSource) and
not (Designer.CurrentComponent as IibSHDDLInfo).BTCLDatabase.DatabaseAliasOptions.DDL.AutoCommit;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRollback;
end;
// Create New
5:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanCreate;
end;
// Alter
6:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanAlter;
end;
// Recreate
7:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRecreate;
end;
// Drop
8:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanDrop;
end;
// Refresh
9:
begin
Visible := True;
Enabled := (Designer.CurrentComponentForm as ISHRunCommands).CanRefresh;
end;
end;
end else
Visible := False;
end;
initialization
Register;
end.
|
unit NewFrontiers.Tapi.TapiWinMessageProvider;
interface
uses NewFrontiers.Tapi;
type
/// <summary>
/// Der WinMessageProvider stellt die Tapi-Funktionen zur Verfügung, indem
/// ein anderes Programm via Windows Messages ferngesteuert wird. Es steht
/// daher nur ein Subset der Funktionen zur Verfügung
/// </summary>
TTapiWinMessageProvider = class(TInterfacedObject, ITapiProvider)
public
function anrufen(aNummer: string): TTapiResult;
end;
implementation
uses Windows, SysUtils, Messages, Vcl.Forms, Vcl.Dialogs;
{ TTapiWinMessageProvider }
function TTapiWinMessageProvider.anrufen(aNummer: string): TTapiResult;
var
copyDataStruct: TCopyDataStruct;
receiverHandle: THandle;
res: integer;
NormNummer: ansistring;
begin
aNummer := TTapi.normalisieren(aNummer);
if (aNummer = '') then
begin
result.result := false;
result.error := 'Keine Nummer angegeben';
exit;
end;
Normnummer := AnsiString(TTapi.normalisieren(aNummer)); // <-- [tb Funktioniert nicht über String, sondern über Ansi]
res := 0;
copyDataStruct.dwData := 0;
copyDataStruct.cbData := 1 + (Length(aNummer) * SizeOf(Char));
copyDataStruct.lpData := PAnsiChar(Normnummer);
//copyDataStruct.lpData := PChar(Normnummer);
receiverHandle := FindWindow(PChar('TForm6'), PChar('TAPI Client'));
if receiverHandle = 0 then
begin
result.result := false;
result.error := 'TAPI Client wurde nicht gefunden. Bitte prüfen Sie ob das Programm gestartet ist';
ShowMessage(result.error);
Exit;
end;
try
res := SendMessage(receiverHandle, WM_COPYDATA, WPARAM(Application.Handle), LPARAM(@copyDataStruct));
except
on E: Exception do
ShowMessage('Leitungen sind voll. Bitte versuchen Sie es noch einmal. ' + E.Message);
end;
result.result := res > 0;
end;
end.
|
unit UnitImHint;
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.ActiveX,
System.SysUtils,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Forms,
Vcl.Menus,
Vcl.Themes,
Vcl.ComCtrls,
Vcl.AppEvnts,
Vcl.ImgList,
DBCMenu,
Dmitry.Utils.System,
Dmitry.Graphics.Utils,
Dmitry.Controls.ImButton,
DropSource,
DropTarget,
GIFImage,
DragDropFile,
DragDrop,
UnitHintCeator,
UnitDBDeclare,
uConstants,
uMemory,
uBitmapUtils,
uDBForm,
uListViewUtils,
uGOM,
uDBDrawing,
uGraphicUtils,
uFormUtils,
uDBIcons,
uDBContext,
uDBEntities,
uDBManager,
uAnimationHelper,
uThemesUtils,
uTranslateUtils,
uRuntime;
const
MaxImageHintPreviewSize = 400;
type
TImHint = class(TDBForm)
TimerShow: TTimer;
TimerHide: TTimer;
TimerHintCheck: TTimer;
ApplicationEvents1: TApplicationEvents;
DropFileSourceMain: TDropFileSource;
DragImageList: TImageList;
DropFileTargetMain: TDropFileTarget;
ImageFrameTimer: TTimer;
function Execute(Sender: TForm; G: TGraphic; W, H: Integer; Info: TMediaItem; Pos: TPoint;
CheckFunction: THintCheckFunction): Boolean;
procedure FormClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CMMOUSELEAVE( var Message: TWMNoParams); message CM_MOUSELEAVE;
procedure WMActivateApp(var Msg: TMessage); message WM_ACTIVATEAPP;
procedure Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure TimerShowTimer(Sender: TObject);
procedure TimerHideTimer(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure Image1ContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
procedure TimerHintCheckTimer(Sender: TObject);
procedure LbSizeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
procedure ImageFrameTimerTimer(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
private
{ Private declarations }
AnimatedImage: TGraphic;
SlideNO: Integer;
AnimatedBuffer: TBitmap;
ImageBuffer: TBitmap;
CanClosed: Boolean;
FFormBuffer: TBitmap;
CurrentInfo: TMediaItem;
FDragDrop: Boolean;
FOwner: TForm;
GoIn: Boolean;
FCheckFunction: THintCheckFunction;
FClosed: Boolean;
FWidth: Integer;
FHeight: Integer;
FAlphaBlend: Byte;
FInternalClose: Boolean;
procedure CreateFormImage;
function GetImageName: string;
protected
function GetFormID: string; override;
property ImageName: string read GetImageName;
public
{ Public declarations }
end;
implementation
{$R *.dfm}
{ TImHint }
procedure DrawHintInfo(Bitmap: TBitmap; Width, Height: Integer; FInfo: TMediaItem);
var
Sm, Y: Integer;
RotationNotInDB: Boolean;
procedure DoDrawIcon(X, Y: Integer; ImageIndex: Integer; Grayscale: Boolean = False);
begin
if not Grayscale then
DrawIconEx(Bitmap.Canvas.Handle, X, Y, Icons[ImageIndex], 16, 16, 0, 0, DI_NORMAL)
else
Icons.IconsEx[ImageIndex].GrayIcon.DoDraw(X, Y, Bitmap);
end;
begin
Y := Height - 18;
Sm := Width - 2;
if (Width < 80) or (Height < 60) then
Exit;
if FInfo.Access = Db_access_private then
begin
Dec(Sm, 20);
DoDrawIcon(Sm, Y, DB_IC_PRIVATE);
end;
Dec(Sm, 20);
RotationNotInDB := (FInfo.ID = 0) and (FInfo.Rotation and DB_IMAGE_ROTATE_NO_DB > 0);
case FInfo.Rotation and DB_IMAGE_ROTATE_MASK of
DB_IMAGE_ROTATE_90:
DoDrawIcon(Sm, Y, DB_IC_ROTATED_90, RotationNotInDB);
DB_IMAGE_ROTATE_180:
DoDrawIcon(Sm, Y, DB_IC_ROTATED_180, RotationNotInDB);
DB_IMAGE_ROTATE_270:
DoDrawIcon(Sm, Y, DB_IC_ROTATED_270, RotationNotInDB);
else
Inc(Sm, 20);
end;
Dec(Sm, 20);
case FInfo.Rating of
1: DoDrawIcon(Sm, Y, DB_IC_RATING_1);
2: DoDrawIcon(Sm, Y, DB_IC_RATING_2);
3: DoDrawIcon(Sm, Y, DB_IC_RATING_3);
4: DoDrawIcon(Sm, Y, DB_IC_RATING_4);
5: DoDrawIcon(Sm, Y, DB_IC_RATING_5);
-10: DoDrawIcon(Sm, Y, DB_IC_RATING_1, True);
-20: DoDrawIcon(Sm, Y, DB_IC_RATING_2, True);
-30: DoDrawIcon(Sm, Y, DB_IC_RATING_3, True);
-40: DoDrawIcon(Sm, Y, DB_IC_RATING_4, True);
-50: DoDrawIcon(Sm, Y, DB_IC_RATING_5, True);
else
Inc(Sm, 20);
end;
if FInfo.Encrypted then
begin
Dec(Sm, 20);
DoDrawIcon(Sm, Y, DB_IC_KEY);
end;
end;
procedure TImHint.CreateFormImage;
var
Bitmap: TBitmap;
SFileSize,
SImageSize: string;
TextHeight, ImageNameHeight: Integer;
R: TRect;
begin
SImageSize := Format(L('Image size: %d x %d'), [FWidth, FHeight]);
SFileSize := Format(L('File size: %s'), [SizeInText(CurrentInfo.FileSize)]);
FFormBuffer.Width := Width;
FFormBuffer.Height := Height;
FillTransparentColor(FFormBuffer, clBlack, 0);
DrawRoundGradientVert(FFormBuffer, Rect(0, 0, Width, Height),
Theme.GradientFromColor, Theme.GradientToColor, Theme.HighlightColor, 8, 220);
TextHeight := Canvas.TextHeight('Iy');
Bitmap := TBitmap.Create;
try
if StyleServices.Enabled then
Font.Color := Theme.GradientText;
DrawShadowToImage(Bitmap, ImageBuffer);
DrawImageEx32(FFormBuffer, Bitmap, 5, 5);
R.Left := 5;
R.Right := FFormBuffer.Width - 5;
R.Top := 5 + Bitmap.Height + 5;
R.Bottom := 5 + Bitmap.Height + TextHeight + 5;
R := Rect(R.Left, R.Top, R.Right, R.Top + 200); //heihgt of text up to 200 pixels
DrawText(Canvas.Handle, PChar(ImageName), Length(ImageName), R, DT_CALCRECT or DT_WORDBREAK);
ImageNameHeight := R.Bottom - R.Top;
//restore right
R.Right := FFormBuffer.Width - 5;
DrawText32Bit(FFormBuffer, ImageName, Font, R, DT_WORDBREAK);
R.Bottom := R.Bottom + ImageNameHeight + 5;
R.Top := R.Top + ImageNameHeight + 5;
DrawText32Bit(FFormBuffer, SFileSize, Font, R, 0);
R.Bottom := R.Bottom + TextHeight + 5;
R.Top := R.Top + TextHeight + 5;
DrawText32Bit(FFormBuffer, SImageSize, Font, R, 0);
RenderForm(Self.Handle, FFormBuffer, FAlphaBlend);
finally
F(Bitmap);
end;
end;
function TImHint.Execute(Sender: TForm; G: TGraphic; W, H: Integer;
Info: TMediaItem; Pos: TPoint; CheckFunction: THintCheckFunction): Boolean;
var
DisplayWidth, DisplayHeight, WindowHeight,
WindowWidth, WindowLeft, WindowTop, TextHeight: Integer;
Rect: TRect;
R: TRect;
InverseHW, IsAnimated: Boolean;
begin
Result := False;
try
FCheckFunction := CheckFunction;
FOwner := Sender;
FWidth := W;
FHeight := H;
if not GOM.IsObj(FOwner) then
Exit;
if not FCheckFunction(Info) then
Exit;
Result := True;
ImageFrameTimer.Enabled := False;
AnimatedBuffer := nil;
CanClosed := True;
TimerHide.Enabled := False;
TimerShow.Enabled := False;
GoIn := False;
TimerHintCheck.Enabled := True;
FDragDrop := True;
CurrentInfo := Info.Copy;
IsAnimated := IsAnimatedGraphic(G);
InverseHW := not (Info.Rotation and DB_IMAGE_ROTATE_MASK in [DB_IMAGE_ROTATE_0, DB_IMAGE_ROTATE_180]);
if not (InverseHW and IsAnimated) then
begin
DisplayWidth := G.Width;
DisplayHeight := G.Height;
end else
begin
DisplayHeight := G.Width;
DisplayWidth := G.Height;
end;
if not IsAnimated then
ProportionalSize(MaxImageHintPreviewSize, MaxImageHintPreviewSize, DisplayWidth, DisplayHeight);
ImageBuffer := TBitmap.Create;
AnimatedBuffer := TBitmap.Create;
AnimatedBuffer.PixelFormat := pf24bit;
AnimatedBuffer.Width := G.Width;
AnimatedBuffer.Height := G.Height;
AnimatedBuffer.Canvas.Brush.Color := Theme.PanelColor;
AnimatedBuffer.Canvas.Pen.Color := Theme.PanelColor;
AnimatedBuffer.Canvas.Rectangle(0, 0, AnimatedBuffer.Width, AnimatedBuffer.Height);
AnimatedImage := G;
if IsAnimated then
begin
SlideNO := -1;
ImageFrameTimer.Interval := 1;
ImageFrameTimer.Enabled := True;
ImageBuffer.Width := DisplayWidth;
ImageBuffer.Height := DisplayHeight;
//Draw first slide
ImageFrameTimerTimer(Self);
end else
ImageBuffer.Assign(G);
WindowWidth := Max(100, DisplayWidth + 10 + 2);
WindowHeight := DisplayHeight + 10;
TextHeight := Canvas.TextHeight('Iy');
R.Left := 5;
R.Right := WindowWidth - 5;
R.Top := WindowHeight + 10;
R.Bottom := 5 + 200;
DrawText(Canvas.Handle, PChar(ImageName), Length(ImageName), R, DT_WORDBREAK or DT_CALCRECT);
Inc(WindowHeight, 2 * (5 + TextHeight) + (5 + R.Bottom - R.Top) + 5);
//fix window position
Rect := System.Classes.Rect(Pos.X, Pos.Y, Pos.X + 100, Pos.Y + 100);
if Rect.Top + WindowHeight + 10 > Screen.Height then
WindowTop := Rect.Top - 20 - WindowHeight
else
WindowTop := Rect.Top + 10;
if Rect.Left + WindowWidth + 10 > Screen.Width then
WindowLeft := Rect.Left - 20 - WindowWidth
else
WindowLeft := Rect.Left + 10;
if GOM.IsObj(Sender) then
begin
if WindowTop < Sender.Monitor.Top then
WindowTop := Sender.Monitor.Top + 100;
if WindowLeft < Sender.Monitor.Left then
WindowLeft := Sender.Monitor.Left + 100;
end;
Top := WindowTop;
Left := WindowLeft;
FAlphaBlend := 0;
TimerShow.Enabled := True;
if GOM.IsObj(FOwner) then
if FOwner.FormStyle = FsStayOnTop then
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE);
FClosed := False;
ClientWidth := WindowWidth;
ClientHeight := WindowHeight;
DrawHintInfo(ImageBuffer, ImageBuffer.Width, ImageBuffer.Height, CurrentInfo);
CreateFormImage;
if Info.InnerImage then
ShowWindow(Handle, SW_SHOW)
else
ShowWindow(Handle, SW_SHOWNOACTIVATE);
finally
F(Info);
end;
end;
procedure TImHint.FormClick(Sender: TObject);
begin
TimerHide.Enabled := True;
Close;
end;
procedure TImHint.FormCreate(Sender: TObject);
begin
FInternalClose := False;
CanClosed := True;
AnimatedBuffer := nil;
CurrentInfo := nil;
DropFileTargetMain.Register(Self);
FClosed := True;
BorderStyle := bsNone;
FFormBuffer := TBitmap.Create;
FFormBuffer.PixelFormat := pf32Bit;
THintManager.Instance.RegisterHint(Self);
end;
procedure TImHint.CMMOUSELEAVE(var Message: TWMNoParams);
var
P: TPoint;
R: TRect;
begin
R := Rect(Self.Left, Self.Top, Self.Left + Self.Width, Self.Top + Self.Height);
Getcursorpos(P);
if not PtInRect(R, P) then
TimerHide.Enabled := True;
end;
procedure TImHint.Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
DragImage: TBitmap;
W, H: Integer;
Context: IDBContext;
SettingsRepository: ISettingsRepository;
Settings: TSettings;
begin
if not FDragDrop then
Exit;
if (Button = mbLeft) then
begin
CanClosed := False;
DragImageList.Clear;
DropFileSourceMain.Files.Clear;
DropFileSourceMain.Files.Add(CurrentInfo.FileName);
W := ImageBuffer.Width;
H := ImageBuffer.Height;
Context := DBManager.DBContext;
SettingsRepository := Context.Settings;
Settings := SettingsRepository.Get;
try
ProportionalSize(Settings.ThSize, Settings.ThSize, W, H);
finally
F(Settings);
end;
DragImage := TBitmap.Create;
try
DragImage.PixelFormat := ImageBuffer.PixelFormat;
DoResize(W, H, ImageBuffer, DragImage);
CreateDragImage(DragImage, DragImageList, Font, ExtractFileName(CurrentInfo.FileName));
finally
F(DragImage);
end;
DropFileSourceMain.ImageIndex := 0;
DropFileSourceMain.Execute;
CanClosed := True;
end;
TimerHintCheck.Enabled := True;
end;
procedure TImHint.TimerShowTimer(Sender: TObject);
begin
FAlphaBlend := Min(FAlphaBlend + 40, 255);
if FAlphaBlend >= 255 then
TimerShow.Enabled := False;
CreateFormImage;
end;
procedure TImHint.WMActivateApp(var Msg: TMessage);
begin
if Msg.wParam = 0 then
TimerHide.Enabled := True;
end;
procedure TImHint.TimerHideTimer(Sender: TObject);
begin
TimerShow.Enabled := False;
FAlphaBlend := Max(FAlphaBlend - 40, 0);
if FAlphaBlend = 0 then
begin
if not BlockClosingOfWindows then
begin
TimerHide.Enabled := False;
FInternalClose := True;
Close;
end else
begin
CreateFormImage;
Hide;
end;
end else
CreateFormImage;
end;
procedure TImHint.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if FInternalClose then
Exit;
if FClosed then
begin
CanClose := False;
Exit;
end;
if (FAlphaBlend > 0) then
begin
TimerHide.Enabled := True;
CanClose := False;
end;
TimerHintCheck.Enabled := False;
FClosed := True;
end;
procedure TImHint.FormClose(Sender: TObject; var Action: TCloseAction);
begin
THintManager.Instance.UnRegisterHint(Self);
if GOM.IsObj(FOwner) then
if FOwner.FormStyle = FsStayOnTop then
FOwner.SetFocus;
F(AnimatedBuffer);
F(ImageBuffer);
ImageFrameTimer.Enabled := False;
Release;
end;
procedure TImHint.Image1ContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
var
MenuInfo: TMediaItemCollection;
begin
TimerHintCheck.Enabled := False;
FDragDrop := True;
MenuInfo := TMediaItemCollection.Create;
try
MenuInfo.Add(CurrentInfo.Copy);
MenuInfo[0].Selected := True;
MenuInfo.ListItem := nil;
MenuInfo.IsListItem := False;
TDBPopupMenu.Instance.Execute(Self, ClientToScreen(MousePos).X, ClientToScreen(MousePos).Y, MenuInfo);
if not FClosed then
TimerHide.Enabled := True;
FDragDrop := False;
finally
F(MenuInfo);
end;
end;
procedure TImHint.TimerHintCheckTimer(Sender: TObject);
var
P: Tpoint;
R: Trect;
begin
if FClosed then
begin
TimerHintCheck.Enabled := False;
Exit;
end;
if not Goin then
Exit;
R := Rect(Left, Top, Left + Width, Top + Height);
Getcursorpos(P);
if not PtInRect(R, P) then
TimerHide.Enabled := True;
GoIn := False;
end;
procedure TImHint.LbSizeMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
GoIn := True;
end;
procedure TImHint.FormDeactivate(Sender: TObject);
begin
Close;
end;
procedure TImHint.FormDestroy(Sender: TObject);
begin
F(AnimatedBuffer);
F(ImageBuffer);
F(AnimatedImage);
F(CurrentInfo);
F(FFormBuffer);
DropFileTargetMain.Unregister;
end;
procedure TImHint.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = Char(VK_ESCAPE) then
Close;
end;
procedure TImHint.ApplicationEvents1Message(var Msg: tagMSG;
var Handled: Boolean);
begin
if FClosed then
Exit;
if Msg.message = WM_KEYDOWN then
begin
if Msg.WParam = VK_ESCAPE then
Close;
end;
end;
procedure TImHint.ImageFrameTimerTimer(Sender: TObject);
begin
if FClosed then
Exit;
AnimatedImage.ProcessNextFrame(AnimatedBuffer, SlideNo, Theme.PanelColor, ImageFrameTimer,
procedure
begin
ImageBuffer.Canvas.Pen.Color := Theme.PanelColor;
ImageBuffer.Canvas.Brush.Color := Theme.PanelColor;
ImageBuffer.Canvas.Rectangle(0, 0, ImageBuffer.Width, ImageBuffer.Height);
case CurrentInfo.Rotation and DB_IMAGE_ROTATE_MASK of
DB_IMAGE_ROTATE_0:
StretchCoolEx0(0, 0, ImageBuffer.Width, ImageBuffer.Height, AnimatedBuffer, ImageBuffer, Theme.PanelColor);
DB_IMAGE_ROTATE_90:
StretchCoolEx90(0, 0, ImageBuffer.Height, ImageBuffer.Width, AnimatedBuffer, ImageBuffer, Theme.PanelColor);
DB_IMAGE_ROTATE_180:
StretchCoolEx180(0, 0, ImageBuffer.Width, ImageBuffer.Height, AnimatedBuffer, ImageBuffer, Theme.PanelColor);
DB_IMAGE_ROTATE_270:
StretchCoolEx270(0, 0, ImageBuffer.Height, ImageBuffer.Width, AnimatedBuffer, ImageBuffer, Theme.PanelColor);
end;
DrawHintInfo(ImageBuffer, ImageBuffer.Width, ImageBuffer.Height, CurrentInfo);
CreateFormImage;
end
);
end;
function TImHint.GetFormID: string;
begin
Result := 'Hint';
end;
function TImHint.GetImageName: string;
begin
if CurrentInfo.Comment <> '' then
Result := CurrentInfo.Comment
else if CurrentInfo.InnerImage then
Result := CurrentInfo.Name
else
Result := ExtractFileName(IIF(CurrentInfo.Name <> '', CurrentInfo.Name, ExtractFileName(CurrentInfo.FileName)));
end;
end.
|
program HowToControlMusic;
uses
SwinGame, sgTypes;
procedure Main();
begin
OpenAudio();
OpenGraphicsWindow('How To Control Music', 320, 240);
LoadDefaultColors();
LoadMusic('game.ogg');
LoadMusic('diving-turtle.mp3');
LoadMusic('fast.mp3');
LoadMusic('gentle-thoughts-1.mp3');
LoadMusic('morning-workout.mp3');
LoadMusic('saber.ogg');
SetMusicVolume(1);
repeat // The game loop...
ProcessEvents();
ClearScreen(ColorWhite);
if KeyDown(RightCtrlKey) OR KeyDown(LeftCtrlKey) then
begin
if KeyTyped(Key1) then FadeMusicIn('game.ogg', -1, 10000);
if KeyTyped(Key2) then FadeMusicIn('fast.mp3', -1, 10000);
if KeyTyped(Key3) then FadeMusicIn('gentle-thoughts-1.mp3', -1, 10000);
if KeyTyped(Key4) then FadeMusicIn('morning-workout.mp3', -1, 10000);
if KeyTyped(Key5) then FadeMusicIn('saber.ogg', -1, 10000);
if KeyTyped(Key6) then FadeMusicIn('diving-turtle.mp3', -1, 10000);
end
else if KeyTyped(RightAltKey) OR KeyTyped(LeftAltKey) then
begin
FadeMusicOut(10000);
end
else
begin
if KeyTyped(Key1) then PlayMusic('game.ogg');
if KeyTyped(Key2) then PlayMusic('fast.mp3');
if KeyTyped(Key3) then PlayMusic('gentle-thoughts-1.mp3');
if KeyTyped(Key4) then PlayMusic('morning-workout.mp3');
if KeyTyped(Key5) then PlayMusic('saber.ogg');
if KeyTyped(Key6) then PlayMusic('diving-turtle.mp3');
if KeyTyped(PKey) then PauseMusic();
if KeyTyped(RKey) then ResumeMusic();
if KeyTyped(KeyPadPlus) and (MusicVolume() < 1) then SetMusicVolume(MusicVolume() + 0.1);
if KeyTyped(KeyPadMinus) and (MusicVolume() > 0) then SetMusicVolume(MusicVolume() - 0.1);
if KeyTyped(SKey) then if MusicPlaying() then StopMusic();
end;
DrawText('Control Music (Escape or q to quit)', ColorRed, 'Arial', 18, 15, 15);
DrawText('1-6 to play different music', ColorBlue, 'Arial', 14, 20, 50);
DrawText('CTRL + (1-6) to Fade Music In', ColorBlue, 'Arial', 14, 20, 75);
DrawText('Alt + (1-6) to Fade Music Out', ColorBlue, 'Arial', 14, 20, 100);
DrawText('p to pause music', ColorBlue, 'Arial', 14, 20, 125);
DrawText('r to resume music', ColorBlue, 'Arial', 14, 20, 150);
DrawText('+ or - increase volume by 10%', ColorBlue, 'Arial', 14, 20, 175);
DrawText('s to stop playing music', ColorBlue, 'Arial', 14, 20, 200);
RefreshScreen(60);
until WindowCloseRequested() OR KeyTyped(EscapeKey) OR KeyTyped(QKey);
CloseAudio();
ReleaseAllResources();
end;
begin
Main();
end. |
namespace GlHelper;
{$DEFINE USEINLINE}
interface
type
{ A 4x4 matrix in row-major order (M[Row, Column]).
You can access the elements directly using M[0,0]..M[3,3] or m11..m44.
}
TMatrix4 = public record
private
method GetComponent(const ARow, AColumn: Integer): Single; {$IF USEINLINE} inline; {$ENDIF}
method SetComponent(const ARow, AColumn: Integer; const Value: Single); {$IF USEINLINE} inline; {$ENDIF}
method GetRow(const AIndex: Integer): TVector4;
method SetRow(const AIndex: Integer; const Value: TVector4);
method GetDeterminant: Single;
public
{ Initializes the matrix to an identity matrix (filled with 0 and value 1
for the diagonal) }
method Init;
{ Fills the matrix with zeros and sets the diagonal.
Parameters:
ADiagonal: the value to use for the diagonal. Use 1 to set the matrix
to an identity matrix. }
method Init(const ADiagonal: Single);
{ Initializes the matrix using four row vectors.
Parameters:
ARow0: the first row of the matrix.
ARow1: the second row of the matrix.
ARow2: the third row of the matrix.
ARow3: the fourth row of the matrix. }
method Init(const ARow0, ARow1, ARow2, ARow3: TVector4);
{ Initializes the matrix with explicit values.
Parameters:
A11-A44: the values of the matrix elements, in row-major order. }
method Init(const A11, A12, A13, A14, A21, A22, A23, A24, A31, A32, A33,
A34, A41, A42, A43, A44: Single);
{ Initializes the matrix with a 3x3 matrix. The 3x3 matrix is copied to the
top-left corner of the 4x4 matrix, and the remaining elements are set
according to an identity matrix.
Parameters:
AMatrix: the source 3x3 matrix. }
method Init(const AMatrix: TMatrix3);
{ Creates a scaling matrix that scales uniformly.
Parameters:
AScale: the uniform scale factor }
method InitScaling(const AScale: Single);
{ Creates a scaling matrix.
Parameters:
AScaleX: the value to scale by on the X axis
AScaleY: the value to scale by on the Y axis
AScaleZ: the value to scale by on the Z axis }
method InitScaling(const AScaleX, AScaleY, AScaleZ: Single);
{ Creates a scaling matrix.
Parameters:
AScale: the scale factors }
method InitScaling(const AScale: TVector3);
{ Creates a translation matrix.
Parameters:
ADeltaX: translation in the X direction
ADeltaY: translation in the Y direction
ADeltaZ: translation in the Z direction }
method InitTranslation(const ADeltaX, ADeltaY, ADeltaZ: Single);
{ Creates a translation matrix.
Parameters:
ADelta: translation vector }
method InitTranslation(const ADelta: TVector3);
{ Creates a matrix for rotating points around the X axis.
Parameters:
AAngle: the rotation angle around the X axis, in radians }
method InitRotationX(const AAngle: Single);
{ Creates a matrix for rotating points around the Y axis.
Parameters:
AAngle: the rotation angle around the Y axis, in radians }
method InitRotationY(const AAngle: Single);
{ Creates a matrix for rotating points around the Z axis.
Parameters:
AAngle: the rotation angle around the Z axis, in radians }
method InitRotationZ(const AAngle: Single);
{ Creates a matrix for rotating points around a certain axis.
Parameters:
AAxis: the direction of the axis to rotate around.
AAngle: the rotation angle around AAxis, in radians }
method InitRotation(const AAxis: TVector3; const AAngle: Single);
{ Creates a rotation matrix from a yaw, pitch and roll angle.
Parameters:
AYaw: the rotation angle around the Y axis, in radians
APitch: the rotation angle around the X axis, in radians
ARoll: the rotation angle around the Z axis, in radians }
method InitRotationYawPitchRoll(const AYaw, APitch, ARoll: Single);
{ Creates a rotation matrix from a heading, pitch and bank angle.
Parameters:
AHeading: the heading angle, in radians
APitch: the pitch angle, in radians
ABank: the bank angle, in radians }
method InitRotationHeadingPitchBank(const AHeading, APitch, ABank: Single);
{ Creates a left-handed view matrix looking at a certain target.
Parameters:
ACameraPosition: position of the camera (or eye).
ACameraTarget: the target towards which the camera is pointing.
ACameraUp: the direction that is "up" from the camera's point of view }
method InitLookAtLH(const ACameraPosition, ACameraTarget, ACameraUp: TVector3);
{ Creates a right-handed view matrix looking at a certain target.
Parameters:
ACameraPosition: position of the camera (or eye).
ACameraTarget: the target towards which the camera is pointing.
ACameraUp: the direction that is "up" from the camera's point of view }
method InitLookAtRH(const ACameraPosition, ACameraTarget, ACameraUp: TVector3);
{ Creates a left-handed view matrix looking into a certain direction.
Parameters:
ACameraPosition: position of the camera (or eye).
ACameraDirection: the direction the camera is pointing in.
ACameraUp: the direction that is "up" from the camera's point of view }
method InitLookAtDirLH(const ACameraPosition, ACameraDirection, ACameraUp: TVector3);
{ Creates a right-handed view matrix looking into a certain direction.
Parameters:
ACameraPosition: position of the camera (or eye).
ACameraDirection: the direction the camera is pointing in.
ACameraUp: the direction that is "up" from the camera's point of view }
method InitLookAtDirRH(const ACameraPosition, ACameraDirection, ACameraUp: TVector3);
{ Creates a left-handed orthographic projection matrix from the given view
volume dimensions.
Parameters:
AWidth: the width of the view volume.
AHeight: the height of the view volume.
AZNearPlane: the minimum Z-value of the view volume.
AZFarPlane: the maximum Z-value of the view volume. }
method InitOrthoLH(const AWidth, AHeight, AZNearPlane, AZFarPlane: Single);
{ Creates a right-handed orthographic projection matrix from the given view
volume dimensions.
Parameters:
AWidth: the width of the view volume.
AHeight: the height of the view volume.
AZNearPlane: the minimum Z-value of the view volume.
AZFarPlane: the maximum Z-value of the view volume. }
method InitOrthoRH(const AWidth, AHeight, AZNearPlane, AZFarPlane: Single);
{ Creates a customized left-handed orthographic projection matrix.
Parameters:
ALeft: the minimum X-value of the view volume.
ATop: the maximum Y-value of the view volume.
ARight: the maximum X-value of the view volume.
ABottom: the minimum Y-value of the view volume.
AZNearPlane: the minimum Z-value of the view volume.
AZFarPlane: the maximum Z-value of the view volume. }
method InitOrthoOffCenterLH(const ALeft, ATop, ARight, ABottom,
AZNearPlane, AZFarPlane: Single);
{ Creates a customized right-handed orthographic projection matrix.
Parameters:
ALeft: the minimum X-value of the view volume.
ATop: the maximum Y-value of the view volume.
ARight: the maximum X-value of the view volume.
ABottom: the minimum Y-value of the view volume.
AZNearPlane: the minimum Z-value of the view volume.
AZFarPlane: the maximum Z-value of the view volume. }
method InitOrthoOffCenterRH(const ALeft, ATop, ARight, ABottom,
AZNearPlane, AZFarPlane: Single);
{ Creates a left-handed perspective projection matrix based on a field of
view, aspect ratio, and near and far view plane distances.
Parameters:
AFieldOfView: the field of view in radians.
AAspectRatio: the aspect ratio, defined as view space width divided by
height.
ANearPlaneDistance:the distance to the near view plane.
AFarPlaneDistance:the distance to the far view plane.
AHorizontalFOV: (optional) boolean indicating the direction of the
field of view. If False (default), AFieldOfView is in the Y direction,
otherwise in the X direction }
method InitPerspectiveFovLH(const AFieldOfView, AAspectRatio,
ANearPlaneDistance, AFarPlaneDistance: Single;
const AHorizontalFOV: Boolean := False);
{ Creates a right-handed perspective projection matrix based on a field of
view, aspect ratio, and near and far view plane distances.
Parameters:
AFieldOfView: the field of view in radians.
AAspectRatio: the aspect ratio, defined as view space width divided by
height.
ANearPlaneDistance:the distance to the near view plane.
AFarPlaneDistance:the distance to the far view plane.
AHorizontalFOV: (optional) boolean indicating the direction of the
field of view. If False (default), AFieldOfView is in the Y direction,
otherwise in the X direction }
method InitPerspectiveFovRH(const AFieldOfView, AAspectRatio,
ANearPlaneDistance, AFarPlaneDistance: Single;
const AHorizontalFOV: Boolean := False);
{ Checks two matrices for equality.
Returns:
True if the two matrices match each other exactly. }
class operator Equal(const A, B: TMatrix4): Boolean; {$IF USEINLINE} inline; {$ENDIF}
{ Checks two matrices for inequality.
Returns:
True if the two matrices are not equal. }
class operator NotEqual(const A, B: TMatrix4): Boolean; {$IF USEINLINE} inline; {$ENDIF}
{ Negates a matrix.
Returns:
The negative value of the matrix (with all elements negated). }
class operator Minus(const A: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Adds a scalar value to each element of a matrix. }
class operator Add(const A: TMatrix4; const B: Single): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Adds a scalar value to each element of a matrix. }
class operator Add(const A: Single; const B: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Adds two matrices component-wise. }
class operator Add(const A, B: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Subtracts a scalar value from each element of a matrix. }
class operator Subtract(const A: TMatrix4; const B: Single): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Subtracts a matrix from a scalar value. }
class operator Subtract(const A: Single; const B: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Subtracts two matrices component-wise. }
class operator Subtract(const A, B: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Multiplies a matrix with a scalar value. }
class operator Multiply(const A: TMatrix4; const B: Single): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Multiplies a matrix with a scalar value. }
class operator Multiply(const A: Single; const B: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Performs a matrix * row vector linear algebraic multiplication. }
class operator Multiply(const A: TMatrix4; const B: TVector4): TVector4; {$IF USEINLINE} inline; {$ENDIF}
{ Performs a column vector * matrix linear algebraic multiplication. }
class operator Multiply(const A: TVector4; const B: TMatrix4): TVector4; {$IF USEINLINE} inline; {$ENDIF}
{ Multiplies two matrices using linear algebraic multiplication. }
class operator Multiply(const A, B: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Divides a matrix by a scalar value. }
class operator Divide(const A: TMatrix4; const B: Single): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Divides a scalar value by a matrix. }
class operator Divide(const A: Single; const B: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Divides a matrix by a vector. This is equivalent to multiplying the
inverse of the matrix with a row vector using linear algebraic
multiplication. }
class operator Divide(const A: TMatrix4; const B: TVector4): TVector4; {$IF USEINLINE} inline; {$ENDIF}
{ Divides a vector by a matrix. This is equivalent to multiplying a column
vector with the inverse of the matrix using linear algebraic
multiplication. }
class operator Divide(const A: TVector4; const B: TMatrix4): TVector4; {$IF USEINLINE} inline; {$ENDIF}
{ Divides two matrices. This is equivalent to multiplying the first matrix
with the inverse of the second matrix using linear algebraic
multiplication. }
class operator Divide(const A, B: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Multiplies this matrix with another matrix component-wise.
Parameters:
AOther: the other matrix.
Returns:
This matrix multiplied by AOther component-wise.
That is, Result.M[I,J] := M[I,J] * AOther.M[I,J].
@bold(Note): For linear algebraic matrix multiplication, use the multiply
(*) operator instead. }
method CompMult(const AOther: TMatrix4): TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Creates a transposed version of this matrix.
Returns:
The transposed version of this matrix.
@bold(Note): Does not change this matrix. To update this itself, use
SetTransposed. }
method Transpose: TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Transposes this matrix.
@bold(Note): If you do not want to change this matrix, but get a
transposed version instead, then use Transpose. }
method SetTransposed;
{ Calculates the inverse of this matrix.
Returns:
The inverse of this matrix.
@bold(Note): Does not change this matrix. To update this itself, use
SetInversed.
@bold(Note): The values in the returned matrix are undefined if this
matrix is singular or poorly conditioned (nearly singular). }
method Inverse: TMatrix4; {$IF USEINLINE} inline; {$ENDIF}
{ Inverts this matrix.
@bold(Note): If you do not want to change this matrix, but get an
inversed version instead, then use Inverse.
@bold(Note): The values in the inversed matrix are undefined if this
matrix is singular or poorly conditioned (nearly singular). }
method SetInversed;
{ Returns the rows of the matrix. This is identical to accessing the
R-field.
Parameters:
AIndex: index of the row to return (0-3). Range is checked with
an assertion. }
property Rows[const AIndex: Integer]: TVector4 read GetRow write SetRow;
{ The determinant of this matrix. }
property Determinant: Single read GetDeterminant;
method getPglMatrix4f : ^Single;
public
{The Rows of the Matrix}
V: array [0..3] of TVector4;
{ Returns the elements of the matrix (in row-major order).
This is identical to accessing the M-field, but this property can be used
as a default array property.
Parameters:
ARow: the row index (0-3). Range is checked with an assertion.
AColumn: the column index (0-3). Range is checked with requires. }
property M[const ARow, AColumn: Integer]: Single read GetComponent write SetComponent; default;
property m11 : Single read GetComponent(0,0);
property m12 : Single read GetComponent(0,1);
property m13 : Single read GetComponent(0,2);
property m14 : Single read GetComponent(0,3);
property m21 : Single read GetComponent(1,0);
property m22 : Single read GetComponent(1,1);
property m23 : Single read GetComponent(1,2);
property m24 : Single read GetComponent(1,3);
property m31 : Single read GetComponent(2,0);
property m32 : Single read GetComponent(2,1);
property m33 : Single read GetComponent(2,2);
property m34 : Single read GetComponent(2,3);
property m41 : Single read GetComponent(3,0);
property m42 : Single read GetComponent(3,1);
property m43 : Single read GetComponent(3,2);
property m44 : Single read GetComponent(3,3);
//m11,
// m12, m13, m14: Single;
// m21, m22, m23, m24: Single;
// m31, m32, m33, m34: Single;
// m41, m42, m43, m44: Single;
end;
implementation
{ TMatrix 4 }
class operator TMatrix4.Add(const A: TMatrix4; const B: Single): TMatrix4;
begin
Result.V[0] := A.V[0] + B;
Result.V[1] := A.V[1] + B;
Result.V[2] := A.V[2] + B;
Result.V[3] := A.V[3] + B;
end;
class operator TMatrix4.Add(const A: Single; const B: TMatrix4): TMatrix4;
begin
Result.V[0] := A + B.V[0];
Result.V[1] := A + B.V[1];
Result.V[2] := A + B.V[2];
Result.V[3] := A + B.V[3];
end;
class operator TMatrix4.Add(const A, B: TMatrix4): TMatrix4;
begin
Result.V[0] := A.V[0] + B.V[0];
Result.V[1] := A.V[1] + B.V[1];
Result.V[2] := A.V[2] + B.V[2];
Result.V[3] := A.V[3] + B.V[3];
end;
method TMatrix4.CompMult(const AOther: TMatrix4): TMatrix4;
var
I: Integer;
begin
for I := 0 to 3 do
Result.V[I] := V[I] * AOther.V[I];
end;
class operator TMatrix4.Divide(const A: Single; const B: TMatrix4): TMatrix4;
begin
Result.V[0] := A / B.V[0];
Result.V[1] := A / B.V[1];
Result.V[2] := A / B.V[2];
Result.V[3] := A / B.V[3];
end;
class operator TMatrix4.Divide(const A: TMatrix4; const B: Single): TMatrix4;
var
InvB: Single;
begin
InvB := 1 / B;
Result.V[0] := A.V[0] * InvB;
Result.V[1] := A.V[1] * InvB;
Result.V[2] := A.V[2] * InvB;
Result.V[3] := A.V[3] * InvB;
end;
method TMatrix4.Inverse: TMatrix4;
var
C00, C02, C03, C04, C06, C07, C08, C10, C11: Single;
C12, C14, C15, C16, C18, C19, C20, C22, C23: Single;
F0, F1, F2, F3, F4, F5, V0, V1, V2, V3, I0, I1, I2, I3, SA, SB, Row, Dot: TVector4;
Inv: TMatrix4;
OneOverDeterminant: Single;
begin
C00 := (M[2,2] * M[3,3]) - (M[3,2] * M[2,3]);
C02 := (M[1,2] * M[3,3]) - (M[3,2] * M[1,3]);
C03 := (M[1,2] * M[2,3]) - (M[2,2] * M[1,3]);
C04 := (M[2,1] * M[3,3]) - (M[3,1] * M[2,3]);
C06 := (M[1,1] * M[3,3]) - (M[3,1] * M[1,3]);
C07 := (M[1,1] * M[2,3]) - (M[2,1] * M[1,3]);
C08 := (M[2,1] * M[3,2]) - (M[3,1] * M[2,2]);
C10 := (M[1,1] * M[3,2]) - (M[3,1] * M[1,2]);
C11 := (M[1,1] * M[2,2]) - (M[2,1] * M[1,2]);
C12 := (M[2,0] * M[3,3]) - (M[3,0] * M[2,3]);
C14 := (M[1,0] * M[3,3]) - (M[3,0] * M[1,3]);
C15 := (M[1,0] * M[2,3]) - (M[2,0] * M[1,3]);
C16 := (M[2,0] * M[3,2]) - (M[3,0] * M[2,2]);
C18 := (M[1,0] * M[3,2]) - (M[3,0] * M[1,2]);
C19 := (M[1,0] * M[2,2]) - (M[2,0] * M[1,2]);
C20 := (M[2,0] * M[3,1]) - (M[3,0] * M[2,1]);
C22 := (M[1,0] * M[3,1]) - (M[3,0] * M[1,1]);
C23 := (M[1,0] * M[2,1]) - (M[2,0] * M[1,1]);
F0.Init(C00, C00, C02, C03);
F1.Init(C04, C04, C06, C07);
F2.Init(C08, C08, C10, C11);
F3.Init(C12, C12, C14, C15);
F4.Init(C16, C16, C18, C19);
F5.Init(C20, C20, C22, C23);
V0.Init(M[1,0], M[0,0], M[0,0], M[0,0]);
V1.Init(M[1,1], M[0,1], M[0,1], M[0,1]);
V2.Init(M[1,2], M[0,2], M[0,2], M[0,2]);
V3.Init(M[1,3], M[0,3], M[0,3], M[0,3]);
I0 := (V1 * F0) - (V2 * F1) + (V3 * F2);
I1 := (V0 * F0) - (V2 * F3) + (V3 * F4);
I2 := (V0 * F1) - (V1 * F3) + (V3 * F5);
I3 := (V0 * F2) - (V1 * F4) + (V2 * F5);
SA.Init(+1, -1, +1, -1);
SB.Init(-1, +1, -1, +1);
Inv.Init(I0 * SA, I1 * SB, I2 * SA, I3 * SB);
Row.Init(Inv[0,0], Inv[1,0], Inv[2,0], Inv[3,0]);
Dot := V[0] * Row;
OneOverDeterminant := 1 / ((Dot.X + Dot.Y) + (Dot.Z + Dot.W));
Result := Inv * OneOverDeterminant;
end;
class operator TMatrix4.Multiply(const A: Single; const B: TMatrix4): TMatrix4;
begin
Result.V[0] := A * B.V[0];
Result.V[1] := A * B.V[1];
Result.V[2] := A * B.V[2];
Result.V[3] := A * B.V[3];
end;
class operator TMatrix4.Multiply(const A: TMatrix4; const B: Single): TMatrix4;
begin
Result.V[0] := A.V[0] * B;
Result.V[1] := A.V[1] * B;
Result.V[2] := A.V[2] * B;
Result.V[3] := A.V[3] * B;
end;
class operator TMatrix4.Multiply(const A: TVector4; const B: TMatrix4): TVector4;
begin
Result.X := (B.M[0,0] * A.X) + (B.M[1,0] * A.Y) + (B.M[2,0] * A.Z) + (B.M[3,0] * A.W);
Result.Y := (B.M[0,1] * A.X) + (B.M[1,1] * A.Y) + (B.M[2,1] * A.Z) + (B.M[3,1] * A.W);
Result.Z := (B.M[0,2] * A.X) + (B.M[1,2] * A.Y) + (B.M[2,2] * A.Z) + (B.M[3,2] * A.W);
Result.W := (B.M[0,3] * A.X) + (B.M[1,3] * A.Y) + (B.M[2,3] * A.Z) + (B.M[3,3] * A.W);
end;
class operator TMatrix4.Multiply(const A: TMatrix4; const B: TVector4): TVector4;
begin
Result.X := (B.X * A.M[0,0]) + (B.Y * A.M[0,1]) + (B.Z * A.M[0,2]) + (B.W * A.M[0,3]);
Result.Y := (B.X * A.M[1,0]) + (B.Y * A.M[1,1]) + (B.Z * A.M[1,2]) + (B.W * A.M[1,3]);
Result.Z := (B.X * A.M[2,0]) + (B.Y * A.M[2,1]) + (B.Z * A.M[2,2]) + (B.W * A.M[2,3]);
Result.W := (B.X * A.M[3,0]) + (B.Y * A.M[3,1]) + (B.Z * A.M[3,2]) + (B.W * A.M[3,3]);
end;
class operator TMatrix4.Multiply(const A, B: TMatrix4): TMatrix4;
begin
Result.M[0,0] := (A.M[0,0] * B.M[0,0]) + (A.M[0,1] * B.M[1,0]) + (A.M[0,2] * B.M[2,0]) + (A.M[0,3] * B.M[3,0]);
Result.M[0,1] := (A.M[0,0] * B.M[0,1]) + (A.M[0,1] * B.M[1,1]) + (A.M[0,2] * B.M[2,1]) + (A.M[0,3] * B.M[3,1]);
Result.M[0,2] := (A.M[0,0] * B.M[0,2]) + (A.M[0,1] * B.M[1,2]) + (A.M[0,2] * B.M[2,2]) + (A.M[0,3] * B.M[3,2]);
Result.M[0,3] := (A.M[0,0] * B.M[0,3]) + (A.M[0,1] * B.M[1,3]) + (A.M[0,2] * B.M[2,3]) + (A.M[0,3] * B.M[3,3]);
Result.M[1,0] := (A.M[1,0] * B.M[0,0]) + (A.M[1,1] * B.M[1,0]) + (A.M[1,2] * B.M[2,0]) + (A.M[1,3] * B.M[3,0]);
Result.M[1,1] := (A.M[1,0] * B.M[0,1]) + (A.M[1,1] * B.M[1,1]) + (A.M[1,2] * B.M[2,1]) + (A.M[1,3] * B.M[3,1]);
Result.M[1,2] := (A.M[1,0] * B.M[0,2]) + (A.M[1,1] * B.M[1,2]) + (A.M[1,2] * B.M[2,2]) + (A.M[1,3] * B.M[3,2]);
Result.M[1,3] := (A.M[1,0] * B.M[0,3]) + (A.M[1,1] * B.M[1,3]) + (A.M[1,2] * B.M[2,3]) + (A.M[1,3] * B.M[3,3]);
Result.M[2,0] := (A.M[2,0] * B.M[0,0]) + (A.M[2,1] * B.M[1,0]) + (A.M[2,2] * B.M[2,0]) + (A.M[2,3] * B.M[3,0]);
Result.M[2,1] := (A.M[2,0] * B.M[0,1]) + (A.M[2,1] * B.M[1,1]) + (A.M[2,2] * B.M[2,1]) + (A.M[2,3] * B.M[3,1]);
Result.M[2,2] := (A.M[2,0] * B.M[0,2]) + (A.M[2,1] * B.M[1,2]) + (A.M[2,2] * B.M[2,2]) + (A.M[2,3] * B.M[3,2]);
Result.M[2,3] := (A.M[2,0] * B.M[0,3]) + (A.M[2,1] * B.M[1,3]) + (A.M[2,2] * B.M[2,3]) + (A.M[2,3] * B.M[3,3]);
Result.M[3,0] := (A.M[3,0] * B.M[0,0]) + (A.M[3,1] * B.M[1,0]) + (A.M[3,2] * B.M[2,0]) + (A.M[3,3] * B.M[3,0]);
Result.M[3,1] := (A.M[3,0] * B.M[0,1]) + (A.M[3,1] * B.M[1,1]) + (A.M[3,2] * B.M[2,1]) + (A.M[3,3] * B.M[3,1]);
Result.M[3,2] := (A.M[3,0] * B.M[0,2]) + (A.M[3,1] * B.M[1,2]) + (A.M[3,2] * B.M[2,2]) + (A.M[3,3] * B.M[3,2]);
Result.M[3,3] := (A.M[3,0] * B.M[0,3]) + (A.M[3,1] * B.M[1,3]) + (A.M[3,2] * B.M[2,3]) + (A.M[3,3] * B.M[3,3]);
end;
class operator TMatrix4.Minus(const A: TMatrix4): TMatrix4;
begin
Result.V[0] := -A.V[0];
Result.V[1] := -A.V[1];
Result.V[2] := -A.V[2];
Result.V[3] := -A.V[3];
end;
method TMatrix4.SetInversed;
begin
Self := Inverse;
end;
method TMatrix4.SetTransposed;
begin
Self := Transpose;
end;
class operator TMatrix4.Subtract(const A: TMatrix4; const B: Single): TMatrix4;
begin
Result.V[0] := A.V[0] - B;
Result.V[1] := A.V[1] - B;
Result.V[2] := A.V[2] - B;
Result.V[3] := A.V[3] - B;
end;
class operator TMatrix4.Subtract(const A, B: TMatrix4): TMatrix4;
begin
Result.V[0] := A.V[0] - B.V[0];
Result.V[1] := A.V[1] - B.V[1];
Result.V[2] := A.V[2] - B.V[2];
Result.V[3] := A.V[3] - B.V[3];
end;
class operator TMatrix4.Subtract(const A: Single; const B: TMatrix4): TMatrix4;
begin
Result.V[0] := A - B.V[0];
Result.V[1] := A - B.V[1];
Result.V[2] := A - B.V[2];
Result.V[3] := A - B.V[3];
end;
method TMatrix4.Transpose: TMatrix4;
begin
Result.M[0,0] := M[0,0];
Result.M[0,1] := M[1,0];
Result.M[0,2] := M[2,0];
Result.M[0,3] := M[3,0];
Result.M[1,0] := M[0,1];
Result.M[1,1] := M[1,1];
Result.M[1,2] := M[2,1];
Result.M[1,3] := M[3,1];
Result.M[2,0] := M[0,2];
Result.M[2,1] := M[1,2];
Result.M[2,2] := M[2,2];
Result.M[2,3] := M[3,2];
Result.M[3,0] := M[0,3];
Result.M[3,1] := M[1,3];
Result.M[3,2] := M[2,3];
Result.M[3,3] := M[3,3];
end;
{ TMatrix4 }
class operator TMatrix4.Divide(const A, B: TMatrix4): TMatrix4;
begin
Result := A * B.Inverse;
end;
class operator TMatrix4.Divide(const A: TVector4; const B: TMatrix4): TVector4;
begin
Result := A * B.Inverse;
end;
class operator TMatrix4.Divide(const A: TMatrix4; const B: TVector4): TVector4;
begin
Result := A.Inverse * B;
end;
method TMatrix4.GetDeterminant: Single;
var
F00, F01, F02, F03, F04, F05: Single;
C: TVector4;
begin
F00 := (M[2,2] * M[3,3]) - (M[3,2] * M[2,3]);
F01 := (M[2,1] * M[3,3]) - (M[3,1] * M[2,3]);
F02 := (M[2,1] * M[3,2]) - (M[3,1] * M[2,2]);
F03 := (M[2,0] * M[3,3]) - (M[3,0] * M[2,3]);
F04 := (M[2,0] * M[3,2]) - (M[3,0] * M[2,2]);
F05 := (M[2,0] * M[3,1]) - (M[3,0] * M[2,1]);
C.X := + ((M[1,1] * F00) - (M[1,2] * F01) + (M[1,3] * F02));
C.Y := - ((M[1,0] * F00) - (M[1,2] * F03) + (M[1,3] * F04));
C.Z := + ((M[1,0] * F01) - (M[1,1] * F03) + (M[1,3] * F05));
C.W := - ((M[1,0] * F02) - (M[1,1] * F04) + (M[1,2] * F05));
Result := (M[0,0] * C.X) + (M[0,1] * C.Y) + (M[0,2] * C.Z) + (M[0,3] * C.W);
end;
class operator TMatrix4.Equal(const A, B: TMatrix4): Boolean;
begin
Result := (A.V[0] = B.V[0]) and (A.V[1] = B.V[1]) and (A.V[2] = B.V[2]) and (A.V[3] = B.V[3]);
end;
method TMatrix4.Init(const ADiagonal: Single);
begin
V[0].Init(ADiagonal, 0, 0, 0);
V[1].Init(0, ADiagonal, 0, 0);
V[2].Init(0, 0, ADiagonal, 0);
V[3].Init(0, 0, 0, ADiagonal);
end;
method TMatrix4.Init;
begin
V[0].Init(1, 0, 0, 0);
V[1].Init(0, 1, 0, 0);
V[2].Init(0, 0, 1, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.Init(const A11, A12, A13, A14, A21, A22, A23, A24, A31, A32,
A33, A34, A41, A42, A43, A44: Single);
begin
V[0].Init(A11, A12, A13, A14);
V[1].Init(A21, A22, A23, A24);
V[2].Init(A31, A32, A33, A34);
V[3].Init(A41, A42, A43, A44);
end;
method TMatrix4.Init(const AMatrix: TMatrix3);
begin
V[0].Init(AMatrix.V[0], 0);
V[1].Init(AMatrix.V[1], 0);
V[2].Init(AMatrix.V[2], 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitLookAtLH(const ACameraPosition, ACameraTarget,
ACameraUp: TVector3);
var
XAxis, YAxis, ZAxis: TVector3;
begin
ZAxis := (ACameraTarget - ACameraPosition).Normalize;
XAxis := ACameraUp.Cross(ZAxis).Normalize;
YAxis := ZAxis.Cross(XAxis);
V[0].Init(XAxis.X, YAxis.X, ZAxis.X, 0);
V[1].Init(XAxis.Y, YAxis.Y, ZAxis.Y, 0);
V[2].Init(XAxis.Z, YAxis.Z, ZAxis.Z, 0);
V[3].Init(-XAxis.Dot(ACameraPosition),
-YAxis.Dot(ACameraPosition),
-ZAxis.Dot(ACameraPosition), 1);
end;
method TMatrix4.InitLookAtRH(const ACameraPosition, ACameraTarget,
ACameraUp: TVector3);
var
XAxis, YAxis, ZAxis: TVector3;
begin
ZAxis := (ACameraPosition - ACameraTarget).Normalize;
XAxis := ACameraUp.Cross(ZAxis).Normalize;
YAxis := ZAxis.Cross(XAxis);
V[0].Init(XAxis.X, YAxis.X, ZAxis.X, 0);
V[1].Init(XAxis.Y, YAxis.Y, ZAxis.Y, 0);
V[2].Init(XAxis.Z, YAxis.Z, ZAxis.Z, 0);
V[3].Init(-XAxis.Dot(ACameraPosition),
-YAxis.Dot(ACameraPosition),
-ZAxis.Dot(ACameraPosition), 1);
end;
method TMatrix4.InitLookAtDirLH(const ACameraPosition, ACameraDirection,
ACameraUp: TVector3);
var
XAxis, YAxis, ZAxis: TVector3;
begin
ZAxis := -ACameraDirection.Normalize;
XAxis := ACameraUp.Cross(ZAxis).Normalize;
YAxis := ZAxis.Cross(XAxis);
V[0].Init(XAxis.X, YAxis.X, ZAxis.X, 0);
V[1].Init(XAxis.Y, YAxis.Y, ZAxis.Y, 0);
V[2].Init(XAxis.Z, YAxis.Z, ZAxis.Z, 0);
V[3].Init(-XAxis.Dot(ACameraPosition),
-YAxis.Dot(ACameraPosition),
-ZAxis.Dot(ACameraPosition), 1);
end;
method TMatrix4.InitLookAtDirRH(const ACameraPosition, ACameraDirection,
ACameraUp: TVector3);
var
XAxis, YAxis, ZAxis: TVector3;
begin
ZAxis := ACameraDirection.Normalize;
XAxis := ACameraUp.Cross(ZAxis).Normalize;
YAxis := ZAxis.Cross(XAxis);
V[0].Init(XAxis.X, YAxis.X, ZAxis.X, 0);
V[1].Init(XAxis.Y, YAxis.Y, ZAxis.Y, 0);
V[2].Init(XAxis.Z, YAxis.Z, ZAxis.Z, 0);
V[3].Init(-XAxis.Dot(ACameraPosition),
-YAxis.Dot(ACameraPosition),
-ZAxis.Dot(ACameraPosition), 1);
end;
method TMatrix4.InitScaling(const AScale: Single);
begin
V[0].Init(AScale, 0, 0, 0);
V[1].Init(0, AScale, 0, 0);
V[2].Init(0, 0, AScale, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitScaling(const AScaleX, AScaleY, AScaleZ: Single);
begin
V[0].Init(AScaleX, 0, 0, 0);
V[1].Init(0, AScaleY, 0, 0);
V[2].Init(0, 0, AScaleZ, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitScaling(const AScale: TVector3);
begin
V[0].Init(AScale.X, 0, 0, 0);
V[1].Init(0, AScale.Y, 0, 0);
V[2].Init(0, 0, AScale.Z, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitTranslation(const ADeltaX, ADeltaY, ADeltaZ: Single);
begin
V[0].Init(1, 0, 0, 0);
V[1].Init(0, 1, 0, 0);
V[2].Init(0, 0, 1, 0);
V[3].Init(ADeltaX, ADeltaY, ADeltaZ, 1);
end;
method TMatrix4.InitTranslation(const ADelta: TVector3);
begin
V[0].Init(1, 0, 0, 0);
V[1].Init(0, 1, 0, 0);
V[2].Init(0, 0, 1, 0);
V[3].Init(ADelta.X, ADelta.Y, ADelta.Z, 1);
end;
class operator TMatrix4.NotEqual(const A, B: TMatrix4): Boolean;
begin
Result := (A.V[0] <> B.V[0]) or (A.V[1] <> B.V[1]) or (A.V[2] <> B.V[2]) or (A.V[3] <> B.V[3]);
end;
method TMatrix4.InitRotationX(const AAngle: Single);
var
S, C: Single;
begin
SinCos(AAngle, out S, out C);
V[0].Init(1, 0, 0, 0);
V[1].Init(0, C, S, 0);
V[2].Init(0, -S, C, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitRotationY(const AAngle: Single);
var
S, C: Single;
begin
SinCos(AAngle, out S, out C);
V[0].Init(C, 0, -S, 0);
V[1].Init(0, 1, 0, 0);
V[2].Init(S, 0, C, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitRotationZ(const AAngle: Single);
var
S, C: Single;
begin
SinCos(AAngle, out S,out C);
V[0].Init(C, S, 0, 0);
V[1].Init(-S, C, 0, 0);
V[2].Init(0, 0, 1, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitRotation(const AAxis: TVector3; const AAngle: Single);
var
S, C, C1: Single;
N: TVector3;
begin
SinCos(AAngle, out S, out C);
C1 := 1 - C;
N := AAxis.Normalize;
V[0].Init((C1 * N.X * N.X) + C,
(C1 * N.X * N.Y) + (N.Z * S),
(C1 * N.Z * N.X) - (N.Y * S), 0);
V[1].Init((C1 * N.X * N.Y) - (N.Z * S),
(C1 * N.Y * N.Y) + C,
(C1 * N.Y * N.Z) + (N.X * S), 0);
V[2].Init((C1 * N.Z * N.X) + (N.Y * S),
(C1 * N.Y * N.Z) - (N.X * S),
(C1 * N.Z * N.Z) + C, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitRotationYawPitchRoll(const AYaw, APitch, ARoll: Single);
var
A, S, C: TVector4;
begin
A.Init(APitch, AYaw, ARoll, 0);
SinCos(A, out S, out C);
V[0].Init((C.Y * C.Z) + (S.X * S.Y * S.Z),
(C.Y * S.X * S.Z) - (C.Z * S.Y),
-C.X * S.Z, 0);
V[1].Init(C.X * S.Y,
C.X * C.Y,
S.X, 0);
V[2].Init((C.Y * S.Z) - (C.Z * S.X * S.Y),
(-C.Z * C.Y * S.X) - (S.Z * S.Y),
C.X * C.Z, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.InitRotationHeadingPitchBank(const AHeading, APitch, ABank: Single);
var
A, S, C: TVector4;
begin
A.Init(AHeading, APitch, ABank, 0);
SinCos(A, out S, out C);
V[0].Init((C.X * C.Z) + (S.X * S.Y * S.Z),
(-C.X * S.Z) + (S.X * S.Y * C.Z),
S.X * C.Y, 0);
V[1].Init(S.Z * C.Y,
C.Y * C.Z,
-S.Y, 0);
V[2].Init((-S.X * C.Z) + (C.X * S.Y * S.Z),
(S.Z * S.X) + (C.X * S.Y * C.Z),
C.X * C.Y, 0);
V[3].Init(0, 0, 0, 1);
end;
method TMatrix4.GetComponent(const ARow, AColumn: Integer): Single;
{$IF USEINLINE}
{$ELSE}
require
(ARow >= 0) and (ARow < 4);
(AColumn >= 0) and (AColumn < 4);
{$ENDIF}
begin
Result := V[ARow][AColumn];
end;
method TMatrix4.GetRow(const AIndex: Integer): TVector4;
{$IF USEINLINE}
{$ELSE}
require
(AIndex >= 0) and (AIndex < 4);
{$ENDIF}
begin
Result := V[AIndex];
end;
method TMatrix4.Init(const ARow0, ARow1, ARow2, ARow3: TVector4);
begin
V[0] := ARow0;
V[1] := ARow1;
V[2] := ARow2;
V[3] := ARow3;
end;
method TMatrix4.InitOrthoLH(const AWidth, AHeight, AZNearPlane,
AZFarPlane: Single);
begin
V[0].Init(2 / AWidth, 0, 0, 0);
V[1].Init(0, 2 / AHeight, 0, 0);
V[2].Init(0, 0, 1 / (AZFarPlane - AZNearPlane), 0);
V[3].Init(0, AZNearPlane / (AZNearPlane - AZFarPlane), 0, 1);
end;
method TMatrix4.InitOrthoRH(const AWidth, AHeight, AZNearPlane,
AZFarPlane: Single);
begin
V[0].Init(2 / AWidth, 0, 0, 0);
V[1].Init(0, 2 / AHeight, 0, 0);
V[2].Init(0, 0, 1 / (AZNearPlane - AZFarPlane), 0);
V[3].Init(0, AZNearPlane / (AZNearPlane - AZFarPlane), 0, 1);
end;
method TMatrix4.InitOrthoOffCenterLH(const ALeft, ATop, ARight, ABottom,
AZNearPlane, AZFarPlane: Single);
begin
V[0].Init(2 / (ARight - ALeft), 0, 0, 0);
V[1].Init(0, 2 / (ATop - ABottom), 0, 0);
V[2].Init(0, 0, 1 / (AZFarPlane - AZNearPlane), 0);
V[3].Init((ALeft + ARight) / (ALeft - ARight),
(ATop + ABottom) / (ABottom - ATop),
AZNearPlane / (AZNearPlane - AZFarPlane), 1);
end;
method TMatrix4.InitOrthoOffCenterRH(const ALeft, ATop, ARight, ABottom,
AZNearPlane, AZFarPlane: Single);
begin
V[0].Init(2 / (ARight - ALeft), 0, 0, 0);
V[1].Init(0, 2 / (ATop - ABottom), 0, 0);
V[2].Init(0, 0, 1 / (AZNearPlane - AZFarPlane), 0);
V[3].Init((ALeft + ARight) / (ALeft - ARight),
(ATop + ABottom) / (ABottom - ATop),
AZNearPlane / (AZNearPlane - AZFarPlane), 1);
end;
method TMatrix4.InitPerspectiveFovLH(const AFieldOfView, AAspectRatio,
ANearPlaneDistance, AFarPlaneDistance: Single; const AHorizontalFOV: Boolean);
var
XScale, YScale: Single;
begin
if (AHorizontalFOV) then
begin
XScale := 1 / Math.Tan(0.5 * AFieldOfView);
YScale := XScale / AAspectRatio;
end
else
begin
YScale := 1 / Math.Tan(0.5 * AFieldOfView);
XScale := YScale / AAspectRatio;
end;
V[0].Init(XScale, 0, 0, 0);
V[1].Init(0, YScale, 0, 0);
V[2].Init(0, 0, AFarPlaneDistance / (AFarPlaneDistance - ANearPlaneDistance), 1);
V[3].Init(0, 0, (-ANearPlaneDistance * AFarPlaneDistance) / (AFarPlaneDistance - ANearPlaneDistance), 0);
end;
method TMatrix4.InitPerspectiveFovRH(const AFieldOfView, AAspectRatio,
ANearPlaneDistance, AFarPlaneDistance: Single; const AHorizontalFOV: Boolean);
var
XScale, YScale: Single;
begin
if (AHorizontalFOV) then
begin
XScale := 1 / Math.Tan(0.5 * AFieldOfView);
YScale := XScale / AAspectRatio;
end
else
begin
YScale := 1 / Math.Tan(0.5 * AFieldOfView);
XScale := YScale / AAspectRatio;
end;
V[0].Init(XScale, 0, 0, 0);
V[1].Init(0, YScale, 0, 0);
V[2].Init(0, 0, AFarPlaneDistance / (ANearPlaneDistance - AFarPlaneDistance), -1);
V[3].Init(0, 0, (ANearPlaneDistance * AFarPlaneDistance) / (ANearPlaneDistance - AFarPlaneDistance), 0);
end;
method TMatrix4.SetComponent(const ARow, AColumn: Integer; const Value: Single);
{$IF USEINLINE}
{$ELSE}
require
(ARow >= 0) and (ARow < 4);
(AColumn >= 0) and (AColumn < 4);
{$ENDIF}
begin
V[ARow][AColumn] := Value;
end;
method TMatrix4.SetRow(const AIndex: Integer; const Value: TVector4);
{$IF USEINLINE}
{$ELSE}
require
(AIndex >= 0) and (AIndex < 4);
{$ENDIF}
begin
V[AIndex] := Value;
end;
method TMatrix4.getPglMatrix4f: ^Single;
begin
exit @V[0].X;
end;
end. |
unit uHandleError;
interface
uses ADOdb, classes, Sysutils;
const
//Applications Error type
CRITICAL_ERROR = 1;
FAILURE_ERROR = 2;
WARNING_ERROR = 3;
type
THandleError = class
private
FConnection : TADOConnection;
FID : Integer;
FType : Integer;
FSource : String;
FMsg : String;
FDate : String;
FIDUser : Integer;
function FlushError:boolean;
public
Constructor Create;
Destructor Destroy; override;
property Connection : TADOCOnnection read FConnection write FConnection;
function ErrorDetected(iID, iType, iIDUser:Integer; sSource, sMsg, sDate : String):Boolean;
end;
implementation
function THandleError.FlushError:boolean;
var
MyQuery : TADOQuery;
iID : Integer;
begin
Result := False;
if not Assigned(FConnection) then
Exit;
Try
MyQuery := TADOQuery.Create(nil);
with MyQuery do
begin
Connection := FConnection;
SQL.Add('INSERT Sis_AppHistory (IDHistory, ErrorLevel, FormSource, ErrorMessage, IDUsuario, HistoryDate)');
SQL.Add('VALUES (' +IntToStr(FID) + ', ' +IntToStr(FType) + ', ' + QuotedStr(FSource) + ', ' );
SQL.Add(QuotedStr(FMsg) + ', ' + IntToStr(FIDUser) + ', ' +QuotedStr(FDate) + ')' );
ExecSQL;
SQL.Clear;
SQL.Add('IF @@TRANCOUNT > 0 COMMIT');
ExecSQL;
end;
Finally
MyQuery.Free;
end;
Result := True;
end;
function THandleError.ErrorDetected(iID, iType, iIDUser:Integer; sSource, sMsg, sDate : String):boolean;
begin
FType := iType;
FSource := sSource;
FMsg := sMsg;
FDate := sDate;
FIDUser := iIDUser;
FID := iID;
Result := FlushError;
end;
Constructor THandleError.Create;
begin
inherited Create;
end;
Destructor THandleError.Destroy;
begin
inherited Destroy;
end;
end.
|
namespace SnapTileSample;
interface
uses
System.Threading.Tasks,
Windows.ApplicationModel.Activation,
Windows.ApplicationModel,
Windows.UI.Xaml;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
type
App = partial class(Application)
private
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
method OnSuspending(sender: System.Object; args: SuspendingEventArgs);
protected
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="args">Details about the launch request and process.</param>
method OnLaunched(args: LaunchActivatedEventArgs); override;
public
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
constructor;
end;
implementation
constructor App;
begin
self.InitializeComponent();
self.Suspending += OnSuspending;
end;
method App.OnLaunched(args: LaunchActivatedEventArgs);
begin
await SuspensionManager.RestoreAsync;
Window.Current.Content := new MainPage();
Window.Current.Activate();
end;
method App.OnSuspending(sender: Object; args: SuspendingEventArgs);
begin
var deferral := args.SuspendingOperation.GetDeferral();
await SuspensionManager.SaveAsync();
deferral.Complete();
end;
end.
|
object Main: TMain
Left = 0
Top = 0
Caption = 'Main'
ClientHeight = 372
ClientWidth = 660
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object ScriptMemo: TMemo
Left = 0
Top = 0
Width = 660
Height = 235
Align = alClient
Lines.Strings = (
'{'
' this is a simple scripting language !'
' it parses expressions and evaluates them'
' and finally sets the result to the output console (memo).'
' '
' variable type can be either : '
' - decimal eg : 15.'
' - hex eg : $1234abc, 0x1234abc.'
' - float eg : 5.2.'
' '
' string can be either : '
' - single quoted string => just like pascal ( double '#39' to e' +
'scape '#39'):'
' '#39'string'#39', '#39#39', '#39#39#39#39'. '
' - double quoted string => just like perl (use \ to escape):'
' "", "\"", "string $variable", "string \$novar' +
'iable", ...'
' '
' comments: just like pascal:'
' - // single line.'
' - (* multi line *).'
' - just like this one with {. '
' '
' operators: '
' - +/*-%'
''
' built in function:'
' - min '
' - max'
' - sin'
' - cos'
' - tan'
' - clear'
' - echo'
'}'
''
'clear; // clear console.'
''
'var a = 00; // decimal'
'var b = 0x0a; // hex'
'var c = $0a; // pascal hex'
'var d = 00.20; // float'
''
'var vmin = min(a, b, c, d);'
'var vmax = max(a, b, c, d);'
''
'echo "min = $vmin ; max = $vmax";'
''
'echo '#39'calculating expression :'#39#39'a = max(1, 10, vmax - 1) * sin( ' +
'min(d % 2, 4, vmin + 1.1) ) + 10 - ( 5 / 2)'#39#39' '#39';'
'a = max(1, 10, vmax - 1) * sin( min(d % 2, 4, vmin + 1.1) ) + 10' +
' - ( 5 / 2);'
'echo "a = $a.";'
''
'// end of script:'
'echo '#39#39';'
'echo '#39#39';'
'echo '#39'script ended.'#39';')
ScrollBars = ssVertical
TabOrder = 0
ExplicitWidth = 626
ExplicitHeight = 185
end
object LogMemo: TMemo
Left = 0
Top = 235
Width = 660
Height = 104
Align = alBottom
Lines.Strings = (
'Memo2')
ScrollBars = ssVertical
TabOrder = 1
ExplicitTop = 208
ExplicitWidth = 626
end
object ParseBtn: TButton
Left = 0
Top = 339
Width = 660
Height = 33
Align = alBottom
Caption = 'Parse'
TabOrder = 2
OnClick = ParseBtnClick
ExplicitTop = 312
ExplicitWidth = 626
end
end
|
unit RegProperty;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Controls,
DBTables, DsgnIntf, TypInfo, DB, StdCtrls, dialogs;
procedure Register;
implementation
uses
DBTreeView;
{ TDBStringProperty }
type
TDBStringProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValueList(List: TStrings); virtual; abstract;
procedure GetValues(Proc: TGetStrProc); override;
end;
function TDBStringProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paMultiSelect];
end;
procedure TDBStringProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
Values: TStringList;
begin
Values := TStringList.Create;
try
GetValueList(Values);
for I := 0 to Values.Count - 1 do Proc(Values[I]);
finally
Values.Free;
end;
end;
{ TLookUpFieldProperty }
type
TLookUpFieldProperty = class(TDbStringProperty)
public
procedure GetValueList(List: TStrings); override;
function GetTablePropName: string; virtual;
end;
function TLookUpFieldProperty.GetTablePropName: string;
begin
Result := 'LookUpTable';
end;
procedure TLookUpFieldProperty.GetValueList(List: TStrings);
var
Instance: TComponent;
PropInfo: PPropInfo;
LookUpTable : TTable;
begin
Instance := TComponent(GetComponent(0));
PropInfo := TypInfo.GetPropInfo(Instance.ClassInfo, GetTablePropName);
if (PropInfo <> nil) and (PropInfo^.PropType^.Kind = tkClass) then
begin
LookUpTable := TObject(GetOrdProp(Instance, PropInfo)) as TTable;
if (LookUpTable <> nil) then
LookUpTable.GetFieldNames(List);
end;
end;
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(string), TDBTreeView, 'IDItemField', TLookUpFieldProperty);
RegisterPropertyEditor(TypeInfo(string), TDBTreeView, 'NameField', TLookUpFieldProperty);
RegisterPropertyEditor(TypeInfo(string), TDBTreeView, 'PathField', TLookUpFieldProperty);
end;
end.
|
unit usynprghl;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, SynEditTypes, SynEditHighlighter, SynEditStrConst;
type
{ TSynPrgHl }
TSynPrgHl = class(TSynCustomHighlighter)
private
FTokenPos, FTokenEnd: Integer;
FLineText: String;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fKeyAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
public
procedure SetLine(const NewValue: String; LineNumber: Integer); override;
procedure Next; override;
function GetEol: Boolean; override;
procedure GetTokenEx(out TokenStart: PChar; out TokenLength: integer); override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetToken: String; override;
function GetTokenPos: Integer; override;
function GetTokenKind: integer; override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override;
constructor Create(AOwner: TComponent); override;
published
property CommentAttri: TSynHighlighterAttributes read fCommentAttri
write fCommentAttri;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri
write fIdentifierAttri;
property KeyAttri: TSynHighlighterAttributes read fKeyAttri
write fKeyAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri
write fStringAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri
write fSpaceAttri;
end;
const
PRG_RESERVED_WORDS : array[1..55] of string =
('array',
'begin',
'break',
'byte' ,
'call' ,
'case' ,
'clone',
'const',
'continue',
'debug' ,
'declare',
'default',
'dup' ,
'elif' ,
'else' ,
'elseif' ,
'elsif' ,
'end' ,
'float' ,
'for' ,
'frame' ,
'from' ,
'function',
'global' ,
'goto' ,
'if' ,
'import' ,
'include',
'int' ,
'jmp' ,
'local' ,
'loop' ,
'offset' ,
'onExit' ,
'pointer',
'private',
'process',
'program',
'public' ,
'repeat' ,
'return' ,
'short' ,
'sizeof' ,
'step' ,
'string' ,
'struct' ,
'switch' ,
'to' ,
'type' ,
'until' ,
'varspace',
'void',
'while',
'word',
'yield');
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FPG Editor', [TSynPrgHl]);
end;
constructor TSynPrgHl.Create(AOwner: TComponent);
var
i :Integer;
begin
inherited Create(AOwner);
fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment, SYNS_XML_AttrComment);
fCommentAttri.Style:= [fsItalic];
fCommentAttri.Foreground:=clGray;
AddAttribute(fCommentAttri);
fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier, SYNS_XML_AttrIdentifier);
fIdentifierAttri.Foreground:=clBlack;
AddAttribute(fIdentifierAttri);
fKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrKey, SYNS_XML_AttrKey);
fKeyAttri.Foreground:=clRed;
AddAttribute(fKeyAttri);
fStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString, SYNS_XML_AttrString);
fStringAttri.Foreground:=clBlue;
AddAttribute(fStringAttri);
fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace, SYNS_XML_AttrSpace);
fIdentifierAttri.Foreground:=clBlack;
AddAttribute(fSpaceAttri);
end;
procedure TSynPrgHl.SetLine(const NewValue: String; LineNumber: Integer);
begin
inherited;
FLineText := NewValue;
FTokenEnd := 1;
Next;
end;
procedure TSynPrgHl.Next;
var
l: Integer;
begin
FTokenPos := FTokenEnd;
l := length(FLineText);
If FTokenPos > l then
exit;
if FLineText[FTokenEnd] in ['/'] then
if FLineText[FTokenEnd+1] in ['/'] then
while (FTokenEnd <= l ) do
begin
inc (FTokenEnd);
end;
if FLineText[FTokenEnd] in [#9,' '] then
while (FTokenEnd+1 <= l ) do
begin
inc (FTokenEnd);
if not (FLineText[FTokenEnd] in [#9,' ']) then
exit;
end;
If FTokenEnd > l then
exit;
if FLineText[FTokenEnd] in ['"'] then
while (FTokenEnd+1 <= l ) do
begin
inc (FTokenEnd);
if (FLineText[FTokenEnd] in ['"']) then
begin
inc (FTokenEnd);
exit;
end;
end;
If FTokenEnd > l then
exit;
while (FTokenEnd+1 <= l ) do
begin
inc (FTokenEnd);
if (FLineText[FTokenEnd] in [#9,' ','"',';']) then
exit;
end;
inc (FTokenEnd);
end;
function TSynPrgHl.GetEol: Boolean;
begin
Result := FTokenPos > length(FLineText);
end;
procedure TSynPrgHl.GetTokenEx(out TokenStart: PChar; out TokenLength: integer);
begin
TokenStart := @FLineText[FTokenPos];
TokenLength := FTokenEnd - FTokenPos;
end;
function TSynPrgHl.GetTokenAttribute: TSynHighlighterAttributes;
var
i: Integer;
begin
// Match the text, specified by FTokenPos and FTokenEnd
Result := fIdentifierAttri;
if (GetToken[1] ='/') and (GetToken[2] ='/') then
begin
Result := fCommentAttri;
exit;
end;
if GetToken[1] ='"' then
begin
Result := fStringAttri;
exit;
end;
if (GetToken[1] in [#9,' ']) then
begin
Result := fSpaceAttri;
exit;
end;
for i:=1 to length(PRG_RESERVED_WORDS) do
if LowerCase(GetToken) = PRG_RESERVED_WORDS[i] then
begin
Result := fKeyAttri;
break;
end;
end;
function TSynPrgHl.GetToken: String;
begin
Result := copy(FLineText, FTokenPos, FTokenEnd - FTokenPos);
end;
function TSynPrgHl.GetTokenPos: Integer;
begin
Result := FTokenPos - 1;
end;
function TSynPrgHl.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_KEYWORD: Result := fKeyAttri;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
else Result := nil;
end;
end;
function TSynPrgHl.GetTokenKind: integer;
var
a: TSynHighlighterAttributes;
begin
// Map Attribute into a unique number
a := GetTokenAttribute;
Result := 0;
if a = fKeyAttri then Result := 1;
if a = fSpaceAttri then Result := 2;
end;
end.
|
//------------------------------------------------------------------------------
//PointList UNIT
//------------------------------------------------------------------------------
// What it does -
// A list of TPoints
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
unit PointList;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Types,
Classes;
type
PPoint = ^TPoint;
//------------------------------------------------------------------------------
//TPointList CLASS
//------------------------------------------------------------------------------
TPointList = Class(TObject)
Private
MsCount : Integer; // Count of Points in the list
MaxCount : Integer; // Maximum Points that can fit into current storage
MemStart : Pointer; // Start of the memory holding the list
NextSlot : PPoint; // Points to the next free slot in memory
Function GetValue(Index : Integer) : TPoint;
Procedure SetValue(Index : Integer; Value : TPoint);
Procedure Expand(const Size : Integer);
Procedure Shrink(const Size : Integer);
Public
Constructor Create();
Destructor Destroy; override;
Property Items[Index : Integer] : TPoint
read GetValue write SetValue;default;
Procedure Add(const APoint : TPoint);
Procedure Delete(Index : Integer);
Procedure Clear();
Procedure Assign(APointList : TPointList);
Property Count : Integer
read MsCount;
end;
//------------------------------------------------------------------------------
implementation
const
ALLOCATE_SIZE = 20; // How many Points to store in each incremental memory block
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Initializes our Pointlist. Creates a storage area.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
constructor TPointList.Create();
begin
inherited Create;
MsCount := 0; // No Points in the list yet
MaxCount := 0; //no mem yet!
MemStart := NIL;//no memory yet
end;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Destroys our list and frees any memory used.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
destructor TPointList.Destroy;
begin
// Free the allocated memory
FreeMem(MemStart);
inherited;
end;{Destroy}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Expand PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Increases the memory area size by Size Address.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TPointList.Expand(const Size : Integer);
var
NewMemoryStart : Pointer;
OldPointer, NewPointer : PPoint;
Index : Integer;
begin
// First allocate a new, bigger memory space
GetMem(NewMemoryStart, (MaxCount + Size) * SizeOf(TPoint));
if(Assigned(MemStart)) then
begin
// Copy the data from the old memory here
OldPointer := MemStart;
NewPointer := NewMemoryStart;
for Index := 1 to MaxCount do
begin
// Copy one Point at a time
NewPointer^ := OldPointer^;
Inc(OldPointer);
Inc(NewPointer);
end;
// Free the old memory
FreeMem(MemStart);
end;
// And now refer to the new memory
MemStart := NewMemoryStart;
NextSlot := MemStart;
Inc(NextSlot, MaxCount);
Inc(MaxCount, Size);
end;{Expand}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Shrink PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Decreases the memory area size by Size PPoint.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TPointList.Shrink(const Size: Integer);
var
NewMemoryStart : Pointer;
OldPointer, NewPointer : PPoint;
Index : Integer;
begin
if MaxCount > Size then
begin
//first allocate a new, smaller memory space
GetMem(NewMemoryStart, (MaxCount - Size) * SizeOf(TPoint));
if(Assigned(MemStart)) then
begin
// Copy the data from the old memory here
OldPointer := MemStart;
NewPointer := NewMemoryStart;
for Index := 1 to MaxCount do
begin
// Copy one Point at a time
NewPointer^ := OldPointer^;
Inc(OldPointer);
Inc(NewPointer);
end;
// Free the old memory
FreeMem(MemStart);
end;
// And now refer to the new memory
MemStart := NewMemoryStart;
NextSlot := MemStart;
Inc(NextSlot, MaxCount);
Inc(MaxCount, Size);
end;
end;{Shrink}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Add PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Adds a TPoint to the list.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TPointList.Add(const APoint : TPoint);
begin
// If we do not have enough space to add the Point, then get more space!
if MsCount = MaxCount then
begin
Expand(ALLOCATE_SIZE);
end;
// Now we can safely add the Point to the list
NextSlot^ := APoint;
// And update things to suit
Inc(MsCount);
Inc(NextSlot);
end;{Add}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Assign PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Assigns the point list another point lists items.
//
// Changes -
// March 12th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
procedure TPointList.Assign(APointList : TPointList);
var
Index : Integer;
begin
Self.Clear;
for Index := 0 to APointList.Count - 1 do
begin
Self.Add(APointList[Index]);
end;
end;{Assign}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Delete PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Removes a TPoint at Index from the list.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TPointList.Delete(Index : Integer);
var
CurrentItem : PPoint;
NextItem : PPoint;
begin
if (MaxCount-ALLOCATE_SIZE) = (MsCount) then
begin
Shrink(ALLOCATE_SIZE);
end;
for Index := Index to MsCount - 1 do
begin
CurrentItem := MemStart;
inc(CurrentItem, Index);
NextItem := CurrentItem;
Inc(NextItem,1);
CurrentItem^ := NextItem^;
end;
Dec(MsCount, 1);
Dec(NextSlot, 1);
end;{Delete}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Clear PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Clears the list.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TPointList.Clear;
begin
// Free the allocated memory
if Assigned(MemStart) then
begin
FreeMem(MemStart);
MsCount := 0; // No Points in the list yet
MaxCount := 0; //no max size
MemStart := NIL;//no memory yet
end;
end;{Clear}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetValue FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Returns a TPoint at the index.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
function TPointList.GetValue(Index : Integer): TPoint;
var
PointPtr : PPoint;
begin
// Simply get the value at the given TPoint index position
PointPtr := MemStart;
Inc(PointPtr, Index); // Point to the index'th TPoint in storage
Result := PointPtr^; // And get the TPoint it points to
end;{GetValue}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetValue PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Sets a TPoint into the list at Index.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TPointList.SetValue(Index : Integer; Value : TPoint);
var
PointPtr : PPoint;
begin
// Simply set the value at the given TPoint index position
PointPtr := MemStart;
Inc(PointPtr, Index); // Point to the index'th TPoint in storage
PointPtr^ := Value;
end;{SetValue}
//------------------------------------------------------------------------------
end.
|
unit uI2XMainController;
interface
uses
uI2XOCR,
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
Menus,
ActnList,
ComCtrls,
StdCtrls,
ExtCtrls,
Grids,
Buttons,
GR32,
GR32_Image,
GR32_Layers,
GR32_RangeBars,
GR32_Filters,
GR32_Transforms,
GR32_Resamplers,
ImgList,
uStrUtil,
uFileDir,
uHashTable,
uReg,
uImage2XML,
uI2XTemplate,
mcmImage,
OmniXML,
ShellAPI,
StdActns,
uDWImage,
uI2XDLL,
JclStrings,
uI2XConstants,
//uI2XImageProcThread,
uI2XImageProcJobThread,
uI2XProductThread,
uI2XOCRProcThread,
uI2XProduct,
UIOCRProductViewDialog,
uI2XOptions,
uI2XPluginManager,
MapStream,
uI2XThreadBase,
uI2XMemMap,
uI2XUndo
;
type
TI2XMainUIController = class(TObject)
private
FBaseForm : TForm;
FOnStatusChange : TOnStatusChangeEvent;
FOnDebugMessage : TOnStatusChangeEvent;
FImageProcCache : TDWImage;
FImageProcCacheInst : string;
FImageProcCacheMMID : string;
DWImgView : TDWImage;
FMemoryMapManager : TI2XMemoryMapManager;
function getImageProcCacheInst: string;
procedure setImageProcCacheInst(const Value: string);
procedure OnImageProcJobEndCache( Sender : TObject; TaskID: string;
InstructionsCompleted: integer; ImageMMID: string);
function getTestsForImageAttrib: TDLLOCRTests;
public
ImageProcCacheUpdating : boolean;
LastSelectedTab : string;
ImgView: TImgView32;
ImageProcJobThread : TI2XImageProcJobThread;
ImageProcCacheThread : TI2XImageProcJobThread;
ProductJobThread : TI2XProductThread;
OCRJobThread : TI2XOCRProcJobThread;
FDLLOCRTestsForImageAttrib : TDLLOCRTests;
function ResolutionCheck( bmp: TBitMap32 ): boolean;
property DLLOCRTestsForImageAttrib : TDLLOCRTests read getTestsForImageAttrib;
property MemoryMapManager : TI2XMemoryMapManager read FMemoryMapManager write FMemoryMapManager;
procedure CacheImageExpire;
procedure CacheProcessedImage( dwimage : TDWImage ); overload;
procedure CacheProcessedImage( bmp : TBitMap32 ); overload;
//procedure TESTCompleteOCR(Sender: TObject);
procedure TESTImageProcBeforeOCR(Sender: TObject);
procedure ProcessImageInstructions(const InstructionList: TStringList; PerformOCRAfter : boolean = false; UtilizeCache : boolean = false );
procedure ProcessImageInstructionsPlusOCR(const InstructionList: TStringList );
procedure OCRImage( BMP32 : TBitmap32; const Template: CTemplate; const OCRRunType : TOCRRunType = otNormal; const ImageFileNameString : string = ''); overload;
procedure OCRImage( const ImageMMID : string; const Template : CTemplate; const OCRRunType : TOCRRunType = otNormal; const ImageFileNameString : string = '' ); overload;
procedure OCRImage( const odwImage : TDWImage; const Template : CTemplate; const OCRRunType : TOCRRunType = otNormal; const ImageFileNameString : string = '' ); overload;
procedure OCRImageSelection( DWImage: TDWImage; const Template: CTemplate); overload;
procedure OCRImageSelection( ImageMMID : string; const Template: CTemplate); overload;
procedure OCRImageSelection( BMP32 : TBitmap32; const Template: CTemplate); overload;
function OCRImageCheck( DWImage : TDWImage; DisplayPrompt : boolean = true ) : boolean; overload;
function OCRImageCheck( BMP32: TBitmap32; DisplayPrompt : boolean = true ) : boolean; overload;
//function GetOCRTests: TDLLOCRTests;
function getImageProcCache: TDWImage;
procedure OnImageProcJobEnd( Sender : TObject; TaskId : string; InstructionsCompleted : integer; ImageMMID : string );
procedure OnImageProcJobStart( Sender : TObject; TaskId : string; InstructionsCount : integer );
procedure OnJobError( Sender : TObject; TaskId : string; ErrorNo : integer; ErrorString: string );
procedure OnJobCacheError( Sender : TObject; TaskId : string; ErrorNo : integer; ErrorString: string );
procedure OnThreadTerminate( Sender : TObject );
procedure OnImageAttributesCalculated( Sender : TObject; const Boundary : TRect; const FirstCharacter : TI2XOCRItem );
procedure OnImageCacheJobEnd( Sender : TObject; TaskId : string; InstructionsCompleted : integer; ImageMMID : string );
procedure OnImageCacheJobStart( Sender : TObject; TaskId : string; InstructionsCount : integer );
procedure OnImageCacheStatusChange( Sender : TObject; TaskId : string; sStatusMessage : string );
procedure OnProductJobEnd( Sender : TObject; TaskId : string; TestsPerformed : integer; ReturnXML : string );
procedure OnProductJobStart( Sender : TObject; TaskId : string; TestsCount : integer );
procedure OnOCRJobEnd( Sender : TObject; TaskId : string; TestsPerformed : integer; ImageMMID : string );
procedure OnReturnXML( Sender : TObject; TaskId : string; ReturnXML : string );
procedure OnOCRJobStart( Sender : TObject; TaskId : string; TestsCount : integer );
procedure OnOCRSelectionJobEnd( Sender : TObject; TaskId : string; TestsPerformed : integer; ImageMMID : string );
procedure OnOCRSelectionReturnXML( Sender : TObject; TaskId : string; ReturnXML : string );
procedure OnOCRSelReturnXMLForFirstChar(Sender: TObject; TaskId,
ReturnXML: string);
procedure OnOCRSelectionJobStart( Sender : TObject; TaskId : string; TestsCount : integer );
procedure OnStatusChange( Sender : TObject; TaskId : string; sStatusMessage : string );
procedure OnDebugMessage( Sender : TObject; TaskId : string; sDebugMessage : string );
property OnStatusChangeEvent : TOnStatusChangeEvent read FOnStatusChange write FOnStatusChange;
property OnDebugMessageEvent : TOnStatusChangeEvent read FOnDebugMessage write FOnDebugMessage;
//property OCRTests : TDLLOCRTests read GetOCRTests;
property BaseForm : TForm read FBaseForm write FBaseForm;
property ImageProcCache : TDWImage read getImageProcCache;
property ImageProcCacheInst : string read getImageProcCacheInst write setImageProcCacheInst;
property ImageProcCacheMMID : string read FImageProcCacheMMID write FImageProcCacheMMID;
function TryObtainMMID(PossibleMMIDObject : TObject; var MMID : string ) : boolean;
procedure StatusMessage( sStatusMessage : string );
procedure DebugMessage( sDebugMessage : string );
constructor Create(BaseForm : TForm);
destructor Destroy; override;
end;
implementation
uses
UII2XBase;
{
I am breaking all sorts of object oriented encapsulation rules here,
but I can take comfort in knowing that it was because of a single
'abstract error' I received in the UI when I tried to 'properly' inherit
a base form that drove me to this abomination. Basically, the
main form can be referenced in this unit using fmain.
}
var
fMain : TI2XBaseUI;
{ TI2XMainUIController }
procedure TI2XMainUIController.CacheProcessedImage( dwimage : TDWImage );
var
sMemoryMapID : string;
InstructionList : TStringList;
sImageCacheOnDisk : string;
sImageCacheOnDiskInst : string;
Begin
try
InstructionList := TStringList.Create();
fMain.ActionListToStringList( fMain.getSelectedActionList(), InstructionList );
//if ( ImageProcCacheThread <> nil ) then
// ImageProcCacheThread.Free;
if ( InstructionList.Count = 0 ) then begin
if ( FImageProcCache <> nil ) then
FImageProcCache.Free;
FImageProcCache := TDWImage.Create( dwimage.Bitmap );
FImageProcCacheMMID := '';
if ( Integer(DebugLevel) >= 2 ) then StatusMessage( 'Image Cached' );
end else begin
sImageCacheOnDisk := fMain.Reg.Get('ImageCacheOnDisk', '');
sImageCacheOnDiskInst := fMain.Reg.Get('ImageCacheOnDiskInst', '');
if (
( sImageCacheOnDiskInst = fMain.ActionListAsString(fMain.getSelectedActionList())) and
( FileExists( sImageCacheOnDisk ) )
)
then begin
if ( FImageProcCache <> nil ) then begin
FImageProcCache.Free;
end;
if ( Integer(DebugLevel) >= 2 ) then StatusMessage( 'Reading Cached Image from Disk' );
FImageProcCache := TDWImage.Create();
FImageProcCache.LoadFromFile( sImageCacheOnDisk );
FImageProcCacheMMID := '';
//FImageProcCache.SaveToMemoryMap( FImageProcCacheMMID );
if ( Integer(DebugLevel) >= 2 ) then StatusMessage( 'Image Cached' );
end else begin
ImageProcCacheThread := TI2XImageProcJobThread.Create();
ImageProcCacheThread.FreeOnTerminate := true;
ImageProcCacheThread.TriggerOCRAfter := false;
ImageProcCacheThread.OnJobStartEvent := self.OnImageCacheJobStart;
ImageProcCacheThread.OnJobEndEvent := self.OnImageCacheJobEnd;
ImageProcCacheThread.OnJobErrorEvent := self.OnJobCacheError;
ImageProcCacheThread.OnStatusChangeEvent := OnImageCacheStatusChange;
ImageProcCacheThread.OnDebugMessageEvent := OnDebugMessage;
ImageProcCacheThread.DebugLevel := uImage2XML.DebugLevel;
if ( Integer(DebugLevel) >= 2 ) then DebugMessage(
'Image Res: X=' + IntToStr(dwimage.DPIX) + ' Y=' + IntToStr(dwimage.DPIY) );
sMemoryMapID := IMAGE_MEMMAP_HEADER+ '_CacheProcessedImage_' + RandomString();
FMemoryMapManager.DebugMessageText := 'At Cache Processed image.';
self.FMemoryMapManager.Write( sMemoryMapID, dwimage );
ImageProcCacheThread.ImageMemoryMapID := sMemoryMapID;
ImageProcCacheThread.InstructionList.Clear;
ImageProcCacheThread.InstructionList.AddStrings( InstructionList );
if ( FImageProcCache = nil ) then begin
FImageProcCache := TDWImage.Create();
end;
ImageProcCacheThread.Resume;
end;
end;
finally
if ( InstructionList <> nil ) then FreeAndNil( InstructionList );
end;
End;
function TI2XMainUIController.getImageProcCache: TDWImage;
begin
if ( FImageProcCache = nil ) then begin
FImageProcCache := TDWImage.Create;
end;
Result := FImageProcCache;
end;
function TI2XMainUIController.getImageProcCacheInst: string;
begin
Result := self.FImageProcCacheInst;
end;
function TI2XMainUIController.getTestsForImageAttrib: TDLLOCRTests;
var
i : integer;
begin
self.FDLLOCRTestsForImageAttrib.Clear;
Options.DLLOCRTestsComplete.CopyTo( FDLLOCRTestsForImageAttrib );
//self.FDLLOCRTestsForImageAttrib.CopyFrom( Options.DLLOCRTestsComplete );
for i := 0 to FDLLOCRTestsForImageAttrib.Count - 1 do begin
//To do image attributes, our tests need to be whole document OCRs, otherwise,
// how can we figure out where the boundaries and the first characters are?
FDLLOCRTestsForImageAttrib[i].SetOCRTest( ocrtNormalWhole, true );
FDLLOCRTestsForImageAttrib[i].SetOCRTest( ocrtNormalSliced, false );
FDLLOCRTestsForImageAttrib[i].SetOCRTest( ocrtInvertedWhole, true );
FDLLOCRTestsForImageAttrib[i].SetOCRTest( ocrtInvertedSliced, false );
end;
Result := FDLLOCRTestsForImageAttrib;
end;
function TI2XMainUIController.ResolutionCheck( bmp : TBitMap32 ) : boolean;
Begin
dbg( 'Resultion Check=' + IntToStr(bmp.BitmapInfo.bmiHeader.biXPelsPerMeter) );
Result := true;
End;
procedure TI2XMainUIController.ProcessImageInstructions(const InstructionList: TStringList; PerformOCRAfter : boolean ; UtilizeCache : boolean );
//procedure TI2XMainUIController.ProcessImageInstructions(const InstructionList : TStringList; PerformOCRAfter : boolean );
var
sMemoryMapID : string;
Begin
try
if (( ResolutionCheck( self.ImgView.Bitmap ) ) and ( InstructionList.Count > 0 )) then begin
if (( UtilizeCache ) and
( FImageProcCacheInst = fMain.ActionListAsString(fMain.getSelectedActionList() ))) then begin
fMain.txtActiveImage.Text := self.FImageProcCache.FileName;
fMain.ReLoadActiveImage();
end else begin
//if ( not (ImageProcJobThread = nil ) ) then
// ImageProcJobThread.Free;
fMain.pmnuExecuteActionList.Enabled := false;
fMain.pmnuProcInstAndOCR.Enabled := false;
ImageProcJobThread := TI2XImageProcJobThread.Create( self.ImgView.Bitmap );
ImageProcJobThread.FreeOnTerminate := true;
ImageProcJobThread.TriggerOCRAfter := PerformOCRAfter;
ImageProcJobThread.OnJobStartEvent := self.OnImageProcJobStart;
ImageProcJobThread.OnJobErrorEvent := self.OnJobError;
ImageProcJobThread.OnTerminate := self.OnThreadTerminate;
//ImageProcJobThread.OnJobEndEvent := self.OnImageProcJobEnd;
if ( UtilizeCache ) then
ImageProcJobThread.OnJobEndEvent := OnImageProcJobEndCache
else
ImageProcJobThread.OnJobEndEvent := self.OnImageProcJobEnd;
ImageProcJobThread.OnStatusChangeEvent := OnStatusChange;
ImageProcJobThread.OnDebugMessageEvent := OnDebugMessage;
ImageProcJobThread.DebugLevel := uImage2XML.DebugLevel;
sMemoryMapID := IMAGE_MEMMAP_HEADER+ '_ProcessImageInstructions_' + RandomString();
MemoryMapManager.Write( sMemoryMapID, ImageProcJobThread.DWImage );
ImageProcJobThread.ImageMemoryMapID := sMemoryMapID;
ImageProcJobThread.InstructionList.Clear;
ImageProcJobThread.InstructionList.AddStrings( InstructionList );
ImageProcJobThread.Resume;
end;
end;
finally
end;
End;
procedure TI2XMainUIController.ProcessImageInstructionsPlusOCR(
const InstructionList: TStringList);
var
sMemoryMapID : string;
Begin
fMain.Repaint;
try
if ( InstructionList.Count > 0 ) then begin
//if ( ImageProcJobThread <> nil ) then
// ImageProcJobThread.Free;
fMain.pmnuExecuteActionList.Enabled := false;
fMain.pmnuProcInstAndOCR.Enabled := false;
ProductJobThread := TI2XProductThread.Create( self.ImgView.Bitmap );
ProductJobThread.FreeOnTerminate := true;
ProductJobThread.OnJobStartEvent := self.OnOCRJobStart;
ProductJobThread.OnJobEndEvent := self.OnOCRJobEnd;
ProductJobThread.OnReturnXMLEvent := self.OnReturnXML;
ProductJobThread.OnJobErrorEvent := self.OnJobError;
ProductJobThread.OnStatusChangeEvent := OnStatusChange;
ProductJobThread.OnDebugMessageEvent := OnDebugMessage;
ProductJobThread.DebugLevel := DebugLevel;
sMemoryMapID := IMAGE_MEMMAP_HEADER+ '_ProcessImageInstructionsPlusOCR_' + RandomString();
MemoryMapManager.Write( sMemoryMapID, ProductJobThread.DWImage );
ProductJobThread.ImageMemoryMapID := sMemoryMapID;
ProductJobThread.InstructionList.Clear;
ProductJobThread.InstructionList.AddStrings( InstructionList );
ProductJobThread.OCREngineTests := Options.DLLOCRTestsComplete;
ProductJobThread.Template := fMain.Template;
ProductJobThread.Resume;
end;
finally
end;
End;
procedure TI2XMainUIController.setImageProcCacheInst(const Value: string);
begin
if (( FImageProcCacheInst <> Value ) and ( ImgView.Bitmap.Handle <> 0 )) then begin
self.CacheProcessedImage( ImgView.Bitmap );
FImageProcCacheInst := Value;
end;
end;
procedure TI2XMainUIController.OCRImage( const ImageMMID : string; const Template : CTemplate; const OCRRunType : TOCRRunType; const ImageFileNameString : string );
Begin
try
//if ( OCRJobThread <> nil ) then
// OCRJobThread.Free;
fMain.pmnuExecuteActionList.Enabled := false;
fMain.pmnuProcInstAndOCR.Enabled := false;
OCRJobThread := TI2XOCRProcJobThread.Create();
OCRJobThread.FreeOnTerminate := true;
OCRJobThread.OnJobStartEvent := self.OnOCRJobStart;
OCRJobThread.OnJobEndEvent := self.OnOCRJobEnd;
OCRJobThread.OnJobErrorEvent := self.OnJobError;
OCRJobThread.ImageFileName := ImageFileNameString;
OCRJobThread.OnStatusChangeEvent := OnStatusChange;
OCRJobThread.OnDebugMessageEvent := OnDebugMessage;
OCRJobThread.DebugLevel := DebugLevel;
//OCRJobThread.OCREngineTests := GetOCRTests;
if ( OCRRunType = otAnalysis ) then begin
OCRJobThread.OnImageAttributesCalculatedEvent := OnImageAttributesCalculated;
OCRJobThread.OCREngineTests := self.DLLOCRTestsForImageAttrib;
//OCRJobThread.OnReturnXMLEvent := self.OnReturnXML;
end else begin
OCRJobThread.OnReturnXMLEvent := self.OnReturnXML;
OCRJobThread.OCREngineTests := Options.DLLOCRTestsComplete;
end;
OCRJobThread.ImageMemoryMapID := ImageMMID;
OCRJobThread.Template := Template;
OCRJobThread.Resume;
finally
//if ( InstructionList <> nil ) then FreeAndNil( InstructionList );
end;
End;
procedure TI2XMainUIController.OCRImageSelection(ImageMMID: string;
const Template: CTemplate);
var
img : TDWImage;
begin
try
//if ( OCRJobThread <> nil ) then
// OCRJobThread.Free;
if ( integer(DebugLevel) >= 2 ) then begin
try
img := TDWImage.Create();
dbg( 'OCRImageSelection(): FMemoryMapManager.OpenMaps ' + FMemoryMapManager.OpenMapsAsString() );
FMemoryMapManager.DebugMessageText := 'At OCRImageSelection.';
FMemoryMapManager.Read( ImageMMID, img, false);
img.SaveToFile( AppTempDir + 'TEST_OCRSEL_1.BMP' );
finally
FreeAndNil( img );
end;
end;
fMain.pmnuExecuteActionList.Enabled := false;
fMain.pmnuProcInstAndOCR.Enabled := false;
OCRJobThread := TI2XOCRProcJobThread.Create();
OCRJobThread.FreeOnTerminate := true;
OCRJobThread.EnableJobEvents := true;
OCRJobThread.OnJobStartEvent := self.OnOCRSelectionJobStart;
OCRJobThread.OnJobEndEvent := self.OnOCRSelectionJobEnd;
if ( fMain.SelectedElement.isFirstChar ) then
OCRJobThread.OnReturnXMLEvent := self.OnOCRSelReturnXMLForFirstChar
else
OCRJobThread.OnReturnXMLEvent := self.OnOCRSelectionReturnXML;
OCRJobThread.OnJobErrorEvent := self.OnJobError;
OCRJobThread.OnStatusChangeEvent := OnStatusChange;
OCRJobThread.OnDebugMessageEvent := OnDebugMessage;
OCRJobThread.DebugLevel := DebugLevel;
//OCRJobThread.OCREngineTests := GetOCRTests;
OCRJobThread.OCREngineTests := Options.DLLOCRTestsSelect;
OCRJobThread.ImageMemoryMapID := ImageMMID;
OCRJobThread.Template := Template;
OCRJobThread.EnableOffsetCorrection := false;
OCRJobThread.Resume;
finally
end;
end;
procedure TI2XMainUIController.OCRImageSelection( DWImage : TDWImage; const Template : CTemplate );
var
sMemoryMapID : string;
Begin
try
MemoryMapManager.Write( sMemoryMapID, DWImage );
OCRImageSelection( sMemoryMapID, Template );
finally
end;
End;
procedure TI2XMainUIController.OCRImageSelection(BMP32: TBitmap32;
const Template: CTemplate);
var
sMemoryMapID : string;
Begin
try
if ( integer(DebugLevel) >= 2 ) then begin
BMP32.SaveToFile( AppTempDir + 'OCRImageSelection_BMP32.bmp' );
end;
MemoryMapManager.Write( sMemoryMapID, BMP32 );
OCRImageSelection( sMemoryMapID, Template );
finally
end;
End;
function TI2XMainUIController.OCRImageCheck( BMP32: TBitmap32; DisplayPrompt : boolean ) : boolean;
var
dw : TDWImage;
Begin
Result := false;
if ( BMP32 = nil ) then Exit;
try
dw := TDWImage.Create( BMP32 );
try
Result := OCRImageCheck( dw, DisplayPrompt );
except
end;
finally
FreeAndNil( dw );
end;
End;
function TI2XMainUIController.OCRImageCheck( DWImage : TDWImage; DisplayPrompt : boolean ) : boolean;
Begin
Result := false;
if ( DWImage = nil ) then Exit;
try
try
if ( DWImage.ColorCount <= 2 ) then
Result := true
//else if ( DWImage.ColorCount <= 4 ) then begin
// Result := (MessageDlg(FILE_EXISTS_TEXT, mtConfirmation, [mbYes, mbNo], 0) = mrYes);
else begin
if ( DisplayPrompt ) then
Result := (MessageDlg(OCR_COLOR_WARNING_TEXT, mtConfirmation, [mbYes, mbNo], 0) = mrYes)
else
self.DebugMessage( OCR_COLOR_WARNING );
end;
except
end;
finally
end;
End;
procedure TI2XMainUIController.TESTImageProcBeforeOCR(Sender: TObject);
Begin
End;
procedure TI2XMainUIController.OCRImage( const odwImage : TDWImage; const Template : CTemplate; const OCRRunType : TOCRRunType; const ImageFileNameString : string );
var
sMMID : string;
Begin
self.MemoryMapManager.Write( sMMID, odwImage );
//odwImage.SaveToMemoryMap( sMMID );
self.OCRImage( sMMID, Template, OCRRunType, ImageFileNameString );
End;
procedure TI2XMainUIController.OCRImage(BMP32: TBitmap32;
const Template: CTemplate; const OCRRunType : TOCRRunType;
const ImageFileNameString : string );
var
sMMID : string;
begin
self.MemoryMapManager.Write( sMMID, BMP32 );
self.OCRImage( sMMID, Template, OCRRunType, ImageFileNameString );
end;
procedure TI2XMainUIController.StatusMessage(sStatusMessage: string);
begin
self.OnStatusChange( self, '', sStatusMessage );
end;
procedure TI2XMainUIController.OnDebugMessage(Sender : TObject; TaskId, sDebugMessage: string);
begin
if ( Assigned( self.FOnDebugMessage ) ) then
self.FOnDebugMessage( Sender, TaskID, sDebugMessage );
end;
procedure TI2XMainUIController.CacheImageExpire();
var
sImageCacheOnDisk : string;
sImageCacheOnDiskInst : string;
Begin
sImageCacheOnDisk := AppTempDir + IMGPROC_CACHE;
sImageCacheOnDiskInst := fMain.ActionListAsString( fMain.getSelectedActionList() );
if ( FileExists( sImageCacheOnDisk ) ) then DeleteFile( sImageCacheOnDisk );
fMain.Reg['ImageCacheOnDisk'] := '';
fMain.Reg['ImageCacheOnDiskInst'] := '';
FImageProcCacheInst := '';
fMain.Boundary.Left:=0;
fMain.Boundary.Top:=0;
fMain.Boundary.Right:=0;
fMain.Boundary.Bottom:=0;
fmain.FirstChar.Clear;
//FImageProcCache.Free;
End;
procedure TI2XMainUIController.OnImageAttributesCalculated(Sender: TObject;
const Boundary: TRect; const FirstCharacter: TI2XOCRItem);
begin
fMain.Boundary := Boundary;
fMain.FirstChar.Assign( FirstCharacter );
fMain.TriggerUIEvents( false );
fMain.txtFirstCharX.Text := IntToStr( FirstCharacter.X );
fMain.txtFirstCharY.Text := IntToStr( FirstCharacter.Y );
fMain.txtFirstCharWidth.Text := IntToStr( FirstCharacter.Width );
fMain.txtFirstCharHeight.Text := IntToStr( FirstCharacter.Height );
fMain.txtXBound.Text := IntToStr( Boundary.Left );
fMain.txtYBound.Text := IntToStr( Boundary.Top );
if ( not fMain.template.Elements.ContainsKey( STANDARD_REGION_FIRST_CHAR ) ) then begin
fMain.CreateRegion( STANDARD_REGION_FIRST_CHAR );
end;
fMain.FirstCharRegionElement := fMain.template.getElement( STANDARD_REGION_FIRST_CHAR );
fMain.RegionAttributeChange( fMain.FirstCharRegionElement, FirstCharacter.AsRect );
if ( not fMain.template.Elements.ContainsKey( STANDARD_REGION_X_AXIS ) ) then begin
fMain.CreateRegion( STANDARD_REGION_X_AXIS );
end;
fMain.XAxisRegionElement := fMain.template.getElement( STANDARD_REGION_X_AXIS );
fMain.XAxisRegionElement.X := Boundary.Left;
if ( not fMain.template.Elements.ContainsKey( STANDARD_REGION_Y_AXIS ) ) then begin
fMain.CreateRegion( STANDARD_REGION_Y_AXIS );
end;
fMain.YAxisRegionElement := fMain.template.getElement( STANDARD_REGION_Y_AXIS );
fMain.YAxisRegionElement.Y := Boundary.Top;
fMain.DrawRegion( Sender, fMain.XAxisRegionElement, true, clGreen32 );
fMain.DrawRegion( Sender, fMain.YAxisRegionElement, true, clGreen32 );
if ( fMain.btnSearchFirstChar.Tag = 1 ) then begin
//SelectDocumentCorrection will display the region we want to display
fMain.SelectDocumentCorrection( fMain.rbtnFirstChar.tag );
fMain.SetZoom( 3 );
ImgView.ScrollToCenter( fMain.FirstCharRegionElement.x, fMain.FirstCharRegionElement.y );
fMain.btnSearchFirstChar.Tag := 0;
end;
if ( fMain.btnFindXYBoundaries.Tag = 1 ) then begin
//SelectDocumentCorrection will display the region we want to display
fMain.SelectDocumentCorrection( fMain.rbtnXYBoundary.tag );
fMain.SetZoom( 0.25 );
fMain.btnFindXYBoundaries.Tag := 0;
end;
fMain.TriggerUIEvents( true );
end;
procedure TI2XMainUIController.OnImageCacheJobEnd(Sender: TObject; TaskId: string;
InstructionsCompleted: integer; ImageMMID: string);
var
sImageCacheOnDisk : string;
sImageCacheOnDiskInst : string;
DPIX : integer;
begin
try
//if ( FImageProcCache <> nil ) then
// FImageProcCache.Free;
dbg( 'OnImageCacheJobEnd(): FMemoryMapManager.OpenMaps ' + FMemoryMapManager.OpenMapsAsString() );
FMemoryMapManager.DebugMessageText := 'At OnImageCacheJobEnd.';
self.MemoryMapManager.Read( ImageMMID, FImageProcCache );
self.FImageProcCacheMMID := ImageMMID;
sImageCacheOnDisk := AppTempDir + IMGPROC_CACHE;
sImageCacheOnDiskInst := fMain.ActionListAsString( fMain.getSelectedActionList() );
if ( fMain.ActiveImageIsLoaded ) then begin
DPIX := 0;
TryStrToInt( fMain.template.getData( 'x_dpi' ), DPIX );
if ( DPIX <> 0 ) then FImageProcCache.setDPI( DPIX );
end;
FImageProcCache.SaveToFile( sImageCacheOnDisk, true );
fMain.Reg['ImageCacheOnDisk'] := sImageCacheOnDisk;
fMain.Reg['ImageCacheOnDiskInst'] := sImageCacheOnDiskInst;
//self.ImageProcCache.ClearMemoryMap;
if ( Integer(DebugLevel) >= 2 ) then fMain.StatusMessage( 'Image Cached', pgDisable );
if ( Integer(DebugLevel) <= 1 ) then fMain.StatusMessage( 'Image Processed', pgDisable );
ImageProcCacheUpdating := false;
fMain.SetOCRMenuOptions( true );
finally
end;
end;
procedure TI2XMainUIController.OnImageCacheJobStart(Sender : TObject; TaskId: string;
InstructionsCount: integer);
begin
if ( Integer(DebugLevel) >= 2 ) then StatusMessage( 'Caching Image...' );
ImageProcCacheUpdating := true;
fMain.SetOCRMenuOptions( false );
end;
procedure TI2XMainUIController.OnImageCacheStatusChange(Sender : TObject; TaskId, sStatusMessage: string);
begin
if ( Integer(DebugLevel) >= 2 ) then StatusMessage( 'IMAGE CACHE: ' + sStatusMessage );
end;
procedure TI2XMainUIController.OnImageProcJobEndCache( Sender : TObject; TaskID : string; InstructionsCompleted: integer; ImageMMID : string );
var
sImageCacheOnDisk : string;
sImageCacheOnDiskInst : string;
DPIX : integer;
img : TDWImage;
begin
try
if ( FImageProcCache <> nil ) then
FImageProcCache.Free;
FImageProcCache := TDWImage.Create();
dbg( 'OnImageProcJobEndCache(): FMemoryMapManager.OpenMaps ' + FMemoryMapManager.OpenMapsAsString() );
FMemoryMapManager.DebugMessageText := 'At OnImageProcJobEndCache.';
self.FMemoryMapManager.Read( ImageMMID, FImageProcCache );
//FImageProcCache.LoadFromMemoryMap( ImageMMID );
self.FImageProcCacheMMID := ImageMMID;
sImageCacheOnDisk := AppTempDir + IMGPROC_CACHE;
sImageCacheOnDiskInst := fMain.ActionListAsString( fMain.getSelectedActionList() );
if ( fMain.ActiveImageIsLoaded ) then begin
DPIX := 0;
TryStrToInt( fMain.template.getData( 'x_dpi' ), DPIX );
if ( DPIX <> 0 ) then FImageProcCache.setDPI( DPIX );
end;
FImageProcCache.SaveToFile( sImageCacheOnDisk, true );
fMain.Reg['ImageCacheOnDisk'] := sImageCacheOnDisk;
fMain.Reg['ImageCacheOnDiskInst'] := sImageCacheOnDiskInst;
if ( Integer(DebugLevel) >= 2 ) then fMain.StatusMessage( 'Image Cached', pgDisable );
if ( Integer(DebugLevel) <= 1 ) then fMain.StatusMessage( 'Image Processed', pgDisable );
ImageProcCacheUpdating := false;
try
img := TDWImage.Create();
FImageProcCache.CopyTo( img );
undo.Add( ImgView );
self.ImgView.Bitmap.Assign( img.BitMap );
fMain.txtActiveImage.Text := self.FImageProcCache.FileName;
finally
FreeAndNil( img );
end;
fMain.SetOCRMenuOptions( true );
finally
end;
End;
procedure TI2XMainUIController.OnImageProcJobEnd( Sender : TObject; TaskID : string; InstructionsCompleted: integer; ImageMMID : string );
var
img : TDWImage;
bCloseMapAfterRead : boolean;
begin
try
img := TDWImage.Create();
bCloseMapAfterRead := not self.ImageProcJobThread.TriggerOCRAfter;
dbg( 'OnImageProcJobEnd(): FMemoryMapManager.OpenMaps ' + FMemoryMapManager.OpenMapsAsString() );
FMemoryMapManager.DebugMessageText := 'At OnImageProcJobEnd. bCloseMapAfterRead=' + BoolToStr(bCloseMapAfterRead);
Self.FMemoryMapManager.Read( ImageMMID, img, bCloseMapAfterRead );
undo.Add( ImgView );
self.ImgView.Bitmap.Assign( img.BitMap );
finally
FreeAndNil( img );
end;
if ( not self.ImageProcJobThread.TriggerOCRAfter ) then begin
fMain.Cursor := fMain.FCursorSave;
fMain.SetOCRMenuOptions( true );
fMain.StatusMessage( 'Image Processing Completed', pgDisable );
end else begin
fMain.StatusMessage( 'Image has been Processed.. beginning OCR', pgIgnore, 'Performing OCR' );
Self.OCRImage(ImageMMID, fMain.template, otNormal, fMain.txtActiveImage.Text );
end;
end;
procedure TI2XMainUIController.OnImageProcJobStart(Sender : TObject; TaskID : string; InstructionsCount: integer);
begin
fMain.SetOCRMenuOptions( false );
fMain.FCursorSave := fMain.Cursor;
fMain.Cursor := crHourGlass;
fMain.StatusMessage( 'Begin Image Processing...', pgStart, 'Processing Image' );
ShowCursor(TRUE);
Application.ProcessMessages;
end;
procedure TI2XMainUIController.OnJobCacheError(Sender : TObject; TaskId: string; ErrorNo: integer;
ErrorString: string);
begin
Dbg('The Image could not be cached... ignoring image cache request');
end;
procedure TI2XMainUIController.OnJobError(Sender : TObject; TaskId : string; ErrorNo: integer;
ErrorString: string);
var
sMMID : string;
begin
fMain.ErrorDisplay( '', ErrorString );
fMain.StatusMessage( ErrorString, pgDisable );
if ( TryObtainMMID( Sender, sMMID ) ) then begin
FMemoryMapManager.DebugMessageText := 'At OnJobError.';
FMemoryMapManager.Delete( sMMID );
end;
end;
procedure TI2XMainUIController.OnThreadTerminate(Sender: TObject);
begin
dbg('OnThreadTerminate');
end;
function TI2XMainUIController.TryObtainMMID(PossibleMMIDObject : TObject; var MMID : string ) : boolean;
var
thd : TI2XThreadedImageJob;
Begin
Result := false;
MMID := '';
try
thd := TI2XThreadedImageJob( PossibleMMIDObject );
MMID := thd.ImageMemoryMapID;
Result := true;
except
Result := false;
end;
End;
procedure TI2XMainUIController.OnOCRJobEnd( Sender : TObject; TaskID : string; TestsPerformed: integer; ImageMMID : string );
var
sMMID : string;
begin
fMain.StatusMessage( 'Image Processing Completed', pgDisable );
if ( TryObtainMMID( Sender, sMMID ) ) then begin
FMemoryMapManager.DebugMessageText := 'At OnOCRJobEnd.';
FMemoryMapManager.Delete( sMMID );
end;
end;
procedure TI2XMainUIController.OnOCRJobStart(Sender : TObject; TaskID : string; TestsCount: integer);
begin
fMain.SetOCRMenuOptions( false );
fMain.FCursorSave := fMain.Cursor;
fMain.Cursor := crHourGlass;
fMain.StatusMessage( 'Begining OCR', pgStart, 'Performing OCR' );
ShowCursor(TRUE);
Application.ProcessMessages;
end;
procedure TI2XMainUIController.OnOCRSelectionReturnXML(Sender : TObject; TaskId: string;
ReturnXML: string);
Begin
fMain.Cursor := fMain.FCursorSave;
fMain.SetOCRMenuOptions( true );
if ( fMain.dlgOCRProductView <> nil ) then
fMain.dlgOCRProductView.free;
fMain.dlgOCRProductView := TOCRProductViewDialog.Create( fMain );
fMain.dlgOCRProductView.DisplayXML( ReturnXML );
//fMain.StatusMessage( 'OCR of Selection Completed', pgDisable );
End;
procedure TI2XMainUIController.OnOCRSelReturnXMLForFirstChar(Sender : TObject; TaskId: string;
ReturnXML: string);
Begin
fMain.Cursor := fMain.FCursorSave;
fMain.SetOCRMenuOptions( true );
if ( fMain.dlgOCRProductView <> nil ) then
fMain.dlgOCRProductView.free;
fMain.dlgOCRProductView := TOCRProductViewDialog.Create( fMain );
fMain.dlgOCRProductView.DisplayXML( ReturnXML );
End;
procedure TI2XMainUIController.OnOCRSelectionJobEnd(Sender : TObject; TaskId: string;
TestsPerformed: integer; ImageMMID: string);
var
sMMID : string;
begin
fMain.StatusMessage( 'Begin OCR of Selected Region', pgDisable );
if ( TryObtainMMID( Sender, sMMID ) ) then begin
FMemoryMapManager.DebugMessageText := 'At OnOCRSelectionJobEnd.';
FMemoryMapManager.Delete( sMMID );
end;
end;
procedure TI2XMainUIController.OnOCRSelectionJobStart(Sender : TObject; TaskId: string;
TestsCount: integer);
begin
fMain.SetOCRMenuOptions( false );
fMain.FCursorSave := fMain.Cursor;
fMain.Cursor := crHourGlass;
StatusMessage( 'Begin OCR of Selected Region' );
ShowCursor(TRUE);
Application.ProcessMessages;
ImageProcCacheInst := fMain.ActionListAsString( fMain.SelectedActionList );
end;
procedure TI2XMainUIController.OnProductJobEnd(Sender : TObject; TaskId: string; TestsPerformed: integer;
ReturnXML: string);
var
sMMID : string;
begin
try
fMain.Cursor := fMain.FCursorSave;
fMain.SetOCRMenuOptions( true );
if ( TryObtainMMID( Sender, sMMID ) ) then begin
FMemoryMapManager.DebugMessageText := 'At OnProductJobEnd.';
FMemoryMapManager.Delete( sMMID );
end;
if ( Integer(DebugLevel) > 1 ) then WriteLog( ReturnXML, 'C:\Dark\pascal\Image2XML\templates\Result.xml' );
fMain.StatusMessage( 'Image Processing Completed', pgDisable );
finally
end;
end;
Procedure TI2XMainUIController.OnProductJobStart(Sender : TObject; TaskId: string; TestsCount: integer);
Begin
fMain.SetOCRMenuOptions( false );
fMain.FCursorSave := fMain.Cursor;
fMain.Cursor := crHourGlass;
fMain.StatusMessage( 'Begin Image Processing and OCR of image...', pgStart, 'Image Processing and OCR' );
ShowCursor(TRUE);
Application.ProcessMessages;
End;
procedure TI2XMainUIController.OnReturnXML(Sender: TObject; TaskId,
ReturnXML: string);
begin
fMain.Cursor := fMain.FCursorSave;
fMain.SetOCRMenuOptions( true );
if ( fMain.dlgOCRProductView <> nil ) then
fMain.dlgOCRProductView.free;
fMain.dlgOCRProductView := TOCRProductViewDialog.Create( fMain );
fMain.dlgOCRProductView.DisplayXML( ReturnXML );
end;
Procedure TI2XMainUIController.OnStatusChange(Sender : TObject; TaskId, sStatusMessage: string);
Begin
if ( Assigned( FOnStatusChange ) ) then
FOnStatusChange( Sender, TaskId, sStatusMessage );
End;
procedure TI2XMainUIController.CacheProcessedImage(bmp: TBitMap32);
begin
if ( DWImgView <> nil ) then
DWImgView.Free;
DWImgView := TDWImage.Create( bmp );
self.CacheProcessedImage( DWImgView );
end;
Constructor TI2XMainUIController.Create(BaseForm: TForm);
Begin
self.FBaseForm := BaseForm;
fMain := TI2XBaseUI(BaseForm);
FDLLOCRTestsForImageAttrib := TDLLOCRTests.Create();
End;
procedure TI2XMainUIController.DebugMessage(sDebugMessage: string);
begin
self.OnDebugMessage( Self, '', sDebugMessage );
end;
destructor TI2XMainUIController.Destroy;
Begin
if ( FImageProcCache <> nil ) then FreeAndNil( FImageProcCache );
if ( FDLLOCRTestsForImageAttrib <> nil ) then FreeAndNil( FDLLOCRTestsForImageAttrib );
//The following should have been freed when it ran
//if ( ImageProcJobThread <> nil ) then FreeAndNil( ImageProcJobThread );
//if ( OCRJobThread <> nil ) then FreeAndNil( OCRJobThread );
//if ( ProductJobThread <> nil ) then FreeAndNil( ProductJobThread );
//if ( ImageProcCacheThread <> nil ) then FreeAndNil( ImageProcCacheThread );
//if ( FDLLOCRTests <> nil ) then FreeAndNil( FDLLOCRTests );
if ( DWImgView <> nil ) then FreeAndNil( DWImgView );
End;
END.
|
unit MultiRBTree;
interface
uses
Classes, RBTree;
type
TStrSortCompare = function (const Item1: String; const Item2: String): Integer;
TMultiColor = (clRed, clBlack);
TMultiRBNodeP = ^TMultiRBNode;
TMultiRBNode = record
Key: String;
Left, Right, Parent: TMultiRBNodeP;
Color: TMultiColor;
Duplicates: TRBTree;
// Data: Pointer;
end;
TMultiRBTree = class
private
Root: TMultiRBNodeP;
Leftmost: TMultiRBNodeP;
Rightmost: TMultiRBNodeP;
CompareFunc: TStrSortCompare;
procedure RotateLeft(var x: TMultiRBNodeP);
procedure RotateRight(var x: TMultiRBNodeP);
function Minimum(var x: TMultiRBNodeP): TMultiRBNodeP;
function Maximum(var x: TMultiRBNodeP): TMultiRBNodeP;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Delete(Z: TMultiRBNodeP; Data: Pointer);
function Find(Key: String): TMultiRBNodeP;
function Add(Key: String; Data: Pointer): TMultiRBNodeP;
public
property First: TMultiRBNodeP read leftmost;
property Last: TMultiRBNodeP read rightmost;
end;
procedure RBInc(var x: TMultiRBNodeP);
implementation
procedure RBInc(var x: TMultiRBNodeP);
var
y: TMultiRBNodeP;
begin
if (x^.Right <> nil) then
begin
x := x^.Right;
while (x^.Left <> nil) do
begin
x := x^.Left;
end;
end
else
begin
y := x^.Parent;
while (x = y^.Right) do
begin
x := y;
y := y^.Parent;
end;
if (x^.Right <> y) then
x := y;
end
end;
{ Pre: x <> first }
procedure RBDec(var x: TMultiRBNodeP);
var
y: TMultiRBNodeP;
begin
if (x^.left <> nil) then
begin
y := x^.Left;
while (y^.Right <> nil) do
begin
y := y^.Right;
end;
x := y;
end
else
begin
y := x^.Parent;
while (x = y^.Left) do
begin
x := y;
y := y^.Parent;
end;
x := y;
end
end;
function CompareStr(const Item1: String; const Item2: String): Integer;
begin
if (Item1 < Item2) then begin
Result := -1;
end
else if (Item1 = Item2) then
begin
Result := 0;
end
else
begin
Result := 1;
end
end;
constructor TMultiRBTree.Create;
begin
inherited Create;
CompareFunc := CompareStr;
Root := nil;
Leftmost := nil;
Rightmost := nil;
end;
destructor TMultiRBTree.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure fast_erase(x: TMultiRBNodeP);
begin
if (x^.Left <> nil) then fast_erase(x^.Left);
if (x^.Right <> nil) then fast_erase(x^.Right);
x^.Duplicates.Free;
dispose(x);
end;
procedure TMultiRBTree.Clear;
begin
if (Root <> nil) then
fast_erase(Root);
Root := nil;
Leftmost := nil;
Rightmost := nil;
end;
function TMultiRBTree.Find(Key: String): TMultiRBNodeP;
var
cmp: integer;
begin
Result := Root;
while (Result <> nil) do
begin
cmp := CompareFunc(Result^.Key, key);
if cmp < 0 then
begin
Result := Result^.right;
end
else if cmp > 0 then
begin
Result := Result^.left;
end
else
begin
break;
end;
end;
end;
procedure TMultiRBTree.RotateLeft(var x: TMultiRBNodeP);
var
y: TMultiRBNodeP;
begin
y := x^.right;
x^.right := y^.left;
if (y^.left <> nil) then
begin
y^.left^.parent := x;
end;
y^.parent := x^.parent;
if (x = Root) then
begin
Root := y;
end
else if (x = x^.parent^.left) then
begin
x^.parent^.left := y;
end
else
begin
x^.parent^.right := y;
end;
y^.left := x;
x^.parent := y;
end;
procedure TMultiRBTree.RotateRight(var x: TMultiRBNodeP);
var
y: TMultiRBNodeP;
begin
y := x^.left;
x^.left := y^.right;
if (y^.right <> nil) then
begin
y^.right^.parent := x;
end;
y^.parent := x^.parent;
if (x = Root) then
begin
Root := y;
end
else if (x = x^.parent^.right) then
begin
x^.parent^.right := y;
end
else
begin
x^.parent^.left := y;
end;
y^.right := x;
x^.parent := y;
end;
function TMultiRBTree.Minimum(var x: TMultiRBNodeP): TMultiRBNodeP;
begin
Result := x;
while (Result^.left <> nil) do
Result := Result^.left;
end;
function TMultiRBTree.Maximum(var x: TMultiRBNodeP): TMultiRBNodeP;
begin
Result := x;
while (Result^.right <> nil) do
Result := Result^.right;
end;
function TMultiRBTree.Add(Key: String; Data: Pointer): TMultiRBNodeP;
var
x, y, z, zpp: TMultiRBNodeP;
cmp: Integer;
begin
z := New(TMultiRBNodeP);
{ Initialize fields in new node z }
z^.Key := key;
z^.Left := nil;
z^.Right := nil;
z^.Color := clRed;
z^.Duplicates := TRBTree.Create;
z^.Duplicates.Add(data, data);
Result := z;
{ Maintain leftmost and rightmost nodes }
if ((leftmost = nil) or (compareFunc(key, leftmost^.Key) < 0)) then
begin
leftmost := z;
end;
if ((rightmost = nil) or (compareFunc(rightmost^.Key, key) < 0)) then
begin
rightmost := z;
end;
{ Insert node z }
y := nil;
x := Root;
while (x <> nil) do
begin
y := x;
cmp := compareFunc(key, x^.Key);
if (cmp < 0) then
begin
x := x^.left;
end
else if (cmp > 0) then
begin
x := x^.right;
end
else
begin
{ Value already exists in tree. }
x^.Duplicates.Add(data, data);
Result := x;
z^.Duplicates.Free;
dispose(z);
exit;
end;
end;
z^.parent := y;
if (y = nil) then
begin
Root := z;
end
else if (compareFunc(key, y^.Key) < 0) then
begin
y^.left := z;
end
else
begin
y^.right := z;
end;
{ Rebalance tree }
while ((z <> Root) and (z^.parent^.color = clRed)) do
begin
zpp := z^.parent^.parent;
if (z^.parent = zpp^.left) then
begin
y := zpp^.right;
if ((y <> nil) and (y^.color = clRed)) then
begin
z^.parent^.color := clBlack;
y^.color := clBlack;
zpp^.color := clRed;
z := zpp;
end
else
begin
if (z = z^.parent^.right) then
begin
z := z^.parent;
rotateLeft(z);
end;
z^.parent^.color := clBlack;
zpp^.color := clRed;
rotateRight(zpp);
end;
end
else
begin
y := zpp^.left;
if ((y <> nil) and (y^.color = clRed)) then
begin
z^.parent^.color := clBlack;
y^.color := clBlack;
zpp^.color := clRed;
z := zpp;
end
else
begin
if (z = z^.parent^.left) then
begin
z := z^.parent;
rotateRight(z);
end;
z^.parent^.color := clBlack;
zpp^.color := clRed;
rotateLeft(zpp);
end;
end;
end;
Root^.color := clBlack;
end;
procedure TMultiRBTree.Delete(Z: TMultiRBNodeP; Data: Pointer);
var
w, x, y, x_parent: TMultiRBNodeP;
tmpcol: TMultiColor;
begin
if Z = NIL then Exit;
if Z^.Duplicates.Count > 1 then
begin
Z^.Duplicates.Delete(Z^.Duplicates.Find(Data));
Exit;
end;
y := z;
x := nil;
x_parent := nil;
if (y^.left = nil) then
begin { z has at most one non-null child. y = z. }
x := y^.right; { x might be null. }
end
else
begin
if (y^.right = nil) then
begin { z has exactly one non-null child. y = z. }
x := y^.left; { x is not null. }
end
else
begin
{ z has two non-null children. Set y to }
y := y^.right; { z's successor. x might be null. }
while (y^.left <> nil) do begin
y := y^.left;
end;
x := y^.right;
end;
end;
if (y <> z) then
begin
{ "copy y's sattelite data into z" }
{ relink y in place of z. y is z's successor }
z^.left^.parent := y;
y^.left := z^.left;
if (y <> z^.right) then
begin
x_parent := y^.parent;
if (x <> nil) then
begin
x^.parent := y^.parent;
end;
y^.parent^.left := x; { y must be a child of left }
y^.right := z^.right;
z^.right^.parent := y;
end
else
begin
x_parent := y;
end;
if (Root = z) then
begin
Root := y;
end
else if (z^.parent^.left = z) then
begin
z^.parent^.left := y;
end else begin
z^.parent^.right := y;
end;
y^.parent := z^.parent;
tmpcol := y^.color;
y^.color := z^.color;
z^.color := tmpcol;
y := z;
{ y now points to node to be actually deleted }
end
else
begin { y = z }
x_parent := y^.parent;
if (x <> nil) then
begin
x^.parent := y^.parent;
end;
if (Root = z) then
begin
Root := x;
end
else
begin
if (z^.parent^.left = z) then
begin
z^.parent^.left := x;
end
else
begin
z^.parent^.right := x;
end;
end;
if (leftmost = z) then
begin
if (z^.right = nil) then
begin { z^.left must be null also }
leftmost := z^.parent;
end else
begin
leftmost := minimum(x);
end;
end;
if (rightmost = z) then
begin
if (z^.left = nil) then
begin { z^.right must be null also }
rightmost := z^.parent;
end
else
begin { x == z^.left }
rightmost := maximum(x);
end;
end;
end;
{ Rebalance tree }
if (y^.color = clBlack) then
begin
while ((x <> Root) and ((x = nil) or (x^.color = clBlack))) do
begin
if (x = x_parent^.left) then
begin
w := x_parent^.right;
if (w^.color = clRed) then
begin
w^.color := clBlack;
x_parent^.color := clRed;
rotateLeft(x_parent);
w := x_parent^.right;
end;
if (((w^.left = nil) or
(w^.left^.color = clBlack)) and
((w^.right = nil) or
(w^.right^.color = clBlack))) then begin
w^.color := clRed;
x := x_parent;
x_parent := x_parent^.parent;
end
else
begin
if ((w^.right = nil) or (w^.right^.color = clBlack)) then
begin
w^.left^.color := clBlack;
w^.color := clRed;
rotateRight(w);
w := x_parent^.right;
end;
w^.color := x_parent^.color;
x_parent^.color := clBlack;
if (w^.right <> nil) then
begin
w^.right^.color := clBlack;
end;
rotateLeft(x_parent);
x := Root; { break; }
end
end
else
begin
{ same as above, with right <^. left. }
w := x_parent^.left;
if (w^.color = clRed) then begin
w^.color := clBlack;
x_parent^.color := clRed;
rotateRight(x_parent);
w := x_parent^.left;
end;
if (((w^.right = nil) or
(w^.right^.color = clBlack)) and
((w^.left = nil) or
(w^.left^.color = clBlack))) then begin
w^.color := clRed;
x := x_parent;
x_parent := x_parent^.parent;
end else begin
if ((w^.left = nil) or (w^.left^.color = clBlack)) then begin
w^.right^.color := clBlack;
w^.color := clRed;
rotateLeft(w);
w := x_parent^.left;
end;
w^.color := x_parent^.color;
x_parent^.color := clBlack;
if (w^.left <> nil) then begin
w^.left^.color := clBlack;
end;
rotateRight(x_parent);
x := Root; { break; }
end;
end;
end;
if (x <> nil) then begin
x^.color := clBlack;
end;
end;
y^.Duplicates.Free;
dispose(y);
end;
end.
|
unit uRecycleBinListOperation;
{$mode ObjFPC}{$H+}
interface
uses
Classes, SysUtils,
uFileSystemListOperation,
uRecycleBinFileSource,
uFileSource;
type
{ TRecycleBinListOperation }
TRecycleBinListOperation = class(TFileSystemListOperation)
public
constructor Create(aFileSource: IFileSource; aPath: String); override;
procedure MainExecute; override;
end;
implementation
uses
Windows, ShlObj, ComObj, JwaShlGuid, Variants, DCOSUtils, DCDateTimeUtils,
uFile, uShellFolder, uShlObjAdditional, uShowMsg;
const
SID_DISPLACED = '{9B174B33-40FF-11d2-A27E-00C04FC30871}';
SCID_OriginalLocation: TSHColumnID = ( fmtid: SID_DISPLACED; pid: PID_DISPLACED_FROM );
SCID_DateDeleted: TSHColumnID = ( fmtid: SID_DISPLACED; pid: PID_DISPLACED_DATE );
{ TRecycleBinListOperation }
constructor TRecycleBinListOperation.Create(aFileSource: IFileSource;
aPath: String);
begin
FFiles := TFiles.Create(aPath);
inherited Create(aFileSource, aPath);
end;
procedure TRecycleBinListOperation.MainExecute;
var
AFile: TFile;
NumIDs: LongWord = 0;
AFolder: IShellFolder2;
EnumIDList: IEnumIDList;
Attr: TFileAttributeData;
DesktopFolder: IShellFolder;
PIDL, TrashPIDL: PItemIDList;
begin
FFiles.Clear;
try
OleCheckUTF8(SHGetDesktopFolder(DesktopFolder));
OleCheckUTF8(SHGetFolderLocation(0, CSIDL_BITBUCKET, 0, 0, {%H-}TrashPIDL));
OleCheckUTF8(DesktopFolder.BindToObject(TrashPIDL, nil, IID_IShellFolder2, Pointer(AFolder)));
OleCheckUTF8(AFolder.EnumObjects(0, SHCONTF_FOLDERS or SHCONTF_NONFOLDERS or SHCONTF_INCLUDEHIDDEN, EnumIDList));
while EnumIDList.Next(1, PIDL, NumIDs) = S_OK do
begin
CheckOperationState;
aFile:= TRecycleBinFileSource.CreateFile(Path);
AFile.FullPath:= GetDisplayName(AFolder, PIDL, SHGDN_NORMAL);
AFile.LinkProperty.LinkTo:= GetDisplayName(AFolder, PIDL, SHGDN_FORPARSING);
if mbFileGetAttr(AFile.LinkProperty.LinkTo, Attr) then
begin
AFile.Size:= Attr.Size;
AFile.Attributes:= Attr.Attr;
AFile.CreationTime:= WinFileTimeToDateTime(Attr.PlatformTime);
AFile.LastAccessTime:= WinFileTimeToDateTime(Attr.LastAccessTime);
AFile.ModificationTime:= WinFileTimeToDateTime(Attr.LastWriteTime);
AFile.CommentProperty.Value:= GetDetails(AFolder, PIDL, SCID_OriginalLocation);
AFile.ChangeTime:= VariantTimeToDateTime(VarToDateTime(GetDetails(AFolder, PIDL, SCID_DateDeleted)));
end;
FFiles.Add(AFile);
end;
except
on E: Exception do msgError(Thread, E.Message);
end;
end;
end.
|
{+--------------------------------------------------------------------------+
| Component: TPowerPanel
| Created: 2/28/96 9:57:43 PM
| Author: John Panagia
| Company: Strategic Applications
| Copyright 1996, all rights reserved.
| Description: PowerPanel for Delphi
| Version: 2.00
| Modification History:
+--------------------------------------------------------------------------+
New for version 2.00:
1. Fixed the problem of a panel being moved out of sight. Now PowerPanels
can only be moved within it's parents area. Will optionally beep when
an attempt to move a panel beyond its parent boundries.
2. New method: Rollitup; Will Rollup or close a parent container of a PowerPanel.
This new method will be called automatically when you right click
on a PowerPanel that has it's align set to altop, albottom, alright or alleft.
If you enable InILogging the state of the panel will be maintained.
3. New method: ResetIni(inifilename: string);
Use this method to reset the INI file setting for this panel to the design time values.
This can be performed on multiple panels by using the globalattributes component editor.
New method: EraseIni(inifilename: string);
Use this method to erase the INI file setting for this panel. This can be performed
on multiple panels by using the globalattributes component editor.
4. New property Attributes.AllowBeeps: boolean;
This property allows you to enable/disable the beeping functionality
for boundry violations.
5. New Property Attributes.AllowRollups: boolean;
This property allows you to enable/disable the rollup functionality.
+--------------------------------------------------------------------------+}
{if you would like to have a version of powerpanel inherit from something other
than TPanel, you must complete the following steps:
1. Make a copy of this unit under another name.
2. Edit the new unit and disable the ($define InheritsFromTPanel)
3. Do a global replace on 'PowerPanel' to something unique like 'PowerMemo',
if you were making a version for a memo component.
4. Change class reference of 'TCustomPanel' to class you would like to inherit,
for example, TMemo, if you were creating a PowerMemo.
5. Set up a registration unit for the new component.
6. Install the new component.
The above steps have been tested on a few components in the VCL, If you decide to
create components in this manner, keep in mind that PowerPanel was originally
designed to work with TPanel. This ability was added because a few users had requested
this functionality. Any components you create this way, will have to be recreated with
each new version of PowerPanel. I had no choice but to take out some features that appear
in The standard PowerPanel component, such as the component editors, the about property and
all of the container logic(hiding and showing of children and siblings).
Also one major problem with this, are mouse event conflicts, for example a listbox interputs
a mouse click as a way of selecting an item, but PowerPanel will attempt to move or
resize the component. }
unit Ppmain;
{define ppdemo}
{remove the $ from the following define if you want create a new PowerComponent}
{$define InheritsFromTPanel}
interface
uses
{$ifdef ppdemo}pputil,{$endif}
SysUtils, WinTypes, WinProcs,
Messages, Classes, Graphics, Controls,
buttons, Forms, Dialogs, menus, filectrl,
extctrls,
stdctrls, toolintf, DsgnIntf, inifiles;
type
TDirection = (DirNone, DirRight, DirLeft, DirTop, DirBottom, DirTL, DirTR, DirBL, DirBR, DirMove);
TPanelState = (psOpen, psClosed, psLocked);
TAttributes = class(TPersistent)
private
FOnGridChanged: TNotifyEvent;
FMinWidth: integer;
FMaxWidth: integer;
FMinHeight: integer;
FMaxHeight: integer;
FSizableTop: boolean;
FSizableBottom: boolean;
FSizableLeft: boolean;
FSizableRight: boolean;
FEdgeOffset: integer;
FMovable: boolean;
FMovableVert: boolean;
FMovableHorz: boolean;
FMoveParent: boolean;
FMoveColor: TColor;
FHideChildren: boolean;
FHideSiblings: boolean;
FStayVisible: boolean;
FTrackPositions: boolean;
FTrackPanel: TPanel;
FCursorMoving: TCursor;
FCursorSizingNS: TCursor;
FCursorSizingEW: TCursor;
FIniLog: Boolean;
FIniFileName: String;
FIniSectionName: String;
FiniPrefix: String;
FAllowRollup: boolean;
FParentOpen: boolean;
FAllowBeeps: boolean;
FGridAlignment: integer;
protected
procedure SetGridAlignment(value: integer);
public
{ property ParentOpen: boolean read FParentOpen write FParentOpen;}
property OnGridChanged: TNotifyEvent read FOnGridChanged write FOnGridChanged;
procedure Reset;
published
property MinWidth: integer read FMinWidth write FMinWidth;
property MaxWidth: integer read FMaxWidth write FMaxWidth;
property MinHeight: integer read FMinHeight write FMinHeight;
property MaxHeight: integer read FMaxHeight write FMaxHeight;
property SizableTop: boolean read FSizableTop write FSizableTop;
property SizableBottom: boolean read FSizableBottom write FSizableBottom;
property SizableLeft: boolean read FSizableLeft write FSizableLeft;
property SizableRight: boolean read FSizableRight write FSizableRight;
property Movable: boolean read fmovable write fmovable;
property MovableHorz: boolean read FMovableHorz write FMovableHorz default true ;
property MovableVert: boolean read FMovableVert write FMovableVert default true;
property MoveParent: boolean read fmoveparent write fmoveparent;
property MoveColor: TColor read FMoveColor write FMoveColor;
property HideChildren: boolean read fHideChildren write fHideChildren;
property HideSiblings: boolean read fHideSiblings write fHideSiblings;
property StayVisible: boolean read FStayVisible write FStayVisible;
property TrackPositions: boolean read FTrackPositions write FTrackPositions;
property TrackPanel: TPanel read FTrackPanel write FTrackpanel;
property EdgeOffset: integer read FEdgeOffset write FEdgeOffset;
property CursorMoving: TCursor read FCursorMoving write FCursorMoving;
property CursorSizingNS: TCursor read FCursorSizingNS write FCursorSizingNS;
property CursorSizingEW: TCursor read FCursorSizingEW write FCursorSizingEW;
property IniLog: Boolean read fIniLog write finiLog;
property IniFileName: string read FIniFileName write FIniFileName;
property IniSectionName: string read FIniSectionName write FIniSectionName;
property IniPrefix: string read FIniPrefix write FIniPrefix;
property AllowRollup: boolean read FAllowRollup write FAllowRollup;
property AllowBeeps: boolean read FAllowBeeps write FAllowBeeps;
property GridAlignment: integer read FGridAlignment write SetGridAlignment;
end;
{$ifdef InheritsFromTPanel}
TGlobalAttributes = class(TComponent)
private
fattributes: TAttributes;
protected
public
constructor create(aowner: TComponent); override;
destructor Destroy; override;
published
property Attributes: TAttributes read FAttributes write FAttributes;
end;
TAboutPowerPanel = class(TPropertyEditor)
function GetAttributes : TPropertyAttributes; override;
function GetValue: string; override;
procedure edit; override;
end;
{$endif}
{change TCustomPanel to something else if your customizing this unit}
TPowerPanel = class(TCustomPanel)
private
{$ifdef InheritsFromTPanel}
FAbout: TAboutPowerPanel;
{$endif}
FOLdCaption: string;
FAttributes: TAttributes;
FOldColor: TColor;
FOpenWidth, FOpenHeight: integer;
FOpenTop, FOpenLeft: integer;
FPanelState: TPanelState;
FOnMouseDown: TMouseEvent;
FOnMouseUp: TMouseEvent;
FOnMouseMove: TMouseMoveEvent;
Origx,
origy,
pleft,
pwidth,
ptop,
pheight,
downx,
downy: integer;
fleft,
ftop,
fright,
fbottom: boolean;
xx,
yy: integer;
Direction: TDirection;
ChildControls: array[0..99] of boolean;
SiblingControls: array[0..99] of boolean;
{$ifdef InheritsFromTPanel}
procedure WMEraseBkgnd(var Msg: TWmEraseBkgnd); message WM_ERASEBKGND;
{$endif}
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: integer); override;
procedure MoveUp(x, y: integer); virtual;
procedure MoveDown(x, y: integer); virtual;
procedure MoveLeft(x, y: integer); virtual;
procedure MoveRight(x, y: integer); virtual;
procedure MoveMove(x, y: integer); virtual;
procedure SetDirection; virtual;
procedure SetCursor; virtual;
procedure TrackPosition; virtual;
procedure GetChildControls; virtual;
procedure GetSiblingControls; virtual;
procedure HideControls; virtual;
procedure ShowControls; virtual;
procedure TestBounds(cc: tcontrol; dr: tdirection; cl, ct, cw, ch: integer); virtual;
function GetNextName(const Value: String):string;
function AdjustToGrid(x: integer): integer; virtual;
public
constructor create(aowner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{$ifdef InheritsFromTPanel}
procedure RollItUp; virtual;
{$endif}
procedure ResetIni(xIniFilename: string); virtual;
procedure EraseIni(xIniFilename: string); virtual;
procedure SaveParentsBounds; virtual;
procedure UpdateGridAlignment(sender: tobject); virtual;
{$ifdef InheritsFromTPanel}
property Canvas;
{$endif}
published
{$ifdef InheritsFromTPanel}
property About: TAboutPowerPanel read fabout;
property Align;
property Alignment;
property BevelInner nodefault;
property BevelOuter nodefault;
property BevelWidth nodefault;
property BorderWidth nodefault;
property BorderStyle nodefault;
property DragCursor;
property DragMode;
property Enabled;
property Caption;
property Color;
property Ctl3D;
property Font;
property Locked;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnResize;
{$endif}
property OnMouseDown read FOnMouseDown write FOnMouseDown;
property OnMouseUp read FOnMouseUp write FOnMouseUp;
property OnMouseMove read FOnMouseMove write FOnMouseMove;
property Attributes: TAttributes read FAttributes write FAttributes;
end;
{$ifdef InheritsFromTPanel}
TPowerPanelEditor = class(TComponentEditor)
procedure edit; override;
end;
TGlobalAttributesEditor = class(TPowerPanelEditor)
procedure edit; override;
end;
{$endif}
implementation
uses {$ifdef InheritsFromTPanel} ppce, ppace, {$endif}ppabout;
{$ifdef InheritsFromTPanel}
function TAboutPowerPanel.GetAttributes: TPropertyAttributes;
begin
result := [paDialog];
end;
function TAboutPowerPanel.getValue: string;
begin
result := format('(%s)',[getproptype^.name]);
end;
procedure TAboutPowerPanel.edit;
var
abt: TPowerPanelAboutBox;
begin
abt := TPowerPanelAboutBox.create( Application );
abt.showmodal;
abt.free;
end;
{$endif}
procedure TAttributes.SetGridAlignment(value: integer);
begin
if fgridalignment = value then exit;
fgridalignment := value;
if assigned(FOnGridChanged) then
FOnGridChanged(self);
end;
procedure TAttributes.Reset;
begin
SizableLeft := false;
SizableRight := false;
SizableTop := false;
SizableBottom := false;
HideChildren := false;
HideSiblings := false;
movable := false;
end;
{$ifdef InheritsFromTPanel}
constructor TGlobalAttributes.Create(AOwner: TComponent);
var
i: integer;
begin
inherited Create(AOwner);
FAttributes := TAttributes.create;
for i := 0 to aowner.componentcount-1 do begin
if i > (aowner.componentcount-1) then exit;
if aowner.components[i] is TGlobalAttributes then
if aowner.components[i] <> self then begin
Raise Exception.Create ('You can only have one GlobalAttributes' + #13 +
'component on each form.');
end;
end;
with fAttributes do begin
MaxHeight := -1;
MaxWidth := -1;
MinHeight := 30;
MinWidth := 30;
FEdgeOffset := 10;
Movable := true;
MovableHorz := true;
MovableVert := true;
MoveParent := false;
MoveColor := clactiveCaption;
FHideChildren := true;
FHideSiblings := false;
FStayVisible := false;
FTrackPositions := true;
FIniLog := true;
FCursorMoving := crArrow;
FCursorSizingNS := crSizeNS;
FCursorSizingEW := crSizeWE;
SizableBottom := true;
SizableTop := true;
SizableLeft := true;
SizableRight := true;
end;
end;
destructor TGlobalAttributes.destroy;
begin
FAttributes.free;
inherited destroy;
end;
{$endif}
constructor TPowerPanel.Create(AOwner: TComponent);
var i: integer;
begin
inherited Create(AOwner);
{$ifdef InheritsFromTPanel}
caption := ' ';
borderwidth := 1;
bevelwidth := 1;
bevelouter := bvraised;
{$endif}
Height := 120;
Width := 100;
origx := -200;
origy := -200;
Cursor := crdefault;
FAttributes := TAttributes.create;
with fAttributes do begin
FParentOpen := true;
FPanelState := psOpen;
MaxHeight := -1;
MaxWidth := -1;
MinHeight := 30;
MinWidth := 30;
FEdgeOffset := 10;
Movable := true;
MovableHorz := true;
MovableVert := true;
MoveParent := false;
MoveColor := clactiveCaption;
FHideChildren := true;
FHideSiblings := false;
FStayVisible := false;
FTrackPositions := true;
FCursorMoving := crArrow;
FCursorSizingNS := crSizeNS;
FCursorSizingEW := crSizeWE;
SizableBottom := true;
SizableTop := true;
SizableLeft := true;
SizableRight := true;
GridAlignment := 1;
OnGridChanged := UpdateGridAlignment;
end;
end;
procedure TPowerPanel.UpdateGridAlignment(sender: tobject);
{gets called due to an Attributes ongridchanged event}
begin
setbounds(adjusttogrid(left), adjusttogrid(top), adjusttogrid(width), adjusttogrid(height));
end;
procedure TPowerPanel.ResetINI(xinifilename: string);
var
PPIni: TIniFile;
work, xIniSectionName, xIniPrefix: string;
i, x: integer;
nums: array [1..4] of integer;
begin
with attributes do begin
if not Attributes.INILog then exit;
xinisectionname := finisectionname;
xiniprefix := finiprefix;
if xiniSectionName = '' then
xiniSectionName := name;
if (FiniPrefix = '') and (FiniSectionName <> name) then
FiniPrefix := name;
PPIni := TIniFile.create(xiniFileName);
work := PPini.readstring(xiniSectionName, xIniPrefix+'Designed', 'None');
if work = 'None' then
begin
PPIni.free;
exit;
end;
work := work + ',';
for i := 1 to 4 do
begin
x := pos(',',work);
nums[i] := strtoint(copy(work,1,x-1));
system.delete(work,1,x);
end;
if not (csDesigning in ComponentState) then
begin
top := nums[1];
left := nums[2];
Height := nums[3];
width := nums[4];
end;
PPini.writeInteger(xiniSectionName, xiniPrefix+'Left', left);
PPini.writeInteger(xiniSectionName, xiniPrefix+'Top', top);
PPini.writeInteger(xiniSectionName, xiniPrefix+'Width', width);
PPini.writeInteger(xiniSectionName, xiniPrefix+'Height', height);
PPIni.free;
end; {with}
end;
procedure TPowerPanel.EraseIni(xIniFileName: string);
var
xsection: string;
ppini: tinifile;
begin
if xInifilename = '' then exit;
xsection := attributes.inisectionname;
if xsection = '' then xsection := name;
PPIni := TIniFile.create(xIniFilename);
PPini.erasesection(xsection);
PPini.free;
end;
procedure TPowerPanel.Notification(AComponent: TComponent; Operation: TOperation);
begin
Inherited Notification(AComponent, Operation);
if Operation = opRemove then
if AComponent = attributes.ftrackpanel then
attributes.ftrackpanel := nil;
end;
procedure TPowerPanel.Loaded;
var
PPIni: TIniFile;
Work: string;
i, x : integer;
nums: array [1..4] of integer;
function getDesignedVals: string;
begin
result := inttostr(top) + ',' + inttostr(left) + ',' +
inttostr(height) + ',' + inttostr(width);
end;
begin
inherited Loaded; { always call the inherited Loaded first! }
if csDesigning in ComponentState then exit;
SaveParentsBounds;
with fattributes do begin
fparentopen := true;
setbounds(adjusttogrid(left), adjusttogrid(top), adjusttogrid(width), adjusttogrid(height));
if not FiniLog then exit;
if FiniFilename = '' then
FiniFileName := extractfilename(ChangeFileExt(ParamStr(0), '.INI'));
if FiniSectionName = '' then
FiniSectionName := name;
if (FiniPrefix = '') and (FiniSectionName <> name) then
FiniPrefix := name;
PPIni := TIniFile.create(FiniFileName);
{get panels parameters }
ppini.writestring(FIniSectionName, FiniPrefix+'Designed',GetDesignedVals);
Left := PPini.readInteger(FiniSectionName, FiniPrefix+'Left', left);
top := PPini.readInteger(FiniSectionName, FiniPrefix+'Top', top);
width := PPini.readInteger(FiniSectionName, FiniPrefix+'Width', width);
height := PPini.readInteger(FiniSectionName, FiniPrefix+'Height', height);
fpanelstate := tpanelstate(PPini.readinteger(FiniSectionName, FiniPrefix+'State', ord(psopen)));
Work := PPini.readstring(FiniSectionName, FIniPrefix+'ExpandParent', 'None');
setbounds(adjusttogrid(left), adjusttogrid(top), adjusttogrid(width), adjusttogrid(height));
{$ifdef InheritsFromTPanel}
if parent is tpowerpanel then
begin
if fpanelstate = psopen
then
attributes.fParentopen := true
else
attributes.fparentopen := false;
end;
{$endif}
if Work = 'None' then begin
PPini.free;
exit;
end;
Work := Work + ','; {ending delimiter}
for i := 1 to 4 do
begin
x := pos(',',Work);
nums[i] := strtoint(copy(Work,1,x-1));
system.delete(Work,1,x);
end;
fopentop := nums[1];
fopenleft := nums[2];
fopenHeight := nums[3];
fopenwidth := nums[4];
PPIni.free;
end;
end;
destructor TPowerPanel.destroy;
var
PPIni: TiniFile;
function getopenvals: string;
begin
result := inttostr(fopentop) + ',' + inttostr(fopenleft) + ',' +
inttostr(fopenheight) + ',' + inttostr(fopenwidth);
end;
begin
with fattributes do begin
if not (csDesigning in ComponentState) and FiniLog then begin
PPIni := TIniFile.create(FiniFileName);
{set panels parameters }
PPini.writeInteger(FiniSectionName, FiniPrefix+'Left', left);
PPini.writeInteger(FiniSectionName, FiniPrefix+'Top', top);
PPini.writeInteger(FiniSectionName, FiniPrefix+'Width', width);
PPini.writeInteger(FiniSectionName, FiniPrefix+'Height', height);
PPini.writeInteger(FiniSectionName, FiniPrefix+'State', ord(fpanelstate));
ppini.writestring(FIniSectionName, FiniPrefix+'ExpandParent',GetOpenVals);
PPIni.free;
end;
end;
FAttributes.free;
inherited destroy;
end;
procedure TPowerPanel.SaveParentsBounds;
begin
fopenwidth := parent.width;
fopenheight := parent.height;
fopenleft := parent.left;
fopentop := parent.top;
end;
function TPowerPanel.AdjustToGrid(x: integer): integer;
var
up, down, saveup: integer;
begin
result := x;
if attributes.GridAlignment < 2 then exit;
if x mod attributes.GridAlignment = 0 then exit;
up := 0;
down := 0;
while result mod attributes.GridAlignment <> 0 do
inc(result);
saveup := result;
up := result - x;
result := x;
while result mod attributes.GridAlignment <> 0 do
dec(result);
down := x - result;
if up < down then result := saveup;
end;
procedure TPowerPanel.TestBounds(cc: tcontrol; dr: tdirection; cl, ct, cw, ch: integer);
var
l, t, w, h: integer;
i, minh, minw: integer;
procedure soundoff;
begin
if Attributes.AllowBeeps then
messagebeep(MB_OK);
end;
procedure soundoff2;
begin
if Attributes.AllowBeeps then
messagebeep(MB_ICONASTERISK);
end;
begin
(* make sure this panel stays within its parents bounds *)
if (cc.left + xx) < 0 then begin soundoff; exit; end;
if (cc.top + yy) < 0 then begin soundoff; exit; end;
l := 0;
t := 0;
minh:= 0;
minw := 0;
{$ifdef InheritsFromTPanel}
for i := 0 to tpowerpanel(cc).controlcount-1 do begin
if Tpowerpanel(cc).controls[i].align in [altop, albottom] then
minh := minh + Tpowerpanel(cc).controls[i].height;
if Tpowerpanel(cc).controls[i].align in [alleft, alright] then
minw := minw + Tpowerpanel(cc).controls[i].width;
end;
if minw <> 0 then inc(minw, 10);
if minh <> 0 then inc(minh, 10);
if (attributes.minheight <> -1) and (minh <> 0) then
if attributes.minheight > minh then minh := attributes.minheight;
if (attributes.minwidth <> -1) and (minw <> 0) then
if attributes.minwidth > minw then minw := attributes.minwidth;
minh := AdjustToGrid(minh);
minw := AdjustToGrid(minw);
{$endif}
w := cc.width;
h := cc.height;
if cl < 0 then soundoff;
if ct < 0 then soundoff;
if cl > -1 then
begin
l := cl;
w := cw;
end;
if ct > -1 then
begin
t := ct;
h := ch;
end;
if (cl+cw) > cc.parent.width then
begin
l := cc.left;
w := cc.width;
{ w := cc.parent.width - cc.left;}
SoundOff;
end;
if (ct+ch) > cc.parent.height then
begin
t := cc.top;
h := cc.height;
{h := cc.parent.height - cc.top;}
SoundOff;
end;
if h < (minh) then
begin
SoundOff;
exit;
end;
if w < (minw) then
begin
SoundOff;
exit;
end;
case dr of
DirRight: w := AdjustToGrid(w);
DirBottom: h := AdjustToGrid(h);
DirLeft:
begin
if not (align = alright) then
l := AdjustToGrid(l);
end;
DirTop:
begin
if not (align = albottom) then
t := AdjustToGrid(t);
{h := AdjustToGrid(h);}
end;
Dirtr:
begin
t := AdjustToGrid(t);
w := AdjustToGrid(w);
end;
Dirbr:
begin
w := AdjustToGrid(w);
h := AdjustToGrid(h);
end;
Dirtl:
begin
t := AdjustToGrid(t);
l := AdjustToGrid(l);
end;
Dirbl:
begin
h := AdjustToGrid(h);
l := AdjustToGrid(l);
end;
DirMove:
begin
t := AdjustToGrid(t);
l := AdjustToGrid(l);
end;
end;
cc.setbounds(l, t, w, h);
end;
procedure TPowerPanel.HideControls;
var i: integer;
begin
{$ifdef InheritsFromTPanel}
if FAttributes.HideChildren then
begin
GetChildControls; {hold onto original visible values}
for i := 0 to controlcount-1 do
if controls[i] is TPowerPanel then
begin
if not tPowerPanel(controls[i]).Attributes.StayVisible then
controls[i].hide;
end
else
controls[i].hide;
end;
{should we hide the siblings while resizing }
if not (direction = dirmove) then
if FAttributes.Hidesiblings then
begin
GetSiblingControls; {hold onto original visible values}
for i := 0 to parent.controlcount-1 do
if parent.controls[i] <> self then
if parent.controls[i] is tPowerPanel then
begin
if not tPowerPanel(parent.controls[i]).Attributes.StayVisible then
parent.controls[i].hide;
end
else
parent.controls[i].hide;
end; {if hidesiblings}
{$endif}
end; {proc}
procedure TPowerPanel.ShowControls;
var i: integer;
begin
{$ifdef InheritsFromTPanel}
if FAttributes.HideChildren then
for i := controlcount-1 downto 0 do
if controls[i] is TPowerPanel then
begin
if not tPowerPanel(controls[i]).Attributes.StayVisible then
if childcontrols[i] then {was it originally visible}
controls[i].show;
end
else
if childcontrols[i] then {was it originally visible}
controls[i].show;
{should we restore the siblings}
if not (direction = dirmove) then
if FAttributes.Hidesiblings then
for i := parent.controlcount-1 downto 0 do
if parent.controls[i] <> self then
if parent.controls[i] is tPowerPanel then
begin
if not tPowerPanel(parent.controls[i]).Attributes.StayVisible then
if Siblingcontrols[i] then {was it originally visible}
parent.controls[i].show;
end
else
if Siblingcontrols[i] then {was it originally visible}
parent.controls[i].show;
{$endif}
end;
procedure TPowerPanel.GetChildControls;
var i: integer;
begin
{$ifdef InheritsFromTPanel}
{save original visible property of each child control}
if controlcount > 100 then exit; {alot of controls}
for i := 0 to controlcount-1 do
ChildControls[i] := controls[i].visible;
{$endif}
end;
procedure TPowerPanel.GetSiblingControls;
var i: integer;
begin
{$ifdef InheritsFromTPanel}
{save original visible property of each sibling control(parents controls)}
if parent.controlcount > 100 then exit; {alot of controls}
for i := 0 to parent.controlcount-1 do
SiblingControls[i] := parent.controls[i].visible;
{$endif}
end;
procedure TPowerPanel.TrackPosition;
var s: string;
begin
{$ifdef InheritsFromTPanel}
{if direction = dirmove then exit;}
if not FAttributes.TrackPositions then exit;
s := 'L' + inttostr(left) + ',T' + inttostr(top) + ',W'
+ inttostr(width) + ',H' + inttostr(height);
if attributes.FTrackPanel = nil then
begin
caption := s;
exit;
end;
tpanel(attributes.FTrackPanel).caption := name + ': ' + s;
{$endif}
end;
{$ifdef InheritsFromTPanel}
procedure TPowerPanel.RollItUp;
var
mysize, myleft, mytop: integer;
function getalignedtotal(al: talign): integer;
var i: integer;
begin
result := 0;
if al in [altop, albottom] then
begin
for i := 0 to self.parent.controlcount-1 do
if self.parent.controls[i].align in [altop, albottom] then
result := result + self.parent.controls[i].height;
end;
if al in [alleft, alright] then
begin
for i := 0 to self.parent.controlcount-1 do
if self.parent.controls[i].align in [alleft, alright] then
result := result + self.parent.controls[i].width;
end;
end;
begin
if not attributes.AllowRollup then exit;
if align = alnone then exit;
if not (parent is tpowerpanel) then exit;
if (tpowerpanel(parent).fpanelstate = pslocked) and (fpanelstate = psopen) then exit; ;
if fpanelstate = pslocked then exit;
if attributes.fParentOpen then
begin
SaveParentsBounds;
if align in [altop, albottom] then
begin
mysize := getalignedtotal(align);
end
else
begin
mysize := getalignedtotal(align);
end;
if align in [albottom] then
begin
mytop := parent.top + ((parent.height-mysize)-5);
end;
if align in [alright] then
begin
myleft := parent.left + ((parent.width-mysize)-5);
end;
if attributes.Allowrollup then
if align in [altop, albottom] then
begin
self.parent.height := mysize+5;
if align in [albottom] then
parent.top := mytop;
end
else
begin
self.parent.width := Mysize+5;
if align in [alright] then
parent.left := myleft;
end;
attributes.fparentopen := false;
fpanelstate := psclosed;
tpowerpanel(parent).fpanelstate := pslocked;
end
{reopen this panels parent}
else
begin
if attributes.Allowrollup then
if align in [altop, albottom] then
begin
self.parent.height := fopenHeight;
if align in [albottom] then
self.parent.top := FOpenTop;
end
else
begin
self.parent.width := fopenwidth;
if align in [alright] then
self.parent.left := fOpenleft;
end;
attributes.fparentopen := true;
{tpowerpanel(parent).fpanelstate := psopen; }
fpanelstate := psopen;
tpowerpanel(parent).fpanelstate := psopen;
end;
exit;
end;
{$endif}
procedure TPowerPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
xx := x;
yy := y;
if assigned(fonmousedown) then
fOnMouseDown(self, Button, Shift, X, Y);
{$ifdef InheritsFromTPanel}
if button = mbright then
begin
RollItUp;
Exit;
end;
{$endif}
if (parent is TPowerPanel) and (tpowerpanel(parent).fpanelstate = pslocked) then exit;
if fpanelstate = pslocked then exit;
SetDirection; {establish the direction to resize}
if direction = dirNone then exit;
if direction = dirMove then
begin
Foldcolor := color;
color := FAttributes.MoveColor;
end;
downx := x;
downy := y;
pleft := left;
pwidth := width;
ptop := top;
pheight := height;
{$ifdef InheritsFromTPanel}
if Attributes.trackpositions then
FOldCaption := caption;
{$endif}
HideControls;
origx := left;
origy := top;
trackposition;
end;
procedure TPowerPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
xx := x;
yy := y;
if assigned(fonmouseup) then
fOnMouseup(self, Button, Shift, X, Y);
if button = mbright then exit;
if (parent is tpowerpanel) and (tpowerpanel(parent).fpanelstate = pslocked) then exit;
if fpanelstate = pslocked then exit;
origx := -200;
origy := -200;
pleft := 0;
pwidth := 0;
if Direction = DirMove then color := FOldColor;
direction := DirNone;
trackposition;
{$ifdef InheritsFromTPanel}
if Attributes.trackpositions then
Caption := FOldcaption;
{$endif}
{restore if hidden}
ShowControls;
end;
procedure TPowerPanel.MouseMove(Shift: TShiftState; X, Y: integer);
begin
x := AdjustToGrid(x);
y := AdjustToGrid(y);
xx := x;
yy := y;
if assigned(fonmousemove) then
fOnMouseMove(self, Shift, X, Y);
{if either this panel or its parent is locked then abort}
if parent is tpowerpanel then
if TPowerpanel(parent).fpanelstate = pslocked
then
begin
cursor := crdefault;
exit;
end;
if fpanelstate = pslocked then
begin
cursor := crdefault;
exit;
end;
if origx = -200 then begin {no mouse down yet}
{modify cursor accordingly}
if not (align = alclient) then
begin
with FAttributes do begin
if Sizabletop then
ftop := (y < edgeoffset);
if SizableLeft then
fleft := (x < edgeoffset);
if SizableRight then
fright := (x > width-edgeoffset);
if SizableBottom then
fbottom := (y > height-edgeoffset);
end;
if align = altop then
begin
ftop := false;
fleft := false;
fright := false;
end;
if align = albottom then
begin
fbottom := false;
fleft := false;
fright := false;
end;
if align = alleft then
begin
fbottom := false;
fleft := false;
ftop := false;
end;
if align = alright then
begin
fbottom := false;
fright := false;
ftop := false;
end;
SetCursor; {change the cursor shape}
end; {with}
end;
if origx = -200 then exit;
case direction of
DirRight: MoveRight(x, y);
DirBottom: MoveDown(x, y);
DirLeft: MoveLeft(x, y);
DirTop: MoveUp(x, y);
Dirtr:
begin
MoveRight(x, y);
MoveUp( x, y);
end;
Dirbr:
begin
MoveRight(x, y);
MoveDown(x, y);
end;
Dirtl:
begin
MoveLeft(x, y);
MoveUp(x, y);
end;
Dirbl:
begin
MoveLeft(x, y);
MoveDown(x, y);
end;
DirMove:
begin
MoveMove(x, y);
end;
end;
trackposition;
end;
procedure TPowerPanel.MoveUp(x, y: integer);
var h, t, z: integer;
begin
{offsety := downy;}
h := ((height) - y);
z := top+height;
t := top+y;
with FAttributes do begin
if maxheight <> -1 then
if h > maxheight then begin
h := maxheight;
t := z-maxheight;
end;
if minheight <> -1 then
if h < minheight then begin
exit;
h := minheight;
t := z-minheight;
end;
end;
{setbounds(left, t, width, h); }
testbounds(self, dirtop, left, t, width, h);
end;
procedure TPowerPanel.MoveDown(x, y: integer);
var h, offsety: integer;
begin
offsety := pheight-downy;
h := offsety + (y+top) - top;
with FAttributes do begin
if maxheight <> -1 then
if h > maxheight then h := maxheight;
if minheight <> -1 then
if h < minheight then h := minheight;
end;
{setbounds(left, top, width, h);}
TestBounds(self, dirbottom, left, top, width, h);
end;
procedure TPowerPanel.MoveLeft(x, y: integer);
var w,l,z: integer;
begin
w:= width-x;
l := left+x;
{if l < 0 then exit;}
z := left+width;
with FAttributes do begin
if maxwidth <> -1 then
if w > maxwidth then begin
w := maxwidth;
l := z-maxwidth;
end;
if minwidth <> -1 then
if w < minwidth then begin
w := minwidth;
l := z-minwidth;
end;
end;
testbounds(self, dirleft, l, top, w, height);
end;
procedure TPowerPanel.MoveRight(x, y: integer);
var w, offsetx: integer;
begin
offsetx := pwidth-downx;
w := (offsetx + (x+left) - left);
with FAttributes do begin
if maxwidth <> -1 then
if w > maxwidth then w := maxwidth;
if minwidth <> -1 then
if w < minwidth then w := minwidth;
end;
testbounds(self, dirright, left, top, w, height);
end;
procedure TPowerPanel.MoveMove(x, y: integer);
var
l, t: integer;
cc: tcontrol;
begin
if (parent.align <> alnone) and (align <> alnone) then exit;
if (align <> alnone) and not (fAttributes.moveparent) then exit;
cc := self;
if FAttributes.MoveParent then begin
cc := parent;
{if parent is aligned then don't move it}
if cc.align <> alnone then cc := self;
end;
with FAttributes do begin
l := cc.left;
t := cc.top;
if x < downx then
if MovableHorz then
l := cc.left - (downx-x);
if x > downx then
if movableHorz then
l := cc.left + (x-downx);
if y < downy then
if movableVert then
t := cc.top - (downy-y);
if y > downy then
if movableVert Then
t := cc.top + (y-downy);
end; {with}
{cc.setbounds(l, t, cc.width, cc.height);}
testbounds(cc, dirmove, l, t, cc.width, cc.height);
end;
procedure TPowerPanel.SetDirection;
begin
direction := dirnone;
if cursor = crdefault then exit;
if FAttributes.Movable then
if cursor = FAttributes.cursormoving then direction := DirMove;
if ftop then direction := dirtop;
if fleft then direction := dirleft;
if fright then direction := dirright;
if fbottom then direction := dirbottom;
if ftop and fleft then direction := dirtl;
if fbottom and fright then direction := dirbr;
if ftop and fright then direction := dirtr;
if fbottom and fleft then direction := dirbl;
end;
procedure TPowerPanel.SetCursor;
var xcursor: tcursor;
{xcursor is used so we dont force redisplay of an unchanged cursor}
begin
with FAttributes do begin
if ftop then xcursor := FCursorSizingNS;
if fleft then xcursor := FCursorSizingEW;
if fright then xcursor := FCursorSizingEW;
if fbottom then xcursor := FCursorSizingNS;
if ftop and fleft then xcursor := crsizenwse;
if fbottom and fright then xcursor := crsizenwse;
if ftop and fright then xcursor := crsizenesw;
if fbottom and fleft then xcursor := crsizenesw;
if not ftop and not fbottom
and not fright and not fleft and not FAttributes.movable
then xcursor := crdefault;
if not ftop and not fbottom
and not fright and not fleft and FAttributes.movable
then xcursor := FAttributes.CursorMoving;
if xcursor <> cursor then cursor := xcursor;
end; {with}
end;
function tPowerPanel.GetNextName(const Value: String):string;
var
i: integer;
a: string[4];
begin
Result := copy(Value,2,255);
a := '1';
i := 1;
while true do
if owner.findcomponent(Result+a)=nil then begin
Result := Result+a;
break;
end
else begin
inc(i);
a := inttostr(i);
end;
end;
{$ifdef InheritsFromTPanel}
procedure TPowerPanel.WMEraseBkgnd;
begin
if origx = -200 then
Msg.result := ord(false)
else
Msg.result := ord(true);
end;
{$endif}
{$ifdef InheritsFromTPanel}
procedure TGlobalAttributesEditor.edit;
begin
inherited edit;
end;
procedure TPowerPanelEditor.edit;
var
Myform: tfrmppce;
i: integer;
c: tcomponent;
ta: tattributes;
begin
c := component;
if c is TPowerPanel then ta := TpowerPanel(c).attributes;
if c is TGlobalAttributes then ta := TGlobalAttributes(c).attributes;
myform := tfrmppce.create(application);
with myform, ta do begin
myform.caption := myform.caption + ' (' + component.owner.name + '.' + component.name + ')';
btncopy.visible := false;
btnGlobal.visible := false;
{find the TGlobalAttributes component}
for i := 0 to component.owner.componentcount-1 do
if component.owner.components[i] is TGlobalAttributes then begin
btncopy.visible := true;
GlobalAttributes := component.owner.components[i];
end;
TargetForm := component.owner;
myform.loadtrackpanels;
if c is TGlobalAttributes then btncopy.visible := false;
if c is TGlobalAttributes then btnglobal.visible := true;
readattributes(ta); {set forms fields with current properties}
if showmodal = mrok then begin
UpdateAttributes(ta); {call form method}
end; {if mrok}
end;
myform.free;
designer.modified;
end;
{$endif}
end. |
{ *
* Copyright (C) 2011-2014 ozok <ozok26@gmail.com>
*
* This file is part of TEncoder.
*
* TEncoder 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.
*
* TEncoder 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 TEncoder. If not, see <http://www.gnu.org/licenses/>.
*
* }
unit UnitEncoder;
interface
uses Classes, Windows, SysUtils, JvCreateProcess, Messages, StrUtils;
// current state of the process
type
TEncoderStatus = (esEncoding, esStopped, esDone);
type
TEncoder = class(TObject)
private
// process
FProcess: TJvCreateProcess;
// list of command lines to be executed
FCommandLines: TStringList;
// list of executables
FPaths: TStringList;
// index of current command line. Also progress.
FCommandIndex: integer;
// last line backend has written to console
FConsoleOutput: string;
// process events
procedure ProcessRead(Sender: TObject; const S: string; const StartsOnNewLine: Boolean);
procedure ProcessTerminate(Sender: TObject; ExitCode: Cardinal);
// field variable read funcs
function GetProcessID: integer;
function GetCommandCount: integer;
public
property ConsoleOutput: string read FConsoleOutput;
property CommandLines: TStringList read FCommandLines write FCommandLines;
property Paths: TStringList read FPaths write FPaths;
property FilesDone: integer read FCommandIndex;
property ProcessID: integer read GetProcessID;
property CommandCount: integer read GetCommandCount;
constructor Create();
destructor Destroy(); override;
procedure Start();
procedure Stop();
procedure ResetValues();
function GetConsoleOutput(): TStrings;
end;
implementation
{ TEncoder }
constructor TEncoder.Create;
begin
inherited Create;
FProcess := TJvCreateProcess.Create(nil);
with FProcess do
begin
OnRead := ProcessRead;
OnTerminate := ProcessTerminate;
ConsoleOptions := [coRedirect];
CreationFlags := [cfUnicode];
Priority := ppIdle;
with StartupInfo do
begin
DefaultPosition := False;
DefaultSize := False;
DefaultWindowState := False;
ShowWindow := swHide;
end;
WaitForTerminate := true;
end;
FCommandLines := TStringList.Create;
FPaths := TStringList.Create;
FCommandIndex := 0;
end;
destructor TEncoder.Destroy;
begin
inherited Destroy;
FreeAndNil(FCommandLines);
FreeAndNil(FPaths);
FProcess.Free;
end;
function TEncoder.GetCommandCount: integer;
begin
Result := FCommandLines.Count;
end;
function TEncoder.GetConsoleOutput: TStrings;
begin
Result := FProcess.ConsoleOutput;
end;
function TEncoder.GetProcessID: integer;
begin
Result := FProcess.ProcessInfo.hProcess;
end;
procedure TEncoder.ProcessRead(Sender: TObject; const S: string; const StartsOnNewLine: Boolean);
begin
FConsoleOutput := Trim(S);
end;
procedure TEncoder.ProcessTerminate(Sender: TObject; ExitCode: Cardinal);
begin
end;
procedure TEncoder.ResetValues;
begin
// reset all lists, indexes etc
FCommandLines.Clear;
FPaths.Clear;
FCommandIndex := 0;
FConsoleOutput := '';
FProcess.ConsoleOutput.Clear;
end;
procedure TEncoder.Start;
begin
if FProcess.ProcessInfo.hProcess = 0 then
begin
if FCommandLines.Count > 0 then
begin
if FileExists(FPaths[0]) then
begin
FProcess.ApplicationName := FPaths[0];
FProcess.CommandLine := FCommandLines[0];
FProcess.Run;
end
else
FConsoleOutput := 'encoder'
end
else
FConsoleOutput := '0 cmd'
end
else
FConsoleOutput := 'not 0'
end;
procedure TEncoder.Stop;
begin
if FProcess.ProcessInfo.hProcess > 0 then
begin
TerminateProcess(FProcess.ProcessInfo.hProcess, 0);
end;
end;
end.
|
unit uFrameWizardBase;
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
uTranslate,
uDBForm,
uGOM;
type
TFrameWizardBase = class;
TFrameWizardBaseClass = class of TFrameWizardBase;
TWizardManagerBase = class(TObject)
private
FOwner: TDBForm;
protected
function GetWizardDone: Boolean; virtual; abstract;
function GetOperationInProgress: Boolean; virtual; abstract;
public
constructor Create(Owner: TDBForm); virtual;
procedure NextStep; virtual; abstract;
procedure PrevStep; virtual; abstract;
procedure NotifyChange; virtual; abstract;
procedure Pause(Value: Boolean); virtual; abstract;
function GetStepByType(StepType: TFrameWizardBaseClass) : TFrameWizardBase; virtual; abstract;
procedure AddStep(Step: TFrameWizardBaseClass); virtual; abstract;
property WizardDone: Boolean read GetWizardDone;
property Owner: TDBForm read FOwner;
property OperationInProgress: Boolean read GetOperationInProgress;
procedure BreakOperation; virtual; abstract;
end;
TFrameWizardBase = class(TFrame)
private
{ Private declarations }
FOnChange: TNotifyEvent;
FManager: TWizardManagerBase;
FIsBusy: Boolean;
FIsStepComplete: Boolean;
protected
{ Protected declarations }
function L(StringToTranslate: string): string; overload;
function L(StringToTranslate, Scope: string): string; overload;
procedure LoadLanguage; virtual;
procedure Changed;
function GetCanGoNext: Boolean; virtual;
function GetOperationInProgress: Boolean; virtual;
function LocalScope: string; virtual;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure Execute; virtual;
function InitNextStep: Boolean; virtual;
procedure Init(Manager: TWizardManagerBase; FirstInitialization: Boolean); virtual;
procedure Unload; virtual;
procedure Pause(Value: Boolean); virtual;
function IsFinal: Boolean; virtual;
function IsPaused: Boolean; virtual;
function ValidateStep(Silent: Boolean): Boolean; virtual;
procedure BreakOperation; virtual;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property IsBusy: Boolean read FIsBusy write FIsBusy;
property IsStepComplete: Boolean read FIsStepComplete write FIsStepComplete;
property Manager: TWizardManagerBase read FManager;
property CanGoNext: Boolean read GetCanGoNext;
property OperationInProgress: Boolean read GetOperationInProgress;
end;
implementation
{$R *.dfm}
{ TFrameWizardBase }
procedure TFrameWizardBase.BreakOperation;
begin
//do nothing
end;
procedure TFrameWizardBase.Changed;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
constructor TFrameWizardBase.Create(AOwner: TComponent);
begin
inherited;
FOnChange := nil;
end;
procedure TFrameWizardBase.Execute;
begin
//write here logic to execute
end;
function TFrameWizardBase.GetCanGoNext: Boolean;
begin
Result := True;
end;
function TFrameWizardBase.GetOperationInProgress: Boolean;
begin
Result := False;
end;
procedure TFrameWizardBase.Init(Manager: TWizardManagerBase; FirstInitialization: Boolean);
begin
//some init logic of step
if FirstInitialization then
begin
GOM.AddObj(Self);
ParentColor := True;
ParentBackground := True;
FIsBusy := False;
FIsStepComplete := False;
FManager := Manager;
TTranslateManager.Instance.BeginTranslate;
try
LoadLanguage;
finally
TTranslateManager.Instance.EndTranslate;
end;
end;
end;
function TFrameWizardBase.InitNextStep: Boolean;
begin
Result := True;
//insert here next step initialization
end;
function TFrameWizardBase.L(StringToTranslate: string): string;
begin
Result := FManager.FOwner.L(StringToTranslate, LocalScope);
end;
function TFrameWizardBase.L(StringToTranslate, Scope: string): string;
begin
Result := FManager.FOwner.L(StringToTranslate, Scope);
end;
function TFrameWizardBase.IsFinal: Boolean;
begin
Result := False;
end;
function TFrameWizardBase.IsPaused: Boolean;
begin
Result := False;
end;
procedure TFrameWizardBase.LoadLanguage;
begin
//create here logic to load language
end;
function TFrameWizardBase.LocalScope: string;
begin
Result := Manager.Owner.FormID;
end;
procedure TFrameWizardBase.Pause(Value: Boolean);
begin
//custom pause action
end;
procedure TFrameWizardBase.Unload;
begin
GOM.RemoveObj(Self);
end;
function TFrameWizardBase.ValidateStep(Silent: Boolean): Boolean;
begin
Result := True;
end;
{ TWizardManagerBase }
constructor TWizardManagerBase.Create(Owner: TDBForm);
begin
FOwner := Owner;
end;
end.
|
unit uUserObj;
interface
type
TUser = Class
private
fID : Integer;
fIDUserType : Integer;
fUserName : String;
fPassword : String;
public
property ID : Integer read fID write fID;
property IDUserType : Integer read fIDUserType write fIDUserType;
property UserName : String read fUserName write fUserName;
property Password : String read fPassword write fPassword;
end;
implementation
end.
|
unit NFSEditFloat;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, AdvEdit,
Winapi.Messages;
type
TNfsEditFloat = class(TAdvEdit)
private
_MinPrecision: smallint;
_Nullen: string;
procedure SetMinPrecision(const Value: smallint);
procedure setFloatFormat;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS;
protected
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
published
property MinPrecision: smallint read _MinPrecision write SetMinPrecision;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('new frontiers', [TNfsEditFloat]);
end;
{ TNfsEditFloat }
constructor TNfsEditFloat.Create(aOwner: TComponent);
begin
inherited;
Precision := -1;
EditType := etFloat;
EditAlign := eaRight;
SetMinPrecision(2);
ReturnIsTab := true;
end;
destructor TNfsEditFloat.Destroy;
begin
inherited;
end;
procedure TNfsEditFloat.CMTextChanged(var Message: TMessage);
begin
inherited;
setFloatFormat;
end;
procedure TNfsEditFloat.setFloatFormat;
var
s : string;
s1: string;
iPos : Integer;
NewValue: string;
d: double;
begin
s := StringReplace(Text, '.', '', [rfReplaceAll]);
d := StrToFloat(s);
NewValue := FloatToStr(d);
if _MinPrecision <= 0 then
exit;
iPos := Pos(',', NewValue);
if iPos <= 0 then
begin
NewValue := NewValue + ',' + _Nullen;
if not SameText(NewValue, Text) then
Text := NewValue;
exit;
end;
s := copy(NewValue, iPos + 1, Length(NewValue));
s1 := '';
while Length(s) < _MinPrecision do
begin
s1 := s1 + '0';
s := s + '0';
end;
NewValue := NewValue + s1;
if SameText(Text, NewValue) then
exit;
Text := NewValue;
end;
procedure TNfsEditFloat.SetMinPrecision(const Value: smallint);
begin
_MinPrecision := Value;
_Nullen := '';
while Length(_Nullen) < _MinPrecision do
_Nullen := _Nullen + '0';
setFloatFormat;
end;
procedure TNfsEditFloat.WMKillFocus(var Msg: TWMKillFocus);
begin
inherited;
setFloatFormat;
end;
end.
|
unit MainUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
ComObj,
ActionsUnit,
ActiveX,
SPIClient_TLB, Vcl.Menus;
type
TfrmMain = class(TForm)
pnlSettings: TPanel;
lblSettings: TLabel;
lblPosID: TLabel;
edtPosID: TEdit;
lblEftposAddress: TLabel;
edtEftposAddress: TEdit;
pnlStatus: TPanel;
lblStatusHead: TLabel;
lblStatus: TLabel;
btnPair: TButton;
pnlReceipt: TPanel;
lblReceipt: TLabel;
richEdtReceipt: TRichEdit;
pnlActions: TPanel;
btnPurchase: TButton;
btnRefund: TButton;
btnSettle: TButton;
btnGetLast: TButton;
edtSecrets: TEdit;
lblSecrets: TLabel;
btnSave: TButton;
btnSecrets: TButton;
procedure btnPairClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnRefundClick(Sender: TObject);
procedure btnSettleClick(Sender: TObject);
procedure btnPurchaseClick(Sender: TObject);
procedure btnGetLastClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnSecretsClick(Sender: TObject);
private
public
end;
type
TMyWorkerThread = class(TThread)
public
procedure Execute; override;
end;
var
frmMain: TfrmMain;
frmActions: TfrmActions;
ComWrapper: SPIClient_TLB.ComWrapper;
Spi: SPIClient_TLB.Spi;
_posId, _eftposAddress: WideString;
SpiSecrets: SPIClient_TLB.Secrets;
UseSynchronize, UseQueue: Boolean;
implementation
{$R *.dfm}
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
ListOfStrings.DelimitedText := Str;
end;
function FormExists(apForm: TForm): boolean;
var
i: Word;
begin
Result := False;
for i := 0 to Screen.FormCount - 1 do
if Screen.Forms[i] = apForm then
begin
Result := True;
Break;
end;
end;
procedure LoadPersistedState;
var
OutPutList: TStringList;
begin
if (frmMain.edtSecrets.Text <> '') then
begin
OutPutList := TStringList.Create;
Split(':', frmMain.edtSecrets.Text, OutPutList);
SpiSecrets := ComWrapper.SecretsInit(OutPutList[0], OutPutList[1]);
end
end;
procedure PrintFlowInfo;
var
purchaseResponse: SPIClient_TLB.PurchaseResponse;
refundResponse: SPIClient_TLB.RefundResponse;
settleResponse: SPIClient_TLB.Settlement;
gltResponse: SPIClient_TLB.GetLastTransactionResponse;
success: SPIClient_TLB.SuccessState;
TimeMinutes : TDateTime;
txFlowState: SPIClient_TLB.TransactionFlowState;
const
MinutesPerDay = 60 * 24;
begin
purchaseResponse := CreateComObject(CLASS_PurchaseResponse)
AS SPIClient_TLB.PurchaseResponse;
refundResponse := CreateComObject(CLASS_RefundResponse)
AS SPIClient_TLB.RefundResponse;
settleResponse := CreateComObject(CLASS_Settlement)
AS SPIClient_TLB.Settlement;
gltResponse := CreateComObject(CLASS_GetLastTransactionResponse)
AS SPIClient_TLB.GetLastTransactionResponse;
case Spi.CurrentFlow of
SpiFlow_Pairing:
begin
frmActions.lblFlowMessage.Caption := spi.CurrentPairingFlowState.Message;
frmActions.richEdtFlow.Lines.Add('### PAIRING PROCESS UPDATE ###');
frmActions.richEdtFlow.Lines.Add('# ' +
spi.CurrentPairingFlowState.Message);
frmActions.richEdtFlow.Lines.Add('# Finished? ' +
BoolToStr(spi.CurrentPairingFlowState.Finished));
frmActions.richEdtFlow.Lines.Add('# Successful? ' +
BoolToStr(spi.CurrentPairingFlowState.Successful));
frmActions.richEdtFlow.Lines.Add('# Confirmation Code: ' +
spi.CurrentPairingFlowState.ConfirmationCode);
frmActions.richEdtFlow.Lines.Add('# Waiting Confirm from Eftpos? ' +
BoolToStr(spi.CurrentPairingFlowState.AwaitingCheckFromEftpos));
frmActions.richEdtFlow.Lines.Add('# Waiting Confirm from POS? ' +
BoolToStr(spi.CurrentPairingFlowState.AwaitingCheckFromPos));
end;
SpiFlow_Transaction:
begin
txFlowState := spi.CurrentTxFlowState;
frmActions.richEdtFlow.Lines.Clear;
frmActions.lblFlowMessage.Caption := txFlowState.DisplayMessage;
frmActions.richEdtFlow.Lines.Add('# Id: ' + txFlowState.Id);
frmActions.richEdtFlow.Lines.Add('# Type: ' +
ComWrapper.GetTransactionTypeEnumName(txFlowState.type_));
frmActions.richEdtFlow.Lines.Add('# RequestSent: ' +
BoolToStr(txFlowState.RequestSent));
frmActions.richEdtFlow.Lines.Add('# WaitingForSignature: ' +
BoolToStr(txFlowState.AwaitingSignatureCheck));
frmActions.richEdtFlow.Lines.Add('# Attempting to Cancel : ' +
BoolToStr(txFlowState.AttemptingToCancel));
frmActions.richEdtFlow.Lines.Add('# Finished: ' +
BoolToStr(txFlowState.Finished));
frmActions.richEdtFlow.Lines.Add('# Outcome: ' +
ComWrapper.GetSuccessStateEnumName(txFlowState.Success));
frmActions.richEdtFlow.Lines.Add('# Display Message: ' +
txFlowState.DisplayMessage);
if (txFlowState.AwaitingSignatureCheck) then
begin
//We need to print the receipt for the customer to sign.
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(txFlowState.SignatureRequiredMessage.GetMerchantReceipt));
end;
//If the transaction is finished, we take some extra steps.
If (txFlowState.Finished) then
begin
if (txFlowState.Success = SuccessState_Unknown) then
begin
//TH-4T, TH-4N, TH-2T - This is the dge case when we can't be sure what happened to the transaction.
//Invite the merchant to look at the last transaction on the EFTPOS using the dicumented shortcuts.
//Now offer your merchant user the options to:
//A. Retry the transaction from scratch or pay using a different method - If Merchant is confident that tx didn't go through.
//B. Override Order as Paid in you POS - If Merchant is confident that payment went through.
//C. Cancel out of the order all together - If the customer has left / given up without paying
frmActions.richEdtFlow.Lines.Add
('# ##########################################################################');
frmActions.richEdtFlow.Lines.Add
('# NOT SURE IF WE GOT PAID OR NOT. CHECK LAST TRANSACTION MANUALLY ON EFTPOS!');
frmActions.richEdtFlow.Lines.Add
('# ##########################################################################');
end
else
begin
//We have a result...
case txFlowState.type_ of
//Depending on what type of transaction it was, we might act diffeently or use different data.
TransactionType_Purchase:
begin
if (txFlowState.Success = SuccessState_Success) then
begin
//TH-6A
frmActions.richEdtFlow.Lines.Add
('# ##########################################################################');
frmActions.richEdtFlow.Lines.Add
('# HOORAY WE GOT PAID (TH-7A). CLOSE THE ORDER!');
frmActions.richEdtFlow.Lines.Add
('# ##########################################################################');
end
else
begin
//TH-6E
frmActions.richEdtFlow.Lines.Add
('# ##########################################################################');
frmActions.richEdtFlow.Lines.Add
('# WE DIDN''T GET PAID. RETRY PAYMENT (TH-5R) OR GIVE UP (TH-5C)!');
frmActions.richEdtFlow.Lines.Add
('# ##########################################################################');
end;
if (txFlowState.Response <> nil) then
begin
purchaseResponse := ComWrapper.PurchaseResponseInit
(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
purchaseResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' +
purchaseResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(purchaseResponse.GetCustomerReceipt));
end
else
begin
//We did not even get a response, like in the case of a time-out.
end;
end;
TransactionType_Refund:
if (txFlowState.Response <> nil) then
begin
refundResponse := ComWrapper.RefundResponseInit
(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
refundResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
refundResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' +
refundResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(refundResponse.GetCustomerReceipt));
end
else
begin
//We did not even get a response, like in the case of a time-out.
end;
TransactionType_Settle:
if (txFlowState.Response <> nil) then
begin
settleResponse := ComWrapper.SettlementInit
(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
settleResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Merchant Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(settleResponse.GetReceipt));
end
else
begin
//We did not even get a response, like in the case of a time-out.
end;
TransactionType_GetLastTransaction:
if (txFlowState.Response <> nil) then
begin
gltResponse := ComWrapper.GetLastTransactionResponseInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Checking to see if it matches the $100.00 purchase we did 1 minute ago :)');
TimeMinutes := 1 / MinutesPerDay;
success := Spi.GltMatch_2(gltResponse, TransactionType_Purchase, 10000, Now - TimeMinutes, 'MYORDER123');
if (success = SuccessState_Unknown) then
begin
frmActions.richEdtFlow.Lines.Add('# Did not retrieve Expected Transaction.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Tx Matched Expected Purchase Request.');
frmActions.richEdtFlow.Lines.Add('# Result: ' + ComWrapper.GetSuccessStateEnumName(success));
purchaseResponse := ComWrapper.PurchaseResponseInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' + purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Response: ' + purchaseResponse.GetResponseText());
frmActions.richEdtFlow.Lines.Add('# RRN: ' + purchaseResponse.GetRRN());
frmActions.richEdtFlow.Lines.Add('# Error: ' + txFlowState.Response.GetError());
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add(TrimLeft(purchaseResponse.GetMerchantReceipt));
end;
end
else
begin
// We did not even get a response, like in the case of a time-out.
end;
end;
end;
end;
end;
end;
end;
procedure PrintStatusAndActions();
begin
frmMain.lblStatus.Caption := ComWrapper.GetSpiStatusEnumName
(Spi.CurrentStatus) + ':' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow);
case Spi.CurrentStatus of
SpiStatus_Unpaired:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
if Assigned(frmActions) then
begin
frmActions.lblFlowMessage.Caption := 'Unpaired';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK-Unpaired';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
end;
SpiFlow_Pairing:
begin
if (Spi.CurrentPairingFlowState.AwaitingCheckFromPos) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Confirm Code';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel Pairing';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end
else if (not Spi.CurrentPairingFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel Pairing';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
end;
end;
SpiFlow_Transaction:
begin
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
end;
SpiStatus_PairedConnecting:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
frmMain.btnPair.Caption := 'UnPair';
frmMain.pnlActions.Visible := True;
frmMain.lblStatus.Color := clYellow;
frmActions.lblFlowMessage.Caption := '# --> SPI Status Changed: ' +
ComWrapper.GetSpiStatusEnumName(spi.CurrentStatus);
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
SpiFlow_Transaction:
begin
if (Spi.CurrentTxFlowState.AwaitingSignatureCheck) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Accept Signature';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Decline Signature';
frmActions.btnAction3.Visible := True;
frmActions.btnAction3.Caption := 'Cancel';
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end
else if (not Spi.CurrentTxFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end
else
begin
case Spi.CurrentTxFlowState.Success of
SuccessState_Success:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
SuccessState_Failed:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Retry';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
end;
end;
end;
SpiFlow_Pairing:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
SpiStatus_PairedConnected:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
frmMain.btnPair.Caption := 'UnPair';
frmMain.pnlActions.Visible := True;
frmMain.lblStatus.Color := clGreen;
frmActions.lblFlowMessage.Caption := '# --> SPI Status Changed: ' +
ComWrapper.GetSpiStatusEnumName(spi.CurrentStatus);
if (frmActions.btnAction1.Caption = 'Retry') then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
end;
exit;
end;
SpiFlow_Transaction:
begin
if (Spi.CurrentTxFlowState.AwaitingSignatureCheck) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Accept Signature';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Decline Signature';
frmActions.btnAction3.Visible := True;
frmActions.btnAction3.Caption := 'Cancel';
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end
else if (not Spi.CurrentTxFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end
else
begin
case Spi.CurrentTxFlowState.Success of
SuccessState_Success:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
SuccessState_Failed:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Retry';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
end;
end;
end;
SpiFlow_Pairing:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
end;
procedure TxFlowStateChanged(e: SPIClient_TLB.TransactionFlowState); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure PairingFlowStateChanged(e: SPIClient_TLB.PairingFlowState); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := TfrmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption := e.Message;
if (e.ConfirmationCode <> '') then
begin
frmActions.richEdtFlow.Lines.Add('# Confirmation Code: ' +
e.ConfirmationCode);
end;
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure SecretsChanged(e: SPIClient_TLB.Secrets); stdcall;
begin
SpiSecrets := e;
frmMain.btnSecretsClick(frmMain.btnSecrets);
end;
procedure SpiStatusChanged(e: SPIClient_TLB.SpiStatusEventArgs); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := TfrmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'It''s trying to connect';
if (Spi.CurrentFlow = SpiFlow_Idle) then
frmActions.richEdtFlow.Lines.Clear();
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure TMyWorkerThread.Execute;
begin
Synchronize(procedure begin
PrintStatusAndActions;
end
);
end;
procedure Start;
begin
LoadPersistedState;
_posId := frmMain.edtPosID.Text;
_eftposAddress := frmMain.edtEftposAddress.Text;
Spi := ComWrapper.SpiInit(_posId, _eftposAddress, SpiSecrets);
ComWrapper.Main(Spi, LongInt(@TxFlowStateChanged),
LongInt(@PairingFlowStateChanged), LongInt(@SecretsChanged),
LongInt(@SpiStatusChanged));
Spi.Start;
TMyWorkerThread.Create(false);
end;
procedure TfrmMain.btnGetLastClick(Sender: TObject);
var
sres: SPIClient_TLB.InitiateTxResult;
begin
sres := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
sres := Spi.InitiateGetLastTx;
if (sres.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# GLT Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate GLT: ' +
sres.Message + '. Please Retry.');
end;
frmActions.Show;
end;
procedure TfrmMain.btnPairClick(Sender: TObject);
begin
if (btnPair.Caption = 'Pair') then
begin
Spi.Pair;
btnSecrets.Visible := True;
edtPosID.Enabled := False;
edtEftposAddress.Enabled := False;
frmMain.lblStatus.Color := clYellow;
end
else if (btnPair.Caption = 'UnPair') then
begin
Spi.Unpair;
frmMain.btnPair.Caption := 'Pair';
frmMain.pnlActions.Visible := False;
edtSecrets.Text := '';
lblStatus.Color := clRed;
end;
end;
procedure TfrmMain.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if (FormExists(frmActions)) then
begin
frmActions.Close;
end;
Action := caFree;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
ComWrapper := CreateComObject(CLASS_ComWrapper) AS SPIClient_TLB.ComWrapper;
Spi := CreateComObject(CLASS_Spi) AS SPIClient_TLB.Spi;
SpiSecrets := CreateComObject(CLASS_Secrets) AS SPIClient_TLB.Secrets;
SpiSecrets := nil;
frmMain.edtPosID.Text := 'DELPHIPOS';
lblStatus.Color := clRed;
end;
procedure TfrmMain.btnPurchaseClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to purchase for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Purchase';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.edtAmount.Visible := True;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnRefundClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to refund for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Refund';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.edtAmount.Visible := True;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnSaveClick(Sender: TObject);
begin
Start;
btnSave.Enabled := False;
if (edtPosID.Text = '') or (edtEftposAddress.Text = '') then
begin
showmessage('Please fill the parameters');
exit;
end;
Spi.SetPosId(edtPosID.Text);
Spi.SetEftposAddress(edtEftposAddress.Text);
frmMain.pnlStatus.Visible := True;
end;
procedure TfrmMain.btnSecretsClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.richEdtFlow.Clear;
if (SpiSecrets <> nil) then
begin
frmActions.richEdtFlow.Lines.Add('Pos Id: ' + _posId);
frmActions.richEdtFlow.Lines.Add('Eftpos Address: ' + _eftposAddress);
frmActions.richEdtFlow.Lines.Add('Secrets: ' + SpiSecrets.encKey + ':' +
SpiSecrets.hmacKey);
end
else
begin
frmActions.richEdtFlow.Lines.Add('I have no secrets!');
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmMain.Enabled := False;
end;
Procedure TfrmMain.btnSettleClick(Sender: TObject);
var
settleres: SPIClient_TLB.InitiateTxResult;
amount: Integer;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.edtAmount.Visible := False;
frmMain.Enabled := False;
settleres := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
settleres := Spi.InitiateSettleTx(ComWrapper.Get_Id('settle'));
if (settleres.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# Settle Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate settlement: ' +
settleres.Message + '. Please Retry.');
end;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fHTMLTidyManageProfiles;
interface
{$I ConTEXT.inc}
{$IFDEF SUPPORTS_HTML_TIDY}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ActnList, StdCtrls, TB2Item, TBX, TB2Dock, TB2Toolbar;
type
TfmHTMLTidyManageProfiles = class(TForm)
lvProfiles: TListView;
Button1: TButton;
alTidyProfiles: TActionList;
acNew: TAction;
acEdit: TAction;
acDelete: TAction;
TBXToolbar1: TTBXToolbar;
TBXItem1: TTBXItem;
TBXItem2: TTBXItem;
TBXItem3: TTBXItem;
acClose: TAction;
procedure acNewExecute(Sender: TObject);
procedure acEditExecute(Sender: TObject);
procedure acDeleteExecute(Sender: TObject);
procedure acCloseExecute(Sender: TObject);
procedure alTidyProfilesUpdate(Action: TBasicAction;
var Handled: Boolean);
private
procedure ProfilesToForm;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
procedure CreateHTMLTidyManageProfilesDialog;
{$ENDIF}
implementation
{$IFDEF SUPPORTS_HTML_TIDY}
{$R *.dfm}
uses
fMain, uHTMLTidy, fHTMLTidyProfile;
////////////////////////////////////////////////////////////////////////////////////////////
// Static functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure CreateHTMLTidyManageProfilesDialog;
begin
with TfmHTMLTidyManageProfiles.Create(Application) do
try
ShowModal;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyManageProfiles.ProfilesToForm;
var
strNames: TStringList;
strFiles: TStringList;
i: integer;
begin
strNames:=HTMLTidy.ProfileList;
strFiles:=HTMLTidy.ProfileFileList;
lvProfiles.Items.BeginUpdate;
try
lvProfiles.Items.Clear;
for i:=0 to strNames.Count-1 do begin
with lvProfiles.Items.Add do begin
Caption:=strNames[i];
SubItems.Add(strFiles[i]);
end;
end;
finally
lvProfiles.Items.EndUpdate;
strNames.Free;
strFiles.Free;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Actions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyManageProfiles.alTidyProfilesUpdate(Action: TBasicAction;
var Handled: Boolean);
var
selected: boolean;
begin
selected:=Assigned(lvProfiles.Selected);
acEdit.Enabled:=selected;
acDelete.Enabled:=selected;
end;
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyManageProfiles.acNewExecute(Sender: TObject);
begin
HTMLTidy.SetDefaults;
with TfmHTMLTidyProfile.Create(SELF, HTMLTidy.Profile, '') do
try
if (ShowModal=mrOK) then
ProfilesToForm;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyManageProfiles.acEditExecute(Sender: TObject);
begin
if Assigned(lvProfiles.Selected) then begin
with TfmHTMLTidyProfile.Create(SELF, HTMLTidy.Profile, lvProfiles.Selected.Caption) do
try
if (ShowModal=mrOK) then
ProfilesToForm;
finally
Free;
end;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyManageProfiles.acDeleteExecute(Sender: TObject);
begin
end;
//------------------------------------------------------------------------------------------
procedure TfmHTMLTidyManageProfiles.acCloseExecute(Sender: TObject);
begin
Close;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TfmHTMLTidyManageProfiles.Create(AOwner: TComponent);
begin
inherited;
ProfilesToForm;
end;
//------------------------------------------------------------------------------------------
destructor TfmHTMLTidyManageProfiles.Destroy;
begin
inherited;
end;
//------------------------------------------------------------------------------------------
{$ENDIF}
end.
|
unit mrLookupCombo;
interface
uses
Windows, Classes, cxDBLookupComboBox, cxEdit, DB, DBClient, uNTDataSetControl,
SysUtils, mrBoundLabel, ExtCtrls, Types, Graphics, StdCtrls, Controls,
Messages, Menus, cxDBEdit, cxDBLookupEdit, uNTUpdateControl, uNTTraceControl,
uUserObj;
type
TmrLookupComboBoxProperties = class(TcxLookupComboBoxProperties)
published
property Buttons;
end;
TmrLookupCombo = class(TcxLookupComboBox)
private
FProviderListName: String;
FConnectionListName: String;
FSession: TmrSession;
FDataSetList: TClientDataSet;
FDataSourceList: TDataSource;
FEditLabel: TmrBoundLabel;
FPopupMenuButton: TPopupMenu;
FRequiredLabel: TmrBoundLabel;
FLabelPosition: TLabelPosition;
FLocked: Boolean;
FRequired: Boolean;
FLabelSpacing: Integer;
FDisableButtons: Boolean;
FFchClassName: String;
FProviderSourceName: String;
FConnectionSourceName: String;
FDataSetControl: TmrDataSetControl;
FTraceControl: TmrTraceControl;
FUpdateControl: TmrUpdateControl;
FSystemUser : TUser;
procedure PopupClick(Sender: TObject);
function GetProperties: TmrLookupComboBoxProperties;
procedure SetProperties(const Value: TmrLookupComboBoxProperties);
procedure SetLabelPosition(const Value: TLabelPosition);
procedure SetLabelSpacing(const Value: Integer);
procedure SetLocked(const Value: Boolean);
procedure SetRequired(const Value: Boolean);
procedure SetupInternalLabel;
procedure SetInternalButtons;
procedure SetCommandButtons;
procedure SetInternalPopup;
procedure SetConfigFch;
procedure OpenListSource;
procedure DoBeforeGetRecordsList(Sender: TObject; var OwnerData: OleVariant);
procedure DoBeforeGetRecordsSource(Sender: TObject; var OwnerData: OleVariant);
procedure InsertRecord(AParams: String = '');
procedure OpenRecord(AParams: String = '');
procedure DeleteRecord;
protected
procedure ClearValue; virtual;
procedure SetDBValues(DataSet: TDataSet); virtual;
procedure SetParent(AParent: TWinControl); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetName(const Value: TComponentName); override;
procedure CMVisiblechanged(var Message: TMessage); message CM_VISIBLECHANGED;
procedure CMEnabledchanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMBidimodechanged(var Message: TMessage); message CM_BIDIMODECHANGED;
procedure DoButtonUp(Index: Integer); override;
property TraceControl: TmrTraceControl read FTraceControl write FTraceControl;
property DataSetControl: TmrDataSetControl read FDataSetControl write FDataSetControl;
property UpdateControl: TmrUpdateControl read FUpdateControl write FUpdateControl;
property Session: TmrSession read FSession write FSession;
property DataSetList: TClientDataSet read FDataSetList write FDataSetList;
property DataSourceList: TDataSource read FDataSourceList write FDataSourceList;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetPropertiesClass: TcxCustomEditPropertiesClass; override;
procedure SetBounds(ALeft: Integer; ATop: Integer; AWidth: Integer; AHeight: Integer); override;
procedure SetInternalList;
procedure CreateListSource(ATraceControl: TmrTraceControl; ADataSetControl: TmrDataSetControl;
AUpdateControl: TmrUpdateControl; ASession: TmrSession; ASystemUser : TUser);
published
property Properties: TmrLookupComboBoxProperties read GetProperties write SetProperties;
property DisableButtons: Boolean read FDisableButtons write FDisableButtons;
property ConnectionListName: String read FConnectionListName write FConnectionListName;
property ConnectionSourceName: String read FConnectionSourceName write FConnectionSourceName;
property ProviderListName: String read FProviderListName write FProviderListName;
property ProviderSourceName: String read FProviderSourceName write FProviderSourceName;
property FchClassName: String read FFchClassName write FFchClassName;
property EditLabel: TmrBoundLabel read FEditLabel;
property LabelPosition: TLabelPosition read FLabelPosition write SetLabelPosition;
property LabelSpacing: Integer read FLabelSpacing write SetLabelSpacing;
property Required: Boolean read FRequired write SetRequired;
property Locked: Boolean read FLocked write SetLocked;
end;
TmrDBLookupCombo = class(TmrLookupCombo)
private
function GetDataBinding: TcxDBTextEditDataBinding;
procedure SetDataBinding(Value: TcxDBTextEditDataBinding);
procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK;
protected
procedure ClearValue; override;
procedure SetDBValues(DataSet: TDataSet); override;
class function GetDataBindingClass: TcxEditDataBindingClass; override;
published
property DataBinding: TcxDBTextEditDataBinding read GetDataBinding write SetDataBinding;
end;
procedure Register;
implementation
uses cxLookupDBGrid, cxDropDownEdit, mrMsgBox, uParentCustomFch,
uClasseFunctions, uMRSQLParam;
procedure Register;
begin
RegisterComponents('MultiTierDataControls', [TmrLookupCombo]);
RegisterComponents('MultiTierDataControls', [TmrDBLookupCombo]);
end;
{ TmrLookupCombo }
constructor TmrLookupCombo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLabelPosition := lpLeft;
FLabelSpacing := 6;
Properties.ListOptions.ShowHeader := False;
SetupInternalLabel;
SetInternalButtons;
SetInternalPopup;
end;
procedure TmrLookupCombo.CreateListSource(ATraceControl: TmrTraceControl; ADataSetControl: TmrDataSetControl;
AUpdateControl: TmrUpdateControl; ASession: TmrSession; ASystemUser : TUser);
begin
TraceControl := ATraceControl;
DataSetControl := ADataSetControl;
UpdateControl := AUpdateControl;
Session := ASession;
FSystemUser := ASystemUser;
// Get DataSource if necesary
if DataSourceList = nil then
begin
DataSourceList := TDataSource.Create(Self);
Properties.ListSource := DataSourceList;
end;
// Get Dataset if necesary
if DataSetList = nil then
begin
DataSetList := Session.CreateDataSet(ConnectionListName, ProviderListName);
// Set combo filter event
DataSetList.BeforeGetRecords := DoBeforeGetRecordsList;
// Set DataSource
Properties.ListSource.DataSet := DataSetList;
OpenListSource;
SetConfigFch;
SetInternalList;
SetCommandButtons;
end;
end;
destructor TmrLookupCombo.Destroy;
begin
FPopupMenuButton.Free;
inherited Destroy;
end;
procedure TmrLookupCombo.DoBeforeGetRecordsList(Sender: TObject;
var OwnerData: OleVariant);
begin
end;
procedure TmrLookupCombo.DoBeforeGetRecordsSource(Sender: TObject;
var OwnerData: OleVariant);
var
Filter: TMRSQLParam;
begin
with TMRSQLParam.Create do
try
AddKey(Properties.KeyFieldNames).AsString := EditValue;
KeyByName(Properties.KeyFieldNames).Condition := tcLike;
OwnerData := ParamString;
finally
Free;
end;
end;
function TmrLookupCombo.GetProperties: TmrLookupComboBoxProperties;
begin
Result := TmrLookupComboBoxProperties(FProperties);
end;
class function TmrLookupCombo.GetPropertiesClass: TcxCustomEditPropertiesClass;
begin
Result := TmrLookupComboBoxProperties;
end;
procedure TmrLookupCombo.OpenListSource;
begin
with DataSetList do
begin
if Active then
Close;
Open;
end;
end;
procedure TmrLookupCombo.SetInternalList;
begin
Properties.ListFieldNames := UpperCase(DataSetList.GetOptionalParam('ListFieldNames'));
Properties.KeyFieldNames := UpperCase(DataSetList.GetOptionalParam('KeyFieldName'));
end;
procedure TmrLookupCombo.SetLabelPosition(const Value: TLabelPosition);
var
P: TPoint;
begin
if Assigned(FEditLabel) then
begin
FLabelPosition := Value;
case Value of
lpAbove: P := Point(Left, Top - FEditLabel.Height - FLabelSpacing);
lpBelow: P := Point(Left, Top + Height + FLabelSpacing);
lpLeft : P := Point(Left - FEditLabel.Width - FLabelSpacing,
Top + ((Height - FEditLabel.Height) div 2));
lpRight: P := Point(Left + Width + FLabelSpacing,
Top + ((Height - FEditLabel.Height) div 2));
end;
FEditLabel.SetBounds(P.x, P.y, FEditLabel.Width, FEditLabel.Height);
end;
if Assigned(FRequiredLabel) then
FRequiredLabel.SetBounds(Left + Width + 3, Top + 1, FRequiredLabel.Width, FRequiredLabel.Height);
end;
procedure TmrLookupCombo.SetLocked(const Value: Boolean);
begin
FLocked := Value;
Properties.ReadOnly := Value;
ParentColor := Value;
if not Value then
Color := clWindow;
end;
procedure TmrLookupCombo.SetLabelSpacing(const Value: Integer);
begin
FLabelSpacing := Value;
SetLabelPosition(FLabelPosition);
end;
procedure TmrLookupCombo.SetProperties(const Value: TmrLookupComboBoxProperties);
begin
FProperties.Assign(Value);
end;
procedure TmrLookupCombo.SetRequired(const Value: Boolean);
begin
FRequired := Value;
if Value then
FRequiredLabel.Parent := Self.Parent
else
FRequiredLabel.Parent := nil;
end;
procedure TmrLookupCombo.SetupInternalLabel;
begin
if not Assigned(FEditLabel) then
begin
FEditLabel := TmrBoundLabel.Create(Self);
FEditLabel.Name := 'SubEditLabel';
FEditLabel.SetSubComponent(True);
FEditLabel.FreeNotification(Self);
TLabel(FEditLabel).FocusControl := Self;
end;
if not Assigned(FRequiredLabel) then
begin
FRequiredLabel := TmrBoundLabel.Create(Self);
with FRequiredLabel do
begin
Name := 'SubRequiredLabel';
SetSubComponent(True);
FreeNotification(Self);
Caption := '*';
Font.Color := $00804000;
Font.Style := [fsBold];
Font.Size := 15;
Font.Name := 'Verdana';
Transparent := True;
end;
end;
end;
procedure TmrLookupCombo.SetName(const Value: TComponentName);
begin
inherited;
if (csDesigning in ComponentState) and ((FEditlabel.GetTextLen = 0) or
(CompareText(FEditLabel.Caption, Name) = 0)) then
FEditLabel.Caption := Value;
inherited SetName(Value);
if csDesigning in ComponentState then
Text := '';
end;
procedure TmrLookupCombo.CMBidimodechanged(var Message: TMessage);
begin
FEditLabel.BiDiMode := BiDiMode;
FRequiredLabel.BiDiMode := BiDiMode;
end;
procedure TmrLookupCombo.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FEditLabel) and (Operation = opRemove) then
FEditLabel := nil;
if (AComponent = FRequiredLabel) and (Operation = opRemove) then
FRequiredLabel := nil;
end;
procedure TmrLookupCombo.SetParent(AParent: TWinControl);
begin
inherited SetParent(AParent);
if Assigned(FEditLabel) then
begin
FEditLabel.Parent := AParent;
FEditLabel.Visible := True;
end;
end;
procedure TmrLookupCombo.CMEnabledchanged(var Message: TMessage);
begin
FEditLabel.Enabled := Enabled;
FRequiredLabel.Enabled := Enabled;
end;
procedure TmrLookupCombo.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
SetLabelPosition(FLabelPosition);
end;
procedure TmrLookupCombo.CMVisiblechanged(var Message: TMessage);
begin
FEditLabel.Visible := Visible;
FRequiredLabel.Visible := Visible;
if Visible and Required then
FRequiredLabel.Parent := Self.Parent
else
FRequiredLabel.Parent := nil;
end;
procedure TmrLookupCombo.SetInternalButtons;
begin
Properties.Buttons.Add;
Properties.Buttons[1].Kind := bkEllipsis;
end;
procedure TmrLookupCombo.SetInternalPopup;
procedure CreateMenuItem(Caption: String);
var
MenuItem: TMenuItem;
begin
MenuItem := TMenuItem.Create(FPopupMenuButton);
FPopupMenuButton.Items.Add(MenuItem);
MenuItem.Caption := Caption;
MenuItem.OnClick := PopupClick;
end;
begin
// Create and config the PoppuMenu
if not Assigned(FPopupMenuButton) then
begin
// I like to use the statemant "with", but it does not function
FPopupMenuButton := TPopupMenu.Create(Self);
FPopupMenuButton.Name := 'SubPopupMenu';
FPopupMenuButton.SetSubComponent(True);
FPopupMenuButton.FreeNotification(Self);
CreateMenuItem('&Novo...');
CreateMenuItem('&Abrir...');
CreateMenuItem('&Excluir...');
CreateMenuItem('-');
CreateMenuItem('Limpar');
end;
end;
procedure TmrLookupCombo.PopupClick(Sender: TObject);
begin
case TMenuItem(Sender).MenuIndex of
0: InsertRecord;
1: OpenRecord;
2: if MsgBox('Confirma a remoção de [' + Text + '] ?', vbQuestion + vbYesNo) = mrYes then
DeleteRecord;
4: ClearValue;
end;
end;
procedure TmrLookupCombo.DoButtonUp(Index: Integer);
var
CursorPos: TPoint;
begin
if (Index = 1) then
begin
SetCommandButtons;
GetCursorPos(CursorPos);
FPopupMenuButton.Popup(CursorPos.X, CursorPos.Y);
end;
// obsolete FOnEditButtonClick
EditButtonClick;
end;
procedure TmrLookupCombo.SetCommandButtons;
var
CommandButtonsList: String;
begin
CommandButtonsList := UpperCase(DataSetList.GetOptionalParam('CommandButtons'));
FPopupMenuButton.Items[0].Visible := (Pos('CBNEW', CommandButtonsList) > 0) and not DisableButtons and not Locked;
FPopupMenuButton.Items[1].Visible := (Pos('CBOPEN', CommandButtonsList) > 0) and not DisableButtons;
FPopupMenuButton.Items[2].Visible := (Pos('CBDELETE', CommandButtonsList) > 0) and not DisableButtons and not Locked;
FPopupMenuButton.Items[4].Visible := (Pos('CBCLEAR', CommandButtonsList) > 0) and not Locked;
FPopupMenuButton.Items[1].Enabled := (Trim(Text) <> '');
FPopupMenuButton.Items[2].Enabled := (Trim(Text) <> '');
end;
procedure TmrLookupCombo.InsertRecord(AParams: String);
var
NewSession: TmrSession;
NewDataSet: TClientDataSet;
Records, NewKey: Integer;
begin
NewSession := nil;
with TParentCustomFch(CreateForm(Self, FchClassName)) do
try
NewSession := DataSetControl.CreateSession;
NewDataSet := NewSession.CreateDataSet(ConnectionSourceName, ProviderSourceName);
NewDataSet.Open;
Records := NewDataSet.RecordCount;
Init(TraceControl, DataSetControl, UpdateControl, NewSession, NewDataSet, Self.FSystemUser);
Append;
ShowFch;
NewKey := NewDataSet.FieldByName(Properties.KeyFieldNames).AsInteger;
if NewDataSet.RecordCount > Records then
SetDBValues(NewDataSet);
finally
Free;
OpenListSource;
if NewDataSet.RecordCount > Records then
SetEditValue(NewKey);
NewSession.Terminate;
end;
end;
procedure TmrLookupCombo.OpenRecord(AParams: String);
var
NewSession: TmrSession;
NewDataSet: TClientDataSet;
ChangedKey: Integer;
begin
NewSession := nil;
with TParentCustomFch(CreateForm(Self, FchClassName)) do
try
NewSession := DataSetControl.CreateSession;
NewDataSet := NewSession.CreateDataSet(ConnectionSourceName, ProviderSourceName);
NewDataSet.BeforeGetRecords := DoBeforeGetRecordsSource;
NewDataSet.Open;
Init(TraceControl, DataSetControl, UpdateControl, NewSession, NewDataSet, Self.FSystemUser);
Open(AParams);
ShowFch;
ChangedKey := EditValue;
finally
Free;
NewSession.Terminate;
OpenListSource;
SetEditValue(ChangedKey);
end;
end;
procedure TmrLookupCombo.DeleteRecord;
begin
with DataSetList do
try
if Locate(Properties.KeyFieldNames, EditValue, []) then
begin
Delete;
ApplyUpdates(0);
end;
finally
ClearValue;
OpenListSource;
end;
end;
procedure TmrLookupCombo.SetConfigFch;
begin
FFchClassName := UpperCase(DataSetList.GetOptionalParam('FchClassName'));
FConnectionSourceName := UpperCase(DataSetList.GetOptionalParam('ConnectionSourceName'));
FProviderSourceName := UpperCase(DataSetList.GetOptionalParam('ProviderSourceName'));
end;
procedure TmrLookupCombo.ClearValue;
begin
Self.Clear;
end;
procedure TmrLookupCombo.SetDBValues(DataSet: TDataSet);
begin
// para ser herdado
end;
{ TmrDBLookupCombo }
procedure TmrDBLookupCombo.ClearValue;
begin
inherited;
if DataBinding <> nil then
begin
DataBinding.DataSource.DataSet.Edit;
DataBinding.DataSource.DataSet.FieldByName(DataBinding.DataField).Clear;
end;
end;
procedure TmrDBLookupCombo.CMGetDataLink(var Message: TMessage);
begin
if not IsInplace then
Message.Result := Integer(TcxDBEditDataBinding(DataBinding).DataLink);
end;
function TmrDBLookupCombo.GetDataBinding: TcxDBTextEditDataBinding;
begin
Result := TcxDBTextEditDataBinding(FDataBinding);
end;
class function TmrDBLookupCombo.GetDataBindingClass: TcxEditDataBindingClass;
begin
Result := TcxDBEditDataBinding;
end;
procedure TmrDBLookupCombo.SetDataBinding(Value: TcxDBTextEditDataBinding);
begin
FDataBinding.Assign(Value);
end;
procedure TmrDBLookupCombo.SetDBValues(DataSet: TDataSet);
begin
if DataBinding <> nil then
begin
DataBinding.DataSource.Edit;
DataBinding.DataLink.Field.Value := DataSet.FieldByName(Properties.KeyFieldNames).AsString;
end;
end;
end.
|
unit uDDStex;
interface
uses
Classes, SysUtils,
GLCompositeImage, GLFileDDS, GLFileJPEG, GLFileTGA, GLFilePNG,
GLMaterial, GLTexture;
function libmat( AMatLib:TGLMaterialLibrary; AMatName:string): TGLLibMaterial;
function DDStex( AMatLib:TGLMaterialLibrary; ATexName,AFileName:string;
ASecondTexName:string=''; ADDSLevel:integer = 0): TGLLibMaterial;
implementation
function libmat( AMatLib:TGLMaterialLibrary; AMatName:string): TGLLibMaterial;
begin
if AMatLib = nil then exit;
result := AMatLib.LibMaterialByName( AMatName );
if result = nil then begin
result := AMatLib.Materials.Add;
result.Name := AMatName;
end;
end;
function DDStex( AMatLib:TGLMaterialLibrary; ATexName,AFileName:string;
ASecondTexName:string=''; ADDSLevel:integer = 0): TGLLibMaterial;
var
d: TGLDDSDetailLevels;
begin
if not fileexists(AFileName) then exit;
d := vDDSDetailLevel;
case ADDSLevel of
1: vDDSDetailLevel := ddsMediumDet;
2: vDDSDetailLevel := ddsLowDet;
else vDDSDetailLevel := ddsHighDet;
end;
result := libmat( AMatLib, ATexName );
result.Texture2Name := ASecondTexName;
with result.Material.Texture do begin
ImageClassName := 'TGLCompositeImage';
Image.LoadFromFile( AFileName );
disabled := false;
end;
vDDSDetailLevel := d;
end;
end.
|
PROGRAM Tanks (Input,Output);
{****************************************************************************
Author: Scott Janousek
Student ID: 4361106
Program Assignment 4b
Due: Fri April 16, 1993
Section: 1 MWF 10:10
Instructor: Jeff Clouse
Program Desciption: This program allows a user to play a simple game, in
which the he or she will attempt to launch a projectile
(a missle from a Tank) at a Target. This program uses a few Procedures and
is a modular Design.
First the user will enter the data for the distance of the specified range
to the Target (in feet). then, the user has 5 chances to blow up the Target
with Missles. If the Missle lands "close" to the area of the Target then
the user wins the game. Otherwise, a miss has occured. The user is given
the data representing how far the missle traveled (in feet), and where it
crashed relative to where the Target was located (relative in feet).
Input : Distance to Target (in feet)
Velocity of Missle (feet/sec)
Angle of Projection (Degrees)
Players Name
Output : Distance Missle Traveled
Hit or Miss Data
Distance Missle needed
Rating of Tank Player
Algorithm : This program implements a procedure HitOrMiss to determine if
the Target has been destroyed or has been missed. Using the
Data entered by the user (Distance, Velocity, Angle of Launch)
the determination can be made for the shot. Computing if there
is hit, requires the formulas for a) Distance Traveled and
b) Percent Distance. If the Value falls under 1.0 then the
missle has killed the enemy Target. Otherwise a miss has occured,
and the user has one less missle to attempt to shoot the Target.
****************************************************************************}
CONST
Gravity = 32.2;
Pi = 3.14159265;
Split = '======= ';
VAR
Distance : Integer; ch: char;
EndGame : Boolean;
Velocity,
Degrees : Real;
NumofTries, i : Integer;
UserName : string [25];
Destroyed : Boolean;
{***************************************************************************}
BEGIN {****** Main Program ******}
END. {****** Main Program ******}
|
unit TestCreateCollection;
interface
uses
TestFramework,
Generics.Collections,
System.Math,
System.SysUtils,
System.Classes,
Vcl.Forms,
Vcl.Graphics,
Vcl.Imaging.Jpeg,
uDBConnection,
uShellUtils,
uDBManager;
type
TTestCreateCollection = class(TTestCase)
strict private
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestCreateCollection;
end;
implementation
procedure TTestCreateCollection.SetUp;
begin
FailsOnMemoryLeak := True;
FailsOnMemoryRecovery := True;
end;
procedure TTestCreateCollection.TearDown;
begin
end;
procedure TTestCreateCollection.TestCreateCollection;
var
TempFileName: string;
begin
TempFileName := GetTempFileName;
try
TDBManager.CreateExampleDB(TempFileName);
finally
TryRemoveConnection(TempFileName, True);
DeleteFile(TempFileName);
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TTestCreateCollection.Suite);
end.
|
unit chrono0;
{Version Delphi}
INTERFACE
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses SysUtils,
util1;
procedure initChrono;overload;
{ Initialise un chronomètre }
procedure initChrono(var tt:TdateTime);overload;
function chrono:AnsiString;overload;
{ Renvoie le temps écoulé depuis l'initialisation du chronomètre
sous la forme d'une chaîne de caractères.
Exemple: '12h 18mn 32s 17c' }
function chrono(tt:TdateTime):AnsiString;overload;
IMPLEMENTATION
var
t0:TdateTime;
procedure initChrono(var tt:TdateTime);
begin
tt:=now;
end;
procedure initChrono;
begin
t0:=Now;
end;
function chrono(tt:TdateTime):AnsiString;
var
t:TdateTime;
h,m,s,c:word;
dd:integer;
sh,sm,ss,sc:string[12];
st:AnsiString;
begin
t:=Now;
decodeTime(t-tt,h,m,s,c);
dd:=trunc(t-tt);
Str(h+dd*24,sh); Str(m,sm); Str(s,ss); Str(c div 10,sc);
if h<>0 then st:=sh+'h ';
if (h<>0) or (m<>0) then st:=st+sm+'mn ';
if (h<>0) or (m<>0) or (s<>0) then st:=st+ss+'s ';
st:=st+sc+'c';
result:=st;
end;
function chrono:AnsiString;
begin
result:=chrono(t0);
end;
end.
|
unit frmExport;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes, System.UITypes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls,
Vcl.ExtCtrls, Vcl.Buttons, Data.DB;
type
TformExporter = class(TForm)
Panel2: TPanel;
pnlAvailable: TPanel;
pnlOrder: TPanel;
bDown: TSpeedButton;
bUp: TSpeedButton;
bRemoveAll: TButton;
bRemove: TButton;
bAddAll: TButton;
bAdd: TButton;
Panel1: TPanel;
lblAvailableFields: TLabel;
listboxavailable: TListBox;
Splitter1: TSplitter;
pnlOptions: TPanel;
pnlExport: TPanel;
listboxfields: TListBox;
Panel3: TPanel;
Label1: TLabel;
pnlTop: TPanel;
lblExportOptions: TLabel;
cbxOutputHeader: TCheckBox;
cbxOpenAfterExport: TCheckBox;
pnlDelimit: TPanel;
lblDelimiter: TLabel;
cbxOnlySTrings: TCheckBox;
cbDelimiter: TComboBox;
pnlDateFiltering: TPanel;
lblDateFilter: TLabel;
cbDateTimeField: TComboBox;
cbxLowerBound: TCheckBox;
cbxUpperBound: TCheckBox;
dtpLowerDate: TDateTimePicker;
dtpUpperDate: TDateTimePicker;
dtpLowerTime: TDateTimePicker;
dtpUpperTime: TDateTimePicker;
cbxAcceptDateBounds: TCheckBox;
cbxUseDateLimits: TCheckBox;
pnlLatex: TPanel;
cbxvRules: TCheckBox;
cbxhlines: TCheckBox;
lblColumnType: TLabel;
cbLatexColType: TComboBox;
cbLatexEnvironment: TComboBox;
Label2: TLabel;
Label3: TLabel;
bOK: TBitBtn;
bCancel: TBitBtn;
procedure bAddClick(Sender: TObject);
procedure cbDateTimeFieldChange(Sender: TObject);
procedure bOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbxLowerBoundClick(Sender: TObject);
procedure cbxUpperBoundClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure bAddAllClick(Sender: TObject);
procedure bUpClick(Sender: TObject);
procedure bDownClick(Sender: TObject);
procedure bRemoveClick(Sender: TObject);
procedure bRemoveAllClick(Sender: TObject);
procedure listboxavailableDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure listboxavailableDblClick(Sender: TObject);
procedure listboxfieldsDblClick(Sender: TObject);
procedure listboxfieldsClick(Sender: TObject);
procedure dtpLowerDateChange(Sender: TObject);
procedure dtpLowerTimeChange(Sender: TObject);
procedure dtpUpperDateChange(Sender: TObject);
procedure dtpUpperTimeChange(Sender: TObject);
procedure cbxUseDateLimitsClick(Sender: TObject);
private
procedure SetAddRemoveButtons;
procedure SetSelectedListFields;
procedure SetUpDownButtons;
public
storedfields : TStringList;
source:TDataSet;
procedure Copysettings(bOpen,bFields,bHidden,bLowTime,bHighTime,
bDelimitEverything,bAcceptDatebounds:boolean;
aLowDateTime,aHighDateTime:TDateTime;sDelimiter:string;
iPrecision:integer);
procedure CopyLaTeXSettings(sEnvironment:string;bhLine,bVRule:boolean);
procedure SaveSettings(var bOpen,bFields,bHidden,bLowTime,bHighTime,
bDelimitEverything,bAcceptDateBounds:boolean;
var aLowDateTime,aHighDateTime:TDateTime;
var sDateTimeField,sDelimiter:string;var iPrecision:integer);
procedure SaveLaTeXSettings(var sEnvironment:string;var bHLine,
bVRule:boolean);
procedure GenerateListFields;
procedure PrepCaption(iType:integer;LaTeXEnvironment:string;
LatexHLine,LatexVRule:boolean);
procedure PrepFilters(sDateTimeFilterField:string;sl:TStringList);
end;
implementation
{$R *.dfm}
// ----- TformExporter.bAddClick -----------------------------------------------
procedure TformExporter.bAddClick(Sender: TObject);
var
i: integer;
begin
i := listboxavailable.ItemIndex;
if i <> -1 then
begin
if (listboxfields.Items.IndexOf(listboxavailable.Items[i]) = -1) then
listboxfields.Items.AddObject(listboxavailable.Items[i],
listboxavailable.Items.Objects[i]);
end;
listboxavailable.Invalidate;
SetUpDownButtons;
end;
// ----- TformExporter.SetAddRemoveButtons -------------------------------------
procedure TformExporter.SetAddRemoveButtons;
begin
bAdd.Enabled := (listboxavailable.ItemIndex <> -1);
bAddAll.Enabled := listboxavailable.Items.Count > listboxfields.Items.Count;
bRemove.Enabled := listboxfields.ItemIndex <> -1;
bRemoveAll.Enabled := listboxfields.Items.Count > 0;
end;
// ----- TformExporter.SetSelectedListFields -----------------------------------
procedure TformExporter.SetSelectedListFields;
var
i:integer;
sfield:string;
begin
listboxfields.clear;
for i:=0 to storedfields.count-1 do
begin
sField := storedfields.Strings[i];
if (Source.FieldDefs.IndexOf(sField) = -1) then
continue; {** skip if the stored field is missing}
listboxfields.Items.AddObject(sField,TField(Source.FieldByName(sField)))
end;
listboxavailable.Invalidate;
SetUpDownButtons;
end;
// ----- TformExporter.SetUpDownButtons ----------------------------------------
procedure TformExporter.SetUpDownButtons;
begin
if ListboxFields.Items.Count=0 then
begin
bUp.Enabled := false;
bDown.Enabled := false;
end else if listboxfields.ItemIndex = 0 then
begin
bUp.Enabled := false;
bDown.Enabled := true;
end else if (listBoxFields.ItemIndex = listboxFields.Items.Count-1) then
begin
bUp.Enabled := true;
bDown.Enabled := false;
end else if (listboxfields.ItemIndex <> -1) then
begin
bUp.Enabled := true;
bDown.Enabled := true;
end else
begin
bUp.Enabled := false;
bDown.Enabled := false;
end;
end;
// ----- TformExporter.cbDateTimeFieldChange -----------------------------------
procedure TformExporter.cbDateTimeFieldChange(Sender: TObject);
var
aField:TField;
begin
aField:=Source.Fields.FindField(cbDateTimeField.Text);
if (aField = nil) then
exit;
if (aField is TDateField) then
begin
dtpLowerTime.Enabled := false;
dtpUpperTime.Enabled := false;
dtpLowerTime.Time := 0.0;
dtpUpperTime.TIme := 0.0;
end else
begin
dtpLowerTime.Enabled := (true and cbxLowerBound.CHecked);
dtpUpperTime.Enabled := (true and cbxUpperBound.Checked);
end;
dtpLowerDate.Enabled := (true and cbxLowerBound.CHecked);
dtpUpperDate.Enabled := (true and cbxUpperBound.Checked);
end;
// --------- TformExporter.CopySettings ----------------------------------------
procedure TformExporter.CopySettings(bOpen,bFields,bHidden,
bLowTime,bHighTime,bDelimitEverything,bAcceptDateBounds:boolean;
aLowDateTime,aHighDateTime:TDateTime;sDelimiter:string;iPrecision:integer);
begin
cbxOpenAfterExport.Checked:= bOpen;
cbxOutputHeader.Checked := bFields;
cbxLowerBound.Checked := bLowTime;
cbxUpperBound.Checked := bHighTime;
try
dtpLowerDate.DateTime := aLowDateTime;
except
dtpLowerDate.DateTime := now;
end;
try
dtpLowerTime.DateTime := aLowDateTime;
except
dtpLowerTime.DateTime := now;
end;
cbxAcceptDateBounds.Checked := bAcceptDateBounds;
try
dtpUpperDate.DateTime := aHighDateTime;
except
dtpUpperDate.dateTime := now;
end;
try
dtpUpperTime.DateTime := aHighDateTime;
except
dtpUpperTime.DateTime := now;
end;
cbLatexColType.ItemIndex := 0;
if (sDelimiter = '''') then
cbDelimiter.ItemIndex := 1
else if (sDelimiter = '"') then
cbDelimiter.ItemIndex := 2
else
cbDelimiter.ItemIndex := 0;
cbxOnlyStrings.Checked := not bDelimitEverything;
end;
// ------ TformExporter.CopyLatexSettings --------------------------------------
procedure TformExporter.CopyLatexSettings(sEnvironment:string;
bhline,bvrule:boolean);
begin
if sEnvironment = 'longtable' then
cbLatexEnvironment.ItemIndex := 0
else
cbLatexEnvironment.Itemindex := 1;
cbLatexColType.ItemIndex := 0;
cbxhlines.CHecked := bHLine;
cbxvrules.Checked := bVRule;
end;
// --------- TformExporter.SaveSettings ----------------------------------------
procedure TformExporter.SaveSettings(var bOpen,bFields,bHidden,
bLowTime,bHighTime,bDelimitEverything,bAcceptDateBounds:boolean;
var aLowDateTime,aHighDateTime:TDateTime;
var sDateTimeField,sDelimiter:string;var iprecision:integer);
begin
bOpen:=cbxOpenAfterExport.Checked;
bFields:=cbxOutputHeader.CHecked;
bLowTime := cbxLowerBound.Checked;
bHighTime := cbxUpperBound.Checked;
bAcceptDateBounds := cbxAcceptDateBounds.Checked;
if pnlDateFiltering.Visible then
begin
aLowDateTime := Trunc(dtpLowerDate.DateTime) + Frac(dtpLowerTime.DateTime);
aHighDateTime := Trunc(dtpUpperDate.DateTime) + Frac(dtpUpperTime.DateTime);
sDateTimeField := cbDateTimeField.Text
end else
sDateTimeField := '';
if cbDelimiter.ItemIndex = 1 then
sDelimiter := ''''
else if cbDelimiter.ItemIndex = 2 then
sDelimiter := '"'
else
sDelimiter := '';
bDelimitEverything := not cbxOnlyStrings.Checked;
iPrecision := 15;
end;
// ------ TformExporter.SaveLatexSettings --------------------------------------
procedure TformExporter.SaveLatexSettings(var sEnvironment:string; var bHline,
bVrule:boolean);
begin
sEnvironment := cbLatexEnvironment.Text;
bHline := cbxhlines.CHecked;
bVRule := cbxvrules.CHecked;
end;
//------ TformExporter.GenerateListFields --------------------------------------
{** this generates a list of field names from the source table}
procedure TformExporter.GenerateListFields;
var
i:integer;
sField:string;
begin
listboxavailable.Clear;
listboxfields.Clear;
// loop over all the source fields
for i:=0 to Source.FieldCount-1 do
begin
sField := Source.Fields[i].FieldName;
listboxavailable.Items.AddObject(sField,TField(Source.Fields[i]));
end;
end;
// ------ TformExporter.PrepCaption --------------------------------------------
procedure TformExporter.PrepCaption(iType:integer;LaTexEnvironment:string;
LatexHLine,LatexVRule:boolean);
begin
case iType of
{** CSV}
0: begin
Caption := 'Export to Comma Separated Value File';
bOK.Caption := 'Save';
end;
{** TSV}
1 : begin
Caption := 'Export to Tab Separated Value File';
bOk.Caption := 'Save';
end;
{** clipboard}
2: begin
Caption := 'Copy to Clipboard';
bOk.Caption := 'Copy';
end;
{** SSV}
3: begin
Caption := 'Export to Space Separated Value File';
bOk.Caption := 'Save';
end;
{** XML}
4: begin
Caption := 'Export to XML File';
bOK.Caption := 'Save';
end;
{** LaTeX}
5: begin
Caption := 'Export to LaTeX File';
CopyLaTeXSettings(LatexEnvironment,LatexHLine,LatexVRule);
bOk.Caption := 'Save';
end;
end;
end;
// ------ TformExporter.PrepFilters --------------------------------------------
procedure TformExporter.PrepFilters(sDateTimeFilterField:string;sl:TStringList);
begin
if (sl.Count > 0) then
begin
pnlDateFiltering.Visible := true;
cbDateTimeField.Items.Assign(sl);
cbDateTimeField.ItemIndex := cbDateTimeField.Items.
IndexOf(sDateTimeFilterField);
cbDateTimeFieldChange(nil);
end else
pnlDateFiltering.Visible := false;
end;
// ----- TformExporter.bOKClick ------------------------------------------------
procedure TformExporter.bOKClick(Sender: TObject);
var
i:integer;
sField : string;
begin
storedFields.Clear;
for i:=0 to listboxfields.Items.Count-1 do
begin
sfield := TField(listboxfields.Items.Objects[i]).FieldName;
storedfields.Add(sField);
end;
end;
procedure TformExporter.FormCreate(Sender: TObject);
begin
storedFields := TStringList.Create;
end;
procedure TformExporter.FormDestroy(Sender: TObject);
begin
storedfields.Free;
end;
procedure TformExporter.FormShow(Sender: TObject);
begin
GenerateListFields;
SetSelectedListFields;
SetUpDownButtons;
listboxAvailable.SetFocus;
end;
procedure TformExporter.cbxLowerBoundClick(Sender: TObject);
begin
cbDateTimeFieldCHange(nil);
end;
procedure TformExporter.cbxUpperBoundClick(Sender: TObject);
begin
cbDateTimeFieldChange(nil);
end;
// ----- TformExporter.FormClose -----------------------------------------------
procedure TformExporter.FormClose(Sender: TObject;
var Action: TCloseAction);
var
low,high : TDateTime;
begin
{** check for the dates}
if ((ModalResult = mrOK) and cbxLowerBound.Checked and cbxUpperBound.Checked) then
begin
low := dtpLowerDate.Date + dtpLowerTime.Time;
high := dtpUpperDate.Date + dtpUpperTime.Time;
if (low >= high) then
begin
MessageDlg('You selected bounded date-time filtering.'+
'The lower Bound must '+#13+#10+'be less than the upper bound.'+
'Please correct!', mtWarning, [mboK], 0);
Action := caNone;
end;
end;
end;
// ----- TformExporter.bAddAllClick --------------------------------------------
procedure TformExporter.bAddAllClick(Sender: TObject);
var
i:integer;
begin
// don't add any in the sort fields
listboxfields.Items.Clear;
for i:=0 to listboxavailable.Items.Count-1 do
if (listboxfields.Items.IndexOf(listboxavailable.Items.Strings[i])=-1) then
listboxfields.Items.AddObject(listboxavailable.Items.Strings[i],
listboxavailable.Items.Objects[i]);
listboxavailable.Invalidate;
SetAddRemoveButtons;
SetUpDownButtons;
end;
procedure TformExporter.bUpClick(Sender: TObject);
begin
listBoxFields.Items.Exchange(listboxfields.ItemIndex,listboxfields.ItemIndex-1);
SetUpDownButtons;
end;
procedure TformExporter.bDownClick(Sender: TObject);
begin
listBoxFields.Items.Exchange(listboxfields.ItemIndex,listboxfields.ItemIndex+1);
SetUpDownButtons;
end;
procedure TformExporter.bRemoveClick(Sender: TObject);
var
i: integer;
begin
i := listboxfields.ItemIndex;
if i <> -1 then
listboxfields.Items.Delete(i);
listboxavailable.Invalidate;
SetAddRemoveButtons;
SetUpDownButtons;
end;
procedure TformExporter.bRemoveAllClick(Sender: TObject);
begin
listboxfields.Items.Clear;
listboxavailable.Invalidate;
SetAddRemoveButtons;
SetUpDownButtons;
end;
procedure TformExporter.listboxavailableDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
with (Control as TListBox).Canvas do
begin
FillRect(Rect);
if not (odSelected in State) then
if (listboxFields.Items.IndexOf(listboxavailable.Items[Index]) <> -1) then
Font.Color := clMaroon
else
Font.Color := clBlack;
TextOut(Rect.Left, Rect.Top, (Control as TListBox).Items[Index]);
end;
end;
procedure TformExporter.listboxavailableDblClick(Sender: TObject);
begin
bAddClick(nil);
end;
procedure TformExporter.listboxfieldsDblClick(Sender: TObject);
begin
bRemoveClick(nil);
end;
procedure TformExporter.listboxfieldsClick(Sender: TObject);
begin
SetAddRemoveButtons;
SetUpdownButtons;
end;
procedure TformExporter.dtpLowerDateChange(Sender: TObject);
begin
cbxUseDateLimits.Checked := false;
end;
procedure TformExporter.dtpLowerTimeChange(Sender: TObject);
begin
cbxUseDateLimits.Checked :=false;
end;
procedure TformExporter.dtpUpperDateChange(Sender: TObject);
begin
cbxUseDateLimits.Checked := false;
end;
procedure TformExporter.dtpUpperTimeChange(Sender: TObject);
begin
cbxUseDateLimits.Checked := false;
end;
// ----- TformExporter.cbxUseDateLimitsClick -----------------------------------
procedure TformExporter.cbxUseDateLimitsClick(Sender: TObject);
var
aField:TField;
mindt,maxdt,currdt : TDateTime;
begin
if (not cbxUseDateLimits.Checked) then
exit;
aField := Source.Fields.FindField(cbDateTimeField.Text);
if (aField = nil) or (Source.RecordCount = 0) then
exit;
Source.DisableControls;
Source.First;
mindt := aField.AsDateTime;
maxdt := aField.AsDateTime;
while not (Source.eof) do
begin
currdt := Source.FieldByName(cbDateTimeField.Text).AsDateTime;
if (mindt > currdt)then
mindt := currdt;
if (maxdt < currdt) then
maxdt := currdt;
Source.Next;
end;
Source.EnableControls;
dtpLowerDate.DateTime := mindt;
dtpUpperDate.DateTime := maxdt;
dtpLowerTime.Time := Frac(mindt);
dtpUpperTime.Time := Frac(maxdt);
cbDateTimeFieldChange(nil);
end;
end.
|
unit uniteTestLecteurFichier;
interface
uses TestFrameWork, SysUtils, uniteLecteurFichier, uniteLecteurFichierTexte;
type
TestLecteurFichier = class (TTestCase)
published
procedure testGetTailleBonneTaille;
procedure testGetTailleFichierInexistant;
procedure testGetEnteteConcatener;
end;
implementation
procedure TestLecteurFichier.testGetTailleBonneTaille;
var lecteurFichierTest:LecteurFichier;
taille:Int64;
begin
lecteurFichierTest:=LecteurFichier.create('FichierExistant.txt');
taille:=lecteurFichierTest.getTaille;
check(taille = 4302);
LecteurFichierTest.destroy;
end;
procedure TestLecteurFichier.testGetTailleFichierInexistant;
var lecteurFichierTest:LecteurFichier;
begin
lecteurFichierTest:=LecteurFichier.create('FichierInexistant.txt');
try
lecteurFichierTest.getTaille;
fail('Une exception n''a pas été lancée');
except on e : Exception do
check(e.Message = 'Le fichier est inexistant');
end;
lecteurFichierTest.destroy;
end;
procedure TestLecteurFichier.testGetEnteteConcatener;
var lecteurFichierTest:LecteurFichier;
chaine:WideString;
begin
lecteurFichierTest:=LecteurFichier.create('FichierExistant.txt');
checkEquals(
'Accept-Ranges: bytes'+#13#10 +'Content-Length: 4302' +#13#10 + 'Content-Type: application/octet-stream'+#13#10 +#13#10,
LecteurFichierTest.getEntete);
lecteurFichierTest.destroy;
end;
initialization
TestFrameWork.RegisterTest(TestLecteurFichier.Suite);
end.
|
unit uPrices_DM;
interface
uses
SysUtils, Classes, frxExportImage, frxExportPDF, frxExportRTF,
frxExportXLS, frxClass, frxExportTXT, frxBarcode, frxDBSet, frxDesgn,
FIBQuery, pFIBQuery, pFIBStoredProc, DB, FIBDataSet, pFIBDataSet,
FIBDatabase, pFIBDatabase, RxMemDS;
type
Tfrm_price_DM = class(TDataModule)
Transaction_Read: TpFIBTransaction;
Transaction_write: TpFIBTransaction;
DataSet_read: TpFIBDataSet;
DataSet_param: TpFIBDataSet;
DataSet_main: TpFIBDataSet;
DataSource_read: TDataSource;
DataSource_param: TDataSource;
DataSource_main: TDataSource;
StoredProc: TpFIBStoredProc;
DataSet_reports: TpFIBDataSet;
Report_main: TfrxReport;
frxDesigner1: TfrxDesigner;
DBDataset_reports: TfrxDBDataset;
frxBarCodeObject1: TfrxBarCodeObject;
frxTXTExport1: TfrxTXTExport;
frxXLSExport1: TfrxXLSExport;
frxRTFExport1: TfrxRTFExport;
frxPDFExport1: TfrxPDFExport;
frxJPEGExport1: TfrxJPEGExport;
DB: TpFIBDatabase;
Global_Transaction_write: TpFIBTransaction;
Global_StoredProc: TpFIBStoredProc;
Global_DataSet: TpFIBDataSet;
DataSource_services: TDataSource;
MemoryData_services: TRxMemoryData;
MemoryData_servicesMemoryData_id: TIntegerField;
MemoryData_servicesMemoryData_name: TStringField;
MemoryData_servicesMemoryData_buget: TStringField;
MemoryData_servicesMemoryData_tariff: TFloatField;
MemoryData_servicesMemoryData_norma: TFloatField;
MemoryData_servicesMemoryData_summa: TFloatField;
MemoryData_servicesMemoryData_id_sm: TIntegerField;
MemoryData_servicesMemoryData_id_rz: TIntegerField;
MemoryData_servicesMemoryData_id_st: TIntegerField;
MemoryData_servicesMemoryData_id_kekv: TIntegerField;
MemoryData_servicesMemoryData_sm_tittle: TStringField;
MemoryData_servicesMemoryData_rz_tittle: TStringField;
MemoryData_servicesMemoryData_st_tittle: TStringField;
MemoryData_servicesMemoryData_kekv_tittle: TStringField;
MemoryData_servicesMemoryData_check_norma: TIntegerField;
MemoryData_servicesMemoryData_st_options: TIntegerField;
MemoryData_servicesMemoryData_id_type_norma: TIntegerField;
MemoryData_servicesMemoryData_name_type_norma: TStringField;
MemoryData_servicesMemoryData_date_beg: TDateField;
MemoryData_servicesMemoryData_date_end: TDateField;
private
{ Private declarations }
public
end;
var
frm_price_DM: Tfrm_price_DM;
implementation
{$R *.dfm}
{ TfrmDM }
end.
|
unit XED.RegEnum;
{$Z4}
interface
type
TXED_Reg_Enum = (
XED_REG_INVALID,
XED_REG_BNDCFGU,
XED_REG_BNDSTATUS,
XED_REG_BND0,
XED_REG_BND1,
XED_REG_BND2,
XED_REG_BND3,
XED_REG_CR0,
XED_REG_CR1,
XED_REG_CR2,
XED_REG_CR3,
XED_REG_CR4,
XED_REG_CR5,
XED_REG_CR6,
XED_REG_CR7,
XED_REG_CR8,
XED_REG_CR9,
XED_REG_CR10,
XED_REG_CR11,
XED_REG_CR12,
XED_REG_CR13,
XED_REG_CR14,
XED_REG_CR15,
XED_REG_DR0,
XED_REG_DR1,
XED_REG_DR2,
XED_REG_DR3,
XED_REG_DR4,
XED_REG_DR5,
XED_REG_DR6,
XED_REG_DR7,
XED_REG_FLAGS,
XED_REG_EFLAGS,
XED_REG_RFLAGS,
XED_REG_AX,
XED_REG_CX,
XED_REG_DX,
XED_REG_BX,
XED_REG_SP,
XED_REG_BP,
XED_REG_SI,
XED_REG_DI,
XED_REG_R8W,
XED_REG_R9W,
XED_REG_R10W,
XED_REG_R11W,
XED_REG_R12W,
XED_REG_R13W,
XED_REG_R14W,
XED_REG_R15W,
XED_REG_EAX,
XED_REG_ECX,
XED_REG_EDX,
XED_REG_EBX,
XED_REG_ESP,
XED_REG_EBP,
XED_REG_ESI,
XED_REG_EDI,
XED_REG_R8D,
XED_REG_R9D,
XED_REG_R10D,
XED_REG_R11D,
XED_REG_R12D,
XED_REG_R13D,
XED_REG_R14D,
XED_REG_R15D,
XED_REG_RAX,
XED_REG_RCX,
XED_REG_RDX,
XED_REG_RBX,
XED_REG_RSP,
XED_REG_RBP,
XED_REG_RSI,
XED_REG_RDI,
XED_REG_R8,
XED_REG_R9,
XED_REG_R10,
XED_REG_R11,
XED_REG_R12,
XED_REG_R13,
XED_REG_R14,
XED_REG_R15,
XED_REG_AL,
XED_REG_CL,
XED_REG_DL,
XED_REG_BL,
XED_REG_SPL,
XED_REG_BPL,
XED_REG_SIL,
XED_REG_DIL,
XED_REG_R8B,
XED_REG_R9B,
XED_REG_R10B,
XED_REG_R11B,
XED_REG_R12B,
XED_REG_R13B,
XED_REG_R14B,
XED_REG_R15B,
XED_REG_AH,
XED_REG_CH,
XED_REG_DH,
XED_REG_BH,
XED_REG_ERROR,
XED_REG_RIP,
XED_REG_EIP,
XED_REG_IP,
XED_REG_K0,
XED_REG_K1,
XED_REG_K2,
XED_REG_K3,
XED_REG_K4,
XED_REG_K5,
XED_REG_K6,
XED_REG_K7,
XED_REG_MMX0,
XED_REG_MMX1,
XED_REG_MMX2,
XED_REG_MMX3,
XED_REG_MMX4,
XED_REG_MMX5,
XED_REG_MMX6,
XED_REG_MMX7,
XED_REG_SSP,
XED_REG_IA32_U_CET,
XED_REG_MXCSR,
XED_REG_STACKPUSH,
XED_REG_STACKPOP,
XED_REG_GDTR,
XED_REG_LDTR,
XED_REG_IDTR,
XED_REG_TR,
XED_REG_TSC,
XED_REG_TSCAUX,
XED_REG_MSRS,
XED_REG_FSBASE,
XED_REG_GSBASE,
XED_REG_X87CONTROL,
XED_REG_X87STATUS,
XED_REG_X87TAG,
XED_REG_X87PUSH,
XED_REG_X87POP,
XED_REG_X87POP2,
XED_REG_X87OPCODE,
XED_REG_X87LASTCS,
XED_REG_X87LASTIP,
XED_REG_X87LASTDS,
XED_REG_X87LASTDP,
XED_REG_CS,
XED_REG_DS,
XED_REG_ES,
XED_REG_SS,
XED_REG_FS,
XED_REG_GS,
XED_REG_TMP0,
XED_REG_TMP1,
XED_REG_TMP2,
XED_REG_TMP3,
XED_REG_TMP4,
XED_REG_TMP5,
XED_REG_TMP6,
XED_REG_TMP7,
XED_REG_TMP8,
XED_REG_TMP9,
XED_REG_TMP10,
XED_REG_TMP11,
XED_REG_TMP12,
XED_REG_TMP13,
XED_REG_TMP14,
XED_REG_TMP15,
XED_REG_ST0,
XED_REG_ST1,
XED_REG_ST2,
XED_REG_ST3,
XED_REG_ST4,
XED_REG_ST5,
XED_REG_ST6,
XED_REG_ST7,
XED_REG_XCR0,
XED_REG_XMM0,
XED_REG_XMM1,
XED_REG_XMM2,
XED_REG_XMM3,
XED_REG_XMM4,
XED_REG_XMM5,
XED_REG_XMM6,
XED_REG_XMM7,
XED_REG_XMM8,
XED_REG_XMM9,
XED_REG_XMM10,
XED_REG_XMM11,
XED_REG_XMM12,
XED_REG_XMM13,
XED_REG_XMM14,
XED_REG_XMM15,
XED_REG_XMM16,
XED_REG_XMM17,
XED_REG_XMM18,
XED_REG_XMM19,
XED_REG_XMM20,
XED_REG_XMM21,
XED_REG_XMM22,
XED_REG_XMM23,
XED_REG_XMM24,
XED_REG_XMM25,
XED_REG_XMM26,
XED_REG_XMM27,
XED_REG_XMM28,
XED_REG_XMM29,
XED_REG_XMM30,
XED_REG_XMM31,
XED_REG_YMM0,
XED_REG_YMM1,
XED_REG_YMM2,
XED_REG_YMM3,
XED_REG_YMM4,
XED_REG_YMM5,
XED_REG_YMM6,
XED_REG_YMM7,
XED_REG_YMM8,
XED_REG_YMM9,
XED_REG_YMM10,
XED_REG_YMM11,
XED_REG_YMM12,
XED_REG_YMM13,
XED_REG_YMM14,
XED_REG_YMM15,
XED_REG_YMM16,
XED_REG_YMM17,
XED_REG_YMM18,
XED_REG_YMM19,
XED_REG_YMM20,
XED_REG_YMM21,
XED_REG_YMM22,
XED_REG_YMM23,
XED_REG_YMM24,
XED_REG_YMM25,
XED_REG_YMM26,
XED_REG_YMM27,
XED_REG_YMM28,
XED_REG_YMM29,
XED_REG_YMM30,
XED_REG_YMM31,
XED_REG_ZMM0,
XED_REG_ZMM1,
XED_REG_ZMM2,
XED_REG_ZMM3,
XED_REG_ZMM4,
XED_REG_ZMM5,
XED_REG_ZMM6,
XED_REG_ZMM7,
XED_REG_ZMM8,
XED_REG_ZMM9,
XED_REG_ZMM10,
XED_REG_ZMM11,
XED_REG_ZMM12,
XED_REG_ZMM13,
XED_REG_ZMM14,
XED_REG_ZMM15,
XED_REG_ZMM16,
XED_REG_ZMM17,
XED_REG_ZMM18,
XED_REG_ZMM19,
XED_REG_ZMM20,
XED_REG_ZMM21,
XED_REG_ZMM22,
XED_REG_ZMM23,
XED_REG_ZMM24,
XED_REG_ZMM25,
XED_REG_ZMM26,
XED_REG_ZMM27,
XED_REG_ZMM28,
XED_REG_ZMM29,
XED_REG_ZMM30,
XED_REG_ZMM31,
XED_REG_LAST,
XED_REG_BNDCFG_FIRST=XED_REG_BNDCFGU, //< PSEUDO
XED_REG_BNDCFG_LAST=XED_REG_BNDCFGU, //<PSEUDO
XED_REG_BNDSTAT_FIRST=XED_REG_BNDSTATUS, //< PSEUDO
XED_REG_BNDSTAT_LAST=XED_REG_BNDSTATUS, //<PSEUDO
XED_REG_BOUND_FIRST=XED_REG_BND0, //< PSEUDO
XED_REG_BOUND_LAST=XED_REG_BND3, //<PSEUDO
XED_REG_CR_FIRST=XED_REG_CR0, //< PSEUDO
XED_REG_CR_LAST=XED_REG_CR15, //<PSEUDO
XED_REG_DR_FIRST=XED_REG_DR0, //< PSEUDO
XED_REG_DR_LAST=XED_REG_DR7, //<PSEUDO
XED_REG_FLAGS_FIRST=XED_REG_FLAGS, //< PSEUDO
XED_REG_FLAGS_LAST=XED_REG_RFLAGS, //<PSEUDO
XED_REG_GPR16_FIRST=XED_REG_AX, //< PSEUDO
XED_REG_GPR16_LAST=XED_REG_R15W, //<PSEUDO
XED_REG_GPR32_FIRST=XED_REG_EAX, //< PSEUDO
XED_REG_GPR32_LAST=XED_REG_R15D, //<PSEUDO
XED_REG_GPR64_FIRST=XED_REG_RAX, //< PSEUDO
XED_REG_GPR64_LAST=XED_REG_R15, //<PSEUDO
XED_REG_GPR8_FIRST=XED_REG_AL, //< PSEUDO
XED_REG_GPR8_LAST=XED_REG_R15B, //<PSEUDO
XED_REG_GPR8h_FIRST=XED_REG_AH, //< PSEUDO
XED_REG_GPR8h_LAST=XED_REG_BH, //<PSEUDO
XED_REG_INVALID_FIRST=XED_REG_INVALID, //< PSEUDO
XED_REG_INVALID_LAST=XED_REG_ERROR, //<PSEUDO
XED_REG_IP_FIRST=XED_REG_RIP, //< PSEUDO
XED_REG_IP_LAST=XED_REG_IP, //<PSEUDO
XED_REG_MASK_FIRST=XED_REG_K0, //< PSEUDO
XED_REG_MASK_LAST=XED_REG_K7, //<PSEUDO
XED_REG_MMX_FIRST=XED_REG_MMX0, //< PSEUDO
XED_REG_MMX_LAST=XED_REG_MMX7, //<PSEUDO
XED_REG_MSR_FIRST=XED_REG_SSP, //< PSEUDO
XED_REG_MSR_LAST=XED_REG_IA32_U_CET, //<PSEUDO
XED_REG_MXCSR_FIRST=XED_REG_MXCSR, //< PSEUDO
XED_REG_MXCSR_LAST=XED_REG_MXCSR, //<PSEUDO
XED_REG_PSEUDO_FIRST=XED_REG_STACKPUSH, //< PSEUDO
XED_REG_PSEUDO_LAST=XED_REG_GSBASE, //<PSEUDO
XED_REG_PSEUDOX87_FIRST=XED_REG_X87CONTROL, //< PSEUDO
XED_REG_PSEUDOX87_LAST=XED_REG_X87LASTDP, //<PSEUDO
XED_REG_SR_FIRST=XED_REG_CS, //< PSEUDO
XED_REG_SR_LAST=XED_REG_GS, //<PSEUDO
XED_REG_TMP_FIRST=XED_REG_TMP0, //< PSEUDO
XED_REG_TMP_LAST=XED_REG_TMP15, //<PSEUDO
XED_REG_X87_FIRST=XED_REG_ST0, //< PSEUDO
XED_REG_X87_LAST=XED_REG_ST7, //<PSEUDO
XED_REG_XCR_FIRST=XED_REG_XCR0, //< PSEUDO
XED_REG_XCR_LAST=XED_REG_XCR0, //<PSEUDO
XED_REG_XMM_FIRST=XED_REG_XMM0, //< PSEUDO
XED_REG_XMM_LAST=XED_REG_XMM31, //<PSEUDO
XED_REG_YMM_FIRST=XED_REG_YMM0, //< PSEUDO
XED_REG_YMM_LAST=XED_REG_YMM31, //<PSEUDO
XED_REG_ZMM_FIRST=XED_REG_ZMM0, //< PSEUDO
XED_REG_ZMM_LAST=XED_REG_ZMM31);//<PSEUDO);
/// This converts strings to #xed_reg_enum_t types.
/// @param s A C-string.
/// @return #xed_reg_enum_t
/// @ingroup ENUM
function str2xed_reg_enum_t(s: PAnsiChar): TXED_Reg_Enum; cdecl; external 'xed.dll';
/// This converts strings to #xed_reg_enum_t types.
/// @param p An enumeration element of type xed_reg_enum_t.
/// @return string
/// @ingroup ENUM
function xed_reg_enum_t2str(const p: TXED_Reg_Enum): PAnsiChar; cdecl; external 'xed.dll';
/// Returns the last element of the enumeration
/// @return xed_reg_enum_t The last element of the enumeration.
/// @ingroup ENUM
function xed_reg_enum_t_last:TXED_Reg_Enum;cdecl; external 'xed.dll';
implementation
end.
|
unit Mail4Delphi.Intf;
interface
type
IMail = interface
['{A63918AD-EA2C-4CB9-98C5-90C3BAB95144}']
function AddTo(const AMail: string; const AName: string = ''): IMail;
function AddFrom(const AMail: string; const AName: string = ''): IMail;
function ReceiptRecipient(const AValue: Boolean): IMail;
function AddSubject(const ASubject: string): IMail;
function AddReplyTo(const AMail: string; const AName: string = ''): IMail;
function AddCC(const AMail: string; const AName: string = ''): IMail;
function AddBCC(const AMail: string; const AName: string = ''): IMail;
function AddBody(const ABody: string): IMail;
function Host(const AHost: string): IMail;
function UserName(const AUserName: string): IMail;
function Password(const APassword: string): IMail;
function Port(const APort: Integer): IMail;
function AddAttachment(const AFile: string): IMail;
function Auth(const AValue: Boolean): IMail;
function SSL(const AValue: Boolean): IMail;
function Clear: IMail;
function SendMail: Boolean;
function SetUpEmail: Boolean;
end;
implementation
end.
|
unit frmSelectFNColorCode;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, DB, DBClient, ExtCtrls;
type
TSelectFNColorCodeForm = class(TForm)
cbbFNColorCode: TComboBox;
Label1: TLabel;
btn1: TButton;
btn2: TButton;
plShowColor: TPanel;
edtRGB: TEdit;
Label6: TLabel;
cbSimpleColor: TComboBox;
cbbDegree: TComboBox;
dsFNColor: TClientDataSet;
procedure cbbFNColorCodeChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function SelectFNColorCode(cds:TClientDataSet): String;
var
SelectFNColorCodeForm: TSelectFNColorCodeForm;
implementation
uses uGlobal;
{$R *.dfm}
function SelectFNColorCode(cds:TClientDataSet): String;
begin
SelectFNColorCodeForm:=TSelectFNColorCodeForm.Create(Application);
try
TGlobal.FillItemsFromDataSet(cds, 'FN_Color_Code','','', SelectFNColorCodeForm.cbbFNColorCode.Items);
TGlobal.FillItemsFromDataSet(cds, 'Simple_Color_Name','','', SelectFNColorCodeForm.cbSimpleColor.Items);
TGlobal.FillItemsFromDataSet(cds, 'Degree','','', SelectFNColorCodeForm.cbbDegree.Items);
{
SelectFNColorCodeForm.cbbFNColorCode.ItemIndex := 1;
SelectFNColorCodeForm.cbSimpleColor.ItemIndex := SelectFNColorCodeForm.cbbFNColorCode.ItemIndex;
SelectFNColorCodeForm.cbbDegree.ItemIndex := SelectFNColorCodeForm.cbbFNColorCode.ItemIndex;
}
SelectFNColorCodeForm.dsFNColor.Data := cds.Data;
SelectFNColorCodeForm.ShowModal;
if SelectFNColorCodeForm.ModalResult = mrCancel then
Result:=''
else
begin
Result:=SelectFNColorCodeForm.cbbFNColorCode.Text;
end;
finally
FreeAndNil(SelectFNColorCodeForm);
end;
end;
procedure TSelectFNColorCodeForm.cbbFNColorCodeChange(Sender: TObject);
begin
if cbbFNColorCode.ItemIndex>=0 then
begin
if dsFNColor.Active then
begin
if dsFNColor.Locate('FN_Color_Code', cbbFNColorCode.Text, []) then
begin
TGlobal.SetComboBoxValue(cbSimpleColor, dsFNColor.FieldByName('Simple_Color_Name').AsString);
TGlobal.SetComboBoxValue(cbbDegree, dsFNColor.FieldByName('Degree').AsString);
//cbSimpleColor.Text := dsFNColor.FieldByName('Simple_Color_Name').AsString;
//cbbDegree.Text := dsFNColor.FieldByName('Degree').AsString;
edtRGB.Text := dsFNColor.FieldByName('RGB').AsString;
plShowColor.Color := dsFNColor.FieldByName('RGB').AsInteger;
end
end
end
end;
end.
|
namespace proholz.xsdparser;
interface
type
XsdChoiceVisitor = public class(XsdAnnotatedElementsVisitor)
private
// *
// * The {@link XsdChoice} instance which owns this {@link XsdChoiceVisitor} instance. This way this visitor instance
// * can perform changes in the {@link XsdChoice} object.
//
//
var owner: XsdChoice;
public
constructor(aowner: XsdChoice);
method visit(element: XsdElement); override;
method visit(element: XsdGroup); override;
method visit(element: XsdChoice); override;
method visit(element: XsdSequence); override;
end;
implementation
constructor XsdChoiceVisitor(aowner: XsdChoice);
begin
inherited constructor(aowner);
self.owner := aowner;
end;
method XsdChoiceVisitor.visit(element: XsdElement);
begin
inherited visit(element);
owner.addElement(element);
end;
method XsdChoiceVisitor.visit(element: XsdGroup);
begin
inherited visit(element);
owner.addElement(element);
end;
method XsdChoiceVisitor.visit(element: XsdChoice);
begin
inherited visit(element);
owner.addElement(element);
end;
method XsdChoiceVisitor.visit(element: XsdSequence);
begin
inherited visit(element);
owner.addElement(element);
end;
end. |
object MainForm: TMainForm
Left = 313
Top = 190
BorderIcons = []
BorderStyle = bsSingle
Caption = 'GLSLWater demo'
ClientHeight = 480
ClientWidth = 640
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
FormStyle = fsStayOnTop
OldCreateOrder = False
Position = poDefault
WindowState = wsMaximized
OnCreate = FormCreate
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object SceneViewer: TGLSceneViewer
Left = 0
Top = 0
Width = 640
Height = 480
Camera = Camera
Buffer.FogEnvironment.FogColor.Color = {0000803F0000803F0000803F0AD7233C}
Buffer.FogEnvironment.FogStart = 300.000000000000000000
Buffer.FogEnvironment.FogEnd = 501.000000000000000000
Buffer.FogEnvironment.FogDistance = fdEyeRadial
Buffer.BackgroundColor = 16772829
Buffer.AmbientColor.Color = {9A99593F9A99593FCDCCCC3D0000803F}
Buffer.ContextOptions = [roDoubleBuffer, roRenderToWindow, roDestinationAlpha, roNoColorBufferClear]
Buffer.FogEnable = True
Buffer.AntiAliasing = aaNone
FieldOfView = 134.760269165039100000
Align = alClient
TabOrder = 0
end
object Scene: TGLScene
ObjectsSorting = osRenderFarthestFirst
Left = 64
Top = 76
object ground: TGLFreeForm
Direction.Coordinates = {000000280000803F2EBDBBB300000000}
PitchAngle = 180.000000000000000000
Up.Coordinates = {2EBD3B9C2EBDBBB3000080BF00000000}
end
object forest: TGLFreeForm
Direction.Coordinates = {000000000000803F2EBDBBB300000000}
PitchAngle = 180.000000000000000000
Up.Coordinates = {000000002EBDBBB3000080BF00000000}
end
object mountains: TGLFreeForm
Direction.Coordinates = {000000000000803F2EBDBBB300000000}
PitchAngle = 180.000000000000000000
Up.Coordinates = {000000002EBDBBB3000080BF00000000}
end
object FPS: TGLHUDText
Rotation = 0.000000000000000000
ModulateColor.Color = {0000803FF8FEFE3E000000000000803F}
end
object dScene: TGLDummyCube
CubeSize = 1.000000000000000000
end
object Camera: TGLCamera
DepthOfView = 500.000000000000000000
FocalLength = 100.000000000000000000
TargetObject = ground
Position.Coordinates = {000000000000A040000016430000803F}
object LightSource: TGLLightSource
Ambient.Color = {0000803F0000803F0000803F0000803F}
ConstAttenuation = 1.000000000000000000
Specular.Color = {0000803F0000803F0000803F0000803F}
SpotCutOff = 180.000000000000000000
end
end
end
object Cadencer: TGLCadencer
Scene = Scene
OnProgress = CadencerProgress
Left = 100
Top = 70
end
object FPSTimer: TTimer
Interval = 200
OnTimer = FPSTimerTimer
Left = 30
Top = 58
end
end
|
program HowToControlSound;
uses
SwinGame, sgTypes;
procedure Main();
var
sndEffect : SoundEffect;
begin
OpenAudio();
OpenGraphicsWindow('How To Control Sound', 320, 240);
LoadDefaultColors();
sndEffect := LoadSoundEffect('chipmunk.ogg');
LoadSoundEffect('bells.ogg');
LoadSoundEffect('camera.ogg');
LoadSoundEffect('comedy_boing.ogg');
LoadSoundEffect('dinosaur.ogg');
LoadSoundEffect('dog_bark.ogg');
repeat // The game loop...
ProcessEvents();
if KeyDown(RightCtrlKey) OR KeyDown(LeftCtrlKey) then
begin
if KeyTyped(Key1) then sndEffect := SoundEffectNamed('chipmunk.ogg');
if KeyTyped(Key2) then sndEffect := SoundEffectNamed('bells.ogg');
if KeyTyped(Key3) then sndEffect := SoundEffectNamed('camera.ogg');
if KeyTyped(Key4) then sndEffect := SoundEffectNamed('comedy_boing.ogg');
if KeyTyped(Key5) then sndEffect := SoundEffectNamed('dinosaur.ogg');
if KeyTyped(Key6) then sndEffect := SoundEffectNamed('dog_bark.ogg');
end
else
begin
if KeyTyped(Key1) then PlaySoundEffect(sndEffect);
if KeyTyped(Key2) then PlaySoundEffect(sndEffect, 0.5);
if KeyTyped(Key3) then PlaySoundEffect(sndEffect, 3, 0.25);
if KeyTyped(Key4) then PlaySoundEffect(sndEffect, -1, 0.1);
if KeyTyped(Key5) then if SoundEffectPlaying(sndEffect) then StopSoundEffect(sndEffect);
end;
ClearScreen(ColorWhite);
DrawText('Control Sound (Escape or q to quit)', ColorRed, 'Arial', 18, 15, 15);
DrawText('1: Play Sound At Full Volume', ColorBlue, 'Arial', 14, 20, 50);
DrawText('2: Play Sound At 50% Volume', ColorBlue, 'Arial', 14, 20, 80);
DrawText('3: Play Sound At 25% Volume 3 Times', ColorBlue, 'Arial', 14, 20, 110);
DrawText('4: Play Sound Continuously at 10%', ColorBlue, 'Arial', 14, 20, 140);
DrawText('5: Stop Playing Current Sound', ColorBlue, 'Arial', 14, 20, 170);
DrawText('CTRL + (1-6) load different sound effects', ColorBlue, 'Arial', 14, 20, 200);
RefreshScreen(60);
until WindowCloseRequested() OR KeyTyped(EscapeKey) OR KeyTyped(QKey);
CloseAudio();
ReleaseAllResources();
end;
begin
Main();
end. |
unit FaceQueue;
interface
type
PFaceData = ^TFaceData;
TFaceData = record
v1,v2,v3 : integer;
location: integer;
Next : PFaceData;
end;
CFaceQueue = class
private
Start,Last : PFaceData;
procedure Reset;
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// Add
procedure Add (_v1,_v2,_v3 : integer);
procedure Delete(var _item: PFaceData);
// Delete
procedure Clear;
// Gets
function IsEmpty: boolean;
// Misc
function GetFirstElement: PFaceData;
function GetLastElement: PFaceData;
end;
implementation
constructor CFaceQueue.Create;
begin
Reset;
end;
destructor CFaceQueue.Destroy;
begin
Clear;
Reset;
inherited Destroy;
end;
procedure CFaceQueue.Reset;
begin
Start := nil;
Last := nil;
end;
// Add
procedure CFaceQueue.Add (_v1,_v2,_v3 : integer);
var
NewPosition : PFaceData;
begin
New(NewPosition);
NewPosition^.V1 := _v1;
NewPosition^.V2 := _v2;
NewPosition^.V3 := _v3;
NewPosition^.location := -1;
NewPosition^.Next := nil;
if Start <> nil then
begin
Last^.Next := NewPosition;
end
else
begin
Start := NewPosition;
end;
Last := NewPosition;
end;
// Delete
procedure CFaceQueue.Delete(var _item: PFaceData);
var
Previous : PFaceData;
begin
if _Item <> nil then
begin
Previous := Start;
if _Item = Start then
begin
Start := Start^.Next;
end
else
begin
while Previous^.Next <> _Item do
begin
Previous := Previous^.Next;
end;
Previous^.Next := _Item^.Next;
if _Item = Last then
begin
Last := Previous;
end;
end;
Dispose(_Item);
end;
end;
procedure CFaceQueue.Clear;
var
Item,Garbage : PFaceData;
begin
Item := Start;
while Item <> nil do
begin
Garbage := Item;
Item := Item^.Next;
dispose(Garbage);
end;
end;
// Gets
function CFaceQueue.IsEmpty: boolean;
begin
Result := (Start = nil);
end;
// Misc
function CFaceQueue.GetFirstElement: PFaceData;
begin
Result := Start;
end;
function CFaceQueue.GetLastElement: PFaceData;
begin
Result := Last;
end;
end.
|
unit ServerMethodsUnit1;
interface
uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, unit1, DBXJSON,
Data.DB, system.JSON, uclasses, dialogs, shellapi, forms;
type
{$METHODINFO ON}
TServerMethods1 = class(TComponent)
private
{ Private declarations }
public
{ Public declarations }
erro : integer;
function insereVendas(const lista : TlistaVendas; const usuario : String) : String;
function getProdutos() : TJSONValue;
function getProdutos1() : TlistaProdutos;
function getFormas() : TlistaFormas;
function getcliente(cnpj: string) : Tcliente;
function getUsuarios() : TlistaUsuario;
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
procedure execSql(const sql : string);
function soma(v1, v2 : currency) : TJSONValue;
function RecordCountProdutosInteger() : Integer;
end;
{$METHODINFO OFF}
implementation
uses System.StrUtils;
function TServerMethods1.insereVendas(const lista : TlistaVendas; const usuario : String) : String;
var
ini, i, fimI, fimV, nota, cliente : integer;
totPrest, totItemV, totItemC, entrada, total : currency;
clienteNome : String;
notasImp : TStringList;
const sqlVenda : String = 'insert into venda(nota, entrada, desconto, data, cliente, total, vendedor' +
', codhis, usuario, hora, datamov, tipo) values(:nota, :entrada, :desconto, :data, :cliente, :total, :vendedor, :codhis, :usuario, :hora, :datamov, ''V'')';
begin
Result := '';
form1.adicionaMemo('Serviço: Sincronização de Vendas');
form1.adicionaMemo('Usuário: ' + usuario);
form1.adicionaMemo('Data:' + FormatDateTime('dd/mm/yyyy hh:mm:ss', now));
form1.adicionaMemo('--------------------------------------');
Result := '';
fimV := Length(lista.listaVenda) -1;
Form1.IBQuery1.Close;
Form1.IBQuery1.SQL.Text := sqlVenda;
//+funcoes.novocod('creceber')+
form1.IBQuery2.Close;
form1.IBQuery2.SQL.Text := 'insert into contasreceber(nota,codgru, cod,formpagto,datamov,vendedor,data,vencimento,documento,codhis,historico,total,valor)' +
'values(:nota, 1, :cod, :codhis, :datamov, :vendedor,:data, :vencimento,:documento,2,:hist,:total,:valor)';
form1.IBQuery3.Close;
form1.IBQuery3.SQL.Text := 'insert into item_venda(data,nota,COD, QUANT, p_venda,total,origem,p_compra,codbar,aliquota, unid)' +
' values(:data,:nota,:cod, :quant, :p_venda,:total,:origem,:p_compra, :codbar,:aliq, :unid)';
form1.IBTransaction1.StartTransaction;
//ShowMessage('recCount = ' + IntToStr(fimV));
notasImp := TStringList.Create;
for ini := 0 to fimV do
begin
erro := 0;
entrada := 0;
total := lista.listaVenda[ini].total;
try
nota := StrToIntDef(form1.Incrementa_Generator('venda', 1), 1);
cliente := form1.insereClienteRetornaCodigo(lista.listaVenda[ini].cliente, clienteNome, erro);
if lista.listaVenda[ini].parcelamento <> nil then
begin
entrada := lista.listaVenda[ini].parcelamento.entrada;
//total := lista.listaVenda[ini].total - entrada;
total := lista.listaVenda[ini].total;
totPrest := ((total) / lista.listaVenda[ini].parcelamento.qtdprest);
for I := 1 to lista.listaVenda[ini].parcelamento.qtdprest do
begin
form1.IBQuery2.Close;
form1.IBQuery2.ParamByName('nota').AsInteger := nota;
form1.IBQuery2.ParamByName('cod').AsString := form1.Incrementa_Generator('creceber', 1);
form1.IBQuery2.ParamByName('codhis').AsInteger := lista.listaVenda[ini].codhis;
form1.IBQuery2.ParamByName('datamov').AsDate := now;
form1.IBQuery2.ParamByName('vendedor').AsInteger := lista.listaVenda[ini].vendedor;
form1.IBQuery2.ParamByName('data').AsDate := lista.listaVenda[ini].parcelamento.data;
if i = 1 then form1.IBQuery2.ParamByName('vencimento').AsDate := lista.listaVenda[ini].parcelamento.vencimento
else form1.IBQuery2.ParamByName('vencimento').AsDate := lista.listaVenda[ini].parcelamento.vencimento + lista.listaVenda[ini].parcelamento.periodo;
form1.IBQuery2.ParamByName('documento').AsInteger := lista.listaVenda[ini].vendedor;
form1.IBQuery2.ParamByName('hist').AsString := Form1.CompletaOuRepete(copy(IntToStr(nota) +'-'+clienteNome,1,28 ),Form1.CompletaOuRepete('',IntToStr(i),' ',2)+'/'+
form1.CompletaOuRepete('', IntToStr(lista.listaVenda[ini].parcelamento.qtdprest),' ',2),' ',35);
form1.IBQuery2.ParamByName('total').AsCurrency := totPrest;
form1.IBQuery2.ParamByName('valor').AsCurrency := totPrest;
try
form1.IBQuery2.ExecSQL;
except
on e:exception do
begin
erro := 1;
form1.adicionaMemo('ERRO: ' + e.Message + #13 + ' PARCELAMENTO' + #13 + '-----------------------' + #13);
end;
end;
end;
end;
if lista.listaVenda[ini].imprime = 'S' then notasImp.Add(IntToStr(nota));
//notasImp.Add(IntToStr(nota) + '=' + CurrToStr(lista.listaVenda[ini].total));
form1.IBQuery1.SQL.Text := sqlVenda;
form1.IBQuery1.Close;
form1.IBQuery1.ParamByName('nota').AsInteger := nota;
form1.IBQuery1.ParamByName('entrada').AsCurrency := entrada;
form1.IBQuery1.ParamByName('desconto').AsCurrency := lista.listaVenda[ini].desconto;
form1.IBQuery1.ParamByName('data').AsDate := lista.listaVenda[ini].data;
form1.IBQuery1.ParamByName('cliente').AsInteger := cliente;
form1.IBQuery1.ParamByName('total').AsCurrency := total;
form1.IBQuery1.ParamByName('vendedor').AsInteger := lista.listaVenda[ini].vendedor;
form1.IBQuery1.ParamByName('codhis').AsInteger := lista.listaVenda[ini].codhis;
form1.IBQuery1.ParamByName('usuario').AsInteger := lista.listaVenda[ini].usuario;
form1.IBQuery1.ParamByName('hora').AsTime := lista.listaVenda[ini].data;
form1.IBQuery1.ParamByName('datamov').AsTime := lista.listaVenda[ini].data;
try
form1.IBQuery1.ExecSQL;
except
on e:exception do
begin
erro := 1;
form1.adicionaMemo('ERRO: ' + e.Message + #13 + ' na Venda' + #13 + '-----------------------' + #13);
end;
end;
fimI := Length(lista.listaVenda[ini].itensV) - 1;
for I := 0 to fimI do
begin
form1.IBQuery1.Close;
form1.IBQuery1.SQL.Text := 'select codbar, aliquota, unid, p_compra from produto where cod = :cod';
form1.IBQuery1.ParamByName('cod').AsInteger := lista.listaVenda[ini].itensV[i].cod;
form1.IBQuery1.Open;
totItemV := (lista.listaVenda[ini].itensV[i].p_venda * lista.listaVenda[ini].itensV[i].quant);
totItemC := (form1.IBQuery1.FieldByName('p_compra').AsCurrency * lista.listaVenda[ini].itensV[i].quant);
form1.IBQuery3.Close;
form1.IBQuery3.ParamByName('data').AsDateTime := lista.listaVenda[ini].data;
form1.IBQuery3.ParamByName('nota').AsInteger := nota;
form1.IBQuery3.ParamByName('cod').AsInteger := lista.listaVenda[ini].itensV[i].cod;
form1.IBQuery3.ParamByName('quant').AsCurrency := lista.listaVenda[ini].itensV[i].quant;
form1.IBQuery3.ParamByName('p_venda').AsCurrency := lista.listaVenda[ini].itensV[i].p_venda;
form1.IBQuery3.ParamByName('total').AsCurrency := totItemV;
form1.IBQuery3.ParamByName('origem').AsString := '1';
form1.IBQuery3.ParamByName('p_compra').AsCurrency := totItemC;
form1.IBQuery3.ParamByName('codbar').AsString := form1.IBQuery1.FieldByName('codbar').AsString;
form1.IBQuery3.ParamByName('aliq').AsString := copy(form1.IBQuery1.FieldByName('aliquota').AsString, 1, 2);
form1.IBQuery3.ParamByName('unid').AsString := form1.IBQuery1.FieldByName('unid').AsString;
try
form1.IBQuery3.ExecSQL;
except
on e:exception do
begin
erro := 1;
form1.adicionaMemo('ERRO: ' + e.Message + #13 + ' ITEM_VENDA' + #13 + '-----------------------' + #13);
end;
end;
form1.IBQuery1.Close;
end;
finally
if erro = 0 then
begin
Result := Result + IntToStr(lista.listaVenda[ini].nota) + '-';
//ShowMessage(Result);
end;
end;
end;
form1.IBTransaction1.Commit;
if notasImp.Count > 0 then begin
notasimp.SaveToFile(ExtractFileDir(ParamStr(0)) + '\notas.imp');
notasimp.Free;
ShellExecute(Application.Handle,'open',pchar(ExtractFileDir(ParamStr(0)) + '\controlw.exe'),nil,nil,1);
end
else begin
notasimp.Free;
end;
end;
function TServerMethods1.getcliente(cnpj: string) : Tcliente;
var
recNo : integer;
cliente : Tcliente;
begin
form1.adicionaMemo('Requisição de sincronização de Cliente ' + cnpj);
if Length(trim(cnpj)) = 11 then cnpj := form1.formataCPF(cnpj)
else cnpj := form1.formataCNPJ(cnpj);
cliente := Tcliente.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome, tipo, ende, bairro, cep, est, ies, cid, telres, telcom, titular from cliente where cnpj = :cnpj');
form1.IBQuery1.ParamByName('cnpj').AsString := (cnpj);
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
form1.IBQuery1.First;
recNo := -1;
cliente.cod := -1;
if (form1.IBQuery1.IsEmpty = false) then begin
recNo := recNo + 1;
cliente.cod := form1.IBQuery1.FieldByName('cod').AsInteger;
cliente.nome := form1.IBQuery1.FieldByName('nome').AsString;
cliente.titular := form1.IBQuery1.FieldByName('titular').AsString;
cliente.cnpj := cnpj;
cliente.tipo := form1.IBQuery1.FieldByName('tipo').AsString;
cliente.ende := form1.IBQuery1.FieldByName('ende').AsString;
cliente.bairro := form1.IBQuery1.FieldByName('bairro').AsString;
cliente.ies := form1.IBQuery1.FieldByName('ies').AsString;
cliente.est := form1.IBQuery1.FieldByName('est').AsString;
cliente.cid := form1.IBQuery1.FieldByName('cid').AsString;
cliente.telres := form1.IBQuery1.FieldByName('telres').AsString;
cliente.telcom := form1.IBQuery1.FieldByName('telcom').AsString;
cliente.cep := form1.IBQuery1.FieldByName('cep').AsString;
form1.adicionaMemo('Cliente Encontrado Cód:: ' + IntToStr(cliente.cod));
end
else begin
form1.adicionaMemo('Nenhum Cliente Encontrado : ' + cnpj);
end;
form1.IBQuery1.Close;
Result := cliente;
end;
function TServerMethods1.getUsuarios() : TlistaUsuario;
var
recNo : integer;
lista : TlistaUsuario;
begin
form1.adicionaMemo('Requisição de sincronização de Usuários');
lista := TlistaUsuario.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome, usu, senha, vendedor, configu, acesso from USUARIO where excluido = 0');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
SetLength(lista.listaUsuario, form1.IBQuery1.RecordCount);
form1.IBQuery1.First;
recNo := -1;
while not form1.IBQuery1.Eof do
begin
recNo := recNo + 1;
lista.listaUsuario[recNo] := TUsuario.Create;
lista.listaUsuario[recNo].cod := form1.IBQuery1.FieldByName('cod').AsInteger;
lista.listaUsuario[recNo].codVendedor := form1.IBQuery1.FieldByName('vendedor').AsInteger;
lista.listaUsuario[recNo].nome := form1.IBQuery1.FieldByName('nome').AsString;
lista.listaUsuario[recNo].senha := form1.DesCriptografar(form1.IBQuery1.FieldByName('senha').AsString);
lista.listaUsuario[recNo].usu := form1.DesCriptografar(form1.IBQuery1.FieldByName('usu').AsString);
lista.listaUsuario[recNo].acesso := form1.IBQuery1.FieldByName('acesso').AsString;
lista.listaUsuario[recNo].configu := form1.IBQuery1.FieldByName('configu').AsString;
form1.IBQuery1.Next;
end;
form1.IBQuery1.Close;
Result := lista;
end;
function TServerMethods1.getFormas() : TlistaFormas;
var
recNo : integer;
lista : TlistaFormas;
begin
form1.adicionaMemo('Requisição de sincronização de Formas de Pagamento');
lista := TlistaFormas.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome from FORMPAGTO');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
SetLength(lista.listaFormas, form1.IBQuery1.RecordCount);
form1.IBQuery1.First;
recNo := -1;
while not form1.IBQuery1.Eof do
begin
recNo := recNo + 1;
lista.listaFormas[recNo] := Tforma.Create;
lista.listaFormas[recNo].cod := form1.IBQuery1.FieldByName('cod').AsInteger;
lista.listaFormas[recNo].nome := form1.IBQuery1.FieldByName('nome').AsString;
form1.IBQuery1.Next;
end;
form1.IBQuery1.Close;
Result := lista;
end;
function TServerMethods1.getProdutos1() : TlistaProdutos;
var
recNo : integer;
lista : TlistaProdutos;
begin
form1.adicionaMemo('Requisição de sincronização de Produtos');
lista := TlistaProdutos.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome, codbar, p_compra, p_venda, obs, p_venda1 from produto');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
SetLength(lista.listaProdutos, form1.IBQuery1.RecordCount);
form1.IBQuery1.First;
recNo := -1;
while not form1.IBQuery1.Eof do
begin
recNo := recNo + 1;
lista.listaProdutos[recNo] := Tproduto.Create;
lista.listaProdutos[recNo].cod := form1.IBQuery1.FieldByName('cod').AsInteger;
lista.listaProdutos[recNo].nome := copy(form1.IBQuery1.FieldByName('nome').AsString, 1, 40);
lista.listaProdutos[recNo].codbar := form1.IBQuery1.FieldByName('codbar').AsString;
lista.listaProdutos[recNo].p_compra := form1.IBQuery1.FieldByName('p_compra').AsCurrency;
lista.listaProdutos[recNo].p_venda := form1.IBQuery1.FieldByName('p_venda').AsCurrency;
lista.listaProdutos[recNo].p_venda1 := form1.IBQuery1.FieldByName('p_venda1').AsCurrency;
lista.listaProdutos[recNo].obs := form1.IBQuery1.FieldByName('obs').AsString;
form1.IBQuery1.Next;
end;
form1.IBQuery1.Close;
Result :=lista;
end;
function TServerMethods1.RecordCountProdutosInteger() : Integer;
begin
Result := 0;
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod from produto');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
Result := form1.IBQuery1.RecordCount;
form1.IBQuery1.Close;
end;
function TServerMethods1.soma(v1, v2 : currency) : TJSONValue;
begin
exit(TJSONNumber.Create(v1 + v2));
end;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods1.getProdutos() : TJSONValue;
var
recNo : integer;
lista : TlistaProdutos;
begin
form1.adicionaMemo('Requisição de sincronização de Produtos');
lista := TlistaProdutos.create();
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add('select cod, nome, codbar, p_compra, p_venda, obs, p_venda1 from produto');
form1.IBQuery1.Open;
form1.IBQuery1.FetchAll;
SetLength(lista.listaProdutos, form1.IBQuery1.RecordCount);
form1.IBQuery1.First;
recNo := -1;
while not form1.IBQuery1.Eof do
begin
recNo := recNo + 1;
lista.listaProdutos[recNo] := Tproduto.Create;
lista.listaProdutos[recNo].cod := form1.IBQuery1.FieldByName('cod').AsInteger;
lista.listaProdutos[recNo].nome := copy(form1.IBQuery1.FieldByName('nome').AsString, 1, 40);
lista.listaProdutos[recNo].codbar := form1.IBQuery1.FieldByName('codbar').AsString;
lista.listaProdutos[recNo].p_compra := form1.IBQuery1.FieldByName('p_compra').AsCurrency;
lista.listaProdutos[recNo].p_venda := form1.IBQuery1.FieldByName('p_venda').AsCurrency;
lista.listaProdutos[recNo].p_venda1 := form1.IBQuery1.FieldByName('p_venda1').AsCurrency;
lista.listaProdutos[recNo].obs := form1.IBQuery1.FieldByName('obs').AsString;
form1.IBQuery1.Next;
end;
form1.IBQuery1.Close;
Result := ListaProdutosToJSON(lista);
end;
procedure TServerMethods1.execSql(const sql : string);
begin
{ if not form1.iBDatabase1.Connected then
begin
ShowMessage('BD não está conectado!');
exit;
end;
}
try
form1.IBQuery1.close;
form1.IBQuery1.SQL.Clear;
form1.IBQuery1.SQL.Add(sql);
form1.IBQuery1.ExecSQL;
form1.IBTransaction1.Commit;
except
end;
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
end.
|
unit RestServerUnit;
interface
uses
// RTL
System.SysUtils,
System.Classes,
System.StrUtils,
Vcl.Dialogs,
// mORMot
mORMot,
mORMotHttpServer,
SynBidirSock,
SynCommons,
SynCrtSock,
// Custom
RestMethodsInterfaceUnit,
RestServerMethodsUnit;
type
lProtocol = (HTTP_Socket, HTTPsys, WebSocketBidir_JSON, WebSocketBidir_Binary, WebSocketBidir_BinaryAES, NamedPipe);
lAuthenticationMode = (NoAuthentication, URI, SignedURI, Default, None, HttpBasic, SSPI);
rServerSettings = record
Protocol: lProtocol;
AuthMode: lAuthenticationMode;
Port: string;
end;
tRestServer = class
private
fModel: TSQLModel;
fRestServer: TSQLRestServer;
fHTTPServer: TSQLHttpServer;
fServerSettings: rServerSettings;
fInitialized: boolean;
procedure ApplyAuthenticationRules(ServiceFactoryServer: TServiceFactoryServer);
public
property Initialized: boolean read fInitialized;
constructor Create();
destructor Destroy(); override;
function Initialize(SrvSettings: rServerSettings): boolean;
function DeInitialize(): boolean;
end;
var
RestServer: tRestServer;
implementation
{ tRestServer }
constructor tRestServer.Create();
begin
//
end;
destructor tRestServer.Destroy();
begin
DeInitialize();
inherited;
end;
procedure tRestServer.ApplyAuthenticationRules(ServiceFactoryServer: TServiceFactoryServer);
var
ID: TID;
GROUP: TSQLAuthGroup;
begin // TSQLAuthUser, TSQLAuthGroup
ID := fRestServer.MainFieldID(TSQLAuthGroup, 'User');
GROUP := TSQLAuthGroup.Create(fRestServer, ID);
GROUP.Free;
ServiceFactoryServer.AllowAll();
end;
function tRestServer.Initialize(SrvSettings: rServerSettings): boolean;
var
ServiceFactoryServer: TServiceFactoryServer;
{ WebSocketServerRest: TWebSocketServerRest; }
begin
Result := false;
// Destroy current object
if DeInitialize() then
try
// Server initialization (!!! for better understanding, each section contain separate code, later should be refactored)
fServerSettings := SrvSettings;
case fServerSettings.AuthMode of
// NoAuthentication
NoAuthentication:
begin
fModel := TSQLModel.Create([], ROOT_NAME);
fRestServer := TSQLRestServerFullMemory.Create(fModel, false);
fRestServer.ServiceDefine(TRestMethods, [IRestMethods], SERVICE_INSTANCE_IMPLEMENTATION);
end;
// TSQLRestServerAuthenticationURI
URI:
begin
fModel := TSQLModel.Create([], ROOT_NAME);
fRestServer := TSQLRestServerFullMemory.Create(fModel, false { make AuthenticationSchemesCount = 0 } );
ServiceFactoryServer := fRestServer.ServiceDefine(TRestMethods, [IRestMethods], SERVICE_INSTANCE_IMPLEMENTATION);
fRestServer.AuthenticationRegister(TSQLRestServerAuthenticationURI); // register single authentication mode
ApplyAuthenticationRules(ServiceFactoryServer);
end;
{
// TSQLRestServerAuthenticationSignedURI
SignedURI:
begin
end;
}
// TSQLRestServerAuthenticationDefault
Default:
begin
fModel := TSQLModel.Create([], ROOT_NAME);
fRestServer := TSQLRestServerFullMemory.Create(fModel, false { make AuthenticationSchemesCount = 0 } );
ServiceFactoryServer := fRestServer.ServiceDefine(TRestMethods, [IRestMethods], SERVICE_INSTANCE_IMPLEMENTATION);
fRestServer.AuthenticationRegister(TSQLRestServerAuthenticationDefault); // register single authentication mode
ApplyAuthenticationRules(ServiceFactoryServer);
end;
// TSQLRestServerAuthenticationNone
None:
begin
fModel := TSQLModel.Create([], ROOT_NAME);
fRestServer := TSQLRestServerFullMemory.Create(fModel, false { make AuthenticationSchemesCount = 0 } );
ServiceFactoryServer := fRestServer.ServiceDefine(TRestMethods, [IRestMethods], SERVICE_INSTANCE_IMPLEMENTATION);
fRestServer.AuthenticationRegister(TSQLRestServerAuthenticationNone); // register single authentication mode
ApplyAuthenticationRules(ServiceFactoryServer);
end;
// TSQLRestServerAuthenticationHttpBasic
HttpBasic:
begin
fModel := TSQLModel.Create([], ROOT_NAME);
fRestServer := TSQLRestServerFullMemory.Create(fModel, false { make AuthenticationSchemesCount = 0 } );
ServiceFactoryServer := fRestServer.ServiceDefine(TRestMethods, [IRestMethods], SERVICE_INSTANCE_IMPLEMENTATION);
fRestServer.AuthenticationRegister(TSQLRestServerAuthenticationHttpBasic); // register single authentication mode
ApplyAuthenticationRules(ServiceFactoryServer);
end;
{
// TSQLRestServerAuthenticationSSPI
SSPI:
begin
end;
}
else
begin
DeInitialize();
raise Exception.Create('Selected Authentication mode not available in this build.');
end;
end;
// protocol initialization
case fServerSettings.Protocol of
HTTP_Socket:
begin
fHTTPServer := TSQLHttpServer.Create(AnsiString(fServerSettings.Port), [fRestServer], '+', useHttpSocket);
end;
{
// require manual URI registration, we will not use this option
HTTPsys:
begin
HTTPServer := TSQLHttpServer.Create(AnsiString(Options.Port), [RestServer], '+', useHttpApi);
end;
}
HTTPsys:
begin
fHTTPServer := TSQLHttpServer.Create(AnsiString(fServerSettings.Port), [fRestServer], '+', useHttpApiRegisteringURI);
end;
WebSocketBidir_JSON:
begin
fHTTPServer := TSQLHttpServer.Create(AnsiString(fServerSettings.Port), [fRestServer], '+', useBidirSocket);
{ WebSocketServerRest := } fHTTPServer.WebSocketsEnable(fRestServer, '', True);
end;
WebSocketBidir_Binary:
begin
fHTTPServer := TSQLHttpServer.Create(AnsiString(fServerSettings.Port), [fRestServer], '+', useBidirSocket);
{ WebSocketServerRest := } fHTTPServer.WebSocketsEnable(fRestServer, '', false);
end;
WebSocketBidir_BinaryAES:
begin
fHTTPServer := TSQLHttpServer.Create(AnsiString(fServerSettings.Port), [fRestServer], '+', useBidirSocket);
{ WebSocketServerRest := } fHTTPServer.WebSocketsEnable(fRestServer, '2141D32ADAD54D9A9DB56000CC9A4A70', false);
end;
NamedPipe:
begin
if not fRestServer.ExportServerNamedPipe(NAMED_PIPE_NAME) then
Exception.Create('Unable to register server with named pipe channel.');
end;
else
begin
DeInitialize();
raise Exception.Create('Selected protocol not available in this build.');
end;
end;
Result := True;
except
on E: Exception do
begin
ShowMessage(E.ToString);
DeInitialize();
end;
end;
fInitialized := Result;
end;
function tRestServer.DeInitialize(): boolean;
begin
Result := True;
try
// if used HttpApiRegisteringURI then remove registration (require run as admin), but seems not work from here
if Assigned(fHTTPServer) and (fHTTPServer.HTTPServer.ClassType = THttpApiServer) then
THttpApiServer(fHTTPServer.HTTPServer).RemoveUrl(ROOT_NAME, fHTTPServer.Port, false, '+');
if Assigned(fHTTPServer) then
FreeAndNil(fHTTPServer);
if Assigned(fRestServer) then
FreeAndNil(fRestServer);
if Assigned(fModel) then
FreeAndNil(fModel);
fInitialized := false;
except
on E: Exception do
begin
ShowMessage(E.ToString);
Result := false;
end;
end;
end;
initialization
RestServer := tRestServer.Create();
finalization
if Assigned(RestServer) then
FreeAndNil(RestServer);
end.
|
unit AST.Intf;
interface
uses AST.Parser.ProcessStatuses;
type
IASTModule = interface
['{1E3A5748-1671-41E8-BAAD-4BBB2B363BF4}']
function GetModuleName: string;
function GetTotalLinesParsed: Integer;
property Name: string read GetModuleName;
property TotalLinesParsed: Integer read GetTotalLinesParsed;
end;
TASTProgressEvent = reference to procedure (const Module: IASTModule; Status: TASTProcessStatusClass);
TASTRrojectConsoleWriteEvent = reference to procedure (const Module: IASTModule; Line: Integer; const Message: string);
IASTProject = interface
['{AE77D75A-4F7F-445B-ADF9-47CF5C2F0A14}']
procedure SetOnProgress(const Value: TASTProgressEvent);
procedure SetOnConsoleWrite(const Value: TASTRrojectConsoleWriteEvent);
function GetOnProgress: TASTProgressEvent;
function GetOnConsoleWrite: TASTRrojectConsoleWriteEvent;
property OnProgress: TASTProgressEvent read GetOnProgress write SetOnProgress;
property OnConsoleWrite: TASTRrojectConsoleWriteEvent read GetOnConsoleWrite write SetOnConsoleWrite;
function GetPointerSize: Integer;
function GetNativeIntSize: Integer;
function GetTotalLinesParsed: Integer;
function GetTotalUnitsParsed: Integer;
function GetTotalUnitsIntfOnlyParsed: Integer;
property PointerSize: Integer read GetPointerSize;
property NativeIntSize: Integer read GetNativeIntSize;
property TotalLinesParsed: Integer read GetTotalLinesParsed;
property TotalUnitsParsed: Integer read GetTotalUnitsParsed;
property TotalUnitsIntfOnlyParsed: Integer read GetTotalUnitsIntfOnlyParsed;
procedure CosoleWrite(const Module: IASTModule; Line: Integer; const Message: string);
end;
IASTProjectSettings = interface
['{F0A54AD9-2588-4CC9-9B8E-0010BD9E06DC}']
end;
implementation
end.
|
unit USetFilterSetings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxControls, cxContainer, cxEdit,
cxTextEdit, StdCtrls, cxButtons;
type
TfmFiltring = class(TForm)
Labelfilter: TLabel;
cxButtonSet: TcxButton;
cxButtonClose: TcxButton;
TextEditWhatFind: TcxTextEdit;
procedure cxButtonCloseClick(Sender: TObject);
procedure cxButtonSetClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
old_set : string;
flag_find : integer;
public
ResultArray : Variant;
end;
function func_Filter(Old: String; sho : Integer) : variant;
var
fmFiltring: TfmFiltring;
implementation
{$R *.dfm}
function func_Filter(Old: String; sho : Integer) : variant;
var
fmfind : TfmFiltring;
begin
fmfind := TfmFiltring.Create(nil);
fmfind.Caption := 'Ïîøóê';
fmfind.Labelfilter.Caption := 'Øóêàòè:';
fmfind.cxButtonSet.Caption := 'Âiäiáðàòè';
fmfind.cxButtonClose.Caption := 'Âiäìiíèòè';
fmfind.TextEditWhatFind.Text := Old;
fmfind.old_set := Old;
fmfind.flag_find := sho;
fmfind.ShowModal;
func_Filter := fmfind.ResultArray;
fmfind.Free;
end;
procedure TfmFiltring.cxButtonCloseClick(Sender: TObject);
begin
ResultArray := VarArrayCreate([0,1], varVariant);
ResultArray[0] := old_set;
ResultArray[1] := flag_find;
Close;
end;
procedure TfmFiltring.cxButtonSetClick(Sender: TObject);
var
str : string;
begin
str := TextEditWhatFind.Text;
if (str <> '') then
begin
str := str[1];
if (str >= 'à') and (str <= 'ÿ') then
begin
flag_find := 1;
old_set := AnsiUpperCase(TextEditWhatFind.Text) + '%';
end;
if (str >= 'À') and (str <= 'ß') then
begin
flag_find := 1;
old_set := TextEditWhatFind.Text + '%';
end;
if (str >= '0') and (str <= '9') then
begin
flag_find := 2;
old_set := TextEditWhatFind.Text + '%';
end;
end else
begin
flag_find := 0;
old_set := '';
end;
ResultArray := VarArrayCreate([0,1], varVariant);
ResultArray[0] := old_set;
ResultArray[1] := flag_find;
Close;
end;
procedure TfmFiltring.FormCreate(Sender: TObject);
var
Layout: array[0.. KL_NAMELENGTH] of char;
begin
LoadKeyboardLayout( StrCopy(Layout,'00000419'),KLF_ACTIVATE);
end;
end.
|
unit BarcodeReaderMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
EanRead, StdCtrls, ExtCtrls, EanKod, EanSpecs;
type
TForm2 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Ean: TEan;
Barcodes: TMemo;
E_PORT: TRadioGroup;
E_SPEED: TRadioGroup;
E_PARITY: TRadioGroup;
E_DATABITS: TRadioGroup;
E_STOPBITS: TRadioGroup;
E_TIMEOUT: TEdit;
E_REMOVECR: TCheckBox;
E_REMOVELF: TCheckBox;
BarcodeReader: TBarcodeReader;
CB_TYPE: TComboBox;
procedure BarcodeReaderBarcodeReady(Sender: TObject; Barcode: String);
procedure FormCreate(Sender: TObject);
procedure E_REMOVECRClick(Sender: TObject);
procedure E_REMOVELFClick(Sender: TObject);
procedure E_TIMEOUTChange(Sender: TObject);
procedure E_PORTClick(Sender: TObject);
procedure E_SPEEDClick(Sender: TObject);
procedure E_PARITYClick(Sender: TObject);
procedure E_DATABITSClick(Sender: TObject);
procedure E_STOPBITSClick(Sender: TObject);
procedure CB_TYPEChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.DFM}
procedure TForm2.BarcodeReaderBarcodeReady(Sender: TObject;
Barcode: String);
begin
Barcodes.Lines.Add(Barcode);
Ean.Barcode := Barcode;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
BarcodeReader.Active := True;
E_TIMEOUT.Text := IntToStr(BarcodeReader.Timeout);
E_PORT.ItemIndex := Integer(BarcodeReader.Port);
E_PARITY.ItemIndex := Integer(BarcodeReader.Parity);
E_SPEED.ItemIndex := Integer(BarcodeReader.BitRate);
E_DATABITS.ItemIndex := Integer(BarcodeReader.DataBits);
E_STOPBITS.ItemIndex := Integer(BarcodeReader.StopBits);
E_REMOVECR.Checked := boRemoveCR in BarcodeReader.Options;
E_REMOVELF.Checked := boRemoveLF in BarcodeReader.Options;
Ean.AddTypesToList(CB_TYPE.Items, btSymbol);
CB_TYPE.ItemIndex := Integer(bcEan13);
end;
procedure TForm2.E_REMOVECRClick(Sender: TObject);
begin
if E_REMOVECR.Checked then
BarcodeReader.Options := BarcodeReader.Options + [boRemoveCR]
else
BarcodeReader.Options := BarcodeReader.Options - [boRemoveCR];
end;
procedure TForm2.E_REMOVELFClick(Sender: TObject);
begin
if E_REMOVELF.Checked then
BarcodeReader.Options := BarcodeReader.Options + [boRemoveLF]
else
BarcodeReader.Options := BarcodeReader.Options - [boRemoveLF];
end;
procedure TForm2.E_TIMEOUTChange(Sender: TObject);
begin
BarcodeReader.TimeOut := StrToIntDef(E_TIMEOUT.Text, 100);
BarcodeReader.ReConnect;
end;
procedure TForm2.E_PORTClick(Sender: TObject);
begin
BarcodeReader.Port := TpsComPort(E_PORT.ItemIndex);
BarcodeReader.ReConnect;
end;
procedure TForm2.E_SPEEDClick(Sender: TObject);
begin
BarcodeReader.BitRate := TpsComBitRate(E_SPEED.ItemIndex);
BarcodeReader.ReConnect;
end;
procedure TForm2.E_PARITYClick(Sender: TObject);
begin
BarcodeReader.Parity := TpsComParity(E_PARITY.ItemIndex);
BarcodeReader.ReConnect;
end;
procedure TForm2.E_DATABITSClick(Sender: TObject);
begin
BarcodeReader.DataBits := TpsComdataBits(E_DATABITS.ItemIndex);
BarcodeReader.ReConnect;
end;
procedure TForm2.E_STOPBITSClick(Sender: TObject);
begin
BarcodeReader.StopBits := TpsComStopBits(E_STOPBITS.ItemIndex);
BarcodeReader.ReConnect;
end;
procedure TForm2.CB_TYPEChange(Sender: TObject);
begin
Ean.TypBarCode := TTypBarcode(CB_TYPE.ItemIndex);
end;
end.
|
unit utilidades;
interface
uses
Vcl.ComCtrls, ACBrCEP, SysUtils, Vcl.Forms, SWHDBEdit,
SWHEdit, SWHComboBox, SWHDBComboBox, SWHDBLookupComboBox, SWHMaskEdit,
Vcl.Grids, Vcl.DBGrids, Winapi.Windows, FireDAC.Comp.Client, Vcl.ExtCtrls,
Vcl.Buttons, Vcl.Graphics, DateUtils, Vcl.DBCtrls, IdHashMessageDigest,
System.Variants;
type
//record ou registro do Endere�o
TEndereco = record
sBairro : String ;
sCEP : String ;
sCodigoIBGE : String ;
sComplemento: String ;
sLogradouro : String ;
sMunicipio : String ;
sUF : String ;
end;
function fnc_ValidaData( const Data: String ): String;
procedure prcAjustarColunasGrid(const xDBGrid: TDBGrid);
function fnc_retorna_idade ( DataNascimento : TDate ): String;
function fnc_retorna_mascara_fone( NTelefone: String ): TTipoMascara;
procedure prcAjustaTamanhoLinha (dbg: TDBGrid);
function fnc_formata_valor( Valor:String ):Double;
function fnc_remove_caracteres(AString: String): String;
procedure prc_validar_campos_obrigatorios ( Form: TForm );
Function fnc_cria_janela_mensagem ( Titulo, Mensagem, CaminhoIcone, TipoMensagem :String ): boolean;
function fnc_retorna_endereco( Cep: String; out Erro:String ): TEndereco;
procedure prc_ocultar_tabs ( PageControl : TPageControl );
function fnc_somente_numeros( AString: String): String;
procedure prc_ordena( QueryConsulta:TFDQuery; Coluna: TColumn);
procedure prc_focar_botao( Painel: TPanel; Botao: TSpeedButton; Focar: Boolean );
function fnc_selecionar_empresas: TFDQuery;
function MD5(const Value: string): string;
procedure prcLimpaCampos( Form: TForm );
TYPE
TDBGridPadrao = class(TCustomGrid);
var
//variaveis globais que serao utilizadas em todo sistema
var_gbl_empresa: Integer;
var_gbl_razao_empresa,
var_gbl_Servidor,
var_gbl_Porta,
var_gbl_Base,
var_gbl_Login,
var_gbl_Senha,
var_gbl_versao,
var_gbl_usuario: String;
implementation
uses
Utilidades.Mensajes;
//PERCORRE O FORMULARIO PASSADO NO PARAMETRO E
//LIMPA O CONTEUDO/TEXTO DE CADA COMPONENTE
procedure prcLimpaCampos( Form: TForm );
var
i : Integer;
begin
for i := 0 to Form.ComponentCount - 1 do
begin
//dbEdit
if Form.Components[i] is TSWHDBEdit then
TSWHDBEdit(Form.Components[i]).Clear
else
//Edit
if Form.Components[i] is TSWHEdit then
TSWHEdit(Form.Components[i]).Clear
else
//combobox
If Form.Components[i] is TSWHComboBox then
TSWHComboBox(Form.Components[i]).ItemIndex := -1
else
//dbcombobox
If Form.Components[i] is TSWHDBComboBox then
TSWHDBComboBox(Form.Components[i]).ItemIndex := -1
else
//SWHdblookupcombobox
If Form.Components[i] is TSWHDBLookUpComboBox then
TSWHDBLookUpComboBox(Form.Components[i]).KeyValue := null
else
//dblookupcombobox
If Form.Components[i] is TDBLookUpComboBox then
TDBLookUpComboBox(Form.Components[i]).KeyValue := null
else
//MaskEdit
If Form.Components[i] is TSWHMaskEdit then
TSWHMaskEdit( Form.Components[i]).Clear;
end;
end;
//FUN��O QUE CRIPTOGRAFA A SENHA DO USUARIO PARA SER GUARDADA NO BANCO DE DADOS
function MD5(const Value: string): string;
var
xMD5: TIdHashMessageDigest5;
begin
xMD5 := TIdHashMessageDigest5.Create;
try
Result := LowerCase(xMD5.HashStringAsHex(Value));
finally
xMD5.Free;
end;
end;
//FUNCAO QUE VALIDA DATA E CONVERTE O ANO EM 4 DIGITOS QUANDO O USUARIO DIGITA SO 2
function fnc_ValidaData( const Data: String ): String;
begin
Result:= '';
try
if Data = ' / / ' then
exit;
Result := DateToStr( Strtodate( Data ) );
except
fnc_cria_janela_mensagem( 'Data Inv�lida','Data Digitada Inv�lida',
ExtractFilePath( Application.ExeName) + '\Icones\mensagem\erro.png',
'ERRO' );
Abort;
end;
end;
//PERCORRE O GRID PASSADO POR PARAMETRO AUMENTANDO A LAGURA DE SUAS COLUNAS ATE PREENCHER TODA A TELA
procedure prcAjustarColunasGrid(const xDBGrid: TDBGrid);
var
I, TotalWidht, VarWidth, QtdTotalColuna : Integer;
xColumn : TColumn;
begin
ShowScrollBar( xDBGrid.Handle,SB_Vert, True );
For I := 0 to xDBGrid.FieldCount - 1 do
begin
//SO SERA REDIMENSIONADO QUEM TEM TAG = 30
//NESSE IF SO OS CAMPOS QUE TEM NOME ABAIXO SERAO REDIMENSIONADOS
//QUALQUER OUTRO CAMPO NAO TERA A LARGURA DA COLUNA ALTERADA
if ( xDBGrid.Fields[I].FieldName = 'DS_NOME' ) or
( xDBGrid.Fields[I].FieldName = 'DS_DESCRICAO' ) OR
( xDBGrid.Fields[I].FieldName = 'DS_RECEBEDOR' ) then
xDBGrid.Fields[I].Tag := 30
else
xDBGrid.Fields[I].Tag := 0;
end;
// Largura total de todas as colunas antes de redimensionar
TotalWidht := 0;
// Quantas colunas devem ser auto-redimensionamento
QtdTotalColuna := 0;
for I := 0 to -1 + xDBGrid.Columns.Count do
begin
TotalWidht := TotalWidht + xDBGrid.Columns[I].Width;
if xDBGrid.Columns[I].Field.Tag <> 0 then
Inc(QtdTotalColuna);
end;
// Adiciona 1px para a linha de separador de coluna
if dgColLines in xDBGrid.Options then
TotalWidht := TotalWidht + xDBGrid.Columns.Count;
// width vale "Left"
VarWidth := xDBGrid.ClientWidth - TotalWidht;
// Da mesma forma distribuir VarWidth para todas as colunas auto-resizable
if QtdTotalColuna > 0 then
VarWidth := varWidth div QtdTotalColuna;
for I := 0 to -1 + xDBGrid.Columns.Count do
begin
xColumn := xDBGrid.Columns[I];
if xColumn.Field.Tag <> 0 then
begin
xColumn.Width := xColumn.Width + VarWidth;
if xColumn.Width < xColumn.Field.Tag then
xColumn.Width := xColumn.Field.Tag;
end;
end;
end;
{
//FUNCAO QUE RETORNA A QUERY COM TODAS AS EMPRESAS QUE ESTAO CADASTRADAS
//SERA USADA ESSA FUNCAO NO DBLOOKUPCOMBOX DO FORM SELECIONAR EMPRESA
function fnc_selecionar_empresas: TFDQuery;
var
QueryConsulta: TFDQuery;
begin
try
//DESCONECTA E CONECTA NO BANCO
//POIS SE FOR BANCO HOSPEDADO PARTIMOS DO PRINCIPIO QUE A CONEXAO NUNCA ESTA ATIVA
form_dados.FDConnection.Connected := False;
form_dados.FDConnection.Connected := TRUE;
//CRIA A QUERY DE CONSULTA
QueryConsulta := TFDQuery.Create( nil );
QueryConsulta.Connection := form_dados.FDConnection;
//ATRIBUI O SQL A ESSA QUERY CRIADA
QueryConsulta.Close;
QueryConsulta.SQL.Clear;
QueryConsulta.SQL.Add('SELECT ID_EMPRESA,FG_STATUS,DT_ABERTURA,DT_FECHAMENTO,');
QueryConsulta.SQL.Add('DS_RAZAOSOCIAL,DS_FANTASIA,NR_CNPJ,NR_IE,NR_CEP,DS_ENDERECO, ');
QueryConsulta.SQL.Add('NR_NUMERO, DS_COMPLEMENTO, DS_BAIRRO, DS_MUNICIPIO, ');
QueryConsulta.SQL.Add('DS_ESTADO, NR_FONE1, NR_FONE2, NR_FONE3, DS_CONTATO, ');
QueryConsulta.SQL.Add('DS_EMAIL, DS_SITE FROM EMPRESAS ');
QueryConsulta.Open;
finally
//RETORNA O RESULTADO PARA A FUNCAO
Result := QueryConsulta;
end;
end;
}
//FUNCAO QUE DA O EFEITO AO BOTAO DE FOCADO QUANDO PASSO O MOUSE
procedure prc_focar_botao( Painel: TPanel; Botao: TSpeedButton; Focar: Boolean );
begin
// O PARAMTRO PAINEL � A BARRA QUE SERA MUDADA A COR AO LADO DO BOTAO
if Focar then
begin
Botao.Font.Color := clBlack;
Painel.Parent := Botao.Parent;
Painel.Left := Botao.Left ;//+ ( Botao.Width - 2);
Painel.Top := Botao.Top ;//+ ( Botao.Height - 2);
Painel.Height := Botao.Height -1;
Painel.Visible := True;
Painel.BringToFront;
end else
begin
Botao.Font.Color := $00626262;
Botao.Font.Style := [];
Painel.Visible := False;
end;
end;
//FUNCAO QUE PEGA UMA STRING PASSADA POR PARAMETRO E
//RETORNA SOMENTE OS NUMERO DESSA STRING
function fnc_somente_numeros(AString: String): String;
var
I : Integer;
Limpos : String;
begin
Limpos := '';
for I := 1 to Length(AString) do
begin
if Pos(Copy(AString, I, 1), '0123456789') <> 0 then
Limpos := Limpos + Copy(AString, i, 1);
end;
Result := Limpos;
end;
//FUNCAO QUE PEGA A STRING DE TELEFONE E TESTA PRA VER SE � FIXO OU
//CELULAR ATRIBUINDO ASSIM SUA MASCARA CORRETA
function fnc_retorna_mascara_fone( NTelefone: String ): TTipoMascara;
begin
Result := tmNone;
if fnc_somente_numeros ( NTelefone ) <> '' then
begin
if Length( Ntelefone ) = 10 then
Result := tmTelefone // mascara do TSWHMASKEDIT TTipoMascara = ( tmData, tmCPF, tmCNPJ, tmCEP, tmTelefone, tmCelular, tmNone );
else
if Length( Ntelefone ) = 11 then
Result := tmCelular ; // mascara do TSWHMASKEDIT TTipoMascara = ( tmData, tmCPF, tmCNPJ, tmCEP, tmTelefone, tmCelular, tmNone );
end ;
end;
//Define o tamanho de cada linha do dbgrid
procedure prcAjustaTamanhoLinha (dbg: TDBGrid);
begin
TDBGridPadrao(dbg).DefaultRowHeight := 32;
TDBGridPadrao(dbg).ClientHeight := ( 33 * TDBGridPadrao(dbg).RowCount ) + 33 ;
TDBGridPadrao(dbg).RowHeights[0] := 30;
end;
//FUNCAO QUE PEGA UMA STRING PASSADA POR PARAMETRO E
//REMOVE O CARACTER '.' DO VALOR SE HOUVER
function fnc_formata_valor( Valor:String ):Double;
Var
i: Integer;
NovoValor : String;
begin
NovoValor:='';
if Valor = '' then
Valor := '0,00';
for i:=1 to Length( Valor ) do
begin
if Valor[i] <> '.' then NovoValor:= NovoValor + Valor[i];
end;
Result := StrToFloat ( NovoValor );
end;
//FUNCAO QUE PEGA UMA STRING PASSADA POR PARAMETRO E
//REMOVE OS CARACTERES DEIXANDO SOMENTE LETRAS E NUMEROS
function fnc_remove_caracteres( AString: String): String;
var
I : Integer;
Limpos : String;
begin
Limpos := '';
for I := 1 to Length(AString) do
begin
if Pos ( Copy( AString, I, 1 ), '"!%$#@&�*().,;:/<>[]{}=+-_\|') = 0 then
Limpos := Limpos + Copy(AString, i, 1);
end;
Result := Limpos;
end;
//PERCORRE O FORMULARIO PASSADO NO PARAMETRO E
//VERIFICA SE A PROPRIEDADE TAG = 5 E O HINT ESTA PREENCHDIO POIS
//SE TIVER � CAMPO OBRIGATORIO E APOS ISSO TESTA SE ESTA VAZIO
//RETORNANDO MENSAGEM AO USUARIO CASO ESTEJA VAZIO
procedure prc_validar_campos_obrigatorios ( Form: TForm );
var
i : Integer;
begin
for i := 0 to Form.ComponentCount - 1 do
begin
//tag = 5 indica que o campo � obrigatorio
if ( Form.Components[i].Tag = 5 ) then
begin
//dbEdit
if Form.Components[i] is TSWHDBEdit then
if ( ( Form.Components[i] as TSWHDBEdit ).Hint <> '' ) and
( ( Form.Components[i] as TSWHDBEdit ).Visible ) and
( Trim ( fnc_remove_caracteres ( ( Form.Components[i] as TSWHDBEdit ).Text ) ) = '' ) then
begin
// CAMPO ESTA VAZIO ENTAO RETORNA MSG AO USUARIO
fnc_cria_janela_mensagem('Aviso de DADOS OBRIGAT�RIOS',
'O campo ' + ( Form.Components[i] as TSWHDBEdit ).Hint + ' � Obrigat�rio',
ExtractFilePath( Application.ExeName) + '\Icones\mensagem\aviso.png',
'AVISO' );
//IF TESTA PRA VER SE O COMPONENTE ESTA EM UM PAGECONTROL COLCOANDO ASSIM O FOCO NELE
if ( Form.Components[i] as TSWHDBEdit ).Enabled and ( Form.Components[i] as TSWHDBEdit ).Visible then
begin
if TSWHDBEdit(Form.Components[I]).Parent.ClassType = TTabSheet then// o Parente n�o � o pageControl e sim o a p�gina proriamente dito
TPageControl( TTabSheet( TSWHDBEdit(Form.Components[I]).Parent).Parent).ActivePage := ( Form.Components[i] as TSWHDBEdit ).Parent as TTabSheet;
TSWHDBEdit(Form.Components[i]).SetFocus;
end;
Abort;
end;
//Edit
if Form.Components[i] is TSWHEdit then
if ( ( Form.Components[i] as TSWHEdit ).Hint <> '' ) and
( ( Form.Components[i] as TSWHEdit ).Visible ) and
( Trim ( fnc_remove_caracteres ( ( Form.Components[i] as TSWHEdit ).Text ) ) = '' ) then
begin
// CAMPO ESTA VAZIO ENTAO RETORNA MSG AO USUARIO
fnc_cria_janela_mensagem('Aviso de DADOS OBRIGAT�RIOS',
'O campo ' + ( Form.Components[i] as TSWHEdit ).Hint + ' � Obrigat�rio',
ExtractFilePath( Application.ExeName) + '\Icones\mensagem\aviso.png',
'AVISO' );
//IF TESTA PRA VER SE O COMPONENTE ESTA EM UM PAGECONTROL COLCOANDO ASSIM O FOCO NELE
if ( Form.Components[i] as TSWHEdit ).Enabled and ( Form.Components[i] as TSWHEdit ).Visible then
begin
if TSWHEdit(Form.Components[I]).Parent.ClassType = TTabSheet then// o Parente n�o � o pageControl e sim o a p�gina proriamente dito
TPageControl( TTabSheet( TSWHEdit(Form.Components[I]).Parent).Parent ).ActivePage := ( Form.Components[i] as TSWHEdit ).Parent as TTabSheet;
TSWHEdit(Form.Components[i]).SetFocus;
end;
Abort;
end;
//combobox
If Form.Components[i] is TSWHComboBox then
if ( ( Form.Components[i] as TSWHComboBox ).Hint <> '' ) and
( ( Form.Components[i] as TSWHComboBox ).Visible ) and
( Trim( fnc_remove_caracteres ( ( Form.Components[i] as TSWHComboBox ).Text ) ) = '' ) then
begin
// CAMPO ESTA VAZIO ENTAO RETORNA MSG AO USUARIO
fnc_cria_janela_mensagem('Aviso de DADOS OBRIGAT�RIOS',
'O campo ' + ( Form.Components[i] as TSWHComboBox ).Hint + ' � Obrigat�rio',
ExtractFilePath( Application.ExeName) + '\Icones\mensagem\aviso.png',
'AVISO' );
//IF TESTA PRA VER SE O COMPONENTE ESTA EM UM PAGECONTROL COLCOANDO ASSIM O FOCO NELE
if ( Form.Components[i] as TSWHComboBox ).Enabled and ( Form.Components[i] as TSWHComboBox ).Visible then
begin
if TSWHComboBox(Form.Components[I]).Parent.ClassType = TTabSheet then// o Parente n�o � o pageControl e sim o a p�gina proriamente dito
TPageControl( TTabSheet( TSWHComboBox(Form.Components[I]).Parent).Parent).ActivePage := ( Form.Components[i] as TSWHComboBox ).Parent as TTabSheet;
TSWHComboBox(Form.Components[i]).SetFocus;
end;
Abort;
end;
//dbcombobox
If Form.Components[i] is TSWHDBComboBox then
if ( ( Form.Components[i] as TSWHDBComboBox ).Hint <> '' ) and
( ( Form.Components[i] as TSWHDBComboBox ).Visible ) and
( Trim( fnc_remove_caracteres ( ( Form.Components[i] as TSWHDBComboBox ).Text ) ) = '' ) then
begin
// CAMPO ESTA VAZIO ENTAO RETORNA MSG AO USUARIO
fnc_cria_janela_mensagem('Aviso de DADOS OBRIGAT�RIOS',
'O campo ' + ( Form.Components[i] as TSWHDBComboBox ).Hint + ' � Obrigat�rio',
ExtractFilePath( Application.ExeName) + '\Icones\mensagem\aviso.png',
'AVISO' );
//IF TESTA PRA VER SE O COMPONENTE ESTA EM UM PAGECONTROL COLCOANDO ASSIM O FOCO NELE
if ( Form.Components[i] as TSWHDBComboBox ).Enabled and ( Form.Components[i] as TSWHDBComboBox ).Visible then
begin
if TSWHDBComboBox(Form.Components[I]).Parent.ClassType = TTabSheet then// o Parente n�o � o pageControl e sim o a p�gina proriamente dito
TPageControl( TTabSheet( TSWHDBComboBox(Form.Components[I]).Parent).Parent).ActivePage := ( Form.Components[i] as TSWHDBComboBox ).Parent as TTabSheet;
TSWHDBComboBox(Form.Components[i]).SetFocus;
end;
Abort;
end;
//dblookupcombobox
If Form.Components[i] is TSWHDBLookUpComboBox then
if ( ( Form.Components[i] as TSWHDBLookUpComboBox ).Hint <> '' ) and
( ( Form.Components[i] as TSWHDBLookUpComboBox ).Visible ) and
( Trim( fnc_remove_caracteres ( ( Form.Components[i] as TSWHDBLookUpComboBox ).Text ) ) = '' ) then
begin
// CAMPO ESTA VAZIO ENTAO RETORNA MSG AO USUARIO
fnc_cria_janela_mensagem('Aviso de DADOS OBRIGAT�RIOS',
'O campo ' + ( Form.Components[i] as TSWHDBLookUpComboBox ).Hint + ' � Obrigat�rio',
ExtractFilePath( Application.ExeName) + '\Icones\mensagem\aviso.png',
'AVISO' );
//IF TESTA PRA VER SE O COMPONENTE ESTA EM UM PAGECONTROL COLCOANDO ASSIM O FOCO NELE
if ( Form.Components[i] as TSWHDBLookUpComboBox ).Enabled and ( Form.Components[i] as TSWHDBLookUpComboBox ).Visible then
begin
if TSWHDBLookUpComboBox(Form.Components[I]).Parent.ClassType = TTabSheet then// o Parente n�o � o pageControl e sim o a p�gina proriamente dito
TPageControl( TTabSheet( TSWHDBLookUpComboBox(Form.Components[I]).Parent).Parent).ActivePage := ( Form.Components[i] as TSWHDBLookUpComboBox ).Parent as TTabSheet;
TSWHDBLookUpComboBox(Form.Components[i]).SetFocus;
end;
Abort;
end;
//dblookupcombobox
If Form.Components[i] is TDBLookUpComboBox then
if ( ( Form.Components[i] as TDBLookUpComboBox ).Hint <> '' ) and
( ( Form.Components[i] as TDBLookUpComboBox ).Visible ) and
( Trim( fnc_remove_caracteres ( ( Form.Components[i] as TDBLookUpComboBox ).Text ) ) = '' ) then
begin
// CAMPO ESTA VAZIO ENTAO RETORNA MSG AO USUARIO
fnc_cria_janela_mensagem('Aviso de DADOS OBRIGAT�RIOS',
'O campo ' + ( Form.Components[i] as TDBLookUpComboBox ).Hint + ' � Obrigat�rio',
ExtractFilePath( Application.ExeName) + '\Icones\mensagem\aviso.png',
'AVISO' );
//IF TESTA PRA VER SE O COMPONENTE ESTA EM UM PAGECONTROL COLCOANDO ASSIM O FOCO NELE
if ( Form.Components[i] as TDBLookUpComboBox ).Enabled and ( Form.Components[i] as TDBLookUpComboBox ).Visible then
begin
if TDBLookUpComboBox(Form.Components[I]).Parent.ClassType = TTabSheet then// o Parente n�o � o pageControl e sim o a p�gina proriamente dito
TPageControl( TTabSheet( TDBLookUpComboBox(Form.Components[I]).Parent).Parent).ActivePage := ( Form.Components[i] as TDBLookUpComboBox ).Parent as TTabSheet;
TDBLookUpComboBox(Form.Components[i]).SetFocus;
end;
Abort;
end;
//MaskEdit
If Form.Components[i] is TSWHMaskEdit then
if ( ( Form.Components[i] as TSWHMaskEdit ).Hint <> '' ) and
( ( Form.Components[i] as TSWHMaskEdit ).Visible ) and
( Trim( fnc_remove_caracteres ( ( Form.Components[i] as TSWHMaskEdit ).Text ) ) = '' ) then
begin
// CAMPO ESTA VAZIO ENTAO RETORNA MSG AO USUARIO
fnc_cria_janela_mensagem('Aviso de DADOS OBRIGAT�RIOS',
'O campo ' + ( Form.Components[i] as TSWHMaskEdit ).Hint + ' � Obrigat�rio',
ExtractFilePath( Application.ExeName) + '\Icones\mensagem\aviso.png',
'AVISO' );
//IF TESTA PRA VER SE O COMPONENTE ESTA EM UM PAGECONTROL COLCOANDO ASSIM O FOCO NELE
if ( Form.Components[i] as TSWHMaskEdit ).Enabled and ( Form.Components[i] as TSWHMaskEdit ).Visible then
begin
if TSWHMaskEdit( Form.Components[I]).Parent.ClassType = TTabSheet then// o Parente n�o � o pageControl e sim o a p�gina proriamente dito
TPageControl( TTabSheet( TSWHMaskEdit(Form.Components[I]).Parent).Parent).ActivePage := ( Form.Components[i] as TSWHMaskEdit ).Parent as TTabSheet;
TSWHMaskEdit( Form.Components[i]).SetFocus;
end;
Abort;
end;
end;
end;
end;
//FUNCAO QUE CRIA A TELA DE MENSAGEM DE ACORDO COM OS PARAMETROS PASSADOS
Function fnc_cria_janela_mensagem ( Titulo, Mensagem, CaminhoIcone, TipoMensagem :String ): boolean;
begin
Result := False;
try
//CRIA FORMULARIO
PagMensajes := TPagMensajes.Create(nil);
//ATRIBUI UM TITULO
PagMensajes.sTitulo := Titulo;
//CONTEUDO DA MENSAGEM
PagMensajes.sMensaje := Mensagem;
//ICONE DA TELA NA MENSAGEM
PagMensajes.sIcono := CaminhoIcone;
//TIPO DE MENSAGEM : ERRO, ALERTA, CONFIRMACAO, ETC...
PagMensajes.sTipo := TipoMensagem;
PagMensajes.ShowModal;
finally
//RETORNA A RESPOSTA DO USUARIO, OK, CANCEL
Result := PagMensajes.bRespuestaMensaje;
PagMensajes.DisposeOf;
end;
end;
//FUNCAO QUE CALCULA A IDADE DA PESSOA A PARTIR DA DATA NASCIMENTO
function fnc_retorna_idade ( DataNascimento : TDate ): String;
var
nDiasTotal, nDias, nAnos, nMeses,
nRestoDias : Integer;
begin
nDiasTotal := DaysBetween ( Date, DataNascimento );
nAnos := nDiasTotal div 365; //pega o resultado inteiro
nRestoDias := nDiasTotal mod 365; //pega o resto
if nRestoDias > 30 then //PASSOU DE 30 DIAS DA MAIS DE 1 MES
begin
nMeses := nRestoDias div 30; // DIAS/30 DA O NUMERO DE MESES
end else
nMeses := 0;
result := IntToStr( nAnos ) + ' Anos e '+
IntToStr( nMeses )+' Meses';
end;
//FUNCAO QUE RETORNA O ENDERE�O ATRAVES DO CEP UTILIZANDO O ACBRCEP
//SE DER ALGUM ERRO NA CONSULTA ARMAZENA O ERRO NA VARIAVEL DE SAIDA :OUT ERRO
function fnc_retorna_endereco( Cep: String; out Erro:String ): TEndereco;
var
ACBrCEP : TACBrCEP;
begin
Erro := '';
if Length ( Cep ) <> 8 then
begin
Erro := 'CEP INCOMPLETO!';
Exit;
end;
//cria o componente
ACBrCEP := TACBrCEP.Create( Nil );
ACBrCEP.WebService := wsViaCep; //escolhi esse webservice para consulta, pode ser outro
ACBrCEP.Enderecos.Clear;
//REALIZA A BUSCA
ACBrCEP.BuscarPorCEP( Cep );
if ACBrCEP.Enderecos.Count = 0 then
Erro := 'CEP N�O ENCONTRADO!'
else
begin
//ARMAZENA NO REGISTRO OS DADOS DO ENDERE�O ENCONTRADO
Result.sBairro := UpperCase ( ACBrCEP.Enderecos[0].Bairro );
Result.sCEP := UpperCase ( ACBrCEP.Enderecos[0].Cep );
Result.sCodigoIBGE := UpperCase ( ACBrCEP.Enderecos[0].IBGE_Municipio );
Result.sComplemento:= UpperCase ( ACBrCEP.Enderecos[0].Complemento );
Result.sLogradouro := UpperCase ( ACBrCEP.Enderecos[0].Logradouro );
Result.sMunicipio := UpperCase ( ACBrCEP.Enderecos[0].Municipio );
Result.sUF := UpperCase ( ACBrCEP.Enderecos[0].UF );
end;
//DESTROY O COMPONENTE POIS NAO USAREMOS MAIS
ACBrCEP.Destroy;
end;
// funcao percorre o pagecontrol passado por parametro escondendo todas as abas
procedure prc_ocultar_tabs ( PageControl : TPageControl );
var
page :Integer;
begin
for page := 0 to PageControl.PageCount - 1 do
PageControl.Pages[page].tabvisible := False;
PageControl.ActivePageIndex := 0;
end;
//FUNCAO QUE ORDENA A CONSULTA NO DBGRID ATRAVES DA COLUNA PASSADA POR PARAMETRO
procedure prc_ordena( QueryConsulta:TFDQuery; Coluna: TColumn);
begin
if QueryConsulta.IndexFieldNames = Coluna.FieldName then
QueryConsulta.IndexFieldNames := Coluna.FieldName + ':D' //DESCENDENTE
else
QueryConsulta.IndexFieldNames := Coluna.FieldName;
QueryConsulta.First;
end;
end.
|
unit LrProject;
interface
uses
SysUtils, Classes, Components, Controls, Forms, Dialogs,
LrPersistComponent;
type
TLrProject = class(TLrPersistComponent)
private
FFilename: string;
FModified: Boolean;
FOnChanged: TNotifyEvent;
protected
function GetDisplayName: string;
procedure SetFilename(const Value: string); virtual;
protected
procedure Changed; virtual;
public
procedure LoadFromFile(const inFilename: string); override;
procedure SaveToFile(const inFilename: string); override;
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
published
property DisplayName: string read GetDisplayName;
property Filename: string read FFilename write SetFilename;
property Modified: Boolean read FModified write FModified;
end;
//
TLrProjectManager = class(TLrPersistComponent)
private
FDefaultProject: string;
FFilename: string;
FLoading: Boolean;
FCurrentProject: TLrProject;
FOnCurrentProjectChanged: TNotifyEvent;
FOnProjectChanged: TNotifyEvent;
FSaveDialog: TSaveDialog;
protected
procedure SetCurrentProject(const Value: TLrProject);
procedure SetFilename(const Value: string);
protected
procedure CurrentProjectChanged;
procedure ProjectChanged(inSender: TObject);
public
constructor Create(AOwner: TComponent = nil); override;
destructor Destroy; override;
function CloseProject: Boolean;
function ProjectIsOpen: Boolean;
function SaveProjectAs: Boolean;
function SaveProject: Boolean;
procedure Load;
procedure OpenDefaultProject;
procedure OpenProject(const inFilename: string);
procedure Save;
property CurrentProject: TLrProject read FCurrentProject
write SetCurrentProject;
property Filename: string read FFilename write SetFilename;
property OnCurrentProjectChanged: TNotifyEvent
read FOnCurrentProjectChanged write FOnCurrentProjectChanged;
property OnProjectChanged: TNotifyEvent read FOnProjectChanged
write FOnProjectChanged;
property SaveDialog: TSaveDialog read FSaveDialog write FSaveDialog;
published
property DefaultProject: string read FDefaultProject
write FDefaultProject;
end;
var
NilProject: TLrProject;
implementation
{ TLrProject }
procedure TLrProject.Changed;
begin
Modified := true;
if Assigned(OnChanged) then
OnChanged(Self);
end;
procedure TLrProject.LoadFromFile(const inFilename: string);
begin
inherited;
Filename := inFilename;
Modified := false;
end;
procedure TLrProject.SaveToFile(const inFilename: string);
begin
Filename := inFilename;
inherited;
Modified := false;
end;
function TLrProject.GetDisplayName: string;
begin
Result := ExtractFileName(Filename);
if Result = '' then
Result := 'Untitled';
end;
procedure TLrProject.SetFilename(const Value: string);
begin
FFilename := Value;
Changed;
end;
{ TLrProjectManager }
constructor TLrProjectManager.Create(AOwner: TComponent);
begin
inherited;
CurrentProject := NilProject;
end;
destructor TLrProjectManager.Destroy;
begin
inherited;
end;
procedure TLrProjectManager.Save;
begin
if not FLoading then
SaveToFile(FFilename);
end;
procedure TLrProjectManager.Load;
begin
FLoading := true;
try
LoadFromFile(Filename);
inherited;
finally
FLoading := false;
end;
end;
function TLrProjectManager.CloseProject: Boolean;
var
mr: TModalResult;
begin
Result := true;
if CurrentProject <> NilProject then
begin
if CurrentProject.Modified then
begin
mr := MessageDlg('Save changes to project "' + CurrentProject.DisplayName
+ '" before closing?', mtConfirmation, mbYesNoCancel, 0);
if mr = mrCancel then
Result := false
else if mr = mrYes then
Result := SaveProject;
end;
if Result then
begin
CurrentProject.Free;
CurrentProject := NilProject;
end;
end;
end;
procedure TLrProjectManager.CurrentProjectChanged;
begin
if CurrentProject.Filename <> '' then
DefaultProject := CurrentProject.Filename;
CurrentProject.OnChanged := ProjectChanged;
if Assigned(OnCurrentProjectChanged) then
OnCurrentProjectChanged(Self);
end;
procedure TLrProjectManager.SetFilename(const Value: string);
begin
FFilename := Value;
Load;
end;
procedure TLrProjectManager.SetCurrentProject(const Value: TLrProject);
begin
FCurrentProject := Value;
CurrentProjectChanged;
end;
procedure TLrProjectManager.ProjectChanged(inSender: TObject);
begin
if (inSender = CurrentProject) and Assigned(OnProjectChanged) then
OnProjectChanged(Self);
end;
procedure TLrProjectManager.OpenDefaultProject;
begin
OpenProject(DefaultProject);
end;
procedure TLrProjectManager.OpenProject(const inFilename: string);
begin
if FileExists(inFilename) then
begin
CurrentProject.LoadFromFile(inFilename);
CurrentProjectChanged;
end;
end;
function TLrProjectManager.SaveProjectAs: Boolean;
begin
SaveDialog.Filename := CurrentProject.Filename;
Result := SaveDialog.Execute;
if Result then
begin
CurrentProject.SaveToFile(SaveDialog.Filename);
CurrentProjectChanged;
end;
end;
function TLrProjectManager.SaveProject: Boolean;
begin
Result := CurrentProject.Filename <> '';
if not Result then
Result := SaveProjectAs
else
CurrentProject.SaveToFile(CurrentProject.Filename);
end;
function TLrProjectManager.ProjectIsOpen: Boolean;
begin
Result := CurrentProject <> NilProject;
end;
initialization
NilProject := TLrProject.Create(nil);
end.
|
unit LrPageControl;
interface
uses
Windows, Messages, SysUtils, Types, Classes, Controls, StdCtrls, ExtCtrls,
Graphics, Forms;
type
TLrCustomTabControl = class;
//
TLrTabPosition = ( ltpTop, ltpBottom );
TLrGetCaptionEvent = procedure(inSender: TLrCustomTabControl;
inIndex: Integer; var ioCaption: string) of object;
TLrBeforeSelectEvent = procedure(inSender: TLrCustomTabControl;
var ioSelected: Integer) of object;
TLrTabState = ( tsEnabled, tsDisabled );
//
TLrCustomTabControl = class(TGraphicControl)
private
FCount: Integer;
FGlyph: TBitmap;
FGlyphVisible: Boolean;
FHot: Integer;
FHotGlyph: TBitmap;
FOnBeforeSelect: TLrBeforeSelectEvent;
FOnGetCaption: TLrGetCaptionEvent;
FOnSelect: TNotifyEvent;
FSelected: Integer;
FTabPosition: TLrTabPosition;
FTabStates: array of TLrTabState;
protected
function GetCount: Integer; virtual;
function GetGlyphSpace: Integer;
function GetTabCaption(inIndex: Integer): string; virtual;
function GetTabHeight: Integer;
function GetTabStates(inIndex: Integer): TLrTabState;
function GetTabWidth(inIndex: Integer): Integer;
procedure SetCount(const Value: Integer);
procedure SetGlyphVisible(const Value: Boolean);
procedure SetHot(const Value: Integer);
procedure SetOnBeforeSelect(const Value: TLrBeforeSelectEvent);
procedure SetOnSelect(const Value: TNotifyEvent);
procedure SetSelected(const Value: Integer);
procedure SetTabHeight(const Value: Integer);
procedure SetTabPosition(const Value: TLrTabPosition);
procedure SetTabStates(inIndex: Integer; const Value: TLrTabState);
protected
function HitTest(inX, inY: Integer): Integer;
procedure CMDesignHitTest(var Message: TCMDesignHitTest);
message CM_DESIGNHITTEST;
// CM_MOUSEENTER = CM_BASE + 19;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure LoadGlyphs;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure Paint; override;
procedure PaintBottomTab(inRect: TRect; inIndex: Integer);
procedure PaintTabClient(inRect: TRect; inIndex: Integer);
procedure PaintTopTab(inRect: TRect; inIndex: Integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function IsGoodIndex(inIndex: Integer): Boolean;
public
property Color;
property Count: Integer read GetCount write SetCount;
property Font;
property GlyphVisible: Boolean read FGlyphVisible write SetGlyphVisible
default true;
property Hot: Integer read FHot write SetHot;
property Selected: Integer read FSelected write SetSelected;
property OnBeforeSelect: TLrBeforeSelectEvent read FOnBeforeSelect
write SetOnBeforeSelect;
property OnGetCaption: TLrGetCaptionEvent read FOnGetCaption
write FOnGetCaption;
property OnSelect: TNotifyEvent read FOnSelect write SetOnSelect;
property ParentColor;
property ParentFont;
property TabHeight: Integer read GetTabHeight write SetTabHeight;
property TabPosition: TLrTabPosition read FTabPosition write SetTabPosition
default ltpTop;
property TabStates[inIndex: Integer]: TLrTabState read GetTabStates
write SetTabStates;
end;
//
TLrTabControl = class(TLrCustomTabControl)
private
FTabs: TStringList;
protected
function GetCount: Integer; override;
function GetTabCaption(inIndex: Integer): string; override;
procedure SetTabs(const Value: TStringList);
protected
procedure TabsChange(inSender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property Color;
property Font;
property GlyphVisible;
property OnBeforeSelect;
property OnGetCaption;
property OnSelect;
property ParentColor;
property ParentFont;
property Selected;
property TabHeight;
property TabPosition;
property Tabs: TStringList read FTabs write SetTabs;
property Visible;
end;
//
TLrTabSheet = class(TCustomControl)
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Deselect;
procedure Select;
published
property Align;
property Caption;
property Color;
property Visible;
end;
//
TLrCustomPageControl = class(TCustomPanel)
private
FActivePageIndex: Integer;
FSheets: TList;
protected
function GetCount: Integer;
function GetSheet(inIndex: Integer): TLrTabSheet;
function GetSheetNamePrefix: string; virtual;
procedure SetActivePageIndex(const Value: Integer);
procedure SetCount(const Value: Integer);
protected
function CreateSheet: TLrTabSheet; virtual;
procedure AdjustClientRect(var Rect: TRect); override;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Paint; override;
procedure RenameSheets; virtual;
procedure Resize; override;
procedure WMEraseBkGnd(var Msg: TWMEraseBkGnd); message WM_ERASEBKGND;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddSheet: TLrTabSheet;
function FindSheet(inSheet: TControl): Integer;
function IsGoodIndex(inIndex: Integer): Boolean;
procedure RemoveSheet(inSheet: TLrTabSheet);
property Sheet[inIndex: Integer]: TLrTabSheet read GetSheet;
published
property ActivePageIndex: Integer read FActivePageIndex
write SetActivePageIndex;
property Align;
property Visible;
property Count: Integer read GetCount write SetCount;
property Color;
end;
//
TLrPageControl = class(TLrCustomPageControl)
private
FTabPosition: TLrTabPosition;
protected
procedure SetTabPosition(const Value: TLrTabPosition);
protected
function GetTabWidth(inIndex: Integer): Integer;
function HitTest(inX, inY: Integer): Boolean;
procedure AdjustClientRect(var Rect: TRect); override;
procedure CMDesignHitTest(var Message: TCMDesignHitTest); message CM_DESIGNHITTEST;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer); override;
procedure Paint; override;
procedure PaintTopTab(inRect: TRect; inState: Integer;
const inCaption: string);
procedure PaintBottomTab(inRect: TRect; inState: Integer;
const inCaption: string);
procedure ShowControl(AControl: TControl); override;
public
TabWidth, TabHeight: Integer;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property TabPosition: TLrTabPosition read FTabPosition write SetTabPosition
default ltpTop;
end;
implementation
uses
Math;
{$R LrPCGlyphs.res}
{ TLrCustomTabControl }
constructor TLrCustomTabControl.Create(AOwner: TComponent);
begin
inherited;
FGlyph := TBitmap.Create;
FHotGlyph := TBitmap.Create;
FSelected := -1;
FHot := -1;
FGlyphVisible := true;
LoadGlyphs;
end;
destructor TLrCustomTabControl.Destroy;
begin
FGlyph.Free;
inherited;
end;
procedure TLrCustomTabControl.LoadGlyphs;
begin
FGlyph.LoadFromResourceName(HInstance, 'LRPC_CLOSE');
FHotGlyph.LoadFromResourceName(HInstance, 'LRPC_CLOSE_HOT');
end;
function TLrCustomTabControl.IsGoodIndex(inIndex: Integer): Boolean;
begin
Result := (inIndex >= 0) and (inIndex < Count);
end;
procedure TLrCustomTabControl.CMDesignHitTest(var Message: TCMDesignHitTest);
var
i: Integer;
begin
Message.Result := 0;
if (Message.Keys and MK_LBUTTON) = MK_LBUTTON then
begin
i := HitTest(Message.Pos.x, Message.Pos.y);
if (i >= 0) then
begin
Selected := i;
Message.Result := 1;
end;
end;
end;
function TLrCustomTabControl.GetTabCaption(inIndex: Integer): string;
begin
if Assigned(OnGetCaption) then
OnGetCaption(Self, inIndex, Result);
end;
function TLrCustomTabControl.GetGlyphSpace: Integer;
begin
if not FGlyph.Empty then
Result := FGlyph.Width + 6
else
Result := 0;
end;
function TLrCustomTabControl.GetTabWidth(inIndex: Integer): Integer;
begin
Result := Canvas.TextWidth(GetTabCaption(inIndex)) + 12;
if inIndex = Selected then
Inc(Result, GetGlyphSpace);
end;
function TLrCustomTabControl.HitTest(inX, inY: Integer): Integer;
var
i, x: Integer;
begin
Result := -1;
case TabPosition of
ltpTop:
if (inY > TabHeight) then
exit;
else
if (inY < ClientHeight - TabHeight) then
exit;
end;
x := 0;
for i := 0 to Pred(Count) do
begin
Inc(x, GetTabWidth(i));
if (inX < x) then
begin
Result := i;
exit;
end;
end;
end;
procedure TLrCustomTabControl.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
i: Integer;
begin
inherited;
i := HitTest(X, Y);
if (TabStates[i] <> tsDisabled) then
Selected := i;
end;
procedure TLrCustomTabControl.MouseMove(Shift: TShiftState; X, Y: Integer);
var
i: Integer;
begin
inherited;
if not Enabled then
Hot := -1
else begin
i := HitTest(X, Y);
if TabStates[i] <> tsDisabled then
Hot := i;
end;
end;
procedure TLrCustomTabControl.Paint;
var
i: Integer;
r: TRect;
begin
inherited;
//
r := Rect(0, 0, ClientWidth, TabHeight);
//
case TabPosition of
ltpBottom: OffsetRect(r, 0, ClientHeight - TabHeight);
end;
//
Canvas.Brush.Color := Color;
Canvas.FillRect(r);
//
SetBkMode(Canvas.Handle, Windows.TRANSPARENT);
for i := 0 to Pred(Count) do
begin
if Enabled and (TabStates[i] = tsEnabled) then
Canvas.Font.Color := clBlack
else
Canvas.Font.Color := clSilver;
r.Right := r.Left + GetTabWidth(i);
case TabPosition of
ltpTop: PaintTopTab(r, i);
ltpBottom: PaintBottomTab(r, i);
end;
PaintTabClient(r, i);
r.Left := r.Right;
end;
//
Canvas.Pen.Color := $BAB19D;
//
case TabPosition of
ltpTop:
begin
Canvas.MoveTo(r.Left, TabHeight - 1);
Canvas.LineTo(ClientWidth, TabHeight - 1);
end;
ltpBottom:
begin
Canvas.MoveTo(r.Left, r.Bottom - TabHeight + 1);
Canvas.LineTo(ClientWidth, r.Bottom - TabHeight + 1);
end;
end;
end;
procedure TLrCustomTabControl.PaintTabClient(inRect: TRect; inIndex: Integer);
var
c: string;
x, h: Integer;
function Offset(inHeight: Integer): Integer;
var
v: Integer;
begin
case TabPosition of
ltpTop: v := 3;
else v := 0;
end;
Result := inRect.Top + v + Max(1, ((TabHeight - 3) div 2) - inHeight);
end;
begin
c := GetTabCaption(inIndex);
h := Offset(Canvas.TextHeight(c) div 2);
if inIndex = Selected then
x := GetGlyphSpace + 4
else
x := 6;
Canvas.TextOut(inRect.Left + x, h, c);
if inIndex = Selected then
begin
h := Offset(FGlyph.Height div 2);
if inIndex = Hot then
Canvas.Draw(inRect.Left + 5, h, FHotGlyph)
else
Canvas.Draw(inRect.Left + 5, h, FGlyph);
end;
end;
procedure TLrCustomTabControl.PaintBottomTab(inRect: TRect; inIndex: Integer);
procedure DrawNormalTab;
begin
with Canvas, inRect do
begin
Brush.Color := $F0EBEB;
Pen.Color := $BAB19D;
RoundRect(Left + 1, Top - 3, Right - 1, Bottom, 6, 6);
MoveTo(Left, Top);
LineTo(Right, Top);
end;
end;
procedure DrawHighlightTab;
begin
with Canvas, inRect do
begin
Brush.Color := $FEFCFC;
Pen.Color := $2C8BE6;
RoundRect(Left, Top - 3, Right, Bottom, 6, 6);
Pen.Color := $3CC7FF;
MoveTo(Left + 2, Bottom - 2);
LineTo(Right - 2, Bottom - 2);
MoveTo(Left + 1, Bottom - 3);
LineTo(Right - 1, Bottom - 3);
Pen.Color := $BAB19D;
MoveTo(Left, Top);
LineTo(Left, Bottom - 4);
MoveTo(Right - 1, Top);
LineTo(Right - 1, Bottom - 4);
end;
end;
begin
case Ord(inIndex = Selected) of
0:
begin
Dec(inRect.Bottom, 3);
if inIndex = Hot then
DrawHighlightTab
else
DrawNormalTab;
end;
//
else begin
Dec(inRect.Left);
Inc(inRect.Right);
DrawHighlightTab;
end;
end;
end;
procedure TLrCustomTabControl.PaintTopTab(inRect: TRect; inIndex: Integer);
procedure DrawNormalTab;
begin
with Canvas, inRect do
begin
Brush.Color := $F0EBEB;
Pen.Color := $BAB19D;
RoundRect(Left + 1, Top, Right - 1, Bottom + 3, 6, 6);
MoveTo(Left, Bottom - 1);
LineTo(Right, Bottom - 1);
end;
end;
procedure DrawHighlightTab;
begin
with Canvas, inRect do
begin
Brush.Color := $FEFCFC;
Pen.Color := $2C8BE6;
RoundRect(Left, Top, Right, Bottom + 3, 6, 6);
Pen.Color := $3CC7FF;
MoveTo(Left + 2, Top + 1);
LineTo(Right - 2, Top + 1);
MoveTo(Left + 1, Top + 2);
LineTo(Right - 1, Top + 2);
Pen.Color := $BAB19D;
MoveTo(Left, Top + 3);
LineTo(Left, Bottom);
MoveTo(Right - 1, Top + 3);
LineTo(Right - 1, Bottom);
end;
end;
begin
case Ord(inIndex = Selected) of
0:
begin
Inc(inRect.Top, 3);
if (inIndex = Hot) and Enabled and (TabStates[inIndex] = tsEnabled) then
DrawHighlightTab
else
DrawNormalTab;
end;
//
else begin
Dec(inRect.Left);
Inc(inRect.Right);
//if Enabled and (TabStates[inIndex] = tsEnabled) then
DrawHighlightTab
//else
// DrawNormalTab;
end;
end;
end;
procedure TLrCustomTabControl.SetTabPosition(const Value: TLrTabPosition);
begin
if (FTabPosition <> Value) then
begin
FTabPosition := Value;
Invalidate;
end;
end;
procedure TLrCustomTabControl.SetCount(const Value: Integer);
begin
if (FCount <> Value) then
begin
FCount := Value;
Invalidate;
end;
end;
function TLrCustomTabControl.GetCount: Integer;
begin
Result := FCount;
end;
procedure TLrCustomTabControl.SetSelected(const Value: Integer);
var
s: Integer;
begin
if (csLoading in ComponentState) then
FSelected := Value
else if (FSelected <> Value) then
begin
s := Value;
if Assigned(OnBeforeSelect) then
OnBeforeSelect(Self, s);
if (s <> FSelected) and IsGoodIndex(s) then
begin
FSelected := s;
Invalidate;
Update;
if Assigned(OnSelect) then
OnSelect(Self);
end;
end;
end;
function TLrCustomTabControl.GetTabHeight: Integer;
begin
Result := Height;
end;
procedure TLrCustomTabControl.SetTabHeight(const Value: Integer);
begin
Height := Value;
end;
procedure TLrCustomTabControl.SetHot(const Value: Integer);
begin
if (FHot <> Value) then
begin
FHot := Value;
Invalidate;
end;
end;
procedure TLrCustomTabControl.CMMouseLeave(var Message: TMessage);
begin
Hot := -1;
end;
procedure TLrCustomTabControl.SetOnSelect(const Value: TNotifyEvent);
begin
FOnSelect := Value;
end;
procedure TLrCustomTabControl.SetGlyphVisible(const Value: Boolean);
begin
FGlyphVisible := Value;
if Value then
LoadGlyphs
else begin
FGlyph.Width := 0;
FHotGlyph.Width := 0;
end;
end;
procedure TLrCustomTabControl.SetOnBeforeSelect(
const Value: TLrBeforeSelectEvent);
begin
FOnBeforeSelect := Value;
end;
function TLrCustomTabControl.GetTabStates(inIndex: Integer): TLrTabState;
begin
Result := tsEnabled;
if IsGoodIndex(inIndex) and (inIndex < Length(FTabStates)) then
Result := FTabStates[inIndex];
end;
procedure TLrCustomTabControl.SetTabStates(inIndex: Integer;
const Value: TLrTabState);
begin
if IsGoodIndex(inIndex) then
begin
if inIndex >= Length(FTabStates) then
SetLength(FTabStates, inIndex + 1);
FTabStates[inIndex] := Value;
Invalidate;
end;
end;
{ TLrTabControl }
constructor TLrTabControl.Create(AOwner: TComponent);
begin
inherited;
FTabs := TStringList.Create;
FTabs.OnChange := TabsChange;
end;
destructor TLrTabControl.Destroy;
begin
FTabs.Free;
inherited;
end;
function TLrTabControl.GetCount: Integer;
begin
Result := FTabs.Count;
end;
function TLrTabControl.GetTabCaption(inIndex: Integer): string;
begin
Result := inherited GetTabCaption(inIndex);
if Result = '' then
Result := FTabs[inIndex];
end;
procedure TLrTabControl.TabsChange(inSender: TObject);
begin
if not (csLoading in ComponentState) then
begin
Invalidate;
Selected := Selected;
end;
end;
procedure TLrTabControl.SetTabs(const Value: TStringList);
begin
FTabs.Assign(Value);
end;
{ TLrTabSheet }
constructor TLrTabSheet.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [ csAcceptsControls ];
end;
destructor TLrTabSheet.Destroy;
begin
if (Parent is TLrCustomPageControl) then
TLrCustomPageControl(Parent).RemoveSheet(Self);
inherited;
end;
procedure TLrTabSheet.Deselect;
begin
// Visible := false;
end;
procedure TLrTabSheet.Select;
begin
// Visible := true;
Top := 0;
BringToFront;
end;
{ TLrCustomPageControl }
constructor TLrCustomPageControl.Create(AOwner: TComponent);
begin
inherited;
// ControlStyle := ControlStyle - [ csAcceptsControls ];
FSheets := TList.Create;
end;
destructor TLrCustomPageControl.Destroy;
begin
FSheets.Destroy;
inherited;
end;
procedure TLrCustomPageControl.GetChildren(Proc: TGetChildProc; Root: TComponent);
//var
// i: Integer;
begin
inherited;
// for i := 0 to Pred(FSheets.Count) do
// Proc(TComponent(FSheets[i]));
end;
function TLrCustomPageControl.IsGoodIndex(inIndex: Integer): Boolean;
begin
Result := (inIndex >= 0) and (inIndex < Count);
end;
function TLrCustomPageControl.GetSheet(inIndex: Integer): TLrTabSheet;
begin
Result := TLrTabSheet(FSheets[inIndex]);
end;
function TLrCustomPageControl.FindSheet(inSheet: TControl): Integer;
begin
Result := FSheets.IndexOf(inSheet);
end;
procedure TLrCustomPageControl.Loaded;
var
i: Integer;
begin
inherited;
for i := 0 to Pred(ControlCount) do
if Controls[i] is TLrTabSheet then
FSheets.Add(Controls[i]);
if IsGoodIndex(ActivePageIndex) then
Sheet[ActivePageIndex].Select;
end;
procedure TLrCustomPageControl.Resize;
//var
// i: Integer;
begin
// for i := 0 to Pred(Count) do
// Sheet[i].Height := Height - 4;
inherited;
end;
procedure TLrCustomPageControl.AdjustClientRect(var Rect: TRect);
begin
//Dec(Rect.Bottom, 4);
//Inc(Rect.Top, TabHeight);
end;
procedure TLrCustomPageControl.SetActivePageIndex(const Value: Integer);
begin
if IsGoodIndex(Value) and (ActivePageIndex <> Value) then
begin
FActivePageIndex := Value;
Sheet[ActivePageIndex].Select;
Invalidate;
end;
end;
function TLrCustomPageControl.GetSheetNamePrefix: string;
begin
Result := 'LrTabSheet';
end;
function TLrCustomPageControl.CreateSheet: TLrTabSheet;
begin
Result := TLrTabSheet.Create(Owner);
if TCustomForm(Owner).Designer <> nil then
Result.Name := TCustomForm(Owner).Designer.UniqueName(GetSheetNamePrefix);
Result.Align := alClient;
Result.Color := clWhite;
Result.Parent := Self;
end;
function TLrCustomPageControl.AddSheet: TLrTabSheet;
begin
Result := CreateSheet;
FSheets.Add(Result);
end;
procedure TLrCustomPageControl.RemoveSheet(inSheet: TLrTabSheet);
begin
FSheets.Remove(inSheet);
end;
function TLrCustomPageControl.GetCount: Integer;
begin
Result := FSheets.Count;
end;
procedure TLrCustomPageControl.SetCount(const Value: Integer);
begin
if not (csLoading in ComponentState) then
begin
while FSheets.Count < Value do
AddSheet;
while (Value >= 0) and (Value < FSheets.Count) do
Sheet[Pred(Count)].Free;
ActivePageIndex := Pred(Value);
end;
end;
procedure TLrCustomPageControl.Notification(AComponent: TComponent;
Operation: TOperation);
//var
// i: Integer;
begin
inherited;
{
if Operation = opRemove then
for i := 0 to Pred(Count) do
if Sheet[i] = AComponent then
begin
RemoveSheet(Sheet[i]);
break;
end;
}
end;
procedure TLrCustomPageControl.RenameSheets;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
Sheet[i].Name := Format('%s%d', [ GetSheetNamePrefix, i + 1 ]);
end;
procedure TLrCustomPageControl.Paint;
begin
//
end;
procedure TLrCustomPageControl.WMEraseBkGnd(var Msg: TWMEraseBkGnd);
begin
// if Transparent or Opaque then
if Count > 0 then
Msg.Result := 0
else
inherited;
end;
{ TLrPageControl }
constructor TLrPageControl.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle - [ csAcceptsControls ];
TabWidth := 64;
TabHeight := 18;
end;
destructor TLrPageControl.Destroy;
begin
inherited;
end;
procedure TLrPageControl.GetChildren(Proc: TGetChildProc;
Root: TComponent);
var
i: Integer;
begin
for i := 0 to Pred(FSheets.Count) do
Proc(TComponent(FSheets[i]));
end;
procedure TLrPageControl.CMDesignHitTest(var Message: TCMDesignHitTest);
var
p: TPoint;
begin
Message.Result := 0;
if (Message.Keys and MK_LBUTTON) = MK_LBUTTON then
begin
p := SmallPointToPoint(Message.Pos);
if HitTest(p.x, p.y) then
Message.Result := 1;
end;
end;
procedure TLrPageControl.AdjustClientRect(var Rect: TRect);
begin
inherited;
case TabPosition of
ltpTop: Inc(Rect.Top, TabHeight);
ltpBottom: Dec(Rect.Bottom, TabHeight);
end;
end;
procedure TLrPageControl.PaintTopTab(inRect: TRect; inState: Integer;
const inCaption: string);
begin
with Canvas, inRect do
case inState of
0:
begin
Inc(Top, 3);
Brush.Color := $F0EBEB;
Pen.Color := $BAB19D;
RoundRect(Left + 1, Top, Right - 1, Bottom + 3, 6, 6);
MoveTo(Left, Bottom - 1);
LineTo(Right, Bottom - 1);
Canvas.TextOut(Left + 6, Top + 1, inCaption);
end;
//
else
begin
Dec(Left);
Inc(Right);
Brush.Color := $FEFCFC;
Pen.Color := $2C8BE6;
RoundRect(Left, Top, Right, Bottom + 3, 6, 6);
Pen.Color := $3CC7FF;
MoveTo(Left + 2, Top + 1);
LineTo(Right - 2, Top + 1);
MoveTo(Left + 1, Top + 2);
LineTo(Right - 1, Top + 2);
Pen.Color := $BAB19D;
MoveTo(Left, Top + 3);
LineTo(Left, Bottom);
MoveTo(Right - 1, Top + 3);
LineTo(Right - 1, Bottom);
Canvas.TextOut(Left + 6, Top + 3, inCaption);
end;
end;
end;
procedure TLrPageControl.PaintBottomTab(inRect: TRect; inState: Integer;
const inCaption: string);
begin
with Canvas, inRect do
case inState of
0:
begin
Brush.Color := $F0EBEB;
Pen.Color := $BAB19D;
Dec(Bottom, 3);
RoundRect(Left + 1, Top - 3, Right - 1, Bottom, 6, 6);
MoveTo(Left, Top);
LineTo(Right, Top);
Canvas.TextOut(Left + 6, Top + 1, inCaption);
end;
//
else
begin
Brush.Color := $FEFCFC;
Pen.Color := $2C8BE6;
Dec(Left);
Inc(Right);
RoundRect(Left, Top - 3, Right, Bottom, 6, 6);
Pen.Color := $3CC7FF;
MoveTo(Left + 2, Bottom - 1);
LineTo(Right - 2, Bottom - 1);
MoveTo(Left + 1, Bottom - 2);
LineTo(Right - 1, Bottom - 2);
Pen.Color := $BAB19D;
MoveTo(Left, Top);
LineTo(Left, Bottom - 3);
MoveTo(Right - 1, Top);
LineTo(Right - 1, Bottom - 3);
Canvas.TextOut(Left + 6, Top + 3, inCaption);
end;
end;
end;
function TLrPageControl.GetTabWidth(inIndex: Integer): Integer;
begin
Result := Canvas.TextWidth(Sheet[inIndex].Caption) + 12;
end;
procedure TLrPageControl.Paint;
var
i: Integer;
r: TRect;
begin
r := Rect(0, 0, ClientWidth, TabHeight);
case TabPosition of
ltpBottom: OffsetRect(r, 0, ClientHeight - TabHeight);
end;
Canvas.Brush.Color := Color;
Canvas.FillRect(r);
//
Canvas.Pen.Color := clBlack;
SetBkMode(Canvas.Handle, Windows.TRANSPARENT);
//
for i := 0 to Pred(Count) do
begin
r.Right := r.Left + GetTabWidth(i);
case TabPosition of
ltpTop: PaintTopTab(r, Ord(i = ActivePageIndex), Sheet[i].Caption);
ltpBottom: PaintBottomTab(r, Ord(i = ActivePageIndex), Sheet[i].Caption);
end;
r.Left := r.Right;
end;
//
Canvas.Pen.Color := $BAB19D;
case TabPosition of
ltpTop:
begin
Canvas.MoveTo(r.Left, TabHeight - 1);
Canvas.LineTo(ClientWidth, TabHeight - 1);
end;
ltpBottom:
begin
Canvas.MoveTo(r.Left, r.Bottom - TabHeight + 1);
Canvas.LineTo(ClientWidth, r.Bottom - TabHeight + 1);
end;
end;
end;
function TLrPageControl.HitTest(inX, inY: Integer): Boolean;
begin
case TabPosition of
ltpTop: Result := (inY < TabHeight);
else Result := (inY > ClientHeight - TabHeight);
end;
if Result then
ActivePageIndex := inX div TabWidth;
end;
procedure TLrPageControl.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
HitTest(X, Y);
end;
procedure TLrPageControl.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
end;
procedure TLrPageControl.ShowControl(AControl: TControl);
var
i: Integer;
begin
inherited;
i := FindSheet(AControl);
if (i >= 0) then
ActivePageIndex := i;
end;
procedure TLrPageControl.SetTabPosition(const Value: TLrTabPosition);
begin
FTabPosition := Value;
Realign;
Invalidate;
end;
initialization
RegisterClass(TLrTabSheet);
end.
|
unit MyCat.BackEnd.HeartBeat;
interface
uses
MyCat.Statistic;
type
TDBHeartbeat = class
public const
DB_SYN_ERROR: Integer = -1;
DB_SYN_NORMAL: Integer = 1;
OK_STATUS: Integer = 1;
ERROR_STATUS: Integer = -1;
TIMEOUT_STATUS: Integer = -2;
INIT_STATUS: Integer = 0;
private const
DEFAULT_HEARTBEAT_TIMEOUT: Int64 = 30 * 1000;
DEFAULT_HEARTBEAT_RETRY: Integer = 10;
protected
// heartbeat config
FHeartbeatTimeout: Int64; // 心跳超时时间
FHeartbeatRetry: Integer; // 检查连接发生异常到切换,重试次数
FHeartbeatSQL: string; // 静态心跳语句
FIsStop: Boolean;
FIsChecking: Boolean;
FErrorCount: Integer;
FStatus: Integer;
FRecorder: THeartbeatRecorder;
FAsynRecorder: TDataSourceSyncRecorder;
public
constructor Create;
end;
//
// private volatile Integer slaveBehindMaster;
// private volatile int dbSynStatus = DB_SYN_NORMAL;
//
// public Integer getSlaveBehindMaster() {
// return slaveBehindMaster;
// }
//
// public int getDbSynStatus() {
// return dbSynStatus;
// }
//
// public void setDbSynStatus(int dbSynStatus) {
// this.dbSynStatus = dbSynStatus;
// }
//
// public void setSlaveBehindMaster(Integer slaveBehindMaster) {
// this.slaveBehindMaster = slaveBehindMaster;
// }
//
// public int getStatus() {
// return status;
// }
//
// public boolean isChecking() {
// return isChecking.get();
// }
//
// public abstract void start();
//
// public abstract void stop();
//
// public boolean isStop() {
// return isStop.get();
// }
//
// public int getErrorCount() {
// return errorCount.get();
// }
//
// public HeartbeatRecorder getRecorder() {
// return recorder;
// }
//
// public abstract String getLastActiveTime();
//
// public abstract long getTimeout();
//
// public abstract void heartbeat();
//
// public long getHeartbeatTimeout() {
// return heartbeatTimeout;
// }
//
// public void setHeartbeatTimeout(long heartbeatTimeout) {
// this.heartbeatTimeout = heartbeatTimeout;
// }
//
// public int getHeartbeatRetry() {
// return heartbeatRetry;
// }
//
// public void setHeartbeatRetry(int heartbeatRetry) {
// this.heartbeatRetry = heartbeatRetry;
// }
//
// public String getHeartbeatSQL() {
// return heartbeatSQL;
// }
//
// public void setHeartbeatSQL(String heartbeatSQL) {
// this.heartbeatSQL = heartbeatSQL;
// }
//
// public boolean isNeedHeartbeat() {
// return heartbeatSQL != null;
// }
//
// public DataSourceSyncRecorder getAsynRecorder() {
// return this.asynRecorder;
// }
implementation
{ TDBHeartbeat }
constructor TDBHeartbeat.Create;
begin
FHeartbeatTimeout := DEFAULT_HEARTBEAT_TIMEOUT; // 心跳超时时间
FHeartbeatRetry := DEFAULT_HEARTBEAT_RETRY; // 检查连接发生异常到切换,重试次数
FIsStop := true;
FIsChecking := false;
FErrorCount := 0;
FRecorder := THeartbeatRecorder.Create;
FAsynRecorder := TDataSourceSyncRecorder.Create;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.